13.4.1-7 baseline

Former-commit-id: 8072752c77 [formerly 4c6ff79e71] [formerly 8347bed50e [formerly dd6304e82206bb46b0c0442d15ab5d9312d9f19f]]
Former-commit-id: 8347bed50e
Former-commit-id: b35027f661
This commit is contained in:
Steve Harris 2013-05-13 12:58:10 -04:00
parent 5be793f2f9
commit ff7a21ac37
1349 changed files with 102423 additions and 9127 deletions

View file

@ -69,6 +69,8 @@ import com.raytheon.uf.viz.core.notification.NotificationMessage;
* ------------ ---------- ----------- --------------------------
* 05/08/08 1127 randerso Initial Creation
* 09/03/08 1448 chammack Refactored notification observer interface
* 04/23/13 1939 randerso Add separate connect method to allow application
* to complete initialization before connecting to JMS
* </pre>
*
* @author randerso
@ -184,7 +186,6 @@ public class NotificationManagerJob implements ExceptionListener, IDisposable {
*/
protected NotificationManagerJob() {
this.listeners = new HashMap<ListenerKey, NotificationListener>();
connect(true);
Activator.getDefault().registerDisposable(this);
}
@ -411,6 +412,20 @@ public class NotificationManagerJob implements ExceptionListener, IDisposable {
}
}
/**
* Connect to JMS
*/
public static void connect() {
getInstance().connect(true);
}
/**
* Disconnect from JMS
*/
public static void disconnect() {
getInstance().disconnect(true);
}
private static class NotificationListener implements MessageListener {
private Type type;

View file

@ -20,23 +20,16 @@
package com.raytheon.uf.viz.d2d.gfe.browser;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.raytheon.uf.common.dataplugin.gfe.dataaccess.GFEDataAccessUtil;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.viz.core.rsc.DisplayType;
import com.raytheon.uf.viz.core.rsc.ResourceType;
import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability;
import com.raytheon.uf.viz.d2d.gfe.rsc.GFEGridResourceData;
import com.raytheon.uf.viz.productbrowser.AbstractRequestableProductBrowserDataDefinition;
import com.raytheon.uf.viz.productbrowser.ProductBrowserLabel;
import com.raytheon.uf.viz.productbrowser.ProductBrowserPreference;
import com.raytheon.viz.grid.rsc.GridLoadProperties;
/**
@ -50,6 +43,9 @@ import com.raytheon.viz.grid.rsc.GridLoadProperties;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 9, 2011 bsteffen Initial creation
* May 02, 2013 1949 bsteffen Update GFE data access in Product
* Browser, Volume Browser, and Data Access
* Framework.
*
* </pre>
*
@ -90,119 +86,4 @@ public class GFEDataDefinition extends
return type;
}
/*
* (non-Javadoc)
*
* @see com.raytheon.uf.viz.productbrowser.
* AbstractRequestableProductBrowserDataDefinition
* #buildProductList(java.util.List)
*/
@Override
public List<String> buildProductList(List<String> historyList) {
String[] parameters = queryData(GFEDataAccessUtil.PARM_ID,
getProductParameters(new String[0], null));
List<String> result = new ArrayList<String>();
for (String orderString : order) {
List<ProductBrowserLabel> labels = formatData(orderString,
parameters);
for (ProductBrowserLabel label : labels) {
if (!result.contains(label.getName())) {
result.add(label.getName());
}
}
}
return Collections.emptyList();
}
@Override
public String populateInitial() {
if (!isEnabled()) {
return null;
}
String[] parameters = queryData(GFEDataAccessUtil.PARM_ID,
getProductParameters(new String[0], null));
if (parameters != null) {
if (parameters.length > 0) {
return displayName;
} else {
return null;
}
} else {
return null;
}
}
@Override
protected String[] queryData(String param,
HashMap<String, RequestConstraint> queryList) {
return super.queryData(GFEDataAccessUtil.PARM_ID, queryList);
}
@Override
public List<ProductBrowserLabel> formatData(String param,
String[] parameters) {
Set<ProductBrowserLabel> labels = new HashSet<ProductBrowserLabel>();
for (String value : parameters) {
String label = value;
try {
ParmID parmId = new ParmID(value);
if (param.equals(GFEDataAccessUtil.SITE_ID)) {
label = parmId.getDbId().getSiteId();
} else if (param.equals(GFEDataAccessUtil.MODEL_NAME)) {
label = parmId.getDbId().getModelName();
} else if (param.equals(GFEDataAccessUtil.MODEL_TIME)) {
label = parmId.getDbId().getModelTime();
} else if (param.equals(GFEDataAccessUtil.DB_TYPE)) {
label = parmId.getDbId().getDbType();
} else if (param.equals(GFEDataAccessUtil.PARM_NAME)) {
label = parmId.getParmName();
} else if (param.equals(GFEDataAccessUtil.PARM_LEVEL)) {
label = parmId.getParmLevel();
}
} catch (Exception e) {
e.printStackTrace();
}
labels.add(new ProductBrowserLabel(label, label));
}
ArrayList<ProductBrowserLabel> finalLabels = new ArrayList<ProductBrowserLabel>(
labels);
Collections.sort(finalLabels);
return finalLabels;
}
@Override
public HashMap<String, RequestConstraint> getProductParameters(
String[] selection, String[] order) {
if (order == null) {
order = this.order;
}
Map<String, String> parmIdComponents = new HashMap<String, String>();
if (selection.length > 1) {
String[] usedSelection = realignSelection(selection);
for (int i = 0; i < usedSelection.length; i++) {
parmIdComponents.put(order[i], usedSelection[i]);
}
}
HashMap<String, RequestConstraint> queryList = new HashMap<String, RequestConstraint>();
queryList.put(PLUGIN_NAME, new RequestConstraint(productName));
queryList.put(GFEDataAccessUtil.PARM_ID,
GFEDataAccessUtil.createParmIdConstraint(parmIdComponents));
return queryList;
}
/*
* (non-Javadoc)
*
* @see com.raytheon.uf.viz.productbrowser.xml.IProductBrowserPreferences#
* configurePreferences()
*/
@Override
public List<ProductBrowserPreference> configurePreferences() {
return super.configurePreferences();
}
}

View file

@ -28,14 +28,18 @@ import java.util.Map;
import javax.measure.unit.UnitFormat;
import com.raytheon.uf.common.dataplugin.gfe.dataaccess.GFEDataAccessUtil;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
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.viz.core.catalog.CatalogQuery;
import com.raytheon.uf.viz.core.drawables.ResourcePair;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.requests.ThriftClient;
import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData;
import com.raytheon.uf.viz.core.rsc.AbstractResourceData;
import com.raytheon.uf.viz.core.rsc.DisplayType;
@ -66,6 +70,9 @@ import com.raytheon.viz.volumebrowser.vbui.VBMenuBarItemsMgr.ViewMenu;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 9, 2011 bsteffen Initial creation
* May 02, 2013 1949 bsteffen Update GFE data access in Product
* Browser, Volume Browser, and Data Access
* Framework.
*
* </pre>
*
@ -80,7 +87,7 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
public IDataCatalogEntry getCatalogEntry(SelectedData selectedData) {
HashMap<String, RequestConstraint> queryList = new HashMap<String, RequestConstraint>();
queryList.put(GFEDataAccessUtil.PLUGIN_NAME, new RequestConstraint("gfe"));
queryList.put(GFEDataAccessUtil.PARM_ID, getParmIdConstraint(selectedData));
queryList.putAll(getParmIdConstraint(selectedData));
try {
String[] result = CatalogQuery.performQuery(GFEDataAccessUtil.PARM_ID,
queryList);
@ -103,7 +110,7 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
List<String> gfeSources = null;
if (selectedSources != null && selectedSources.length != 0) {
gfeSources = new ArrayList<String>();
gfeSources = new ArrayList<String>(selectedSources.length);
for (String selectedSource : selectedSources) {
String gfeSource = VbGFEMapping.getGfeSource(selectedSource);
if (gfeSource != null) {
@ -117,7 +124,7 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
List<String> gfeFields = null;
if (selectedFields != null && selectedFields.length != 0) {
gfeFields = new ArrayList<String>();
gfeFields = new ArrayList<String>(selectedFields.length);
for (String selectedField : selectedFields) {
String gfeParam = VbGFEMapping.getGfeParam(selectedField);
if (gfeParam != null) {
@ -131,7 +138,7 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
List<String> gfePlanes = null;
if (selectedPlanes != null && selectedPlanes.length != 0) {
gfePlanes = new ArrayList<String>();
gfePlanes = new ArrayList<String>(selectedPlanes.length);
for (String selectedPlane : selectedPlanes) {
String gfePlane = VbGFEMapping.getGfeLevel(selectedPlane);
if (gfePlane != null) {
@ -143,40 +150,56 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
}
}
for (String parmIdStr : getParmIds()) {
ParmID parmId = new ParmID(parmIdStr);
DbQueryRequest dbRequest = new DbQueryRequest();
dbRequest.setEntityClass(GFERecord.class);
dbRequest.addRequestField(GFEDataAccessUtil.MODEL_NAME);
dbRequest.addRequestField(GFEDataAccessUtil.PARM_NAME);
dbRequest.addRequestField(GFEDataAccessUtil.PARM_LEVEL);
DbQueryResponse dbResponse = null;
try {
dbResponse = (DbQueryResponse) ThriftClient.sendRequest(dbRequest);
} catch (VizException e) {
statusHandler
.handle(Priority.PROBLEM,
"Unable to load availability for GFE in the Volume Browser",
e);
return;
}
for (Map<String, Object> row : dbResponse.getResults()) {
String modelName = row.get(GFEDataAccessUtil.MODEL_NAME).toString();
String parmName = row.get(GFEDataAccessUtil.PARM_NAME).toString();
String parmLevel = row.get(GFEDataAccessUtil.PARM_LEVEL).toString();
boolean source = true;
boolean field = true;
boolean plane = true;
if (gfeSources != null
&& !gfeSources.contains(parmId.getDbId().getModelName())) {
if (gfeSources != null && !gfeSources.contains(modelName)) {
field = false;
plane = false;
}
if (gfeFields != null && !gfeFields.contains(parmId.getParmName())) {
if (gfeFields != null && !gfeFields.contains(parmName)) {
source = false;
plane = false;
}
if (gfePlanes != null && !gfePlanes.contains(parmId.getParmLevel())) {
if (gfePlanes != null && !gfePlanes.contains(parmLevel)) {
source = false;
field = false;
}
if (source) {
String vbSource = VbGFEMapping.getVbSource(parmId.getDbId()
.getModelName());
String vbSource = VbGFEMapping.getVbSource(modelName);
if (vbSource != null) {
request.addAvailableSource(vbSource);
}
}
if (field) {
String vbParam = VbGFEMapping.getVbParam(parmId.getParmName());
String vbParam = VbGFEMapping.getVbParam(parmName);
if (vbParam != null) {
request.addAvailableField(vbParam);
}
}
if (plane) {
String vbLevel = VbGFEMapping.getVbLevel(parmId.getParmLevel());
String vbLevel = VbGFEMapping.getVbLevel(parmLevel);
if (vbLevel != null) {
request.addAvailablePlane(vbLevel);
}
@ -188,13 +211,24 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
@Override
public List<String> getSupportedSources() {
List<String> results = new ArrayList<String>();
for (String parmIdStr : getParmIds()) {
ParmID parmId = new ParmID(parmIdStr);
String vbSource = VbGFEMapping.getVbSource(parmId.getDbId()
.getModelName());
if (vbSource != null) {
results.add(vbSource);
DbQueryRequest dbRequest = new DbQueryRequest();
dbRequest.setEntityClass(GFERecord.class);
dbRequest.setDistinct(true);
dbRequest.addRequestField(GFEDataAccessUtil.MODEL_NAME);
try {
DbQueryResponse dbResponse = (DbQueryResponse) ThriftClient
.sendRequest(dbRequest);
for (String modelName : dbResponse.getFieldObjects(
GFEDataAccessUtil.MODEL_NAME, String.class)) {
String vbSource = VbGFEMapping.getVbSource(modelName);
if (vbSource != null) {
results.add(vbSource);
}
}
} catch (VizException e) {
statusHandler.handle(Priority.PROBLEM,
"Unable to load any GFE sources in the Volume Browser", e);
}
return results;
}
@ -207,18 +241,8 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
@Override
protected void addProductParameters(IDataCatalogEntry catalogEntry,
HashMap<String, RequestConstraint> productParameters) {
productParameters.put(GFEDataAccessUtil.PARM_ID,
getParmIdConstraint(catalogEntry.getSelectedData()));
}
private String[] getParmIds() {
HashMap<String, RequestConstraint> queryList = new HashMap<String, RequestConstraint>();
queryList.put(GFEDataAccessUtil.PLUGIN_NAME, new RequestConstraint("gfe"));
try {
return CatalogQuery.performQuery(GFEDataAccessUtil.PARM_ID, queryList);
} catch (VizException e) {
throw new RuntimeException(e);
}
productParameters.putAll(getParmIdConstraint(catalogEntry
.getSelectedData()));
}
@Override
@ -249,63 +273,61 @@ public class GFEVbDataCatalog extends AbstractDataCatalog {
@Override
protected String getDisplayUnit(IDataCatalogEntry catalogEntry,
DisplayType displayType) {
if (catalogEntry instanceof GFECatalogEntry) {
ParmID sampleId = ((GFECatalogEntry) catalogEntry).getSampleId();
ParamLevelMatchCriteria criteria = GFEGridResource
.getMatchCriteria(sampleId);
StyleRule sr = null;
try {
ParmID sampleId = ((GFECatalogEntry) catalogEntry).getSampleId();
ParamLevelMatchCriteria criteria = GFEGridResource
.getMatchCriteria(sampleId);
StyleRule sr = null;
try {
StyleManager.StyleType styleType = StyleManager.StyleType.CONTOUR;
StyleManager.StyleType styleType = StyleManager.StyleType.CONTOUR;
if (displayType.equals(DisplayType.IMAGE)) {
styleType = StyleManager.StyleType.IMAGERY;
}
if (displayType.equals(DisplayType.BARB)) {
styleType = StyleManager.StyleType.ARROW;
}
sr = StyleManager.getInstance().getStyleRule(styleType,
criteria);
} catch (VizStyleException e) {
statusHandler
.handle(Priority.PROBLEM,
"Unable to obtain a style rule for"
+ catalogEntry.getSelectedData()
.getUniqueKey(), e);
if (displayType.equals(DisplayType.IMAGE)) {
styleType = StyleManager.StyleType.IMAGERY;
}
if (sr != null) {
return sr.getPreferences().getDisplayUnitLabel();
} else {
try {
return UnitFormat.getUCUMInstance().format(
GFEDataAccessUtil.getGridParmInfo(sampleId).getUnitObject());
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM,
"Unable to obtain a unit information for"
if (displayType.equals(DisplayType.BARB)) {
styleType = StyleManager.StyleType.ARROW;
}
sr = StyleManager.getInstance().getStyleRule(styleType,
criteria);
} catch (VizStyleException e) {
statusHandler
.handle(Priority.PROBLEM,
"Unable to obtain a style rule for"
+ catalogEntry.getSelectedData()
.getUniqueKey(), e);
return "";
}
}
}
if (sr != null) {
return sr.getPreferences().getDisplayUnitLabel();
} else {
return super.getDisplayUnit(catalogEntry, displayType);
try {
return UnitFormat.getUCUMInstance().format(
GFEDataAccessUtil.getGridParmInfo(sampleId).getUnitObject());
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM,
"Unable to obtain a unit information for"
+ catalogEntry.getSelectedData()
.getUniqueKey(), e);
return "";
}
}
}
private RequestConstraint getParmIdConstraint(SelectedData selectedData) {
private Map<String, RequestConstraint> getParmIdConstraint(SelectedData selectedData) {
String parmName = VbGFEMapping.getGfeParam(selectedData.getFieldsKey());
String parmLevel = VbGFEMapping
.getGfeLevel(selectedData.getPlanesKey());
String modelName = VbGFEMapping.getGfeSource(selectedData
.getSourcesKey());
Map<String, String> parmIdComponents = new HashMap<String, String>();
parmIdComponents.put(GFEDataAccessUtil.PARM_NAME, parmName);
parmIdComponents.put(GFEDataAccessUtil.PARM_LEVEL, parmLevel);
parmIdComponents.put(GFEDataAccessUtil.MODEL_NAME, modelName);
return GFEDataAccessUtil.createParmIdConstraint(parmIdComponents);
Map<String, RequestConstraint> result = new HashMap<String, RequestConstraint>();
result.put(GFEDataAccessUtil.PARM_NAME, new RequestConstraint(parmName));
result.put(GFEDataAccessUtil.PARM_LEVEL, new RequestConstraint(
parmLevel));
result.put(GFEDataAccessUtil.MODEL_NAME, new RequestConstraint(
modelName));
return result;
}
private static class GFECatalogEntry extends DataCatalogEntry {

View file

@ -4,7 +4,6 @@ import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
@ -29,7 +28,6 @@ import com.raytheon.uf.common.dataplugin.ffmp.FFMPAggregateRecord;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPBasin;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPBasinData;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPGuidanceBasin;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPGuidanceInterpolation;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPRecord;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPRecord.FIELDS;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPTemplates;
@ -55,7 +53,6 @@ import com.raytheon.uf.common.monitor.xml.SourceXML;
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.common.time.DataTime;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.viz.core.HDF5Util;
import com.raytheon.uf.viz.core.VizApp;
@ -101,6 +98,7 @@ import com.raytheon.uf.viz.monitor.listeners.IMonitorListener;
* Mar 6, 2013 1769 dhladky Changed threading to use count down latch.
* Apr 9, 2013 1890 dhladky Fixed the broken cache file load
* Apr 16, 2013 1912 bsteffen Initial bulk hdf5 access for ffmp
* Apr 26, 2013 1954 bsteffen Minor code cleanup throughout FFMP.
*
* </pre>
*
@ -111,21 +109,18 @@ import com.raytheon.uf.viz.monitor.listeners.IMonitorListener;
public class FFMPMonitor extends ResourceMonitor {
private static long SECONDS_PER_HOUR = 60 * 60;
/** boolean for initialization **/
public static boolean isInitialized = false;
/** Singleton instance of this class */
private static FFMPMonitor monitor = null;
/** Array of scan listeners **/
private ArrayList<IFFMPResourceListener> resourceListeners = new ArrayList<IFFMPResourceListener>();
private List<IFFMPResourceListener> resourceListeners = new ArrayList<IFFMPResourceListener>();
public FFMPSplash ffmpSplash;
private FFMPSplash ffmpSplash;
private String wfo = null;
/** Pattern for dates in radar */
public static ThreadLocal<SimpleDateFormat> datePattern = new ThreadLocal<SimpleDateFormat>() {
private static ThreadLocal<SimpleDateFormat> datePattern = new ThreadLocal<SimpleDateFormat>() {
@Override
protected SimpleDateFormat initialValue() {
@ -138,16 +133,11 @@ public class FFMPMonitor extends ResourceMonitor {
private FFMPSiteDataContainer siteDataMap = new FFMPSiteDataContainer();
// Interpolation Guidance Sources
public FFMPGuidanceInterpolation interpolation = null;
/** config manager **/
private FFMPSourceConfigurationManager fscm = null;
/** config manager **/
public FFMPSourceConfigurationManager fscm = null;
/** config manager **/
public FFMPConfig ffmpConfig = null;
public ArrayList<Date> dataTimes = null;
private FFMPConfig ffmpConfig = null;
private FFMPTimeWindow qpfWindow = null;
@ -246,7 +236,6 @@ public class FFMPMonitor extends ResourceMonitor {
public static synchronized FFMPMonitor getInstance() {
if (monitor == null) {
monitor = new FFMPMonitor();
isInitialized = true;
}
return monitor;
@ -274,7 +263,6 @@ public class FFMPMonitor extends ResourceMonitor {
public FFMPSourceConfigurationManager getSourceConfig() {
if (fscm == null) {
fscm = FFMPSourceConfigurationManager.getInstance();
fscm.readConfigXml();
}
return fscm;
@ -329,15 +317,8 @@ public class FFMPMonitor extends ResourceMonitor {
* @return
* @throws VizException
*/
public void populateFFMPRecord(ProductXML product, String siteKey,
String dataKey, String source, Date ptime, String phuc,
boolean retrieveNew) {
boolean isProductLoad = false;
if (product != null) {
isProductLoad = true;
}
public void populateFFMPRecord(String siteKey, String dataKey,
String source, Date ptime, String phuc, boolean retrieveNew) {
if (source != null) {
boolean dupOverride = false;
@ -357,7 +338,7 @@ public class FFMPMonitor extends ResourceMonitor {
|| !getLoadedUris(siteKey, source, phuc)
.contains(uri)) {
try {
populateFFMPRecord(isProductLoad, siteKey,
populateFFMPRecord(siteKey,
new FFMPRecord(uri), source, phuc);
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM,
@ -381,12 +362,11 @@ public class FFMPMonitor extends ResourceMonitor {
* @return
* @throws VizException
*/
public FFMPRecord populateFFMPRecord(boolean isProductLoad, String uri,
String siteKey, String source, String phuc) throws Exception {
public FFMPRecord populateFFMPRecord(String uri, String siteKey,
String source, String phuc) throws Exception {
try {
populateFFMPRecord(isProductLoad, siteKey, new FFMPRecord(uri),
source, phuc);
populateFFMPRecord(siteKey, new FFMPRecord(uri), source, phuc);
} catch (VizException e) {
statusHandler.handle(Priority.INFO,
"FFMP Can't retrieve FFMP URI, " + uri, e);
@ -455,10 +435,10 @@ public class FFMPMonitor extends ResourceMonitor {
* @param phuc
* @throws Exception
*/
public void populateFFMPRecord(boolean isProductLoad, String siteKey,
public void populateFFMPRecord(String siteKey,
FFMPRecord ffmpRec, String source, String phuc) throws Exception {
FFMPLoadRecord flr = new FFMPLoadRecord(isProductLoad, siteKey,
FFMPLoadRecord flr = new FFMPLoadRecord(siteKey,
ffmpRec, source, phuc);
flr.run();
}
@ -481,8 +461,8 @@ public class FFMPMonitor extends ResourceMonitor {
if (!uris.contains(dataUri)) {
try {
SourceXML sourceXML = fscm.getSource(source);
FFMPRecord ffmpRec = populateFFMPRecord(true, dataUri,
siteKey, source, phuc);
FFMPRecord ffmpRec = populateFFMPRecord(dataUri, siteKey,
source, phuc);
File loc = HDF5Util.findHDF5Location(ffmpRec);
IDataStore dataStore = DataStoreFactory.getDataStore(loc);
@ -734,8 +714,6 @@ public class FFMPMonitor extends ResourceMonitor {
FFMPRecord record = siteDataMap.get(siteKey).getSourceData(sourceName)
.getRecord();
String guidSrc = FFMPConfig.getInstance().getFFMPConfigData()
.getGuidSrc();
if ((record != null)
&& (record.getBasinData(phuc).getBasins().size() > 0)) {
@ -754,7 +732,8 @@ public class FFMPMonitor extends ResourceMonitor {
ProductRunXML productRun = getRunConfig().getProduct(
siteKey);
String guidSrc = FFMPConfig.getInstance()
.getFFMPConfigData().getGuidSrc();
for (SourceXML source : productRun.getGuidanceSources(
product, guidSrc)) {
if (siteDataMap.get(siteKey)
@ -762,7 +741,7 @@ public class FFMPMonitor extends ResourceMonitor {
.hasLoadedAnyUris()) {
continue;
} else {
populateFFMPRecord(product, siteKey, dataKey,
populateFFMPRecord(siteKey, dataKey,
source.getSourceName(), ptime, phuc,
retrieveNew);
}
@ -771,8 +750,8 @@ public class FFMPMonitor extends ResourceMonitor {
// FFG is the primary if
if (!siteDataMap.get(siteKey).getSourceData(sourceName)
.hasLoadedAnyUris()) {
populateFFMPRecord(product, siteKey, dataKey,
sourceName, ptime, phuc, retrieveNew);
populateFFMPRecord(siteKey, dataKey, sourceName, ptime,
phuc, retrieveNew);
}
}
@ -780,8 +759,8 @@ public class FFMPMonitor extends ResourceMonitor {
.getRecord();
} else {
populateFFMPRecord(product, siteKey, dataKey, sourceName,
ptime, phuc, retrieveNew);
populateFFMPRecord(siteKey, dataKey, sourceName, ptime, phuc,
retrieveNew);
}
} else { // must populate for a different huc for all possible times
@ -801,20 +780,22 @@ public class FFMPMonitor extends ResourceMonitor {
.getSourceType()
.equals(FFMPSourceConfigurationManager.SOURCE_TYPE.GUIDANCE
.getSourceType())) {
String guidSrc = FFMPConfig.getInstance()
.getFFMPConfigData().getGuidSrc();
for (SourceXML ffgSource : productRun
.getGuidanceSources(product, guidSrc)) {
populateFFMPRecord(product, siteKey, dataKey,
populateFFMPRecord(siteKey, dataKey,
ffgSource.getSourceName(), ptime, phuc,
retrieveNew);
}
} else {
populateFFMPRecord(product, siteKey, dataKey,
populateFFMPRecord(siteKey, dataKey,
sourceName, ptime, phuc, retrieveNew);
}
}
} else {
populateFFMPRecord(product, siteKey, dataKey, sourceName,
populateFFMPRecord(siteKey, dataKey, sourceName,
ptime, phuc, retrieveNew);
}
} else {
@ -828,8 +809,8 @@ public class FFMPMonitor extends ResourceMonitor {
SOURCE_TYPE.GUIDANCE.getSourceType())) {
sourceName = sourcexml.getDisplayName();
} else {
populateFFMPRecord(product, siteKey, dataKey, sourceName,
ptime, phuc, retrieveNew);
populateFFMPRecord(siteKey, dataKey, sourceName, ptime,
phuc, retrieveNew);
}
}
@ -842,21 +823,6 @@ public class FFMPMonitor extends ResourceMonitor {
}
/**
* Sort by DataTime
*
* @author dhladky
*
*/
public class SortByDataTime implements Comparator<DataTime> {
@Override
public int compare(DataTime o1, DataTime o2) {
return o1.compareTo(o2);
}
}
/**
* gets the wfo
*
@ -883,21 +849,13 @@ public class FFMPMonitor extends ResourceMonitor {
*/
public FIELDS getField(String sourceName) {
String sfield = getSourceConfig().getSourceType(sourceName)
.getSourceType().toLowerCase();
FIELDS myField = null;
if (sfield.equals(FFMPRecord.FIELDS.QPE.getFieldName())) {
myField = FFMPRecord.FIELDS.QPE;
} else if (sfield.equals(FFMPRecord.FIELDS.RATE.getFieldName())) {
myField = FFMPRecord.FIELDS.RATE;
} else if (sfield.equals(FFMPRecord.FIELDS.QPF.getFieldName())) {
myField = FFMPRecord.FIELDS.QPF;
} else if (sfield.equals(FFMPRecord.FIELDS.GUIDANCE.getFieldName())) {
myField = FFMPRecord.FIELDS.GUIDANCE;
} else if (sfield.equals("gage")) {
myField = FFMPRecord.FIELDS.VIRTUAL;
String sourceType = getSourceConfig().getSource(sourceName)
.getSourceType();
if (sourceType.equalsIgnoreCase(SOURCE_TYPE.GAGE.name())) {
return FFMPRecord.FIELDS.VIRTUAL;
} else {
return FFMPRecord.FIELDS.valueOf(sourceType);
}
return myField;
}
/**
@ -933,10 +891,7 @@ public class FFMPMonitor extends ResourceMonitor {
}
public void launchSplash(String siteKey) {
final String fsiteKey = siteKey;
public void launchSplash(final String siteKey) {
VizApp.runAsync(new Runnable() {
@Override
public void run() {
@ -948,7 +903,7 @@ public class FFMPMonitor extends ResourceMonitor {
ffmpSplash.open();
// latch
int count = 0;
while (!getTemplates(fsiteKey).done) {
while (!getTemplates(siteKey).done) {
try {
count++;
@ -1110,7 +1065,7 @@ public class FFMPMonitor extends ResourceMonitor {
System.gc();
}
public ArrayList<IFFMPResourceListener> getResourceListenerList() {
public List<IFFMPResourceListener> getResourceListenerList() {
return resourceListeners;
}
@ -1327,13 +1282,13 @@ public class FFMPMonitor extends ResourceMonitor {
* @param retrieveNew
* @return
*/
public HashMap<String, FFMPRecord> getGuidanceRecords(ProductXML product,
public Map<String, FFMPRecord> getGuidanceRecords(ProductXML product,
String siteKey, Date date, String phuc, boolean retrieveNew) {
HashMap<String, FFMPRecord> guidRecs = new HashMap<String, FFMPRecord>();
Map<String, FFMPRecord> guidRecs = new HashMap<String, FFMPRecord>();
ProductRunXML productRun = FFMPRunConfigurationManager.getInstance()
.getProduct(siteKey);
ArrayList<String> guidTypes = productRun.getGuidanceTypes(product);
List<String> guidTypes = productRun.getGuidanceTypes(product);
for (String type : guidTypes) {
@ -1520,9 +1475,8 @@ public class FFMPMonitor extends ResourceMonitor {
* @param sourceName
* @return
*/
public long getSourceTimeWindow(String sourceName, String siteKey) {
return getSourceConfig().getSource(sourceName).getExpirationMinutes(
siteKey) * 60 * 1000;
private long getSourceTimeWindow(SourceXML source, String siteKey) {
return source.getExpirationMinutes(siteKey) * 60 * 1000;
}
/**
@ -1531,10 +1485,10 @@ public class FFMPMonitor extends ResourceMonitor {
* @param sourceName
* @return
*/
public FFMPTimeWindow getTimeWindow(String sourceName, Date date,
public FFMPTimeWindow getTimeWindow(SourceXML source, Date date,
String siteKey) {
FFMPTimeWindow window = new FFMPTimeWindow();
long lwindow = getSourceTimeWindow(sourceName, siteKey);
long lwindow = getSourceTimeWindow(source, siteKey);
window.setAfterTime(new Date(date.getTime() - lwindow));
window.setBeforeTime(new Date(date.getTime() + lwindow));
@ -1730,11 +1684,11 @@ public class FFMPMonitor extends ResourceMonitor {
* @param barrierTime
* @param phuc
*/
public void processUri(boolean isProductLoad, String uri, String siteKey,
public void processUri(String uri, String siteKey,
String sourceName, Date barrierTime, String phuc) {
if (uri != null) {
try {
FFMPRecord record = populateFFMPRecord(isProductLoad, uri,
FFMPRecord record = populateFFMPRecord(uri,
siteKey, sourceName, phuc);
if (record != null) {
record.getBasinData(phuc).loadNow();
@ -1759,10 +1713,8 @@ public class FFMPMonitor extends ResourceMonitor {
* @param sourceName
*/
public void processUris(NavigableMap<Date, List<String>> uriMap,
boolean isProductLoad, String siteKey, String sourceName,
Date barrierTime, String phuc) {
FFMPProcessUris processor = new FFMPProcessUris(uriMap, isProductLoad,
String siteKey, String sourceName, Date barrierTime, String phuc) {
FFMPProcessUris processor = new FFMPProcessUris(uriMap,
siteKey, sourceName, barrierTime, phuc);
processor.run();
}
@ -2226,8 +2178,8 @@ public class FFMPMonitor extends ResourceMonitor {
final String fsiteKey;
public FFMPLoadRecord(boolean isProductLoad, String siteKey,
FFMPRecord ffmpRec, String source, String huc) throws Exception {
public FFMPLoadRecord(String siteKey, FFMPRecord ffmpRec,
String source, String huc) throws Exception {
this.fffmpRec = ffmpRec;
this.fsource = source;
this.fsiteKey = siteKey;
@ -2318,7 +2270,6 @@ public class FFMPMonitor extends ResourceMonitor {
final NavigableMap<Date, List<String>> furiMap;
final boolean fisProductLoad;
final String fsiteKey;
@ -2329,13 +2280,10 @@ public class FFMPMonitor extends ResourceMonitor {
final String fhuc;
public FFMPProcessUris(NavigableMap<Date, List<String>> uriMap,
boolean isProductLoad, String siteKey, String sourceName,
Date barrierTime, String phuc) {
String siteKey, String sourceName, Date barrierTime, String phuc) {
this.furiMap = uriMap;
this.fsiteKey = siteKey;
this.fbarrierTime = barrierTime;
this.fisProductLoad = isProductLoad;
this.fsourceName = sourceName;
this.fhuc = phuc;
@ -2363,8 +2311,8 @@ public class FFMPMonitor extends ResourceMonitor {
.after(fbarrierTime)
|| isGuidance) {
try {
record = populateFFMPRecord(fisProductLoad,
uri, fsiteKey, fsourceName, fhuc);
record = populateFFMPRecord(uri, fsiteKey,
fsourceName, fhuc);
if (record != null) {
populatedRecords.add(record);
if (source != null) {

View file

@ -21,7 +21,10 @@ package com.raytheon.uf.viz.monitor.ffmp.ui.dialogs;
import java.io.File;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXB;
@ -57,6 +60,7 @@ import com.raytheon.uf.viz.monitor.ffmp.xml.FFMPTableColumnXML;
* getting ColorCell and ReverseFilter
* Apr 12, 2013 1902 mpduff Speed up cell coloring.
* Apr 15. 2013 1890 dhladky Added Mikes fix for singleton.
* Apr 26, 2013 1954 bsteffen Minor code cleanup throughout FFMP.
*
* </pre>
*
@ -111,14 +115,16 @@ public class FFMPConfig {
private final Color vgbColor = new Color(Display.getDefault(), 196, 137,
250);
private final String defaultConfigXml = "DefaultFFMPconfig_basin.xml";
private static final String DEFAULT_CONFIG_XML = "ffmp"
+ IPathManager.SEPARATOR + "guiConfig" + IPathManager.SEPARATOR
+ "DefaultFFMPconfig_basin.xml";
/**
* Used for looking up data - NOT for editing.
*/
private HashMap<ThreshColNames, ThresholdManager> threshMgrMap;
private Map<ThreshColNames, ThresholdManager> threshMgrMap;
private HashMap<String, ThreshColNames> thresholdLookup;
private Map<String, ThreshColNames> thresholdLookup;
private AttributesDlgData attrData = null;
@ -133,7 +139,8 @@ public class FFMPConfig {
}
private void init() {
threshMgrMap = new HashMap<ThreshColNames, ThresholdManager>();
threshMgrMap = new EnumMap<ThreshColNames, ThresholdManager>(
ThreshColNames.class);
thresholdLookup = new HashMap<String, ThreshColNames>();
@ -141,7 +148,7 @@ public class FFMPConfig {
thresholdLookup.put(threshColName.name(), threshColName);
}
readDefaultFFMPConfigBasin(defaultConfigXml);
readDefaultFFMPConfigBasin();
}
public boolean isThreshold(String colName) {
@ -182,7 +189,7 @@ public class FFMPConfig {
}
public void loadDefaultConfig() {
readDefaultFFMPConfigBasin(defaultConfigXml);
readDefaultFFMPConfigBasin();
}
private void readNewFFMPConfigBasin(LocalizationFile xmlFileName) {
@ -198,19 +205,14 @@ public class FFMPConfig {
}
}
private void readDefaultFFMPConfigBasin(String xmlFileName) {
private void readDefaultFFMPConfigBasin() {
ffmpCfgBasin = null;
String fs = String.valueOf(File.separatorChar);
try {
IPathManager pm = PathManagerFactory.getPathManager();
String path = null;
File file = pm.getStaticFile("ffmp" + fs + "guiConfig" + fs
+ xmlFileName);
if (file != null) {
path = file.getAbsolutePath();
} else {
File file = pm.getStaticFile(DEFAULT_CONFIG_XML);
if (file == null) {
// Should never get here since there is a baseline version of
// the file.
statusHandler.handle(Priority.ERROR,
@ -218,9 +220,9 @@ public class FFMPConfig {
return;
}
System.out.println("Path Config FFMP: " + path);
System.out.println("Path Config FFMP: " + file.getAbsolutePath());
ffmpCfgBasin = JAXB.unmarshal(new File(path),
ffmpCfgBasin = JAXB.unmarshal(file,
FFMPConfigBasinXML.class);
createThresholdManager();
@ -333,15 +335,15 @@ public class FFMPConfig {
private void createThresholdManager() {
threshMgrMap.clear();
ArrayList<FFMPTableColumnXML> tableColData = ffmpCfgBasin
List<FFMPTableColumnXML> tableColData = ffmpCfgBasin
.getTableColumnData();
for (ThreshColNames threshName : ThreshColNames.values()) {
for (FFMPTableColumnXML tcXML : tableColData) {
if (threshName.name().compareTo(tcXML.getColumnName()) == 0) {
ThresholdManager threshMgr = new ThresholdManager(tcXML);
threshMgrMap.put(threshName, threshMgr);
}
for (FFMPTableColumnXML tcXML : tableColData) {
ThreshColNames colNames = thresholdLookup
.get(tcXML.getColumnName());
if (colNames != null) {
ThresholdManager threshMgr = new ThresholdManager(tcXML);
threshMgrMap.put(colNames, threshMgr);
}
}
}

View file

@ -117,6 +117,7 @@ import com.raytheon.viz.ui.dialogs.ICloseCallback;
* Feb 28, 2013 1729 dhladky Adjusted the way in which the dialog load thread rejoins the main GUI thread.
* Mar 01, 2013 13228 gzhang Adding field rowName for VGB in County
* Mar 24, 2013 1818 mpduff Fixed Attributes dialog on multiple opens, needed an isDisposed check.
* Apr 25, 2013 1902 mpduff Fixed Thresholds dialog on multiple opens, needed an isDisposed check.
* </pre>
*
* @author lvenable
@ -319,8 +320,8 @@ public class FfmpBasinTableDlg extends CaveSWTDialog implements
dataLoadFont.dispose();
timeDurFont.dispose();
//FFMPConfig.getInstance().disposeResources();
//FFMPConfig.unloadConfig();
// FFMPConfig.getInstance().disposeResources();
// FFMPConfig.unloadConfig();
if (refreshColor != null) {
refreshColor.dispose();
@ -1313,18 +1314,18 @@ public class FfmpBasinTableDlg extends CaveSWTDialog implements
attributeDlg = new AttributesDlg(shell, resource, attrData, this);
attributeDlg.open();
} else {
attributeDlg.bringToTop();
attributeDlg.bringToTop();
}
}
private void displayThresholdsDialog(ThreshColNames colName) {
if (attrThreshDlg == null) {
if (attrThreshDlg == null || attrThreshDlg.isDisposed()) {
attrThreshDlg = new AttributeThresholdDlg(shell, colName, this);
attrThreshDlg.open();
} else {
attrThreshDlg.bringToTop();
attrThreshDlg.bringToTop();
}
attrThreshDlg.newThreshold(colName);
}
@ -2110,17 +2111,17 @@ public class FfmpBasinTableDlg extends CaveSWTDialog implements
shell.pack();
}
String prefix = null;
String prefix = null;
if (status.getLoaderType() == LOADER_TYPE.SECONDARY) {
prefix = " Secondary Data Load: ";
} else if (status.getLoaderType() == LOADER_TYPE.TERTIARY) {
prefix = " Tertiary Data Load: ";
} else if (status.getLoaderType() == LOADER_TYPE.GENERAL) {
prefix = " General Data Load: ";
} else {
prefix = " Tertiary Data Load: ";
}
if (status.getLoaderType() == LOADER_TYPE.SECONDARY) {
prefix = " Secondary Data Load: ";
} else if (status.getLoaderType() == LOADER_TYPE.TERTIARY) {
prefix = " Tertiary Data Load: ";
} else if (status.getLoaderType() == LOADER_TYPE.GENERAL) {
prefix = " General Data Load: ";
} else {
prefix = " Tertiary Data Load: ";
}
if (status.isDone() == false) {
dataLoadingLbl.setText(prefix + status.getMessage());

View file

@ -20,6 +20,7 @@
package com.raytheon.uf.viz.monitor.ffmp.ui.rsc;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import org.eclipse.swt.graphics.RGB;
@ -50,6 +51,8 @@ import com.raytheon.viz.core.style.image.ImagePreferences;
* ------------ ---------- ----------- --------------------------
* 08/29/09 2152 D. Hladky Initial release
* 05/21/12 DR 14833 G. Zhang Error handling for invalid cmap
* Apr 26, 2013 1954 bsteffen Minor code cleanup throughout FFMP.
*
* </pre>
*
* @author dhladky
@ -155,18 +158,15 @@ public class FFMPColorUtils {
* @return
*/
private static RGB convert(Color color) {
int blue;
int green;
int red;
RGB returnColor = null;
if (color != null) {
blue = new Float(color.getBlue() * 255.0).intValue();
green = new Float(color.getGreen() * 255.0).intValue();
red = new Float(color.getRed() * 255.0).intValue();
returnColor = new RGB(red, green, blue);
int blue = (int) (color.getBlue() * 255.0f);
int green = (int) (color.getGreen() * 255.0f);
int red = (int) (color.getRed() * 255.0f);
return new RGB(red, green, blue);
}
return returnColor;
return null;
}
/**
@ -186,37 +186,31 @@ public class FFMPColorUtils {
return rgb;
}
double val2 = (Math.round(valueArg * 100.0)) / 100.0;
Double value = val2;
double value = (Math.round(valueArg * 100.0)) / 100.0;
if (value < 0.005 && field != FIELDS.DIFF) {
ret = 0;
} else if (field == FIELDS.DIFF) {
Color color = colormapparams.getColorByValue(value.floatValue());
if (field == FIELDS.DIFF) {
Color color = colormapparams.getColorByValue((float) value);
rgb = convert(color);
return rgb;
} else {
if (value < 0.0) {
ret = 0;
} else {
Color color = colormapparams
.getColorByValue(value.floatValue());
} else if (value >= 0.005) {
Color color = colormapparams.getColorByValue((float) value);
rgb = convert(color);
return rgb;
}
}
if (ret >= getColorMap().getColors().size()) {
ret = getColorMap().getColors().size() - 1;
List<Color> colors = getColorMap().getColors();
if (ret >= colors.size()) {
ret = colors.size() - 1;
}
if (ret < 0) {
ret = 0;
}
rgb = convert(getColorMap().getColors().get(ret));
rgb = convert(colors.get(ret));
return rgb;
}

View file

@ -20,9 +20,11 @@
package com.raytheon.uf.viz.monitor.ffmp.ui.rsc;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPBasin;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPBasinData;
@ -37,7 +39,6 @@ import com.raytheon.uf.common.dataplugin.ffmp.FFMPVirtualGageBasin;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPVirtualGageBasinMetaData;
import com.raytheon.uf.common.monitor.config.FFFGDataMgr;
import com.raytheon.uf.common.monitor.config.FFMPRunConfigurationManager;
import com.raytheon.uf.common.monitor.config.FFMPSourceConfigurationManager;
import com.raytheon.uf.common.monitor.xml.DomainXML;
import com.raytheon.uf.common.monitor.xml.ProductRunXML;
import com.raytheon.uf.common.monitor.xml.ProductXML;
@ -72,9 +73,11 @@ import com.raytheon.uf.viz.monitor.ffmp.ui.dialogs.FfmpTableConfigData;
* feb 20, 2013 1635 dhladky Fixed multi guidance displays
* Feb 28, 2013 1729 dhladky General enhancements for speed.
* Apr 12, 2013 1902 mpduff Code Cleanup.
* Apr 15, 2013 1890 dhladky Added another constant fix.
* Apr 15, 2013 1911 dhladky Fixed forced FFG for centered aggregates.
* Apr 24, 2013 1946 mpduff Fixed FFFG value for ALL when an aggregate is forced
* Apr 15, 2013 1890 dhladky Added another constant fix.
* Apr 15, 2013 1911 dhladky Fixed forced FFG for centered aggregates.
* Apr 24, 2013 1946 mpduff Fixed FFFG value for ALL when an aggregate is forced
* Apr 26, 2013 1954 bsteffen Minor code cleanup throughout FFMP.
*
* </pre>
*
* @author dhladky
@ -87,83 +90,59 @@ public class FFMPDataGenerator {
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(FFMPDataGenerator.class);
private final String ALL = FFMPRecord.ALL;
private static final String ALL = FFMPRecord.ALL;
private final String NA = "NA";
private static final String NA = "NA";
private final String siteKey;
private final String dataKey;
private final ProductXML product;
private final Date paintRefTime;
private final Date tableTime;
private final Object centeredAggregationKey;
private final String huc;
private final ArrayList<DomainXML> domains;
private final double sliderTime;
private boolean isWorstCase = false;
FFMPConfig ffmpCfg = FFMPConfig.getInstance();
private FFMPTemplates ft = null;
FFMPTemplates ft = null;
private FFMPResource resource = null;
FFMPResource resource = null;
private FFMPMonitor monitor = null;
FFMPMonitor monitor = null;
private FFMPBasinData qpeBasin = null;
FFMPBasinData qpeBasin = null;
private FFMPBasinData qpfBasin = null;
FFMPBasinData qpfBasin = null;
private FFMPBasinData rateBasin = null;
FFMPBasinData rateBasin = null;
private Map<String, FFMPBasinData> guidBasins = null;
HashMap<String, FFMPBasinData> guidBasins = null;
private FFMPBasinData virtualBasin = null;
FFMPBasinData virtualBasin = null;
private Map<String, FFMPRecord> guidRecords = null;
FFMPRecord rateRecord = null;
private FFMPRecord baseRec = null;
FFMPRecord qpeRecord = null;
private boolean isRate = false;
FFMPRecord qpfRecord = null;
HashMap<String, FFMPRecord> guidRecords = null;
FFMPRecord virtualRecord = null;
FFMPRecord baseRec = null;
SourceXML primarySource = null;
FFFGDataMgr dman = null;
boolean isRate = false;
long expirationTime = 0l;
private long expirationTime = 0l;
private String[] cwaArr = null;
private HashMap<String, FFFGForceUtil> forceUtils = null;
private Map<String, FFFGForceUtil> forceUtils = null;
private FfmpTableConfigData ffmpTableCfgData = null;
public FFMPDataGenerator(FFMPMonitor monitor, FFMPResource resource) {
siteKey = resource.getSiteKey();
dataKey = resource.getDataKey();
product = resource.getProduct();
paintRefTime = resource.getPaintTime().getRefTime();
tableTime = resource.getTableTime();
centeredAggregationKey = resource.centeredAggregationKey;
huc = resource.getHuc();
domains = resource.getDomains();
sliderTime = resource.getTime();
isWorstCase = resource.isWorstCase();
@ -171,10 +150,11 @@ public class FFMPDataGenerator {
this.resource = resource;
this.monitor = monitor;
this.ft = monitor.getTemplates(siteKey);
this.primarySource = resource.getResourceData().getPrimarySourceXML();
SourceXML primarySource = resource.getResourceData()
.getPrimarySourceXML();
this.isRate = primarySource.isRate();
this.expirationTime = primarySource.getExpirationMinutes(resource
.getSiteKey()) * TimeUtil.MILLIS_PER_MINUTE;
this.expirationTime = primarySource.getExpirationMinutes(siteKey)
* TimeUtil.MILLIS_PER_MINUTE;
ffmpTableCfgData = tableConfig.getTableConfigData(siteKey);
}
@ -195,94 +175,53 @@ public class FFMPDataGenerator {
try {
FIELDS field = getBaseField();
if (field != null) {
if (baseRec != null) {
FFMPBasinData fbd = null;
if (centeredAggregationKey != null) {
fbd = baseRec.getBasinData(ALL);
} else {
fbd = baseRec.getBasinData(huc);
}
if (field == null || baseRec == null) {
return tData;
}
FFMPBasinData fbd = null;
if (centeredAggregationKey != null) {
fbd = baseRec.getBasinData(ALL);
} else {
fbd = baseRec.getBasinData(huc);
}
if (!fbd.getBasins().isEmpty()) {
if ((centeredAggregationKey == null) || huc.equals(ALL)) {
// System.out.println(fbd.getBasins().keySet().size()
// + " rows in the table");
for (Long key : fbd.getBasins().keySet()) {
if (huc.equals(ALL)) {
for (DomainXML domain : domains) {
List<DomainXML> domains = resource.getDomains();
if (!fbd.getBasins().isEmpty()) {
if ((centeredAggregationKey == null) || huc.equals(ALL)) {
// System.out.println(fbd.getBasins().keySet().size()
// + " rows in the table");
for (Long key : fbd.getBasins().keySet()) {
if (huc.equals(ALL)) {
FFMPBasinMetaData fmdb = ft.getBasin(siteKey, key);
if (fmdb == null) {
continue;
}
FFMPBasinMetaData fmdb = ft.getBasin(
siteKey, key);
String cwa = domain.getCwa();
for (DomainXML domain : domains) {
String cwa = domain.getCwa();
if (fmdb == null) {
continue;
}
if ((cwa.equals(fmdb.getCwa()))
|| (domain.isPrimary() && fmdb
.isPrimaryCwa())) {
try {
setFFMPRow(fbd.get(key), tData,
false, cwa);
} catch (Exception e) {
statusHandler.handle(
Priority.PROBLEM,
if ((cwa.equals(fmdb.getCwa()))
|| (domain.isPrimary() && fmdb
.isPrimaryCwa())) {
try {
setFFMPRow(fbd.get(key), tData, false,
cwa);
} catch (Exception e) {
statusHandler
.handle(Priority.PROBLEM,
"Couldn't create table row"
+ e);
}
if (virtualBasin != null) {
for (Long id : ft
.getVirtualGageBasinLookupIds(
siteKey,
key,
huc,
resource.basinTableDlg
.getRowName())) {
try {
setFFMPRow(
virtualBasin
.get(id),
tData, true,
domain.getCwa());
} catch (Exception e) {
statusHandler
.handle(Priority.PROBLEM,
"Couldn't create table row"
+ e);
}
}
}
}
}
} else {
/*
* make sure at least one basin in the agg
* is in the CWA
*/
ArrayList<Long> pfafs = ft
.getAggregatePfafs(key, siteKey,
huc);
boolean isVGB = false;
if (ft.checkVGBsInAggregate(key, siteKey,
huc)) {
isVGB = true;
}
if (!pfafs.isEmpty()) {
FFMPBasinMetaData fmdb = ft
.getBasinInDomains(siteKey,
domains, pfafs);
if (fmdb != null) {
if (virtualBasin != null) {
for (Long id : ft
.getVirtualGageBasinLookupIds(
siteKey, key, huc,
resource.basinTableDlg
.getRowName())) {
try {
setFFMPRow(fbd.get(key), tData,
isVGB, null);
setFFMPRow(
virtualBasin.get(id),
tData, true, cwa);
} catch (Exception e) {
statusHandler.handle(
Priority.PROBLEM,
@ -293,77 +232,99 @@ public class FFMPDataGenerator {
}
}
}
}
// show pfafs in aggregation
else {
for (Long key : resource
.getCenteredAggregatePfafs()) {
FFMPBasinMetaData fmdb = ft.getBasin(siteKey,
key);
} else {
/*
* make sure at least one basin in the agg is in the
* CWA
*/
List<Long> pfafs = ft.getAggregatePfafs(key,
siteKey, huc);
boolean isVGB = false;
if (ft.checkVGBsInAggregate(key, siteKey, huc)) {
isVGB = true;
}
if (!pfafs.isEmpty()) {
FFMPBasinMetaData fmdb = ft.getBasinInDomains(
siteKey, domains, pfafs);
if (fmdb != null) {
for (DomainXML domain : domains) {
try {
setFFMPRow(fbd.get(key), tData, isVGB,
null);
} catch (Exception e) {
statusHandler
.handle(Priority.PROBLEM,
"Couldn't create table row"
+ e);
}
}
}
}
}
}
// show pfafs in aggregation
else {
for (Long key : resource.getCenteredAggregatePfafs()) {
if ((domain.getCwa().equals(fmdb
.getCwa()))
|| (domain.isPrimary() && fmdb
.isPrimaryCwa())) {
FFMPBasinMetaData fmdb = ft.getBasin(siteKey, key);
setFFMPRow(fbd.get(key), tData,
false, null);
if (fmdb != null) {
for (DomainXML domain : domains) {
if (virtualBasin != null) {
for (Long id : ft
.getVirtualGageBasinLookupIds(
siteKey,
key,
huc,
resource.basinTableDlg
.getRowName())) {
try {
setFFMPRow(
virtualBasin
.get(id),
tData, true,
null);
} catch (Exception e) {
statusHandler
.handle(Priority.PROBLEM,
"Couldn't create table row"
+ e);
}
}
if ((domain.getCwa().equals(fmdb.getCwa()))
|| (domain.isPrimary() && fmdb
.isPrimaryCwa())) {
setFFMPRow(fbd.get(key), tData, false, null);
if (virtualBasin != null) {
for (Long id : ft
.getVirtualGageBasinLookupIds(
siteKey, key, huc,
resource.basinTableDlg
.getRowName())) {
try {
setFFMPRow(
virtualBasin.get(id),
tData, true, null);
} catch (Exception e) {
statusHandler.handle(
Priority.PROBLEM,
"Couldn't create table row"
+ e);
}
}
}
}
}
}
tData.sortData();
}
}
tData.sortData();
}
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM,
"Failed to load FFMP table data!", e);
}
return tData;
}
private void setFFMPRow(FFMPBasin cBasin, FFMPTableData tData,
boolean isVGB, String domain) {
try {
String pfafToTest = null;
if (cBasin instanceof FFMPVirtualGageBasin) {
if (tData.containsPfaf(((FFMPVirtualGageBasin) cBasin).getLid()
.toString())) {
return;
}
pfafToTest = ((FFMPVirtualGageBasin) cBasin).getLid();
} else {
if (tData.containsPfaf(cBasin.getPfaf().toString())) {
return;
}
pfafToTest = cBasin.getPfaf().toString();
}
if (tData.containsPfaf(pfafToTest)) {
return;
}
} catch (Exception e) {
return;
@ -386,31 +347,28 @@ public class FFMPDataGenerator {
}
if (cBasin instanceof FFMPVirtualGageBasin) {
rowField = FIELDS.VIRTUAL;
String lid = ((FFMPVirtualGageBasin) cBasin).getLid();
FFMPVirtualGageBasin vgBasin = (FFMPVirtualGageBasin) cBasin;
String lid = vgBasin.getLid();
if (lid != null) {
StringBuilder sb = new StringBuilder(lid);
// in this special case it is actually the LID
trd.setPfaf(((FFMPVirtualGageBasin) cBasin).getLid());
trd.setPfaf(lid);
FFMPVirtualGageBasinMetaData fvgmbd = ft
.getVirtualGageBasinMetaData(siteKey,
((FFMPVirtualGageBasin) cBasin).getLid());
.getVirtualGageBasinMetaData(siteKey, lid);
FFMPBasinMetaData metabasin = ft.getBasin(siteKey,
fvgmbd.getParentPfaf());
Long parentBasinPfaf = fvgmbd.getParentPfaf();
if (fvgmbd != null) {
mouseOverText = metabasin.getBasinId() + "\n" + lid + "-"
+ fvgmbd.getName();
mouseOverText = metabasin.getBasinId() + "\n"
+ fvgmbd.getLid() + "-" + fvgmbd.getName();
if (!huc.equals(ALL)) {
sb.append("-").append(fvgmbd.getName());
}
if (!huc.equals(ALL)) {
sb.append("-").append(fvgmbd.getName());
}
trd.setTableCellData(0,
@ -421,29 +379,29 @@ public class FFMPDataGenerator {
|| (centeredAggregationKey != null)) {
if (!cBasin.getValues().isEmpty()) {
rate = ((FFMPVirtualGageBasin) cBasin)
.getValue(paintRefTime);
}
trd.setTableCellData(1, new FFMPTableCellData(FIELDS.RATE,
rate));
if (!cBasin.getValues().isEmpty()) {
rate = vgBasin.getValue(paintRefTime);
if (sliderTime > 0.00) {
qpe = cBasin.getAccumValue(monitor.getQpeWindow()
.getAfterTime(), monitor.getQpeWindow()
.getBeforeTime(), expirationTime, isRate);
FFMPTimeWindow window = monitor.getQpeWindow();
qpe = cBasin.getAccumValue(window.getAfterTime(),
window.getBeforeTime(), expirationTime,
isRate);
} else {
qpe = 0.0f;
}
}
trd.setTableCellData(1, new FFMPTableCellData(FIELDS.RATE,
rate));
trd.setTableCellData(2, new FFMPTableCellData(FIELDS.QPE,
qpe));
if ((qpfBasin != null)
&& (qpfBasin.get(parentBasinPfaf) != null)) {
qpf = qpfBasin.get(parentBasinPfaf).getAverageValue(
monitor.getQpfWindow().getAfterTime(),
monitor.getQpfWindow().getBeforeTime());
if (qpfBasin != null) {
FFMPBasin basin = qpfBasin.get(parentBasinPfaf);
if (basin != null) {
FFMPTimeWindow window = monitor.getQpfWindow();
qpf = basin.getAverageValue(window.getAfterTime(),
window.getBeforeTime());
}
}
trd.setTableCellData(3, new FFMPTableCellData(FIELDS.QPF,
qpf));
@ -451,113 +409,23 @@ public class FFMPDataGenerator {
// run over each guidance type
int i = 0;
for (String guidType : guidBasins.keySet()) {
List<Long> pfafList = new ArrayList<Long>();
List<Long> forcedPfafs = new ArrayList<Long>();
guidance = Float.NaN;
boolean forced = false;
Float diffValue = Float.NaN;
Float ratioValue = Float.NaN;
FFFGForceUtil forceUtil = forceUtils.get(guidType);
forceUtil.setSliderTime(sliderTime);
FFMPBasinData guidBasin = guidBasins.get(guidType);
if ((guidBasin != null)
&& ((FFMPGuidanceBasin) guidBasin
.get(parentBasinPfaf) != null)) {
FFMPGuidanceBasin ffmpGuidBasin = ((FFMPGuidanceBasin) guidBasin
.get(parentBasinPfaf));
// If aggregate, get basins within the aggregate
if (cBasin.getAggregated()) {
if (domain == null) {
pfafList = ft.getAggregatePfafs(
cBasin.getPfaf(), siteKey, huc);
} else if (!domain.equals(NA)) {
if (!huc.equals(ALL)) {
pfafList = ft
.getAggregatePfafsByDomain(
parentBasinPfaf,
siteKey, domain, huc);
}
} else {
pfafList = ft.getAggregatePfafsByDomain(
parentBasinPfaf, siteKey, domain,
huc);
pfafList.add(ft.getAggregatedPfaf(
cBasin.getPfaf(), siteKey, huc));
}
}
FFFGDataMgr fdm = FFFGDataMgr.getInstance();
if (fdm.isForcingConfigured()) {
FFMPBasin parentBasin = baseRec.getBasinData(
ALL).get(parentBasinPfaf);
forceUtil.calculateForcings(domain, ft,
parentBasin);
forcedPfafs = forceUtil.getForcedPfafList();
forced = forceUtil.isForced();
}
if ((!forcedPfafs.isEmpty()) && forced
&& centeredAggregationKey == null
&& !pfafList.isEmpty()) {
// Recalculate the guidance using the forced
// value(s)
guidance = guidRecords
.get(guidType)
.getBasinData(ALL)
.getAverageGuidanceValue(
pfafList,
resource.getGuidanceInterpolators()
.get(guidType),
guidance,
forcedPfafs,
resource.getGuidSourceExpiration(guidType));
} else if (!forcedPfafs.isEmpty()
&& centeredAggregationKey == null
&& !pfafList.isEmpty()) {
guidance = guidRecords
.get(guidType)
.getBasinData(ALL)
.getAverageGuidanceValue(
pfafList,
resource.getGuidanceInterpolators()
.get(guidType),
Float.NaN,
forcedPfafs,
resource.getGuidSourceExpiration(guidType));
forced = true;
} else if (!pfafList.isEmpty()
&& centeredAggregationKey == null) {
guidance = guidRecords
.get(guidType)
.getBasinData(ALL)
.getAverageGuidanceValue(
pfafList,
resource.getGuidanceInterpolators()
.get(guidType),
Float.NaN,
forcedPfafs,
resource.getGuidSourceExpiration(guidType));
} else {
guidance = resource.getGuidanceValue(
ffmpGuidBasin, paintRefTime, guidType);
if (guidance < 0.0f) {
guidance = Float.NaN;
}
}
trd.setTableCellData(i + 4, new FFMPTableCellData(
FIELDS.GUIDANCE, guidance, forced));
FFMPTableCellData guidCellData = getGuidanceCellData(
cBasin, domain, guidType, parentBasinPfaf);
if (guidCellData == null) {
guidCellData = new FFMPTableCellData(
FIELDS.GUIDANCE, Float.NaN);
} else {
trd.setTableCellData(i + 4, new FFMPTableCellData(
FIELDS.GUIDANCE, Float.NaN));
guidance = guidCellData.getValueAsFloat();
}
trd.setTableCellData(i + 4, guidCellData);
float ratioValue = Float.NaN;
float diffValue = Float.NaN;
// If guidance is NaN then it cannot be > 0
if (!qpe.isNaN() && (guidance > 0.0f)) {
ratioValue = FFMPUtils.getRatioValue(qpe, guidance);
@ -581,167 +449,73 @@ public class FFMPDataGenerator {
displayName = getDisplayName(cBasin);
if (displayName != null) {
String cbasinPfaf = cBasin.getPfaf().toString();
StringBuilder sb = new StringBuilder(cbasinPfaf);
long cBasinPfaf = cBasin.getPfaf();
String cBasinPfafStr = Long.toString(cBasinPfaf);
StringBuilder sb = new StringBuilder(cBasinPfafStr);
sb.append("\n").append(displayName);
trd.setPfaf(cbasinPfaf);
trd.setPfaf(cBasinPfafStr);
trd.setTableCellData(0, new FFMPTableCellData(rowField,
displayName, sb.toString()));
if (!isWorstCase || huc.equals(ALL)
|| (centeredAggregationKey != null)) {
if ((rateBasin != null)
&& (rateBasin.get(cBasin.getPfaf()) != null)) {
rate = rateBasin.get(cBasin.getPfaf()).getValue(
paintRefTime);
if (rateBasin != null) {
FFMPBasin basin = rateBasin.get(cBasinPfaf);
if (basin != null) {
rate = basin.getValue(paintRefTime);
}
}
trd.setTableCellData(1, new FFMPTableCellData(FIELDS.RATE,
rate));
if ((qpeBasin != null)
&& (qpeBasin.get(cBasin.getPfaf()) != null)) {
qpe = qpeBasin.get(cBasin.getPfaf()).getAccumValue(
monitor.getQpeWindow().getAfterTime(),
monitor.getQpeWindow().getBeforeTime(),
expirationTime, isRate);
if (qpeBasin != null) {
FFMPBasin basin = qpeBasin.get(cBasinPfaf);
if (basin != null) {
FFMPTimeWindow window = monitor.getQpeWindow();
qpe = basin.getAccumValue(window.getAfterTime(),
window.getBeforeTime(), expirationTime,
isRate);
}
}
trd.setTableCellData(2, new FFMPTableCellData(FIELDS.QPE,
qpe));
if ((qpfBasin != null)
&& (qpfBasin.get(cBasin.getPfaf()) != null)) {
qpf = qpfBasin.get(cBasin.getPfaf()).getAverageValue(
monitor.getQpfWindow().getAfterTime(),
monitor.getQpfWindow().getBeforeTime());
// qpf = getQPFValue(false, cBasin.getPfaf(),
// new ArrayList<Long>());/* DR13839 */
if (qpfBasin != null) {
FFMPBasin basin = qpfBasin.get(cBasinPfaf);
if (basin != null) {
FFMPTimeWindow window = monitor.getQpfWindow();
qpf = basin.getAverageValue(window.getAfterTime(),
window.getBeforeTime());
}
}
trd.setTableCellData(3, new FFMPTableCellData(FIELDS.QPF,
qpf));
// run over each guidance type
int i = 0;
Float ratioValue;
Float diffValue;
for (String guidType : guidBasins.keySet()) {
List<Long> pfafList = new ArrayList<Long>();
List<Long> forcedPfafs = new ArrayList<Long>();
guidance = Float.NaN;
boolean forced = false;
ratioValue = Float.NaN;
diffValue = Float.NaN;
FFFGForceUtil forceUtil = forceUtils.get(guidType);
forceUtil.setSliderTime(sliderTime);
FFMPBasinData guidBasin = guidBasins.get(guidType);
if ((guidBasin != null)
&& ((FFMPGuidanceBasin) guidBasin.get(cBasin
.getPfaf()) != null)) {
FFMPGuidanceBasin ffmpGuidBasin = ((FFMPGuidanceBasin) guidBasin
.get(cBasin.getPfaf()));
// If aggregate, get basins within the aggregate
if (cBasin.getAggregated()) {
if (domain == null) {
pfafList = ft.getAggregatePfafs(
cBasin.getPfaf(), siteKey, huc);
} else if (!domain.equals(NA)) {
if (!huc.equals(ALL)) {
pfafList = ft
.getAggregatePfafsByDomain(
cBasin.getPfaf(),
siteKey, domain, huc);
}
} else {
pfafList = ft.getAggregatePfafsByDomain(
cBasin.getPfaf(), siteKey, domain,
huc);
pfafList.add(ft.getAggregatedPfaf(
cBasin.getPfaf(), siteKey, huc));
}
}
FFFGDataMgr fdm = FFFGDataMgr.getInstance();
if (fdm.isForcingConfigured()) {
forceUtil.calculateForcings(domain, ft, cBasin);
forcedPfafs = forceUtil.getForcedPfafList();
forced = forceUtil.isForced();
}
if ((!forcedPfafs.isEmpty()) && forced
&& centeredAggregationKey == null
&& !pfafList.isEmpty()) {
// Recalculate the guidance using the forced
// value(s)
guidance = guidRecords
.get(guidType)
.getBasinData(ALL)
.getAverageGuidanceValue(
pfafList,
resource.getGuidanceInterpolators()
.get(guidType),
guidance,
forcedPfafs,
resource.getGuidSourceExpiration(guidType));
} else if (!forcedPfafs.isEmpty()
&& centeredAggregationKey == null
&& !pfafList.isEmpty()) {
guidance = guidRecords
.get(guidType)
.getBasinData(ALL)
.getAverageGuidanceValue(
pfafList,
resource.getGuidanceInterpolators()
.get(guidType),
Float.NaN,
forcedPfafs,
resource.getGuidSourceExpiration(guidType));
forced = true;
} else if (!pfafList.isEmpty()
&& centeredAggregationKey == null) {
guidance = guidRecords
.get(guidType)
.getBasinData(ALL)
.getAverageGuidanceValue(
pfafList,
resource.getGuidanceInterpolators()
.get(guidType),
Float.NaN,
forcedPfafs,
resource.getGuidSourceExpiration(guidType));
if (!forcedPfafs.isEmpty()) {
forced = true;
}
} else {
guidance = resource.getGuidanceValue(
ffmpGuidBasin, monitor.getQpeWindow()
.getBeforeTime(), guidType);
if (guidance < 0.0f) {
guidance = Float.NaN;
}
}
trd.setTableCellData(i + 4, new FFMPTableCellData(
FIELDS.GUIDANCE, guidance, forced));
} else {
FFMPTableCellData guidCellData = getGuidanceCellData(
cBasin, domain, guidType, cBasinPfaf);
if (guidCellData == null) {
// check for forcing even if no data are available
guidance = getForcedAvg(forceUtil, domain, cBasin,
guidType);
if (!guidance.isNaN()) {
forced = true;
} else {
forced = false;
}
trd.setTableCellData(i + 4, new FFMPTableCellData(
FIELDS.GUIDANCE, guidance, forced));
boolean forced = !guidance.isNaN();
guidCellData = new FFMPTableCellData(
FIELDS.GUIDANCE, guidance, forced);
} else {
guidance = guidCellData.getValueAsFloat();
}
trd.setTableCellData(i + 4, guidCellData);
float ratioValue = Float.NaN;
float diffValue = Float.NaN;
// If guidance is NaN then it cannot be > 0
if (!qpe.isNaN() && (guidance > 0.0f)) {
ratioValue = FFMPUtils.getRatioValue(qpe, guidance);
@ -763,6 +537,70 @@ public class FFMPDataGenerator {
}
}
private FFMPTableCellData getGuidanceCellData(FFMPBasin cBasin,
String domain, String guidType, Long parentBasinPfaf) {
long cBasinPfaf = cBasin.getPfaf();
FFMPBasinData guidBasin = guidBasins.get(guidType);
FFMPGuidanceBasin ffmpGuidBasin = null;
if (guidBasin != null) {
ffmpGuidBasin = (FFMPGuidanceBasin) guidBasin.get(cBasinPfaf);
}
if (ffmpGuidBasin == null) {
return null;
}
List<Long> pfafList = Collections.emptyList();
List<Long> forcedPfafs = Collections.emptyList();
boolean forced = false;
Float guidance = Float.NaN;
FFFGForceUtil forceUtil = forceUtils.get(guidType);
// If aggregate, get basins within the aggregate
if (cBasin.getAggregated()) {
if (domain == null) {
pfafList = ft.getAggregatePfafs(cBasinPfaf, siteKey, huc);
} else if (!domain.equals(NA)) {
if (!huc.equals(ALL)) {
pfafList = ft.getAggregatePfafsByDomain(parentBasinPfaf,
siteKey, domain, huc);
}
} else {
pfafList = ft.getAggregatePfafsByDomain(parentBasinPfaf,
siteKey, domain, huc);
pfafList.add(ft.getAggregatedPfaf(cBasinPfaf, siteKey, huc));
}
}
if (FFFGDataMgr.getInstance().isForcingConfigured()) {
FFMPBasin parentBasin = cBasin;
if (cBasinPfaf != parentBasinPfaf.longValue()) {
parentBasin = baseRec.getBasinData(ALL).get(parentBasinPfaf);
}
forceUtil.calculateForcings(domain, ft, parentBasin);
forcedPfafs = forceUtil.getForcedPfafList();
forced = forceUtil.isForced();
}
if (!forcedPfafs.isEmpty() || !pfafList.isEmpty() && centeredAggregationKey == null) {
FFMPBasinData basinData = guidRecords.get(guidType).getBasinData(
ALL);
guidance = basinData.getAverageGuidanceValue(pfafList, resource
.getGuidanceInterpolators().get(guidType), guidance,
forcedPfafs, resource.getGuidSourceExpiration(guidType));
forced = !forcedPfafs.isEmpty();
} else {
guidance = resource.getGuidanceValue(ffmpGuidBasin, paintRefTime,
guidType);
if (guidance < 0.0f) {
guidance = Float.NaN;
}
}
return new FFMPTableCellData(FIELDS.GUIDANCE, guidance, forced);
}
private float getForcedAvg(FFFGForceUtil forceUtil, String domain,
FFMPBasin cBasin, String guidType) {
FFFGDataMgr fdm = FFFGDataMgr.getInstance();
@ -1146,17 +984,19 @@ public class FFMPDataGenerator {
*/
private FIELDS getBaseField() {
String dataKey = resource.getDataKey();
ProductXML product = resource.getProduct();
Date tableTime = resource.getTableTime();
FIELDS field = null;
String localHuc = null;
dman = FFFGDataMgr.getInstance();
FfmpTableConfigData ffmpTableCfgData = FfmpTableConfig.getInstance()
.getTableConfigData(siteKey);
String qpfType = ffmpTableCfgData.getQpfType();
ProductRunXML productRun = FFMPRunConfigurationManager.getInstance()
.getProduct(siteKey);
String qpfSource = productRun.getQpfSources(product, qpfType).get(0)
.getSourceName();
SourceXML qpfSource = productRun.getQpfSources(product, qpfType).get(0);
FFMPConfig config = FFMPConfig.getInstance();
String includedCWAs = config.getFFMPConfigData().getIncludedCWAs();
@ -1167,41 +1007,33 @@ public class FFMPDataGenerator {
if (resource.isSplit()) {
// hack off the QPF duration for the table values of QPE (Split
// Window)
double duration = FFMPSourceConfigurationManager.getInstance()
.getSource(qpfSource).getDurationHour();
double duration = qpfSource.getDurationHour();
qpeTime = new Date(
(long) (qpeTime.getTime() - (duration * TimeUtil.MILLIS_PER_HOUR)));
}
monitor.setQpeWindow(new FFMPTimeWindow(tableTime, qpeTime));
if (isWorstCase || (centeredAggregationKey != null)) {
// make sure that "ALL" is loaded
localHuc = ALL;
rateRecord = monitor.getRateRecord(product, siteKey, dataKey,
product.getRate(), paintRefTime, localHuc, true);
qpeRecord = monitor.getQPERecord(product, siteKey, dataKey,
product.getQpe(), tableTime, localHuc, true);
qpfRecord = monitor.getQPFRecord(product, siteKey, dataKey, null,
paintRefTime, localHuc, true);
guidRecords = monitor.getGuidanceRecords(product, siteKey,
tableTime, localHuc, true);
} else {
localHuc = huc;
}
FFMPRecord rateRecord = monitor.getRateRecord(product, siteKey,
dataKey, product.getRate(), paintRefTime, localHuc, true);
FFMPRecord qpeRecord = monitor.getQPERecord(product, siteKey, dataKey,
product.getQpe(), tableTime, localHuc, true);
FFMPRecord qpfRecord = monitor.getQPFRecord(product, siteKey, dataKey,
null, paintRefTime, localHuc, true);
guidRecords = monitor.getGuidanceRecords(product, siteKey, tableTime,
localHuc, true);
FFMPRecord virtualRecord = null;
if (localHuc.equals(ALL)) {
virtualRecord = monitor.getVirtualRecord(product, siteKey, dataKey,
product.getVirtual(), tableTime, localHuc, true);
} else {
rateRecord = monitor.getRateRecord(product, siteKey, dataKey,
product.getRate(), paintRefTime, huc, true);
qpeRecord = monitor.getQPERecord(product, siteKey, dataKey,
product.getQpe(), tableTime, huc, true);
qpfRecord = monitor.getQPFRecord(product, siteKey, dataKey, null,
paintRefTime, huc, true);
guidRecords = monitor.getGuidanceRecords(product, siteKey,
tableTime, huc, true);
if (huc.equals(ALL)) {
virtualRecord = monitor.getVirtualRecord(product, siteKey,
dataKey, product.getVirtual(), tableTime, huc, true);
}
localHuc = huc;
}
try {

View file

@ -71,6 +71,7 @@ import com.raytheon.uf.viz.monitor.ffmp.ui.listeners.FFMPLoaderEvent;
* Mar 6, 2013 1769 dhladky Changed threading to use count down latch.
* Apr 9, 2013 1890 dhladky removed loading of phantom Virtual template and cache file processing.
* Apr 18, 2013 1912 bsteffen Increase bulk requests to pypies.
* Apr 26, 2013 1954 bsteffen Minor code cleanup throughout FFMP.
*
* </pre>
*
@ -96,7 +97,7 @@ public class FFMPDataLoader extends Thread {
private String dataKey = null;
private ArrayList<String> hucsToLoad = null;
private List<String> hucsToLoad = null;
private String wfo = null;
@ -109,8 +110,7 @@ public class FFMPDataLoader extends Thread {
private CountDownLatch latch;
public FFMPDataLoader(FFMPResourceData resourceData, Date timeBack,
Date mostRecentTime, LOADER_TYPE loadType,
ArrayList<String> hucsToLoad) {
Date mostRecentTime, LOADER_TYPE loadType, List<String> hucsToLoad) {
this.product = resourceData.getProduct();
this.siteKey = resourceData.siteKey;
@ -172,9 +172,8 @@ public class FFMPDataLoader extends Thread {
.getSourceConfig();
ProductRunXML productRun = runner.getProduct(siteKey);
ArrayList<SourceXML> qpfSources = new ArrayList<SourceXML>();
List<SourceXML> qpfSources = new ArrayList<SourceXML>();
String layer = config.getFFMPConfigData().getLayer();
boolean isProductLoad = true;
String rateURI = null;
if (loadType != LOADER_TYPE.GENERAL) {
@ -278,8 +277,8 @@ public class FFMPDataLoader extends Thread {
fireLoaderEvent(loadType, "Processing " + product.getRate(),
isDone());
for (String phuc : hucsToLoad) {
monitor.processUri(isProductLoad, rateURI, siteKey,
product.getRate(), timeBack, phuc);
monitor.processUri(rateURI, siteKey, product.getRate(),
timeBack, phuc);
}
fireLoaderEvent(loadType, product.getRate(), isDone());
}
@ -305,8 +304,8 @@ public class FFMPDataLoader extends Thread {
if (!qpeURIs.isEmpty()) {
for (String phuc : hucsToLoad) {
if (phuc.equals(layer) || phuc.equals(FFMPRecord.ALL)) {
monitor.processUris(qpeURIs, isProductLoad, siteKey,
product.getQpe(), timeBack, phuc);
monitor.processUris(qpeURIs, siteKey, product.getQpe(),
timeBack, phuc);
}
}
}
@ -338,8 +337,8 @@ public class FFMPDataLoader extends Thread {
if (!qpfURIs.isEmpty()) {
for (String phuc : hucsToLoad) {
if (phuc.equals(layer) || phuc.equals(FFMPRecord.ALL)) { // old
monitor.processUris(qpfURIs, isProductLoad,
siteKey, product.getQpf(i), timeBack, phuc);
monitor.processUris(qpfURIs, siteKey,
product.getQpf(i), timeBack, phuc);
}
}
}
@ -353,8 +352,8 @@ public class FFMPDataLoader extends Thread {
isDone());
// process virtual all for all only, never uses cache files
if (!virtualURIs.isEmpty()) {
monitor.processUris(virtualURIs, isProductLoad, siteKey,
product.getVirtual(), timeBack, FFMPRecord.ALL);
monitor.processUris(virtualURIs, siteKey, product.getVirtual(),
timeBack, FFMPRecord.ALL);
}
fireLoaderEvent(loadType, product.getVirtual(), isDone());
@ -373,7 +372,7 @@ public class FFMPDataLoader extends Thread {
"Processing " + guidSource.getSourceName(),
isDone());
monitor.processUris(iguidURIs, isProductLoad, siteKey,
monitor.processUris(iguidURIs, siteKey,
guidSource.getSourceName(), timeBack,
FFMPRecord.ALL);

View file

@ -32,7 +32,6 @@ import org.eclipse.swt.graphics.RGB;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPRecord.FIELDS;
import com.raytheon.uf.common.monitor.xml.DomainXML;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.viz.core.PixelExtent;
import com.raytheon.uf.viz.monitor.ffmp.ui.dialogs.FFMPTableData;
/**
@ -46,6 +45,8 @@ import com.raytheon.uf.viz.monitor.ffmp.ui.dialogs.FFMPTableData;
* ------------ ---------- ----------- --------------------------
* 04/23/10 4494 D. Hladky Initial release
* 02/01/13 1569 D. Hladky Added constants
* Apr 25, 2013 1954 bsteffen Skip extent checking for FFMP shape
* generation.
*
* </pre>
*
@ -79,15 +80,10 @@ public class FFMPDrawable {
private DataTime time = null;
private PixelExtent ext = null;
private double dtime = 0.0;
protected HashMap<Long, Float> worstCaseHash = new HashMap<Long, Float>();
private ConcurrentMap<String, Set<Long>> basins = new ConcurrentHashMap<String, Set<Long>>(
10, 0.75f, 5);
private String guidType = null;
public FFMPDrawable(Collection<DomainXML> domains) {
@ -95,7 +91,7 @@ public class FFMPDrawable {
}
public void setValidDomains(Collection<DomainXML> domains) {
Set<String> cwasToRemove = new HashSet<String>(basins.keySet());
Set<String> cwasToRemove = new HashSet<String>(colorMaps.keySet());
for (DomainXML domain : domains) {
cwasToRemove.remove(domain.getCwa());
}
@ -124,7 +120,7 @@ public class FFMPDrawable {
* Disposes of currently drawn shapes.
*/
public void disposeImage() {
for (String cwa : basins.keySet()) {
for (String cwa : colorMaps.keySet()) {
disposeCwa(cwa);
}
}
@ -135,8 +131,6 @@ public class FFMPDrawable {
colorMap.clear();
colorMap = null;
}
basins.remove(cwa);
// tableData.clear();
worstCaseHash.clear();
}
@ -225,22 +219,6 @@ public class FFMPDrawable {
this.isWorstCase = isWorstCase;
}
public PixelExtent getExt() {
return ext;
}
public void setExt(PixelExtent ext) {
this.ext = ext;
}
public Set<Long> getBasins(String cwa) {
return basins.get(cwa);
}
public void setBasins(String cwa, Set<Long> basins) {
this.basins.put(cwa, basins);
}
public void setTableData(String thuc, FFMPTableData tData) {
tableData.put(thuc, tData);
}

View file

@ -20,7 +20,6 @@
package com.raytheon.uf.viz.monitor.ffmp.ui.rsc;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.NavigableMap;
@ -35,11 +34,7 @@ import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPRecord;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPRecord.FIELDS;
import com.raytheon.uf.common.dataplugin.ffmp.FFMPTemplates;
import com.raytheon.uf.common.localization.IPathManager;
import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
import com.raytheon.uf.common.localization.PathManagerFactory;
import com.raytheon.uf.common.monitor.config.FFMPRunConfigurationManager;
import com.raytheon.uf.common.monitor.config.FFMPSourceConfigurationManager.SOURCE_TYPE;
import com.raytheon.uf.common.monitor.xml.DomainXML;
@ -54,6 +49,7 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.localization.LocalizationManager;
import com.raytheon.uf.viz.core.rsc.AbstractNameGenerator;
import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData;
import com.raytheon.uf.viz.core.rsc.AbstractVizResource;
@ -78,6 +74,7 @@ import com.raytheon.uf.viz.monitor.ffmp.xml.FFMPConfigBasinXML;
* Feb 10, 2013 1584 mpduff Add performance logging.
* Feb 28, 2013 1729 dhladky Got rid of thread sleeps
* Mar 6, 2013 1769 dhladky Changed threading to use count down latch.
* Apr 26, 2013 1954 bsteffen Minor code cleanup throughout FFMP.
*
* </pre>
*
@ -134,7 +131,7 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
protected FFMPMonitor monitor = null;
/** County Warning Area (Domain) for which to display **/
protected ArrayList<DomainXML> domains = null;
protected List<DomainXML> domains = null;
/** Product Displayed **/
private ProductXML product = null;
@ -177,10 +174,7 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
protected AbstractVizResource<?, ?> constructResource(
LoadProperties loadProperties, PluginDataObject[] objects)
throws VizException {
IPathManager pm = PathManagerFactory.getPathManager();
LocalizationContext context = pm.getContext(
LocalizationType.COMMON_STATIC, LocalizationLevel.SITE);
this.wfo = context.getContextName();
this.wfo = LocalizationManager.getContextName(LocalizationLevel.SITE);
FFMPMonitor monitor = getMonitor();
monitor.setWfo(wfo);
this.field = monitor.getField(sourceName);
@ -192,8 +186,8 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
DataTime[] availableTimes = this.getAvailableTimes();
// no data available;
if (availableTimes.length != 0) {
if (getMonitor().getProductXML(sourceName) != null) {
setProduct(getMonitor().getProductXML(sourceName));
product = monitor.getProductXML(sourceName);
if (product != null) {
monitor.launchSplash(siteKey);
FFMPTemplates templates = monitor.getTemplates(siteKey);
@ -227,11 +221,12 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
FFMPConfig ffmpConfig = monitor.getConfig();
FFMPConfigBasinXML cfgBasinXML = ffmpConfig.getFFMPConfigData();
String[] sdomains = cfgBasinXML.getIncludedCWAs().split(",");
ArrayList<DomainXML> defaults = new ArrayList<DomainXML>();
List<DomainXML> defaults = new ArrayList<DomainXML>(
sdomains.length);
for (String domain : sdomains) {
if (domain.length() == 0) {
if (domain.isEmpty()) {
defaults.add(monitor.getRunConfig().getDomain(wfo));
break;
}
@ -247,26 +242,18 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
this.domains = defaults;
DataTime mostRecentTime = availableTimes[availableTimes.length - 1];
Date mostRecentTime = availableTimes[availableTimes.length - 1]
.getRefTime();
this.timeBack = new Date(
(long) (mostRecentTime.getRefTime().getTime() - (cfgBasinXML
(long) (mostRecentTime.getTime() - (cfgBasinXML
.getTimeFrame() * TimeUtil.MILLIS_PER_HOUR)));
ArrayList<String> hucsToLoad = monitor.getTemplates(siteKey)
List<String> hucsToLoad = monitor.getTemplates(siteKey)
.getTemplateMgr().getHucLevels();
// goes back X hours and pre populates the Data Hashes
FFMPDataLoader loader = new FFMPDataLoader(this, timeBack,
mostRecentTime.getRefTime(), LOADER_TYPE.INITIAL,
mostRecentTime, LOADER_TYPE.INITIAL,
hucsToLoad);
loader.start();
// make the table load wait for finish of initial data load
try {
loader.waitFor();
} catch (InterruptedException e) {
statusHandler.handle(Priority.INFO,
"Data Loader thread interrupted, dying!", e);
}
loader.run();
} else {
/*
* This appears completely un-orthodox for anything in D2D. But
@ -305,7 +292,7 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
NavigableMap<Date, List<String>> sourceURIs = getMonitor()
.getAvailableUris(siteKey, dataKey, sourceName,
standAloneTime);
getMonitor().processUris(sourceURIs, false, siteKey,
monitor.processUris(sourceURIs, siteKey,
sourceName, standAloneTime, FFMPRecord.ALL);
}
}
@ -405,50 +392,14 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
*
* @param record
*/
public void populateRecord(ProductXML product, FFMPRecord precord,
String phuc) throws VizException {
public void populateRecord(FFMPRecord precord)
throws VizException {
try {
boolean isProductLoad = false;
if (product != null) {
isProductLoad = true;
}
getMonitor().populateFFMPRecord(isProductLoad, siteKey, precord,
precord.getSourceName(), phuc);
getMonitor().populateFFMPRecord(siteKey, precord,
precord.getSourceName(), huc);
} catch (Exception e) {
throw new VizException("Failed to populate ffmp record "
+ precord.getDataURI() + " for huc " + phuc);
}
}
/**
* Sort by Date
*
* @author dhladky
*
*/
public class SortByDate implements Comparator<FFMPRecord> {
@Override
public int compare(FFMPRecord o1, FFMPRecord o2) {
return o1.getDataTime().getRefTime()
.compareTo(o2.getDataTime().getRefTime());
}
}
/**
* Sort by DataTime
*
* @author dhladky
*
*/
public class SortByDataTime implements Comparator<DataTime> {
@Override
public int compare(DataTime o1, DataTime o2) {
return o1.compareTo(o2);
+ precord.getDataURI() + " for huc " + huc);
}
}
@ -488,7 +439,7 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
this.domains = domains;
}
public ArrayList<DomainXML> getDomains() {
public List<DomainXML> getDomains() {
return domains;
}
@ -548,7 +499,7 @@ public class FFMPResourceData extends AbstractRequestableResourceData {
* @param pfield
* @return
*/
public ArrayList<String> getSourceName(FIELDS pfield) {
public List<String> getSourceName(FIELDS pfield) {
ArrayList<String> sourceNames = null;
ProductXML product = getProduct();
ProductRunXML productRun = FFMPRunConfigurationManager.getInstance()

View file

@ -111,6 +111,7 @@ import com.vividsolutions.jts.io.WKBReader;
* Jan 29, 2009 dhladky Initial creation
* Apr 18, 2013 1926 njensen Changed inner data maps to have Long key
* to avoid !TimeStamp.equals(Date) issue
* Apr 26, 2013 1926 njensen Optimized getAvailableUris()
* </pre>
*
* @author dhladky
@ -445,34 +446,6 @@ public class ScanMonitor extends ResourceMonitor implements IScanDialogListener
return scanRec;
}
/**
* Get list of records
*
* @param type
* @param interval
* @return
*/
public ScanRecord[] getScanRecords(ScanTables type, String icao)
throws VizException {
List<ScanRecord> recordList = new ArrayList<ScanRecord>();
String[] uriList = getAvailableUris(type, icao);
for (String uri : uriList) {
Map<String, Object> vals = new HashMap<String, Object>();
vals.put("pluginName", "scan");
vals.put("dataURI", uri);
ScanRecord scanRec = (ScanRecord) Loader.loadData(vals);
File loc = HDF5Util.findHDF5Location(scanRec);
IDataStore dataStore = DataStoreFactory.getDataStore(loc);
if (scanRec != null) {
scanRec.retrieveMapFromDataStore(dataStore);
recordList.add(scanRec);
}
}
return recordList.toArray(new ScanRecord[recordList.size()]);
}
/**
* Return the tilt angle at which the table is currently at
*
@ -1277,41 +1250,40 @@ public class ScanMonitor extends ResourceMonitor implements IScanDialogListener
return uri;
}
public String[] getAvailableUris(ScanTables type, String icao) {
List<String> uriList = new ArrayList<String>();
SimpleDateFormat datef = new SimpleDateFormat(datePattern);
datef.setTimeZone(TimeZone.getTimeZone("Zulu"));
String addedSQL = "";
public List<String> getAvailableUris(ScanTables type, String icao) {
List<String> uriList = null;
String sql = null;
if (type == ScanTables.DMD) {
addedSQL = "' and lastelevationangle = 't'";
sql = "(select datauri from scan where type = '"
+ type.name()
+ "' and icao = '"
+ icao
+ "' and lastelevationangle ='t')"
+ " union (select datauri from scan where type = '"
+ type.name()
+ "' and icao = '"
+ icao
+ "' and lastelevationangle = 'f' order by reftime desc, tilt desc limit 1)";
} else {
addedSQL = "'";
sql = "(select datauri from scan where type = '" + type.name()
+ "' and icao = '" + icao + "')";
}
String sql = "(select datauri from scan where type = '"
+ type.name()
+ "' and icao = '"
+ icao
+ addedSQL
+ " order by reftime desc) "
+ "union (select datauri from scan where type = '"
+ type.name()
+ "' and icao = '"
+ icao
+ "' and lastelevationangle = 'f' order by reftime desc, tilt desc limit 1)";
try {
List<Object[]> results = DirectDbQuery.executeQuery(sql,
"metadata", QueryLanguage.SQL);
uriList = new ArrayList<String>(results.size());
if (results.size() > 0) {
for (Object[] ob : results) {
uriList.add((String) ob[0]);
}
}
} catch (VizException e) {
e.printStackTrace();
statusHandler.error("Error retrieving scan uris", e);
}
return uriList.toArray(new String[uriList.size()]);
return uriList;
}
/**

View file

@ -26,6 +26,7 @@ import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import com.raytheon.uf.common.monitor.scan.config.SCANConfig;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
import com.raytheon.uf.viz.core.VizApp;
@ -76,6 +77,8 @@ public class ScanStarterJob extends Job {
scan.setup(icao);
}
SCANConfig.getInstance();
VizApp.runAsync(new Runnable() {
@Override

View file

@ -238,7 +238,6 @@ public class ScanDrawer {
circle.radius = size * (SIN_HEX_ANGLE);
circle.lineWidth = outlineWidth;
circle.basics.color = color;
aTarget.drawCircle(circle);
if (isNew(ctdr)) {
DrawableCircle innerCircle = new DrawableCircle();
@ -247,7 +246,9 @@ public class ScanDrawer {
innerCircle.radius = size / 2 * (SIN_HEX_ANGLE);
innerCircle.lineWidth = outlineWidth;
innerCircle.basics.color = color;
aTarget.drawCircle(innerCircle);
aTarget.drawCircle(circle, innerCircle);
} else {
aTarget.drawCircle(circle);
}
}
}
@ -831,7 +832,7 @@ public class ScanDrawer {
double dir, double length) {
double[] earAngles = new double[] { 10, -10 };
List<double[]> coords = new ArrayList<double[]>();
List<double[]> coords = new ArrayList<double[]>(earAngles.length);
for (double earAngle : earAngles) {
@ -969,15 +970,13 @@ public class ScanDrawer {
if (sdc.getPastTracks()) {
if (ctdr.getPastCoordinates() != null) {
for (Date date : ctdr.getPastCoordinates().keySet()) {
dates.add(date);
}
Collections.sort(dates);
count = dates.size();
double[] point = null;
double[] point = null;
for (int i = dates.size() - 1; i >= 0; i--) {
Coordinate coor = ctdr.getPastCoordinates().get(
dates.get(i));
@ -1014,45 +1013,34 @@ public class ScanDrawer {
}
}
// Draw data
// draw the past points
if (pastPoints.size() > 0) {
double cirRadius = 2.0 / screenToWorldRatio;
DrawableCircle[] pastCircles = new DrawableCircle[pastPoints.size()];
for (int i = 0; i < pastPoints.size(); i++) {
DrawableCircle pc = new DrawableCircle();
double[] point = pastPoints.get(i);
pc.setCoordinates(point[0], point[1], 0);
pc.basics.color = getResourceColor();
pc.radius = cirRadius;
pc.filled = true;
pastCircles[i] = pc;
}
aTarget.drawCircle(pastCircles);
aTarget.drawPoints(pastPoints, getResourceColor(), PointStyle.DISC,
0.7f);
}
if (pastPoints.size() > 1) {
DrawableLine line = new DrawableLine();
line.points = pastPoints;
line.width = outlineWidth;
line.basics.color = getResourceColor();
aTarget.drawLine(line);
}
if (pastPoints.size() > 0) {
double[] oldPoint = pastPoints.get(0);
aTarget.drawLine(oldPoint[0], oldPoint[1], 0.0, center[0],
center[1], 0.0, getResourceColor(), outlineWidth);
}
drawX(center);
// draw the X
aTarget.drawPoint(center[0], center[1], 0.0, getResourceColor(),
PointStyle.X, 1.3f);
// draw the future points
if (futurePoints.size() > 0) {
aTarget.drawPoints(futurePoints, getResourceColor(),
PointStyle.CROSS, 1.3f);
}
if (futurePoints.size() > 1) {
DrawableLine line = new DrawableLine();
line.points = futurePoints;
// draw the track line
DrawableLine line = new DrawableLine();
for (int i = pastPoints.size() - 1; i > -1; i--) {
double[] pt = pastPoints.get(i);
line.addPoint(pt[0], pt[1]);
}
line.addPoint(center[0], center[1]);
for (double[] pt : futurePoints) {
line.addPoint(pt[0], pt[1]);
}
if (line.points.size() > 1) {
line.width = outlineWidth;
line.basics.color = getResourceColor();
aTarget.drawLine(line);

View file

@ -21,7 +21,6 @@ package com.raytheon.uf.viz.monitor.scan.resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
@ -177,16 +176,12 @@ public class ScanResource extends
PluginDataObject[] pdos = (PluginDataObject[]) object;
ScanRecord scan = null;
List<String> uris = Arrays.asList(getScan().getAvailableUris(
getTable(), resourceData.icao));
for (PluginDataObject pdo : pdos) {
try {
scan = (ScanRecord) pdo;
if (uris.contains(scan.getDataURI())) {
if (scan.getType().equals(getTable().name())) {
addRecord(scan);
}
}
if (scan.getIcao().equals(resourceData.icao)
&& scan.getType().equals(getTable().name()))
addRecord(scan);
} catch (Exception e) {
statusHandler.handle(Priority.PROBLEM,
"Error updating SCAN resource", e);

View file

@ -21,7 +21,6 @@ package com.raytheon.uf.viz.monitor.scan.resource;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
@ -97,8 +96,8 @@ public class ScanResourceData extends AbstractRequestableResourceData {
protected AbstractVizResource<?, ?> constructResource(
LoadProperties loadProperties, PluginDataObject[] objects)
throws VizException {
List<String> uris = Arrays.asList(getScan().getAvailableUris(
ScanTables.valueOf(tableType), icao));
List<String> uris = getScan().getAvailableUris(
ScanTables.valueOf(tableType), icao);
try {
long t0 = System.currentTimeMillis();
// Forces ScanMonitor to grab data back for one extra hour 1/2 past

View file

@ -50,6 +50,7 @@ import org.eclipse.swt.widgets.Shell;
import com.raytheon.uf.common.localization.LocalizationFile;
import com.raytheon.uf.common.monitor.scan.config.SCANConfig;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.viz.core.alerts.AlertMessage;
import com.raytheon.uf.viz.monitor.IMonitor;
import com.raytheon.uf.viz.monitor.Monitor;
@ -74,6 +75,7 @@ import com.raytheon.uf.viz.monitor.scan.commondialogs.LoadSaveConfigDlg.DialogTy
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Nov 21, 2009 #3039 lvenable Initial creation
* Apr 26, 2013 #1945 lvenable Some code cleanup.
*
* </pre>
*
@ -179,14 +181,10 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
initData();
// fileButtonTipText = "Current Config:\n" +
// scanCfg.getCurrentConfigFileName(scanTable);
setShellText();
setTableType();
initComponents();
shellCloseAction();
shellDisposeAction();
shell.pack();
@ -260,7 +258,6 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
}
// Loop and close all of the open dialogs;
Set<ICommonDialogAction> keys = dialogsMap.keySet();
for (ICommonDialogAction icda : keys) {
@ -476,6 +473,29 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
fileBtn.setToolTipText(fileButtonTipText);
}
/**
* Get the scan time. If link to frame is turned on then get that time with
* the displayed frame otherwise get the latest time.
*
* @param scanMonitor
* The scan monitor.
* @return The scan time.
*/
protected Date getScanTime(ScanMonitor scanMonitor) {
Date time = null;
if (getLinkToFrame(scanTable.name())) {
time = scanMonitor.getScanTime(scanTable, site);
} else {
DataTime dt = scanMonitor.getMostRecent(scanMonitor,
scanTable.name(), site);
if (dt != null) {
time = dt.getRefTime();
}
}
return time;
}
@Override
public void addMonitorControlListener(IMonitor monitor) {
getMonitorControlListeners().add(monitor);
@ -491,6 +511,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
public void fireConfigUpdate(IMonitorConfigurationEvent imce) {
final IMonitorConfigurationEvent fimce = imce;
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -504,6 +525,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
@Override
public void fireKillMonitor() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -518,6 +540,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
public void fireThresholdUpdate(IMonitorThresholdEvent imte) {
final IMonitorThresholdEvent fimte = imte;
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -534,8 +557,8 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
* @param ident
* @param type
*/
public TrendGraphData getTrendGraphData(ScanTables type,
String field, String ident) {
public TrendGraphData getTrendGraphData(ScanTables type, String field,
String ident) {
TrendGraphData tgd = null;
Iterator<IMonitor> iter = getMonitorControlListeners().iterator();
while (iter.hasNext()) {
@ -572,6 +595,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
final ScanTables ftype = type;
final String ficao = icao;
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -590,6 +614,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
*/
public void fireScanPaint() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -612,10 +637,8 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
}
// TODO: What needs to be done here is to grab the current selected
// trend set
// and fire a trend set for the passed in ID and table
// trend set and fire a trend set for the passed in ID and table
// this will mean firing a get graphData Event back to the monitor
System.out.println("Trend Set requested: " + type + " : " + ident);
}
@Override
@ -635,6 +658,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
@Override
public void fireDialogShutdown(IMonitorListener iml) {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -646,8 +670,8 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
}
@Override
public TrendGraphData requestTrendGraphData(ScanTables type,
String field, String ident) {
public TrendGraphData requestTrendGraphData(ScanTables type, String field,
String ident) {
return getTrendGraphData(type, field, ident);
}
@ -683,6 +707,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
* used to notify updates of data to display elements from classes that
* implement the IMonitor interface.
*/
@Override
public void fireMonitorEvent() {
return;
}
@ -694,6 +719,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
* listener class as an argument that can be used for targeted
* notifications.
*/
@Override
public void fireMonitorEvent(String type) {
return;
}
@ -703,6 +729,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
* used to notify updates of data to display elements from classes that
* implement the IMonitor interface.
*/
@Override
public void fireMonitorEvent(Monitor monitor) {
return;
}
@ -712,6 +739,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
*
* @param pluginName
*/
@Override
public void initObserver(String pluginName, Monitor monitor) {
return;
}
@ -722,6 +750,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
* @param type
* @return
*/
@Override
public ArrayList<Date> getTimeOrderedKeys(IMonitor monitor, String type) {
return monitor.getTimeOrderedKeys(monitor, type);
}
@ -742,6 +771,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
/*
* Abstract methods to be implemented by classes extending this class.
*/
@Override
public abstract void notify(IMonitorEvent me);
public abstract void displayTrendSetGraphs(String ident);
@ -750,12 +780,8 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
protected abstract void initComponents();
// protected abstract void update();
protected abstract void setShellText();
protected abstract void shellCloseAction();
protected abstract void shellDisposeAction();
protected abstract void updateAfterConfigLoad();
@ -766,7 +792,7 @@ public abstract class AbstractTableDlg extends Dialog implements IMonitor,
public abstract void updateThresh(String attr);
public abstract void turnOffAlarm();
public abstract void turnOffAlarm();
public abstract void turnOnAlarm();
public abstract void turnOnAlarm();
}

View file

@ -44,6 +44,7 @@ import com.raytheon.uf.viz.monitor.scan.commondialogs.IRequestTrendGraphData;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 3, 2009 #3039 lvenable Initial creation
* Apr 29, 2013 #1945 lvenable Code cleanup for SCAN performance.
*
* </pre>
*
@ -59,13 +60,28 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
private static final String UNWARNED_SVR_TOOLTIP = "\nA storm meeting Severe "
+ "Weather warning\ncriteria is outside any SVR warning polygon.";
// private Point mouseMovePt = new Point(0, 0);
//
// private Point mouseDownPt = new Point(0, 0);
//
// private Point prevMousePt = new Point(-9999, -9999);
/** Radius interpolation column name. */
private String radVarColName = "";
public SCANCellTableComp(Composite parent, SCANTableData tableData, ITableAction tableActionCB,
/** Clutter control column name. */
private String clutterCoName = "";
/**
* Constructor.
*
* @param parent
* Parent composite.
* @param tableData
* Table data.
* @param tableActionCB
* Table action callback
* @param requestDataCallback
* Request data callback
* @param site
* The site.
*/
public SCANCellTableComp(Composite parent, SCANTableData tableData,
ITableAction tableActionCB,
IRequestTrendGraphData requestDataCallback, String site) {
super(parent, tableData, tableActionCB, requestDataCallback, site);
@ -105,22 +121,24 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
if (colIndex == 0) {
tableIndex = rowIndex;
if ((tableIndex >= 0) || (tableIndex > table.getItemCount())) {
tableActionCB.centerByStormId(table.getItem(tableIndex).getText());
tableActionCB.centerByStormId(table.getItem(tableIndex)
.getText());
redrawTable();
}
} else {
String name = (String) table.getColumn(colIndex).getData();
if (scanCfg.canViewTrend(scanTable, name) == true) {
String ident = tableData.getTableRows().get(rowIndex).getTableCellData(0).getCellText();
String ident = tableData.getTableRows().get(rowIndex)
.getTableCellData(0).getCellText();
System.out.println("Display trend graph dialog for " + ident);
displayTrendGraphDialog(ident, name);
}
}
} else if (event.button == 3) {
if (colIndex == 0) {
String ident = tableData.getTableRows().get(rowIndex).getTableCellData(0).getCellText();
String ident = tableData.getTableRows().get(rowIndex)
.getTableCellData(0).getCellText();
displayTrendSetsGraphDialog(ident);
}
}
@ -141,10 +159,10 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
}
Rectangle rect;
// rect = item.getBounds(table.getColumnCount() - 1);
rect = item.getBounds(scanCfg.getCountyColumnIndex(scanTable));
if (scanCfg.showTips(scanTable) == false && rect.contains(mouseMovePt) == false) {
if (scanCfg.showTips(scanTable) == false
&& rect.contains(mouseMovePt) == false) {
prevMousePt.x = -9999;
prevMousePt.y = -9999;
table.setToolTipText(null);
@ -162,17 +180,22 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
prevMousePt.x = mouseMovePt.x;
prevMousePt.y = mouseMovePt.y;
String toolTip = toolTipMgr.getTableCellTip(scanTable, (String) table.getColumn(i).getData());
String toolTip = toolTipMgr.getTableCellTip(scanTable,
(String) table.getColumn(i).getData());
if (i == 0) {
WARN_TYPE wt = tableData.getTableRows().get(table.indexOf(item)).getTableCellData(0).getWarnType();
WARN_TYPE wt = tableData.getTableRows()
.get(table.indexOf(item)).getTableCellData(0)
.getWarnType();
if (wt == WARN_TYPE.SEVERE) {
toolTip = toolTip.concat(UNWARNED_SVR_TOOLTIP);
} else if (wt == WARN_TYPE.TVS) {
toolTip = toolTip.concat(UNWARNED_TOR_TOOLTIP);
}
} else if (((String) table.getColumn(i).getData()).equals(CELLTable.COUNTY.getColName())) {
toolTip = tableData.getTableRows().get(table.indexOf(item)).getTableCellData(i).getCellText();
} else if (((String) table.getColumn(i).getData())
.equals(CELLTable.COUNTY.getColName())) {
toolTip = tableData.getTableRows().get(table.indexOf(item))
.getTableCellData(i).getCellText();
}
table.setToolTipText(toolTip);
@ -191,6 +214,17 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
*/
@Override
protected void setColumnImages() {
/*
* If the Radius Interpolation, Clutter Control, or sort column hasn't
* changed then return because the images will not change.
*/
if (scanCfg.isRadVar(scanTable, radVarColName)
&& scanCfg.isClutterControl(scanTable, clutterCoName)
&& lastSortColIndex == sortedColumnIndex) {
return;
}
TableColumn[] tCols = table.getColumns();
for (int i = 0; i < tCols.length; i++) {
@ -215,13 +249,16 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
*/
if (scanCfg.isRadVar(scanTable, colName) == true) {
radVarColName = colName;
gc.setBackground(scanCfg.getScanColor(ScanColors.RadVar));
}
// Set the foreground color to the clutter control color if the
// column is a clutter control.
if (scanCfg.isClutterControl(scanTable, colName) == true) {
gc.setForeground(scanCfg.getScanColor(ScanColors.ClutterControl));
clutterCoName = colName;
gc.setForeground(scanCfg
.getScanColor(ScanColors.ClutterControl));
}
// Set the background color to the sort color if that column is
@ -237,12 +274,12 @@ public class SCANCellTableComp extends SCANTableTrendGraphLayer {
gc.setBackground(scanCfg.getScanColor(ScanColors.Sort));
}
lastSortColIndex = sortedColumnIndex;
gc.fillRectangle(0, 0, imageWidth, imageHeight);
int colNameExt = gc.stringExtent(colName).x;
// int xCoord = (imageWidth / 2) - (colName.length() * textWidth /
// 2);
int xCoord = (imageWidth / 2) - (colNameExt / 2);
gc.drawText(colName, xCoord, 3, true);

View file

@ -54,6 +54,7 @@ import com.raytheon.uf.common.monitor.scan.config.SCANConfig;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.MESOTable;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanColors;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.viz.monitor.IMonitor;
import com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent;
import com.raytheon.uf.viz.monitor.events.IMonitorEvent;
@ -87,6 +88,8 @@ import com.raytheon.viz.ui.EditorUtil;
* Nov 21, 2009 #3039 lvenable Initial creation
*
* 03/15/2012 13939 Mike Duff For a SCAN Alarms issue
* Apr 26, 2013 #1945 lvenable Improved SCAN performance, reworked
* some bad code, and some code cleanup.
*
* </pre>
*
@ -99,7 +102,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
private boolean killDialog = false;
/*
* Action button at the top of the dialog.
* Action buttons at the top of the dialog.
*/
private Button configBtn;
@ -180,6 +183,10 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
private SCANAlarmsDlg alarmDlg = null;
/** Date format for the time label. */
private SimpleDateFormat dateFmt = new SimpleDateFormat(
"E MMM dd HH:mm yyyy");
/**
* Constructor.
*
@ -209,6 +216,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
*/
@Override
protected void initComponents() {
dateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
createTopControls();
createCellTable();
createFilePopupMenu();
@ -231,7 +239,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
}
/**
*
* Add an alarm timer.
*/
private void addAlarmTimer() {
if (scanTableComp.timer != null) {
@ -239,6 +247,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
@Override
public void run() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (shell.isDisposed()) {
scanTableComp.timer.cancel();
@ -437,11 +446,16 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
vertChk.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
vertChk.setSelection(cellCfgMgr.getScanCellCfgXML().getFilterOption());
vertChk.setLayoutData(gd);
vertChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
/*
* The vertical table is a techblocked DR. This selection listener will
* be commented out until it is needed.
*/
// vertChk.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// }
// });
setupButtonMouseListeners(vertChk);
gd = new GridData();
@ -475,7 +489,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
alarmDlg.open();
if (!alarmBtn.isDisposed()
&& (mgr.getAlertedAlarmCount(site, scanTable) == 0)) {
turnOffAlarm();
turnOffAlarm();
}
}
});
@ -489,52 +503,19 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
@Override
public void turnOffAlarm() {
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(false);
}
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(false);
}
mgr.setRing(false);
}
}
@Override
public void turnOnAlarm() {
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(true);
}
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(true);
}
mgr.setRing(true);
}
// private void resetButtonForegroundColor(Button btn)
// {
// btn.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
// }
// private void setupButtonMouseListeners(final Button btn)
// {
// btn.addMouseMoveListener(new MouseMoveListener()
// {
// @Override
// public void mouseMove(MouseEvent e)
// {
// btn.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
// }
//
// });
//
// btn.addMouseTrackListener(new MouseTrackAdapter()
// {
// @Override
// public void mouseExit(MouseEvent e)
// {
// btn.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
// }
//
// @Override
// public void mouseEnter(MouseEvent e)
// {
// btn.setForeground(display.getSystemColor(SWT.COLOR_BLACK));
// }
// });
// }
}
/**
* Create the CELL table.
@ -605,19 +586,6 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
}
});
// new MenuItem(filePopupMenu, SWT.SEPARATOR);
//
// MenuItem exitMI = new MenuItem(filePopupMenu, SWT.NONE);
// exitMI.setText("Exit");
// exitMI.addSelectionListener(new SelectionAdapter()
// {
// @Override
// public void widgetSelected(SelectionEvent e)
// {
// shellDisposeDialog();
// }
// });
fileBtn.setMenu(filePopupMenu);
}
@ -903,6 +871,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
*/
private void displayMesoTableDialog() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -921,6 +890,7 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
*/
private void displayTvsTableDialog() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
Iterator<IMonitor> iter = getMonitorControlListeners()
.iterator();
@ -943,8 +913,6 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
return;
}
SimpleDateFormat dateFmt = new SimpleDateFormat("E MMM dd HH:mm yyyy");
dateFmt.setTimeZone(TimeZone.getTimeZone("GMT"));
timeLbl.setText(dateFmt.format(currentTime));
}
@ -1012,144 +980,6 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
mb.open();
}
// /**
// * Retrieve the default configuration.
// */
// private void retrieveDefaultConfig()
// {
// /*
// * TODO : when loading the default config, the controls on the dialog
// * needs to be updated and a new table data should be loaded
// */
// scanCfg.loadDefaultConfigFileName(scanTable);
//
// updateAfterConfigLoad();
// }
//
// /**
// * Retrieve an existing configuration.
// */
// private void retrieveExistingConfig()
// {
// /*
// * TODO : when loading an existing config, the controls on the dialog
// * needs to be updated and a new table data should be loaded
// */
//
// if (closedOpenDialogs() == false)
// {
// return;
// }
//
// LoadSaveConfigDlg loadDlg = new LoadSaveConfigDlg(shell, DialogType.OPEN,
// scanTable);
// LocalizationFile fileName = loadDlg.open();
//
// if (fileName == null)
// {
// System.out.println("FileName is null...");
// return;
// }
//
// scanCfg.loadNewConfigFileName(scanTable, fileName.getFile().getName());
//
// System.out.println(fileName.getFile().getAbsolutePath());
//
// updateAfterConfigLoad();
//
// }
//
// /**
// * Save the current configuration.
// */
// private void saveCurrentConfiguration()
// {
// /*
// * TODO : save the current configuration...
// *
// * do not need to update the display...
// *
// * call to configuration manager to save the config...
// */
//
// /*
// * check if the user is trying to save the default config
// */
//
// if (scanCfg.currentConfigIsDefault(scanTable) == true)
// {
// MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK |
// SWT.CANCEL);
// mb.setText("Overwrite");
// mb.setMessage("Saving will overwrite the default configuration.\n" +
// "Do you wish to continue?");
// int result = mb.open();
//
// // If the user selected Cancel then return.
// if (result == SWT.CANCEL)
// {
// return;
// }
// }
//
// scanCfg.saveCurrentConfigurationFile(scanTable);
// }
//
// /**
// * Save the current configuration as a different name.
// */
// private void saveConfigurationAs()
// {
// /*
// * TODO : launch the save dialog and then get a name to save the
// configuration.
// *
// * do not need to update the display...
// */
// String defCfgName = scanCfg.getDefaultConfigName(scanTable);
//
//
//
// LoadSaveConfigDlg loadDlg = new LoadSaveConfigDlg(shell,
// DialogType.SAVE_AS, scanTable);
// LocalizationFile fileName = loadDlg.open();
//
// if (fileName == null)
// {
// System.out.println("FileName is null...");
// return;
// }
//
// if (defCfgName.compareTo(fileName.getFile().getName()) == 0)
// {
// MessageBox mb = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK |
// SWT.CANCEL);
// mb.setText("Overwrite");
// mb.setMessage("The Save As name is the same as the default configuration name. Saving "
// +
// "will overwrite the default configuration.\n" +
// "Do you wish to continue?");
// int result = mb.open();
//
// // If the user selected Cancel then return.
// if (result == SWT.CANCEL)
// {
// return;
// }
// }
//
// scanCfg.saveConfigurationFileAs(scanTable, fileName.getFile().getName());
// }
/**
* Shell closed action.
*/
@Override
protected void shellCloseAction() {
// TODO : this method may be deleted from the abstract
// class if it is not needed
}
/**
* Shell dispose action.
*/
@ -1164,7 +994,6 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
@Override
public void shellClosed(ShellEvent e) {
e.doit = killDialog;
// unregisterDialog();
}
});
}
@ -1186,6 +1015,22 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
shell.setText(this.site + " CELL Table");
}
/**
* Update the table with new data.
*
* @param scan
* Scan Monitor.
* @param time
* The new time.
* @param sdg
* Scan Data Generator.
*/
private void updateTable(ScanMonitor scan, Date time, ScanDataGenerator sdg) {
tableData = sdg.generateCellData(scan.getTableData(scanTable, site,
time));
scanTableComp.setTableData(tableData);
}
/**
* Notify when the table data needs to be updated.
*/
@ -1193,18 +1038,15 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
public void notify(IMonitorEvent me) {
if (me.getSource() instanceof IMonitor) {
ScanMonitor scan = (ScanMonitor) me.getSource();
Date time = null;
try {
if (getLinkToFrame(scanTable.name())) {
time = scan.getScanTime(scanTable, site);
} else {
time = scan.getMostRecent(scan, scanTable.name(), site)
.getRefTime();
}
} catch (Exception e) {
// If scan is null return since nothing will be done.
if (scan == null) {
return;
}
if ((time != null) && (scan != null)) {
Date time = getScanTime(scan);
if ((time != null)) {
ScanDataGenerator sdg = new ScanDataGenerator(site);
@ -1218,21 +1060,18 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
sdg.setUnwarnedCells(warnings);
}
tableData = sdg.generateCellData((scan).getTableData(scanTable,
site, time));
scanTableComp.setTableData(tableData);
setShellText();
if (getLinkToFrame(scanTable.name())) {
currentTime = (scan).getDialogTime(scanTable, site);
currentTime = scan.getDialogTime(scanTable, site);
updateTimeLabel();
updateTable(scan, time, sdg);
} else {
currentTime = time;
if (currentTime == null || !currentTime.equals(time)) {
currentTime = time;
updateTimeLabel();
updateTable(scan, time, sdg);
}
}
updateTimeLabel();
scan.fireMonitorEvent(SCANMesoTableDlg.class.getName());
scan.fireMonitorEvent(SCANTvsTableDlg.class.getName());
@ -1242,11 +1081,10 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
// closes the alarm dialog if new data comes in or user switches
// frame
Date scanMostRecentTime = null;
try {
scanMostRecentTime = scan.getMostRecent(scan,
scanTable.name(), site).getRefTime();
} catch (NullPointerException npe) {
// scan has been turned off
DataTime dataTime = scan.getMostRecent(scan, scanTable.name(),
site);
if (dataTime != null) {
scanMostRecentTime = dataTime.getRefTime();
}
if (scanMostRecentTime != null) {
@ -1265,13 +1103,14 @@ public class SCANCellTableDlg extends AbstractTableDlg implements
scanTableComp.checkBlink(sdg, scanMostRecentTime);
if (mgr.getAlertedAlarms(site, scanTable).size() > 0) {
boolean displayAlarmBtn = false;
for (AlertedAlarms alarm: mgr.getAlertedAlarms(site, scanTable)) {
for (AlertedAlarms alarm : mgr.getAlertedAlarms(
site, scanTable)) {
if (!alarm.cleared) {
displayAlarmBtn = true;
break;
}
}
alarmBtn.setVisible(displayAlarmBtn);
addAlarmTimer();
} else {

View file

@ -27,7 +27,6 @@ import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableColumn;
@ -55,6 +54,8 @@ import com.raytheon.uf.viz.monitor.scan.commondialogs.TimeHeightDlg;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 3, 2009 #3039 lvenable Initial creation
* Apr 26, 2013 #1945 lvenable Improved SCAN performance, reworked
* some bad code, and some code cleanup.
*
* </pre>
*
@ -63,16 +64,14 @@ import com.raytheon.uf.viz.monitor.scan.commondialogs.TimeHeightDlg;
*/
public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
IRequestTimeHeightData {
private Point mouseMovePt = new Point(0, 0);
private Point mouseDownPt = new Point(0, 0);
private Point prevMousePt = new Point(-9999, -9999);
private TimeHeightDlg timeHeightDlg = null;
private IRequestTimeHeightData timeHeightCB;
/** Clutter control column name. */
private String clutterColName = "";
public SCANDmdTableComp(Composite parent, SCANTableData tableData,
ITableAction tableActionCB,
IRequestTrendGraphData requestDataCallback,
@ -85,6 +84,15 @@ public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
@Override
protected void setColumnImages() {
/*
* If the clutter control & sort column hasn't changed then return
* because the images will not change.
*/
if (scanCfg.isClutterControl(scanTable, clutterColName)
&& lastSortColIndex == sortedColumnIndex) {
return;
}
TableColumn[] tCols = table.getColumns();
for (int i = 0; i < tCols.length; i++) {
@ -100,9 +108,9 @@ public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
gc.setBackground(this.getDisplay().getSystemColor(SWT.COLOR_BLACK));
// Set the foreground color to the clutter control color if the
// column
// is a clutter control.
// column is a clutter control.
if (scanCfg.isClutterControl(scanTable, colName) == true) {
clutterColName = colName;
gc.setForeground(scanCfg
.getScanColor(ScanColors.ClutterControl));
}
@ -120,12 +128,12 @@ public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
gc.setBackground(scanCfg.getScanColor(ScanColors.Sort));
}
lastSortColIndex = sortedColumnIndex;
gc.fillRectangle(0, 0, imageWidth, imageHeight);
int colNameExt = gc.stringExtent(colName).x;
// int xCoord = (imageWidth / 2) - (colName.length() * textWidth /
// 2);
int xCoord = (imageWidth / 2) - (colNameExt / 2);
gc.drawText(colName, xCoord, 3, true);
@ -201,12 +209,6 @@ public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
@Override
protected void tableMouseMoveAction(MouseEvent event) {
// if (scanCfg.showTips(scanTable) == false) {
// prevMousePt.x = -9999;
// prevMousePt.y = -9999;
// table.setToolTipText(null);
// return;
// }
mouseMovePt.x = event.x;
mouseMovePt.y = event.y;
@ -219,7 +221,6 @@ public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
}
Rectangle rect;
// rect = item.getBounds(table.getColumnCount() - 2);
rect = item.getBounds(scanCfg.getCountyColumnIndex(scanTable));
if ((scanCfg.showTips(scanTable) == false)
@ -282,9 +283,9 @@ public class SCANDmdTableComp extends SCANTableTrendGraphLayer implements
public void redrawTimeHeightGraph() {
if ((timeHeightDlg == null) || timeHeightDlg.isDisposed()) {
return;
} else {
timeHeightDlg.redrawGraph();
}
timeHeightDlg.redrawGraph();
}
public boolean timeHeightDisplayed() {

View file

@ -57,7 +57,6 @@ import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanColors;
import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
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.viz.monitor.IMonitor;
import com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent;
import com.raytheon.uf.viz.monitor.events.IMonitorEvent;
@ -90,6 +89,8 @@ import com.raytheon.viz.ui.EditorUtil;
* Apr 29, 2010 lvenable Initial creation
*
* 03/15/2012 13939 Mike Duff For a SCAN Alarms issue
* Apr 29, 2013 #1945 lvenable Improved SCAN performance, reworked
* some bad code, and some code cleanup.
*
* </pre>
*
@ -315,6 +316,7 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
@Override
public void run() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
if (shell.isDisposed()) {
dmdTableComp.timer.cancel();
@ -473,11 +475,16 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
vertChk.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
vertChk.setSelection(dmdConfigMgr.getScanDmdCfgXML().getFilterOption());
vertChk.setLayoutData(gd);
vertChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
/*
* The vertical table is a techblocked DR. This will be commented out
* until that is addressed.
*/
// vertChk.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// }
// });
setupButtonMouseListeners(vertChk);
gd = new GridData();
@ -514,7 +521,7 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
alarmsDlg.open();
if (!alarmBtn.isDisposed()
&& mgr.getAlertedAlarms(site, scanTable).isEmpty()) {
turnOffAlarm();
turnOffAlarm();
}
}
});
@ -522,8 +529,7 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
gd = new GridData(SWT.DEFAULT, SWT.CENTER, false, true);
gd.widthHint = 135;
elevationLbl = new Label(controlComp, SWT.CENTER | SWT.BORDER);
elevationLbl.setText("* No Elevation *"); // TODO - need to add
// elevation
elevationLbl.setText("* No Elevation *");
elevationLbl.setBackground(elevationLabelColor);
elevationLbl.setLayoutData(gd);
@ -677,53 +683,6 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
configBtn.setMenu(configPopupMenu);
}
/**
* Create the Rank popup menu.
*/
// private void createRankPopupMenu() {
// rankPopupMenu = new Menu(rankBtn);
/*
* TODO : need to handle default ranking in the list... DMD -- stRank not
* really clear on how the legacy system handle this.
*/
/*
* Default menu item
*/
// MenuItem defaultMI = new MenuItem(rankPopupMenu, SWT.NONE);
// defaultMI.setText(SCANConfig.getInstance().getDefaultName());
// defaultMI.setData(SCANConfig.getInstance().getDefaultName());
// defaultMI.setEnabled(false);
// defaultMI.addSelectionListener(new SelectionAdapter()
// {
// @Override
// public void widgetSelected(SelectionEvent event)
// {
// handleRankMenuEvent(event);
// }
// });
//
/*
* Create the remaining rank menus from the configuration
*/
// String[] ranks = SCANConfig.getInstance().getRankColumns(scanTable);
//
// for (String rankStr : ranks) {
// MenuItem mi = new MenuItem(rankPopupMenu, SWT.NONE);
// mi.setText(rankStr);
// mi.setData(rankStr);
// mi.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent event) {
// handleRankMenuEvent(event);
// }
// });
// }
//
// rankBtn.setMenu(rankPopupMenu);
// }
/**
* Display the Create/Edit trend dialog.
*/
@ -893,9 +852,6 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
linkToFrameChk.getSelection());
IMonitorConfigurationEvent imce = new IMonitorConfigurationEvent(this);
this.fireConfigUpdate(imce);
// System.out.println("######## Link to frame is : " +
// linkToFrameChk.getSelection());
}
/**
@ -925,15 +881,6 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
}
}
/**
* Shell close action.
*/
@Override
protected void shellCloseAction() {
// TODO Auto-generated method stub
}
/**
* Shell dispose action.
*/
@ -970,7 +917,6 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
@Override
protected void setShellText() {
shell.setText(this.site + " DMD Table");
}
/**
@ -994,19 +940,14 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
public void notify(IMonitorEvent me) {
if (me.getSource() instanceof IMonitor) {
ScanMonitor scan = (ScanMonitor) me.getSource();
Date time = null;
try {
if (getLinkToFrame(scanTable.name())) {
time = (scan).getScanTime(scanTable, site);
} else {
time = (scan).getMostRecent(scan, scanTable.name(), site)
.getRefTime();
}
} catch (Exception e) {
statusHandler.handle(Priority.ERROR, "Unable to retrieve time",
e);
// If scan is null return since nothing will be done.
if (scan == null) {
return;
}
Date time = getScanTime(scan);
if ((time != null) && scan.isInstantiated()) {
ScanDataGenerator sdg = new ScanDataGenerator(site);
ScanTableData<?> data = null;
@ -1070,7 +1011,9 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
&& currentTime.equals(scan.getMostRecent(scan,
scanTable.name(), site).getRefTime())
&& !scanCfg.getAlarmsDisabled(scanTable)) {
dmdTableComp.checkBlink(sdg, scan.getMostRecent(scan, scanTable.name(), site).getRefTime());
dmdTableComp.checkBlink(sdg,
scan.getMostRecent(scan, scanTable.name(), site)
.getRefTime());
if (mgr.getAlertedAlarms(site, scanTable).size() > 0) {
alarmBtn.setVisible(true);
addAlarmTimer();
@ -1298,19 +1241,21 @@ public class SCANDmdTableDlg extends AbstractTableDlg implements
dmdTableComp.alarmSelection(ident);
}
public void turnOffAlarm() {
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(false);
}
mgr.setRing(false);
}
@Override
public void turnOffAlarm() {
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(false);
}
mgr.setRing(false);
}
@Override
public void turnOnAlarm() {
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(true);
}
if (alarmBtn != null && !alarmBtn.isDisposed()) {
alarmBtn.setVisible(true);
}
mgr.setRing(true);
}
}
}

View file

@ -20,7 +20,6 @@
package com.raytheon.uf.viz.monitor.scan.tables;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableItem;
@ -38,6 +37,7 @@ import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 2, 2009 #3039 lvenable Initial creation
* Apr 29, 2013 #1945 lvenable Code cleanup for SCAN performance.
*
* </pre>
*
@ -45,11 +45,6 @@ import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
* @version 1.0
*/
public class SCANMesoTableComp extends SCANTable {
// private Point mouseMovePt = new Point(0, 0);
private Point mouseDownPt = new Point(0, 0);
// private Point prevMousePt = new Point(-9999, -9999);
/**
* Constructor.
@ -68,49 +63,6 @@ public class SCANMesoTableComp extends SCANTable {
init();
}
/**
* Set the column images for the table columns.
*/
// @Override
// protected void setColumnImages() {
// TableColumn[] tCols = table.getColumns();
//
// for (int i = 0; i < tCols.length; i++) {
// String colName = (String) tCols[i].getData();
// Image img = new Image(this.getDisplay(), imageWidth, imageHeight);
//
// GC gc = new GC(img);
// gc.setFont(columnFont);
//
// // Set the initial foreground and background colors.
// gc.setForeground(this.getDisplay().getSystemColor(SWT.COLOR_WHITE));
// gc.setBackground(this.getDisplay().getSystemColor(SWT.COLOR_BLACK));
//
// // Set the background color to the sort color if that column is
// // sorted.
// if (sortedColumnIndex == -1) {
// scanCfg.getDefaultName();
// String sortColName = scanCfg.getDefaultRank(this.scanTable);
// int colIndex = scanCfg.getColumnIndex(scanTable, sortColName);
// sortedColumnIndex = colIndex;
// }
// if (table.indexOf(tCols[i]) == sortedColumnIndex) {
// gc.setBackground(scanCfg.getScanColor(ScanColors.Sort));
// }
//
// gc.fillRectangle(0, 0, imageWidth, imageHeight);
//
// int xCoord = (imageWidth / 2) - (colName.length() * textWidth / 2);
//
// gc.drawText(colName, xCoord, 3, true);
//
// gc.dispose();
// tCols[i].setImage(img);
//
// img.dispose();
// }
// }
@Override
protected void tableMouseDownAction(MouseEvent event) {
mouseDownPt.x = event.x;
@ -154,13 +106,4 @@ public class SCANMesoTableComp extends SCANTable {
}
}
}
// @Override
// protected void tableMouseMoveAction(MouseEvent event) {
// /*
// * The legacy system has tool tip text indicating trend dialogs can be
// * launched but that is not the case. There should not be tool tip text
// * at this time.
// */
// }
}

View file

@ -60,9 +60,29 @@ import com.raytheon.uf.viz.monitor.scan.commondialogs.SCANAttributesDlg;
import com.raytheon.uf.viz.monitor.scan.commondialogs.SCANColorThreshDlg;
import com.raytheon.uf.viz.monitor.scan.data.ScanDataGenerator;
/**
*
* Scan dialog for the MESO table.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 29, 2013 #1945 lvenable Code cleanup for SCAN performance.
*
* </pre>
*
* @author lvenable
* @version 1.0
*/
public class SCANMesoTableDlg extends AbstractTableDlg implements
IAttributeUpdate, IThresholdUpdate {
/*
* Buttons at the top of the dialog and the popup menus.
*/
private Button configBtn;
private Button rankBtn;
@ -96,6 +116,16 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
private Date currentTime = null;
/**
* Constructor.
*
* @param parentShell
* Parent shell.
* @param site
* Site name.
* @param tableData
* Data to be displayed in the table.
*/
public SCANMesoTableDlg(Shell parentShell, String site,
SCANTableData tableData) {
super(parentShell);
@ -221,11 +251,16 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
vertChk.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
vertChk.setSelection(mesoCfgMgr.getScanMesoCfgXML().getFilterOption());
vertChk.setLayoutData(gd);
vertChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
/*
* The vertical table is a techblocked DR. This selection listener will
* be commented out until it is needed.
*/
// vertChk.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// }
// });
setupButtonMouseListeners(vertChk);
gd = new GridData();
@ -353,47 +388,6 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
configBtn.setMenu(configPopupMenu);
}
// private void createRankPopupMenu() {
// rankPopupMenu = new Menu(rankBtn);
// TODO : need to handle default ranking in the list... MESO -- mdaSR
/*
* Default menu item
*/
// MenuItem defaultMI = new MenuItem(rankPopupMenu, SWT.NONE);
// defaultMI.setText(SCANConfig.getInstance().getDefaultName());
// defaultMI.setData(SCANConfig.getInstance().getDefaultName());
// defaultMI.setEnabled(false);
// defaultMI.addSelectionListener(new SelectionAdapter()
// {
// @Override
// public void widgetSelected(SelectionEvent event)
// {
// handleRankMenuEvent(event);
// }
// });
//
/*
* Create the remaining rank menus from the configuration
*/
// String[] ranks = SCANConfig.getInstance().getRankColumns(scanTable);
//
// for (String rankStr : ranks) {
// MenuItem mi = new MenuItem(rankPopupMenu, SWT.NONE);
// mi.setText(rankStr);
// mi.setData(rankStr);
// mi.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent event) {
// handleRankMenuEvent(event);
// }
// });
// }
//
// rankBtn.setMenu(rankPopupMenu);
// }
private void displayAttributesDialog() {
if ((attributeDlg == null)
|| (attributeDlg.getParent().isDisposed() == true)) {
@ -459,12 +453,6 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
this.fireDialogShutdown(this);
}
@Override
protected void shellCloseAction() {
// TODO : this method may be deleted from the abstract
// class if it is not needed
}
@Override
protected void shellDisposeAction() {
shell.addDisposeListener(new DisposeListener() {
@ -474,16 +462,6 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
unregisterDialogFromMonitor();
}
});
// shell.addShellListener(new ShellAdapter()
// {
// @Override
// public void shellClosed(ShellEvent e)
// {
// System.out.println("MESO dialog SHELL CLOSED");
// unregisterDialog();
// }
// });
}
@Override
@ -506,36 +484,29 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
@Override
public void notify(IMonitorEvent me) {
if (me.getSource() instanceof IMonitor) {
// System.out.println("SCAN MESO Table Notify Event Received");
ScanMonitor scan = (ScanMonitor) me.getSource();
Date time = null;
try {
if (getLinkToFrame(scanTable.name())) {
time = scan.getScanTime(scanTable, site);
} else {
time = scan.getMostRecent(scan, scanTable.name(), site)
.getRefTime();
}
} catch (Exception e) {
// If scan is null return since nothing will be done.
if (scan == null || scanTableComp.isDisposed()) {
return;
}
Date time = getScanTime(scan);
if (time != null) {
ScanDataGenerator sdg = new ScanDataGenerator(site);
// scanTableComp.setTableData(sdg.generateMesoData(scan
// .getTableData(ScanTables.MESO, time)));
ScanTableData<?> data = scan.getTableData(ScanTables.MESO,
site, time);
if (!scanTableComp.isDisposed()) {
scanTableComp.setTableData(sdg.generateMesoData(data));
setShellText();
if (getLinkToFrame(scanTable.name())) {
currentTime = scan.getDialogTime(scanTable, site);
} else {
currentTime = time;
}
updateTimeLabel();
scanTableComp.setTableData(sdg.generateMesoData(data));
if (getLinkToFrame(scanTable.name())) {
currentTime = scan.getDialogTime(scanTable, site);
} else {
currentTime = time;
}
updateTimeLabel();
}
}
}
@ -647,14 +618,14 @@ public class SCANMesoTableDlg extends AbstractTableDlg implements
return false;
}
@Override
public void turnOffAlarm() {
mgr.setRing(false);
}
@Override
public void turnOffAlarm() {
mgr.setRing(false);
}
@Override
public void turnOnAlarm() {
mgr.setRing(true);
}
@Override
public void turnOnAlarm() {
mgr.setRing(true);
}
}

View file

@ -62,15 +62,26 @@ import com.raytheon.uf.viz.monitor.scan.ScanMonitor;
import com.raytheon.uf.viz.monitor.scan.data.ScanDataGenerator;
import com.raytheon.uf.viz.monitor.scan.tables.SCANAlarmAlertManager.AlertedAlarms;
/* Modification History:
* Date Ticket# Name Change
* ------------ ---------- ------------ --------------------------
* 02/23/2012 14538 Xiaochuan Fix TVS table default rank.
/**
*
* 03/15/2012 13939 Mike Duff For a SCAN Alarms issue
*
* Abstract scan table class used for the CELL, DMD, MESO, and TVS tables..
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 02/23/2012 14538 Xiaochuan Fix TVS table default rank.
* 03/15/2012 13939 Mike Duff For a SCAN Alarms issue
* Apr 29, 2013 #1945 lvenable Improved SCAN performance, reworked
* some bad code, and some code cleanup.
*
* </pre>
*
* @author lvenable
* @version 1.0
*/
public abstract class SCANTable extends Composite {
protected Table table;
@ -140,6 +151,24 @@ public abstract class SCANTable extends Composite {
protected Point prevMousePt = new Point(-9999, -9999);
/**
* Last sorted column index. This is set to -2 because sortedColumnIndex is
* set to -1 and they should not have the same initial value at start up.
*/
protected int lastSortColIndex = -2;
/**
* Constructor.
*
* @param parent
* Parent composite.
* @param tableData
* Data to be display into the table.
* @param tableActionCB
* Callback when the table is clicked.
* @param site
* Site name.
*/
public SCANTable(Composite parent, SCANTableData tableData,
ITableAction tableActionCB, String site) {
super(parent, 0);
@ -176,8 +205,6 @@ public abstract class SCANTable extends Composite {
createTableItems();
// packColumns();
sortedColumnIndex = -1;
sortTableUsingConfig();
@ -185,6 +212,7 @@ public abstract class SCANTable extends Composite {
showHideTableColumns();
this.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent arg0) {
if ((scanTable == ScanTables.CELL)
|| (scanTable == ScanTables.DMD)) {
@ -209,11 +237,6 @@ public abstract class SCANTable extends Composite {
gd.heightHint = 175;
gd.widthHint = scanCfg.getDefaultTableWidth(scanTable);
// **********************************************************
// **********************************************************
// **********************************************************
// **********************************************************
boolean[] visCols = scanCfg.getVisibleColumns(scanTable);
int tableWidth = 0;
@ -223,17 +246,6 @@ public abstract class SCANTable extends Composite {
}
}
System.out.println("widthHint = " + gd.widthHint);
System.out.println("tableWidth = " + tableWidth);
// **********************************************************
// **********************************************************
// **********************************************************
// **********************************************************
// **********************************************************
// table = new Table(this, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL
// | SWT.FULL_SELECTION);
table = new Table(this, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL);
table.setLayoutData(gd);
table.setHeaderVisible(true);
@ -243,13 +255,9 @@ public abstract class SCANTable extends Composite {
gc.dispose();
table.addListener(SWT.PaintItem, new Listener() {
@Override
public void handleEvent(Event event) {
// if (scanTable != ScanTables.CELL) {
// // System.out.println("scanTable = " + scanTable.name());
// // System.out.println("in paintListener");
// }
if (tableData.getTableRows().size() != 0) {
table.deselectAll();
event.gc.setForeground(lineColor);
@ -262,10 +270,7 @@ public abstract class SCANTable extends Composite {
rect.height);
// Draw an extra line on the edges of the table cell to hide
// the
// white lines
// dividing the columns;
// event.gc.setLineWidth(2);
// the white lines dividing the columns;
event.gc.drawLine(rect.x + rect.width - 2, rect.y - 1,
rect.x + rect.width - 2, rect.y - 1 + rect.height);
@ -284,9 +289,6 @@ public abstract class SCANTable extends Composite {
}
} else {
// System.out.println("scanTable = " + scanTable.name());
// System.out.println("event.index = " + event.index);
if ((event.index >= 0) || (event.index <= 6)) {
int offset = 0;
@ -299,7 +301,6 @@ public abstract class SCANTable extends Composite {
event.gc.setForeground(getParent().getShell()
.getDisplay().getSystemColor(SWT.COLOR_GREEN));
// event.gc.setBackground(display.getSystemColor(SWT.COLOR_BLACK));
int y = event.y + (event.height - extent.y) / 2;
event.gc.drawString(noDataStr, event.x - offset, y);
@ -357,7 +358,6 @@ public abstract class SCANTable extends Composite {
@Override
public void widgetSelected(SelectionEvent event) {
tableColumnSelectAction(event);
}
});
@ -380,13 +380,6 @@ public abstract class SCANTable extends Composite {
}
setColumnImages();
//
// TODO : Rank is default so we have to sort by the default - fix this
//
// TableColumn stc = table.getColumn(0);
// TODO : Will need to fix with the default ranking
sortedColumnIndex = -1;
}
@ -545,15 +538,14 @@ public abstract class SCANTable extends Composite {
tableData = td;
if ((tableData == null) || (tableData.getTableRows().size() == 0)) {
// System.out.println("*** no data");
// table.setEnabled(true);
table.removeAll();
/*
* This TableItem is needed to draw "No Detections" on. Do not
* remove it.
*/
TableItem item = new TableItem(table, SWT.NONE);
new TableItem(table, SWT.NONE);
table.setBackground(getParent().getShell().getDisplay()
.getSystemColor(SWT.COLOR_BLACK));
@ -629,10 +621,10 @@ public abstract class SCANTable extends Composite {
return;
}
if( scanTable == ScanTables.TVS && sortedIndex == -1)
{
if (scanTable == ScanTables.TVS && sortedIndex == -1) {
sortedIndex = TVSTable.valueOf("IDENT").ordinal();
}
// get the ident, if a row is outlined in blue
if (tableIndex >= 0) {
SCANTableRowData stdr = tableData.getTableRows().get(tableIndex);
@ -670,12 +662,9 @@ public abstract class SCANTable extends Composite {
} else {
tableData.sortDefault();
}
createTableItems();
// packColumns();
showHideTableColumns();
if (timer != null) {
timer.cancel();
}
@ -684,11 +673,14 @@ public abstract class SCANTable extends Composite {
}
ScanDataGenerator sdg = new ScanDataGenerator(site);
if ((scanTable == ScanTables.CELL) || ((scanTable == ScanTables.DMD)
&& !mgr.getAlertedAlarms(site, scanTable).isEmpty())) {
if ((scanTable == ScanTables.CELL)
|| ((scanTable == ScanTables.DMD) && !mgr.getAlertedAlarms(
site, scanTable).isEmpty())) {
ScanMonitor monitor = ScanMonitor.getInstance();
if (monitor.getMostRecent(monitor, scanTable.name(), site) != null) {
checkBlink(sdg, monitor.getMostRecent(monitor, scanTable.name(), site).getRefTime());
checkBlink(sdg,
monitor.getMostRecent(monitor, scanTable.name(), site)
.getRefTime());
}
}
@ -753,7 +745,6 @@ public abstract class SCANTable extends Composite {
private void packSingleColumn(TableColumn tc, int index) {
tc.pack();
// tCols[i].setWidth(table.getColumn(i).getWidth() + 5);
tc.setWidth(table.getColumn(index).getWidth() + 2);
if (tc.getWidth() > defaultColWidth) {
@ -791,20 +782,11 @@ public abstract class SCANTable extends Composite {
maxTextLength = colNames[i].length();
}
// System.out.println("--- column name = " + colNames[i]);
// System.out.println("--- extent = " +
// gc.stringExtent(colNames[i]));
if (gc.stringExtent(colNames[i]).x > maxColNameExtent) {
maxColNameExtent = gc.stringExtent(colNames[i]).x;
}
}
// System.out.println("maxColNameExtent = " + maxColNameExtent + " - "
// + scanTable.name());
// imageWidth = maxTextLength * textWidth + 6;
// imageWidth = maxColNameExtent + 2;
imageWidth = maxColNameExtent;
imageHeight = textHeight + 4;
@ -812,6 +794,9 @@ public abstract class SCANTable extends Composite {
image.dispose();
}
/**
* Update the column tooltip text.
*/
public void updateColumnTips() {
if (scanCfg.showTips(scanTable) == false) {
TableColumn[] tCols = table.getColumns();
@ -827,8 +812,6 @@ public abstract class SCANTable extends Composite {
(String) tCols[i].getData()));
}
}
// TODO - need the column tool tip text to be set
}
/**
@ -919,6 +902,7 @@ public abstract class SCANTable extends Composite {
@Override
public void run() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
runTimerTask();
}
@ -932,6 +916,7 @@ public abstract class SCANTable extends Composite {
@Override
public void run() {
Display.getDefault().asyncExec(new Runnable() {
@Override
public void run() {
// Fail-safe check to determine if the we have no
@ -966,9 +951,7 @@ public abstract class SCANTable extends Composite {
private void runTimerTask() {
// Fail-safe check to determine if the we have
// no
// data
// in the table data.
// no data in the table data.
if ((timer != null) && (tableData != null)) {
if (tableData.getTableRows().size() == 0) {
if (timer != null) {
@ -986,27 +969,26 @@ public abstract class SCANTable extends Composite {
boolean allClear = true;
ArrayList<Point> points = new ArrayList<Point>();
Set<AlertedAlarms> alarmList = mgr.getAlertedAlarms(site, scanTable);
for (int i = 0; i < tableData
.getNumberOfDataRows(); i++) {
Set<AlertedAlarms> alarmList = mgr.getAlertedAlarms(site,
scanTable);
for (int i = 0; i < tableData.getNumberOfDataRows(); i++) {
TableItem ti = table.getItem(i);
if (ti == null) {
continue;
}
if ((alarmList != null) && (alarmList.size() > 0)) {
for (AlertedAlarms alarm: alarmList) {
if (tableData.getTableRows().get(i).getIdent().equals(alarm.ident)) {
for (AlertedAlarms alarm : alarmList) {
if (tableData.getTableRows().get(i).getIdent()
.equals(alarm.ident)) {
if (alarm.cleared == false) {
ti.setBackground(alarm.col, blinkColor);
allClear = false;
// handle the beep while
// looking at
// all the cells
if (SCANConfig
.getInstance()
.getAlarmBell(
scanTable)) {
if (SCANConfig.getInstance().getAlarmBell(
scanTable)) {
mgr.setRing(true);
}
} else {
@ -1016,10 +998,9 @@ public abstract class SCANTable extends Composite {
}
}
}
for (int i = 0; i < points.size(); i++) {
updateThresholds(points.get(i).x,
points.get(i).y);
updateThresholds(points.get(i).x, points.get(i).y);
}
// checks if there are no more alarms
@ -1030,9 +1011,9 @@ public abstract class SCANTable extends Composite {
timer.purge();
}
}
}
}
}
public Timer getBlinkTimer() {
if (timer == null) {
timer = new Timer();
@ -1056,6 +1037,9 @@ public abstract class SCANTable extends Composite {
blinkColor = Display.getDefault().getSystemColor(blinkColorInt);
}
/**
* Redraw the table.
*/
public void redrawTable() {
table.redraw();
}
@ -1066,6 +1050,14 @@ public abstract class SCANTable extends Composite {
* DMD do this).
*/
protected void setColumnImages() {
/*
* If the sort column hasn't changed then return because the images will
* not change.
*/
if (lastSortColIndex == sortedColumnIndex) {
return;
}
TableColumn[] tCols = table.getColumns();
for (int i = 0; i < tCols.length; i++) {
@ -1082,13 +1074,16 @@ public abstract class SCANTable extends Composite {
// Set the background color to the sort color if that column is
// sorted.
// sortedColumnIndex=-1 is default sort
// sortedColumnIndex=-1 is default sort
if (sortedColumnIndex == -1) {
scanCfg.getDefaultName();
String sortColName = scanCfg.getDefaultRank(this.scanTable);
int colIndex = scanCfg.getColumnIndex(scanTable, sortColName);
sortedColumnIndex = colIndex;
}
lastSortColIndex = sortedColumnIndex;
if (table.indexOf(tCols[i]) == sortedColumnIndex) {
gc.setBackground(scanCfg.getScanColor(ScanColors.Sort));
}
@ -1124,7 +1119,6 @@ public abstract class SCANTable extends Composite {
}
Rectangle rect;
// rect = item.getBounds(table.getColumnCount() - 1);
rect = item.getBounds(scanCfg.getCountyColumnIndex(scanTable));
if ((scanCfg.showTips(scanTable) == false)
@ -1229,5 +1223,4 @@ public abstract class SCANTable extends Composite {
* Mouse event.
*/
protected abstract void tableMouseDownAction(MouseEvent event);
}

View file

@ -20,7 +20,6 @@
package com.raytheon.uf.viz.monitor.scan.tables;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TableItem;
@ -38,6 +37,7 @@ import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 3, 2009 #3039 lvenable Initial creation
* Apr 29, 2013 #1945 lvenable Code cleanup for SCAN performance.
*
* </pre>
*
@ -45,12 +45,19 @@ import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables;
* @version 1.0
*/
public class SCANTvsTableComp extends SCANTable {
private Point mouseMovePt = new Point(0, 0);
private Point mouseDownPt = new Point(0, 0);
private Point prevMousePt = new Point(-9999, -9999);
/**
* Constructor.
*
* @param parent
* Parent composite.
* @param tableData
* Data to be displayed in the table.
* @param tableActionCB
* Callback called when the table is clicked.
* @param site
* The site name.
*/
public SCANTvsTableComp(Composite parent, SCANTableData tableData,
ITableAction tableActionCB, String site) {
super(parent, tableData, tableActionCB, site);
@ -58,46 +65,6 @@ public class SCANTvsTableComp extends SCANTable {
init();
}
// @Override
// protected void setColumnImages() {
// TableColumn[] tCols = table.getColumns();
//
// for (int i = 0; i < tCols.length; i++) {
// String colName = (String) tCols[i].getData();
// Image img = new Image(this.getDisplay(), imageWidth, imageHeight);
//
// GC gc = new GC(img);
// gc.setFont(columnFont);
//
// // Set the initial foreground and background colors.
// gc.setForeground(this.getDisplay().getSystemColor(SWT.COLOR_WHITE));
// gc.setBackground(this.getDisplay().getSystemColor(SWT.COLOR_BLACK));
//
// // Set the background color to the sort color if that column is
// // sorted.
// if (sortedColumnIndex == -1) {
// scanCfg.getDefaultName();
// String sortColName = scanCfg.getDefaultRank(this.scanTable);
// int colIndex = scanCfg.getColumnIndex(scanTable, sortColName);
// sortedColumnIndex = colIndex;
// }
// if (table.indexOf(tCols[i]) == sortedColumnIndex) {
// gc.setBackground(scanCfg.getScanColor(ScanColors.Sort));
// }
//
// gc.fillRectangle(0, 0, imageWidth, imageHeight);
//
// int xCoord = (imageWidth / 2) - (colName.length() * textWidth / 2);
//
// gc.drawText(colName, xCoord, 3, true);
//
// gc.dispose();
// tCols[i].setImage(img);
//
// img.dispose();
// }
// }
@Override
protected void tableMouseDownAction(MouseEvent event) {
mouseDownPt.x = event.x;
@ -140,12 +107,4 @@ public class SCANTvsTableComp extends SCANTable {
}
}
}
// @Override
// protected void tableMouseMoveAction(MouseEvent event) {
// /*
// * TODO: Looking at the WES the TVS table is empty. Need to look at the
// * legacy code to determine if there are tool tip texts for the cells.
// */
// }
}

View file

@ -59,6 +59,23 @@ import com.raytheon.uf.viz.monitor.scan.commondialogs.SCANAttributesDlg;
import com.raytheon.uf.viz.monitor.scan.commondialogs.SCANColorThreshDlg;
import com.raytheon.uf.viz.monitor.scan.data.ScanDataGenerator;
/**
*
* Dialog for the SCAN TVS table.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 29, 2013 #1945 lvenable Code cleanup for SCAN performance.
*
* </pre>
*
* @author lvenable
* @version 1.0
*/
public class SCANTvsTableDlg extends AbstractTableDlg implements
IAttributeUpdate, IThresholdUpdate {
private Button configBtn;
@ -91,6 +108,16 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
private Date currentTime = null;
/**
* Constructor.
*
* @param parentShell
* Parent shell.
* @param site
* Site name.
* @param tableData
* Tabel data.
*/
public SCANTvsTableDlg(Shell parentShell, String site,
SCANTableData tableData) {
super(parentShell);
@ -215,11 +242,16 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
vertChk.setForeground(display.getSystemColor(SWT.COLOR_WHITE));
vertChk.setSelection(tvsCfgMgr.getScanTvsCfgXML().getFilterOption());
vertChk.setLayoutData(gd);
vertChk.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
}
});
/*
* The vertical table is a techblocked DR. This selection listener will
* be commented out until it is needed.
*/
// vertChk.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent e) {
// }
// });
setupButtonMouseListeners(vertChk);
gd = new GridData();
@ -347,47 +379,6 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
configBtn.setMenu(configPopupMenu);
}
// private void createRankPopupMenu() {
// rankPopupMenu = new Menu(rankBtn);
// TODO : need to handle default ranking in the list... MESO -- mdaSR
/*
* Default menu item
*/
// MenuItem defaultMI = new MenuItem(rankPopupMenu, SWT.NONE);
// defaultMI.setText(SCANConfig.getInstance().getDefaultName());
// defaultMI.setData(SCANConfig.getInstance().getDefaultName());
// defaultMI.setEnabled(false);
// defaultMI.addSelectionListener(new SelectionAdapter()
// {
// @Override
// public void widgetSelected(SelectionEvent event)
// {
// handleRankMenuEvent(event);
// }
// });
//
/*
* Create the remaining rank menus from the configuration
*/
// String[] ranks = SCANConfig.getInstance().getRankColumns(scanTable);
//
// for (String rankStr : ranks) {
// MenuItem mi = new MenuItem(rankPopupMenu, SWT.NONE);
// mi.setText(rankStr);
// mi.setData(rankStr);
// mi.addSelectionListener(new SelectionAdapter() {
// @Override
// public void widgetSelected(SelectionEvent event) {
// handleRankMenuEvent(event);
// }
// });
// }
//
// rankBtn.setMenu(rankPopupMenu);
// }
private void displayAttributesDialog() {
if ((attributeDlg == null)
|| (attributeDlg.getParent().isDisposed() == true)) {
@ -451,18 +442,11 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
this.fireDialogShutdown(this);
}
@Override
protected void shellCloseAction() {
// TODO : this method may be deleted from the abstract
// class if it is not needed
}
@Override
protected void shellDisposeAction() {
shell.addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
System.out.println("TVS dialog DISPOSED");
unregisterDialogFromMonitor();
}
});
@ -470,7 +454,6 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
shell.addShellListener(new ShellAdapter() {
@Override
public void shellClosed(ShellEvent e) {
System.out.println("TVS dialog SHELL CLOSED");
unregisterDialogFromMonitor();
}
});
@ -496,35 +479,47 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
@Override
public void notify(IMonitorEvent me) {
if (me.getSource() instanceof IMonitor) {
// System.out.println("SCAN TVS Table Notify Event Received");
ScanMonitor scan = (ScanMonitor) me.getSource();
Date time = null;
try {
if (getLinkToFrame(scanTable.name())) {
time = scan.getScanTime(scanTable, site);
} else {
time = scan.getMostRecent(scan, scanTable.name(), site)
.getRefTime();
}
} catch (Exception e) {
}
if (time != null && !scanTableComp.isDisposed()) {
ScanDataGenerator sdg = new ScanDataGenerator(site);
scanTableComp.setTableData(sdg.generateTVSData(scan
.getTableData(ScanTables.TVS, site, time)));
setShellText();
// If scan is null or the scan table has been disposed then return
// since nothing will be done.
if (scan == null || scanTableComp.isDisposed()) {
return;
}
Date time = getScanTime(scan);
if (time != null) {
if (getLinkToFrame(scanTable.name())) {
currentTime = scan.getDialogTime(scanTable, site);
updateTimeLabel();
updateTable(scan, time);
} else {
currentTime = time;
if (currentTime == null || !currentTime.equals(time)) {
currentTime = time;
updateTimeLabel();
updateTable(scan, time);
}
}
updateTimeLabel();
// System.out.println("SCAN TVS Table Updated Time Label");
}
}
}
/**
* Update the table with new data.
*
* @param scan
* Scan Monitor.
* @param time
* New time.
*/
private void updateTable(ScanMonitor scan, Date time) {
ScanDataGenerator sdg = new ScanDataGenerator(site);
scanTableComp.setTableData(sdg.generateTVSData(scan.getTableData(
ScanTables.TVS, site, time)));
}
@Override
public void centerByIdent(String ident) {
fireRecenter(ident, ScanTables.TVS, site);
@ -590,9 +585,11 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
// NOT USED
}
/*
* Update the threshold in the composite contained in this dialog for the
* desired attribute in the dialog.
*/
@Override
// Update the threshold in the composite contained in this dialog for the
// desired attribute in the dialog.
public void updateThresh(String attr) {
this.scanTableComp.updateThresholds(attr);
}
@ -610,13 +607,13 @@ public class SCANTvsTableDlg extends AbstractTableDlg implements
return false;
}
@Override
public void turnOffAlarm() {
mgr.setRing(false);
}
@Override
public void turnOffAlarm() {
mgr.setRing(false);
}
@Override
public void turnOnAlarm() {
mgr.setRing(true);
}
@Override
public void turnOnAlarm() {
mgr.setRing(true);
}
}

View file

@ -61,6 +61,8 @@ import com.vividsolutions.jts.geom.Coordinate;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Dec 6, 2011 bsteffen Initial creation
* May 02, 2013 1949 bsteffen Switch Product Browser from uengine to
* DbQueryRequest.
*
* </pre>
*
@ -91,7 +93,7 @@ public class CrimssDataDefinition
@Override
protected String[] queryData(String param,
HashMap<String, RequestConstraint> queryList) {
Map<String, RequestConstraint> queryList) {
if (param.equals(POINT)) {
// TODO depending on how much data we have this might be way too
// data to request.

View file

@ -25,7 +25,6 @@ Export-Package: com.raytheon.uf.viz.productbrowser;
com.raytheon.uf.viz.productbrowser.actions;uses:="org.eclipse.core.commands",
com.raytheon.uf.viz.productbrowser.bookmarks,
com.raytheon.uf.viz.productbrowser.xml
Import-Package: com.raytheon.edex.scriptfactory,
Import-Package: com.raytheon.uf.common.dataplugin,
com.raytheon.uf.common.message.response,
com.raytheon.uf.common.serialization,
com.raytheon.uf.viz.core.catalog
com.raytheon.uf.common.serialization

View file

@ -31,27 +31,29 @@ import javax.xml.bind.annotation.XmlAccessorType;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
import com.raytheon.uf.common.serialization.ISerializableObject;
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.viz.core.DescriptorMap;
import com.raytheon.uf.viz.core.IDisplayPaneContainer;
import com.raytheon.uf.viz.core.catalog.CatalogQuery;
import com.raytheon.uf.viz.core.catalog.DbQuery;
import com.raytheon.uf.viz.core.RecordFactory;
import com.raytheon.uf.viz.core.drawables.AbstractRenderableDisplay;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.ResourcePair;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.map.MapDescriptor;
import com.raytheon.uf.viz.core.procedures.Bundle;
import com.raytheon.uf.viz.core.requests.ThriftClient;
import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData;
import com.raytheon.uf.viz.core.rsc.ResourceProperties;
import com.raytheon.uf.viz.core.rsc.ResourceType;
import com.raytheon.uf.viz.productbrowser.ProductBrowserPreference.PreferenceType;
import com.raytheon.viz.ui.EditorUtil;
import com.raytheon.viz.ui.BundleProductLoader;
import com.raytheon.viz.ui.EditorUtil;
import com.raytheon.viz.ui.VizWorkbenchManager;
import com.raytheon.viz.ui.editor.AbstractEditor;
import com.raytheon.viz.ui.perspectives.AbstractVizPerspectiveManager;
@ -66,6 +68,8 @@ import com.raytheon.viz.ui.perspectives.VizPerspectiveListener;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 3, 2010 mnash Initial creation
* May 02, 2013 1949 bsteffen Switch Product Browser from uengine to
* DbQueryRequest.
*
* </pre>
*
@ -103,23 +107,23 @@ public abstract class AbstractRequestableProductBrowserDataDefinition<T extends
if (!isEnabled()) {
return null;
}
List<Object[]> parameters = null;
Object[] parameters = null;
if (order.length >= 1) {
try {
DbQuery query = new DbQuery(productName);
query.setMaxResults(1);
parameters = query.performQuery();
DbQueryRequest request = new DbQueryRequest();
request.setEntityClass(RecordFactory.getInstance()
.getPluginClass(productName));
request.setLimit(1);
DbQueryResponse response = (DbQueryResponse) ThriftClient
.sendRequest(request);
parameters = response.getEntityObjects(Object.class);
} catch (VizException e) {
statusHandler.handle(Priority.ERROR,
"Unable to populate initial product tree", e);
}
if (parameters != null && !parameters.isEmpty()) {
if (parameters.get(0).length > 0) {
return displayName;
} else {
return null;
}
if (parameters != null && parameters.length != 0) {
return displayName;
} else {
return null;
}
@ -172,9 +176,26 @@ public abstract class AbstractRequestableProductBrowserDataDefinition<T extends
* @return
*/
protected String[] queryData(String param,
HashMap<String, RequestConstraint> queryList) {
Map<String, RequestConstraint> queryList) {
try {
return CatalogQuery.performQuery(param, queryList);
DbQueryRequest request = new DbQueryRequest();
request.setEntityClass(RecordFactory.getInstance().getPluginClass(
productName));
request.setConstraints(queryList);
request.addRequestField(param);
request.setDistinct(true);
DbQueryResponse response = (DbQueryResponse) ThriftClient
.sendRequest(request);
Object[] paramObjs = response.getFieldObjects(param, Object.class);
if (paramObjs != null) {
String[] params = new String[paramObjs.length];
for (int i = 0; i < params.length; i += 1) {
if (paramObjs[i] != null) {
params[i] = paramObjs[i].toString();
}
}
return params;
}
} catch (VizException e) {
statusHandler
.handle(Priority.PROBLEM, "Unable to perform query", e);
@ -238,16 +259,14 @@ public abstract class AbstractRequestableProductBrowserDataDefinition<T extends
RequestConstraint contstraint = new RequestConstraint(productName);
queryList.put(PLUGIN_NAME, contstraint);
for (int i = 0; i < order.length; i++) {
try {
String[] items = CatalogQuery.performQuery(order[i], queryList);
String[] items = queryData(order[i], queryList);
if (items != null) {
List<ProductBrowserLabel> labels = formatData(order[i], items);
if (labels != null) {
for (int j = 0; j < labels.size(); j++) {
historyList.add(labels.get(j).getName());
}
}
} catch (VizException e) {
e.printStackTrace();
}
}
return historyList;

View file

@ -79,6 +79,8 @@ import com.raytheon.uf.viz.productbrowser.xml.ProductBrowserBookmarksXML;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 3, 2010 mnash Initial creation
* May 02, 2013 1949 bsteffen Switch Product Browser from uengine to
* DbQueryRequest.
*
* </pre>
*
@ -141,7 +143,7 @@ public class ProductBrowserView extends ViewPart {
// createBookmarkTreeContextMenu();
createProductTree(fullComp);
createProductBrowserContextMenu();
createSearchBar(fullComp);
// createSearchBar(fullComp);
}
/**

View file

@ -27,6 +27,7 @@ import java.util.List;
import javax.xml.bind.JAXBException;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.application.WorkbenchAdvisor;
import org.osgi.framework.Bundle;
@ -67,7 +68,8 @@ import com.raytheon.viz.ui.personalities.awips.CAVE;
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 4, 2011 njensen Initial creation
* Aug 4, 2011 njensen Initial creation
* Apr 23, 2013 1939 randerso Return null from initializeSerialization
*
* </pre>
*
@ -192,6 +194,7 @@ public class ThinClientComponent extends CAVE implements IThinClientComponent {
}
}
@Override
public void stopComponent() {
// Persist caches
cacheManager.storeCaches();
@ -201,13 +204,15 @@ public class ThinClientComponent extends CAVE implements IThinClientComponent {
}
@Override
protected void initializeSerialization() {
protected Job initializeSerialization() {
try {
SerializationUtil.getJaxbContext();
} catch (JAXBException e) {
statusHandler.handle(Priority.CRITICAL,
"An error occured initializing Serialization", e);
}
return null;
}
}

View file

@ -24,7 +24,6 @@ import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.media.opengl.GL;
@ -48,7 +47,8 @@ import com.vividsolutions.jts.geom.LineString;
/**
*
* TODO Add Description
* Provides base implementation of shaded shapes in openGL that can be easily
* extended to implement IShadedShape or IColormapShadedShape.
*
* <pre>
*
@ -57,6 +57,8 @@ import com.vividsolutions.jts.geom.LineString;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 3, 2011 bsteffen Initial creation
* Apr 25, 2013 1954 bsteffen Speed up creation of
* GLColormapShadedShapes.
*
* </pre>
*
@ -116,32 +118,22 @@ public class GLShadedShapeBase implements IShape {
for (int i = 0; i < lineString.length; i++) {
buffers[i] = FloatBuffer.allocate(lineString[i].getNumPoints() * 2);
for (Coordinate c : lineString[i].getCoordinates()) {
double[] loc = { c.x, c.y };
loc = worldToPixel(loc);
buffers[i].put((float) loc[0]);
buffers[i].put((float) loc[1]);
buffers[i].put((float) c.x);
buffers[i].put((float) c.y);
numVertices += 1;
}
try {
float[] array = buffers[i].array();
worldToPixel.transform(array, 0, array, 0,
lineString[i].getNumPoints());
} catch (TransformException e) {
// Ignore...
}
numContours += 1;
}
polygons.add(buffers);
}
protected double[] worldToPixel(double[] world) {
if (worldToPixel != null) {
try {
double[] out = new double[world.length];
worldToPixel.transform(world, 0, out, 0, 1);
return out;
} catch (TransformException e) {
// Ignore...
}
return null;
} else {
return Arrays.copyOf(world, world.length);
}
}
public synchronized void addPolygonPixelSpace(LineString[] contours) {
FloatBuffer[] buffers = new FloatBuffer[contours.length];
for (int i = 0; i < contours.length; i++) {
@ -239,10 +231,10 @@ public class GLShadedShapeBase implements IShape {
if (tessellate) {
// This over allocates to avoid future resizing
if (vertexBuffer == null) {
vertexBuffer = FloatBuffer.allocate(numVertices * 2);
vertexBuffer = FloatBuffer.allocate(numVertices * 2 * 3);
} else {
FloatBuffer vertexBuffer = FloatBuffer.allocate(numVertices * 2
+ this.vertexBuffer.capacity());
* 3 + this.vertexBuffer.capacity());
this.vertexBuffer.rewind();
vertexBuffer.put(this.vertexBuffer);
this.vertexBuffer = vertexBuffer;

View file

@ -37,9 +37,7 @@ 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.common.time.TimeRange;
import com.raytheon.viz.gfe.Activator;
import com.raytheon.viz.gfe.GFEServerException;
import com.raytheon.viz.gfe.constants.StatusConstants;
import com.raytheon.viz.gfe.core.DataManager;
import com.raytheon.viz.gfe.core.IParmManager;
import com.raytheon.viz.gfe.core.internal.IFPClient;
@ -54,14 +52,15 @@ import com.raytheon.viz.gfe.core.parm.Parm;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 10, 2010 #4475 randerso Initial creation
*
* May 02, 2013 1949 rjpeter Change ServerResponse return type.
* </pre>
*
* @author randerso
* @version 1.0
*/
public class ClearPracticeGrids extends AbstractHandler {
private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(ClearPracticeGrids.class);
private static final transient IUFStatusHandler statusHandler = UFStatus
.getHandler(ClearPracticeGrids.class);
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
@ -97,16 +96,15 @@ public class ClearPracticeGrids extends AbstractHandler {
ServerResponse<List<LockTable>> sr = client
.requestLockChange(lreq);
if (!sr.isOkay()) {
ArrayList<ServerMsg> messages = sr
.getMessages();
List<ServerMsg> messages = sr.getMessages();
StringBuilder msg = new StringBuilder(
"Error attempting to remove locks.");
for (ServerMsg serverMsg : messages) {
msg.append("\n").append(
serverMsg.getMessage());
}
statusHandler.handle(Priority.PROBLEM, msg
.toString());
statusHandler.handle(Priority.PROBLEM,
msg.toString());
}
}
@ -121,8 +119,8 @@ public class ClearPracticeGrids extends AbstractHandler {
"Prac_Fcst database has been cleared.");
} catch (GFEServerException e) {
statusHandler.handle(
Priority.PROBLEM,
statusHandler
.handle(Priority.PROBLEM,
"Unexpected exception while attempting to clear practice grids",
e);
}

View file

@ -25,17 +25,23 @@ import org.eclipse.core.commands.ExecutionException;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import com.raytheon.viz.gfe.core.DataManager;
import com.raytheon.viz.gfe.core.DataManagerUIFactory;
import com.raytheon.viz.gfe.dialogs.FormatterLauncherDialog;
/**
* TODO Add Description FormatterlauncherAction.java Apr 11, 2008
* Displays Formatter Launcher dialog.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 11, 2008 Eric Babin Initial Creation
* Oct 23, 2012 1287 rferrel Changes for non-blocking FormatterLauncherDialog.
* Apr 11, 2008 ebabin Initial creation
* Oct 23, 2012 1287 rferrel Changes for non-blocking FormatterLauncherDialog.
* Apr 24, 2013 1936 dgilling Pass DataManager to
* FormatterLauncherDialog via constructor.
*
* </pre>
*
@ -60,7 +66,8 @@ public class FormatterlauncherAction extends AbstractHandler {
if (dialog == null || dialog.getShell() == null || dialog.isDisposed()) {
Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getShell();
dialog = new FormatterLauncherDialog(shell);
DataManager dm = DataManagerUIFactory.getCurrentInstance();
dialog = new FormatterLauncherDialog(shell, dm);
dialog.setBlockOnOpen(false);
dialog.open();
} else {

View file

@ -74,6 +74,7 @@ import com.raytheon.viz.gfe.smarttool.EditActionProcessor;
import com.raytheon.viz.gfe.smarttool.GridCycler;
import com.raytheon.viz.gfe.smarttool.script.SmartToolFactory;
import com.raytheon.viz.gfe.smarttool.script.SmartToolUIController;
import com.raytheon.viz.gfe.textformatter.TextProductManager;
/**
* DataManager is the central singleton in GFE upon which other managers are
@ -93,6 +94,8 @@ import com.raytheon.viz.gfe.smarttool.script.SmartToolUIController;
* 02/15/2013 1507 dgilling Force procedureInterface and
* smartToolInterface to be
* initialized by constructor.
* 04/24/2013 1936 dgilling Move initialization of TextProductMgr
* to GFE startup.
*
* </pre>
*
@ -159,6 +162,8 @@ public class DataManager {
private ProcedureUIController procedureInterface;
private TextProductManager textProductMgr;
private IToolController itoolInterface;
private EditActionProcessor editActionProcessor;
@ -507,6 +512,8 @@ public class DataManager {
statusHandler.handle(Priority.PROBLEM,
"Error initializing smart tool interface", e);
}
DataManager.this.textProductMgr = new TextProductManager();
}
});
}
@ -685,4 +692,8 @@ public class DataManager {
return initStatus;
}
public TextProductManager getTextProductMgr() {
return textProductMgr;
}
}

View file

@ -69,6 +69,8 @@ import com.vividsolutions.jts.geom.Coordinate;
* 02/19/2013 1637 randerso Added throws declarations to translateDataFrom
* 04/15/2013 1892 randerso Adding logging to help determine what is different in the gridInfos
* Changed how gridInfo is retrieved which seems to have fixed the problem
* 04/23/2013 1949 rjpeter Removed validation on copy, source is verified on store.
* </pre>
*
* @author chammack
@ -307,14 +309,6 @@ public abstract class AbstractGridData implements IGridData {
public boolean copyGridValues(final IGridData sourceGrid) {
populate();
// ensure valid data in the source before attempting a copy
if (!sourceGrid.isValid()) {
statusHandler.handle(Priority.PROBLEM,
"Attempt to copyGridValues from invalid grid on "
+ getParm().getParmID());
return false;
}
// validate data type
if (sourceGrid.getParm().getGridInfo().getGridType() != getParm()
.getGridInfo().getGridType()) {
@ -326,7 +320,6 @@ public abstract class AbstractGridData implements IGridData {
}
// validate units same or can be converted
if (!getParm()
.getGridInfo()
.getUnitObject()
@ -413,16 +406,16 @@ public abstract class AbstractGridData implements IGridData {
ArrayList<GridDataHistory> thisGDHA = new ArrayList<GridDataHistory>();
// add one by one to eliminate any duplicates
for (int i = 0; i < history.length; i++) {
for (GridDataHistory element : history) {
boolean found = false;
for (GridDataHistory thisGDH : thisGDHA) {
if (history[i].equals(thisGDH)) {
if (element.equals(thisGDH)) {
found = true;
break;
}
}
if (!found) {
thisGDHA.add(history[i]);
thisGDHA.add(element);
}
}
this.gridSlice.setHistory(thisGDHA
@ -567,8 +560,8 @@ public abstract class AbstractGridData implements IGridData {
// If we've left the area, we're all done
int x = (int) (pos.x + 0.5); // round off
int y = (int) (pos.y + 0.5); // round off
if (x >= area.getXdim() || y >= area.getYdim()
|| area.get(x, y) != 1) {
if ((x >= area.getXdim()) || (y >= area.getYdim())
|| (area.get(x, y) != 1)) {
// We're either off the grid or out of the area
edge.x = x;
edge.y = y;
@ -654,7 +647,7 @@ public abstract class AbstractGridData implements IGridData {
for (int i = ll.x; i <= ur.x; i++) {
for (int j = ll.y; j <= ur.y; j++) {
if (points.get(i, j) > 0) {
if (i == 0 || i == xMax || j == 0 || j == yMax) {
if ((i == 0) || (i == xMax) || (j == 0) || (j == yMax)) {
edge.set(i, j);
} else {
for (int k = i - 1; k <= i + 1; k++) {
@ -729,7 +722,8 @@ public abstract class AbstractGridData implements IGridData {
Point p = new Point((int) thisCoord.x, (int) thisCoord.y);
// if point is in the grid
if (p.x >= 0 && p.x < gridSize.x && p.y >= 0 && p.y < gridSize.y) {
if ((p.x >= 0) && (p.x < gridSize.x) && (p.y >= 0)
&& (p.y < gridSize.y)) {
gridCoords.add(p);
}
}
@ -890,8 +884,8 @@ public abstract class AbstractGridData implements IGridData {
public List<String> getHistorySites() {
GridDataHistory[] h = this.getHistory();
List<String> sites = new ArrayList<String>();
for (int i = 0; i < h.length; i++) {
String site = h[i].getOriginParm().getDbId().getSiteId();
for (GridDataHistory element : h) {
String site = element.getOriginParm().getDbId().getSiteId();
if (!sites.contains(site)) {
sites.add(site);
}

View file

@ -82,7 +82,7 @@ import com.raytheon.viz.gfe.core.griddata.IGridData;
* 01/21/12 #1504 randerso Cleaned up old debug logging to improve performance
* 02/12/13 #1597 randerso Made save threshold a configurable value. Added detailed
* logging for save performance
*
* 04/23/13 #1949 rjpeter Added logging of number of records.
* </pre>
*
* @author chammack
@ -120,7 +120,8 @@ public class DbParm extends Parm {
}
}
if (this.dataManager != null && this.dataManager.getClient() != null) {
if ((this.dataManager != null)
&& (this.dataManager.getClient() != null)) {
this.lockTable = this.dataManager.getClient().getLockTable(
this.getParmID());
}
@ -222,7 +223,7 @@ public class DbParm extends Parm {
.getGridHistory(getParmID(), gridTimes);
histories = (Map<TimeRange, List<GridDataHistory>>) sr
.getPayload();
if (!sr.isOkay() || histories.size() != gridTimes.size()) {
if (!sr.isOkay() || (histories.size() != gridTimes.size())) {
statusHandler.handle(Priority.PROBLEM,
"Unable to retrieve gridded data [history] for "
+ getParmID() + sr);
@ -456,13 +457,13 @@ public class DbParm extends Parm {
IGridData[] grids = this.getGridInventory(tr);
// if only a single unmodified grid exactly matches the time range
if (grids.length == 1 && !this.isLocked(tr)
if ((grids.length == 1) && !this.isLocked(tr)
&& grids[0].getGridTime().equals(tr)) {
List<GridDataHistory> newHist = histories.get(tr);
GridDataHistory[] currentHist = grids[0].getHistory();
// if current history exists and has a matching update time
if (currentHist != null
if ((currentHist != null)
&& currentHist[0].getUpdateTime().equals(
newHist.get(0).getUpdateTime())) {
// update last sent time
@ -495,7 +496,7 @@ public class DbParm extends Parm {
}
timer.stop();
perfLog.logDuration("Server lock change for " + this.getParmID() + " "
+ lreq.size() + " time rangess", timer.getElapsedTime());
+ lreq.size() + " time ranges", timer.getElapsedTime());
timer.reset();
timer.start();
@ -565,7 +566,9 @@ public class DbParm extends Parm {
int gridCount = 0;
int totalGrids = 0;
long totalSize = 0;
int totalRecords = 0;
long size = 0;
int recordCount = 0;
for (int i = 0; i < trs.size(); i++) {
// ensure we have a lock for the time period
TimeRange lockTime = new TimeRange();
@ -629,6 +632,7 @@ public class DbParm extends Parm {
}
totalGrids += gridCount;
totalRecords += records.size();
totalSize += size;
pendingUnlocks.clear();
@ -641,9 +645,10 @@ public class DbParm extends Parm {
}
// if any grids or any time not saved
if (size > 0 || saveTime.getDuration() > 0) {
if ((size > 0) || (saveTime.getDuration() > 0)) {
sgr.add(new SaveGridRequest(getParmID(), saveTime, records,
dataManager.clientISCSendStatus()));
recordCount = records.size();
}
// if we haven't had a failure yet add to pending locks
@ -666,6 +671,7 @@ public class DbParm extends Parm {
totalSize += size;
totalGrids += gridCount;
totalRecords += recordCount;
pendingUnlocks.clear();
}
@ -685,8 +691,8 @@ public class DbParm extends Parm {
timer.stop();
perfLog.logDuration("Save Grids " + getParmID().getParmName() + ": "
+ totalGrids + " grids (" + totalSize + " bytes) ",
timer.getElapsedTime());
+ totalRecords + " records, " + totalGrids + " grids ("
+ totalSize + " bytes) ", timer.getElapsedTime());
return success;
}

View file

@ -143,7 +143,7 @@ public class VParm extends Parm {
@Override
public void looseLocks() {
// simply replace the lock table with one without any locks
this.lockTable.setLocks(new ArrayList<Lock>());
this.lockTable.setLocks(new ArrayList<Lock>(0));
}
}

View file

@ -92,6 +92,9 @@ import com.raytheon.viz.ui.dialogs.ICloseCallback;
* Jul 26, 2012 15165 ryu Set default db source when formatter has no db defined.
* Oct 23, 2012 1287 rferrel Changes for non-blocking dialogs and code clean up.
* Nov 08, 2012 1298 rferrel Changes for non-blocking IssuanceSiteIdDlg.
* Apr 24, 2013 1936 dgilling Remove initialization of
* TextProductManager from this class, clean
* up warnings.
*
* </pre>
*
@ -205,6 +208,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
private TextProductManager textProductMgr;
private DataManager dataMgr;
private String selectedDataSource = null;
private boolean doClose = false;
@ -214,12 +219,14 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
*
* @param parent
* Parent Shell.
* @param dataMgr
* DataManager instance.
*/
public FormatterLauncherDialog(Shell parent) {
public FormatterLauncherDialog(Shell parent, DataManager dataMgr) {
super(parent);
setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE | SWT.RESIZE);
textProductMgr = new TextProductManager();
this.dataMgr = dataMgr;
this.textProductMgr = this.dataMgr.getTextProductMgr();
}
@Override
@ -326,10 +333,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
// Create all the items in the Data Source dropdown menu
// ------------------------------------------------------
DataManager dm = DataManager.getCurrentInstance();
// Get the CAVE operating mode
CAVEMode mode = dm.getOpMode();
CAVEMode mode = dataMgr.getOpMode();
// Forecast menu item, set text based on operating mode
fcstMI = new MenuItem(dataSourceMenu, SWT.RADIO);
@ -345,8 +350,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
fcstMI.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent event) {
selectedDataSource = DataManager.getCurrentInstance()
.getParmManager().getMutableDatabase().toString();
selectedDataSource = dataMgr.getParmManager()
.getMutableDatabase().toString();
}
});
@ -382,8 +387,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
}
});
} else {
selectedDataSource = DataManager.getCurrentInstance()
.getParmManager().getMutableDatabase().toString();
selectedDataSource = dataMgr.getParmManager().getMutableDatabase()
.toString();
}
}
@ -735,8 +740,9 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
ProductDefinition prodDef = textProductMgr
.getProductDefinition(productName);
String dataSource = (String) prodDef.get("database");
if (dataSource == null)
if (dataSource == null) {
dataSource = "Official";
}
if (dataSource.equals("ISC")) {
selectedDataSource = getIscDataSource();
@ -787,6 +793,7 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
* @param tabName
* Name of the tab to be removed.
*/
@Override
public void removeProductTab(String tabName) {
TabItem[] items = tabFolder.getItems();
@ -808,6 +815,7 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
* @param tabName
* Name of the tab.
*/
@Override
public void setTabState(ConfigData.productStateEnum state, String tabName) {
TabItem[] items = tabFolder.getItems();
@ -999,8 +1007,7 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
* @return The FcstDataSource
*/
private String getFcstDataSource() {
return DataManager.getCurrentInstance().getParmManager()
.getMutableDatabase().toString();
return dataMgr.getParmManager().getMutableDatabase().toString();
}
/**
@ -1012,8 +1019,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
* @return The ISC Data Source
*/
private String getIscDataSource() {
java.util.List<DatabaseID> dbs = DataManager.getCurrentInstance()
.getParmManager().getIscDatabases();
java.util.List<DatabaseID> dbs = dataMgr.getParmManager()
.getIscDatabases();
if (dbs.size() > 0) {
// Always return the last one in the list
@ -1031,8 +1038,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements
private String getOfficialDataSource() {
String source = null;
try {
ServerResponse<java.util.List<DatabaseID>> sr = DataManager
.getCurrentInstance().getClient().getOfficialDBName();
ServerResponse<java.util.List<DatabaseID>> sr = dataMgr.getClient()
.getOfficialDBName();
source = sr.getPayload().get(0).toString();
} catch (GFEServerException e) {
statusHandler.handle(Priority.PROBLEM,

View file

@ -45,8 +45,6 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.viz.core.VizApp;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.localization.LocalizationManager;
import com.raytheon.viz.gfe.Activator;
import com.raytheon.viz.gfe.constants.StatusConstants;
import com.raytheon.viz.gfe.core.DataManager;
/**
@ -59,6 +57,7 @@ import com.raytheon.viz.gfe.core.DataManager;
* ------------ ---------- ----------- --------------------------
* May 1, 2009 njensen Initial creation
* Jan 15, 2010 3395 ryu Fix &quot;issued by&quot; functionality
* Apr 24, 2013 1936 dgilling Remove unused imports.
*
* </pre>
*
@ -67,7 +66,8 @@ import com.raytheon.viz.gfe.core.DataManager;
*/
public class TextProductManager {
private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(TextProductManager.class);
private static final transient IUFStatusHandler statusHandler = UFStatus
.getHandler(TextProductManager.class);
private String issuedBy = "";
@ -224,8 +224,8 @@ public class TextProductManager {
try {
varDict = (String) script.execute("getVarDict", map);
} catch (JepException e) {
statusHandler.handle(Priority.PROBLEM,
"Exception getting VarDict", e);
statusHandler.handle(Priority.PROBLEM, "Exception getting VarDict",
e);
}
return varDict;

View file

@ -73,6 +73,8 @@ import com.raytheon.viz.grid.rsc.GridResourceData;
* ------------ ---------- ----------- --------------------------
* May 21, 2010 bsteffens Initial creation
* May 26, 2010 mnash Used ProductBrowserLabel implementation instead of requery
* May 02, 2013 1949 bsteffen Switch Product Browser from uengine to
* DbQueryRequest.
*
* </pre>
*
@ -175,7 +177,7 @@ public class GridProductBrowserDataDefinition extends
@Override
protected String[] queryData(String param,
HashMap<String, RequestConstraint> queryList) {
Map<String, RequestConstraint> queryList) {
try {
if (getInventory() == null) {
return super.queryData(param, queryList);

View file

@ -19,9 +19,6 @@
**/
package com.raytheon.viz.hydro.timeseries;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
@ -30,9 +27,8 @@ import org.eclipse.core.runtime.jobs.IJobChangeListener;
import org.eclipse.core.runtime.jobs.Job;
/**
* The TimeSeriesDataJob Manager asynchronously retrieves
* Time Series Graph and Time Series Tabular Data via the
* Eclipse Job capability.
* The TimeSeriesDataJob Manager asynchronously retrieves Time Series Graph and
* Time Series Tabular Data via the Eclipse Job capability.
*
* <pre>
*
@ -40,7 +36,8 @@ import org.eclipse.core.runtime.jobs.Job;
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jan 28, 2011 bkowal Initial creation
* Jan 28, 2011 bkowal Initial creation
* May 06, 2013 1976 mpduff Moved c.getDataForGraph() inside .runasync block
*
* </pre>
*
@ -71,11 +68,12 @@ public class TimeSeriesDataJobManager extends Job {
TimeSeriesDisplayCanvas tsDisplayCanvas = (TimeSeriesDisplayCanvas) this
.getProperty(new QualifiedName(null,
"TimeSeriesDisplayCanvas"));
tsDisplayCanvas.getDataForGraph();
final TimeSeriesDisplayCanvas c = tsDisplayCanvas;
tsDisplayCanvas.getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if(!c.isDisposed()) {
if (!c.isDisposed()) {
c.getDataForGraph();
c.redraw();
}
}

View file

@ -59,7 +59,6 @@ import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.viz.hydro.timeseries.util.GraphData;
import com.raytheon.viz.hydro.timeseries.util.GroupInfo;
import com.raytheon.viz.hydro.timeseries.util.PageInfo;
import com.raytheon.viz.hydro.timeseries.util.TraceData;
import com.raytheon.viz.hydro.util.LoadMaxFcst;
import com.raytheon.viz.hydrocommon.HydroConstants;
import com.raytheon.viz.hydrocommon.data.ForecastData;
@ -94,6 +93,7 @@ import com.raytheon.viz.ui.dialogs.CaveSWTDialog;
* 22 Jan 2013 14903 lbousaidi Fix display error after save to DB.
* 30 Jan 2012 15459 mpduff Redmine 1560 - Make graph canvases redraw on page up/down.
* 06 Feb 2013 1578 rferrel Code cleanup for non-blocking dialogs.
* 24 Apr 2013 1921 mpduff Fix zoom reset to only reset the "active" graph
*
* </pre>
*
@ -393,6 +393,11 @@ public class TimeSeriesDisplayDlg extends CaveSWTDialog {
*/
private boolean reset = false;
/**
* The selected graph canvas.
*/
private TimeSeriesDisplayCanvas selectedCanvas;
/**
* Constructor.
*
@ -995,10 +1000,9 @@ public class TimeSeriesDisplayDlg extends CaveSWTDialog {
setZoomAction(false);
setSelectZoom(false);
reset = true;
for (TimeSeriesDisplayCanvas dc : canvasList) {
dc.setZoomed(false);
dc.redraw();
}
selectedCanvas.setZoomed(false);
selectedCanvas.redraw();
reset = false;
} else {
displayCanvas.resetTS();
}
@ -1356,7 +1360,6 @@ public class TimeSeriesDisplayDlg extends CaveSWTDialog {
String showCat = AppsDefaults.getInstance().getToken(
"timeseries_showcat");
int sc = Integer.parseInt(showCat);
System.out.println(showCat);
if (sc == 1) {
batchDataOnlyShowCatMI.setSelection(false);
batchDataOnlyMI.setSelection(true);
@ -2347,4 +2350,14 @@ public class TimeSeriesDisplayDlg extends CaveSWTDialog {
public boolean isReset() {
return reset;
}
/**
* Set the selected canvas.
*
* @param selectedCanvas
* The selected canvas
*/
public void setSelectedCanvas(TimeSeriesDisplayCanvas selectedCanvas) {
this.selectedCanvas = selectedCanvas;
}
}

View file

@ -120,6 +120,7 @@ import com.raytheon.viz.hydrocommon.util.StnClassSyncUtil;
* despite start up in CAVE or standalone.
* 30 Jan 2013 15264 wkwock Fix the missing group_definition.cfg file crash
* 05 Feb 2013 1578 rferrel Dialog made non-blocking and a singleton.
* 06 May 2013 1976 mpduff Code cleanup.
* </pre>
*
* @author lvenable
@ -127,7 +128,7 @@ import com.raytheon.viz.hydrocommon.util.StnClassSyncUtil;
*
*/
public class TimeSeriesDlg extends CaveHydroSWTDialog {
private static final transient IUFStatusHandler statusHandler = UFStatus
private static final IUFStatusHandler statusHandler = UFStatus
.getHandler(TimeSeriesDlg.class);
/* Constants */
@ -441,27 +442,18 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
private LIDData currLidData = new LIDData();
/** List of GroupInfo objects */
private ArrayList<GroupInfo> groupList = new ArrayList<GroupInfo>();
/** Holds the Group Information */
private GroupInfo groupInfo;
private final ArrayList<GroupInfo> groupList = new ArrayList<GroupInfo>();
/** Holds the last graphed GroupInfo object */
private GroupInfo prevGroupInfo;
/** Holds the page information */
private PageInfo pageInfo = null;
/** Holds the graph information */
private GraphData graphData = null;
private String groupConfigFilePath = null;
private ArrayList<SiteInfo> siteInfoList = new ArrayList<SiteInfo>();
private final ArrayList<SiteInfo> siteInfoList = new ArrayList<SiteInfo>();
private ArrayList<TabInfo> tabInfoList = new ArrayList<TabInfo>();
private final ArrayList<TabInfo> tabInfoList = new ArrayList<TabInfo>();
private HydroDisplayManager displayManager;
private final HydroDisplayManager displayManager;
private boolean openTimeSeriesDisplays = false;
@ -662,7 +654,7 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
font = new Font(shell.getDisplay(), "Monospace", 11, SWT.NORMAL);
// Initialize all of the controls and layoutsendCal
// Initialize all of the controls
initializeComponents();
setCurrentData();
}
@ -1097,7 +1089,6 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
public void keyReleased(KeyEvent event) {
String search = searchTF.getText();
if (!search.equals("") && !search.equals(" ")) {
/* Iterate over the location Ids in the list */
ListIterator<String> iter = lidList.listIterator();
while (iter.hasNext()) {
@ -1119,10 +1110,8 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
}
}
}
} else {
// topDataList.setSelection(0); // Commented to more closely
// match legacy app
}
if (topDataList.getSelectionIndex() > 0) {
populateBottomList(
lidList.get(topDataList.getSelectionIndex()),
@ -1276,6 +1265,7 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
bottomDataList.setLayoutData(gd);
bottomDataList.setFont(font);
bottomDataList.addListener(SWT.Selection, new Listener() {
@Override
public void handleEvent(Event e) {
correctSelections();
}
@ -1532,7 +1522,6 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
si.setTs((String) row[2]);
si.setExt((String) row[3]);
si.setDur((Integer) row[4]);
// siteInfoList.add(si);
if (si.getPe().startsWith("H")) {
if (!si.getPe().equals(prevPE)) {
@ -1617,6 +1606,14 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
} else {
this.populateGroupListForStandalone();
}
for (GroupInfo gi : this.groupList) {
for (PageInfo pi : gi.getPageInfoList()) {
for (GraphData gd : pi.getGraphDataList()) {
gd.saveTraceInfo();
}
}
}
}
/**
@ -1644,7 +1641,6 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
groupDataList.removeAll();
if (this.groupConfigFilePath != null) {
this.readGroupList();
}
}
@ -1653,6 +1649,10 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
* Read the Group List file.
*/
private void readGroupList() {
GroupInfo groupInfo = null;
PageInfo pageInfo = null;
GraphData graphData = null;
try {
BufferedReader in = new BufferedReader(new FileReader(
groupConfigFilePath));
@ -1664,7 +1664,148 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
if (str.trim().equals("")) {
continue;
}
processGroupData(str);
boolean showpp_flag = false;
// Remove any leading whitespace
String line = str.replaceAll("^\\s+", "");
if (line.startsWith(GROUP)) {
groupInfo = new GroupInfo();
groupInfo.setGroupSelected(true);
groupList.add(groupInfo);
}
String[] parts = line.split(":");
if (parts[0].equals(GROUP)) {
String[] pairs = parts[1].split(",");
for (String s : pairs) {
String[] values = s.split("=", 2);
// make sure we have values to go with the key
if (values.length > 1) {
if ((values[0] != null)
&& values[0].equalsIgnoreCase(NAME)) {
if (values[1] != null)
groupInfo.setGroupName(values[1]);
groupDataList.add(groupInfo.getGroupName());
} else if (values[0].equalsIgnoreCase(DESCRIPT)) {
groupInfo.setDescription(values[1]);
} else if (values[0].equalsIgnoreCase(GRID)) {
if (values[1].equalsIgnoreCase("T")) {
groupInfo.setGridLines(true);
} else {
groupInfo.setGridLines(false);
}
} else if (values[0].equalsIgnoreCase(TRACEMODE)) {
groupInfo.setTraceMode(values[1]);
} else if (values[0].equalsIgnoreCase(PASTHOURS)) {
groupInfo.setPastHours(Integer
.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(FUTUREHOURS)) {
groupInfo.setFutureHours(Integer
.parseInt(values[1]));
} else {
statusHandler.warn("Invalid key/value pair: "
+ s);
}
}
}
} else if (parts[0].equals(PAGE)) {
String[] values = parts[1].split("=", 2);
if (values.length > 1) {
pageInfo = new PageInfo();
pageInfo.setTitle(values[1]);
groupInfo.addPageInfo(pageInfo);
}
} else if (parts[0].equals(GRAPH)) {
graphData = new GraphData();
String[] pairs = parts[1].split(",");
for (String s : pairs) {
String[] values = s.split("=", 2);
if (values.length > 1) {
if (values[0].equalsIgnoreCase(POS)) {
graphData.setGraph_pos(Integer
.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(XSIZE)) {
graphData.setXsize(Integer.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(YSIZE)) {
graphData.setYsize(Integer.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(YLINEAR)) {
graphData.setYlinear(values[1]);
} else if (values[0].equalsIgnoreCase(YSCALE)) {
graphData.setYscale(values[1]);
} else if (values[0].equalsIgnoreCase(SHOWCAT)) {
if (values[1].equalsIgnoreCase("T")) {
graphData.setShowcat(true);
} else {
graphData.setShowcat(false);
}
} else if (values[0].equalsIgnoreCase(DERIVEPP)) {
graphData.setDerivepp(values[1]);
} else if (values[0].equalsIgnoreCase(SHOWPP)) {
if (values[1].equalsIgnoreCase("T")) {
showpp_flag = true;
} else {
showpp_flag = false;
}
} else if (values[0]
.equalsIgnoreCase(LATESTFCSTONLY)) {
if (values[1].equalsIgnoreCase("T")) {
graphData.setLatestfcstonly(true);
} else {
graphData.setLatestfcstonly(false);
}
} else {
statusHandler.warn("Invalid key/value pair: "
+ s);
}
}
}
// handle the case where there isn't a page element when
// there should be
if (pageInfo == null) {
pageInfo = new PageInfo();
groupInfo.addPageInfo(pageInfo);
}
pageInfo.addGraphData(graphData);
} else if (parts[0].equals(TRACE)) {
TraceData td = new TraceData();
String[] pairs = parts[1].split(",");
for (String s : pairs) {
String[] values = s.split("=", 2);
if (values.length > 1) {
if (values[0].equalsIgnoreCase(STN)) {
td.setLid(values[1]);
} else if (values[0]
.equalsIgnoreCase(HydroConstants.PC)) {
td.setPc(values[1]);
if (showpp_flag == true)
graphData.setShowpp(true);
else
graphData.setShowpp(false);
} else if (values[0].equalsIgnoreCase(COLOR)) {
td.setColorName(values[1]);
}
}
}
graphData.addTrace(td);
graphData.setBeginDate(beginDate);
graphData.setEndDate(endDate);
} else {
statusHandler
.warn("Error in Group Definition Config file: "
+ line);
}
// select the first item in the list
if (groupDataList.getItemCount() > 0) {
groupDataList.select(0);
}
}
in.close();
} catch (IOException e) {
@ -1831,7 +1972,7 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
}
}
// Reset the siteInfoList selections
// Reset the selections
int selectedIndex = bottomDataList.getSelectionIndex();
for (int i = 0; i < siteInfoList.size(); i++) {
@ -1893,144 +2034,6 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
timeSeriesDisplayDlg.getShell().moveAbove(this.shell);
}
/**
* Process the lines in the group config file.
*
* @param line
*/
private void processGroupData(String line) {
Boolean showpp_flag = false;
// Remove any leading whitespace
line = line.replaceAll("^\\s+", "");
if (line.startsWith(GROUP)) {
groupInfo = new GroupInfo();
groupInfo.setGroupSelected(true);
groupList.add(groupInfo);
}
String[] parts = line.split(":");
if (parts[0].equals(GROUP)) {
String[] pairs = parts[1].split(",");
for (String s : pairs) {
String[] values = s.split("=", 2);
// make sure we have values to go with the key
if (values.length > 1) {
if ((values[0] != null) && values[0].equalsIgnoreCase(NAME)) {
if (values[1] != null)
groupInfo.setGroupName(values[1]);
groupDataList.add(groupInfo.getGroupName());
} else if (values[0].equalsIgnoreCase(DESCRIPT)) {
groupInfo.setDescription(values[1]);
} else if (values[0].equalsIgnoreCase(GRID)) {
if (values[1].equalsIgnoreCase("T")) {
groupInfo.setGridLines(true);
} else {
groupInfo.setGridLines(false);
}
} else if (values[0].equalsIgnoreCase(TRACEMODE)) {
groupInfo.setTraceMode(values[1]);
} else if (values[0].equalsIgnoreCase(PASTHOURS)) {
groupInfo.setPastHours(Integer.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(FUTUREHOURS)) {
groupInfo.setFutureHours(Integer.parseInt(values[1]));
} else {
statusHandler.warn("Invalid key/value pair: " + s);
}
}
}
} else if (parts[0].equals(PAGE)) {
String[] values = parts[1].split("=", 2);
if (values.length > 1) {
pageInfo = new PageInfo();
pageInfo.setTitle(values[1]);
groupInfo.addPageInfo(pageInfo);
}
} else if (parts[0].equals(GRAPH)) {
graphData = new GraphData();
String[] pairs = parts[1].split(",");
for (String s : pairs) {
String[] values = s.split("=", 2);
if (values.length > 1) {
if (values[0].equalsIgnoreCase(POS)) {
graphData.setGraph_pos(Integer.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(XSIZE)) {
graphData.setXsize(Integer.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(YSIZE)) {
graphData.setYsize(Integer.parseInt(values[1]));
} else if (values[0].equalsIgnoreCase(YLINEAR)) {
graphData.setYlinear(values[1]);
} else if (values[0].equalsIgnoreCase(YSCALE)) {
graphData.setYscale(values[1]);
} else if (values[0].equalsIgnoreCase(SHOWCAT)) {
if (values[1].equalsIgnoreCase("T")) {
graphData.setShowcat(true);
} else {
graphData.setShowcat(false);
}
} else if (values[0].equalsIgnoreCase(DERIVEPP)) {
graphData.setDerivepp(values[1]);
} else if (values[0].equalsIgnoreCase(SHOWPP)) {
if (values[1].equalsIgnoreCase("T")) {
showpp_flag = true;
} else {
showpp_flag = false;
}
} else if (values[0].equalsIgnoreCase(LATESTFCSTONLY)) {
if (values[1].equalsIgnoreCase("T")) {
graphData.setLatestfcstonly(true);
} else {
graphData.setLatestfcstonly(false);
}
} else {
statusHandler.warn("Invalid key/value pair: " + s);
}
}
}
// handle the case where there isn't a page element when
// there should be
if (pageInfo == null) {
pageInfo = new PageInfo();
}
pageInfo.addGraphData(graphData);
} else if (parts[0].equals(TRACE)) {
TraceData td = new TraceData();
String[] pairs = parts[1].split(",");
for (String s : pairs) {
String[] values = s.split("=", 2);
if (values.length > 1) {
if (values[0].equalsIgnoreCase(STN)) {
td.setLid(values[1]);
} else if (values[0].equalsIgnoreCase(HydroConstants.PC)) {
td.setPc(values[1]);
if (showpp_flag == true)
graphData.setShowpp(true);
else
graphData.setShowpp(false);
} else if (values[0].equalsIgnoreCase(COLOR)) {
td.setColorName(values[1]);
}
}
}
graphData.addTrace(td);
graphData.setBeginDate(beginDate);
graphData.setEndDate(endDate);
} else {
statusHandler
.warn("Error in Group Definition Config file: " + line);
}
// select the first item in the list
if (groupDataList.getItemCount() > 0) {
groupDataList.select(0);
}
}
/**
* Handle Table option when selected on the Time Series Control Dialog
*/
@ -2062,7 +2065,7 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
/* Set up the GraphData objects */
if (modeCbo.getText().equals(STATION_SELECTION)) {
groupInfo = new GroupInfo();
GroupInfo groupInfo = new GroupInfo();
groupInfo.setCurrentPage(0);
/* Get the data from the station list */
@ -2096,7 +2099,8 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
} else {
/* Set the group info object */
groupInfo = groupList.get(groupDataList.getSelectionIndex());
GroupInfo groupInfo = groupList.get(groupDataList
.getSelectionIndex());
tabularDlg.setGroupInfo(groupInfo);
for (PageInfo pi : groupInfo.getPageInfoList()) {
@ -2151,7 +2155,7 @@ public class TimeSeriesDlg extends CaveHydroSWTDialog {
/* Set up the GraphData objects */
if (modeCbo.getText().equals(STATION_SELECTION)) {
int numberGraphs = 1;
groupInfo = new GroupInfo();
GroupInfo groupInfo = new GroupInfo();
groupInfo.setCurrentPage(0);
/* Get the data from the station list */

View file

@ -21,6 +21,7 @@ package com.raytheon.viz.hydro.timeseries.util;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.raytheon.viz.hydrocommon.HydroConstants;
@ -28,62 +29,68 @@ import com.raytheon.viz.hydrocommon.HydroConstants;
* Object to hold the data and metadata for the time series.
*
* <pre>
*
*
* SOFTWARE HISTORY
*
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jun 24, 2008 mpduff Initial creation
* Jun 24, 2008 mpduff Initial creation.
* May 06, 2013 1976 mpduff Use List interface.
*
* </pre>
*
*
* @author mpduff
* @version 1.0
* @version 1.0
*/
public class GraphData {
public class GraphData {
private double x;
/**
* yMax - yMin
*/
private double y;
private double y2;
/**
* Graph Area Width
*/
private int w;
/**
* Graph Area Height
*/
private int h;
private boolean displayFlowUnit;
private Date xMin;
private Date xMax;
private double ymin = Integer.MAX_VALUE;
private double ymax = Integer.MIN_VALUE;
private double ymin2;
private double ymax2;
/**
* List of traces for graphing
*/
private ArrayList<TraceData> traces = new ArrayList<TraceData>();
private List<TraceData> traces = new ArrayList<TraceData>();
/**
* List of traces for this graphing object
*/
private ArrayList<TraceData> originalTraces = new ArrayList<TraceData>();
private ArrayList<Boolean> isStage = new ArrayList<Boolean>();
private final List<TraceData> originalTraces = new ArrayList<TraceData>();
private List<Boolean> isStage = new ArrayList<Boolean>();
private Date beginDate = null;
private Date endDate = null;
private String title = null;
@ -119,16 +126,25 @@ public class GraphData {
private String showppc = null;
private String latestfcstonlyc = null;
private double actionStage = -9999;
private double floodStage = -9999;
private double minorStage = -9999;
private double moderateStage = -9999;
private double majorStage = -9999;
private double actionFlow = -9999;
private double floodFlow = -9999;
private double minorFlow = -9999;
private double moderateFlow = -9999;
private double majorFlow = -9999;
/**
@ -139,7 +155,8 @@ public class GraphData {
}
/**
* @param x the x to set
* @param x
* the x to set
*/
public void setX(double x) {
this.x = x;
@ -154,7 +171,9 @@ public class GraphData {
/**
* y = yMax - yMin
* @param y the y to set
*
* @param y
* the y to set
*/
public void setY(double y) {
this.y = y;
@ -168,7 +187,8 @@ public class GraphData {
}
/**
* @param w the w to set
* @param w
* the w to set
*/
public void setW(int w) {
this.w = w;
@ -182,7 +202,8 @@ public class GraphData {
}
/**
* @param h the h to set
* @param h
* the h to set
*/
public void setH(int h) {
this.h = h;
@ -203,7 +224,8 @@ public class GraphData {
}
/**
* @param display_flow_unit the display_flow_unit to set
* @param display_flow_unit
* the display_flow_unit to set
*/
public void setDisplayFlowUnit(boolean displayFlowUnit) {
this.displayFlowUnit = displayFlowUnit;
@ -217,7 +239,8 @@ public class GraphData {
}
/**
* @param min the xMin to set
* @param min
* the xMin to set
*/
public void setXMin(Date min) {
xMin = min;
@ -231,68 +254,13 @@ public class GraphData {
}
/**
* @param max the xMax to set
* @param max
* the xMax to set
*/
public void setXMax(Date max) {
xMax = max;
}
// /**
// * @return the oldXMax
// */
// public Date getOldXMax() {
// return oldXMax;
// }
//
// /**
// * @param oldXMax the oldXMax to set
// */
// public void setOldXMax(Date oldXMax) {
// this.oldXMax = oldXMax;
// }
//
// /**
// * @return the oldXMin
// */
// public Date getOldXMin() {
// return oldXMin;
// }
//
// /**
// * @param oldXMin the oldXMin to set
// */
// public void setOldXMin(Date oldXMin) {
// this.oldXMin = oldXMin;
// }
//
// /**
// * @return the orgXMax
// */
// public Date getOrgXMax() {
// return orgXMax;
// }
//
// /**
// * @param orgXMax the orgXMax to set
// */
// public void setOrgXMax(Date orgXMax) {
// this.orgXMax = orgXMax;
// }
//
// /**
// * @return the orgXMin
// */
// public Date getOrgXMin() {
// return orgXMin;
// }
//
// /**
// * @param orgXMin the orgXMin to set
// */
// public void setOrgXMin(Date orgXMin) {
// this.orgXMin = orgXMin;
// }
/**
* @return the ymin
*/
@ -301,7 +269,8 @@ public class GraphData {
}
/**
* @param ymin the ymin to set
* @param ymin
* the ymin to set
*/
public void setYmin(double ymin) {
this.ymin = ymin;
@ -315,7 +284,8 @@ public class GraphData {
}
/**
* @param ymax the ymax to set
* @param ymax
* the ymax to set
*/
public void setYmax(double ymax) {
this.ymax = ymax;
@ -324,21 +294,22 @@ public class GraphData {
/**
* @return the traces
*/
public ArrayList<TraceData> getTraces() {
public List<TraceData> getTraces() {
return traces;
}
public TraceData getTraceData(int index) {
return traces.get(index);
}
/**
* @param traces the traces to set
* @param traces
* the traces to set
*/
public void setTraces(ArrayList<TraceData> traces) {
public void setTraces(List<TraceData> traces) {
this.traces = traces;
}
public void addTrace(TraceData trace) {
if (traces.size() < HydroConstants.MAX_TRACES) {
if (!traces.contains(trace)) {
@ -350,12 +321,13 @@ public class GraphData {
/**
* @return the isStage
*/
public ArrayList<Boolean> getIsStage() {
public List<Boolean> getIsStage() {
return isStage;
}
/**
* @param isStage the isStage to set
* @param isStage
* the isStage to set
*/
public void setIsStage(ArrayList<Boolean> isStage) {
this.isStage = isStage;
@ -364,7 +336,8 @@ public class GraphData {
/**
* Add the isStage boolean value to the list
*
* @param isStage true if value is stage, false otherwise
* @param isStage
* true if value is stage, false otherwise
*/
public void addIsStage(boolean isStage) {
if (traces.size() < HydroConstants.MAX_TRACES) {
@ -380,7 +353,8 @@ public class GraphData {
}
/**
* @param beginCal the beginCal to set
* @param beginCal
* the beginCal to set
*/
public void setBeginDate(Date beginDate) {
this.beginDate = beginDate;
@ -394,7 +368,8 @@ public class GraphData {
}
/**
* @param endCal the endCal to set
* @param endCal
* the endCal to set
*/
public void setEndDate(Date endDate) {
this.endDate = endDate;
@ -408,7 +383,8 @@ public class GraphData {
}
/**
* @param title the title to set
* @param title
* the title to set
*/
public void setTitle(String title) {
this.title = title;
@ -422,7 +398,8 @@ public class GraphData {
}
/**
* @param num_traces the num_traces to set
* @param num_traces
* the num_traces to set
*/
public void setNum_traces(int num_traces) {
this.num_traces = num_traces;
@ -436,7 +413,8 @@ public class GraphData {
}
/**
* @param graph_pos the graph_pos to set
* @param graph_pos
* the graph_pos to set
*/
public void setGraph_pos(int graph_pos) {
this.graph_pos = graph_pos;
@ -450,7 +428,8 @@ public class GraphData {
}
/**
* @param xsize the xsize to set
* @param xsize
* the xsize to set
*/
public void setXsize(int xsize) {
this.xsize = xsize;
@ -464,7 +443,8 @@ public class GraphData {
}
/**
* @param ysize the ysize to set
* @param ysize
* the ysize to set
*/
public void setYsize(int ysize) {
this.ysize = ysize;
@ -478,7 +458,8 @@ public class GraphData {
}
/**
* @param yscale the yscale to set
* @param yscale
* the yscale to set
*/
public void setYscale(String yscale) {
this.yscale = yscale;
@ -492,7 +473,8 @@ public class GraphData {
}
/**
* @param ylinear the ylinear to set
* @param ylinear
* the ylinear to set
*/
public void setYlinear(String ylinear) {
this.ylinear = ylinear;
@ -506,7 +488,8 @@ public class GraphData {
}
/**
* @param showcat the showcat to set
* @param showcat
* the showcat to set
*/
public void setShowcat(boolean showcat) {
this.showcat = showcat;
@ -520,7 +503,8 @@ public class GraphData {
}
/**
* @param derivepp the derivepp to set
* @param derivepp
* the derivepp to set
*/
public void setDerivepp(String derivepp) {
this.derivepp = derivepp;
@ -534,7 +518,8 @@ public class GraphData {
}
/**
* @param showpp the showpp to set
* @param showpp
* the showpp to set
*/
public void setShowpp(boolean showpp) {
this.showpp = showpp;
@ -548,7 +533,8 @@ public class GraphData {
}
/**
* @param latestfcstonly the latestfcstonly to set
* @param latestfcstonly
* the latestfcstonly to set
*/
public void setLatestfcstonly(boolean latestfcstonly) {
this.latestfcstonly = latestfcstonly;
@ -562,7 +548,8 @@ public class GraphData {
}
/**
* @param ylinearc the ylinearc to set
* @param ylinearc
* the ylinearc to set
*/
public void setYlinearc(String ylinearc) {
this.ylinearc = ylinearc;
@ -576,7 +563,8 @@ public class GraphData {
}
/**
* @param yscalec the yscalec to set
* @param yscalec
* the yscalec to set
*/
public void setYscalec(String yscalec) {
this.yscalec = yscalec;
@ -590,7 +578,8 @@ public class GraphData {
}
/**
* @param showcatc the showcatc to set
* @param showcatc
* the showcatc to set
*/
public void setShowcatc(String showcatc) {
this.showcatc = showcatc;
@ -604,7 +593,8 @@ public class GraphData {
}
/**
* @param deriveppc the deriveppc to set
* @param deriveppc
* the deriveppc to set
*/
public void setDeriveppc(String deriveppc) {
this.deriveppc = deriveppc;
@ -618,7 +608,8 @@ public class GraphData {
}
/**
* @param showppc the showppc to set
* @param showppc
* the showppc to set
*/
public void setShowppc(String showppc) {
this.showppc = showppc;
@ -632,7 +623,8 @@ public class GraphData {
}
/**
* @param latestfcstonlyc the latestfcstonlyc to set
* @param latestfcstonlyc
* the latestfcstonlyc to set
*/
public void setLatestfcstonlyc(String latestfcstonlyc) {
this.latestfcstonlyc = latestfcstonlyc;
@ -651,7 +643,8 @@ public class GraphData {
}
/**
* @param actionStage the actionStage to set
* @param actionStage
* the actionStage to set
*/
public void setActionStage(double actionStage) {
this.actionStage = actionStage;
@ -665,7 +658,8 @@ public class GraphData {
}
/**
* @param minorStage the minorStage to set
* @param minorStage
* the minorStage to set
*/
public void setMinorStage(double minorStage) {
this.minorStage = minorStage;
@ -679,7 +673,8 @@ public class GraphData {
}
/**
* @param moderateStage the moderateStage to set
* @param moderateStage
* the moderateStage to set
*/
public void setModerateStage(double moderateStage) {
this.moderateStage = moderateStage;
@ -693,7 +688,8 @@ public class GraphData {
}
/**
* @param majorStage the majorStage to set
* @param majorStage
* the majorStage to set
*/
public void setMajorStage(double majorStage) {
this.majorStage = majorStage;
@ -707,7 +703,8 @@ public class GraphData {
}
/**
* @param actionFlow the actionFlow to set
* @param actionFlow
* the actionFlow to set
*/
public void setActionFlow(double actionFlow) {
this.actionFlow = actionFlow;
@ -721,7 +718,8 @@ public class GraphData {
}
/**
* @param minorFlow the minorFlow to set
* @param minorFlow
* the minorFlow to set
*/
public void setMinorFlow(double minorFlow) {
this.minorFlow = minorFlow;
@ -735,7 +733,8 @@ public class GraphData {
}
/**
* @param moderateFlow the moderateFlow to set
* @param moderateFlow
* the moderateFlow to set
*/
public void setModerateFlow(double moderateFlow) {
this.moderateFlow = moderateFlow;
@ -749,7 +748,8 @@ public class GraphData {
}
/**
* @param majorFlow the majorFlow to set
* @param majorFlow
* the majorFlow to set
*/
public void setMajorFlow(double majorFlow) {
this.majorFlow = majorFlow;
@ -763,7 +763,8 @@ public class GraphData {
}
/**
* @param floodStage the floodStage to set
* @param floodStage
* the floodStage to set
*/
public void setFloodStage(double floodStage) {
this.floodStage = floodStage;
@ -777,7 +778,8 @@ public class GraphData {
}
/**
* @param floodFlow the floodFlow to set
* @param floodFlow
* the floodFlow to set
*/
public void setFloodFlow(double floodFlow) {
this.floodFlow = floodFlow;
@ -791,7 +793,8 @@ public class GraphData {
}
/**
* @param ymin2 the ymin2 to set
* @param ymin2
* the ymin2 to set
*/
public void setYmin2(double ymin2) {
this.ymin2 = ymin2;
@ -805,7 +808,8 @@ public class GraphData {
}
/**
* @param ymax2 the ymax2 to set
* @param ymax2
* the ymax2 to set
*/
public void setYmax2(double ymax2) {
this.ymax2 = ymax2;
@ -819,7 +823,8 @@ public class GraphData {
}
/**
* @param y2 the y2 to set
* @param y2
* the y2 to set
*/
public void setY2(double y2) {
this.y2 = y2;
@ -828,21 +833,22 @@ public class GraphData {
/**
* @return the originalTraces
*/
public ArrayList<TraceData> getOriginalTraces() {
ArrayList<TraceData> rtnList = new ArrayList<TraceData>(originalTraces.size());
for (TraceData td: originalTraces) {
public List<TraceData> getOriginalTraces() {
List<TraceData> rtnList = new ArrayList<TraceData>(
originalTraces.size());
for (TraceData td : originalTraces) {
TraceData data = new TraceData(td);
rtnList.add(data);
}
return rtnList;
}
/**
* Generate a copy of the original trace data.
*/
public void saveTraceInfo() {
for (TraceData td: traces) {
for (TraceData td : traces) {
TraceData data = new TraceData(td);
originalTraces.add(data);
}

View file

@ -133,15 +133,16 @@ public class LPIResource extends
"Label");
getCapability(LabelableCapability.class).setLabelField("Label");
File file = new File(resourceData.getFilename());
String filename = resourceData.getFilename();
File file = new File(filename);
if (!file.isAbsolute()) {
filename = FileUtil.join(VizApp.getMapsDir(), filename);
file = PathManagerFactory.getPathManager().getStaticFile(
FileUtil.join(VizApp.getMapsDir(),
resourceData.getFilename()));
filename);
}
if (file == null || file.exists() == false) {
throw new VizException("Could not find lpi file",
new FileNotFoundException(String.valueOf(file)));
new FileNotFoundException(filename));
}
points = new ArrayList<LPIPoint>();

View file

@ -42,12 +42,10 @@
</win>
</launcher>
<vm>
<windows include="true">jdk1.6.0</windows>
</vm>
<plugins>
</plugins>

View file

@ -22,6 +22,7 @@ package com.raytheon.viz.redbook.blocks;
import java.nio.ByteBuffer;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlock;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
import com.raytheon.viz.redbook.rsc.RedbookLegend;
import com.raytheon.viz.redbook.rsc.RedbookLegend.Type;
@ -33,6 +34,7 @@ import com.raytheon.viz.redbook.rsc.RedbookLegend.Type;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 18, 2010 #3260 dfriedma Initial creation
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -45,8 +47,8 @@ public abstract class AbstractTextBlock extends RedbookBlock {
protected int origXPos;
protected int origYPos;
public AbstractTextBlock(ByteBuffer data) {
super(data);
public AbstractTextBlock(RedbookBlockHeader header, ByteBuffer data) {
super(header, data);
}
public abstract TextBlock getTextBlock();

View file

@ -24,6 +24,7 @@ import java.nio.ByteBuffer;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
import com.vividsolutions.jts.geom.Coordinate;
/**
@ -34,6 +35,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 22, 2008 #1162 chammack Initial creation
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -45,8 +47,9 @@ public class AlphaNumBlock extends AbstractTextBlock {
private final TextBlock textBlock;
public AlphaNumBlock(ByteBuffer data, MathTransform mt, int maxX, int maxY) {
super(data);
public AlphaNumBlock(RedbookBlockHeader header, ByteBuffer data,
MathTransform mt, int maxX, int maxY) {
super(header, data);
int length = getLength();

View file

@ -24,6 +24,7 @@ import java.nio.ByteBuffer;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
import com.vividsolutions.jts.geom.Coordinate;
/**
@ -37,6 +38,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 22, 2008 #1162 chammack Initial creation
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -47,8 +49,9 @@ import com.vividsolutions.jts.geom.Coordinate;
public class PlotDataBlock extends AbstractTextBlock {
private TextBlock textBlock;
public PlotDataBlock(ByteBuffer data, MathTransform mt, int maxX, int maxY) {
super(data);
public PlotDataBlock(RedbookBlockHeader header, ByteBuffer data,
MathTransform mt, int maxX, int maxY) {
super(header, data);
/* int mode = ( */data.get() /* & 0xFF) */;

View file

@ -22,6 +22,7 @@ package com.raytheon.viz.redbook.blocks;
import java.nio.ByteBuffer;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlock;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
/**
* Implements the redbook plot parameter block
@ -31,6 +32,7 @@ import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlock;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 22, 2008 #1162 chammack Initial creation
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -52,9 +54,9 @@ public class PlotParametersBlock extends RedbookBlock {
private int lineWidth;
public PlotParametersBlock(ByteBuffer data) {
public PlotParametersBlock(RedbookBlockHeader header, ByteBuffer data) {
super(data);
super(header, data);
// Set up some reasonable defaults
this.lineWidth = 1;

View file

@ -32,6 +32,7 @@ import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.raytheon.edex.plugin.redbook.common.blocks.Block_004_017;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
import com.raytheon.uf.common.geospatial.MapUtil;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
@ -45,6 +46,7 @@ import com.vividsolutions.jts.geom.Point;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 27, 2008 #1162 chammack Initial creation
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -58,8 +60,8 @@ public class RedbookProjectionBlock extends Block_004_017 {
*
* @param separator
*/
public RedbookProjectionBlock(ByteBuffer data) {
super(data);
public RedbookProjectionBlock(RedbookBlockHeader header, ByteBuffer data) {
super(header, data);
}

View file

@ -26,6 +26,7 @@ import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlock;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
import com.raytheon.viz.redbook.rsc.RedbookLegend;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
@ -40,6 +41,7 @@ import com.vividsolutions.jts.geom.LineString;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* May 22, 2008 #1162 chammack Initial creation
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -51,9 +53,10 @@ public class ShortLongVectorsBlock extends RedbookBlock {
protected Geometry geometry;
public ShortLongVectorsBlock(java.nio.ByteBuffer data, MathTransform mt,
public ShortLongVectorsBlock(RedbookBlockHeader header,
java.nio.ByteBuffer data, MathTransform mt,
int maxX, int maxY, RedbookLegend legend) {
super(data);
super(header, data);
List<Geometry> geometries = new ArrayList<Geometry>();
List<Coordinate> coords = new ArrayList<Coordinate>();

View file

@ -39,6 +39,8 @@ import org.opengis.referencing.operation.TransformException;
import com.raytheon.edex.plugin.redbook.common.blocks.Block_004_016;
import com.raytheon.edex.plugin.redbook.common.blocks.DefaultBlock;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockBuilder;
import com.raytheon.edex.plugin.redbook.common.blocks.RedbookBlockHeader;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.common.datastorage.records.ByteDataRecord;
import com.raytheon.uf.common.geospatial.MapUtil;
@ -89,6 +91,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* May 29, 2008 #1162 chammack Initial creation
* Jan 28, 2010 #4224 M. Huang Added Line Style, Line Width
* menu choice
* Apr 29, 2013 1958 bgonzale New class RedbookBlockHeader.
*
* </pre>
*
@ -160,19 +163,24 @@ public class RedbookFrame implements IRenderable {
while (dataBuf.hasRemaining()) {
String currBlock = getBlockKey(dataBuf);
RedbookBlockHeader header = RedbookBlockBuilder
.getHeader(dataBuf);
String currBlock = header.blockFactoryKey;
if (currBlock.equals("005_002")) {
// Block that describes plot data
PlotDataBlock pdb = new PlotDataBlock(dataBuf, mt, m, n);
PlotDataBlock pdb = new PlotDataBlock(header, dataBuf,
mt, m, n);
parsedTextBlocks.add(pdb);
} else if (currBlock.equals("005_001")) {
// Block that describes alphanumeric data
AlphaNumBlock pdb = new AlphaNumBlock(dataBuf, mt, m, n);
AlphaNumBlock pdb = new AlphaNumBlock(header, dataBuf,
mt, m, n);
parsedTextBlocks.add(pdb);
} else if (currBlock.equals("004_005")) {
// Block that describes the relative short/long format
ShortLongVectorsBlock vb = new ShortLongVectorsBlock(
dataBuf, mt, m, n, legend);
header, dataBuf, mt, m, n, legend);
try {
this.compiler.handle(vb.getGeometry());
} catch (VizException e) {
@ -188,12 +196,12 @@ public class RedbookFrame implements IRenderable {
}
} else if (currBlock.equals("001_004")) {
// Block that describes the plot parameters
new PlotParametersBlock(dataBuf);
new PlotParametersBlock(header, dataBuf);
// Currently, this is not used in rendering
} else if (currBlock.equals("004_017")) {
// Block that describes the projection
RedbookProjectionBlock vb = new RedbookProjectionBlock(
dataBuf);
header, dataBuf);
String customProjection = null;
try {
@ -264,7 +272,7 @@ public class RedbookFrame implements IRenderable {
}
} else if (currBlock.equals("004_016")) {
// Block that describes the plot space
Block_004_016 vb = new Block_004_016(dataBuf);
Block_004_016 vb = new Block_004_016(header, dataBuf);
// Store off the pixel space
m = vb.getRefM2coord();
@ -277,11 +285,11 @@ public class RedbookFrame implements IRenderable {
|| currBlock.startsWith("002_")) {
// Recognized blocks that we don't do anything with
new DefaultBlock(dataBuf);
new DefaultBlock(header, dataBuf);
} else {
DefaultBlock block = new DefaultBlock(dataBuf);
DefaultBlock block = new DefaultBlock(header, dataBuf);
if (!currBlock.equals("")) {
status.unhandledPackets = true;
@ -618,29 +626,6 @@ public class RedbookFrame implements IRenderable {
}
}
/**
*
* @param dataBuffer
* @return
*/
private static String getBlockKey(ByteBuffer dataBuffer) {
String blockKey = "";
// Must have at least 4 bytes
if (dataBuffer.remaining() > MIN_REMAINING) {
dataBuffer.mark();
// Dummy read for the flags/length
dataBuffer.getShort();
int mode = (dataBuffer.get() & 0xFF);
int subMode = (dataBuffer.get() & 0xFF);
dataBuffer.reset();
blockKey = String.format(MODE_KEY_FMT, mode, subMode);
}
return blockKey;
}
public void dispose() {
if (this.wireframeShape != null) {
this.wireframeShape.dispose();

View file

@ -50,6 +50,8 @@ 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.common.time.SimulatedTime;
import com.raytheon.uf.common.time.util.ITimer;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.viz.alertviz.SystemStatusHandler;
import com.raytheon.uf.viz.alertviz.ui.dialogs.AlertVisualization;
import com.raytheon.uf.viz.application.ProgramArguments;
@ -60,6 +62,7 @@ import com.raytheon.uf.viz.core.localization.CAVELocalizationNotificationObserve
import com.raytheon.uf.viz.core.localization.LocalizationConstants;
import com.raytheon.uf.viz.core.localization.LocalizationInitializer;
import com.raytheon.uf.viz.core.localization.LocalizationManager;
import com.raytheon.uf.viz.core.notification.jobs.NotificationManagerJob;
import com.raytheon.uf.viz.core.status.VizStatusHandlerFactory;
import com.raytheon.viz.alerts.jobs.AutoUpdater;
import com.raytheon.viz.alerts.jobs.MenuUpdater;
@ -90,6 +93,8 @@ import com.raytheon.viz.core.units.UnitRegistrar;
* mode is off.
* Jan 09, 2013 #1442 rferrel Changes to notify SimultedTime listeners.
* Apr 17, 2013 1786 mpduff startComponent now sets StatusHandlerFactory
* Apr 23, 2013 #1939 randerso Allow serialization to complete initialization
* before connecting to JMS to avoid deadlock
*
* </pre>
*
@ -139,7 +144,8 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
UnitRegistrar.registerUnits();
CAVEMode.performStartupDuties();
long t0 = System.currentTimeMillis();
ITimer timer = TimeUtil.getTimer();
timer.start();
Display display = null;
int modes = getRuntimeModes();
@ -166,7 +172,7 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
}
UFStatus.setHandlerFactory(new VizStatusHandlerFactory());
initializeSerialization();
Job serializationJob = initializeSerialization();
initializeDataStoreFactory();
initializeObservers();
@ -204,12 +210,22 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
WorkbenchAdvisor workbenchAdvisor = null;
// A component was passed as command line arg
// launch cave normally, should cave be registered as component?
long t1 = System.currentTimeMillis();
System.out.println("Localization time: " + (t1 - t0) + "ms");
try {
initializeSimulatedTime();
// wait for serialization initialization to complete before
// opening JMS connection to avoid deadlock in class loaders
if (serializationJob != null) {
serializationJob.join();
}
// open JMS connection to allow alerts to be received
NotificationManagerJob.connect();
timer.stop();
System.out.println("Initialization time: " + timer.getElapsedTime()
+ "ms");
if (cave) {
workbenchAdvisor = getWorkbenchAdvisor();
} else if (!nonui) {
@ -220,6 +236,7 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
if (workbenchAdvisor instanceof HiddenWorkbenchAdvisor == false) {
startInternal(componentName);
}
if (workbenchAdvisor != null) {
returnCode = PlatformUI.createAndRunWorkbench(display,
workbenchAdvisor);
@ -239,6 +256,15 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
// catch any exceptions to ensure rest of finally block
// executes
}
try {
// disconnect from JMS
NotificationManagerJob.disconnect();
} catch (RuntimeException e) {
// catch any exceptions to ensure rest of finally block
// executes
}
if (av != null) {
av.dispose();
}
@ -368,8 +394,8 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
!LocalizationManager.internalAlertServer).run();
}
protected void initializeSerialization() {
new Job("Loading Serialization") {
protected Job initializeSerialization() {
Job job = new Job("Loading Serialization") {
@Override
protected IStatus run(IProgressMonitor monitor) {
@ -382,7 +408,9 @@ public abstract class AbstractCAVEComponent implements IStandaloneComponent {
return Status.OK_STATUS;
}
}.schedule();
};
job.schedule();
return job;
}
/**

View file

@ -51,6 +51,8 @@ import com.raytheon.viz.volumebrowser.xml.VbSourceList;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 28, 2011 mschenke Initial creation
* May 02, 2013 1949 bsteffen Force ModelSounding in Vb to play nicely
* with others.
*
* </pre>
*
@ -167,7 +169,9 @@ public class ModelSoundingCatalog extends PointDataCatalog {
String[] selectedSources = request.getSelectedSources();
if (selectedSources != null) {
for (int i = 0; i < selectedSources.length; i++) {
selectedSources[i] = pluginName;
if (selectedSources[i].startsWith(pluginName)) {
selectedSources[i] = pluginName;
}
}
}
return request;

View file

@ -136,6 +136,7 @@ import com.vividsolutions.jts.geom.Polygon;
* Feb 18, 2013 #1633 rferrel Changed checkFollowupSelection to use SimulatedTime.
* Mar 28, 2013 DR 15974 D. Friedman Do not track removed GIDs.
* Apr 11, 2013 1894 jsanchez Removed the ability to load/unload maps via bullet selection. This will be resolved in a follow on ticket.
* Apr 30, 2013 DR 16118 Qinglu Lin For reissue (followup NEW), called redrawFromWarned() in okPressed().
* </pre>
*
* @author chammack
@ -989,6 +990,11 @@ public class WarngenDialog extends CaveSWTDialog implements
return;
}
if (followupData != null && WarningAction.valueOf(followupData
.getAct()) == WarningAction.NEW) {
redrawFromWarned();
}
if ((followupData == null || (WarningAction.valueOf(followupData
.getAct()) == WarningAction.CON && warngenLayer
.conWarnAreaChanged(followupData)))

View file

@ -48,6 +48,7 @@ import com.vividsolutions.jts.geom.GeometryFactory;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 27, 2012 1149 jsanchez Refactored methods from AbstractWarningsResource into this class.
* May 06, 2013 1930 bsteffen Check for null in WatchesResource.
*
* </pre>
*
@ -186,16 +187,13 @@ public class WatchesResource extends AbstractWWAResource {
if (record.getUgczones().size() > 0) {
setGeometry(record);
if (record.getGeometry() != null) {
if (record.getGeometry() != null && record.getPhen() != null) {
IShadedShape ss = target.createShadedShape(false,
descriptor.getGridGeometry(), false);
geo = (Geometry) record.getGeometry().clone();
JTSCompiler jtsCompiler = new JTSCompiler(ss, null,
this.descriptor, PointStyle.CROSS);
jtsCompiler.handle(geo, color);
if (record.getPhen() == null) {
return;
}
ss.setFillPattern(FillPatterns.getGLPattern(record.getPhen()
.equals("TO") ? "VERTICAL" : "HORIZONTAL"));
ss.compile();
@ -272,7 +270,7 @@ public class WatchesResource extends AbstractWWAResource {
if (createShape != null) {
WarningEntry entry = entryMap.get(createShape
.getDataURI());
if (entry != null) {
if (entry != null && entry.shadedShape != null) {
entry.shadedShape.dispose();
}
initShape(target, createShape);

View file

@ -0,0 +1,84 @@
-- called by normalizeGfe.sh to create new GFE tables
DROP TABLE IF EXISTS gfe_locks CASCADE;
DROP TABLE IF EXISTS gfe_parmid CASCADE;
DROP TABLE IF EXISTS gfe_dbid CASCADE;
DROP SEQUENCE IF EXISTS gfe_lock_seq;
DROP SEQUENCE IF EXISTS gfe_parmid_seq;
DROP SEQUENCE IF EXISTS gfe_dbid_seq;
DROP SEQUENCE IF EXISTS gfe_history_seq;
CREATE TABLE gfe_dbid
(
id integer NOT NULL,
dbtype character varying(15),
format character varying(255) NOT NULL,
modelname character varying(64) NOT NULL,
modeltime character varying(13) NOT NULL,
siteid character varying(4) NOT NULL,
CONSTRAINT gfe_dbid_pkey PRIMARY KEY (id),
CONSTRAINT gfe_dbid_siteid_modelname_modeltime_dbtype_key UNIQUE (siteid, modelname, modeltime, dbtype)
)
WITH (
OIDS=FALSE
);
ALTER TABLE gfe_dbid
OWNER TO awips;
CREATE TABLE gfe_parmid
(
id integer NOT NULL,
parmlevel character varying(8),
parmname character varying(100),
dbid_id integer NOT NULL,
CONSTRAINT gfe_parmid_pkey PRIMARY KEY (id),
CONSTRAINT fkbec2950012156549 FOREIGN KEY (dbid_id)
REFERENCES gfe_dbid (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT gfe_parmid_dbid_id_parmname_parmlevel_key UNIQUE (dbid_id, parmname, parmlevel)
)
WITH (
OIDS=FALSE
);
ALTER TABLE gfe_parmid
OWNER TO awips;
CREATE TABLE gfe_locks
(
id integer NOT NULL,
endtime timestamp without time zone NOT NULL,
starttime timestamp without time zone NOT NULL,
wsid character varying(255) NOT NULL,
parmid_id integer NOT NULL,
CONSTRAINT gfe_locks_pkey PRIMARY KEY (id),
CONSTRAINT fk92582e8f7bab05cc FOREIGN KEY (parmid_id)
REFERENCES gfe_parmid (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE,
CONSTRAINT gfe_locks_parmid_id_starttime_endtime_key UNIQUE (parmid_id, starttime, endtime)
)
WITH (
OIDS=FALSE
);
ALTER TABLE gfe_locks
OWNER TO awips;
CREATE SEQUENCE gfe_lock_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE gfe_lock_seq
OWNER TO awips;
CREATE SEQUENCE gfe_history_seq
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 1
CACHE 1;
ALTER TABLE gfe_history_seq
OWNER TO awips;
ALTER TABLE gfe ADD COLUMN parmId_id integer;

View file

@ -0,0 +1,17 @@
#!/bin/bash
# DR #1926 - this update script will create a scan index
PSQL="/awips2/psql/bin/psql"
echo "INFO: Creating scan_icao_type_idx"
${PSQL} -U awips -d metadata -c "CREATE INDEX scan_icao_type_idx ON scan USING btree (icao COLLATE pg_catalog.\"default\", type COLLATE pg_catalog.\"default\");"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to create index."
echo "FATAL: The update has failed."
exit 1
fi
echo "INFO: Index created successfully!"
exit 0

View file

@ -0,0 +1,20 @@
#!/awips2/python/bin/python
import re
import sys
# we expect the filename as a command-line argument.
hdf5file = sys.argv[1]
matches = re.search(r'modelsounding-([0-9]+-[0-9]+-[0-9]+)-([0-9]+).h5', hdf5file, re.M|re.I)
if matches:
# extract the date
# extract the hour
date = matches.group(1)
hour = matches.group(2)
reftimeDirName = date + "_" + hour + ":00:00.0"
print reftimeDirName
else:
print "ERROR: unrecognized file - " + hdf5file + "!"
sys.exit(-1)

View file

@ -0,0 +1,20 @@
#!/awips2/python/bin/python
import re
import sys
# we expect the filename, model name, and forecast hour as arguments
hdf5file = sys.argv[1]
model = sys.argv[2]
forecastHour = sys.argv[3]
matches = re.search(r'modelsounding-([0-9]+-[0-9]+-[0-9]+-[0-9]+).h5', hdf5file, re.M|re.I)
if matches:
# extract the reftime
reftime = matches.group(1)
newFileName = "modelsounding-" + model + "-" + reftime + "-FH-" + str(forecastHour) + ".h5"
print newFileName
else:
print "ERROR: unrecognized file - " + hdf5file + "!"
sys.exit(-1)

View file

@ -0,0 +1,104 @@
#!/bin/bash
# Main script for updating GFE database structure
PSQL="/awips2/psql/bin/psql"
PYTHON="/awips2/python/bin/python"
SQL_SCRIPT="createNewGfeTables.sql"
# ensure that the sql script is present
if [ ! -f ${SQL_SCRIPT} ]; then
echo "ERROR: the required sql script - ${SQL_SCRIPT} was not found."
echo "FATAL: the update has failed!"
exit 1
fi
echo "Creating new GFE tables"
${PSQL} -U awips -d metadata -f ${SQL_SCRIPT}
if [ $? -ne 0 ]; then
echo "FATAL: the update has failed!"
exit 1
fi
echo
echo "Querying GFE parmIds"
RETRIEVE_PARMIDS_SQL="SELECT distinct parmId FROM gfe order by parmID"
_parmid_list_txt=parmIdList.txt
${PSQL} -U awips -d metadata -c "${RETRIEVE_PARMIDS_SQL}" -t -o ${_parmid_list_txt}
if [ $? -ne 0 ]; then
echo "ERROR: Failed to retrieve the list of parm ids."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Parsing parmIds for insertion into new tables"
PYTHON_PARSE_SCRIPT="parseParmIds.py"
if [ ! -f ${PYTHON_PARSE_SCRIPT} ]; then
echo "ERROR: the required python script - ${PYTHON_PARSE_SCRIPT} was not found."
echo "FATAL: the update has failed!"
exit 1
fi
${PYTHON} ${PYTHON_PARSE_SCRIPT} ${_parmid_list_txt}
if [ $? -ne 0 ]; then
echo "ERROR: Failed to parse parm ids."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Inserting db ids"
# dbIdInserts.sql generated from parseParmIds.py
${PSQL} -U awips -d metadata -q -f dbIdInserts.sql
if [ $? -ne 0 ]; then
echo "ERROR: Failed to insert database ids."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Inserting parm ids"
# parmIdInserts.sql generated from parseParmIds.py
${PSQL} -U awips -d metadata -q -f parmIdInserts.sql
if [ $? -ne 0 ]; then
echo "ERROR: Failed to insert parm ids."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Add gfe record reference to parm id table"
# gfeToParmIdUpdates.sql generated from parseParmIds.py
${PSQL} -U awips -d metadata -q -f gfeToParmIdUpdates.sql
if [ $? -ne 0 ]; then
echo "ERROR: Failed to add gfe to parm id mapping."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Updating constraints and indexes on gfe"
SQL_SCRIPT="updateGfeConstraintsAndIndexes.sql"
${PSQL} -U awips -d metadata -f ${SQL_SCRIPT}
if [ $? -ne 0 ]; then
echo "ERROR: Failed to update constraints and indexes."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Updating dataURIs for gfe"
UPDATE_DATAURIS_SQL="UPDATE gfe SET dataURI =regexp_replace(dataURI, '(/gfe/[^/]+)/([^_]+)_([^:]+):([^_]+)_GRID_([^_]*)_([^_]+)_(\\d{8}_\\d{4})/[^/]+', '\\1/\\4/\\6/\\7/\\5/\\2/\\3') where dataURI ~ '/gfe/[^/]+/[^/]+/[^/]+';"
${PSQL} -U awips -d metadata -c "${UPDATE_DATAURIS_SQL}"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to retrieve the list of parm ids."
echo "FATAL: The update has failed."
exit 1
fi
echo
echo "Running full vacuum for gfe"
${PSQL} -U awips -d metadata -c "VACUUM FULL VERBOSE ANALYZE gfe"

View file

@ -0,0 +1,53 @@
# Called by normalizeGfe.sh to parse the distinct parmIds into table insert
import sys
from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.db.objects import ParmID
from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.gfe.db.objects import DatabaseID
fileName = sys.argv[1]
f = open(fileName, 'r')
dbIdInsertFile = open('dbIdInserts.sql', 'w')
parmIdInsertFile = open('parmIdInserts.sql', 'w')
recordUpdateFile = open('gfeToParmIdUpdates.sql', 'w')
dbIds={}
parmIds={}
dbIdCounter = 1
parmIdCounter = 1
for parmIdString in f:
# Strip new line
parmIdString = parmIdString.strip()
# skip last line of file that's empty
if len(parmIdString.strip()) > 0:
if not parmIds.has_key(parmIdString):
parmIds[parmIdString] = parmIdCounter
parmId = ParmID(parmIdString)
dbId = parmId.getDbId()
dbIdString = dbId.getModelId()
if not dbIds.has_key(dbIdString):
dbIds[dbIdString] = dbIdCounter
dbIdInsertFile.write("INSERT INTO gfe_dbid (id, dbtype, format, modelname, modeltime, siteid) VALUES (" +
str(dbIdCounter) + ", '" + dbId.getDbType() + "', '" + dbId.getFormat() + "', '" +
dbId.getModelName() + "', '" + dbId.getModelTime() + "', '" + dbId.getSiteId() + "');\n")
dbIdCounter += 1
dbIdVal = dbIds[dbIdString]
parmIdInsertFile.write("INSERT INTO gfe_parmid (id, parmlevel, parmname, dbid_id) VALUES (" +
str(parmIdCounter) + ", '" + parmId.getParmLevel() + "', '" +
parmId.getParmName() + "', " + str(dbIdVal) + ");\n")
recordUpdateFile.write("UPDATE gfe set parmId_id = " + str(parmIdCounter) +
" WHERE parmId = '" + parmIdString + "';\n")
parmIdCounter+=1
else:
# should never happen if query feeding this is using distinct
print "Received duplicate parmId: " + parmIdString
dbIdInsertFile.write("CREATE SEQUENCE gfe_dbid_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START "
+ str((dbIdCounter / 50) + 1) + " CACHE 1;\nALTER TABLE gfe_dbid_seq OWNER TO awips;")
parmIdInsertFile.write("CREATE SEQUENCE gfe_parmid_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START "
+ str((parmIdCounter / 50) + 1) + " CACHE 1;\nALTER TABLE gfe_parmid_seq OWNER TO awips;")
f.close()
dbIdInsertFile.close()
parmIdInsertFile.close()
recordUpdateFile.close()

View file

@ -0,0 +1,36 @@
-- Called by normalizeGfe.sh to dop and add constraints
ALTER TABLE gfe DROP CONSTRAINT gfe_datauri_key;
DROP INDEX IF EXISTS gfeParmTime_idx;
DROP INDEX IF EXISTS gfedatauri_idx;
DROP INDEX IF EXISTS gfefcsttimeindex;
ALTER TABLE gfe DROP COLUMN IF EXISTS parmname;
ALTER TABLE gfe DROP COLUMN IF EXISTS parmlevel;
ALTER TABLE gfe DROP COLUMN IF EXISTS dbid;
ALTER TABLE gfe DROP COLUMN IF EXISTS parmid;
ALTER TABLE gfe ADD CONSTRAINT fk18f667bab05cc FOREIGN KEY (parmid_id)
REFERENCES gfe_parmid (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE;
ALTER TABLE gfe ADD CONSTRAINT gfe_parmid_id_rangestart_rangeend_reftime_forecasttime_key
UNIQUE (parmid_id, rangestart, rangeend, reftime, forecasttime);
ALTER TABLE gfe_gridhistory DROP CONSTRAINT fk66434335e416514f;
ALTER TABLE gfe_gridhistory RENAME COLUMN key TO id;
ALTER TABLE gfe_gridhistory RENAME COLUMN parent to parent_id;
ALTER TABLE gfe_gridhistory ADD CONSTRAINT fk664343359ad1f975 FOREIGN KEY (parent_id)
REFERENCES gfe (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE CASCADE;
DROP TABLE IF EXISTS gfelocktable;

View file

@ -0,0 +1,130 @@
#!/bin/bash
# DR #1846 - this update script will re-arrange the existing modelsounding hdf5 files to divide them by
# model name and site. Currently, every file will be copied to every potential path that it could be
# accessed at. But, any new files that are written after the upgrade is complete, will contain only
# the minimum amount of required data.
# ensure that we actually have modellsounding data to re-arrange
DATA_DIRECTORY="/awips2/edex/data/hdf5/modelsounding"
if [ ! -d ${DATA_DIRECTORY} ]; then
echo "INFO: No Model Sounding Data Was Found On The System!"
echo "INFO: Update Terminated ..."
exit 0
fi
# determine where we are
path_to_script=`readlink -f $0`
dir=$(dirname $path_to_script)
# first, retrieve all possible models
PSQL="/awips2/psql/bin/psql"
SQL="SELECT DISTINCT reporttype FROM awips.modelsounding ORDER BY reporttype;"
_modelslist=modelslist.txt
echo "INFO: update started."
pushd . > /dev/null 2>&1
cd ${DATA_DIRECTORY}
# retrieve the models
${PSQL} -U awips -d metadata -c "${SQL}" -t -o ${_modelslist}
if [ $? -ne 0 ]; then
echo "ERROR: Failed to retrieve the list of models."
echo "FATAL: The update has failed."
exit 1
fi
PYTHON="/awips2/python/bin/python"
_python_script="${dir}/determineRefTimeDirectory.py"
_python_script2="${dir}/modelsoundingFileName.py"
_fcsthourslist=fcsthourslist.txt
# now loop through the models
for model in `cat ${_modelslist}`; do
# create a directory for the model.
mkdir -p ${DATA_DIRECTORY}/${model}
if [ $? -ne 0 ]; then
echo "ERROR: Failed to create directory - ${DATA_DIRECTORY}/${model}!"
echo "FATAL: The update has failed."
exit 1
fi
# retrieve the potential forecast hours for the model that we are
# currently processing.
SQL_FCST_HOUR="SELECT DISTINCT (fcstSeconds / 3600) AS forecastHour FROM modelsounding WHERE reporttype = '${model}' ORDER BY forecastHour;"
${PSQL} -U awips -d metadata -c "${SQL_FCST_HOUR}" -t -o ${_fcsthourslist}
# loop through the hdf5 files
for file in `ls -1 *.h5`; do
# determine which reftime directory would be associated with the file
reftimeDirectory=`${PYTHON} ${_python_script} "${file}"`
if [ $? -ne 0 ]; then
echo "FATAL: The update has failed."
exit 1
fi
# create the reftime directory
mkdir -p "${DATA_DIRECTORY}/${model}/${reftimeDirectory}"
if [ $? -ne 0 ]; then
echo "ERROR: Failed to create directory - ${DATA_DIRECTORY}/${model}/${reftimeDirectory}!"
echo "FATAL: The update has failed."
exit 1
fi
# loop through the possible forecast hours
for fcstHour in `cat ${_fcsthourslist}`; do
# determine the new name of the file
destinationFile=`${PYTHON} ${_python_script2} "${file}" "${model}" ${fcstHour}`
if [ $? -ne 0 ]; then
echo "ERROR: Failed to determine the adjusted name of file - ${file}!"
echo "FATAL: The update has failed."
exit 1
fi
# create a link between the files
ln ${file} ${DATA_DIRECTORY}/${model}/${reftimeDirectory}/${destinationFile}
if [ $? -ne 0 ]; then
echo "ERROR: Failed create a link for ${file} to ${DATA_DIRECTORY}/${model}/${reftimeDirectory}/${destinationFile}!"
echo "FATAL: The update has failed."
exit 1
fi
done
done
rm -f ${_fcsthourslist}
if [ $? -ne 0 ]; then
echo "WARNING: Failed to remove temporary file - ${_fcsthourslist}."
fi
done
# remove the models list text file
rm -f ${_modelslist}
if [ $? -ne 0 ]; then
echo "WARNING: Failed to remove temporary file - ${_modelslist}."
fi
# remove the hdf5 files
rm -f *.h5
if [ $? -ne 0 ]; then
echo "ERROR: Failed to remove the obsolete hdf5 files!"
echo "WARNING: Removing the files manually is recommended."
fi
popd > /dev/null 2>&1
echo "INFO: the update has completed successfully!"
exit 0

View file

@ -0,0 +1,60 @@
#!/bin/bash
# This script will update any gribParamInfo files to use the gridParamInfo tag
# and move gribModels files from common_static to edex_static and remove
# deprecated fields.
#
# This update is optional with 13.4.1 but it must be performed before grib can
# move to the futue.
#
# This update is only for edex servers which host the cave localization files
echo "INFO: Moving all parameterInfo files to grid."
IFS=$'\n'
gribFiles=`find /awips2/edex/data/utility/edex_static/*/*/grib/parameterInfo/ -iname '*.xml'`
for f in $gribFiles; do
newf=${f//grib/grid}
if [ -e "$newf" ]; then
echo Cannot upgrade $f because $newf already exists
else
mkdir -p `dirname $newf`
mv $f $newf
fi
done
echo "INFO: Upgrading all parameterInfo files."
gridFiles=`find /awips2/edex/data/utility/edex_static/*/*/grid/parameterInfo/ -iname '*.xml'`
for f in $gridFiles; do
sed -n 's/gribParamInfo/gridParamInfo/g;p;' -i $f
done
echo "INFO: Moving all gribModels to edex_static."
commonFiles=`find /awips2/edex/data/utility/common_static/*/*/grib/models/ -iname '*.xml'`
for f in $commonFiles; do
newf=${f//common_static/edex_static}
if [ -e "$newf" ]; then
echo Cannot upgrade $f because $newf already exists
else
mkdir -p `dirname $newf`
mv $f $newf
fi
done
echo "INFO: Cleaning all gribModel files."
edexFiles=`find /awips2/edex/data/utility/edex_static/*/*/grib/models/ -iname '*.xml'`
for f in $edexFiles; do
sed '/^\s*<title>.*<\/title>\s*$/d' -i $f
sed '/^\s*<alias>.*<\/alias>\s*$/d' -i $f
sed '/^\s*<dt>.*<\/dt>\s*$/d' -i $f
sed '/^\s*<paramInfo>.*<\/paramInfo>\s*$/d' -i $f
done
echo "INFO: The update finished successfully."
exit 0

View file

@ -9,6 +9,15 @@ export IH_DB_NAME=hd_ob83oax
### end of localization variables ###
### flag to control grib deprecation ###
if [ -z "$gribMode" ]; then
# uncomment only one of the following two lines
export gribMode=deprecated
#export gribMode=future
fi
## end of grib deprecation flag ###
# setup environment for HPE
export DATA_ARCHIVE_ROOT=/tmp/sbn

View file

@ -147,6 +147,7 @@ wrapper.java.additional.48=-Dhttp.port=${HTTP_PORT}
wrapper.java.additional.49=-Dedex.arch=${EDEX_BITS}-bit
wrapper.java.additional.50=-Dedex.tmp=${TEMP_DIR}
wrapper.java.additional.51=-Dncf.bandwidth.manager.service=${NCF_BANDWIDTH_MANAGER_SERVICE}
wrapper.java.additional.52=-DinitializeHibernatables=true
# Initial Java Heap Size (in MB)
wrapper.java.initmemory=${INIT_MEM}

View file

@ -50,6 +50,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
* ------------ ---------- ----------- --------------------------
* 14Nov2008 1709 MW Fegan Initial creation.
* 14Apr2011 5163 cjeanbap NWRWAVES Setting AFOS text triggers in AWIPS II
* 04/24/13 1949 rjpeter Removed @Override on delete.
* </pre>
*
* @author mfegan
@ -90,8 +91,7 @@ public class SubscriptionDAO extends CoreDao {
super(config);
}
@Override
public void delete(PersistableDataObject obj) {
public void delete(PersistableDataObject<?> obj) {
super.delete(obj);
sendSubscriptionNotifyMessage(String.valueOf(obj.getIdentifier()));
}
@ -145,7 +145,7 @@ public class SubscriptionDAO extends CoreDao {
*/
@SuppressWarnings("unchecked")
public List<SubscriptionRecord> getSubscriptions() {
if (cachedRecords == null || dirtyRecords) {
if ((cachedRecords == null) || dirtyRecords) {
List<?> retVal = getHibernateTemplate().loadAll(this.daoClass);
if (retVal == null) {
logger.info("Unable to perform query, 'null' result returned");
@ -182,7 +182,7 @@ public class SubscriptionDAO extends CoreDao {
synchronized (recordsMap) {
rval = recordsMap.get(key);
}
if (rval == null || rval.isEmpty() || rval.size() == 0) {
if ((rval == null) || rval.isEmpty()) {
List<?> retVal = null;
List<QueryParam> params = new ArrayList<QueryParam>();
for (Property prop : props) {

View file

@ -50,8 +50,8 @@ import com.raytheon.uf.edex.database.DatabasePluginRegistry;
import com.raytheon.uf.edex.database.DatabaseSessionFactoryBean;
import com.raytheon.uf.edex.database.IDatabasePluginRegistryChanged;
import com.raytheon.uf.edex.database.cluster.ClusterLockUtils;
import com.raytheon.uf.edex.database.cluster.ClusterTask;
import com.raytheon.uf.edex.database.cluster.ClusterLockUtils.LockState;
import com.raytheon.uf.edex.database.cluster.ClusterTask;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
import com.raytheon.uf.edex.database.plugin.PluginVersion;
@ -67,6 +67,8 @@ import com.raytheon.uf.edex.database.plugin.PluginVersionDao;
* 10/8/2008 1532 bphillip Initial checkin
* 2/9/2009 1990 bphillip Fixed index creation
* 03/20/09 njensen Implemented IPluginRegistryChanged
* Mar 02, 2013 1970 bgonzale Updated createIndexTableNamePattern to match text preceeding
* %TABLE%.
* </pre>
*
* @author bphillip
@ -100,7 +102,7 @@ public class SchemaManager implements IDatabasePluginRegistryChanged {
.compile("^create (?:table |index |sequence )(?:[A-Za-z_0-9]*\\.)?(.+?)(?: .*)?$");
private Pattern createIndexTableNamePattern = Pattern
.compile("^create index %TABLE%.+? on (.+?) .*$");
.compile("^create index \\w*?%TABLE%.+? on (.+?) .*$");
/**
* Gets the singleton instance
@ -294,8 +296,7 @@ public class SchemaManager implements IDatabasePluginRegistryChanged {
runPluginScripts(props);
String database = props.getDatabase();
PluginVersion pv = new PluginVersion(props.getPluginName(),
true,
props.getTableName(), database);
true, props.getTableName(), database);
pvd.saveOrUpdate(pv);
logger.info(pluginName + " plugin initialization complete!");
} else if (initialized == false) {
@ -343,9 +344,6 @@ public class SchemaManager implements IDatabasePluginRegistryChanged {
createSql.add(sql);
}
// only truly want the sql for just this plugin
removeAllDependentCreateSql(props, sessFactory, createSql);
for (int i = 0; i < createSql.size(); i++) {
String sql = createSql.get(i);
if (sql.startsWith("create index")) {
@ -358,6 +356,9 @@ public class SchemaManager implements IDatabasePluginRegistryChanged {
}
createSql.trimToSize();
// only truly want the sql for just this plugin
removeAllDependentCreateSql(props, sessFactory, createSql);
pluginCreateSql.put(fqn, createSql);
}
return createSql;

View file

@ -23,13 +23,13 @@ import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.ManyToOne;
import javax.persistence.MappedSuperclass;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;
import javax.persistence.UniqueConstraint;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@ -59,15 +59,17 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
* 20080221 862 jkorman Initial Coding.
* 02/06/09 1990 bphillip removed populateDataStore method
* Apr 12, 2013 1857 bgonzale Added SequenceGenerator annotation.
* May 02, 2013 1970 bgonzale Removed Table annotation, changed from Entity
* annotation to MappedSuperClass.
*
* </pre>
*
* @author jkorman
* @version 1.0
*/
@Entity
@SequenceGenerator(initialValue = 1, name = PluginDataObject.ID_GEN, sequenceName = "bufrmosseq")
@Table(name = "bufrmos", uniqueConstraints = { @UniqueConstraint(columnNames = { "dataURI" }) })
@MappedSuperclass
@SequenceGenerator(name = PluginDataObject.ID_GEN)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@DynamicSerialize

View file

@ -36,7 +36,7 @@
factory-method="getInstance" depends-on="commonTimeRegistered">
</bean>
<bean factory-bean="siteAwareRegistry" factory-method="register">
<bean id="gfeSitesActive" factory-bean="siteAwareRegistry" factory-method="register">
<constructor-arg ref="gfeSiteActivation" />
</bean>

View file

@ -465,9 +465,8 @@
<property name="threads" value="1"/>
<property name="runningTimeOutMillis" value="300000"/>
<property name="threadSleepInterval" value="5000"/>
<property name="initialDelay" value="120000"/>
</bean>
<bean depends-on="gfeDbRegistered" id="sendIscSrv" class="com.raytheon.edex.plugin.gfe.isc.SendIscSrv">
<bean depends-on="gfeDbRegistered, gfeSitesActive" id="sendIscSrv" class="com.raytheon.edex.plugin.gfe.isc.SendIscSrv">
<constructor-arg ref="iscSendSrvCfg" />
</bean>
<!-- End ISC Send Beans -->

View file

@ -22,10 +22,9 @@
<property name="pendingInitMinTimeMillis" value="180000"/>
<property name="runningInitTimeOutMillis" value="300000"/>
<property name="threadSleepInterval" value="60000"/>
<property name="initialDelay" value="320000"/>
</bean>
<bean depends-on="gfeDbRegistered" id="smartInitSrv" class="com.raytheon.edex.plugin.gfe.smartinit.SmartInitSrv">
<bean depends-on="gfeDbRegistered, gfeSitesActive" id="smartInitSrv" class="com.raytheon.edex.plugin.gfe.smartinit.SmartInitSrv">
<constructor-arg ref="smartInitSrvCfg" />
</bean>

View file

@ -27,19 +27,20 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.LockOptions;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID;
import com.raytheon.uf.common.dataplugin.gfe.server.lock.Lock;
import com.raytheon.uf.common.dataplugin.gfe.server.lock.LockTable;
import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand;
import com.raytheon.uf.common.message.WsId;
import com.raytheon.uf.common.time.TimeRange;
import com.raytheon.uf.common.util.CollectionUtil;
import com.raytheon.uf.edex.database.DataAccessLayerException;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
import com.raytheon.uf.edex.database.query.DatabaseQuery;
/**
* Data access object for manipulating locks
@ -49,6 +50,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 06/17/08 #940 bphillip Initial Creation
* 04/19/13 rjpeter Normalized GFE Database.
* </pre>
*
* @author bphillip
@ -60,89 +62,12 @@ public class GFELockDao extends CoreDao {
super(DaoConfig.forClass(Lock.class));
}
/**
* Gets all locks held by a specified user
*
* @param wsId
* The workstation ID of the user
* @return All locks held by a specified user
* @throws DataAccessLayerException
* If database errors occur
*/
@SuppressWarnings("unchecked")
public List<Lock> getLocksByOwner(String wsId)
throws DataAccessLayerException {
DatabaseQuery query = new DatabaseQuery(daoClass.getName());
query.addQueryParam("wsId", wsId);
List<Lock> locks = (List<Lock>) queryByCriteria(query);
return locks;
}
/**
* Gets all locks in the specified time range
*
* @param parmId
* The parmId of the locks
* @param timeRange
* The time range to examine
* @return All locks in the specified time range
* @throws DataAccessLayerException
* If database errors occur
*/
@SuppressWarnings("unchecked")
public List<Lock> getLocksInRange(ParmID parmId, TimeRange timeRange)
throws DataAccessLayerException {
DatabaseQuery query = new DatabaseQuery(daoClass.getName());
query.addQueryParam("startTime", timeRange.getStart().getTime(),
QueryOperand.GREATERTHANEQUALS);
query.addQueryParam("endTime", timeRange.getEnd().getTime(),
QueryOperand.LESSTHANEQUALS);
query.addQueryParam("parmId", parmId);
List<Lock> locks = (List<Lock>) queryByCriteria(query);
return locks;
}
/**
* Gets a specific lock
*
* @param parmId
* The parmId of the lock
* @param timeRange
* The time range of the lock
* @param wsId
* The workstation ID of the lock holder
* @return A specific lock
* @throws DataAccessLayerException
* If database errors occur
*/
@SuppressWarnings("unchecked")
public Lock getLock(ParmID parmId, TimeRange timeRange, WsId wsId)
throws DataAccessLayerException {
DatabaseQuery query = new DatabaseQuery(daoClass.getName());
query.addQueryParam("startTime", timeRange.getStart().getTime());
query.addQueryParam("endTime", timeRange.getEnd().getTime());
query.addQueryParam("parmId", parmId);
List<Lock> locks = (List<Lock>) queryByCriteria(query);
if (locks.isEmpty()) {
logger.info("No locks returned for -- ParmID: " + parmId
+ " TimeRange: " + timeRange + " wsId: " + wsId);
return null;
} else if (locks.size() > 1) {
logger.info("Duplicate locks detected for -- ParmID: " + parmId
+ " TimeRange: " + timeRange + " wsId: " + wsId);
return locks.get(0);
} else {
return locks.get(0);
}
}
/**
* Gets locks for the provided list of ParmIDs. The locks are retrieved,
* lock tables are constructed and assigned the provided workstation ID
*
* @param parmIds
* The ParmIDs to get the lock tables for
* The database ParmIDs to get the lock tables for
* @param wsId
* The workstation ID to assign to the lock tables
* @return A map of the ParmID and its associated lock table
@ -150,77 +75,114 @@ public class GFELockDao extends CoreDao {
* If errors occur during database interaction
*/
@SuppressWarnings("unchecked")
public Map<ParmID, LockTable> getLocks(List<ParmID> parmIds, WsId wsId)
public Map<ParmID, LockTable> getLocks(final List<ParmID> parmIds, WsId wsId)
throws DataAccessLayerException {
// The return variable
Map<ParmID, LockTable> lockMap = new HashMap<ParmID, LockTable>();
// Variable to hold the results of the lock table query
List<Lock> queryResult = null;
// Return if no parmIDs are provided
if (parmIds.isEmpty()) {
return Collections.emptyMap();
}
DatabaseQuery query = new DatabaseQuery(daoClass.getName());
query.addQueryParam("parmId", parmIds, QueryOperand.IN);
queryResult = (List<Lock>) queryByCriteria(query);
// The return variable
Map<ParmID, LockTable> lockMap = new HashMap<ParmID, LockTable>(
parmIds.size(), 1);
ParmID lockParmID = null;
for (Lock lock : queryResult) {
lockParmID = lock.getParmId();
LockTable lockTable = lockMap.get(lockParmID);
if (lockTable == null) {
lockTable = new LockTable(lockParmID, new ArrayList<Lock>(),
wsId);
lockMap.put(lockParmID, lockTable);
}
lockTable.addLock(lock);
// create a blank lock table for each parmId ensuring all parms are
// covered
for (ParmID requiredParmId : parmIds) {
lockMap.put(requiredParmId, new LockTable(requiredParmId,
new ArrayList<Lock>(), wsId));
}
/*
* Do a check to make sure all required lock tables are present in the
* map
*/
if (parmIds != null) {
Session sess = null;
Transaction tx = null;
try {
sess = getHibernateTemplate().getSessionFactory().openSession();
tx = sess.beginTransaction();
// reattach object so any parmIds found don't requery
for (ParmID requiredParmId : parmIds) {
if (!lockMap.containsKey(requiredParmId)) {
lockMap.put(requiredParmId, new LockTable(requiredParmId,
new ArrayList<Lock>(0), wsId));
sess.buildLockRequest(LockOptions.NONE).lock(requiredParmId);
}
Query query = sess
.createQuery("FROM Lock WHERE parmId IN (:parmIds)");
query.setParameterList("parmIds", parmIds);
List<Lock> locks = query.list();
tx.commit();
// populate Lock table
for (Lock lock : locks) {
lockMap.get(lock.getParmId()).addLock(lock);
}
return lockMap;
} catch (Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (Exception e1) {
logger.error("Error occurred rolling back transaction", e1);
}
}
throw new DataAccessLayerException(
"Unable to look up locks for parmIds " + parmIds, e);
} finally {
if (sess != null) {
try {
sess.close();
} catch (Exception e) {
statusHandler.error(
"Error occurred closing database session", e);
}
}
}
return lockMap;
}
/**
* Updates additions and deletions to the lock table in a single transaction
* Adds and removes the passed locks.
*
* @param locksToDelete
* The locks to delete
* @param locksToAdd
* The locks to add
*/
public void updateCombinedLocks(Collection<Lock> locksToDelete,
Collection<Lock> locksToAdd) throws DataAccessLayerException {
if (!locksToDelete.isEmpty() || !locksToAdd.isEmpty()) {
Session s = this.getHibernateTemplate().getSessionFactory()
.openSession();
Transaction tx = s.beginTransaction();
try {
public void addRemoveLocks(final Collection<Lock> locksToAdd,
final Collection<Integer> locksToDelete)
throws DataAccessLayerException {
StatelessSession s = null;
Transaction tx = null;
try {
s = this.getHibernateTemplate().getSessionFactory()
.openStatelessSession();
tx = s.beginTransaction();
if (!CollectionUtil.isNullOrEmpty(locksToDelete)) {
Query q = s
.createQuery("DELETE FROM Lock WHERE id IN (:locksToDelete)");
q.setParameterList("locksToDelete", locksToDelete);
q.executeUpdate();
}
if (!CollectionUtil.isNullOrEmpty(locksToAdd)) {
for (Lock lock : locksToAdd) {
s.save(lock);
s.insert(lock);
}
for (Lock lock : locksToDelete) {
s.delete(lock);
}
tx.commit();
} catch (Throwable e) {
tx.rollback();
throw new DataAccessLayerException("Error combining locks", e);
} finally {
if (s != null) {
}
tx.commit();
} catch (Throwable e) {
tx.rollback();
throw new DataAccessLayerException("Error combining locks", e);
} finally {
if (s != null) {
try {
s.close();
} catch (Exception e) {
statusHandler.error(
"Error occurred closing database session", e);
}
}
}

View file

@ -40,7 +40,6 @@ import com.raytheon.edex.plugin.gfe.server.GridParmManager;
import com.raytheon.edex.plugin.gfe.util.SendNotifications;
import com.raytheon.uf.common.dataplugin.PluginException;
import com.raytheon.uf.common.dataplugin.gfe.GridDataHistory;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID;
import com.raytheon.uf.common.dataplugin.gfe.server.message.ServerResponse;
import com.raytheon.uf.common.dataplugin.gfe.server.notify.GridHistoryUpdateNotification;
@ -63,7 +62,8 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory;
* 07/06/09 1995 bphillip Initial release
* 04/06/12 #457 dgilling Move call to delete records
* from queue into run().
*
* 04/23/13 #1949 rjpeter Move setting of lastSentTime to dao
* and removed initial delay.
* </pre>
*
* @author bphillip
@ -78,14 +78,12 @@ public class IscSendJob implements Runnable {
private static final SimpleDateFormat ISC_EXTRACT_DATE = new SimpleDateFormat(
"yyyyMMdd_HHmm");
private Map<String, IscSendScript> scripts;
private final Map<String, IscSendScript> scripts;
private int runningTimeOutMillis;
private int threadSleepInterval;
private int initialDelay;
/**
* Constructs a new IscSendJob
*
@ -98,14 +96,11 @@ public class IscSendJob implements Runnable {
scripts = new HashMap<String, IscSendScript>();
runningTimeOutMillis = 300000;
threadSleepInterval = 30000;
initialDelay = 120000;
}
@Override
public void run() {
long curTime = System.currentTimeMillis();
while ((!EDEXUtil.isRunning())
|| ((System.currentTimeMillis() - curTime) < initialDelay)) {
while (!EDEXUtil.isRunning()) {
try {
Thread.sleep(threadSleepInterval);
} catch (Throwable t) {
@ -205,6 +200,7 @@ public class IscSendJob implements Runnable {
}
try {
// TODO: Interact with IFPGridDatabase
GFEDao dao = (GFEDao) PluginFactory.getInstance().getPluginDao(
"gfe");
@ -216,31 +212,14 @@ public class IscSendJob implements Runnable {
}
WsId wsId = new WsId(InetAddress.getLocalHost(), "ISC", "ISC");
List<TimeRange> inventory = sr.getPayload();
List<TimeRange> overlapTimes = new ArrayList<TimeRange>();
for (TimeRange range : inventory) {
if (tr.contains(range)) {
overlapTimes.add(range);
}
}
List<GridHistoryUpdateNotification> notifications = new ArrayList<GridHistoryUpdateNotification>();
List<GFERecord> records = dao.getRecords(id, overlapTimes);
for (GFERecord record : records) {
List<GridDataHistory> history = record.getGridHistory();
Map<TimeRange, List<GridDataHistory>> historyMap = new HashMap<TimeRange, List<GridDataHistory>>();
Date now = new Date();
for (GridDataHistory hist : history) {
hist.setLastSentTime(now);
}
historyMap.put(record.getTimeRange(), history);
dao.saveOrUpdate(record);
notifications.add(new GridHistoryUpdateNotification(id,
historyMap, wsId, siteId));
}
List<GridHistoryUpdateNotification> notifications = new ArrayList<GridHistoryUpdateNotification>(
1);
Map<TimeRange, List<GridDataHistory>> histories = dao
.updateSentTime(id, tr, new Date());
notifications.add(new GridHistoryUpdateNotification(id,
histories, wsId, siteId));
SendNotifications.send(notifications);
} catch (PluginException e) {
statusHandler.error("Error creating GFE dao!", e);
} catch (Exception e) {
@ -268,12 +247,4 @@ public class IscSendJob implements Runnable {
public void setThreadSleepInterval(int threadSleepInterval) {
this.threadSleepInterval = threadSleepInterval;
}
public int getInitialDelay() {
return initialDelay;
}
public void setInitialDelay(int initialDelay) {
this.initialDelay = initialDelay;
}
}

View file

@ -78,6 +78,7 @@ public class IscSendRecord implements IPersistableDataObject, Serializable,
@GeneratedValue()
private int key;
// TODO: Normalize with parmId table
@DynamicSerializeElement
@Column(nullable = false)
@Type(type = "com.raytheon.uf.common.dataplugin.gfe.db.type.ParmIdType")
@ -143,7 +144,7 @@ public class IscSendRecord implements IPersistableDataObject, Serializable,
*/
@Override
public IscSendRecord clone() throws CloneNotSupportedException {
IscSendRecord rval = new IscSendRecord(this.parmID.clone(),
IscSendRecord rval = new IscSendRecord(this.parmID,
this.timeRange.clone(), this.xmlDest, this.state);
rval.setInsertTime((Date) this.insertTime.clone());
return rval;

View file

@ -52,7 +52,6 @@ public class SendIscSrv {
IscSendJob thread = new IscSendJob();
thread.setRunningTimeOutMillis(cfg.getRunningTimeOutMillis());
thread.setThreadSleepInterval(cfg.getThreadSleepInterval());
thread.setInitialDelay(cfg.getInitialDelay());
executor.execute(thread);
}
}

View file

@ -30,8 +30,8 @@ import java.util.concurrent.Executor;
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Oct 20, 2011 dgilling Initial creation
*
* Oct 20, 2011 dgilling Initial creation
* Apr 30, 2013 1949 rjpeter Removed initial delay.
* </pre>
*
* @author dgilling
@ -48,8 +48,6 @@ public class SendIscSrvConfig {
protected int threadSleepInterval;
protected int initialDelay;
public int getThreads() {
return threads;
}
@ -81,12 +79,4 @@ public class SendIscSrvConfig {
public void setThreadSleepInterval(int threadSleepInterval) {
this.threadSleepInterval = threadSleepInterval;
}
public int getInitialDelay() {
return initialDelay;
}
public void setInitialDelay(int initialDelay) {
this.initialDelay = initialDelay;
}
}

View file

@ -60,6 +60,7 @@ import com.raytheon.uf.common.util.mapping.MultipleMappingException;
* extension.
* Mar 20, 2013 #1774 randerso Added getModelInfo,
* added Dflt if no levels specified
* Apr 30, 2013 1961 bsteffen Add ability to disable grib tables.
*
* </pre>
*
@ -73,6 +74,12 @@ public class GridParamInfoLookup {
/** The singleton instance */
private static GridParamInfoLookup instance;
/**
* Temporary boolean to enable or disable loading deprecated grib
* definitions
*/
private static boolean loadGribDefs = false;
/** Parameter information map */
private Map<String, GridParamInfo> modelParamMap;
@ -88,6 +95,17 @@ public class GridParamInfoLookup {
return instance;
}
public static synchronized boolean enableLoadGribDefs() {
GridParamInfoLookup.loadGribDefs = true;
if(instance != null){
System.err.println("setLoadGribDefs was called too late.");
// this will trigger a complete reload. In testing it is never
// called too late, this is paranoia code.
instance = null;
}
return GridParamInfoLookup.loadGribDefs;
}
/**
* Creates a new GribParamInfoLookup instance
*/
@ -172,9 +190,16 @@ public class GridParamInfoLookup {
private void init() {
Unmarshaller um = null;
try {
JAXBContext context = JAXBContext.newInstance(ParameterInfo.class,
GridParamInfo.class, GribParamInfo.class);
um = context.createUnmarshaller();
if (loadGribDefs) {
JAXBContext context = JAXBContext.newInstance(
ParameterInfo.class, GridParamInfo.class,
GribParamInfo.class);
um = context.createUnmarshaller();
} else {
JAXBContext context = JAXBContext.newInstance(
ParameterInfo.class, GridParamInfo.class);
um = context.createUnmarshaller();
}
} catch (JAXBException e) {
statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e);
return;
@ -194,33 +219,41 @@ public class GridParamInfoLookup {
if (!modelParamMap.containsKey(key)) {
modelParamMap.put(key, paramInfo);
}
if (paramInfo instanceof GribParamInfo) {
statusHandler.info("Loaded deprecated gribParamInfo for "
+ key);
}
} catch (JAXBException e) {
statusHandler.handle(Priority.PROBLEM,
"Error unmarshalling grid parameter information", e);
}
}
if (loadGribDefs) {
// Deprecated grib SITE level files.
files = pm.listFiles(pm.getContext(LocalizationType.EDEX_STATIC,
LocalizationLevel.SITE), "grib" + IPathManager.SEPARATOR
+ "parameterInfo", new String[] { ".xml" }, true, true);
for (LocalizationFile file : files) {
statusHandler.info("Loading deprecated paramInfo file: "
+ file.getFile());
String name = file.getFile().getName().replace(".xml", "");
// Do not override grid files.
if (modelParamMap.get(name) != null) {
continue;
}
// Deprecated grib SITE level files.
files = pm.listFiles(pm.getContext(LocalizationType.EDEX_STATIC,
LocalizationLevel.SITE), "grib" + IPathManager.SEPARATOR
+ "parameterInfo", new String[] { ".xml" }, true, true);
for (LocalizationFile file : files) {
String name = file.getFile().getName().replace(".xml", "");
// Do not override grid files.
if (modelParamMap.get(name) != null) {
continue;
}
try {
GridParamInfo paramInfo = (GridParamInfo) um.unmarshal(file
.getFile());
modelParamMap.put(name, paramInfo);
} catch (JAXBException e) {
statusHandler.handle(Priority.PROBLEM,
"Error unmarshalling grid parameter information", e);
try {
GridParamInfo paramInfo = (GridParamInfo) um.unmarshal(file
.getFile());
modelParamMap.put(name, paramInfo);
} catch (JAXBException e) {
statusHandler
.handle(Priority.PROBLEM,
"Error unmarshalling grid parameter information",
e);
}
}
}
for (GridParamInfo gridParamInfo : modelParamMap.values()) {
for (String parmName : gridParamInfo.getParmNames()) {
ParameterInfo parameterInfo = gridParamInfo

View file

@ -31,12 +31,12 @@ import com.raytheon.edex.plugin.gfe.db.dao.GFEDao;
import com.raytheon.edex.plugin.gfe.server.database.D2DGridDatabase;
import com.raytheon.edex.plugin.gfe.server.database.GridDatabase;
import com.raytheon.edex.plugin.gfe.server.lock.LockManager;
import com.raytheon.uf.common.dataplugin.PluginException;
import com.raytheon.uf.common.dataplugin.gfe.GridDataHistory;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GridParmInfo;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.TimeConstraints;
import com.raytheon.uf.common.dataplugin.gfe.server.lock.Lock;
import com.raytheon.uf.common.dataplugin.gfe.server.lock.LockTable;
import com.raytheon.uf.common.dataplugin.gfe.server.lock.LockTable.LockMode;
import com.raytheon.uf.common.dataplugin.gfe.server.message.ServerResponse;
@ -50,7 +50,14 @@ import com.raytheon.uf.common.dataplugin.gfe.slice.DiscreteGridSlice;
import com.raytheon.uf.common.dataplugin.gfe.slice.IGridSlice;
import com.raytheon.uf.common.dataplugin.gfe.slice.WeatherGridSlice;
import com.raytheon.uf.common.message.WsId;
import com.raytheon.uf.common.status.IPerformanceStatusHandler;
import com.raytheon.uf.common.status.IUFStatusHandler;
import com.raytheon.uf.common.status.PerformanceStatus;
import com.raytheon.uf.common.status.UFStatus;
import com.raytheon.uf.common.time.TimeRange;
import com.raytheon.uf.common.time.util.ITimer;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.common.util.CollectionUtil;
import com.raytheon.uf.edex.database.plugin.PluginFactory;
/**
@ -64,9 +71,10 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory;
* ------------ ---------- ----------- --------------------------
* 04/08/08 #875 bphillip Initial Creation
* 06/17/08 #940 bphillip Implemented GFE Locking
* 02/10/13 #1603 randerso Returned number of records purged from timePurge
* 03/15/13 #1795 njensen Added updatePublishTime()
*
* 02/10/13 #1603 randerso Returned number of records purged from timePurge
* 03/15/13 #1795 njensen Added updatePublishTime()
* 04/23/13 #1949 rjpeter Removed excess validation on retrieval, added
* inventory for a given time range.
* </pre>
*
* @author bphillip
@ -74,6 +82,13 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory;
*/
public class GridParm {
// separate logger for GFE performance logging
private final IPerformanceStatusHandler perfLog = PerformanceStatus
.getHandler("GFE:");
private static final transient IUFStatusHandler statusHandler = UFStatus
.getHandler(GridParm.class);
/** The parm ID associated with this GridParm */
private ParmID id;
@ -120,6 +135,16 @@ public class GridParm {
return db.getGridInventory(id);
}
/**
* Returns the grid inventory for this parameter that overlaps the given
* timeRange
*
* @return The server response containing the grid inventory
*/
public ServerResponse<List<TimeRange>> getGridInventory(TimeRange tr) {
return db.getGridInventory(id, tr);
}
/**
* Returns the grid history for this parameter and specified grids through
* history. Returns the status
@ -133,12 +158,6 @@ public class GridParm {
return db.getGridHistory(id, trs);
}
@Deprecated
public ServerResponse<?> updateGridHistory(
Map<TimeRange, List<GridDataHistory>> history) {
return db.updateGridHistory(id, history);
}
/**
* Updates the publish times in the database of all provided
* GridDataHistories. Does not alter the publish times in memory.
@ -228,8 +247,13 @@ public class GridParm {
}
// validate the data
ITimer timer = TimeUtil.getTimer();
timer.start();
sr.addMessages(recordsOkay(saveRequest.getGridSlices(),
new ArrayList<TimeRange>()));
new ArrayList<TimeRange>(0)));
timer.stop();
perfLog.logDuration("Validating " + saveRequest.getGridSlices().size()
+ " grids for saving", timer.getElapsedTime());
if (!sr.isOkay()) {
return sr;
}
@ -286,45 +310,20 @@ public class GridParm {
// Get current inventory
List<TimeRange> reqTimes = getRequest.getTimes();
// TODO do we really need this time range check? it's not worth much
// njensen made it only work on non-D2D databases since
// it was slowing down smart init
if (!id.getDbId().getDbType().equals("D2D")) {
List<TimeRange> trs = null;
ServerResponse<List<TimeRange>> ssr = getGridInventory();
trs = ssr.getPayload();
sr.addMessages(ssr);
if (!CollectionUtil.isNullOrEmpty(reqTimes)) {
// Get the data
if (getRequest.isConvertUnit() && (db instanceof D2DGridDatabase)) {
sr = ((D2DGridDatabase) db).getGridData(id, reqTimes,
getRequest.isConvertUnit());
} else {
sr = db.getGridData(id, reqTimes);
}
if (!sr.isOkay()) {
sr.addMessage("Cannot get grid data with the get inventory failure");
sr.addMessage("Failure in retrieving grid data from GridDatabase");
return sr;
}
// Ensure that all requested time ranges are in the inventory
if (!trs.containsAll(reqTimes)) {
sr.addMessage("Some of the requested time ranges are not in the inventory."
+ " Inv: "
+ trs
+ " requestTimes: "
+ getRequest.getTimes());
return sr;
}
}
// Get the data
if (getRequest.isConvertUnit() && (db instanceof D2DGridDatabase)) {
sr = ((D2DGridDatabase) db).getGridData(id, reqTimes,
getRequest.isConvertUnit());
} else {
sr = db.getGridData(id, reqTimes);
}
if (!sr.isOkay()) {
sr.addMessage("Failure in retrieving grid data from GridDatabase");
return sr;
}
// Validate the data
sr.addMessages(dataOkay(sr.getPayload(), badDataTimes));
if (!sr.isOkay()) {
sr.addMessage("Cannot get grid data - data is not valid");
sr.setPayload(new ArrayList<IGridSlice>(0));
}
return sr;
@ -374,52 +373,49 @@ public class GridParm {
// Get the lock table
WsId wsId = new WsId(null, "timePurge", "EDEX");
List<LockTable> lts = new ArrayList<LockTable>();
List<LockTable> lts = new ArrayList<LockTable>(0);
LockTableRequest lockreq = new LockTableRequest(this.id);
ServerResponse<List<LockTable>> ssr2 = LockManager.getInstance()
.getLockTables(lockreq, wsId, siteID);
sr.addMessages(ssr2);
lts = ssr2.getPayload();
if (!sr.isOkay() || lts.size() != 1) {
if (!sr.isOkay() || (lts.size() != 1)) {
sr.addMessage("Cannot timePurge since getting lock table failed");
}
List<TimeRange> breakList = new ArrayList<TimeRange>();
List<TimeRange> noBreak = new ArrayList<TimeRange>();
for (int i = 0; i < lts.get(0).getLocks().size(); i++) {
if (lts.get(0).getLocks().get(i).getTimeRange().getEnd()
.before(purgeTime)
|| lts.get(0).getLocks().get(i).getTimeRange().getEnd()
.equals(purgeTime)) {
breakList.add(lts.get(0).getLocks().get(i).getTimeRange());
LockTable myLockTable = lts.get(0);
for (Lock lock : myLockTable.getLocks()) {
if (lock.getEndTime() < purgeTime.getTime()) {
breakList.add(lock.getTimeRange());
} else {
noBreak.add(lts.get(0).getLocks().get(i).getTimeRange());
noBreak.add(lock.getTimeRange());
}
}
List<TimeRange> purge = new ArrayList<TimeRange>();
for (int i = 0; i < trs.size(); i++) {
if (trs.get(i).getEnd().before(purgeTime)
|| trs.get(i).getEnd().equals(purgeTime)) {
for (TimeRange tr : trs) {
if (tr.getEnd().getTime() <= purgeTime.getTime()) {
boolean found = false;
for (int j = 0; j < noBreak.size(); j++) {
if (noBreak.get(j).contains(trs.get(i))) {
for (TimeRange noBreakTr : noBreak) {
if (noBreakTr.contains(tr)) {
found = true;
break;
}
}
if (!found) {
purge.add(trs.get(i));
purge.add(tr);
}
}
}
List<LockRequest> lreqs = new ArrayList<LockRequest>();
List<LockTable> ltChanged = new ArrayList<LockTable>();
for (int i = 0; i < breakList.size(); i++) {
lreqs.add(new LockRequest(id, breakList.get(i), LockMode.BREAK_LOCK));
for (TimeRange tr : breakList) {
lreqs.add(new LockRequest(id, tr, LockMode.BREAK_LOCK));
}
ServerResponse<List<LockTable>> lockResponse = LockManager
@ -434,25 +430,24 @@ public class GridParm {
for (int i = 0; i < ltChanged.size(); i++) {
lockNotifications
.add(new LockNotification(ltChanged.get(i), siteID));
// gridNotifications.add(new GridUpdateNotification(id, breakList
// .get(i), Arrays.asList, ""));
}
GFEDao dao = null;
try {
dao = (GFEDao) PluginFactory.getInstance().getPluginDao("gfe");
} catch (PluginException e) {
sr.addMessage("Unable to get gfe dao");
}
dao.deleteRecords(id, purge);
for (int i = 0; i < purge.size(); i++) {
// assemble the GridUpdateNotification
dao.deleteRecords(id, purge);
Map<TimeRange, List<GridDataHistory>> histories = new HashMap<TimeRange, List<GridDataHistory>>(
0);
gridNotifications.add(new GridUpdateNotification(id, purge.get(i),
histories, wsId, siteID));
for (TimeRange tr : purge) {
// assemble the GridUpdateNotification
gridNotifications.add(new GridUpdateNotification(id, tr,
histories, wsId, siteID));
}
sr.setPayload(new Integer(purge.size()));
} catch (Exception e) {
sr.addMessage("Failed to delete records for timePurge");
statusHandler.error("Failed to delete records for timePurge", e);
}
sr.setPayload(new Integer(purge.size()));
return sr;
}
@ -469,20 +464,6 @@ public class GridParm {
return "ParmID: " + id;
}
private ServerResponse<?> dataOkay(List<IGridSlice> gridSlices,
List<TimeRange> badDataTimes) {
ServerResponse<?> sr = new ServerResponse<String>();
for (IGridSlice slice : gridSlices) {
ServerResponse<?> sr1 = gridSliceOkay(slice);
sr.addMessages(sr1);
if (!sr1.isOkay()) {
badDataTimes.add(slice.getValidTime());
}
}
return sr;
}
/**
* Checks the data to ensure that it is valid. If there is a bad data slice,
* then place the valid time of that grid in the badDataTimes entry.
@ -582,7 +563,7 @@ public class GridParm {
.getLockTables(req, requestor, siteID);
lockTables = ssr.getPayload();
sr.addMessages(ssr);
if (!sr.isOkay() || lockTables.size() != 1) {
if (!sr.isOkay() || (lockTables.size() != 1)) {
sr.addMessage("Cannot verify locks due to problem with Lock Manager");
return sr;

View file

@ -69,6 +69,7 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
import com.raytheon.uf.common.time.TimeRange;
import com.raytheon.uf.common.time.util.ITimer;
import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.edex.database.DataAccessLayerException;
import com.raytheon.uf.edex.database.plugin.PluginFactory;
import com.raytheon.uf.edex.database.purge.PurgeLogger;
@ -89,11 +90,11 @@ import com.raytheon.uf.edex.database.purge.PurgeLogger;
* fixed a purge inefficiency,
* fixed error which caused D2D purging to remove
* smartInit hdf5 data
* 03/07/13 #1773 njensen Logged commitGrid() times
* 03/15/13 #1795 njensen Sped up commitGrid()
* 03/20/2013 #1774 randerso Removed dead method, changed to use new
* 03/07/13 #1773 njensen Logged commitGrid() times
* 03/15/13 #1795 njensen Sped up commitGrid()
* 03/20/2013 #1774 randerso Removed dead method, changed to use new
* D2DGridDatabase constructor
*
* 04/23/2013 #1949 rjpeter Added inventory retrieval for a given time range.
* </pre>
*
* @author bphillip
@ -174,6 +175,39 @@ public class GridParmManager {
return sr;
}
/**
* Returns the grid inventory overlapping timeRange for the parmId. Returns
* the status. Calls gridParm() to look up the parameter. If not found,
* returns the appropriate error. Calls the grid parm's getGridInventory()
* to obtain the inventory.
*
* @param parmId
* The parmID to get the inventory for
* @param timeRange
* The timeRange to get the inventory for
* @return The server response
*/
public static ServerResponse<List<TimeRange>> getGridInventory(
ParmID parmId, TimeRange timeRange) {
ServerResponse<List<TimeRange>> sr = new ServerResponse<List<TimeRange>>();
try {
GridParm gp = gridParm(parmId);
if (gp.isValid()) {
sr = gp.getGridInventory(timeRange);
} else {
sr.addMessage("Unknown Parm: " + parmId
+ " in getGridInventory()");
}
} catch (Exception e) {
sr.addMessage("Unknown Parm: " + parmId + " in getGridInventory()");
logger.error("Unknown Parm: " + parmId + " in getGridInventory()",
e);
}
return sr;
}
/**
* Returns the grid history through "history" for the parmId and specified
* grids. Returns the status.
@ -485,6 +519,9 @@ public class GridParmManager {
continue;
}
// TODO: No need to get inventory and then compare for history
// times, just request the history times directly
// get the source data inventory
inventoryTimer.start();
ServerResponse<List<TimeRange>> invSr = sourceGP.getGridInventory();
@ -543,14 +580,14 @@ public class GridParmManager {
// if update time is less than publish time, grid has not
// changed since last published, therefore only update
// history, do not publish
if (gdh.getPublishTime() == null
if ((gdh.getPublishTime() == null)
|| (gdh.getUpdateTime().getTime() > gdh
.getPublishTime().getTime())
// in service backup, times on srcHistory could
// appear as not needing a publish, even though
// dest data does not exist
|| currentDestHistory.get(tr) == null
|| currentDestHistory.get(tr).size() == 0) {
|| (currentDestHistory.get(tr) == null)
|| (currentDestHistory.get(tr).size() == 0)) {
doPublish = true;
}
}
@ -778,11 +815,18 @@ public class GridParmManager {
public static ServerResponse<List<DatabaseID>> getDbInventory(String siteID) {
ServerResponse<List<DatabaseID>> sr = new ServerResponse<List<DatabaseID>>();
List<DatabaseID> databases = new ArrayList<DatabaseID>();
List<DatabaseID> gfeDbs = gfeDao.getDatabaseInventory();
List<DatabaseID> gfeDbs = null;
List<DatabaseID> singletons = null;
List<DatabaseID> d2dDbs = null;
try {
gfeDbs = gfeDao.getDatabaseInventory(siteID);
} catch (DataAccessLayerException e) {
sr.addMessage("Unable to get IFP databases for site: " + siteID);
logger.error("Unable to get IFP databases for site: " + siteID, e);
return sr;
}
d2dDbs = D2DParmIdCache.getInstance().getDatabaseIDs();
try {
@ -793,6 +837,7 @@ public class GridParmManager {
logger.error("Unable to get singleton databases", e);
return sr;
}
if (singletons != null) {
for (DatabaseID singleton : singletons) {
if (singleton.getSiteId().equals(siteID)) {
@ -800,11 +845,13 @@ public class GridParmManager {
}
}
}
for (DatabaseID dbId : gfeDbs) {
if (!databases.contains(dbId) && dbId.getSiteId().equals(siteID)) {
if (!databases.contains(dbId)) {
databases.add(dbId);
}
}
if (d2dDbs != null) {
for (DatabaseID d2d : d2dDbs) {
if (d2d.getSiteId().equals(siteID)) {
@ -815,9 +862,7 @@ public class GridParmManager {
DatabaseID topoDbId = TopoDatabaseManager.getTopoDbId(siteID);
databases.add(topoDbId);
databases.addAll(NetCDFDatabaseManager.getDatabaseIds(siteID));
sr.setPayload(databases);
return sr;
}
@ -994,7 +1039,7 @@ public class GridParmManager {
// process the id and determine whether it should be purged
count++;
if (count > desiredVersions
if ((count > desiredVersions)
&& !dbId.getModelTime().equals(DatabaseID.NO_MODEL_TIME)) {
deallocateDb(dbId, true);
PurgeLogger.logInfo("Purging " + dbId, "gfe");
@ -1114,7 +1159,7 @@ public class GridParmManager {
* Validate the database ID. Throws an exception if the database ID is
* invalid
*/
if (!dbId.isValid() || dbId.getFormat() != DatabaseID.DataType.GRID) {
if (!dbId.isValid() || (dbId.getFormat() != DatabaseID.DataType.GRID)) {
throw new GfeException(
"Database id "
+ dbId
@ -1192,15 +1237,11 @@ public class GridParmManager {
}
public static void purgeDbCache(String siteID) {
List<DatabaseID> toRemove = new ArrayList<DatabaseID>();
for (DatabaseID dbId : dbMap.keySet()) {
if (dbId.getSiteId().equals(siteID)) {
toRemove.add(dbId);
removeDbFromMap(dbId);
}
}
for (DatabaseID dbId : toRemove) {
removeDbFromMap(dbId);
}
}
private static ServerResponse<GridDatabase> getOfficialDB(

View file

@ -25,6 +25,7 @@ import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import com.raytheon.uf.common.dataplugin.gfe.GridDataHistory;
@ -72,8 +73,9 @@ import com.raytheon.uf.common.time.TimeRange;
* in the gfeBaseDataDir.
* 02/10/13 #1603 randerso Moved removeFromDb, removeFromHDF5 and deleteModelHDF5
* methods down to IFPGridDatabase
* 03/15/13 #1795 njensen Added updatePublishTime()
*
* 03/15/13 #1795 njensen Added updatePublishTime()
* 04/23/13 #1949 rjpeter Added default implementations of history by time range
* and cachedParmId
* </pre>
*
* @author bphillip
@ -348,6 +350,29 @@ public abstract class GridDatabase {
*/
public abstract ServerResponse<List<TimeRange>> getGridInventory(ParmID id);
/**
* Gets the inventory of time ranges currently for the specified ParmID that
* overlap the given time range.
*
* @param id
* The parmID to get the inventory for
* @return The server response
*/
public ServerResponse<List<TimeRange>> getGridInventory(ParmID id,
TimeRange tr) {
// default to prior behavior with removing the extra inventories
ServerResponse<List<TimeRange>> sr = getGridInventory(id);
List<TimeRange> trs = sr.getPayload();
ListIterator<TimeRange> iter = trs.listIterator(trs.size());
while (iter.hasPrevious()) {
TimeRange curTr = iter.previous();
if (!curTr.overlaps(tr)) {
iter.remove();
}
}
return sr;
}
/**
* Retrieves a sequence gridSlices from the database based on the specified
* parameters and stores them in the data parameter. TimeRanges of the grids
@ -438,12 +463,6 @@ public abstract class GridDatabase {
+ this.getClass().getName());
}
public ServerResponse<?> updateGridHistory(ParmID parmId,
Map<TimeRange, List<GridDataHistory>> history) {
throw new UnsupportedOperationException("Not implemented for class "
+ this.getClass().getName());
}
/**
* Updates the publish times in the database of all provided
* GridDataHistories. Does not alter the publish times in memory.
@ -469,4 +488,16 @@ public abstract class GridDatabase {
}
public abstract void updateDbs();
/**
* Return the internally cache'd parmID for this database implementation.
*
* @param parmID
* @return
* @throws GfeException
* If the parm does not exist for this database.
*/
public ParmID getCachedParmID(ParmID parmID) throws GfeException {
return parmID;
}
}

View file

@ -61,7 +61,7 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
* Jun 19, 2008 #1160 randerso Initial creation
* Jul 10, 2009 #2590 njensen Support for multiple sites.
* May 04, 2012 #574 dgilling Re-port to better match AWIPS1.
*
* Apr 23, 2013 #1949 rjpeter Removed unused method.
* </pre>
*
* @author randerso
@ -70,13 +70,13 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
public class TopoDatabase extends VGridDatabase {
private static final TimeRange TR = TimeRange.allTimes();
private TopoDatabaseManager topoMgr;
private final TopoDatabaseManager topoMgr;
private GridLocation gloc;
private final GridLocation gloc;
private ParmID pid;
private final ParmID pid;
private GridParmInfo gpi;
private final GridParmInfo gpi;
public TopoDatabase(final IFPServerConfig config,
TopoDatabaseManager topoMgr) {
@ -195,7 +195,7 @@ public class TopoDatabase extends VGridDatabase {
if (!this.pid.equals(id)) {
sr.addMessage("Unknown ParmID: " + id);
} else if (timeRanges.size() != 1 || !timeRanges.get(0).equals(TR)) {
} else if ((timeRanges.size() != 1) || !timeRanges.get(0).equals(TR)) {
sr.addMessage("Invalid time requested");
} else {
@ -278,21 +278,6 @@ public class TopoDatabase extends VGridDatabase {
// no-op
}
/*
* (non-Javadoc)
*
* @see
* com.raytheon.edex.plugin.gfe.server.database.GridDatabase#updateGridHistory
* (com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID, java.util.Map)
*/
@Override
public ServerResponse<?> updateGridHistory(ParmID parmId,
Map<TimeRange, List<GridDataHistory>> history) {
ServerResponse<?> sr = new ServerResponse<Object>();
sr.addMessage("Can't update Grid History on TopoDatabase");
return sr;
}
/*
* (non-Javadoc)
*

View file

@ -1,54 +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.edex.plugin.gfe.server.handler;
import java.util.Date;
import com.raytheon.edex.plugin.gfe.db.dao.GFEDao;
import com.raytheon.uf.common.dataplugin.gfe.request.GetLatestDbTimeRequest;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
/**
* Handler for getting the latest insert time for a given database ID
*
* <pre>
*
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 8/16/2010 6349 bphillip Initial creation
*
* </pre>
*
* @author bphillip
* @version 1.0
*/
public class GetLatestDbTimeHandler implements
IRequestHandler<GetLatestDbTimeRequest> {
@Override
public Date handleRequest(GetLatestDbTimeRequest request)
throws Exception {
Date latestDate = new GFEDao().getLatestDbIdInsertTime(request.getDbId());
return latestDate;
}
}

View file

@ -1,61 +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.edex.plugin.gfe.server.handler;
import com.raytheon.edex.plugin.gfe.db.dao.GFEDao;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.DatabaseID;
import com.raytheon.uf.common.dataplugin.gfe.request.GetLatestModelDbIdRequest;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
/**
* Handler for getting the latest DatabaseID for a given model name and site ID.
*
* <pre>
*
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 17, 2010 dgilling Initial creation
*
* </pre>
*
* @author dgilling
* @version 1.0
*/
public class GetLatestModelDbIdHandler implements
IRequestHandler<GetLatestModelDbIdRequest> {
/*
* (non-Javadoc)
*
* @see
* com.raytheon.uf.common.serialization.comm.IRequestHandler#handleRequest
* (com.raytheon.uf.common.serialization.comm.IServerRequest)
*/
@Override
public DatabaseID handleRequest(GetLatestModelDbIdRequest request)
throws Exception {
DatabaseID dbId = new GFEDao().getLatestModelDbId(request.getSiteId(), request
.getModelName());
return dbId;
}
}

View file

@ -43,6 +43,7 @@ import com.raytheon.uf.common.serialization.comm.IRequestHandler;
* 04/08/08 #875 bphillip Initial Creation
* 06/17/08 #940 bphillip Implemented GFE Locking
* 09/22/09 3058 rjpeter Converted to IRequestHandler
* 04/24/13 1949 rjpeter Added list sizing
* </pre>
*
* @author bphillip
@ -59,8 +60,11 @@ public class LockChangeHandler implements IRequestHandler<LockChangeRequest> {
if (sr.isOkay()) {
try {
List<GfeNotification> notes = new ArrayList<GfeNotification>();
for (LockTable table : sr.getPayload()) {
List<LockTable> lockTables = sr.getPayload();
List<GfeNotification> notes = new ArrayList<GfeNotification>(
lockTables.size());
for (LockTable table : lockTables) {
notes.add(new LockNotification(table, siteID));
}
ServerResponse<?> notifyResponse = SendNotifications
@ -75,7 +79,6 @@ public class LockChangeHandler implements IRequestHandler<LockChangeRequest> {
+ e.getMessage());
}
}
return sr;
}
}

View file

@ -59,7 +59,7 @@ import com.raytheon.uf.common.status.UFStatus;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Apr 21, 2011 dgilling Initial creation
*
* Apr 23, 2013 1949 rjpeter Removed extra lock table look up
* </pre>
*
* @author dgilling
@ -149,18 +149,6 @@ public class SaveASCIIGridsHandler implements
// make a LockTableRequest
LockTableRequest ltr = new LockTableRequest(pid);
// get the lock tables
ServerResponse<List<LockTable>> srLockTables = LockManager
.getInstance().getLockTables(ltr,
request.getWorkstationID(), siteId);
if (!srLockTables.isOkay()) {
msg = "Skipping grid storage [" + (i + 1) + " of " + ngrids
+ "]. Unable to obtain lock table for "
+ pid.toString() + ": " + srLockTables.message();
sr.addMessage(msg);
continue;
}
// make the Lock Request object to lock
LockRequest lrl = new LockRequest(pid, agrid.getGridSlices().get(i)
.getValidTime(), LockMode.LOCK);
@ -185,8 +173,7 @@ public class SaveASCIIGridsHandler implements
grid.setMessageData(agrid.getGridSlices().get(i));
grid.setGridHistory(agrid.getGridSlices().get(i).getHistory());
records.add(grid);
final List<SaveGridRequest> sgrs = new ArrayList<SaveGridRequest>();
sgrs.clear();
final List<SaveGridRequest> sgrs = new ArrayList<SaveGridRequest>(1);
SaveGridRequest sgr = new SaveGridRequest(pid, agrid
.getGridSlices().get(i).getValidTime(), records);
sgrs.add(sgr);

View file

@ -21,9 +21,12 @@
package com.raytheon.edex.plugin.gfe.server.lock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
@ -60,7 +63,8 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
* ------------ ---------- ----------- --------------------------
* 04/08/08 #875 bphillip Initial Creation
* 06/17/08 #940 bphillip Implemented GFE Locking
*
* 04/23/13 #1949 rjpeter Updated to work with Normalized Database,
* fixed inefficiencies in querying/merging
* </pre>
*
* @author bphillip
@ -69,22 +73,21 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
public class LockManager {
/** The logger */
private Log logger = LogFactory.getLog(getClass());
private final Log logger = LogFactory.getLog(getClass());
private LockComparator startTimeComparator = new LockComparator();
private final LockComparator startTimeComparator = new LockComparator();
private final GFELockDao dao = new GFELockDao();
/** The singleton instance of the LockManager */
private static LockManager instance;
private static LockManager instance = new LockManager();
/**
* Gets the singleton instance of the LockManager
*
* @return The singleton instance of the LockManager
*/
public synchronized static LockManager getInstance() {
if (instance == null) {
instance = new LockManager();
}
public static LockManager getInstance() {
return instance;
}
@ -117,14 +120,15 @@ public class LockManager {
// extract the ParmIds from the request list
List<ParmID> parmIds = new ArrayList<ParmID>();
sr.addMessages(extractParmIds(request, parmIds, siteID));
try {
sr.setPayload(new ArrayList<LockTable>(new GFELockDao().getLocks(
parmIds, requestor).values()));
} catch (DataAccessLayerException e) {
sr.addMessages(extractParmIds(request, parmIds, siteID));
sr.setPayload(new ArrayList<LockTable>(dao.getLocks(parmIds,
requestor).values()));
} catch (Exception e) {
logger.error("Error getting lock tables for " + parmIds, e);
sr.addMessage("Error getting lock tables for " + parmIds);
sr.setPayload(new ArrayList<LockTable>());
sr.setPayload(new ArrayList<LockTable>(0));
}
return sr;
@ -143,9 +147,7 @@ public class LockManager {
*/
public ServerResponse<List<LockTable>> getLockTables(
LockTableRequest request, WsId wsId, String siteID) {
List<LockTableRequest> requests = new ArrayList<LockTableRequest>();
requests.add(request);
return getLockTables(requests, wsId, siteID);
return getLockTables(Arrays.asList(request), wsId, siteID);
}
public ServerResponse<List<LockTable>> requestLockChange(
@ -167,9 +169,8 @@ public class LockManager {
public ServerResponse<List<LockTable>> requestLockChange(
LockRequest request, WsId requestor, String siteID,
boolean combineLocks) throws GfeLockException {
List<LockRequest> requests = new ArrayList<LockRequest>();
requests.add(request);
return requestLockChange(requests, requestor, siteID, combineLocks);
return requestLockChange(Arrays.asList(request), requestor, siteID,
combineLocks);
}
public ServerResponse<List<LockTable>> requestLockChange(
@ -191,8 +192,8 @@ public class LockManager {
List<LockRequest> requests, WsId requestor, String siteID,
boolean combineLocks) {
List<LockTable> lockTablesAffected = new ArrayList<LockTable>();
List<GridUpdateNotification> gridUpdatesAffected = new ArrayList<GridUpdateNotification>();
List<LockTable> lockTablesAffected = new LinkedList<LockTable>();
List<GridUpdateNotification> gridUpdatesAffected = new LinkedList<GridUpdateNotification>();
ServerResponse<List<LockTable>> sr = new ServerResponse<List<LockTable>>();
sr.setPayload(lockTablesAffected);
@ -205,7 +206,7 @@ public class LockManager {
// expand the request as appropriate to the time boundary requirements
// and convert to all parm-type requests
List<LockRequest> req = new ArrayList<LockRequest>();
List<LockRequest> req = new ArrayList<LockRequest>(requests.size());
sr.addMessages(adjustLockToTimeBoundaries(requests, req));
if (!sr.isOkay()) {
@ -213,85 +214,87 @@ public class LockManager {
return sr;
}
// extract the ParmIds from the requests
List<ParmID> parmIds = new ArrayList<ParmID>();
sr.addMessages(extractParmIdsFromLockReq(req, parmIds, siteID));
// get the lock tables specific to the extracted parmIds
List<ParmID> parmIds = new LinkedList<ParmID>();
Map<ParmID, LockTable> lockTableMap;
try {
lockTableMap = new GFELockDao().getLocks(parmIds, requestor);
} catch (DataAccessLayerException e) {
// extract the ParmIds from the requests
sr.addMessages(extractParmIdsFromLockReq(req, parmIds, siteID));
// get the lock tables specific to the extracted parmIds
lockTableMap = dao.getLocks(parmIds, requestor);
} catch (Exception e) {
logger.error("Error getting lock tables for " + parmIds, e);
sr.addMessage("Error getting lock tables for " + parmIds);
return sr;
}
// process each modified lock request, these are all parm-type requests
ParmID currentParmId = null;
TimeRange currentTimeRange = null;
for (LockRequest currentRequest : req) {
currentParmId = currentRequest.getParmId();
currentTimeRange = currentRequest.getTimeRange();
// get table from sequence
LockTable lt = lockTableMap.get(currentParmId);
LockTable prevLT = lt.clone();
try {
// Change Lock
if (!changeLock(lt, currentRequest.getTimeRange(), requestor,
if (!changeLock(lt, currentTimeRange, requestor,
currentRequest.getMode(), combineLocks)) {
sr.addMessage("Requested change lock failed - Lock is owned by another user - "
+ currentRequest + " LockTable=" + lt);
lockTablesAffected.clear();
gridUpdatesAffected.clear();
return sr;
continue;
}
} catch (Exception e) {
logger.error("Error changing lock", e);
sr.addMessage("Requested change lock failed - Exception thrown - "
+ currentRequest
+ " LockTable="
+ lt
+ " Exception: "
+ e.getLocalizedMessage());
lockTablesAffected.clear();
gridUpdatesAffected.clear();
return sr;
continue;
}
// the change lock worked, but resulted in the same lock situation
if (prevLT.equals(lt)) {
// TODO: Equals not implemented, this is dead code due to clone
continue;
}
// add the lock table to the lockTablesAffected" if it already
// doesn't exist -- if it does exist, then replace it but don't add
// it if it really didn't change
// add the lock table to the lockTablesAffected if it already
// doesn't exist
LockTable tableToRemove = null;
for (int j = 0; j < lockTablesAffected.size(); j++) {
if (lockTablesAffected.get(j).getParmId().equals(currentParmId)) {
tableToRemove = lockTablesAffected.get(j);
boolean addTable = true;
for (LockTable ltAffected : lockTablesAffected) {
if (ltAffected.getParmId().equals(currentParmId)) {
addTable = false;
break;
}
}
if (tableToRemove != null) {
lockTablesAffected.remove(tableToRemove);
if (addTable) {
lockTablesAffected.add(lt);
}
lockTablesAffected.add(lt);
// assemble a grid update notification since the lock table has
// changed - IF this is BREAK LOCK request
if (currentRequest.getMode().equals(LockTable.LockMode.BREAK_LOCK)) {
// TODO: Should be able to do in a single look up that retrieves
// the histories that intersect the time ranges instead of the
// current two stage query
List<TimeRange> trs = new ArrayList<TimeRange>();
ServerResponse<List<TimeRange>> ssr = GridParmManager
.getGridInventory(currentParmId);
.getGridInventory(currentParmId, currentTimeRange);
sr.addMessages(ssr);
trs = ssr.getPayload();
if (!sr.isOkay()) {
lockTablesAffected.clear();
gridUpdatesAffected.clear();
return sr;
// unable to get payload, can't reverse the break lock, add
// a new message to our current response and keep going
sr.addMessages(ssr);
continue;
}
List<TimeRange> updatedGridsTR = new ArrayList<TimeRange>();
for (int p = 0; p < trs.size(); p++) {
if (trs.get(p).overlaps(currentRequest.getTimeRange())) {
@ -312,14 +315,17 @@ public class LockManager {
}
}
// if we made it here, then all lock requests were successful
for (int k = 0; k < lockTablesAffected.size(); k++) {
lockTablesAffected.get(k).resetWsId(requestor);
// update the lockTables that were successful
for (LockTable lt : lockTablesAffected) {
lt.resetWsId(requestor);
}
// process the break lock notifications that were successful
for (GridUpdateNotification notify : gridUpdatesAffected) {
sr.addNotifications(notify);
}
return sr;
}
@ -348,143 +354,161 @@ public class LockManager {
} else if (ls.equals(LockTable.LockStatus.LOCKED_BY_ME)) {
return true;
} else if (ls.equals(LockTable.LockStatus.LOCKABLE)) {
GFELockDao dao = new GFELockDao();
List<Lock> existingLocks = new ArrayList<Lock>();
try {
existingLocks = dao.getLocksInRange(lt.getParmId(),
timeRange);
if (existingLocks != null && !existingLocks.isEmpty()) {
for (Lock lock : existingLocks) {
dao.delete(lock);
lt.removeLock(lock);
}
}
Lock newLock = new Lock(lt.getParmId(), timeRange,
requestorId);
replaceLocks(lt, newLock, combineLocks);
} catch (DataAccessLayerException e) {
logger.error("Error changing locks", e);
logger.error("Error adding lock", e);
throw new GfeLockException("Unable add new lock", e);
}
Lock newLock = new Lock(timeRange, requestorId);
newLock.setParmId(lt.getParmId());
dao.persist(newLock);
try {
newLock = dao.getLock(newLock.getParmId(),
newLock.getTimeRange(), newLock.getWsId());
} catch (DataAccessLayerException e) {
throw new GfeLockException("Unable to update new lock", e);
}
lt.addLock(newLock);
}
if (combineLocks) {
combineLocks(lt);
}
}
else if (lockMode.equals(LockTable.LockMode.UNLOCK)) {
} else if (lockMode.equals(LockTable.LockMode.UNLOCK)) {
if (ls.equals(LockTable.LockStatus.LOCKED_BY_ME)) {
try {
GFELockDao dao = new GFELockDao();
Lock newLock = dao.getLock(lt.getParmId(), timeRange,
requestorId);
if (newLock != null) {
dao.delete(newLock);
lt.removeLock(newLock);
}
deleteLocks(lt, timeRange);
} catch (DataAccessLayerException e) {
throw new GfeLockException(
"Unable to retrieve lock information for: "
+ lt.getParmId() + " TimeRange: "
+ timeRange + " WorkstationID: "
+ requestorId);
throw new GfeLockException("Unable to delete locks for: "
+ lt.getParmId() + " TimeRange: " + timeRange
+ " WorkstationID: " + requestorId);
}
} else if (ls.equals(LockTable.LockStatus.LOCKED_BY_OTHER)) {
logger.warn("Lock for time range: " + timeRange
+ " already owned");
} else {
// Record already unlocked
}
}
else if (lockMode.equals(LockTable.LockMode.BREAK_LOCK)) {
} else if (lockMode.equals(LockTable.LockMode.BREAK_LOCK)) {
try {
GFELockDao dao = new GFELockDao();
Lock newLock = dao.getLock(lt.getParmId(), timeRange,
requestorId);
if (newLock != null) {
dao.delete(newLock);
lt.removeLock(newLock);
}
deleteLocks(lt, timeRange);
} catch (DataAccessLayerException e) {
throw new GfeLockException(
"Unable to retrieve lock information for: "
+ lt.getParmId() + " TimeRange: " + timeRange
+ " WorkstationID: " + requestorId);
throw new GfeLockException("Unable to delete locks for: "
+ lt.getParmId() + " TimeRange: " + timeRange
+ " WorkstationID: " + requestorId);
}
}
return true;
}
/**
* Examines the locks contained in a given lock table and combines locks if
* possible.
* Replaces locks in the given time range with the passed lock.
*
* @param lt
* The lock table to examine
* @param newLock
* The lock to add
* @throws GfeLockException
* If errors occur when updating the locks in the database
*/
private void combineLocks(final LockTable lt) throws GfeLockException {
private void replaceLocks(final LockTable lt, final Lock newLock,
boolean combineLocks) throws DataAccessLayerException {
// update the locks in memory
Set<Lock> added = new HashSet<Lock>();
Set<Lock> deleted = new HashSet<Lock>();
List<Lock> locks = null;
Lock currentLock = null;
Lock nextLock = null;
boolean lockCombined = true;
while (lockCombined) {
lockCombined = false;
lt.addLocks(added);
lt.removeLocks(deleted);
Collections.sort(lt.getLocks(), startTimeComparator);
locks = lt.getLocks();
for (int i = 0; i < locks.size() - 1; i++) {
currentLock = locks.get(i);
nextLock = locks.get(i + 1);
if (currentLock.getEndTime() >= nextLock.getStartTime()
&& currentLock.getWsId().equals(nextLock.getWsId())) {
lockCombined = true;
deleted.add(currentLock);
deleted.add(nextLock);
Lock newLock = new Lock(new TimeRange(
currentLock.getStartTime(), nextLock.getEndTime()),
lt.getWsId());
newLock.setParmId(lt.getParmId());
added.add(newLock);
List<Integer> removed = new ArrayList<Integer>();
List<Lock> locks = lt.getLocks();
Collections.sort(locks, startTimeComparator);
long start = newLock.getStartTime();
long end = newLock.getEndTime();
Iterator<Lock> iter = locks.iterator();
while (iter.hasNext()) {
Lock lock = iter.next();
if (start <= lock.getStartTime()) {
if (end >= lock.getEndTime()) {
removed.add(lock.getId());
iter.remove();
} else {
// list was sorted by start time, not need to go any further
break;
}
}
}
try {
new GFELockDao().updateCombinedLocks(deleted, added);
} catch (DataAccessLayerException e) {
throw new GfeLockException("Error combining locks", e);
added.add(newLock);
locks.add(newLock);
// if combineLocks, do the combine before storing the initial change to
// the db
if (combineLocks) {
Lock prevLock = null;
Lock currentLock = null;
Collections.sort(locks, startTimeComparator);
prevLock = locks.get(0);
for (int i = 1; i < locks.size(); i++) {
currentLock = locks.get(i);
if ((prevLock.getEndTime() >= currentLock.getStartTime())
&& prevLock.getWsId().equals(currentLock.getWsId())) {
// remove previous lock, checking if it was a new lock first
if (!added.remove(prevLock)) {
removed.add(prevLock.getId());
}
// remove currentLock, checking if it was a new lock first
if (!added.remove(currentLock)) {
removed.add(currentLock.getId());
}
locks.remove(i);
// replace prevLock with new Lock
prevLock = new Lock(lt.getParmId(), new TimeRange(
prevLock.getStartTime(), Math.max(
prevLock.getEndTime(),
currentLock.getEndTime())), lt.getWsId());
added.add(prevLock);
locks.set(i - 1, prevLock);
// keep current position
i--;
} else {
prevLock = currentLock;
}
}
}
// update the database
if (!added.isEmpty() || !removed.isEmpty()) {
dao.addRemoveLocks(added, removed);
}
}
/**
* Notification that one or more databases were deleted. No lock change
* notifications are generated since all clients will already know that the
* databases have been removed.
* Deletes locks in the given time range
*
* Asks the LockDatabase for the list of LockTables. Eliminate entries in
* LockTables that no longer should exist based on the sequence of database
* identifiers that were deleted. Restore the LockTables by passing them to
* the LockDatabase.
*
* @param deletions
* @param lt
* The lock table to examine
* @param tr
* The TimeRange to delete
* @throws GfeLockException
* If errors occur when updating the locks in the database
*/
public void databaseDeleted(List<DatabaseID> deletions) {
// TODO: Implement database deletion
private void deleteLocks(final LockTable lt, final TimeRange tr)
throws DataAccessLayerException {
// update the locks in memory
List<Lock> locks = lt.getLocks();
Collections.sort(locks, startTimeComparator);
long start = tr.getStart().getTime();
long end = tr.getEnd().getTime();
Iterator<Lock> iter = locks.iterator();
List<Integer> locksToRemove = new LinkedList<Integer>();
while (iter.hasNext()) {
Lock lock = iter.next();
if (start <= lock.getStartTime()) {
if (end >= lock.getEndTime()) {
locksToRemove.add(lock.getId());
iter.remove();
} else {
// list was sorted by start time, not need to go any further
break;
}
}
}
// update the database
dao.addRemoveLocks(null, locksToRemove);
}
/**
@ -520,10 +544,7 @@ public class LockManager {
}
for (LockRequest req : requestsOut) {
List<LockRequest> reqList = new ArrayList<LockRequest>();
reqList.add(req);
sr.addMessages(expandRequestToBoundary(reqList));
req = reqList.get(0);
sr.addMessages(expandRequestToBoundary(req));
if (!sr.isOkay()) {
return sr;
}
@ -596,27 +617,27 @@ public class LockManager {
* The lock requst
* @return
*/
private ServerResponse<?> expandRequestToBoundary(List<LockRequest> req) {
private ServerResponse<?> expandRequestToBoundary(LockRequest req) {
ServerResponse<?> sr = new ServerResponse<String>();
if (!req.get(0).isParmRequest()) {
if (!req.isParmRequest()) {
logger.error("Expected parm-type request in expandRequestToBoundary");
}
// If this is a break-lock request, then do not expand to time constrts
if (req.get(0).getMode().equals(LockTable.LockMode.BREAK_LOCK)) {
if (req.getMode().equals(LockTable.LockMode.BREAK_LOCK)) {
return sr;
}
// Only expand for request lock and unlock
DatabaseID dbid = req.get(0).getParmId().getDbId();
DatabaseID dbid = req.getParmId().getDbId();
TimeRange tr = null;
switch (dbid.getFormat()) {
case GRID:
ServerResponse<GridParmInfo> ssr = GridParmManager
.getGridParmInfo(req.get(0).getParmId());
.getGridParmInfo(req.getParmId());
GridParmInfo gpi = ssr.getPayload();
sr.addMessages(ssr);
if (!sr.isOkay()) {
@ -624,8 +645,7 @@ public class LockManager {
return sr;
}
// calculate the expanded time
tr = gpi.getTimeConstraints().expandTRToQuantum(
req.get(0).getTimeRange());
tr = gpi.getTimeConstraints().expandTRToQuantum(req.getTimeRange());
if (!tr.isValid()) {
sr.addMessage("Request does not match TimeConstraints "
+ gpi.getTimeConstraints() + " ParmReq: " + req);
@ -638,9 +658,7 @@ public class LockManager {
// Update the lock request
if (tr.isValid()) {
req.add(new LockRequest(req.get(0).getParmId(), tr, req.get(0)
.getMode()));
req.remove(0);
req.setTimeRange(tr);
} else {
sr.addMessage("TimeRange not valid in LockRequest");
}
@ -649,10 +667,10 @@ public class LockManager {
}
/**
* * Overloaded utility routine to extract the ParmIds for a given
* Overloaded utility routine to extract the ParmIds for a given
* SeqOf<LockTableRequest>. If the request is a parm request, the ParmId
* will be appended to the list ParmIds to be returned. If the request is a
* database request, all the ParmIds for the given databaseId wil be
* database request, all the ParmIds for the given databaseId will be
* appended to the list of ParmIds. If the request is neither a parm nor a
* database request, all the parmId for all the databaseIds are appended to
* the list of ParmIds to be returned.
@ -662,22 +680,23 @@ public class LockManager {
* @return The ParmIDs contained in the requests
* @throws GfeException
*/
private ServerResponse<?> extractParmIds(List<LockTableRequest> ltr,
List<ParmID> parmIds, String siteID) {
private ServerResponse<?> extractParmIds(List<LockTableRequest> ltrList,
List<ParmID> parmIds, String siteID) throws GfeException {
ServerResponse<?> sr = new ServerResponse<String>();
// process each request
for (int i = 0; i < ltr.size(); i++) {
if (ltr.get(i).isParmRequest()) {
for (LockTableRequest ltr : ltrList) {
if (ltr.isParmRequest()) {
ParmID parmId = ltr.getParmId();
// append parm (if not already in the list)
if (!parmIds.contains(ltr.get(i).getParmId())) {
parmIds.add(ltr.get(i).getParmId());
if (!parmIds.contains(parmId)) {
parmIds.add(GridParmManager.getDb(parmId.getDbId())
.getCachedParmID(parmId));
}
} else if (ltr.get(i).isDatabaseRequest()) {
} else if (ltr.isDatabaseRequest()) {
// get all the parmIds for that databaseId
List<ParmID> pids = GridParmManager.getParmList(
ltr.get(i).getDbId()).getPayload();
List<ParmID> pids = GridParmManager.getParmList(ltr.getDbId())
.getPayload();
for (ParmID id : pids) {
if (!parmIds.contains(id)) {
parmIds.add(id);
@ -696,7 +715,6 @@ public class LockManager {
}
}
}
// this only needs to be done once
}
}
return sr;
@ -719,23 +737,24 @@ public class LockManager {
* @throws GfeException
* If errors occur
*/
private ServerResponse<?> extractParmIdsFromLockReq(List<LockRequest> lr,
List<ParmID> parmIds, String siteID) {
private ServerResponse<?> extractParmIdsFromLockReq(List<LockRequest> lrs,
List<ParmID> parmIds, String siteID) throws GfeException {
ServerResponse<?> sr = new ServerResponse<String>();
// process each request
for (int i = 0; i < lr.size(); i++) {
if (lr.get(i).isParmRequest()) {
for (LockRequest lr : lrs) {
if (lr.isParmRequest()) {
ParmID parmId = lr.getParmId();
// append parm (if not already in the list)
if (!parmIds.contains(lr.get(i).getParmId())) {
parmIds.add(lr.get(i).getParmId());
if (!parmIds.contains(parmId)) {
parmIds.add(GridParmManager.getDb(parmId.getDbId())
.getCachedParmID(parmId));
}
} else if (lr.get(i).isDatabaseRequest()) {
List<ParmID> pids = new ArrayList<ParmID>();
} else if (lr.isDatabaseRequest()) {
ServerResponse<List<ParmID>> ssr = GridParmManager
.getParmList(lr.get(i).getDbId());
.getParmList(lr.getDbId());
sr.addMessages(ssr);
pids = ssr.getPayload();
List<ParmID> pids = ssr.getPayload();
if (!sr.isOkay()) {
return sr;
}
@ -755,11 +774,10 @@ public class LockManager {
return sr;
}
for (int j = 0; j < dbids.size(); j++) {
List<ParmID> pids = new ArrayList<ParmID>();
ServerResponse<List<ParmID>> ssr1 = GridParmManager
.getParmList(dbids.get(j));
sr.addMessages(ssr1);
pids = ssr1.getPayload();
List<ParmID> pids = ssr1.getPayload();
if (!sr.isOkay()) {
return sr;
}
@ -769,7 +787,6 @@ public class LockManager {
}
}
}
// this only needs to be done once
}
}
@ -786,17 +803,16 @@ public class LockManager {
*/
private ServerResponse<?> officialDbLockCheck(final List<LockRequest> req,
String siteID) {
ServerResponse<?> sr = new ServerResponse<String>();
Set<DatabaseID> official = null;
List<DatabaseID> official = new ArrayList<DatabaseID>();
List<DatabaseID> officialDbs = null;
try {
officialDbs = IFPServerConfigManager.getServerConfig(siteID)
.getOfficialDatabases();
List<DatabaseID> officialDbs = IFPServerConfigManager
.getServerConfig(siteID).getOfficialDatabases();
official = new HashSet<DatabaseID>(officialDbs.size(), 1);
for (int j = 0; j < officialDbs.size(); j++) {
official.add(officialDbs.get(j).stripModelTime());
for (DatabaseID offDbId : officialDbs) {
official.add(offDbId.stripModelTime());
}
} catch (GfeException e) {
sr.addMessage("Unable to get official databases from IFPServer config");
@ -806,15 +822,15 @@ public class LockManager {
}
// process each request - extracting out the databse id w/o modeltime
for (int i = 0; i < req.size(); i++) {
for (LockRequest lr : req) {
DatabaseID requestDB = null;
if (req.get(i).isDatabaseRequest()) {
requestDB = req.get(i).getDbId();
} else if (req.get(i).isParmRequest()) {
requestDB = req.get(i).getParmId().getDbId();
if (lr.isDatabaseRequest()) {
requestDB = lr.getDbId();
} else if (lr.isParmRequest()) {
requestDB = lr.getParmId().getDbId();
} else {
sr.addMessage("Invalid Lock Request (not parm or databse type): "
+ req.get(i));
+ lr);
return sr;
}
requestDB = requestDB.stripModelTime();
@ -822,7 +838,7 @@ public class LockManager {
// look for a match
if (official.contains(requestDB)) {
sr.addMessage("Request locks on official database not permitted. Request="
+ req.get(i));
+ lr);
return sr;
}

View file

@ -24,7 +24,9 @@ import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.TimeZone;
import com.raytheon.edex.plugin.gfe.config.IFPServerConfig;
@ -35,7 +37,6 @@ import com.raytheon.edex.plugin.gfe.server.lock.LockManager;
import com.raytheon.edex.plugin.gfe.util.SendNotifications;
import com.raytheon.uf.common.dataplugin.gfe.GridDataHistory;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord.GridType;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.GridParmInfo;
import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID;
import com.raytheon.uf.common.dataplugin.gfe.discrete.DiscreteKey;
@ -77,6 +78,9 @@ import com.raytheon.uf.common.time.TimeRange;
* Jan 22, 2010 4248 njensen Better error msgs
* Jul 25, 2012 #957 dgilling Implement getEditArea().
* Apr 23, 2013 #1937 dgilling Implement get().
* Apr 23, 2013 #1941 dgilling Implement put(), add methods to build
* Scalar/VectorGridSlices, refactor
* Discrete/WeatherGridSlices builders.
*
* </pre>
*
@ -234,6 +238,76 @@ public class IFPWE {
return rval;
}
/**
* Stores the provided grid slices into this weather element's permanent
* storage.
*
* @param inventory
* A Map of TimeRanges to IGridSlices to be saved. Time is the
* slice's valid time.
* @param timeRangeSpan
* The replacement time range of grids to be saved. Must cover
* each individual TimeRange in inventory.
* @throws GfeException
* If an error occurs while trying to obtain a lock on the
* destination database.
*/
public void put(LinkedHashMap<TimeRange, IGridSlice> inventory,
TimeRange timeRangeSpan) throws GfeException {
statusHandler.debug("Getting lock for ParmID: " + parmId + " TR: "
+ timeRangeSpan);
ServerResponse<List<LockTable>> lockResponse = LockManager
.getInstance().requestLockChange(
new LockRequest(parmId, timeRangeSpan, LockMode.LOCK),
wsId, siteId);
if (lockResponse.isOkay()) {
statusHandler.debug("LOCKING: Lock granted for: " + wsId
+ " for time range: " + timeRangeSpan);
} else {
statusHandler.error("Could not lock TimeRange " + timeRangeSpan
+ " for parm [" + parmId + "]: " + lockResponse.message());
throw new GfeException("Request lock failed. "
+ lockResponse.message());
}
List<GFERecord> records = new ArrayList<GFERecord>(inventory.size());
for (Entry<TimeRange, IGridSlice> entry : inventory.entrySet()) {
GFERecord rec = new GFERecord(parmId, entry.getKey());
rec.setGridHistory(entry.getValue().getHistory());
rec.setMessageData(entry.getValue());
records.add(rec);
}
SaveGridRequest sgr = new SaveGridRequest(parmId, timeRangeSpan,
records);
try {
ServerResponse<?> sr = GridParmManager.saveGridData(
Arrays.asList(sgr), wsId, siteId);
if (sr.isOkay()) {
SendNotifications.send(sr.getNotifications());
} else {
statusHandler.error("Unable to save grids for parm [" + parmId
+ "] over time range " + timeRangeSpan + ": "
+ sr.message());
}
} finally {
ServerResponse<List<LockTable>> unLockResponse = LockManager
.getInstance().requestLockChange(
new LockRequest(parmId, timeRangeSpan,
LockMode.UNLOCK), wsId, siteId);
if (unLockResponse.isOkay()) {
statusHandler.debug("LOCKING: Unlocked for: " + wsId + " TR: "
+ timeRangeSpan);
} else {
statusHandler.error("Could not unlock TimeRange "
+ timeRangeSpan + " for parm [" + parmId + "]: "
+ lockResponse.message());
throw new GfeException("Request unlock failed. "
+ unLockResponse.message());
}
}
}
private void setItem(TimeRange time, IGridSlice gridSlice,
List<GridDataHistory> gdh) throws GfeException {
GFERecord rec = new GFERecord(parmId, time);
@ -373,9 +447,7 @@ public class IFPWE {
public void setItemDiscrete(TimeRange time, byte[] discreteData,
String keys, List<GridDataHistory> gdhList) throws GfeException {
IGridSlice gridSlice = buildDiscreteSlice(time, discreteData, keys,
gpi.getGridType());
gridSlice
.setHistory(gdhList.toArray(new GridDataHistory[gdhList.size()]));
gdhList);
setItem(time, gridSlice, gdhList);
}
@ -393,9 +465,7 @@ public class IFPWE {
public void setItemWeather(TimeRange time, byte[] weatherData, String keys,
List<GridDataHistory> gdhList) throws GfeException {
IGridSlice gridSlice = buildWeatherSlice(time, weatherData, keys,
gpi.getGridType());
gridSlice
.setHistory(gdhList.toArray(new GridDataHistory[gdhList.size()]));
gdhList);
setItem(time, gridSlice, gdhList);
}
@ -433,60 +503,96 @@ public class IFPWE {
return keys.toArray(new String[keys.size()]);
}
/**
* Builds a ScalarGridSlice to store.
*
* @param time
* The valid time of the slice.
* @param data
* A float array that corresponds to the slice's data.
* @param history
* The GridDataHistory for the new slice.
* @return A ScalarGridSlice based on the provided data, valid for the given
* time, with the provided history.
*/
public ScalarGridSlice buildScalarSlice(TimeRange time, float[] data,
List<GridDataHistory> history) {
return new ScalarGridSlice(time, gpi, history, new Grid2DFloat(gpi
.getGridLoc().getNx(), gpi.getGridLoc().getNy(), data));
}
/**
* Builds a VectorGridSlice to store.
*
* @param time
* The valid time of the slice.
* @param magData
* A float array that corresponds to the slice's magnitude data.
* @param dirData
* A float array that corresponds to the slice's directional
* data.
* @param history
* The GridDataHistory for the new slice.
* @return A VectorGridSlice based on the provided data, valid for the given
* time, with the provided history.
*/
public VectorGridSlice buildVectorSlice(TimeRange time, float[] magData,
float[] dirData, List<GridDataHistory> history) {
return new VectorGridSlice(time, gpi, history, new Grid2DFloat(gpi
.getGridLoc().getNx(), gpi.getGridLoc().getNy(), magData),
new Grid2DFloat(gpi.getGridLoc().getNx(), gpi.getGridLoc()
.getNy(), dirData));
}
/**
* Builds a discrete grid slice to store
*
* @param time
* the time of the data
* @param slice
* an Object[] { byte[], String } corresponding to discrete/wx
* types
* @param type
* the type of the data
* The valid time of the data.
* @param bytes
* A byte[] corresponding to discrete
* @param keyString
* Python encoded form of discrete keys.
* @param history
* histories for this grid.
* @return
* @throws GfeException
*/
private IGridSlice buildDiscreteSlice(TimeRange time, byte[] bytes,
String keyString, GridType type) throws GfeException {
public DiscreteGridSlice buildDiscreteSlice(TimeRange time, byte[] bytes,
String keyString, List<GridDataHistory> history) {
List<DiscreteKey> discreteKeyList = new ArrayList<DiscreteKey>();
List<String> keys = GfeUtil.discreteKeyStringToList(keyString);
for (String k : keys) {
discreteKeyList.add(new DiscreteKey(siteId, k, parmId));
}
return new DiscreteGridSlice(
time,
gpi,
new GridDataHistory[] {},
new Grid2DByte(gpi.getGridLoc().getNx(), gpi.getGridLoc()
.getNy(), bytes),
discreteKeyList.toArray(new DiscreteKey[discreteKeyList.size()]));
return new DiscreteGridSlice(time, gpi, history, new Grid2DByte(gpi
.getGridLoc().getNx(), gpi.getGridLoc().getNy(), bytes),
discreteKeyList);
}
/**
* Builds a weather grid slice to store
*
* @param time
* the time of the data
* @param slice
* an Object[] { byte[], String } corresponding to weather/wx
* types
* @param type
* the type of the data
* The valid time of the data.
* @param bytes
* A byte[] corresponding to weather
* @param keyString
* Python encoded form of weather keys.
* @param history
* histories for this grid.
* @return
* @throws GfeException
*/
private IGridSlice buildWeatherSlice(TimeRange time, byte[] bytes,
String keyString, GridType type) throws GfeException {
public WeatherGridSlice buildWeatherSlice(TimeRange time, byte[] bytes,
String keyString, List<GridDataHistory> history) {
List<WeatherKey> weatherKeyList = new ArrayList<WeatherKey>();
List<String> keys = GfeUtil.discreteKeyStringToList(keyString);
for (String k : keys) {
weatherKeyList.add(new WeatherKey(siteId, k));
}
return new WeatherGridSlice(time, gpi, new GridDataHistory[] {},
new Grid2DByte(gpi.getGridLoc().getNx(), gpi.getGridLoc()
.getNy(), bytes),
weatherKeyList.toArray(new WeatherKey[weatherKeyList.size()]));
return new WeatherGridSlice(time, gpi, history, new Grid2DByte(gpi
.getGridLoc().getNx(), gpi.getGridLoc().getNy(), bytes),
weatherKeyList);
}
@Override

View file

@ -54,7 +54,7 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory;
* Jul 17, 2009 #2590 njensen Multiple site support
* Jul 28, 2010 #6725 jdynina Manual init support
* Aug 27, 2010 #3688 wkwock Find model class for a model
*
* Aug 24, 2013 #1949 rjpeter Updated start up logic
* </pre>
*
* @author njensen
@ -63,7 +63,7 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory;
public class SmartInitSrv {
private Map<Long, SmartInitScript> cachedInterpreters = new HashMap<Long, SmartInitScript>();
private final Map<Long, SmartInitScript> cachedInterpreters = new HashMap<Long, SmartInitScript>();
private static boolean enabled = true;
@ -84,7 +84,6 @@ public class SmartInitSrv {
thread.pendingInitMinTimeMillis = cfg.getPendingInitMinTimeMillis();
thread.runningInitTimeOutMillis = cfg.getRunningInitTimeOutMillis();
thread.threadSleepInterval = cfg.getThreadSleepInterval();
thread.initialDelay = cfg.getInitialDelay();
executor.execute(thread);
}
}
@ -99,21 +98,18 @@ public class SmartInitSrv {
private final transient Log logger = LogFactory.getLog(getClass());
private int initialDelay = 120000;
@Override
public void run() {
long curTime = System.currentTimeMillis();
while (!EDEXUtil.isRunning()
|| System.currentTimeMillis() - curTime < initialDelay) {
try {
Thread.sleep(threadSleepInterval);
} catch (Throwable t) {
// ignore
}
}
try {
// Wait for server to come fully up due to route dependencies
while (!EDEXUtil.isRunning()) {
try {
Thread.sleep(threadSleepInterval);
} catch (InterruptedException e) {
// ignore
}
}
// run forever
while (true) {
SmartInitRecord record = SmartInitTransactions
@ -170,7 +166,7 @@ public class SmartInitSrv {
LocalizationLevel.BASE);
File file = pathMgr.getFile(ctx, "smartinit");
if (file != null && file.exists()) {
if ((file != null) && file.exists()) {
initScript.addSitePath(file.getPath(), pathMgr
.getFile(baseCtx, "smartinit")
.getPath());
@ -178,7 +174,7 @@ public class SmartInitSrv {
}
file = pathMgr.getFile(ctx,
FileUtil.join("config", "gfe"));
if (file != null && file.exists()) {
if ((file != null) && file.exists()) {
initScript.addSitePath(
file.getPath(),
pathMgr.getFile(baseCtx,

View file

@ -30,7 +30,7 @@ import java.util.concurrent.Executor;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 24, 2010 #7277 rjpeter Initial creation
*
* Apr 23, 2013 #1949 rjpeter Removed initial delay
* </pre>
*
* @author rjpeter
@ -48,8 +48,6 @@ public class SmartInitSrvConfig {
protected int threadSleepInterval;
protected int initialDelay;
public int getThreads() {
return threads;
}
@ -90,12 +88,4 @@ public class SmartInitSrvConfig {
this.threadSleepInterval = threadSleepInterval;
}
public int getInitialDelay() {
return initialDelay;
}
public void setInitialDelay(int initialDelay) {
this.initialDelay = initialDelay;
}
}

View file

@ -32,6 +32,7 @@ import numpy
import JUtil
from java.util import ArrayList
from java.util import LinkedHashMap
from com.raytheon.uf.common.dataplugin.gfe.grid import Grid2DFloat
from com.raytheon.uf.common.dataplugin.gfe.grid import Grid2DByte
from com.raytheon.uf.common.time import TimeRange
@ -74,7 +75,8 @@ from com.raytheon.uf.edex.database.cluster import ClusterTask
# 07/06/09 1995 bphillip Initial Creation.
# 01/17/13 15588 jdynina Fixed Publish history removal
# 03/12/13 1759 dgilling Remove unnecessary command line
# processing.
# processing.
# 04/24/13 1941 dgilling Re-port WECache to match A1.
#
#
@ -86,53 +88,49 @@ ISC_USER="isc"
class WECache(object):
def __init__(self, we, tr=None):
self._grids = []
self._hist = []
self._we = we
self._inv = []
theKeys = self._we.getKeys()
for i in range(0, theKeys.size()):
self._inv.append(iscUtil.transformTime(theKeys.get(i)))
self._inv = {}
self._invCache = None
javaInv = self._we.getKeys()
pyInv = []
for i in xrange(javaInv.size()):
pyInv.append(iscUtil.transformTime(javaInv.get(i)))
# Dont get grids outside of the passed in timerange.
if tr:
tokill = []
for i, t in enumerate(self._inv):
for i, t in enumerate(pyInv):
if not self.overlaps(tr, t):
tokill.append(i)
tokill.reverse()
for i in tokill:
del self._inv[i]
del pyInv[i]
javaTRs = ArrayList()
for tr in pyInv:
javaTRs.add(iscUtil.toJavaTimeRange(tr))
gridsAndHist = self._we.get(javaTRs, True)
for idx, tr in enumerate(pyInv):
pair = gridsAndHist.get(idx)
g = self.__encodeGridSlice(pair.getFirst())
h = self.__encodeGridHistory(pair.getSecond())
self._inv[tr] = (g, h)
def keys(self):
return tuple(self._inv)
if not self._invCache:
self._invCache = tuple(sorted(self._inv.keys(), key=lambda t: t[0]))
return self._invCache
def __getitem__(self, key):
grid = self._we.getItem(iscUtil.toJavaTimeRange(key))
history = grid.getGridDataHistory()
hist = []
for i in range(0, history.size()):
hist.append(history.get(i))
gridType = grid.getGridInfo().getGridType().toString()
if gridType == "SCALAR":
return (grid.__numpy__[0], hist)
elif gridType == "VECTOR":
vecGrids = grid.__numpy__
return ((vecGrids[0], vecGrids[1]), hist)
elif gridType == "WEATHER":
keys = grid.getKeys()
keyList = []
for theKey in keys:
keyList.append(theKey.toString())
return ((grid.__numpy__[0], keyList), hist)
elif gridType == "DISCRETE":
keys = grid.getKey()
keyList = []
for theKey in keys:
keyList.append(theKey.toString())
return ((grid.__numpy__[0], keyList), hist)
try:
return self._inv[key]
except KeyError:
grid = self._we.getItem(iscUtil.toJavaTimeRange(key))
pyGrid = self.__encodeGridSlice(grid)
history = grid.getGridDataHistory()
pyHist = self.__encodeGridHistory(history)
return (pyGrid, pyHist)
def __setitem__(self, tr, value):
if value is None:
@ -142,48 +140,106 @@ class WECache(object):
# Remove any overlapping grids
tokill = []
for i, itr in enumerate(self._inv):
for itr in self._inv:
if self.overlaps(tr, itr):
tokill.append(i)
tokill.reverse()
tokill.append(itr)
for i in tokill:
del self._inv[i]
del self._inv[i]
self._invCache = None
# Now add the new grid if it exists
if grid is not None:
timeRange=iscUtil.toJavaTimeRange(tr)
LogStream.logDebug("iscMosaic: Saving Parm:",self._we.getParmid(),"TR:",timeRange)
gridType = self._we.getGridType()
index = bisect.bisect_left(map(lambda x : x[0], self._inv), tr[0])
self._inv.insert(index, tr)
history = ArrayList()
self._inv[tr] = (grid, hist)
self._invCache = None
for h in hist:
dbName = self._we.getParmid().getDbId().toString()
if dbName.find('Fcst') != -1:
#strip out publish time to allow for publishing correctly
#when merging Fcst out of A1
hh = GridDataHistory(h)
hh.setPublishTime(None)
history.add(hh)
else:
history.add(GridDataHistory(h))
if gridType == 'SCALAR':
self._we.setItemScalar(timeRange, grid.astype(numpy.float32), history)
elif gridType == 'VECTOR':
self._we.setItemVector(timeRange, grid[0].astype(numpy.float32), grid[1].astype(numpy.float32), history)
elif gridType == 'WEATHER':
self._we.setItemWeather(timeRange, grid[0].astype(numpy.byte), str(grid[1]), history)
elif gridType == 'DISCRETE':
self._we.setItemDiscrete(timeRange, grid[0].astype(numpy.byte), str(grid[1]), history)
LogStream.logDebug("iscMosaic: Successfully saved Parm:",self._we.getParmid(),"Time:",timeRange)
def flush(self):
"""Actually writes the contents of the WECache to HDF5/DB"""
# get cache inventory in time range order
# we want to write to disk in contiguous time range blocks so we only
# overwrite what we have full sets of grids for.
inv = list(self.keys())
# Don't believe the grid slices need to be in time order when saving
# but leaving them that way just in case.
gridsToSave = LinkedHashMap()
while inv:
# retrieve the next BATCH of grids to persist
i = inv[:BATCH_WRITE_COUNT]
# pre-compute the replacement TR for the save requests generated by
# IFPWE.put().
# since the inventory is in order it's the start time of the
# first TR and the end time of the last TR.
gridSaveTR = iscUtil.toJavaTimeRange((i[0][0], i[-1][1]))
for tr in i:
javaTR = iscUtil.toJavaTimeRange(tr)
pyGrid, pyHist = self._inv[tr]
javaHist = self.__buildJavaGridHistory(pyHist)
javaGrid = self.__buildJavaGridSlice(javaTR, pyGrid, javaHist)
gridsToSave.put(javaTR, javaGrid)
self._we.put(gridsToSave, gridSaveTR)
# delete the persisted items from the cache and our copy of the
# inventory
gridsToSave.clear()
for tr in i:
del self._inv[tr]
self._invCache = None
inv = inv[BATCH_WRITE_COUNT:]
time.sleep(BATCH_DELAY)
def overlaps(self, tr1, tr2):
if (tr1[0] >= tr2[0] and tr1[0] < tr2[1]) or \
(tr2[0] >= tr1[0] and tr2[0] < tr1[1]):
return True
return False
def __encodeGridSlice(self, grid):
gridType = self._we.getGridType()
if gridType == "SCALAR":
return grid.__numpy__[0]
elif gridType == "VECTOR":
vecGrids = grid.__numpy__
return (vecGrids[0], vecGrids[1])
elif gridType == "WEATHER":
keys = grid.getKeys()
keyList = []
for theKey in keys:
keyList.append(theKey.toString())
return (grid.__numpy__[0], keyList)
elif gridType =="DISCRETE":
keys = grid.getKey()
keyList = []
for theKey in keys:
keyList.append(theKey.toString())
return (grid.__numpy__[0], keyList)
def __encodeGridHistory(self, histories):
retVal = []
for i in xrange(histories.size()):
retVal.append(histories.get(i).getCodedString())
return tuple(retVal)
def __buildJavaGridSlice(self, tr, grid, history):
gridType = self._we.getGridType()
if gridType == "SCALAR":
return self._we.buildScalarSlice(tr, grid.astype(numpy.float32), history)
elif gridType == "VECTOR":
return self._we.buildVectorSlice(tr, grid[0].astype(numpy.float32), grid[1].astype(numpy.float32), history)
elif gridType == "WEATHER":
return self._we.buildWeatherSlice(tr, grid[0].astype(numpy.byte), str(grid[1]), history)
elif gridType == "DISCRETE":
return self._we.buildDiscreteSlice(tr, grid[0].astype(numpy.byte), str(grid[1]), history)
def __buildJavaGridHistory(self, histories):
retVal = ArrayList()
blankPubTime = "Fcst" in self._we.getParmid().getDbId().toString()
for histEntry in histories:
javaHist = GridDataHistory(histEntry)
# strip out publish time to allow for publishing correctly
# when merging Fcst out of A1
if blankPubTime:
javaHist.setPublishTime(None)
retVal.add(javaHist)
return retVal
class IscMosaic:
@ -549,7 +605,8 @@ class IscMosaic:
# Returns tuple of (parmName, TR, #grids, #fails)
if len(inTimesProc):
totalTimeRange = (inTimesProc[0][0], inTimesProc[ -1][ -1] - 3600)
self._wec.flush()
retryAttempt = retries
except:
retryAttempt = retryAttempt + 1

View file

@ -0,0 +1,43 @@
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:amq="http://activemq.apache.org/schema/core" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd
http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd">
<bean id="gribPathProvider" class="com.raytheon.uf.common.dataplugin.grib.GribPathProvider" />
<bean id="gribProperties" class="com.raytheon.uf.common.dataplugin.PluginProperties">
<property name="pluginName" value="grib" />
<property name="pluginFQN" value="com.raytheon.uf.common.dataplugin.grib" />
<property name="dao" value="com.raytheon.edex.plugin.grib.dao.GribDao" />
<property name="record" value="com.raytheon.uf.common.dataplugin.grib.GribRecord" />
<property name="dependencyFQNs">
<list>
<value>com.raytheon.uf.common.dataplugin.level</value>
<value>com.raytheon.uf.common.parameter</value>
<value>com.raytheon.uf.common.gridcoverage</value>
</list>
</property>
<property name="pathProvider">
<ref bean="gribPathProvider"/>
</property>
<property name="compression" value="LZF"/>
</bean>
<bean id="gribRegistered" factory-bean="pluginRegistry" factory-method="register"
depends-on="levelRegistered,parameterRegistered,gridcoverageRegistered">
<constructor-arg value="grib"/>
<constructor-arg ref="gribProperties"/>
</bean>
<bean id="gfeLoadGribParamInfo"
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetClass">
<value>com.raytheon.edex.plugin.gfe.paraminfo.GridParamInfoLookup</value>
</property>
<property name="targetMethod">
<value>enableLoadGribDefs</value>
</property>
</bean>
</beans>

Some files were not shown because too many files have changed in this diff Show more