Merge branch 'ncep_14.2.2-n' into ncep_14.4.1

Conflicts:
	cave/com.raytheon.uf.viz.ncep.displays.feature/feature.xml
	ncep/gov.noaa.nws.ncep.common.dataplugin.geomag/src/gov/noaa/nws/ncep/common/dataplugin/geomag/dao/GeoMagK1minDao.java
	ncep/gov.noaa.nws.ncep.common.dataplugin.geomag/src/gov/noaa/nws/ncep/common/dataplugin/geomag/dao/GeoMagK3hrDao.java
	ncep/gov.noaa.nws.ncep.common.dataplugin.ncuair/src/gov/noaa/nws/ncep/common/dataplugin/ncuair/dao/NcUairToRecord.java
	ncep/gov.noaa.nws.ncep.edex.plugin.mosaic/src/gov/noaa/nws/ncep/edex/plugin/mosaic/common/MosaicRecord.java
	ncep/gov.noaa.nws.ncep.viz.gempak/META-INF/MANIFEST.MF
	ncep/gov.noaa.nws.ncep.viz.gempak/src/gov/noaa/nws/ncep/viz/gempak/util/GempakGrid.java
	ncep/gov.noaa.nws.ncep.viz.localization/localization/ncep/ResourceDefns/ResourceFilters.xml
	ncep/gov.noaa.nws.ncep.viz.rsc.ntrans/src/gov/noaa/nws/ncep/viz/rsc/ntrans/rsc/NtransResource.java
	ncep/gov.noaa.nws.ncep.viz.rsc.plotdata/src/gov/noaa/nws/ncep/viz/rsc/plotdata/plotModels/NcPlotImageCreator.java
	ncep/gov.noaa.nws.ncep.viz.rsc.plotdata/src/gov/noaa/nws/ncep/viz/rsc/plotdata/plotModels/NcPlotModelHdf5DataRequestor.java
	ncep/gov.noaa.nws.ncep.viz.rsc.plotdata/src/gov/noaa/nws/ncep/viz/rsc/plotdata/rsc/NcPlotResource2.java
	tests/.classpath

Former-commit-id: 09ae4e1dc5063df9f94d802f2630632d4c856fff
This commit is contained in:
Stephen Gilbert 2014-12-16 13:06:21 -05:00
commit 33c9f191b4
306 changed files with 38191 additions and 13866 deletions

View file

@ -1,4 +1,15 @@
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagRecord
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagAvg
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK1min
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK3hr
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK3hr
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagState
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK3hrState
gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagStationStateChange
gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStationList
gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStation
gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagSource
gov.noaa.nws.ncep.common.dataplugin.geomag.table.Location
gov.noaa.nws.ncep.common.dataplugin.geomag.table.DataFormat
gov.noaa.nws.ncep.common.dataplugin.geomag.table.RawDataFormat
gov.noaa.nws.ncep.common.dataplugin.geomag.table.HeaderFormat
gov.noaa.nws.ncep.common.dataplugin.geomag.table.Group

View file

@ -0,0 +1,3 @@
INSERT INTO awips.geomag_states VALUES (1,'Process');
INSERT INTO awips.geomag_states VALUES (2,'Algorithm');
INSERT INTO awips.geomag_states VALUES (3,'Active');

View file

@ -29,7 +29,9 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 08/14/2013 T989 qzhou Initial creation.
* 03/03/2014 #1110 qzhou modified get/set
* 03/03/2014 #1110 qzhou modified get/set
* 04/05/2014 R4078 sgurung Added method match().
*
* </pre>
*
* @author qzhou
@ -365,4 +367,14 @@ public class GeoMagK1min extends PersistableDataObject<Object> {
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
public boolean match(Date refTime, String stationCode) {
if (this.refTime.compareTo(refTime) == 0
&& this.stationCode.equals(stationCode)) {
return true;
} else {
return false;
}
}
}

View file

@ -0,0 +1,126 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* Record implementation for geomag_K3hr_state.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 06/27/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
@Entity
@SequenceGenerator(initialValue = 1, name = PluginDataObject.ID_GEN, sequenceName = "geomagk3hrstateseq")
@Table(name = "geomag_k3hr_state", uniqueConstraints = { @UniqueConstraint(columnNames = {
"k3hrId", "stateId" }) })
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@XmlAccessorType(XmlAccessType.NONE)
@DynamicSerialize
public class GeoMagK3hrState extends PersistableDataObject<Object> {
private static final long serialVersionUID = 1L;
public static final String ID_GEN = "idgen";
/** The id */
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = ID_GEN)
private Integer id;
/**
* station state id
*/
@Column
@XmlAttribute
@DynamicSerializeElement
private Integer stateId;
@Column
@XmlAttribute
@DynamicSerializeElement
private Integer k3hrId;
/**
*
* @return id
*/
public Integer getId() {
return id;
}
/**
*
* @param id
*/
public void setId(Integer id) {
this.id = id;
}
/**
*
* @return stateId
*/
public Integer getStateId() {
return stateId;
}
/**
*
* @param stateId
*/
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
/**
*
* @return k3hrId
*/
public Integer getK3hrId() {
return k3hrId;
}
/**
*
* @param k3hrStateId
*/
public void setK3hrId(Integer k3hrId) {
this.k3hrId = k3hrId;
}
}

View file

@ -0,0 +1,102 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* Record implementation for geomag station state.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 06/27/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
@Entity
@SequenceGenerator(initialValue = 1, name = PluginDataObject.ID_GEN, sequenceName = "geomagstateseq")
@Table(name = "geomag_states", uniqueConstraints = { @UniqueConstraint(columnNames = { "processingState" }) })
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@XmlAccessorType(XmlAccessType.NONE)
@DynamicSerialize
public class GeoMagState extends PersistableDataObject<Object> {
private static final long serialVersionUID = 1L;
public static final String ID_GEN = "idgen";
/** The id */
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = ID_GEN)
private Integer stateId;
/**
* processing state
*/
@Column
@XmlAttribute
@DynamicSerializeElement
private String processingState;
/**
* @return the stateId
*/
public Integer getStateId() {
return stateId;
}
/**
* @param stateId
*/
public void setStateId(Integer stateId) {
this.stateId = stateId;
}
/**
*
* @return processingState
*/
public String getProcessingState() {
return processingState;
}
/**
*
* @param processingState
*/
public void setProcessingState(String processingState) {
this.processingState = processingState;
}
}

View file

@ -0,0 +1,134 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
* Record implementation for geomag station state. Tracks all the magnetometers
* station state changes.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 06/27/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
@Entity
@SequenceGenerator(initialValue = 1, name = PluginDataObject.ID_GEN, sequenceName = "geomagstatechangeseq")
@Table(name = "geomag_station_state_changes")
@Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
@XmlAccessorType(XmlAccessType.NONE)
@DynamicSerialize
public class GeoMagStationStateChange extends PersistableDataObject<Object> {
private static final long serialVersionUID = 1L;
public static final String ID_GEN = "idgen";
/** The id */
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = ID_GEN)
private Integer id;
/**
* station code
*/
@Column
@XmlAttribute
@DynamicSerializeElement
private String stationCode;
/**
* issued action
*/
@Column
@XmlAttribute
@DynamicSerializeElement
private String issuedAction;
/**
* insert time tag
*/
@Column
@XmlAttribute
@DynamicSerializeElement
private Date insertTime;
public String getStationCode() {
return stationCode;
}
/**
*
* @param stationCode
*/
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
/**
*
* @return issuedAction
*/
public String getIssuedAction() {
return issuedAction;
}
/**
*
* @param issuedAction
*/
public void setIssuedAction(String issuedAction) {
this.issuedAction = issuedAction;
}
/**
*
* @return insertTime
*/
public Date getInsertTime() {
return insertTime;
}
/**
*
* @param insertTime
*/
public void setInsertTime(Date insertTime) {
this.insertTime = insertTime;
}
}

View file

@ -23,7 +23,6 @@ import java.util.Map;
* ----------- ---------- ---------- --------------------------
* 05/14/2013 #989 qzhou Initial Creation
* 06/23/2014 R4152 qzhou Touched up 3 functions
* 07/22/2014 R4152 qzhou Fixed getMedian. This func. is uesd very rare if ever
* </pre>
*
* @author qzhou
@ -535,10 +534,11 @@ public class CalcUtil {
// remove missing data
List<Float> newArray = new ArrayList<Float>();
for (int k = 0; k < arraySort.length; k++) {
for (int k = 0; k < arraySort.length - 1; k++)
if (arraySort[k] != MISSING_VAL)
newArray.add(arraySort[k]);
}
else
break; // to sorted arraySort
int size = newArray.size();
if (size % 2 == 0)

View file

@ -94,8 +94,8 @@ public class GeoMagAvgDao extends CoreDao {
public int purgeDataByRefTime(Date refTime) throws DataAccessLayerException {
DatabaseQuery deleteStmt = new DatabaseQuery(this.daoClass);
// add 30 minutes to get hourly average reference time
Date avgTime = new Date(refTime.getTime() + (30 * 60000));
// subtract 30 minutes to get hourly average reference time
Date avgTime = new Date(refTime.getTime() - (30 * 60000));
deleteStmt.addQueryParam("avgTime", avgTime);
return this.deleteByCriteria(deleteStmt);
}

View file

@ -9,6 +9,14 @@ import java.util.Date;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.raytheon.uf.common.dataplugin.PluginException;
import com.raytheon.uf.common.dataplugin.persist.IPersistable;
import com.raytheon.uf.common.datastorage.IDataStore;
@ -30,6 +38,7 @@ import com.raytheon.uf.edex.database.purge.PurgeLogger;
* ------------ ---------- ----------- --------------------------
* 04/2013 975 S. Gurung Initial Creation
* 07/16/2013 975 Q. Zhou Added fields.
* 07/02/2014 R4078 S. Gurung Added k3hrStateDao, methods getGeoMagRecords() and getGeoMagRecordsCount()
* </pre>
*
* @author sgurung
@ -44,6 +53,8 @@ public class GeoMagDao extends PluginDao {
private GeoMagK1minDao k1minDao = new GeoMagK1minDao();
private GeoMagK3hrStateDao k3hrStateDao = new GeoMagK3hrStateDao();
public GeoMagDao(String pluginName) throws PluginException {
super(pluginName);
}
@ -61,12 +72,21 @@ public class GeoMagDao extends PluginDao {
int results = super.purgeDataByRefTime(refTime, productKeys, trackHdf5,
trackToUri, hdf5FileToUriPurged);
// delete expired data from geomag_k1min, geomag_houravg and geomag_k3hr
// delete expired data from geomag_k1min, geomag_houravg, geomag_k3hr
// and geomag_k3hr_state
// tables
try {
avgDao.purgeDataByRefTime(refTime);
k1minDao.purgeDataByRefTime(refTime);
// purge states associated with k3hr record with the given refTime
List<GeoMagK3hr> k3hrList = k3hrDao.getK3hr(null, refTime);
for (GeoMagK3hr k3hr : k3hrList) {
k3hrStateDao.purgeDataByK3hrId(k3hr.getId());
}
k3hrDao.purgeDataByRefTime(refTime);
} catch (Exception e) {
PurgeLogger
.logError(
@ -298,4 +318,51 @@ public class GeoMagDao extends PluginDao {
public void setGeoMagK3hrDao(GeoMagK3hrDao k3hrDao) {
this.k3hrDao = k3hrDao;
}
@SuppressWarnings("unchecked")
public List<GeoMagRecord> getGeoMagRecords(final String stationCode,
final Date start, final Date end, final int sourceId) {
return (List<GeoMagRecord>) txTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess.createCriteria(GeoMagRecord.class);
Criterion where1 = Restrictions.eq("stationCode",
stationCode);
crit.add(where1);
Criterion where2 = Restrictions
.eq("sourceId", sourceId);
crit.add(where2);
Criterion where3 = Restrictions.between(
"dataTime.refTime", start, end);
crit.add(where3);
crit.addOrder(Order.asc("dataTime.refTime"));
return crit.list();
}
});
}
@SuppressWarnings("unchecked")
public Integer getGeoMagRecordsCount(final String stationCode,
final Date start, final Date end, final int sourceId) {
return (Integer) txTemplate.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess.createCriteria(GeoMagRecord.class);
Criterion where1 = Restrictions.eq("stationCode", stationCode);
crit.add(where1);
Criterion where2 = Restrictions.eq("sourceId", sourceId);
crit.add(where2);
if (crit.list() != null)
return crit.list().size();
else
return 0;
}
});
}
}

View file

@ -2,12 +2,18 @@ package gov.noaa.nws.ncep.common.dataplugin.geomag.dao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK1min;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
@ -28,6 +34,8 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
* 03/03/2014 #1110 qzhou Added method getRangeK1min(), Cleaned code
* 03/13/2014 sgurung Added method purgeDataByRefTime()
* 10/16/2014 3454 bphillip Upgrading to Hibernate 4
* 04/05/2014 R4078 sgurung Added methods getEstKIndex1min(), getEstKpIndex1min(),
* getLatestEstKIndex() and getLastDataDate().
* </pre>
*
* @author qzhou
@ -35,6 +43,10 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
*/
public class GeoMagK1minDao extends CoreDao {
/** The logger */
protected transient Log logger = LogFactory.getLog(getClass());
/**
* Creates a new GeoMagK1minDao
*/
@ -64,6 +76,7 @@ public class GeoMagK1minDao extends CoreDao {
crit.add(where2);
Criterion where3 = Restrictions.lt("refTime", end);
crit.add(where3);
crit.addOrder(Order.asc("refTime"));
return crit.list();
}
@ -90,6 +103,278 @@ public class GeoMagK1minDao extends CoreDao {
});
}
@SuppressWarnings("unchecked")
public List<GeoMagK1min> getEstKIndex1min(final List<String> stations,
final Date start, final Date end) {
return (List<GeoMagK1min>) txTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess.createCriteria(GeoMagK1min.class);
if (stations != null) {
Criterion where1 = Restrictions.in("stationCode",
stations);
crit.add(where1);
}
Criterion where2 = Restrictions.gt("refTime", start);
crit.add(where2);
Criterion where3 = Restrictions.le("refTime", end);
crit.add(where3);
// Criterion where4 = Restrictions.ge("ks", 9.0);
// crit.add(where4);
crit.addOrder(Order.asc("refTime"));
crit.addOrder(Order.asc("stationCode"));
return crit.list();
}
});
}
/**
* Retrieves data from geomag_k1min table for the provided list of stations,
* given start date and end date. <br>
*
* @param stations
* A list of stations
* @param start
* start date
* @param end
* end date
* @return List of data map containing "reftime", "ks_avg", "station_count"
* @throws Exception
*/
public List<Map<String, Object>> getEstKpIndex1min(
final List<String> stations, final Date start, final Date end)
throws Exception {
StringBuffer sql = new StringBuffer();
sql.append(" SELECT a.reftime, AVG(a.ks) ks_avg, COUNT(a.stationcode) station_count FROM geomag_k1min a ");
sql.append(" INNER JOIN geomag_k3hr b ON b.stationcode = a.stationcode ");
sql.append(" INNER JOIN geomag_k3hr_state c ON c.k3hrid = b.id ");
sql.append(" INNER JOIN geomag_states d ON d.stateid = c.stateid ");
sql.append(" WHERE ");
if (stations != null) {
sql.append(" a.stationcode IN ('");
String station = null;
for (int i = 0; i < stations.size(); i++) {
station = stations.get(i);
sql.append(station).append("'");
if (i != (stations.size() - 1)) {
sql.append(",'");
}
}
sql.append(") AND");
}
sql.append(" a.reftime > '");
sql.append(start).append("' AND a.reftime <= '").append(end)
.append("'");
sql.append(" AND a.ks <= 9.0 ");
sql.append(" AND d.processingstate <= 'Active' ");
sql.append(" AND b.reftime = date_trunc('hour', a.reftime - cast(date_part('HOUR',a.reftime) as bigint) % 3 * INTERVAL '1 hour' + interval '0 hour') ");
sql.append(" GROUP BY a.reftime ORDER BY a.reftime ASC");
// logger.info(" Inside GeoMagK1minDao.getEstKpIndex1min(), sql = "
// + sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return new ArrayList<Map<String, Object>>();
}
String[] fieldNames = { "reftime", "ks_avg", "station_count" };
List<Map<String, Object>> resultMaps = new ArrayList<Map<String, Object>>(
results.length);
for (Object obj : results) {
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
Map<String, Object> resultMap = new HashMap<String, Object>(
objs.length * 2);
for (int i = 0; i < fieldNames.length; ++i) {
resultMap.put(fieldNames[i], objs[i]);
}
resultMaps.add(resultMap);
}
return resultMaps;
}
/**
* Get a list of maps containing the latest estimate kindex and ks values
* for a given list of station codes, start and end dates.
*
* @param stationCodes
* A list of station codes
* @param startTime
* start date
* @param endTime
* end date
* @return List<Map>
*/
public List<Map<String, Object>> getLatestEstKIndex(
final List<String> stationCodes, final Date start, final Date end)
throws Exception {
StringBuffer sql = new StringBuffer();
sql.append(" select a.stationcode, a.reftime, a.kestindex, ks from geomag_k1min a "
+ " inner join (SELECT max(reftime) as latestreftime, stationcode FROM geomag_k1min ");
if (stationCodes != null || (start != null && end != null)) {
sql.append(" WHERE ");
if (stationCodes != null) {
sql.append(" stationcode IN ('");
String station = null;
for (int i = 0; i < stationCodes.size(); i++) {
station = stationCodes.get(i);
sql.append(station).append("'");
if (i != (stationCodes.size() - 1)) {
sql.append(",'");
}
}
sql.append(" ) ");
}
if ((stationCodes != null) && (start != null && end != null)) {
sql.append(" AND ");
}
if (start != null && end != null) {
sql.append(" reftime > '");
sql.append(start).append("' AND reftime <= '").append(end)
.append("'");
}
}
sql.append(" group by stationcode) b "
+ " ON a.stationcode = b.stationcode "
+ " AND a.reftime = b.latestreftime");
sql.append(" order by a.stationcode asc ");
// logger.info(" Inside GeoMagK1minDao.getLatestEstKIndex(), sql = "
// + sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return new ArrayList<Map<String, Object>>();
}
String[] fieldNames = { "stationcode", "reftime", "kestindex", "ks" };
List<Map<String, Object>> resultMaps = new ArrayList<Map<String, Object>>(
results.length);
for (Object obj : results) {
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
Map<String, Object> resultMap = new HashMap<String, Object>(
objs.length * 2);
for (int i = 0; i < fieldNames.length; ++i) {
resultMap.put(fieldNames[i], objs[i]);
}
resultMaps.add(resultMap);
}
return resultMaps;
}
/**
* Get a list of maps containing the latest estimate kindex and ks values
* for a given list of station codes, start and end dates.
*
* @param stationCodes
* A list of station codes
* @param startTime
* start date
* @param endTime
* end date
* @return List<Map>
*/
public Date getLastDataDate(final List<String> stationCodes,
final Date start, final Date end) throws Exception {
StringBuffer sql = new StringBuffer();
sql.append(" select max(reftime) as lastDataDate from geomag_k1min ");
if (stationCodes != null || (start != null && end != null)) {
sql.append(" WHERE ");
if (stationCodes != null) {
sql.append(" stationcode IN ('");
String station = null;
for (int i = 0; i < stationCodes.size(); i++) {
station = stationCodes.get(i);
sql.append(station).append("'");
if (i != (stationCodes.size() - 1)) {
sql.append(",'");
}
}
sql.append(" ) ");
}
if ((stationCodes != null) && (start != null && end != null)) {
sql.append(" AND ");
}
if (start != null && end != null) {
sql.append(" reftime > '");
sql.append(start).append("' AND reftime <= '").append(end)
.append("'");
}
sql.append(" AND ks <= 9.0 ");
}
// logger.info(" Inside GeoMagK1minDao.getLastDataDate(), sql = "
// + sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return new Date();
}
Date lastDataDate = new Date();
String[] fieldNames = { "lastDataDate" };
for (Object obj : results) {
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
lastDataDate = (Date) objs[0];
}
return lastDataDate;
}
public int purgeDataByRefTime(Date refTime) throws DataAccessLayerException {
DatabaseQuery deleteStmt = new DatabaseQuery(this.daoClass);
deleteStmt.addQueryParam("refTime", refTime);

View file

@ -5,6 +5,8 @@ import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK3hr;
import java.util.Date;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
@ -27,6 +29,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
* 08/14/2013 T989 qzhou Initial creation.
* 03/13/2014 sgurung Added method purgeDataByRefTime()
* 10/16/2014 3454 bphillip Upgrading to Hibernate 4
* 07/01/2014 R4078 sgurung Added method getStationMaxPrevTime()
* </pre>
*
* @author qzhou
@ -34,6 +37,10 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
*/
public class GeoMagK3hrDao extends CoreDao {
/** The logger */
protected transient Log logger = LogFactory.getLog(getClass());
/**
* Creates a new GribModelDao
*/
@ -67,25 +74,76 @@ public class GeoMagK3hrDao extends CoreDao {
}
@SuppressWarnings("unchecked")
public List<GeoMagK3hr> getSingleK3hr(final String stationCode,
final Date time) {
public List<GeoMagK3hr> getK3hr(final String stationCode, final Date time) {
return (List<GeoMagK3hr>) txTemplate.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess.createCriteria(GeoMagK3hr.class);
Criterion where1 = Restrictions.eq("stationCode", stationCode);
crit.add(where1);
Criterion where2 = Restrictions.eq("refTime", time);
crit.add(where2);
if (stationCode != null) {
Criterion where1 = Restrictions.eq("stationCode",
stationCode);
crit.add(where1);
}
if (time != null) {
Criterion where2 = Restrictions.eq("refTime", time);
crit.add(where2);
}
return crit.list();
}
});
}
/**
* Returns the record with the max previous time for a given station and
* time tag<br>
*
* @param stationCode
* stationCode
* @param reftime
* time tag
* @return GeoMagK3hr
* @throws Exception
*/
public Date getStationMaxPrevTime(final String stationCode,
final Date reftime) throws Exception {
StringBuffer sql = new StringBuffer();
sql.append(" SELECT reftime FROM geomag_k3hr "
+ " WHERE stationcode = '" + stationCode + "'"
+ " AND reftime < '" + reftime + "'");
sql.append(" ORDER BY reftime DESC");
sql.append(" LIMIT 1");
// logger.info("Inside GeoMagK3hrDao.getStationMaxPrevTime(), sql = "
// + sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return null;
}
String[] fieldNames = { "reftime" };
Object obj = results[0];
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
Date previousTime = (Date) objs[0];
return previousTime;
}
public int purgeDataByRefTime(Date refTime) throws DataAccessLayerException {
DatabaseQuery deleteStmt = new DatabaseQuery(this.daoClass);
deleteStmt.addQueryParam("refTime", refTime);
return this.deleteByCriteria(deleteStmt);
}
}

View file

@ -0,0 +1,454 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.dao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK3hrState;
import gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStation;
import gov.noaa.nws.ncep.common.dataplugin.geomag.util.GeoMagStationLookup;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.transaction.TransactionException;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
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;
/**
* Dao class for GeoMagK3hrState.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 06/27/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
public class GeoMagK3hrStateDao extends CoreDao {
/** The logger */
protected transient Log logger = LogFactory.getLog(getClass());
/**
* Creates a new GeoMagK3hrStateDao
*/
public GeoMagK3hrStateDao() {
super(DaoConfig.forClass(GeoMagK3hrState.class));
}
/**
* Retrieves a GeoMagK3hrState based on the given id
*
* @param id
* The given ID number
* @return The GeoMagK3hrState object associated with the given id
*/
public GeoMagK3hrState queryById(int id) {
return (GeoMagK3hrState) super.queryById(id);
}
/**
* Retrieves list of all GeoMagK3hrState objects
*
* @return list of GeoMagK3hrState objects
*/
@SuppressWarnings("unchecked")
public List<GeoMagK3hrState> getAllStationStateChanges() {
return (List<GeoMagK3hrState>) txTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess
.createCriteria(GeoMagK3hrState.class);
return crit.list();
}
});
}
/**
* Returns the processing states for a list of magnetometer stations (for a
* given synoptic period, if provided)<br>
*
* @param stations
* A list of stations
* @param reftime
* time tag
* @return List of data map containing "reftime", "stationCode",
* "processingState"
* @throws Exception
*/
public List<Map<String, Object>> getKpStationsStates(
final List<String> stations, final Date reftime) throws Exception {
StringBuffer sql = new StringBuffer();
sql.append(" SELECT a.reftime as reftime, a.stationcode as stationcode, c.processingState as processingstate FROM geomag_k3hr AS a"
+ " INNER JOIN geomag_k3hr_state AS b ON b.k3hrId = a.id "
+ " INNER JOIN geomag_states AS c ON c.stateid = b.stateid");
sql.append(" WHERE ");
if (stations != null) {
sql.append(" a.stationcode IN ('");
String station = null;
for (int i = 0; i < stations.size(); i++) {
station = stations.get(i);
sql.append(station).append("'");
if (i != (stations.size() - 1)) {
sql.append(",'");
}
}
sql.append(") AND");
}
sql.append(" a.reftime = '" + reftime + "'");
// sql.append(" AND a.kestreal <= 9.0 ");
sql.append("ORDER BY a.stationcode ASC, c.processingState ASC");
logger.info("Inside GeoMagK3hrStateDao.getKpStationsStates(), sql = "
+ sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return new ArrayList<Map<String, Object>>();
}
String[] fieldNames = { "reftime", "stationcode", "processingstate" };
List<Map<String, Object>> resultMaps = new ArrayList<Map<String, Object>>(
results.length);
for (Object obj : results) {
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
Map<String, Object> resultMap = new HashMap<String, Object>(
objs.length * 2);
for (int i = 0; i < fieldNames.length; ++i) {
resultMap.put(fieldNames[i], objs[i]);
}
resultMaps.add(resultMap);
}
return resultMaps;
}
/**
* Returns the processing states for a given magnetometer station (for a
* given synoptic period, if provided)<br>
*
* @param station
* Station code
* @param reftime
* time tag
* @return List of strings containing "processingstate"
* @throws Exception
*/
public List<String> getKpStationStates(final String station,
final Date reftime) throws Exception {
StringBuffer sql = new StringBuffer();
sql.append(" SELECT c.processingState as processingstate FROM geomag_k3hr AS a"
+ " INNER JOIN geomag_k3hr_state AS b ON b.k3hrId = a.id "
+ " INNER JOIN geomag_states AS c ON c.stateid = b.stateid");
sql.append(" WHERE stationcode = '" + station + "'");
sql.append(" AND");
sql.append(" a.reftime = '" + reftime + "'");
// sql.append(" AND a.kestreal <= 9.0 ");
sql.append("ORDER BY c.processingState ASC");
logger.info("Inside GeoMagK3hrStateDao.getKpStationStates(), sql = "
+ sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return new ArrayList<String>();
}
String[] fieldNames = { "processingstate" };
List<String> resultLst = new ArrayList<String>(results.length);
for (Object obj : results) {
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
resultLst.add((String) objs[0]);
}
return resultLst;
}
/**
* Returns the processing state id for a given station code, reftime and
* processing state.<br>
*
* @param stationCode
* Station code
* @param prevTime
* time tag
* @param state
* processing state
* @return stateId
* @throws Exception
*/
public Integer getStationK3hrStateId(final String stationCode,
final Date prevTime, String state) throws Exception {
Integer stateId = null;
StringBuffer sql = new StringBuffer();
sql.append(" SELECT b.k3hrId FROM geomag_k3hr AS a"
+ " INNER JOIN geomag_k3hr_state AS b ON b.k3hrId = a.id "
+ " INNER JOIN geomag_states AS c ON c.stateid = b.stateid");
sql.append(" WHERE a.stationcode = '" + stationCode + "'");
sql.append(" AND a.reftime = '" + prevTime + "'");
if (state != null) {
sql.append(" AND c.processingState = '" + state + "'");
}
logger.info("Inside GeoMagK3hrStateDao.getStationK3hrStateId(), sql = "
+ sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return null;
}
String[] fieldNames = { "stateid" };
Object obj = results[0];
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
stateId = (Integer) objs[0];
return stateId;
}
/**
* Returns the processing state id for a given station code, reftime and
* processing state.<br>
*
* @param stationCode
* Station code
* @param prevTime
* time tag
* @param state
* processing state
* @return stateId
* @throws Exception
*/
public Integer getStationStateId(final String stationCode,
final Date prevTime, String state) throws Exception {
Integer stateId = null;
StringBuffer sql = new StringBuffer();
sql.append(" SELECT c.stateid FROM geomag_k3hr AS a"
+ " INNER JOIN geomag_k3hr_state AS b ON b.k3hrId = a.id "
+ " INNER JOIN geomag_states AS c ON c.stateid = b.stateid");
sql.append(" WHERE a.stationcode = '" + stationCode + "'");
sql.append(" AND a.reftime = '" + prevTime + "'");
if (state != null) {
sql.append(" AND c.processingState = '" + state + "'");
}
logger.info("Inside GeoMagK3hrStateDao.getStationStateId(), sql = "
+ sql.toString());
Object[] results = executeSQLQuery(sql.toString());
if (results.length == 0) {
return null;
}
System.out.println(" results.length = " + results.length);
String[] fieldNames = { "stateid" };
Object obj = results[0];
if (obj instanceof Object[] == false) {
obj = new Object[] { obj };
}
Object[] objs = (Object[]) obj;
if (objs.length != fieldNames.length) {
throw new Exception(
"Column count returned does not match expected column count");
}
stateId = (Integer) objs[0];
return stateId;
}
/**
* Updates the processing states when a new record is inserted for a
* magnetometer station in the geomag_k3hr table.<br>
*
* @param k3hrId
* k3hrId
* @param stationCode
* stationCode
* @return reftime time tag
* @throws Exception
*/
public void updateStates(final Integer k3hrId, final String stationCode,
final Date refTime) throws TransactionException {
GeoMagK3hrDao k3hrDao = new GeoMagK3hrDao();
GeoMagStateDao stateDao = new GeoMagStateDao();
boolean kpStation = false;
Map<String, ArrayList<GeoMagStation>> allStations = GeoMagStationLookup
.getInstance().getStationsByCodeMap();
if (allStations != null) {
ArrayList<GeoMagStation> geomagStnsSameCode = allStations
.get(stationCode);
if (geomagStnsSameCode != null) {
for (int i = 0; i < geomagStnsSameCode.size(); i++) {
GeoMagStation stn = geomagStnsSameCode.get(i);
if (stn.getKpStation() == 1) {
kpStation = true;
}
}
}
}
try {
Date previousTime = k3hrDao.getStationMaxPrevTime(stationCode,
refTime);
// logger.info("Inside GeoMagK3hrStateDao.updateStates(), previousTime = "
// + previousTime);
Integer stateId = stateDao.getStateByProcessingState("Process")
.getStateId();
if (stateId != null) {
// To get here it would have already been set to Process.
GeoMagK3hrState k3hrStateRec = new GeoMagK3hrState();
k3hrStateRec.setK3hrId(k3hrId);
k3hrStateRec.setStateId(stateId);
persist(k3hrStateRec);
if (kpStation) {
// if station is a kpstation, set to Algorithm
stateId = stateDao.getStateByProcessingState("Algorithm")
.getStateId();
k3hrStateRec = new GeoMagK3hrState();
k3hrStateRec.setK3hrId(k3hrId);
k3hrStateRec.setStateId(stateId);
persist(k3hrStateRec);
if (previousTime != null) {
// if previous period exists and if station state is
// active for that period,
// insert as active
stateId = getStationStateId(stationCode, previousTime,
"Active");
// logger.info("Inside GeoMagK3hrStateDao.updateStates(), stateId = "
// + stateId);
// if there is no data for previous synoptic period,
// then look for stateId
// based on the last data date
// if (stateId == null) {
// List<String> stnList = new ArrayList<String>();
// stnList.add(stationCode);
// GeoMagK1minDao dao = new GeoMagK1minDao();
// Date lastDataDate = dao.getLastDataDate(stnList,
// null, null);
// logger.info("Inside GeoMagK3hrStateDao.updateStates(), lastDataDate = "
// + lastDataDate);
//
// if (lastDataDate != null) {
// stateId = getStationStateId(stationCode,
// lastDataDate, "Active");
//
// logger.info("Inside GeoMagK3hrStateDao.updateStates(), new stateId = "
// + stateId);
//
// }
// }
if (stateId != null) {
k3hrStateRec = new GeoMagK3hrState();
k3hrStateRec.setK3hrId(k3hrId);
k3hrStateRec.setStateId(stateId);
persist(k3hrStateRec);
}
}
}
}
} catch (DataIntegrityViolationException de) {
// logger.info("Record with given stateId and k3hr combination exists.");
} catch (Exception e) {
logger.error("Error while updating processing states.", e);
}
}
public int delete(Integer stateId, Integer k3hrId)
throws DataAccessLayerException {
DatabaseQuery deleteStmt = new DatabaseQuery(this.daoClass);
deleteStmt.addQueryParam("stateId", stateId);
deleteStmt.addQueryParam("k3hrId", k3hrId);
return this.deleteByCriteria(deleteStmt);
}
public int purgeDataByK3hrId(Integer k3hrId)
throws DataAccessLayerException {
DatabaseQuery deleteStmt = new DatabaseQuery(this.daoClass);
deleteStmt.addQueryParam("k3hrId", k3hrId);
return this.deleteByCriteria(deleteStmt);
}
}

View file

@ -0,0 +1,103 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.dao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagState;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
/**
* Dao class for GeoMagState.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 06/27/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
public class GeoMagStateDao extends CoreDao {
/**
* Creates a new GeoMagStateDao
*/
public GeoMagStateDao() {
super(DaoConfig.forClass(GeoMagState.class));
}
/**
* Retrieves a GeoMagState based on the given id
*
* @param id
* The given ID number
* @return The GeoMagState object associated with the given id
*/
public GeoMagState queryById(int id) {
return (GeoMagState) super.queryById(id);
}
/**
* Retrieves list of all GeoMagState objects
*
* @return list of GeoMagState objects
*/
@SuppressWarnings("unchecked")
public List<GeoMagState> getAllStates() {
return (List<GeoMagState>) txTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess.createCriteria(GeoMagState.class);
return crit.list();
}
});
}
/**
* Retrieves a GeoMagState object based on the given processing state
*
* @param procState
* The processing state
* @return The GeoMagState object associated with the processing state
*/
@SuppressWarnings("unchecked")
public GeoMagState getStateByProcessingState(final String procState) {
return (GeoMagState) txTemplate.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess.createCriteria(GeoMagState.class);
Criterion where1 = Restrictions
.eq("processingState", procState);
crit.add(where1);
if (crit.list() != null && crit.list().size() > 0)
return crit.list().get(0);
else
return null;
}
});
}
}

View file

@ -0,0 +1,105 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.dao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagStationStateChange;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import com.raytheon.uf.edex.database.dao.CoreDao;
import com.raytheon.uf.edex.database.dao.DaoConfig;
/**
* Dao class for GeoMagStationStateChange.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ---------------- --------------------------
* 06/27/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
public class GeoMagStationStateChangeDao extends CoreDao {
/**
* Creates a new GeoMagStationStateChangeDao
*/
public GeoMagStationStateChangeDao() {
super(DaoConfig.forClass(GeoMagStationStateChange.class));
}
/**
* Retrieves a GeoMagStationStateChange based on the given id
*
* @param id
* The given ID number
* @return The GeoMagStationStateChange object associated with the given id
*/
public GeoMagStationStateChange queryById(int id) {
return (GeoMagStationStateChange) super.queryById(id);
}
/**
* Retrieves list of all GeoMagStationStateChange objects
*
* @return list of GeoMagStationStateChange objects
*/
@SuppressWarnings("unchecked")
public List<GeoMagStationStateChange> getAllStationStateChanges() {
return (List<GeoMagStationStateChange>) txTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess
.createCriteria(GeoMagStationStateChange.class);
return crit.list();
}
});
}
/**
* Retrieves list of all GeoMagStationStateChange objects for a given
* stationCode
*
* @param stationCode
* The Station code
* @return list of GeoMagStationStateChange objects
*/
@SuppressWarnings("unchecked")
public List<GeoMagStationStateChange> getAllStationStateChangesByStation(
final String stationCode) {
return (List<GeoMagStationStateChange>) txTemplate
.execute(new TransactionCallback() {
@Override
public Object doInTransaction(TransactionStatus status) {
Session sess = getCurrentSession();
Criteria crit = sess
.createCriteria(GeoMagStationStateChange.class);
Criterion where1 = Restrictions.eq("stationCode",
stationCode);
crit.add(where1);
return crit.list();
}
});
}
}

View file

@ -0,0 +1,81 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.request;
import java.util.Date;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
import com.raytheon.uf.common.serialization.comm.IServerRequest;
/**
*
* ChangeStationStateRequest
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 07/01/2014 R4078 sgurung Initial Creation
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
@DynamicSerialize
public class ChangeStationStateRequest implements IServerRequest {
@DynamicSerializeElement
private String stationCode;
@DynamicSerializeElement
private Date synopticTime;
@DynamicSerializeElement
private Integer prevPeriod;
public ChangeStationStateRequest() {
}
public ChangeStationStateRequest(String stationCode, Integer prevPeriod,
Date timeTag) {
super();
this.stationCode = stationCode;
this.synopticTime = timeTag;
this.prevPeriod = prevPeriod;
}
public Integer getPrevPeriod() {
return prevPeriod;
}
public void setPrevPeriod(Integer prevPeriod) {
this.prevPeriod = prevPeriod;
}
public String getStationCode() {
return stationCode;
}
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
public Date getSynopticTime() {
return synopticTime;
}
public void setSynopticTime(Date synopticTime) {
this.synopticTime = synopticTime;
}
}

View file

@ -196,7 +196,7 @@ public class DatabaseUtil {
String station = CalcUtil.getStationFromUri(dataUri);
List<GeoMagK3hr> resultsList = null;
resultsList = k3hrDao.getSingleK3hr(station, epTime);
resultsList = k3hrDao.getK3hr(station, epTime);
return resultsList;
}

View file

@ -0,0 +1,102 @@
package gov.noaa.nws.ncep.common.dataplugin.geomag.request;
import java.util.Date;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
import com.raytheon.uf.common.serialization.comm.IServerRequest;
/**
*
* Request for GeoMag data
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 07/31/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
@DynamicSerialize
public class RetrieveGeoMagDataRequest implements IServerRequest {
public static enum RetrieveGeoMagDataRequestType {
DATA_LIST, COUNT
}
@DynamicSerializeElement
private String stationCode;
@DynamicSerializeElement
private Date startTime;
@DynamicSerializeElement
private Date endTime;
@DynamicSerializeElement
private int sourceId;
@DynamicSerializeElement
private RetrieveGeoMagDataRequestType requestType = RetrieveGeoMagDataRequestType.DATA_LIST;
public RetrieveGeoMagDataRequest() {
}
public RetrieveGeoMagDataRequest(String stationCode, Date startTime,
Date endTime, int sourceId,
RetrieveGeoMagDataRequestType requestType) {
super();
this.stationCode = stationCode;
this.startTime = startTime;
this.endTime = endTime;
this.sourceId = sourceId;
this.requestType = requestType;
}
public String getStationCode() {
return stationCode;
}
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public int getSourceId() {
return sourceId;
}
public void setSourceId(int sourceId) {
this.sourceId = sourceId;
}
public RetrieveGeoMagDataRequestType getRequestType() {
return requestType;
}
public void setRequestType(RetrieveGeoMagDataRequestType requestType) {
this.requestType = requestType;
}
}

View file

@ -1,6 +1,17 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.request;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
@ -8,7 +19,7 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest;
/**
*
* Request for a GeoMagk1min for the given dataURI
* Request for a GeoMagk1min
*
* <pre>
*
@ -17,6 +28,7 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 2014/02/12 #1110 qzhou Init
* 03/05/2014 R4078 sgurung Added requestType and stationCodeList.
*
* </pre>
*
@ -26,6 +38,10 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest;
@DynamicSerialize
public class RetrieveK1minRequest implements IServerRequest {
public static enum RetrieveK1minRequestType {
K, KP, LATEST_K, LAST_DATA_DATE
}
@DynamicSerializeElement
private String stationCode;
@ -35,6 +51,12 @@ public class RetrieveK1minRequest implements IServerRequest {
@DynamicSerializeElement
private Date endTime;
@DynamicSerializeElement
private List<String> stationCodeList;
@DynamicSerializeElement
private RetrieveK1minRequestType requestType = RetrieveK1minRequestType.K;
public RetrieveK1minRequest() {
}
@ -43,6 +65,17 @@ public class RetrieveK1minRequest implements IServerRequest {
this.stationCode = stationCode;
this.startTime = startTime;
this.endTime = endTime;
stationCodeList = new ArrayList<String>();
}
public RetrieveK1minRequest(List<String> stationCodeList, Date startTime,
Date endTime, RetrieveK1minRequestType reqType) {
super();
this.stationCode = null;
this.startTime = startTime;
this.endTime = endTime;
this.stationCodeList = stationCodeList;
requestType = reqType;
}
public String getStationCode() {
@ -69,4 +102,20 @@ public class RetrieveK1minRequest implements IServerRequest {
this.endTime = endTime;
}
public List<String> getStationCodeList() {
return stationCodeList;
}
public void setStationCodeList(List<String> stationCodeList) {
this.stationCodeList = stationCodeList;
}
public RetrieveK1minRequestType getRequestType() {
return requestType;
}
public void setRequestType(RetrieveK1minRequestType requestType) {
this.requestType = requestType;
}
}

View file

@ -0,0 +1,90 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.request;
import java.util.Date;
import java.util.List;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
import com.raytheon.uf.common.serialization.comm.IServerRequest;
/**
*
* RetrieveStationStateRequest
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 07/01/2014 R4078 sgurung Initial Creation
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
@DynamicSerialize
public class RetrieveStationStateRequest implements IServerRequest {
@DynamicSerializeElement
private String stationCode;
@DynamicSerializeElement
private Date refTime;
@DynamicSerializeElement
private List<String> stationCodeList;
public RetrieveStationStateRequest() {
}
public RetrieveStationStateRequest(String stationCode, Date timeTag) {
super();
this.stationCode = stationCode;
this.refTime = timeTag;
this.stationCodeList = null;
}
public RetrieveStationStateRequest(List<String> stationCodeList,
Date timeTag) {
super();
this.stationCode = null;
this.refTime = timeTag;
this.stationCodeList = stationCodeList;
}
public String getStationCode() {
return stationCode;
}
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
public Date getRefTime() {
return refTime;
}
public void setRefTime(Date refTime) {
this.refTime = refTime;
}
public List<String> getStationCodeList() {
return stationCodeList;
}
public void setStationCodeList(List<String> stationCodeList) {
this.stationCodeList = stationCodeList;
}
}

View file

@ -1,3 +1,12 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.table;
import java.util.ArrayList;
@ -9,236 +18,289 @@ import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Defines a magnetometer station.
*
*<pre>
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/29/2013 975 sgurung Initial Creation
* 07/17/2013 975 qzhou Changed source type for reading source attributes
* 04/28/2014 R4078 sgurung Added field kStation and method compareTo().
* </pre>
*
* @author sgurung
* @version 1
*/
@XmlRootElement(name = "geoMagStation")
@XmlAccessorType(XmlAccessType.NONE)
public class GeoMagStation {
@XmlAccessorType(XmlAccessType.FIELD)
public class GeoMagStation implements Comparable<GeoMagStation> {
/**
* Station Code
*/
@XmlElement
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
private String stationCode;
/**
* Provider
*/
@XmlElement
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
private String provider;
/**
* Data sources for the station
*/
@XmlElement
protected ArrayList<GeoMagSource> source;
/**
* Indicates whether the station should be included
* in the K-index processing (if set to true).
*/
@XmlElement
protected Boolean processKQDC;
/**
* Indicates whether the Ks value (station estimate of kp)
* should be calculated for the station (if set to true).
*/
@XmlElement
protected Boolean kpStation;
/**
* Indicates whether the station has a header.
* Same station data may have or have no header.
*/
@XmlElement
protected String hasHeader;
/**
* Data order (e.g. HDZF or XYZF)
*/
@XmlElement
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
private String dataOrder;
/**
* Location (latitude/longitude) of the station
*/
@XmlElement
protected Location location;
/**
* Raw data format of the input data for the station
*/
@XmlElement
protected RawDataFormat rawDataFormat;
public GeoMagStation() {
source = new ArrayList<GeoMagSource>();
}
/**
* Gets the stationCode of this station
* @return the stationCode
*/
public String getStationCode() {
return stationCode;
}
* Station Code
*/
@XmlElement
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
private String stationCode;
/**
* Sets the stationCode of this station
* @param stationCode the stationCode to set
*/
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
/**
* Provider
*/
@XmlElement
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
private String provider;
/**
* Gets the provider of this station
* @return the provider
*/
public String getProvider() {
return provider;
}
/**
* Data sources for the station
*/
@XmlElement
protected ArrayList<GeoMagSource> source;
/**
* Sets the provider of this station
* @param provider the provider to set
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Indicates whether the station should process K quiet day curve (1=yes,
* 0=no).
*/
@XmlElement
protected Integer processKQDC;
/**
* Gets the stationCode of this station
* @return the stationCode
*/
public ArrayList<GeoMagSource> getSource() {
return source;
}
/**
* Indicates whether station is an approved part of Kp network (1=yes,
* 0=no).
*/
@XmlElement
protected Integer kpStation;
/**
* Sets the source of this station
* @param source the source to set
*/
public void setSource(ArrayList<GeoMagSource> source) {
this.source = source;
}
/**
* Indicates whether station will have k-index processing (1=yes, 0=no).
*/
@XmlElement
protected Integer kStation;
/**
* Gets the processKQDC value of this station
* @return the processKQDC
*/
public boolean getProcessKQDC() {
return processKQDC;
}
/**
* Indicates whether the station has a header. Same station data may have or
* have no header.
*/
@XmlElement
protected String hasHeader;
/**
* Sets the processKQDC value of this station
* @param processKQDC the processKQDC to set
*/
public void setProcessKQDC(boolean processKQDC) {
this.processKQDC = processKQDC;
}
/**
* Data order (e.g. HDZF or XYZF)
*/
@XmlElement
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
private String dataOrder;
/**
* Gets the kpStation value of this station
* @return the kpStation
*/
public boolean getKpStation() {
return kpStation;
}
/**
* Location (latitude/longitude) of the station
*/
@XmlElement
protected Location location;
/**
* Sets the kpStation value of this station
* @param kpStation the kpStation to set
*/
public void setKpStation(boolean kpStation) {
this.kpStation = kpStation;
}
/**
* Raw data format of the input data for the station
*/
@XmlElement
protected RawDataFormat rawDataFormat;
/**
* Gets the header true or false
* @return the hasHeader
*/
public String getHasHeader() {
return hasHeader;
}
public GeoMagStation() {
source = new ArrayList<GeoMagSource>();
}
/**
* Sets the hasHeader value of this station
* @param hasHeader the hasHeader to set
*/
public void setHasHeader(String hasHeader) {
this.hasHeader = hasHeader;
}
/**
* Gets the dataOrder of this station
* @return the dataOrder
*/
public String getDataOrder() {
return dataOrder;
}
/**
* Gets the stationCode of this station
*
* @return the stationCode
*/
public String getStationCode() {
return stationCode;
}
/**
* Sets the dataOrder of this station
* @param dataOrder the dataOrder to set
*/
public void setDataOrder(String dataOrder) {
this.dataOrder = dataOrder;
}
/**
* Sets the stationCode of this station
*
* @param stationCode
* the stationCode to set
*/
public void setStationCode(String stationCode) {
this.stationCode = stationCode;
}
/**
* Gets the longitude of this station
* @return the longitude
*/
public Location getLocation() {
return location;
}
/**
* Gets the provider of this station
*
* @return the provider
*/
public String getProvider() {
return provider;
}
/**
* Sets the longitude of this station
* @param longitude the longitude to set
*/
public void setLocation(Location location) {
this.location = location;
}
/**
* Gets the rawDataFormat of this station
* @return the rawDataFormat
*/
public RawDataFormat getRawDataFormat() {
return rawDataFormat;
}
/**
* Sets the provider of this station
*
* @param provider
* the provider to set
*/
public void setProvider(String provider) {
this.provider = provider;
}
/**
* Sets the rawDataFormat of this station
* @param rawDataFormat the rawDataFormat to set
*/
public void setRawDataFormat(RawDataFormat rawDataFormat) {
this.rawDataFormat = rawDataFormat;
}
/**
* Gets the stationCode of this station
*
* @return the stationCode
*/
public ArrayList<GeoMagSource> getSource() {
return source;
}
/**
* Sets the source of this station
*
* @param source
* the source to set
*/
public void setSource(ArrayList<GeoMagSource> source) {
this.source = source;
}
/**
* Gets the processKQDC value of this station
*
* @return the processKQDC
*/
public Integer getProcessKQDC() {
return processKQDC;
}
/**
* Sets the processKQDC value of this station
*
* @param processKQDC
* the processKQDC to set
*/
public void setProcessKQDC(Integer processKQDC) {
this.processKQDC = processKQDC;
}
/**
* Gets the kpStation value of this station
*
* @return the kpStation
*/
public Integer getKpStation() {
return kpStation;
}
/**
* Sets the kpStation value of this station
*
* @param kpStation
* the kpStation to set
*/
public void setKpStation(Integer kpStation) {
this.kpStation = kpStation;
}
/**
* Gets the kStation value of this station
*
* @return the kStation
*/
public Integer getkStation() {
return kStation;
}
/**
* Sets the kStation value of this station
*
* @param kStation
* the kStation to set
*/
public void setkStation(Integer kStation) {
this.kStation = kStation;
}
/**
* Gets the header true or false
*
* @return the hasHeader
*/
public String getHasHeader() {
return hasHeader;
}
/**
* Sets the hasHeader value of this station
*
* @param hasHeader
* the hasHeader to set
*/
public void setHasHeader(String hasHeader) {
this.hasHeader = hasHeader;
}
/**
* Gets the dataOrder of this station
*
* @return the dataOrder
*/
public String getDataOrder() {
return dataOrder;
}
/**
* Sets the dataOrder of this station
*
* @param dataOrder
* the dataOrder to set
*/
public void setDataOrder(String dataOrder) {
this.dataOrder = dataOrder;
}
/**
* Gets the longitude of this station
*
* @return the longitude
*/
public Location getLocation() {
return location;
}
/**
* Sets the longitude of this station
*
* @param longitude
* the longitude to set
*/
public void setLocation(Location location) {
this.location = location;
}
/**
* Gets the rawDataFormat of this station
*
* @return the rawDataFormat
*/
public RawDataFormat getRawDataFormat() {
return rawDataFormat;
}
/**
* Sets the rawDataFormat of this station
*
* @param rawDataFormat
* the rawDataFormat to set
*/
public void setRawDataFormat(RawDataFormat rawDataFormat) {
this.rawDataFormat = rawDataFormat;
}
@Override
public int compareTo(GeoMagStation o) {
return stationCode.compareTo(o.stationCode);
}
}

View file

@ -1,11 +1,17 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.table;
import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
@ -14,20 +20,22 @@ import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import com.raytheon.uf.common.serialization.ISerializableObject;
/**
* This object contains a list of magnetometer stations.
* An object of this class is used by JAXB when marshaling/unmarshaling a list of GeoMagStations
* to/from an XML file.
*
*<pre>
* This object contains a list of magnetometer stations. An object of this class
* is used by JAXB when marshaling/unmarshaling a list of GeoMagStations to/from
* an XML file.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 03/29/2013 975 sgurung Initial Creation
* 03/29/2013 975 sgurung Initial Creation
* 04/29/2014 R4078 sgurung Added constructor GeoMagStationList(ArrayList<GeoMagStation>)
* </pre>
*
* @author sgurung
@ -35,43 +43,49 @@ import com.raytheon.uf.common.serialization.ISerializableObject;
*/
@XmlRootElement(name = "GeoMagStationList")
@XmlAccessorType(XmlAccessType.NONE)
@XmlSeeAlso({ GeoMagStation.class })
public class GeoMagStationList implements ISerializableObject {
/**
* A list of the available GeoMagStaions
*/
@XmlElement(name="geoMagStation")
private ArrayList<GeoMagStation> stationList;
/**
* Default constructor.
*/
public GeoMagStationList() {
stationList = new ArrayList<GeoMagStation>();
}
/**
* Gets the list of GeoMagStaions
* @return the stationList
*/
public ArrayList<GeoMagStation> getGeoMagStationList() {
return stationList;
}
/**
* A list of the available GeoMagStaions
*/
@XmlElement(name = "geoMagStation")
private ArrayList<GeoMagStation> stationList;
/**
/**
* Default constructor.
*/
public GeoMagStationList() {
stationList = new ArrayList<GeoMagStation>();
}
public GeoMagStationList(ArrayList<GeoMagStation> stnsList) {
stationList = stnsList;
}
/**
* Gets the list of GeoMagStaions
*
* @return the stationList
*/
public ArrayList<GeoMagStation> getGeoMagStationList() {
return stationList;
}
/**
*
* @param file
* @return
* @throws JAXBException
*/
public static GeoMagStationList fromFile(File file) throws JAXBException {
GeoMagStationList gml = null;
GeoMagStationList gml = null;
JAXBContext ctx = JAXBContext.newInstance(GeoMagStationList.class);
if (ctx != null) {
Unmarshaller um = ctx.createUnmarshaller();
if (um != null) {
gml = (GeoMagStationList) um.unmarshal(file);
gml = (GeoMagStationList) um.unmarshal(file);
}
}
@ -86,13 +100,13 @@ public class GeoMagStationList implements ISerializableObject {
*/
public static GeoMagStationList fromStream(InputStream is)
throws JAXBException {
GeoMagStationList gml = null;
GeoMagStationList gml = null;
JAXBContext ctx = JAXBContext.newInstance(GeoMagStationList.class);
if (ctx != null) {
Unmarshaller um = ctx.createUnmarshaller();
if (um != null) {
gml = (GeoMagStationList) um.unmarshal(is);
gml = (GeoMagStationList) um.unmarshal(is);
}
}

View file

@ -0,0 +1,93 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.common.dataplugin.geomag.table;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* <pre>
*
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 04/29/2014 R4078 sgurung Initial Creation
* </pre>
*
* @author sgurung
* @version 1
*/
public class GeoMagStationTableReaderWriter {
private final String PACKAGE = "gov.noaa.nws.ncep.common.dataplugin.geomag.table";
/** The logger */
protected transient Log logger = LogFactory.getLog(getClass());
private String xmlFile = null;
public GeoMagStationTableReaderWriter(String file) {
xmlFile = file;
}
public List<GeoMagStation> readGeoMagStationList() throws JAXBException {
JAXBContext context = JAXBContext.newInstance(PACKAGE);
Unmarshaller unmarshaller = context.createUnmarshaller();
GeoMagStationList sfstnlist = null;
File file = new File(xmlFile);
try {
if (file.exists()) {
sfstnlist = (GeoMagStationList) unmarshaller
.unmarshal(new FileReader(xmlFile));
List<GeoMagStation> listOfItems = sfstnlist
.getGeoMagStationList();
return listOfItems;
}
} catch (FileNotFoundException e) {
logger.error(xmlFile + " not found!", e);
}
return null;
}
public void writeGeoMagStationList(GeoMagStationList sfstnlist)
throws JAXBException {
JAXBContext context = JAXBContext.newInstance(PACKAGE);
Marshaller marshaller = context.createMarshaller();
File file = new File(xmlFile);
try {
if (file.exists()) {
marshaller.marshal(sfstnlist, file);
}
} catch (JAXBException e) {
logger.error("Error marshalling " + xmlFile, e);
}
}
}

View file

@ -15,8 +15,8 @@ public class TestGeoMagStationsTable {
public static void main(String args[]) throws Exception{
GeoMagStationTableReader gmstr = new GeoMagStationTableReader("/awips2/edex/data/utility/edex_static/base/ncep/geomagstns/GeoMagStations.xml");
List<GeoMagStation> list = gmstr.getStationList();//gml.getGeoMagStationList();
GeoMagStationTableReaderWriter gmstr = new GeoMagStationTableReaderWriter("/awips2/edex/data/utility/edex_static/base/ncep/geomagstns/GeoMagStations.xml");
List<GeoMagStation> list = gmstr.readGeoMagStationList();//gml.getGeoMagStationList();
System.out.println(" Station count: " + list.size());
for(GeoMagStation itm : list){
System.out.println(" *******************************************************");

View file

@ -1,9 +1,9 @@
package gov.noaa.nws.ncep.common.dataplugin.geomag.util;
import gov.noaa.nws.ncep.common.dataplugin.geomag.exception.GeoMagException;
import gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStation;
import gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStationTableReader;
import gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStationList;
import gov.noaa.nws.ncep.common.dataplugin.geomag.table.GeoMagStationTableReaderWriter;
import java.io.File;
import java.io.IOException;
@ -28,6 +28,7 @@ import com.raytheon.uf.common.localization.PathManagerFactory;
* ------------ ---------- ----------- --------------------------
* 04/2013 975 sgurung Initial creation
* 07/2013 975 qzhou Change Map<String, GeoMagStation> stnsByCode to
* 04/2014 R4078 sgurung Modified methods initStationList() and saveGeoMagStationList()
* </pre>
*
* @author sgurung
@ -72,20 +73,23 @@ public class GeoMagStationLookup {
}
public GeoMagStation getStationByCode(String stnCode, boolean hasHeader) {
ArrayList<GeoMagStation> stationList = null;
stationList = stnsByCode.get(stnCode);
int i = 0;
for (i = 0; i <stationList.size(); i++) {
if (hasHeader == true && stationList.get(i).getRawDataFormat().getHeaderFormat() != null)
break;
else if (hasHeader == false && stationList.get(i).getRawDataFormat().getHeaderFormat() == null)
break;
else if (hasHeader == true && stationList.get(i).getRawDataFormat().getHeaderFormat() == null)
break;
}
ArrayList<GeoMagStation> stationList = null;
stationList = stnsByCode.get(stnCode);
int i = 0;
for (i = 0; i < stationList.size(); i++) {
if (hasHeader == true
&& stationList.get(i).getRawDataFormat().getHeaderFormat() != null)
break;
else if (hasHeader == false
&& stationList.get(i).getRawDataFormat().getHeaderFormat() == null)
break;
else if (hasHeader == true
&& stationList.get(i).getRawDataFormat().getHeaderFormat() == null)
break;
}
return stationList.get(i);
}
@ -95,62 +99,121 @@ public class GeoMagStationLookup {
}
private void initStationList() throws GeoMagException {
IPathManager pathMgr = PathManagerFactory.getPathManager();
LocalizationContext commonStaticBase = pathMgr.getContext(
IPathManager pathMgr = PathManagerFactory.getPathManager();
LocalizationContext commonStaticBase = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.BASE);
/*LocalizationContext commonStaticSite = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.SITE);*/
String path = "";
//String sitePath = "";
LocalizationContext commonStaticSite = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.SITE);
String path = "";
String sitePath = "";
try {
path = pathMgr.getFile(commonStaticBase,
"ncep" + File.separator + "geomag" + File.separator + "geoMagStations.xml")
.getCanonicalPath();
//sitePath = pathMgr.getFile(commonStaticSite, NcPathConstants.GEOMAG_STNS_TBL).getCanonicalPath();
path = pathMgr.getFile(
commonStaticBase,
"ncep" + File.separator + "geomag" + File.separator
+ "geoMagStations.xml").getCanonicalPath();
sitePath = pathMgr.getFile(
commonStaticSite,
"ncep" + File.separator + "geomag" + File.separator
+ "geoMagStations.xml").getCanonicalPath();
} catch (IOException e) {
logger.error("Error reading geomag stations table. ", e);
logger.error("Error reading geomag stations table. ", e);
}
File stnsFile = new File(path);
//File siteStnsFile = new File(sitePath);
GeoMagStationTableReader geoMagStationsTbl = null;
File siteStnsFile = new File(sitePath);
GeoMagStationTableReaderWriter geoMagStationsTbl = null;
try {
if (stnsFile.exists()) {
geoMagStationsTbl = new GeoMagStationTableReader(stnsFile.getPath());
}
// if site version exists, use it instead
/*if (siteStnsFile.exists()) {
geoMagStationsTbl = new GeoMagStationTableReader(stnsFile.getPath());
}*/
List<GeoMagStation> list = (geoMagStationsTbl!=null)?geoMagStationsTbl.getStationList():new ArrayList<GeoMagStation>();
//System.out.println("**list "+list.size());
for(GeoMagStation station : list){
ArrayList<GeoMagStation> stationList = null;
if (stnsByCode.containsKey(station.getStationCode())) {
stationList = stnsByCode.get(station.getStationCode());
if(stationList==null)
stationList=new ArrayList<GeoMagStation>();
if (siteStnsFile.exists()) {
geoMagStationsTbl = new GeoMagStationTableReaderWriter(
siteStnsFile.getPath());
} else if (stnsFile.exists()) {
geoMagStationsTbl = new GeoMagStationTableReaderWriter(
stnsFile.getPath());
}
stationList.add(station);
List<GeoMagStation> list = (geoMagStationsTbl != null) ? geoMagStationsTbl
.readGeoMagStationList() : new ArrayList<GeoMagStation>();
}else{
stationList=new ArrayList<GeoMagStation>();
stationList.add(station);
}
stnsByCode.put(station.getStationCode(), stationList);//station);
}
for (GeoMagStation station : list) {
ArrayList<GeoMagStation> stationList = null;
if (stnsByCode.containsKey(station.getStationCode())) {
stationList = stnsByCode.get(station.getStationCode());
if (stationList == null)
stationList = new ArrayList<GeoMagStation>();
stationList.add(station);
} else {
stationList = new ArrayList<GeoMagStation>();
stationList.add(station);
}
stnsByCode.put(station.getStationCode(), stationList);// station);
}
} catch (Exception e) {
throw new GeoMagException("Unable to unmarshal ncep geomag stations file");
throw new GeoMagException(
"Unable to unmarshal ncep geomag stations file");
}
}
public void saveGeoMagStationList(GeoMagStationList sfstnlist)
throws GeoMagException {
IPathManager pathMgr = PathManagerFactory.getPathManager();
LocalizationContext commonStaticBase = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.BASE);
LocalizationContext commonStaticSite = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.SITE);
String basePath = "";
String sitePath = "";
try {
basePath = pathMgr.getFile(
commonStaticBase,
"ncep" + File.separator + "geomag" + File.separator
+ "geoMagStations.xml").getCanonicalPath();
sitePath = pathMgr.getFile(
commonStaticSite,
"ncep" + File.separator + "geomag" + File.separator
+ "geoMagStations.xml").getCanonicalPath();
} catch (IOException e) {
logger.error("Error reading geomag stations table. ", e);
throw new GeoMagException("Error reading geoMagStations.xml file. "
+ e);
}
File stnsTableBase = new File(basePath);
File stnsTableSite = new File(sitePath);
GeoMagStationTableReaderWriter geoMagStationsTbl = null;
try {
if (stnsTableSite.exists()) {
geoMagStationsTbl = new GeoMagStationTableReaderWriter(
stnsTableSite.getPath());
geoMagStationsTbl.writeGeoMagStationList(sfstnlist);
} else {
if (stnsTableBase.exists()) {
geoMagStationsTbl = new GeoMagStationTableReaderWriter(
stnsTableBase.getPath());
geoMagStationsTbl.writeGeoMagStationList(sfstnlist);
}
}
} catch (Exception e) {
throw new GeoMagException(
"Unable to marshal ncep geomag stations file");
}
}
}

View file

@ -1,6 +1,7 @@
package gov.noaa.nws.ncep.common.dataplugin.geomag.util;
import gov.noaa.nws.ncep.common.dataplugin.geomag.exception.GeoMagException;
import java.io.File;
import com.raytheon.uf.common.localization.IPathManager;
@ -8,13 +9,15 @@ import com.raytheon.uf.common.localization.LocalizationContext;
import com.raytheon.uf.common.localization.PathManagerFactory;
/**
* TableTimeStamp - A Java class to update geoMagStations.xml.
*
* TableTimeStamp - A Java class to update geoMagStations.xml.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 04/2013 975 S. Gurung Initial creation
* 04/2013 975 S. Gurung Initial creation
* 06/2014 R4078 S. Gurung Added support for site level geoMagStations.xml file
*
* </pre>
*
@ -34,33 +37,56 @@ public class TableTimeStamp {
long geoMagStationFileTime = 0;
IPathManager pathMgr = PathManagerFactory.getPathManager();
LocalizationContext commonStaticBase = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.BASE);
LocalizationContext commonStaticSite = pathMgr.getContext(
LocalizationContext.LocalizationType.COMMON_STATIC,
LocalizationContext.LocalizationLevel.SITE);
/* check geoMagStations.xml file */
String path = "";
String basePath = "";
String sitePath = "";
try {
path = pathMgr.getFile(commonStaticBase,
"ncep" + File.separator + "geomag" + File.separator + "geoMagStations.xml")
.getCanonicalPath();
basePath = pathMgr.getFile(
commonStaticBase,
"ncep" + File.separator + "geomag" + File.separator
+ "geoMagStations.xml").getCanonicalPath();
sitePath = pathMgr.getFile(
commonStaticSite,
"ncep" + File.separator + "geomag" + File.separator
+ "geoMagStations.xml").getCanonicalPath();
} catch (Exception e) {
throw new GeoMagException(
"Unable to unmarshal geoMagStations.xml file");
}
File stnsTable = new File(path);
File stnsTableBase = new File(basePath);
File stnsTableSite = new File(sitePath);
try {
if (stnsTable.exists()) {
geoMagStationFileTime = stnsTable.lastModified();
if (stnsTableSite.exists()) {
geoMagStationFileTime = stnsTableSite.lastModified();
if (geoMagStationFileTime != getGeoMagStationsTimeStamp()) {
System.out
.println("geoMagStations.xml has been modified or the first time, so load it ...");
.println("Site level geoMagStations.xml has been modified or the first time, so load it ...");
GeoMagStationLookup.ReloadInstance();
setGeoMagStationsTimeStamp(geoMagStationFileTime);
}
} else {
if (stnsTableBase.exists()) {
geoMagStationFileTime = stnsTableBase.lastModified();
if (geoMagStationFileTime != getGeoMagStationsTimeStamp()) {
System.out
.println("Base level geoMagStations.xml has been modified or the first time, so load it ...");
GeoMagStationLookup.ReloadInstance();
setGeoMagStationsTimeStamp(geoMagStationFileTime);
}
}
}
} catch (Exception e) {
throw new GeoMagException("Unable to read geoMagStations.xml file");

View file

@ -0,0 +1,220 @@
/**
*
*/
package gov.noaa.nws.ncep.common.dataplugin.ncscat;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* NcscatMode - Enum class to centralize and encapsulate all the things that
* vary among different satellite and data feed types.
*
* //TODO: Consider moving this information entirely to the bundle and/or
* preferences (.xml/.prm) files, so the Java code can be completely agnostic
* about satellite data types; would allow extended 'configurability', at the
* expense of slightly longer bundle/preference files...
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 02 Jun 2010 235B B. Hebbard Initial creation.
* 03 Feb 2011 235E B. Hebbard Add support for ambiguity variants.
* 16 Aug 2012 B. Hebbard Add OSCAT / OSCAT_HI
* 11 Apr 2014 1128 B. Hebbard Add longitudeCoding field; change wind sense from boolean to enum.
* 21 Oct 2014 R4865 B. Hebbard (TTR 984) Add file-header length and reportType fields to enable refactor to make decoding more robust (and thereby prevent date and other corruption)
*
* </pre>
*
* @author bhebbard
* @version 1.0
*/
public enum NcscatMode {
// The only ordering constraint here is that if A.pointsPerRow divides
// B.pointsPerRow and A and B have the same byteOrder, then A should come
// before B. (Currently, no such cases exist.) This is so that we can check
// an unknown data file for 'consistency' with these types, in order, and
// choose the first one that matches. (In the hypothetical case above, A and
// B could both pass consistency checking, but we'd want to choose A.)
// @formatter:off ppr hdr
QUIKSCAT ( 76, 0, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN, "quikscat" ),
QUIKSCAT_HI ( 152, 0, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN, "quikscat-hi"),
ASCAT ( 42, 0, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN, "ascat"),
ASCAT_HI ( 82, 0, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN, "ascat-hi"),
EXASCT ( 42, 0, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.LITTLE_ENDIAN, "Exasct"),
EXASCT_HI ( 82, 0, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.LITTLE_ENDIAN, "Exasct-hi"),
OSCAT ( 36, 0, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN, "oscat"),
OSCAT_HI ( 76, 0, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.LITTLE_ENDIAN, "oscat-hi"),
WSCAT ( 79, 56, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.SIGNED, ByteOrder.LITTLE_ENDIAN, "wscat"),
UNKNOWN ( 76, 0, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN, "unknown");
// @formatter:on
private int pointsPerRow; // number of Wind Vector Cell in each scan row
// across satellite track
private WindDirectionSense windDirectionSense; // is the numeric wind
// direction the "from"
// (METEOROLOGICAL)
// direction, or the "to"
// (OCEANOGRAPHIC) direction?
private LongitudeCoding longitudeCoding; // is the two-byte value a SIGNED
// (-18000 -- +18000) or UNSIGNED
// (0 -- 36000) representation of
// the (scaled by 100) longitude
// east of Greenwich?
private ByteOrder byteOrder; // endianess of data in the byte stream
private String reportType; // string to use in reportType field of DB
private int valuesPerPoint = 9; // number of (short int) data values per
// point
private int bytesPerValue = 2; // all are short int
private int fileHeaderLength; // length in bytes of per-file header field,
// if any, in input file, before repeating
// per-row data begins; of interest to decoder
private int rowHeaderLength = 8; // length in bytes of per-row header field
// (2 bytes each for day, hour, min, sec)
private int bytesPerRow; // length in bytes of each row, comprising row
// header and all data values for all points in
// that row
public int getBytesPerRow() {
return bytesPerRow;
}
// Constructor
NcscatMode(int pointsPerRow, int fileHeaderLength,
WindDirectionSense windDirectionSense,
LongitudeCoding longitudeCoding, ByteOrder byteOrder,
String reportType) {
this.pointsPerRow = pointsPerRow;
this.fileHeaderLength = fileHeaderLength;
this.windDirectionSense = windDirectionSense;
this.longitudeCoding = longitudeCoding;
this.byteOrder = byteOrder;
this.reportType = reportType;
bytesPerRow = rowHeaderLength + pointsPerRow * valuesPerPoint
* bytesPerValue;
}
public String getReportType() {
return reportType;
}
public int getPointsPerRow() {
return pointsPerRow;
}
public int getFileHeaderLength() {
return fileHeaderLength;
}
public WindDirectionSense getWindDirectionSense() {
return windDirectionSense;
}
public LongitudeCoding getLongitudeCoding() {
return longitudeCoding;
}
public ByteOrder getByteOrder() {
return byteOrder;
}
public enum WindDirectionSense { // numeric direction value gives...
METEOROLOGICAL, // degrees FROM which wind is blowing
OCEANOGRAPHIC // degrees TO which wind is blowing
}
public enum LongitudeCoding { // 2-byte wvc_lon (Wind Vector Cell -
// longitude) field is (x0.01 deg)...
SIGNED, // SIGNED short (-18000..+18000)
UNSIGNED // UNSIGNED short (0..36000 east of Greenwich)
}
public static NcscatMode stringToMode(String name) {
// Given a string, return the corresponding enum
NcscatMode returnValue = null;
name = name.toUpperCase();
name = name.replaceAll("-", "_");
// TODO: Remove ambiguity number??
try {
returnValue = valueOf(name);
} catch (IllegalArgumentException e) {
// TODO: Signal unrecognized Ncscat mode string
returnValue = UNKNOWN;
}
return returnValue;
}
public boolean consistentWith(ByteBuffer byteBuffer) {
// Given a ByteBuffer containing ingested binary data of unknown
// satellite type (mode), determine whether data are consistent
// with "this" mode. We do this by seeing if date/hour fields
// repeat where they would be expected to appear, and contain
// reasonable values for those fields.
// TODO: Consider moving this to decoder...? (Kind of prefer
// encapsulating it here, but also like enums to be rather
// minimalistic...? -bh)
byteBuffer.order(byteOrder);
int base = fileHeaderLength;
for (int cycle = 0; cycle < 2; cycle++) {
// DAY (of year) candidate fields of consecutive rows out of
// range...
short thisCandidateDayOfYear = byteBuffer.getShort(base);
short nextCandidateDayOfYear = byteBuffer.getShort(base
+ bytesPerRow);
if (thisCandidateDayOfYear < 1 || thisCandidateDayOfYear > 366
|| nextCandidateDayOfYear < 1
|| nextCandidateDayOfYear > 366)
// ...means (right away) data can't be this type
return false;
// ...but if they don't match...
if (thisCandidateDayOfYear != nextCandidateDayOfYear) {
// ...can't rule it out (since first two rows could straddle a
// day boundary)...but can skip checking hour and go to check
// next pair of rows...
break;
}
// HOUR candidate fields (of consecutive rows) in range...?
short thisCandidateHour = byteBuffer.getShort(base + 2);
short nextCandidateHour = byteBuffer.getShort(base + 2
+ bytesPerRow);
if (thisCandidateHour < 0 || thisCandidateHour > 23
|| nextCandidateHour < 0 || nextCandidateHour > 23)
return false;
// ...and if they do match (as well as day field above), then we
// conclude consistency
if (byteBuffer.getShort(base) == byteBuffer.getShort(base
+ bytesPerRow)) {
return true;
}
// ...but if they don't, again, first two rows could straddle an
// hour boundary, so go to next pair of rows (cycle)...
base += bytesPerRow;
}
// We've made it through 2 consecutive cycles, and neither (1st/2nd
// nor 2nd/3rd) day+hour match, so conclude (assuming real consecutive
// rows are not separated by an hour or more) data not consistent with
// this type
return false;
}
}

View file

@ -16,6 +16,8 @@
* from database instead of snstns.xml file
* 6/2014 T.Lee Added support XXAA, XXBB, XXCC, XXDD
* Jul 23, 2014 3410 bclement location changed to floats
* 10/2014 B. Hebbard Allow subsetting XXAA/TTAA params only for faster
* retrieval in cases where other params not needed
* </pre>
*
* This code has been developed by the SIB for use in the AWIPS2 system.
@ -41,6 +43,7 @@ import org.apache.commons.logging.LogFactory;
import com.raytheon.uf.common.pointdata.PointDataContainer;
import com.raytheon.uf.common.pointdata.PointDataView;
import com.raytheon.uf.common.pointdata.spatial.SurfaceObsLocation;
public class NcUairToRecord {
/** The logger */
@ -67,7 +70,7 @@ public class NcUairToRecord {
HDR_PARAMS_LIST = sb.toString();
}
public static final String MAN_PARAMS_LIST;
public static final String AA_ONLY_PARAMS_LIST;
static {
StringBuffer sb = new StringBuffer();
sb.append(HDR_PARAMS_LIST);
@ -79,7 +82,22 @@ public class NcUairToRecord {
sb.append("TTAA_SPED,");
sb.append("TTAA_HGHT,");
// -------------------------
sb.append("numTTBB,");
sb.append("numXXAA,");
sb.append("XXAA_PRES,");
sb.append("XXAA_TEMP,");
sb.append("XXAA_DWPT,");
sb.append("XXAA_DRCT,");
sb.append("XXAA_SPED,");
sb.append("XXAA_HGHT");
AA_ONLY_PARAMS_LIST = sb.toString();
}
public static final String MAN_PARAMS_LIST;
static {
StringBuffer sb = new StringBuffer();
sb.append(AA_ONLY_PARAMS_LIST);
// -------------------------
sb.append(",numTTBB,");
sb.append("TTBB_PRES,");
sb.append("TTBB_TEMP,");
sb.append("TTBB_DWPT,");
@ -151,14 +169,6 @@ public class NcUairToRecord {
sb.append("TTBB_HI_MEAN_DRCT,");
sb.append("TTBB_HI_MEAN_SPED,");
// -------------------------
sb.append("numXXAA,");
sb.append("XXAA_PRES,");
sb.append("XXAA_TEMP,");
sb.append("XXAA_DWPT,");
sb.append("XXAA_DRCT,");
sb.append("XXAA_SPED,");
sb.append("XXAA_HGHT,");
// -------------------------
sb.append("numXXBB,");
sb.append("XXBB_PRES,");
sb.append("XXBB_TEMP,");

View file

@ -41,7 +41,7 @@ public class MetParameterFactory implements ISerializableObject {
@DynamicSerializeElement
private HashMap<String, String> ncParamsAliasMap = new HashMap<String, String>();
//
//
@DynamicSerializeElement
private HashMap<String, AbstractMetParameter> ncParamsMap = new HashMap<String, AbstractMetParameter>();
@ -57,290 +57,559 @@ public class MetParameterFactory implements ISerializableObject {
private MetParameterFactory() {
try {
ncParamsMap.put(AircraftType.class.getSimpleName(), new AircraftType());
ncParamsMap.put(AircraftReportType.class.getSimpleName(), new AircraftReportType());
ncParamsMap.put(AmountOfCondPrecipIn12Hrs.class.getSimpleName(), new AmountOfCondPrecipIn12Hrs());
ncParamsMap.put(AmountOfCondPrecipIn24Hrs.class.getSimpleName(), new AmountOfCondPrecipIn24Hrs());
ncParamsMap.put(Avg3HrShipSpeed.class.getSimpleName(), new Avg3HrShipSpeed());
ncParamsMap.put(Avg1HrHeatFlux.class.getSimpleName(), new Avg1HrHeatFlux());
ncParamsMap.put(Avg1HrSnowPhaseChangeHeatFlux.class.getSimpleName(), new Avg1HrSnowPhaseChangeHeatFlux());
ncParamsMap.put(Avg1HrSubSurfaceHeatFlux.class.getSimpleName(), new Avg1HrSubSurfaceHeatFlux());
ncParamsMap.put(BaseOfIcing.class.getSimpleName(), new BaseOfIcing());
ncParamsMap.put(BaseOfTurbulence.class.getSimpleName(), new BaseOfTurbulence());
ncParamsMap.put(BaseOfWeather.class.getSimpleName(), new BaseOfWeather());
ncParamsMap.put(BruntVaisalaFreq.class.getSimpleName(), new BruntVaisalaFreq());
ncParamsMap.put(BruntVaisalaPeriod.class.getSimpleName(), new BruntVaisalaPeriod());
// ncParamsMap.put( BruntVaisalaFrequencySquared.class.getSimpleName(), new BruntVaisalaFrequencySquared() );
ncParamsMap.put(CatFcstCeilingHeightCond.class.getSimpleName(), new CatFcstCeilingHeightCond());
ncParamsMap.put(CatFcstObstructionsVision.class.getSimpleName(), new CatFcstObstructionsVision());
ncParamsMap.put(CatFcstPrecipitation.class.getSimpleName(), new CatFcstPrecipitation());
ncParamsMap.put(AircraftType.class.getSimpleName(),
new AircraftType());
ncParamsMap.put(AircraftReportType.class.getSimpleName(),
new AircraftReportType());
ncParamsMap.put(AmountOfCondPrecipIn12Hrs.class.getSimpleName(),
new AmountOfCondPrecipIn12Hrs());
ncParamsMap.put(AmountOfCondPrecipIn24Hrs.class.getSimpleName(),
new AmountOfCondPrecipIn24Hrs());
ncParamsMap.put(Avg3HrShipSpeed.class.getSimpleName(),
new Avg3HrShipSpeed());
ncParamsMap.put(Avg1HrHeatFlux.class.getSimpleName(),
new Avg1HrHeatFlux());
ncParamsMap.put(
Avg1HrSnowPhaseChangeHeatFlux.class.getSimpleName(),
new Avg1HrSnowPhaseChangeHeatFlux());
ncParamsMap.put(Avg1HrSubSurfaceHeatFlux.class.getSimpleName(),
new Avg1HrSubSurfaceHeatFlux());
ncParamsMap.put(BaseOfIcing.class.getSimpleName(),
new BaseOfIcing());
ncParamsMap.put(BaseOfTurbulence.class.getSimpleName(),
new BaseOfTurbulence());
ncParamsMap.put(BaseOfWeather.class.getSimpleName(),
new BaseOfWeather());
ncParamsMap.put(BruntVaisalaFreq.class.getSimpleName(),
new BruntVaisalaFreq());
ncParamsMap.put(BruntVaisalaPeriod.class.getSimpleName(),
new BruntVaisalaPeriod());
// ncParamsMap.put(
// BruntVaisalaFrequencySquared.class.getSimpleName(), new
// BruntVaisalaFrequencySquared() );
ncParamsMap.put(CatFcstCeilingHeightCond.class.getSimpleName(),
new CatFcstCeilingHeightCond());
ncParamsMap.put(CatFcstObstructionsVision.class.getSimpleName(),
new CatFcstObstructionsVision());
ncParamsMap.put(CatFcstPrecipitation.class.getSimpleName(),
new CatFcstPrecipitation());
ncParamsMap.put(CatFcstSnowAmountFalling06hr.class.getSimpleName(), new CatFcstSnowAmountFalling06hr());
ncParamsMap.put(CatFcstSnowAmountFalling12hr.class.getSimpleName(), new CatFcstSnowAmountFalling12hr());
ncParamsMap.put(CatFcstSnowAmountFalling24hr.class.getSimpleName(), new CatFcstSnowAmountFalling24hr());
ncParamsMap.put(CatFcstVisibilityCond.class.getSimpleName(), new CatFcstVisibilityCond());
ncParamsMap.put(CeilingFromSurface.class.getSimpleName(), new CeilingFromSurface());
ncParamsMap.put(CeilingFromSeaLevel.class.getSimpleName(), new CeilingFromSeaLevel());
ncParamsMap.put(CatFcstSnowAmountFalling06hr.class.getSimpleName(),
new CatFcstSnowAmountFalling06hr());
ncParamsMap.put(CatFcstSnowAmountFalling12hr.class.getSimpleName(),
new CatFcstSnowAmountFalling12hr());
ncParamsMap.put(CatFcstSnowAmountFalling24hr.class.getSimpleName(),
new CatFcstSnowAmountFalling24hr());
ncParamsMap.put(CatFcstVisibilityCond.class.getSimpleName(),
new CatFcstVisibilityCond());
ncParamsMap.put(CeilingFromSurface.class.getSimpleName(),
new CeilingFromSurface());
ncParamsMap.put(CeilingFromSeaLevel.class.getSimpleName(),
new CeilingFromSeaLevel());
ncParamsMap.put(CloudCover.class.getSimpleName(), new CloudCover());
ncParamsMap.put(ClimDayTemp.class.getSimpleName(), new ClimDayTemp());
ncParamsMap.put(ClimNightTemp.class.getSimpleName(), new ClimNightTemp());
ncParamsMap.put(Clim12HrPOP.class.getSimpleName(), new Clim12HrPOP());
ncParamsMap.put(Clim24HrPOP.class.getSimpleName(), new Clim24HrPOP());
ncParamsMap.put(ClimDayTemp.class.getSimpleName(),
new ClimDayTemp());
ncParamsMap.put(ClimNightTemp.class.getSimpleName(),
new ClimNightTemp());
ncParamsMap.put(Clim12HrPOP.class.getSimpleName(),
new Clim12HrPOP());
ncParamsMap.put(Clim24HrPOP.class.getSimpleName(),
new Clim24HrPOP());
ncParamsMap.put(CloudBase1.class.getSimpleName(), new CloudBase1());
ncParamsMap.put(CloudBase2.class.getSimpleName(), new CloudBase2());
ncParamsMap.put(CloudFractionInLayer.class.getSimpleName(), new CloudFractionInLayer());
ncParamsMap.put(CloudFractionInLayer.class.getSimpleName(),
new CloudFractionInLayer());
ncParamsMap.put(CloudWater.class.getSimpleName(), new CloudWater());
ncParamsMap.put(CloudTop1.class.getSimpleName(), new CloudTop1());
ncParamsMap.put(CloudTop2.class.getSimpleName(), new CloudTop2());
ncParamsMap.put(CondProbOf6HrSevereWeather.class.getSimpleName(), new CondProbOf6HrSevereWeather());
ncParamsMap.put(CondProbOf12HrSevereWeather.class.getSimpleName(), new CondProbOf12HrSevereWeather());
ncParamsMap.put(CondProbOf12HrFreezingPrecip.class.getSimpleName(), new CondProbOf12HrFreezingPrecip());
ncParamsMap.put(CondProbOf12HrRain.class.getSimpleName(), new CondProbOf12HrRain());
ncParamsMap.put(CondFcstPrecip12HrType.class.getSimpleName(), new CondFcstPrecip12HrType());
ncParamsMap.put(CondProbOf12HrSnow.class.getSimpleName(), new CondProbOf12HrSnow());
ncParamsMap.put(CondProbOf24HrSevereWeather.class.getSimpleName(), new CondProbOf24HrSevereWeather());
ncParamsMap.put(CondProbOfFreezingPrecip.class.getSimpleName(), new CondProbOfFreezingPrecip());
ncParamsMap.put(CondProbOfLiquidPrecip.class.getSimpleName(), new CondProbOfLiquidPrecip());
ncParamsMap.put(CondProbOfMixedPrecip.class.getSimpleName(), new CondProbOfMixedPrecip());
ncParamsMap.put(CondProbOfContPrecip.class.getSimpleName(), new CondProbOfContPrecip());
ncParamsMap.put(CondProbOfDrizzle.class.getSimpleName(), new CondProbOfDrizzle());
ncParamsMap.put(CondProbOfShowers.class.getSimpleName(), new CondProbOfShowers());
ncParamsMap.put(CondProbOfSnow.class.getSimpleName(), new CondProbOfSnow());
ncParamsMap.put(ConvectivePrecip.class.getSimpleName(), new ConvectivePrecip());
ncParamsMap.put(CondProbOf6HrSevereWeather.class.getSimpleName(),
new CondProbOf6HrSevereWeather());
ncParamsMap.put(CondProbOf12HrSevereWeather.class.getSimpleName(),
new CondProbOf12HrSevereWeather());
ncParamsMap.put(CondProbOf12HrFreezingPrecip.class.getSimpleName(),
new CondProbOf12HrFreezingPrecip());
ncParamsMap.put(CondProbOf12HrRain.class.getSimpleName(),
new CondProbOf12HrRain());
ncParamsMap.put(CondFcstPrecip12HrType.class.getSimpleName(),
new CondFcstPrecip12HrType());
ncParamsMap.put(CondProbOf12HrSnow.class.getSimpleName(),
new CondProbOf12HrSnow());
ncParamsMap.put(CondProbOf24HrSevereWeather.class.getSimpleName(),
new CondProbOf24HrSevereWeather());
ncParamsMap.put(CondProbOfFreezingPrecip.class.getSimpleName(),
new CondProbOfFreezingPrecip());
ncParamsMap.put(CondProbOfLiquidPrecip.class.getSimpleName(),
new CondProbOfLiquidPrecip());
ncParamsMap.put(CondProbOfMixedPrecip.class.getSimpleName(),
new CondProbOfMixedPrecip());
ncParamsMap.put(CondProbOfContPrecip.class.getSimpleName(),
new CondProbOfContPrecip());
ncParamsMap.put(CondProbOfDrizzle.class.getSimpleName(),
new CondProbOfDrizzle());
ncParamsMap.put(CondProbOfShowers.class.getSimpleName(),
new CondProbOfShowers());
ncParamsMap.put(CondProbOfSnow.class.getSimpleName(),
new CondProbOfSnow());
ncParamsMap.put(ConvectivePrecip.class.getSimpleName(),
new ConvectivePrecip());
ncParamsMap.put(ShipCourse.class.getSimpleName(), new ShipCourse());
ncParamsMap.put(DayTempAnomaly.class.getSimpleName(), new DayTempAnomaly());
ncParamsMap.put(DayTempFcst.class.getSimpleName(), new DayTempFcst());
ncParamsMap.put(DewPointDepression.class.getSimpleName(), new DewPointDepression());
ncParamsMap.put(DewPointTemp.class.getSimpleName(), new DewPointTemp());
ncParamsMap.put(DryBulbTemp.class.getSimpleName(), new DryBulbTemp());
ncParamsMap.put(FiveSecPeakWindDir.class.getSimpleName(), new FiveSecPeakWindDir());
ncParamsMap.put(PredomSwellWaveDir.class.getSimpleName(), new PredomSwellWaveDir());
ncParamsMap.put(SecondarySwellWaveDir.class.getSimpleName(), new SecondarySwellWaveDir());
ncParamsMap.put(DayTempAnomaly.class.getSimpleName(),
new DayTempAnomaly());
ncParamsMap.put(DayTempFcst.class.getSimpleName(),
new DayTempFcst());
ncParamsMap.put(DewPointDepression.class.getSimpleName(),
new DewPointDepression());
ncParamsMap.put(DewPointTemp.class.getSimpleName(),
new DewPointTemp());
ncParamsMap.put(DryBulbTemp.class.getSimpleName(),
new DryBulbTemp());
ncParamsMap.put(FiveSecPeakWindDir.class.getSimpleName(),
new FiveSecPeakWindDir());
ncParamsMap.put(PredomSwellWaveDir.class.getSimpleName(),
new PredomSwellWaveDir());
ncParamsMap.put(SecondarySwellWaveDir.class.getSimpleName(),
new SecondarySwellWaveDir());
ncParamsMap.put(DPRN.class.getSimpleName(), new DPRN());
ncParamsMap.put(DryAirDensity.class.getSimpleName(), new DryAirDensity());
ncParamsMap.put(DryHydrostaticHeight.class.getSimpleName(), new DryHydrostaticHeight());
ncParamsMap.put(TimeOf5SecPeakWindInHrs.class.getSimpleName(), new TimeOf5SecPeakWindInHrs());
ncParamsMap.put(TimeOf5SecPeakWindInMins.class.getSimpleName(), new TimeOf5SecPeakWindInMins());
ncParamsMap.put(EquivPotentialTemp.class.getSimpleName(), new EquivPotentialTemp());
ncParamsMap.put(EquivWindSpeed10min.class.getSimpleName(), new EquivWindSpeed10min());
ncParamsMap.put(EquivWindSpeed20min.class.getSimpleName(), new EquivWindSpeed20min());
ncParamsMap.put(FcstFZRainAccumulationIn12Hours.class.getSimpleName(), new FcstFZRainAccumulationIn12Hours());
ncParamsMap.put(FcstFZRainAccumulationToWatchThresh.class.getSimpleName(), new FcstFZRainAccumulationToWatchThresh());
ncParamsMap.put(FcstSnowIcePelletAccumulation12Hrs.class.getSimpleName(), new FcstSnowIcePelletAccumulation12Hrs());
ncParamsMap.put(FcstSnowIcePelletAccumToWatchThresh.class.getSimpleName(), new FcstSnowIcePelletAccumToWatchThresh());
ncParamsMap.put(FlashFloodGuid01Hr.class.getSimpleName(), new FlashFloodGuid01Hr());
ncParamsMap.put(FlashFloodGuid03Hr.class.getSimpleName(), new FlashFloodGuid03Hr());
ncParamsMap.put(FlashFloodGuid06Hr.class.getSimpleName(), new FlashFloodGuid06Hr());
ncParamsMap.put(FlashFloodGuid12Hr.class.getSimpleName(), new FlashFloodGuid12Hr());
ncParamsMap.put(FlashFloodGuid24Hr.class.getSimpleName(), new FlashFloodGuid24Hr());
ncParamsMap.put(FlightRulesID.class.getSimpleName(), new FlightRulesID());
ncParamsMap.put(FlightLevel.class.getSimpleName(), new FlightLevel());
ncParamsMap.put(FosbergFireWxIndex.class.getSimpleName(), new FosbergFireWxIndex());
ncParamsMap.put(FZRainWatchThresh.class.getSimpleName(), new FZRainWatchThresh());
// ncParamsMap.put( GenericDimensionlessParameter.class.getSimpleName(), new GenericDimensionlessParameter() );
// ncParamsMap.put( GustBarb.class.getSimpleName(), new GustBarb() );
ncParamsMap.put(DryAirDensity.class.getSimpleName(),
new DryAirDensity());
ncParamsMap.put(DryHydrostaticHeight.class.getSimpleName(),
new DryHydrostaticHeight());
ncParamsMap.put(TimeOf5SecPeakWindInHrs.class.getSimpleName(),
new TimeOf5SecPeakWindInHrs());
ncParamsMap.put(TimeOf5SecPeakWindInMins.class.getSimpleName(),
new TimeOf5SecPeakWindInMins());
ncParamsMap.put(EquivPotentialTemp.class.getSimpleName(),
new EquivPotentialTemp());
ncParamsMap.put(EquivWindSpeed10min.class.getSimpleName(),
new EquivWindSpeed10min());
ncParamsMap.put(EquivWindSpeed20min.class.getSimpleName(),
new EquivWindSpeed20min());
ncParamsMap.put(
FcstFZRainAccumulationIn12Hours.class.getSimpleName(),
new FcstFZRainAccumulationIn12Hours());
ncParamsMap.put(
FcstFZRainAccumulationToWatchThresh.class.getSimpleName(),
new FcstFZRainAccumulationToWatchThresh());
ncParamsMap.put(
FcstSnowIcePelletAccumulation12Hrs.class.getSimpleName(),
new FcstSnowIcePelletAccumulation12Hrs());
ncParamsMap.put(
FcstSnowIcePelletAccumToWatchThresh.class.getSimpleName(),
new FcstSnowIcePelletAccumToWatchThresh());
ncParamsMap.put(FlashFloodGuid01Hr.class.getSimpleName(),
new FlashFloodGuid01Hr());
ncParamsMap.put(FlashFloodGuid03Hr.class.getSimpleName(),
new FlashFloodGuid03Hr());
ncParamsMap.put(FlashFloodGuid06Hr.class.getSimpleName(),
new FlashFloodGuid06Hr());
ncParamsMap.put(FlashFloodGuid12Hr.class.getSimpleName(),
new FlashFloodGuid12Hr());
ncParamsMap.put(FlashFloodGuid24Hr.class.getSimpleName(),
new FlashFloodGuid24Hr());
ncParamsMap.put(FlightRulesID.class.getSimpleName(),
new FlightRulesID());
ncParamsMap.put(FlightLevel.class.getSimpleName(),
new FlightLevel());
ncParamsMap.put(FosbergFireWxIndex.class.getSimpleName(),
new FosbergFireWxIndex());
ncParamsMap.put(FZRainWatchThresh.class.getSimpleName(),
new FZRainWatchThresh());
// ncParamsMap.put(
// GenericDimensionlessParameter.class.getSimpleName(), new
// GenericDimensionlessParameter() );
// ncParamsMap.put( GustBarb.class.getSimpleName(), new GustBarb()
// );
ncParamsMap.put(HailSize.class.getSimpleName(), new HailSize());
ncParamsMap.put(HeatIndex.class.getSimpleName(), new HeatIndex());
ncParamsMap.put(HeightAboveSeaLevel.class.getSimpleName(), new HeightAboveSeaLevel());
ncParamsMap.put(InstrumentWaveHeight.class.getSimpleName(), new InstrumentWaveHeight());
ncParamsMap.put(PredomSwellWaveHeight.class.getSimpleName(), new PredomSwellWaveHeight());
ncParamsMap.put(SecondarySwellWaveHeight.class.getSimpleName(), new SecondarySwellWaveHeight());
ncParamsMap.put(HeightAboveSeaLevel.class.getSimpleName(),
new HeightAboveSeaLevel());
ncParamsMap.put(InstrumentWaveHeight.class.getSimpleName(),
new InstrumentWaveHeight());
ncParamsMap.put(PredomSwellWaveHeight.class.getSimpleName(),
new PredomSwellWaveHeight());
ncParamsMap.put(SecondarySwellWaveHeight.class.getSimpleName(),
new SecondarySwellWaveHeight());
ncParamsMap.put(WaveHeight.class.getSimpleName(), new WaveHeight());
ncParamsMap.put(WindWaveHeight.class.getSimpleName(), new WindWaveHeight());
ncParamsMap.put(Highest1MinMeanWindSpeedInPastHour.class.getSimpleName(), new Highest1MinMeanWindSpeedInPastHour());
ncParamsMap.put(HighResWaveHeight.class.getSimpleName(), new HighResWaveHeight());
ncParamsMap.put(HumitureIndex.class.getSimpleName(), new HumitureIndex());
ncParamsMap.put(WindWaveHeight.class.getSimpleName(),
new WindWaveHeight());
ncParamsMap.put(
Highest1MinMeanWindSpeedInPastHour.class.getSimpleName(),
new Highest1MinMeanWindSpeedInPastHour());
ncParamsMap.put(HighResWaveHeight.class.getSimpleName(),
new HighResWaveHeight());
ncParamsMap.put(HumitureIndex.class.getSimpleName(),
new HumitureIndex());
ncParamsMap.put(IceCode.class.getSimpleName(), new IceCode());
ncParamsMap.put(IceType.class.getSimpleName(), new IceType());
ncParamsMap.put(IcingIntensitySymbol.class.getSimpleName(), new IcingIntensitySymbol());
ncParamsMap.put(IcingTypeSymbol.class.getSimpleName(), new IcingTypeSymbol());
ncParamsMap.put(InterWindDir.class.getSimpleName(), new InterWindDir());
ncParamsMap.put(InterWindSpeed.class.getSimpleName(), new InterWindSpeed());
ncParamsMap.put(InterWindTime.class.getSimpleName(), new InterWindTime());
ncParamsMap.put(IcingIntensitySymbol.class.getSimpleName(),
new IcingIntensitySymbol());
ncParamsMap.put(IcingTypeSymbol.class.getSimpleName(),
new IcingTypeSymbol());
ncParamsMap.put(InterWindDir.class.getSimpleName(),
new InterWindDir());
ncParamsMap.put(InterWindSpeed.class.getSimpleName(),
new InterWindSpeed());
ncParamsMap.put(InterWindTime.class.getSimpleName(),
new InterWindTime());
ncParamsMap.put(LandSea.class.getSimpleName(), new LandSea());
ncParamsMap.put(LatentHeatOfVapor.class.getSimpleName(), new LatentHeatOfVapor());
ncParamsMap.put(LCLParcelPressure.class.getSimpleName(), new LCLParcelPressure());
ncParamsMap.put(LCLParcelTemperature.class.getSimpleName(), new LCLParcelTemperature());
ncParamsMap.put(LiftedIndex.class.getSimpleName(), new LiftedIndex());
ncParamsMap.put(LiftedSurfaceAirTempAt500mb.class.getSimpleName(), new LiftedSurfaceAirTempAt500mb());
ncParamsMap.put(Lowest01MinAvgPressInPastHour.class.getSimpleName(), new Lowest01MinAvgPressInPastHour());
ncParamsMap.put(Max24HrTemp.class.getSimpleName(), new Max24HrTemp());
ncParamsMap.put(LatentHeatOfVapor.class.getSimpleName(),
new LatentHeatOfVapor());
ncParamsMap.put(LCLParcelPressure.class.getSimpleName(),
new LCLParcelPressure());
ncParamsMap.put(LCLParcelTemperature.class.getSimpleName(),
new LCLParcelTemperature());
ncParamsMap.put(LiftedIndex.class.getSimpleName(),
new LiftedIndex());
ncParamsMap.put(LiftedSurfaceAirTempAt500mb.class.getSimpleName(),
new LiftedSurfaceAirTempAt500mb());
ncParamsMap.put(
Lowest01MinAvgPressInPastHour.class.getSimpleName(),
new Lowest01MinAvgPressInPastHour());
ncParamsMap.put(Max24HrTemp.class.getSimpleName(),
new Max24HrTemp());
ncParamsMap.put(Max6HrTemp.class.getSimpleName(), new Max6HrTemp());
ncParamsMap.put(MaxDailyWeatherMapTemp.class.getSimpleName(), new MaxDailyWeatherMapTemp());
ncParamsMap.put(MaxDailyWeatherMapTemp.class.getSimpleName(),
new MaxDailyWeatherMapTemp());
ncParamsMap.put(MaxDayTemp.class.getSimpleName(), new MaxDayTemp());
ncParamsMap.put(MaxEditedTemp.class.getSimpleName(), new MaxEditedTemp());
ncParamsMap.put(MaxCloudCover.class.getSimpleName(), new MaxCloudCover());
ncParamsMap.put(MaxPrecipPR6X.class.getSimpleName(), new MaxPrecipPR6X()); //remove??
ncParamsMap.put(MaxMidnightTemp.class.getSimpleName(), new MaxMidnightTemp());
ncParamsMap.put(MaxOrMinTemp.class.getSimpleName(), new MaxOrMinTemp());
ncParamsMap.put(Max12HrPrecipFcst.class.getSimpleName(), new Max12HrPrecipFcst());
ncParamsMap.put(MaxWindSpeed.class.getSimpleName(), new MaxWindSpeed());
ncParamsMap.put(MeanSeaLevelPres.class.getSimpleName(), new MeanSeaLevelPres());
ncParamsMap.put(Min24HrTemp.class.getSimpleName(), new Min24HrTemp());
ncParamsMap.put(MaxEditedTemp.class.getSimpleName(),
new MaxEditedTemp());
ncParamsMap.put(MaxCloudCover.class.getSimpleName(),
new MaxCloudCover());
ncParamsMap.put(MaxPrecipPR6X.class.getSimpleName(),
new MaxPrecipPR6X()); // remove??
ncParamsMap.put(MaxMidnightTemp.class.getSimpleName(),
new MaxMidnightTemp());
ncParamsMap.put(MaxOrMinTemp.class.getSimpleName(),
new MaxOrMinTemp());
ncParamsMap.put(Max12HrPrecipFcst.class.getSimpleName(),
new Max12HrPrecipFcst());
ncParamsMap.put(MaxWindSpeed.class.getSimpleName(),
new MaxWindSpeed());
ncParamsMap.put(MeanSeaLevelPres.class.getSimpleName(),
new MeanSeaLevelPres());
ncParamsMap.put(Min24HrTemp.class.getSimpleName(),
new Min24HrTemp());
ncParamsMap.put(Min6HrTemp.class.getSimpleName(), new Min6HrTemp());
ncParamsMap.put(MinDailyWeatherMapTemp.class.getSimpleName(), new MinDailyWeatherMapTemp());
ncParamsMap.put(MinNightTemp.class.getSimpleName(), new MinNightTemp());
ncParamsMap.put(MixingRatio.class.getSimpleName(), new MixingRatio());
ncParamsMap.put(MoistHydrostaticHeight.class.getSimpleName(), new MoistHydrostaticHeight());
ncParamsMap.put(MontgomeryStreamFnct.class.getSimpleName(), new MontgomeryStreamFnct());
ncParamsMap.put(MountainObscThreshMetIndicator.class.getSimpleName(), new MountainObscThreshMetIndicator());
ncParamsMap.put(MountainObscThresh.class.getSimpleName(), new MountainObscThresh());
ncParamsMap.put(NightTempAnomaly.class.getSimpleName(), new NightTempAnomaly());
ncParamsMap.put(NewSnowAmount.class.getSimpleName(), new NewSnowAmount());
ncParamsMap.put(NightTempFcst.class.getSimpleName(), new NightTempFcst());
ncParamsMap.put(NumInterWinds.class.getSimpleName(), new NumInterWinds());
ncParamsMap.put(AirParcelTemp.class.getSimpleName(), new AirParcelTemp());
ncParamsMap.put(MinDailyWeatherMapTemp.class.getSimpleName(),
new MinDailyWeatherMapTemp());
ncParamsMap.put(MinNightTemp.class.getSimpleName(),
new MinNightTemp());
ncParamsMap.put(MixingRatio.class.getSimpleName(),
new MixingRatio());
ncParamsMap.put(MoistHydrostaticHeight.class.getSimpleName(),
new MoistHydrostaticHeight());
ncParamsMap.put(MontgomeryStreamFnct.class.getSimpleName(),
new MontgomeryStreamFnct());
ncParamsMap.put(
MountainObscThreshMetIndicator.class.getSimpleName(),
new MountainObscThreshMetIndicator());
ncParamsMap.put(MountainObscThresh.class.getSimpleName(),
new MountainObscThresh());
ncParamsMap.put(NightTempAnomaly.class.getSimpleName(),
new NightTempAnomaly());
ncParamsMap.put(NewSnowAmount.class.getSimpleName(),
new NewSnowAmount());
ncParamsMap.put(NightTempFcst.class.getSimpleName(),
new NightTempFcst());
ncParamsMap.put(NumInterWinds.class.getSimpleName(),
new NumInterWinds());
ncParamsMap.put(AirParcelTemp.class.getSimpleName(),
new AirParcelTemp());
ncParamsMap.put(Omega.class.getSimpleName(), new Omega());
ncParamsMap.put(PeakWindDir.class.getSimpleName(), new PeakWindDir());
ncParamsMap.put(PeakWindSpeed.class.getSimpleName(), new PeakWindSpeed());
ncParamsMap.put(PeakWindSpeedTime.class.getSimpleName(), new PeakWindSpeedTime());
ncParamsMap.put(InstrumentWavePeriod.class.getSimpleName(), new InstrumentWavePeriod());
ncParamsMap.put(PredomSwellWavePeriod.class.getSimpleName(), new PredomSwellWavePeriod());
ncParamsMap.put(SecondarySwellWavePeriod.class.getSimpleName(), new SecondarySwellWavePeriod());
ncParamsMap.put(PeakWindDir.class.getSimpleName(),
new PeakWindDir());
ncParamsMap.put(PeakWindSpeed.class.getSimpleName(),
new PeakWindSpeed());
ncParamsMap.put(PeakWindSpeedTime.class.getSimpleName(),
new PeakWindSpeedTime());
ncParamsMap.put(InstrumentWavePeriod.class.getSimpleName(),
new InstrumentWavePeriod());
ncParamsMap.put(PredomSwellWavePeriod.class.getSimpleName(),
new PredomSwellWavePeriod());
ncParamsMap.put(SecondarySwellWavePeriod.class.getSimpleName(),
new SecondarySwellWavePeriod());
ncParamsMap.put(WavePeriod.class.getSimpleName(), new WavePeriod());
ncParamsMap.put(WindWavePeriod.class.getSimpleName(), new WindWavePeriod());
ncParamsMap.put(PerpendicularWindComp.class.getSimpleName(), new PerpendicularWindComp());
ncParamsMap.put(PotentialTemp.class.getSimpleName(), new PotentialTemp());
ncParamsMap.put(PotentialTempAt10Meters.class.getSimpleName(), new PotentialTempAt10Meters());
ncParamsMap.put(PlatformTrueDirection.class.getSimpleName(), new PlatformTrueDirection());
ncParamsMap.put(PlatformTrueSpeed.class.getSimpleName(), new PlatformTrueSpeed());
ncParamsMap.put(PotentialTempLapseRate.class.getSimpleName(), new PotentialTempLapseRate());
ncParamsMap.put(PrecipitableWaterForEntireSounding.class.getSimpleName(), new PrecipitableWaterForEntireSounding());
ncParamsMap.put(PrecipitableWaterUptoSpecifiedLevel.class.getSimpleName(), new PrecipitableWaterUptoSpecifiedLevel());
ncParamsMap.put(Precipitation.class.getSimpleName(), new Precipitation());
ncParamsMap.put(WindWavePeriod.class.getSimpleName(),
new WindWavePeriod());
ncParamsMap.put(PerpendicularWindComp.class.getSimpleName(),
new PerpendicularWindComp());
ncParamsMap.put(PotentialTemp.class.getSimpleName(),
new PotentialTemp());
ncParamsMap.put(PotentialTempAt10Meters.class.getSimpleName(),
new PotentialTempAt10Meters());
ncParamsMap.put(PlatformTrueDirection.class.getSimpleName(),
new PlatformTrueDirection());
ncParamsMap.put(PlatformTrueSpeed.class.getSimpleName(),
new PlatformTrueSpeed());
ncParamsMap.put(PotentialTempLapseRate.class.getSimpleName(),
new PotentialTempLapseRate());
ncParamsMap.put(
PrecipitableWaterForEntireSounding.class.getSimpleName(),
new PrecipitableWaterForEntireSounding());
ncParamsMap.put(
PrecipitableWaterUptoSpecifiedLevel.class.getSimpleName(),
new PrecipitableWaterUptoSpecifiedLevel());
ncParamsMap.put(Precipitation.class.getSimpleName(),
new Precipitation());
ncParamsMap.put(Precip01Hr.class.getSimpleName(), new Precip01Hr());
ncParamsMap.put(Precip03Hr.class.getSimpleName(), new Precip03Hr());
ncParamsMap.put(Precip06Hr.class.getSimpleName(), new Precip06Hr());
// ncParamsMap.put( PrecipitationIn09Hours.class.getSimpleName(), new PrecipitationIn09Hours() );
// ncParamsMap.put( PrecipitationIn09Hours.class.getSimpleName(),
// new PrecipitationIn09Hours() );
ncParamsMap.put(Precip12Hr.class.getSimpleName(), new Precip12Hr());
ncParamsMap.put(Precip18Hr.class.getSimpleName(), new Precip18Hr());
ncParamsMap.put(Precip24Hr.class.getSimpleName(), new Precip24Hr());
ncParamsMap.put(PresentWeather.class.getSimpleName(), new PresentWeather());
ncParamsMap.put(PressureLevel.class.getSimpleName(), new PressureLevel());
ncParamsMap.put(PressChange3Hr.class.getSimpleName(), new PressChange3Hr());
ncParamsMap.put(PresentWeather.class.getSimpleName(),
new PresentWeather());
ncParamsMap.put(PressureLevel.class.getSimpleName(),
new PressureLevel());
ncParamsMap.put(PressChange3Hr.class.getSimpleName(),
new PressChange3Hr());
// TTR 923
ncParamsMap.put(PressChange3HrAbsVal.class.getSimpleName(), new PressChange3HrAbsVal());
ncParamsMap.put(PressureChange3HrAndTendency.class.getSimpleName(), new PressureChange3HrAndTendency());
ncParamsMap.put(PressChange3HrAbsVal.class.getSimpleName(),
new PressChange3HrAbsVal());
ncParamsMap.put(PressureChange3HrAndTendency.class.getSimpleName(),
new PressureChange3HrAndTendency());
ncParamsMap.put(PressChange24Hr.class.getSimpleName(), new PressChange24Hr());
ncParamsMap.put(PressureTendencySymbol.class.getSimpleName(), new PressureTendencySymbol());
ncParamsMap.put(POPFcst06Hrs.class.getSimpleName(), new POPFcst06Hrs());
ncParamsMap.put(POPFcst12Hrs.class.getSimpleName(), new POPFcst12Hrs());
ncParamsMap.put(POPFcst24Hrs.class.getSimpleName(), new POPFcst24Hrs());
ncParamsMap.put(POPAnomalyIn12hrs.class.getSimpleName(), new POPAnomalyIn12hrs());
ncParamsMap.put(POPAnomalyIn12hrs.class.getSimpleName(), new POPAnomalyIn12hrs());
ncParamsMap.put(PressChange24Hr.class.getSimpleName(),
new PressChange24Hr());
ncParamsMap.put(PressureTendencySymbol.class.getSimpleName(),
new PressureTendencySymbol());
ncParamsMap.put(POPFcst06Hrs.class.getSimpleName(),
new POPFcst06Hrs());
ncParamsMap.put(POPFcst12Hrs.class.getSimpleName(),
new POPFcst12Hrs());
ncParamsMap.put(POPFcst24Hrs.class.getSimpleName(),
new POPFcst24Hrs());
ncParamsMap.put(POPAnomalyIn12hrs.class.getSimpleName(),
new POPAnomalyIn12hrs());
ncParamsMap.put(POPAnomalyIn12hrs.class.getSimpleName(),
new POPAnomalyIn12hrs());
ncParamsMap.put(POP01Hr.class.getSimpleName(), new POP01Hr());
ncParamsMap.put(POP03Hrs.class.getSimpleName(), new POP03Hrs());
ncParamsMap.put(POP06Hrs.class.getSimpleName(), new POP06Hrs());
ncParamsMap.put(POP12Hrs.class.getSimpleName(), new POP12Hrs());
ncParamsMap.put(POP24Hrs.class.getSimpleName(), new POP24Hrs());
ncParamsMap.put(POPAnomalyIn24hrs.class.getSimpleName(), new POPAnomalyIn24hrs());
ncParamsMap.put(QuantPrecipFcstBestCat06Hr.class.getSimpleName(), new QuantPrecipFcstBestCat06Hr());
ncParamsMap.put(QuantPrecipFcstBestCat12Hr.class.getSimpleName(), new QuantPrecipFcstBestCat12Hr());
ncParamsMap.put(QuantPrecipFcstBestCat24Hr.class.getSimpleName(), new QuantPrecipFcstBestCat24Hr());
ncParamsMap.put(RateOfIceAccretionOnVesselInSaltWater.class.getSimpleName(), new RateOfIceAccretionOnVesselInSaltWater());
ncParamsMap.put(RelativeHumidity.class.getSimpleName(), new RelativeHumidity());
ncParamsMap.put(RelFreqPrecip24HrsClim.class.getSimpleName(), new RelFreqPrecip24HrsClim());
ncParamsMap.put(RichardsonNumber.class.getSimpleName(), new RichardsonNumber());
ncParamsMap.put(SatEquivPotentialTemp.class.getSimpleName(), new SatEquivPotentialTemp());
ncParamsMap.put(SatMixingRatio.class.getSimpleName(), new SatMixingRatio());
ncParamsMap.put(SatVaporPressure.class.getSimpleName(), new SatVaporPressure());
ncParamsMap.put(SeaIceDriftDist.class.getSimpleName(), new SeaIceDriftDist());
ncParamsMap.put(SeaLevelPressure.class.getSimpleName(), new SeaLevelPressure());
ncParamsMap.put(SeaSurfaceTemp.class.getSimpleName(), new SeaSurfaceTemp());
ncParamsMap.put(ShowalterIndex.class.getSimpleName(), new ShowalterIndex());
ncParamsMap.put(SkinTemperature.class.getSimpleName(), new SkinTemperature());
ncParamsMap.put(SkyCoverage.class.getSimpleName(), new SkyCoverage());
ncParamsMap.put(SnowDepth.class.getSimpleName(), new SnowDepth());
ncParamsMap.put(SnowIcePelletWatchThresh.class.getSimpleName(), new SnowIcePelletWatchThresh());
ncParamsMap.put(SpeedOf05SecPeakWind.class.getSimpleName(), new SpeedOf05SecPeakWind());
ncParamsMap.put(SpecificHumidity.class.getSimpleName(), new SpecificHumidity());
ncParamsMap.put(SpecificHumidityAt02Meters.class.getSimpleName(), new SpecificHumidityAt02Meters());
ncParamsMap.put(SpecificHumidityAt10Meters.class.getSimpleName(), new SpecificHumidityAt10Meters());
ncParamsMap.put(StabilityWithRespectToPressure.class.getSimpleName(), new StabilityWithRespectToPressure());
ncParamsMap.put(StationElevation.class.getSimpleName(), new StationElevation());
ncParamsMap.put(StationID.class.getSimpleName(), new StationID());
ncParamsMap.put(StationLatitude.class.getSimpleName(), new StationLatitude());
ncParamsMap.put(StationLongitude.class.getSimpleName(), new StationLongitude());
ncParamsMap.put(StationName.class.getSimpleName(), new StationName());
ncParamsMap.put(SurfacePressure.class.getSimpleName(), new SurfacePressure());
ncParamsMap.put(StormMotionSpeed.class.getSimpleName(), new StormMotionSpeed());
ncParamsMap.put(StormMotionDirection.class.getSimpleName(), new StormMotionDirection());
// ncParamsMap.put( SumOfFour6HrPrecipitation.class.getSimpleName(), new SumOfFour6HrPrecipitation() );
ncParamsMap.put(SunshineDuration.class.getSimpleName(), new SunshineDuration());
ncParamsMap.put(SurfaceEquivPotentialTemp.class.getSimpleName(), new SurfaceEquivPotentialTemp());
ncParamsMap.put(SurfaceMixingRatio.class.getSimpleName(), new SurfaceMixingRatio());
ncParamsMap.put(SurfacePotentialTemp.class.getSimpleName(), new SurfacePotentialTemp());
ncParamsMap.put(SurfacePressure.class.getSimpleName(), new SurfacePressure());
ncParamsMap.put(SurfaceSatEquivPotentialTemp.class.getSimpleName(), new SurfaceSatEquivPotentialTemp());
ncParamsMap.put(SurfaceSatMixingRatio.class.getSimpleName(), new SurfaceSatMixingRatio());
ncParamsMap.put(AirTemperature.class.getSimpleName(), new AirTemperature());
ncParamsMap.put(TempLapseRate.class.getSimpleName(), new TempLapseRate());
ncParamsMap.put(ProbableCeiling.class.getSimpleName(), new ProbableCeiling());
ncParamsMap.put(ProbableCeilingAsMeanSeaLevel.class.getSimpleName(), new ProbableCeilingAsMeanSeaLevel());
ncParamsMap.put(ProbableFlightRuleIdentifier.class.getSimpleName(), new ProbableFlightRuleIdentifier());
ncParamsMap.put(ProbableMountainObscThreshMetIndicator.class.getSimpleName(), new ProbableMountainObscThreshMetIndicator());
ncParamsMap.put(ProbableVisibility.class.getSimpleName(), new ProbableVisibility());
ncParamsMap.put(ProbableWindDirection.class.getSimpleName(), new ProbableWindDirection());
ncParamsMap.put(ProbableWindGust.class.getSimpleName(), new ProbableWindGust());
ncParamsMap.put(ProbableWindSpeed.class.getSimpleName(), new ProbableWindSpeed());
// ncParamsMap.put( ThunderstormOccurring2hr.class.getSimpleName(), new ThunderstormOccurring2hr() );
// ncParamsMap.put( ThunderstormOccurring6hr.class.getSimpleName(), new ThunderstormOccurring6hr() );
// ncParamsMap.put( ThunderstormOccurring12hr.class.getSimpleName(), new ThunderstormOccurring12hr() );
// ncParamsMap.put( ThunderstormOccurring24hr.class.getSimpleName(), new ThunderstormOccurring24hr() );
ncParamsMap.put(ShipIceThickness.class.getSimpleName(), new ShipIceThickness());
ncParamsMap.put(StationNumber.class.getSimpleName(), new StationNumber());
ncParamsMap.put(TopOfIcing.class.getSimpleName(), new TopOfIcing());
ncParamsMap.put(TopOfTurbulence.class.getSimpleName(), new TopOfTurbulence());
ncParamsMap.put(TopOfWeather.class.getSimpleName(), new TopOfWeather());
ncParamsMap.put(TotalSkyCoverFcst12hr.class.getSimpleName(), new TotalSkyCoverFcst12hr());
ncParamsMap.put(TotalPrecip.class.getSimpleName(), new TotalPrecip());
ncParamsMap.put(TotalSkyCoverFcst12hr.class.getSimpleName(), new TotalSkyCoverFcst12hr());
ncParamsMap.put(TurbulenceFrequencySymbol.class.getSimpleName(), new TurbulenceFrequencySymbol());
ncParamsMap.put(TurbulenceIntensitySymbol.class.getSimpleName(), new TurbulenceIntensitySymbol());
ncParamsMap.put(TurbulenceTypeSymbol.class.getSimpleName(), new TurbulenceTypeSymbol());
ncParamsMap.put(TurbulentKineticEnergy.class.getSimpleName(), new TurbulentKineticEnergy());
ncParamsMap.put(EstStormDirectionUComp.class.getSimpleName(), new EstStormDirectionUComp());
ncParamsMap.put(UCompAt10Meters.class.getSimpleName(), new UCompAt10Meters());
ncParamsMap.put(UncondProbOf06HrSevereWeather.class.getSimpleName(), new UncondProbOf06HrSevereWeather());
ncParamsMap.put(UncondProbOf12HrSevereWeather.class.getSimpleName(), new UncondProbOf12HrSevereWeather());
ncParamsMap.put(UncondProbOf24HrSevereWeather.class.getSimpleName(), new UncondProbOf24HrSevereWeather());
ncParamsMap.put(POPAnomalyIn24hrs.class.getSimpleName(),
new POPAnomalyIn24hrs());
ncParamsMap.put(QuantPrecipFcstBestCat06Hr.class.getSimpleName(),
new QuantPrecipFcstBestCat06Hr());
ncParamsMap.put(QuantPrecipFcstBestCat12Hr.class.getSimpleName(),
new QuantPrecipFcstBestCat12Hr());
ncParamsMap.put(QuantPrecipFcstBestCat24Hr.class.getSimpleName(),
new QuantPrecipFcstBestCat24Hr());
ncParamsMap
.put(RateOfIceAccretionOnVesselInSaltWater.class
.getSimpleName(),
new RateOfIceAccretionOnVesselInSaltWater());
ncParamsMap.put(RelativeHumidity.class.getSimpleName(),
new RelativeHumidity());
ncParamsMap.put(RelFreqPrecip24HrsClim.class.getSimpleName(),
new RelFreqPrecip24HrsClim());
ncParamsMap.put(RichardsonNumber.class.getSimpleName(),
new RichardsonNumber());
ncParamsMap.put(SatEquivPotentialTemp.class.getSimpleName(),
new SatEquivPotentialTemp());
ncParamsMap.put(SatMixingRatio.class.getSimpleName(),
new SatMixingRatio());
ncParamsMap.put(SatVaporPressure.class.getSimpleName(),
new SatVaporPressure());
ncParamsMap.put(SeaIceDriftDist.class.getSimpleName(),
new SeaIceDriftDist());
ncParamsMap.put(SeaLevelPressure.class.getSimpleName(),
new SeaLevelPressure());
ncParamsMap.put(SeaSurfaceTemp.class.getSimpleName(),
new SeaSurfaceTemp());
ncParamsMap.put(ShowalterIndex.class.getSimpleName(),
new ShowalterIndex());
ncParamsMap.put(UncondProbOfTstorms2hr.class.getSimpleName(), new UncondProbOfTstorms2hr());
ncParamsMap.put(UncondProbOfTstorms6hr.class.getSimpleName(), new UncondProbOfTstorms6hr());
ncParamsMap.put(UncondProbOfTstorms12hr.class.getSimpleName(), new UncondProbOfTstorms12hr());
ncParamsMap.put(UncondProbOfTstorms24hr.class.getSimpleName(), new UncondProbOfTstorms24hr());
ncParamsMap.put(VCompAt10Meters.class.getSimpleName(), new VCompAt10Meters());
ncParamsMap.put(WindDirectionUComp.class.getSimpleName(), new WindDirectionUComp());
ncParamsMap.put(VaporPressure.class.getSimpleName(), new VaporPressure());
ncParamsMap.put(EstStormDirectionVComp.class.getSimpleName(), new EstStormDirectionVComp());
ncParamsMap.put(IsentropesVerticalSeparation.class.getSimpleName(), new IsentropesVerticalSeparation());
ncParamsMap.put(VerticalVelocity.class.getSimpleName(), new VerticalVelocity());
ncParamsMap.put(VirtualPotentialTemp.class.getSimpleName(), new VirtualPotentialTemp());
ncParamsMap.put(VirtualTemp.class.getSimpleName(), new VirtualTemp());
// Redmine 4318
ncParamsMap.put(SignificantWaveHeight.class.getSimpleName(),
new SignificantWaveHeight());
ncParamsMap.put(SkinTemperature.class.getSimpleName(),
new SkinTemperature());
ncParamsMap.put(SkyCoverage.class.getSimpleName(),
new SkyCoverage());
ncParamsMap.put(SnowDepth.class.getSimpleName(), new SnowDepth());
ncParamsMap.put(SnowIcePelletWatchThresh.class.getSimpleName(),
new SnowIcePelletWatchThresh());
ncParamsMap.put(SpeedOf05SecPeakWind.class.getSimpleName(),
new SpeedOf05SecPeakWind());
ncParamsMap.put(SpecificHumidity.class.getSimpleName(),
new SpecificHumidity());
ncParamsMap.put(SpecificHumidityAt02Meters.class.getSimpleName(),
new SpecificHumidityAt02Meters());
ncParamsMap.put(SpecificHumidityAt10Meters.class.getSimpleName(),
new SpecificHumidityAt10Meters());
ncParamsMap.put(
StabilityWithRespectToPressure.class.getSimpleName(),
new StabilityWithRespectToPressure());
ncParamsMap.put(StationElevation.class.getSimpleName(),
new StationElevation());
ncParamsMap.put(StationID.class.getSimpleName(), new StationID());
ncParamsMap.put(StationLatitude.class.getSimpleName(),
new StationLatitude());
ncParamsMap.put(StationLongitude.class.getSimpleName(),
new StationLongitude());
ncParamsMap.put(StationName.class.getSimpleName(),
new StationName());
ncParamsMap.put(SurfacePressure.class.getSimpleName(),
new SurfacePressure());
ncParamsMap.put(StormMotionSpeed.class.getSimpleName(),
new StormMotionSpeed());
ncParamsMap.put(StormMotionDirection.class.getSimpleName(),
new StormMotionDirection());
// ncParamsMap.put( SumOfFour6HrPrecipitation.class.getSimpleName(),
// new SumOfFour6HrPrecipitation() );
ncParamsMap.put(SunshineDuration.class.getSimpleName(),
new SunshineDuration());
ncParamsMap.put(SurfaceEquivPotentialTemp.class.getSimpleName(),
new SurfaceEquivPotentialTemp());
ncParamsMap.put(SurfaceMixingRatio.class.getSimpleName(),
new SurfaceMixingRatio());
ncParamsMap.put(SurfacePotentialTemp.class.getSimpleName(),
new SurfacePotentialTemp());
ncParamsMap.put(SurfacePressure.class.getSimpleName(),
new SurfacePressure());
ncParamsMap.put(SurfaceSatEquivPotentialTemp.class.getSimpleName(),
new SurfaceSatEquivPotentialTemp());
ncParamsMap.put(SurfaceSatMixingRatio.class.getSimpleName(),
new SurfaceSatMixingRatio());
ncParamsMap.put(AirTemperature.class.getSimpleName(),
new AirTemperature());
ncParamsMap.put(TempLapseRate.class.getSimpleName(),
new TempLapseRate());
ncParamsMap.put(ProbableCeiling.class.getSimpleName(),
new ProbableCeiling());
ncParamsMap.put(
ProbableCeilingAsMeanSeaLevel.class.getSimpleName(),
new ProbableCeilingAsMeanSeaLevel());
ncParamsMap.put(ProbableFlightRuleIdentifier.class.getSimpleName(),
new ProbableFlightRuleIdentifier());
ncParamsMap.put(ProbableMountainObscThreshMetIndicator.class
.getSimpleName(),
new ProbableMountainObscThreshMetIndicator());
ncParamsMap.put(ProbableVisibility.class.getSimpleName(),
new ProbableVisibility());
ncParamsMap.put(ProbableWindDirection.class.getSimpleName(),
new ProbableWindDirection());
ncParamsMap.put(ProbableWindGust.class.getSimpleName(),
new ProbableWindGust());
ncParamsMap.put(ProbableWindSpeed.class.getSimpleName(),
new ProbableWindSpeed());
// ncParamsMap.put( ThunderstormOccurring2hr.class.getSimpleName(),
// new ThunderstormOccurring2hr() );
// ncParamsMap.put( ThunderstormOccurring6hr.class.getSimpleName(),
// new ThunderstormOccurring6hr() );
// ncParamsMap.put( ThunderstormOccurring12hr.class.getSimpleName(),
// new ThunderstormOccurring12hr() );
// ncParamsMap.put( ThunderstormOccurring24hr.class.getSimpleName(),
// new ThunderstormOccurring24hr() );
ncParamsMap.put(ShipIceThickness.class.getSimpleName(),
new ShipIceThickness());
ncParamsMap.put(StationNumber.class.getSimpleName(),
new StationNumber());
ncParamsMap.put(TopOfIcing.class.getSimpleName(), new TopOfIcing());
ncParamsMap.put(TopOfTurbulence.class.getSimpleName(),
new TopOfTurbulence());
ncParamsMap.put(TopOfWeather.class.getSimpleName(),
new TopOfWeather());
ncParamsMap.put(TotalSkyCoverFcst12hr.class.getSimpleName(),
new TotalSkyCoverFcst12hr());
ncParamsMap.put(TotalPrecip.class.getSimpleName(),
new TotalPrecip());
ncParamsMap.put(TotalSkyCoverFcst12hr.class.getSimpleName(),
new TotalSkyCoverFcst12hr());
ncParamsMap.put(TurbulenceFrequencySymbol.class.getSimpleName(),
new TurbulenceFrequencySymbol());
ncParamsMap.put(TurbulenceIntensitySymbol.class.getSimpleName(),
new TurbulenceIntensitySymbol());
ncParamsMap.put(TurbulenceTypeSymbol.class.getSimpleName(),
new TurbulenceTypeSymbol());
ncParamsMap.put(TurbulentKineticEnergy.class.getSimpleName(),
new TurbulentKineticEnergy());
ncParamsMap.put(EstStormDirectionUComp.class.getSimpleName(),
new EstStormDirectionUComp());
ncParamsMap.put(UCompAt10Meters.class.getSimpleName(),
new UCompAt10Meters());
ncParamsMap.put(
UncondProbOf06HrSevereWeather.class.getSimpleName(),
new UncondProbOf06HrSevereWeather());
ncParamsMap.put(
UncondProbOf12HrSevereWeather.class.getSimpleName(),
new UncondProbOf12HrSevereWeather());
ncParamsMap.put(
UncondProbOf24HrSevereWeather.class.getSimpleName(),
new UncondProbOf24HrSevereWeather());
ncParamsMap.put(UncondProbOfTstorms2hr.class.getSimpleName(),
new UncondProbOfTstorms2hr());
ncParamsMap.put(UncondProbOfTstorms6hr.class.getSimpleName(),
new UncondProbOfTstorms6hr());
ncParamsMap.put(UncondProbOfTstorms12hr.class.getSimpleName(),
new UncondProbOfTstorms12hr());
ncParamsMap.put(UncondProbOfTstorms24hr.class.getSimpleName(),
new UncondProbOfTstorms24hr());
ncParamsMap.put(VCompAt10Meters.class.getSimpleName(),
new VCompAt10Meters());
ncParamsMap.put(WindDirectionUComp.class.getSimpleName(),
new WindDirectionUComp());
ncParamsMap.put(VaporPressure.class.getSimpleName(),
new VaporPressure());
ncParamsMap.put(EstStormDirectionVComp.class.getSimpleName(),
new EstStormDirectionVComp());
ncParamsMap.put(IsentropesVerticalSeparation.class.getSimpleName(),
new IsentropesVerticalSeparation());
ncParamsMap.put(VerticalVelocity.class.getSimpleName(),
new VerticalVelocity());
ncParamsMap.put(VirtualPotentialTemp.class.getSimpleName(),
new VirtualPotentialTemp());
ncParamsMap.put(VirtualTemp.class.getSimpleName(),
new VirtualTemp());
ncParamsMap.put(Visibility.class.getSimpleName(), new Visibility());
ncParamsMap.put(WindDirectionVComp.class.getSimpleName(), new WindDirectionVComp());
ncParamsMap.put(WaterEquivOfNewSnow.class.getSimpleName(), new WaterEquivOfNewSnow());
ncParamsMap.put(WaveSteepness.class.getSimpleName(), new WaveSteepness());
ncParamsMap.put(WetBulbPotentialTemp.class.getSimpleName(), new WetBulbPotentialTemp());
ncParamsMap.put(WetBulbTemp.class.getSimpleName(), new WetBulbTemp());
// ncParamsMap.put( WindBarb.class.getSimpleName(), new WindBarb() );
ncParamsMap.put(WindChillEquivalentTemp.class.getSimpleName(), new WindChillEquivalentTemp());
ncParamsMap.put(WindChillTemperature.class.getSimpleName(), new WindChillTemperature());
ncParamsMap.put(WindSpeedComp.class.getSimpleName(), new WindSpeedComp());
ncParamsMap.put(WindCompDirection.class.getSimpleName(), new WindCompDirection());
ncParamsMap.put(WindDirection.class.getSimpleName(), new WindDirection());
ncParamsMap.put(WindDirectionVComp.class.getSimpleName(),
new WindDirectionVComp());
ncParamsMap.put(WaterEquivOfNewSnow.class.getSimpleName(),
new WaterEquivOfNewSnow());
ncParamsMap.put(WaveSteepness.class.getSimpleName(),
new WaveSteepness());
ncParamsMap.put(WetBulbPotentialTemp.class.getSimpleName(),
new WetBulbPotentialTemp());
ncParamsMap.put(WetBulbTemp.class.getSimpleName(),
new WetBulbTemp());
// ncParamsMap.put( WindBarb.class.getSimpleName(), new WindBarb()
// );
ncParamsMap.put(WindChillEquivalentTemp.class.getSimpleName(),
new WindChillEquivalentTemp());
ncParamsMap.put(WindChillTemperature.class.getSimpleName(),
new WindChillTemperature());
ncParamsMap.put(WindSpeedComp.class.getSimpleName(),
new WindSpeedComp());
ncParamsMap.put(WindCompDirection.class.getSimpleName(),
new WindCompDirection());
ncParamsMap.put(WindDirection.class.getSimpleName(),
new WindDirection());
ncParamsMap.put(WindGust.class.getSimpleName(), new WindGust());
ncParamsMap.put(WindSpeed.class.getSimpleName(), new WindSpeed());
ncParamsMap.put(CeilingFromSeaLevelWorstCase.class.getSimpleName(), new CeilingFromSeaLevelWorstCase());
ncParamsMap.put(FlightRulesIdWorstCase.class.getSimpleName(), new FlightRulesIdWorstCase());
ncParamsMap.put(MountainObscThreshMetIndicatorWorstCase.class.getSimpleName(), new MountainObscThreshMetIndicatorWorstCase());
ncParamsMap.put(Probability.class.getSimpleName(), new Probability());
ncParamsMap.put(ProbableSkyCoverage.class.getSimpleName(), new ProbableSkyCoverage());
ncParamsMap.put(ReportTimeInHourMins.class.getSimpleName(), new ReportTimeInHourMins());
ncParamsMap.put(ProbablePresentWeather.class.getSimpleName(), new ProbablePresentWeather());
ncParamsMap.put(LowLevelWindShear.class.getSimpleName(), new LowLevelWindShear());
ncParamsMap.put(CeilingFromSeaLevelWorstCase.class.getSimpleName(),
new CeilingFromSeaLevelWorstCase());
ncParamsMap.put(FlightRulesIdWorstCase.class.getSimpleName(),
new FlightRulesIdWorstCase());
ncParamsMap.put(MountainObscThreshMetIndicatorWorstCase.class
.getSimpleName(),
new MountainObscThreshMetIndicatorWorstCase());
ncParamsMap.put(Probability.class.getSimpleName(),
new Probability());
ncParamsMap.put(ProbableSkyCoverage.class.getSimpleName(),
new ProbableSkyCoverage());
ncParamsMap.put(ReportTimeInHourMins.class.getSimpleName(),
new ReportTimeInHourMins());
ncParamsMap.put(ProbablePresentWeather.class.getSimpleName(),
new ProbablePresentWeather());
ncParamsMap.put(LowLevelWindShear.class.getSimpleName(),
new LowLevelWindShear());
ncParamsMap.put(WxPresent.class.getSimpleName(), new WxPresent());
} catch (Exception e) {
e.printStackTrace();
@ -369,16 +638,19 @@ public class MetParameterFactory implements ISerializableObject {
AbstractMetParameter ncParam = ncParamsMap.get(ncParamName);
try {
AbstractMetParameter newParam = (AbstractMetParameter) ncParam.getClass().getConstructor().newInstance();
AbstractMetParameter newParam = (AbstractMetParameter) ncParam
.getClass().getConstructor().newInstance();
return newParam;
} catch (Exception e) {
System.out.println("error getting newInstance for metParam " + ncParam.getClass().getSimpleName());
System.out.println("error getting newInstance for metParam "
+ ncParam.getClass().getSimpleName());
}
return null;
}
// u is the expected units and must be compatible with the units for the implemented
// u is the expected units and must be compatible with the units for the
// implemented
// Quantity.
public AbstractMetParameter createParameter(String prmName, String unitName) {
Unit<?> units;
@ -387,7 +659,8 @@ public class MetParameterFactory implements ISerializableObject {
units = Unit.ONE;
} else {
try {
units = UnitFormat.getUCUMInstance().parseProductUnit(unitName, new ParsePosition(0));
units = UnitFormat.getUCUMInstance().parseProductUnit(unitName,
new ParsePosition(0));
} catch (ParseException e) {
System.out.println("unable to determine units for " + unitName);
return null;
@ -399,7 +672,7 @@ public class MetParameterFactory implements ISerializableObject {
// create a parameter value with MISSING value.
// name may be an alias, or the name of the parameter
//
//
public AbstractMetParameter createParameter(String prmName, Unit<?> u) {
AbstractMetParameter newParam = createParameter(prmName);
newParam.setUnitPair(u);
@ -412,7 +685,8 @@ public class MetParameterFactory implements ISerializableObject {
return newParam;
}
public AbstractMetParameter createParameter(String prmName, Unit<?> u, DataTime dt) {
public AbstractMetParameter createParameter(String prmName, Unit<?> u,
DataTime dt) {
AbstractMetParameter newParam = createParameter(prmName);
newParam.setValidTime(dt);
newParam.setUnitPair(u);
@ -421,9 +695,12 @@ public class MetParameterFactory implements ISerializableObject {
public boolean alias(String prmName, String alias) {
if (ncParamsAliasMap.containsKey(alias) && !ncParamsAliasMap.get(alias).equals(prmName)) {
System.out.println("Error aliasing ncParam " + prmName + " : " + alias + " is already aliased to " + ncParamsAliasMap.get(alias));
// return false;
if (ncParamsAliasMap.containsKey(alias)
&& !ncParamsAliasMap.get(alias).equals(prmName)) {
System.out.println("Error aliasing ncParam " + prmName + " : "
+ alias + " is already aliased to "
+ ncParamsAliasMap.get(alias));
// return false;
}
ncParamsAliasMap.put(alias, prmName);

View file

@ -21,7 +21,8 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@DynamicSerialize
public class PressureChange3HrAndTendency extends AbstractMetParameter implements Dimensionless, ISerializableObject {
public class PressureChange3HrAndTendency extends AbstractMetParameter
implements Dimensionless, ISerializableObject {
@DynamicSerializeElement
private static final long serialVersionUID = -6602297437762954327L;
@ -32,7 +33,9 @@ public class PressureChange3HrAndTendency extends AbstractMetParameter implement
}
@DeriveMethod
public PressureChange3HrAndTendency derive(PressChange3HrAbsVal p, PressureTendencySymbol ptsy) throws InvalidValueException, NullPointerException {
public PressureChange3HrAndTendency derive(PressChange3HrAbsVal p,
PressureTendencySymbol ptsy) throws InvalidValueException,
NullPointerException {
if (p.hasValidValue() && ptsy.hasValidValue()) {
Number n = (Number) new Integer(ptsy.getStringValue());

View file

@ -0,0 +1,59 @@
package gov.noaa.nws.ncep.edex.common.metparameters;
import gov.noaa.nws.ncep.edex.common.metparameters.MetParameterFactory.DeriveMethod;
import gov.noaa.nws.ncep.edex.common.metparameters.parameterconversion.PRLibrary;
import gov.noaa.nws.ncep.edex.common.metparameters.parameterconversion.PRLibrary.InvalidValueException;
import javax.measure.quantity.Dimensionless;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import com.raytheon.uf.common.serialization.ISerializableObject;
import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
/**
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Sep 26, 2014 Redmine 4318 srussell Initial creation
*
* </pre>
*
* @author srussell
* @version 1.0
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
@DynamicSerialize
public class SignificantWaveHeight extends AbstractMetParameter implements
Dimensionless, ISerializableObject {
@DynamicSerializeElement
private static final long serialVersionUID = 1L;
public SignificantWaveHeight() {
super(UNIT);
}
@DeriveMethod
public SignificantWaveHeight derive(WindWaveHeight w,
PredomSwellWaveHeight p) throws InvalidValueException,
NullPointerException {
if (w.hasValidValue() && p.hasValidValue()) {
Amount swh = PRLibrary.prSGHT(w, p);
this.setValue(swh);
} else {
this.setValueToMissing();
}
return this;
}
}

View file

@ -56,10 +56,11 @@ import com.raytheon.uf.edex.decodertools.core.IDecoderConstants;
* 1. if AwwParser.processWMO failed, simply
* drop the record by throwing an exception
* 2. comment out the end check "if(record == null")
* because it is a dead code.
* because it is a dead code. [DS- removed 8/14]
* Aug 08, 2013 1028 G. Hull rm underscores from reportType and set mndTime in URI
* Aug 30, 2013 2298 rjpeter Make getPluginName abstract
* Mar 21, 2103 1112 S. Russell *.WCN files, get the watch number
* Aug 13, 2014 (none?) D. Sushon refactor to be sure all bulletins get decoded, removed some dead code, marked possibly dead code as such
* </pre>
*
* This code has been developed by the SIB for use in the AWIPS2 system.
@ -79,7 +80,10 @@ public class AwwDecoder extends AbstractDecoder {
public AwwDecoder() throws DecoderException {
}
public PluginDataObject[] decode(byte[] data, Headers headers) throws DecoderException {
public PluginDataObject[] decode(byte[] data, Headers headers)
throws DecoderException {
List<PluginDataObject> outPdo = new ArrayList<PluginDataObject>();
String traceId = "";
if (headers != null) {
@ -108,202 +112,235 @@ public class AwwDecoder extends AbstractDecoder {
messageData = sep.next();
String theMessage = new String(messageData);
/* May have multiple duplicate bulletins, only get the first bulletin
* and eliminate the remaining bulletins after the first bulletin. */
Scanner cc = new Scanner(theMessage).useDelimiter(etx);
if (cc.hasNext()) {
theBulletin = cc.next();
} else {
// System.out.println("setting.... theBulletin = theMessage;");
theBulletin = theMessage;
}
// Set MND (Mass News Disseminator) time string and convert it into
// Calendar object
MndTime mt = new MndTime(theBulletin.getBytes());
mndTime = mt.getMndTime();
do {
// Decode and set WMO line
AwwRecord record = AwwParser.processWMO(theBulletin, mndTime);
if (record == null) {
throw new AwwDecoderException("Error on decoding Aww Record");
}
// Set MND (Mass News Disseminator) time string and convert it into
// Calendar object
MndTime mt = new MndTime(theBulletin.getBytes());
mndTime = mt.getMndTime();
boolean isWtchFlag = AwwDecoder.isWtch(record);// Ticket 456
// boolean isSevereWeatherStatusFlag =
// AwwDecoder.isSevereWeatherStatus(record);
// Get report type
String reportType = AwwParser.getReportType(theBulletin);
ArrayList<String> segmentList = new ArrayList<String>();
segmentList.clear();
// Break the bulletin message into segments by a "$$"
Scanner sc = new Scanner(theBulletin).useDelimiter(segmentDelim);
boolean isWCN = false;
String wcnLbl = AwwRecord.AwwReportType.WATCH_COUNTY_NOTIFICATION.name();
wcnLbl = wcnLbl.replace("_", " ");
if (reportType.equals(wcnLbl)) {
isWCN = true;
}
while (sc.hasNext()) {
String segment = sc.next();
Matcher ugcMatcher = ugcPattern.matcher(segment);
// discard if the segment did not have an UGC line.
if (ugcMatcher.find() || isWtchFlag) { // ????? not sure if this
// logic is correct
segmentList.add(segment);
// Decode and set WMO line
AwwRecord record = AwwParser.processWMO(theBulletin, mndTime);
if (record == null) {
throw new AwwDecoderException("Error on decoding Aww Record");
}
}
if (record != null) {
try {
// process each segment in a order of UGC, VTEC, H-VTEC, FIPS,
// LATLON...
for (String segment : segmentList) {
Matcher ugcMatcher = ugcPattern.matcher(segment);
AwwUgc ugc = null;
boolean isWtchFlag = AwwDecoder.isWtch(record);// Ticket 456
// TRAC 1112
if (isWCN) {
String watchNumber = AwwParser.retrieveWatchNumberFromWCN(segment);
if (watchNumber != null) {
record.setWatchNumber(watchNumber);
if (ugcMatcher.find()) {
ugc = AwwParser.processUgc(ugcMatcher.group(), segment, mndTime, watchesList);
// boolean isSevereWeatherStatusFlag =
// AwwDecoder.isSevereWeatherStatus(record); //dead code?
// Get report type
String reportType = AwwParser.getReportType(theBulletin);
ArrayList<String> segmentList = new ArrayList<String>();
segmentList.clear();
// Break the bulletin message into segments by a "$$"
Scanner sc = new Scanner(theBulletin).useDelimiter(segmentDelim);
boolean isWCN = false;
String wcnLbl = AwwRecord.AwwReportType.WATCH_COUNTY_NOTIFICATION
.name();
wcnLbl = wcnLbl.replace("_", " ");
if (reportType.equals(wcnLbl)) {
isWCN = true;
}
while (sc.hasNext()) {
String segment = sc.next();
Matcher ugcMatcher = ugcPattern.matcher(segment);
// discard if the segment did not have an UGC line.
if (ugcMatcher.find() || isWtchFlag) { // ????? not sure if this
// logic is correct
segmentList.add(segment);
}
}
if (record != null) {
try {
// process each segment in a order of UGC, VTEC, H-VTEC,
// FIPS, LATLON...
for (String segment : segmentList) {
Matcher ugcMatcher = ugcPattern.matcher(segment);
AwwUgc ugc = null;
// TRAC 1112
if (isWCN) {
String watchNumber = AwwParser
.retrieveWatchNumberFromWCN(segment);
if (watchNumber != null) {
record.setWatchNumber(watchNumber);
if (ugcMatcher.find()) {
ugc = AwwParser.processUgc(
ugcMatcher.group(), segment,
mndTime, watchesList);
}
}
}
}
// local forecast
else if (isWtchFlag) {
ugc = AwwParser.processUgcForWtch(AwwParser.WTCH_BOX_UGC_LINE, segment, mndTime, record.getIssueOffice(), watchesList);
// else if(isSevereWeatherStatusFlag)
// ugc =
// AwwParser.processUgcForSereveWeatherStatus(ugcMatcher.group(),
// segment, mndTime, record.getIssueOffice(),
// watchesList);
String watchNumber = AwwParser.processUgcToRetrieveWatchNumberForThunderstormOrTornado(segment);
record.setWatchNumber(watchNumber);
// } else if(isSevereWeatherStatusFlag) {
// String watchNumber =
// AwwParser.processUgcToRetrieveWatchNumberForStatusReport(segment);
// record.setWatchNumber(watchNumber);
} else if (ugcMatcher.find()) {
ugc = AwwParser.processUgc(ugcMatcher.group(), segment, mndTime, watchesList);
}
if (ugc != null) {
record.addAwwUGC(ugc);
/* Collect watch numbers which are the event tracking
* numbers in VTEC lines as one of primary keys in AWW
* record to prevent not writing raw data to DB note: 1.
* each bulletin may have multiple segments 2. each
* segment has one UGC line but may have multiple VTEC
* lines and have more than one watch number */
/* not quite sure the following logic is correct to
* retrieve and then store the watch number. thus
* comment it out now. M. Gao */
// if (watchesList.size() > 0) {
// String collectWatches = null;
// for (int idxWatch = 0; idxWatch < watchesList.size();
// idxWatch++) {
//
// if (idxWatch == 0) {
// collectWatches = watchesList.get(idxWatch);
// } else {
// collectWatches = collectWatches.concat("/")
// .concat(watchesList.get(idxWatch));
// }
// }
// // System.out.println("==collection length=" +
// // collectWatches.length() );
// record.setWatchNumber(collectWatches);
// } else {
//
// // The special reports may not have VTEC line; given
// // a default watch number "0000".
// record.setWatchNumber("0000");
// }
/* construct VTEC object and then add it to the current
* Ugc for SevereWeatherStatus aww reocrd */
if (AwwParser.isSegmentTextValid(segment)) {
/* parse and then set the Watch Number for Status
* Report */
String watchNumber = AwwParser.processUgcToRetrieveWatchNumberForStatusReport(segment);
// local forecast
else if (isWtchFlag) {
ugc = AwwParser.processUgcForWtch(
AwwParser.WTCH_BOX_UGC_LINE, segment,
mndTime, record.getIssueOffice(),
watchesList);
// else if(isSevereWeatherStatusFlag) ---dead code?
// ugc =
// AwwParser.processUgcForSereveWeatherStatus(ugcMatcher.group(),
// segment, mndTime, record.getIssueOffice(),
// watchesList);
String watchNumber = AwwParser
.processUgcToRetrieveWatchNumberForThunderstormOrTornado(segment);
record.setWatchNumber(watchNumber);
AwwVtec awwVtec = AwwParser.processVtectForSevereWeatherStatus(theBulletin, record.getIssueTime(), record.getIssueOffice());
Set<AwwVtec> awwVtecSet = new HashSet<AwwVtec>();
awwVtecSet.add(awwVtec);
ugc.setAwwVtecLine(awwVtecSet);
/* now calculate status latlon info and then add to
* ugc */
List<AwwLatlons> pointAwwLatLonsList = AwwLatLonUtil.getAwwLatLonsListBySereveWeatherStatusPointLine(awwVtec.getVtecLine());
for (AwwLatlons eachAwwLatlons : pointAwwLatLonsList) {
ugc.addAwwLatLon(eachAwwLatlons);
}
// } else if(isSevereWeatherStatusFlag) { dead code?
// String watchNumber =
// AwwParser.processUgcToRetrieveWatchNumberForStatusReport(segment);
// record.setWatchNumber(watchNumber);
} else if (ugcMatcher.find()) {
ugc = AwwParser.processUgc(ugcMatcher.group(),
segment, mndTime, watchesList);
}
if (ugc != null) {
record.addAwwUGC(ugc);
/*
* Collect watch numbers which are the event
* tracking numbers in VTEC lines as one of primary
* keys in AWW record to prevent not writing raw
* data to DB note: 1. each bulletin may have
* multiple segments 2. each segment has one UGC
* line but may have multiple VTEC lines and have
* more than one watch number
*/
/*
* not quite sure the following logic is correct to
* retrieve and then store the watch number. thus
* comment it out now. M. Gao
*/
// if (watchesList.size() > 0) {
// String collectWatches = null;
// for (int idxWatch = 0; idxWatch <
// watchesList.size();
// idxWatch++) {
//
// if (idxWatch == 0) {
// collectWatches = watchesList.get(idxWatch);
// } else {
// collectWatches = collectWatches.concat("/")
// .concat(watchesList.get(idxWatch));
// }
// }
// // System.out.println("==collection length=" +
// // collectWatches.length() );
// record.setWatchNumber(collectWatches);
// } else {
//
// // The special reports may not have VTEC line;
// // given a default watch number "0000".
// record.setWatchNumber("0000");
// }
/*
* construct VTEC object and then add it to the
* current Ugc for SevereWeatherStatus aww reocrd
*/
if (AwwParser.isSegmentTextValid(segment)) {
/*
* parse and then set the Watch Number for
* Status Report
*/
String watchNumber = AwwParser
.processUgcToRetrieveWatchNumberForStatusReport(segment);
record.setWatchNumber(watchNumber);
AwwVtec awwVtec = AwwParser
.processVtectForSevereWeatherStatus(
theBulletin,
record.getIssueTime(),
record.getIssueOffice());
Set<AwwVtec> awwVtecSet = new HashSet<AwwVtec>();
awwVtecSet.add(awwVtec);
ugc.setAwwVtecLine(awwVtecSet);
/*
* now calculate status latlon info and then add
* to ugc
*/
List<AwwLatlons> pointAwwLatLonsList = AwwLatLonUtil
.getAwwLatLonsListBySereveWeatherStatusPointLine(awwVtec
.getVtecLine());
for (AwwLatlons eachAwwLatlons : pointAwwLatLonsList) {
ugc.addAwwLatLon(eachAwwLatlons);
}
}
}
}
} catch (Exception e) {
logger.error("Error processing decoded segment", e);
record = null;
}
}
if (record != null) {
// T976 - check if the record has a valid UGC. If not return an
// empty PluginDataObject array
if ((record.getAwwUGC() == null)
|| (record.getAwwUGC().size() == 0)) {
return new PluginDataObject[0];
}
} catch (Exception e) {
logger.error("Error processing decoded segment", e);
record = null;
}
}
/* Check the AWW record object. If not, throws exception. */
if (record != null) {
// T976 - check if the record has a valid UGC. If not return an
// empty PluginDataObject array
if ((record.getAwwUGC() == null) || (record.getAwwUGC().size() == 0)) {
return new PluginDataObject[0];
}
record.setReportType(reportType.trim());
record.setTraceId(traceId);
// Set MND remark before the URI is constructed
if ((mt.getMndTimeString() == null)
|| mt.getMndTimeString().trim().isEmpty()) {
record.setMndTime("unknown");
} else {
record.setMndTime(mt.getMndTimeString());
}
record.setReportType(reportType.trim());
record.setTraceId(traceId);
// Set MND remark before the URI is constructed
if ((mt.getMndTimeString() == null) || mt.getMndTimeString().trim().isEmpty()) {
record.setMndTime("unknown");
try {
record.constructDataURI();
} catch (PluginException e) {
throw new DecoderException(this.getClass()
.getCanonicalName()
+ ":Error constructing dataURI:", e);
}
} else {
record.setMndTime(mt.getMndTimeString());
throw new DecoderException(this.getClass().getCanonicalName()
+ ":Error Aww Record object is NULL");
}
try {
record.constructDataURI();
} catch (PluginException e) {
throw new DecoderException("Error constructing dataURI", e);
// Decode and set attention line
record.setAttentionWFO(AwwParser.processATTN(theBulletin));
// Replace special characters to a blank so that it may be readable.
if (theBulletin.length() < 40000) {
record.setBullMessage(UtilN
.removeLeadingWhiteSpaces(theBulletin
.replace('\r', ' ').replace('\003', ' ')
.replace('\000', ' ').replace('\001', ' ')
.replace('\036', ' ')));
}
} else {
throw new DecoderException("Error Aww Reocrd object is NULL");
}
// Decode and set attention line
record.setAttentionWFO(AwwParser.processATTN(theBulletin));
// Replace special characters to a blank so that it may be readable.
if (theBulletin.length() < 40000) {
record.setBullMessage(UtilN
.removeLeadingWhiteSpaces(theBulletin.replace('\r', ' ').replace('\003', ' ').replace('\000', ' ').replace('\001', ' ').replace('\036', ' ')));
}
// Return the AwwRecord record object.
// if (record == null) {
// return new PluginDataObject[0];
// } else {
// return new PluginDataObject[] {record};
// }
/* The reason the above is commented out is the check to see if record
* == null is a dead code. It will never get executed according the
* logic before the if statement. */
return new PluginDataObject[] { record };
outPdo.add(record);
if (cc.hasNext()) {
theBulletin = cc.next();
}
} while (cc.hasNext());
return outPdo.toArray(new PluginDataObject[] {});
}
/**

View file

@ -19,6 +19,8 @@
* 01/26/2011 N/A M. Gao Refactor:
* change the WMO regular expression more flexible.
* 08/01/2013 1028 G. Hull sanity check on AwwReportType.
* 9/15/2014 4637 J. Huber Changed parser for WCN's to read VTEC lines to parse out the watch
* number instead of the WATCH NOTIFICATION string.
*
* </pre>
*
@ -53,6 +55,7 @@ import com.raytheon.uf.common.time.util.TimeUtil;
import com.raytheon.uf.edex.database.DataAccessLayerException;
public class AwwParser {
private final static String VTEC_EXP = "(/([A-Z]{1}).([A-Z]{3}).([A-Z]{4}).([A-Z]{2}).([A-Z]{1}).([0-9]{4}).([0-9]{6}T[0-9]{4})Z-([0-9]{6}T[0-9]{4})Z/\\x0d\\x0d\\x0a)+";
private static Logger logger = Logger.getLogger(AwwParser.class
.getCanonicalName());
@ -315,19 +318,18 @@ public class AwwParser {
}
/* TRAC 1112 Extract the watch number from a *.WCN file segment */
/*
* RM 4697 Use VTEC Line to extract watch number instead of WATCH COUNTY
* NOTIFCATION text string
*/
public static String retrieveWatchNumberFromWCN(String segment) {
String watchNmbr = null;
int watchNmbrLength = 4;
int lengthDiff = 0;
String s = "WATCH COUNTY NOTIFICATION FOR WATCH\\s+(\\d+)\\s+";
Pattern p = Pattern.compile(s);
Pattern p = Pattern.compile(VTEC_EXP);
Matcher m = p.matcher(segment);
if (m.find()) {
watchNmbr = m.group(1);
watchNmbr = (watchNmbr != null) ? watchNmbr.trim() : watchNmbr;
watchNmbr = m.group(7);
watchNmbr = watchNmbr.replaceAll("^0+", "");
}
return watchNmbr;
}
@ -392,9 +394,6 @@ public class AwwParser {
String trackingNumber;
int[] latlonIndex = new int[1];
// Regular expression for VTEC line
final String VTEC_EXP = "(/([A-Z]{1}).([A-Z]{3}).([A-Z]{4}).([A-Z]{2}).([A-Z]{1}).([0-9]{4}).([0-9]{6}T[0-9]{4})Z-([0-9]{6}T[0-9]{4})Z/\\x0d\\x0d\\x0a)+";
// Pattern used to extract VTEC line
final Pattern vtecPattern = Pattern.compile(VTEC_EXP);
@ -629,9 +628,6 @@ public class AwwParser {
String trackingNumber;
int[] latlonIndex = new int[1];
// Regular expression for VTEC line
final String VTEC_EXP = "(/([A-Z]{1}).([A-Z]{3}).([A-Z]{4}).([A-Z]{2}).([A-Z]{1}).([0-9]{4}).([0-9]{6}T[0-9]{4})Z-([0-9]{6}T[0-9]{4})Z/\\x0d\\x0d\\x0a)+";
// final String WTCH_VTEC_EXP =
// "WW\\s\\d{3}\\sTORNADO\\s([A-Z]{2}\\s)+CW\\s(\\d{6}Z)\\s\\-\\s(\\d{6}Z)";
final String WTCH_VTEC_EXP = "WW\\s(\\d{1,4})\\s(TORNADO|SEVERE TSTM)\\s((\\w+|\\s+)*)\\s(\\d{6}Z)\\s\\-\\s(\\d{6}Z)";
// Pattern used to extract VTEC line

View file

@ -61,4 +61,28 @@
value="gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveSingleK1minRequest" />
<constructor-arg ref="RetrieveSingleK1minHandler" />
</bean>
<bean id="RetrieveStationStateRequestHandler"
class="gov.noaa.nws.ncep.edex.plugin.geomag.handler.RetrieveStationStateRequestHandler" />
<bean factory-bean="handlerRegistry" factory-method="register">
<constructor-arg
value="gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveStationStateRequest" />
<constructor-arg ref="RetrieveStationStateRequestHandler" />
</bean>
<bean id="ChangeStationStateRequestHandler"
class="gov.noaa.nws.ncep.edex.plugin.geomag.handler.ChangeStationStateRequestHandler" />
<bean factory-bean="handlerRegistry" factory-method="register">
<constructor-arg
value="gov.noaa.nws.ncep.common.dataplugin.geomag.request.ChangeStationStateRequest" />
<constructor-arg ref="ChangeStationStateRequestHandler" />
</bean>
<bean id="RetrieveGeoMagDataRequestHandler"
class="gov.noaa.nws.ncep.edex.plugin.geomag.handler.RetrieveGeoMagDataRequestHandler" />
<bean factory-bean="handlerRegistry" factory-method="register">
<constructor-arg
value="gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveGeoMagDataRequest" />
<constructor-arg ref="RetrieveGeoMagDataRequestHandler" />
</bean>
</beans>

View file

@ -12,6 +12,7 @@ import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagAvgDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagK1minDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagK3hrDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagK3hrStateDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.DatabaseUtil;
import java.io.FileNotFoundException;
@ -44,6 +45,8 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory;
* 06/07/2013 #989 qzhou Initial Creation, event driven
* 03/18/2014 #1123 qzhou Move some functions to common. Modified FillAvgTimeGap in the moved functions
* 06/26/2014 #1136 qzhou Calculate hourly average when min>=55 instead of min=59
* 07/16/2014 R4078 sgurung Modified method calcK3hr() to add states when a k3hr record is inserted
*
* </pre>
*
* @author qzhou
@ -465,7 +468,7 @@ public class TrigKCalculation {
// int h = d.getHours();
// int m = d.getMinutes();
// if (h == 10 && m == 41) { // && day == 14
// System.out.println("**dataURI " + dataURI);
// System.out.println("***********dataURI " + dataURI);
// teststr = dataURI;
// }
// } catch (ParseException e1) {
@ -531,11 +534,12 @@ public class TrigKCalculation {
float[] qdaQdc = CalcEach1min.getQHAQDC(dQdc);
// test hQdc
// if (!teststr.equals("")) {
// System.out.println("\n**qhaQdc length " + teststr);
// System.out.println("\n**qhaQdctest2 length "
// + qhaQdc.length);
// for (int i = 0; i < qhaQdc.length; i++)
// System.out.print((float) qhaQdc[i] + " ");
// System.out
// .println("\n**qdaQdc length " + qdaQdc.length);
// System.out.println("\n**qdaQdctest2 length "
// + qdaQdc.length);
// for (int i = 0; i < qdaQdc.length; i++)
// System.out.print((float) qdaQdc[i] + " ");
// teststr = "";
@ -908,6 +912,11 @@ public class TrigKCalculation {
GeoMagK3hrDao k3hrDao = new GeoMagK3hrDao();
k3hrDao.persist(recK3hr);
if (recK3hr.getId() != null) {
GeoMagK3hrStateDao k3hrStateDao = new GeoMagK3hrStateDao();
k3hrStateDao.updateStates(recK3hr.getId(), stationCode, epTime);
}
}
else {
@ -980,6 +989,11 @@ public class TrigKCalculation {
GeoMagK3hrDao k3hrDao = new GeoMagK3hrDao();
k3hrDao.persist(recK3hr);
if (recK3hr.getId() != null) {
GeoMagK3hrStateDao k3hrStateDao = new GeoMagK3hrStateDao();
k3hrStateDao.updateStates(recK3hr.getId(), stationCode, epTime);
}
}
}

View file

@ -0,0 +1,116 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.edex.plugin.geomag.handler;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK3hrState;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagStationStateChange;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagK3hrStateDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagStateDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagStationStateChangeDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.ChangeStationStateRequest;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
/**
*
* Handler for ChangeStationStateRequest.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 07/01/2014 R4078 sgurung Initial Creation
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
public class ChangeStationStateRequestHandler implements
IRequestHandler<ChangeStationStateRequest> {
private static Logger logger = Logger
.getLogger(ChangeStationStateRequestHandler.class.toString());
private GeoMagK3hrStateDao dao;
@Override
public Object handleRequest(ChangeStationStateRequest request)
throws Exception {
Boolean rval = Boolean.TRUE;
logger.info("ChangeStationStateRequest for " + request.getStationCode());
try {
dao = new GeoMagK3hrStateDao();
GeoMagStateDao stateDao = new GeoMagStateDao();
GeoMagStationStateChangeDao stateChangeDao = new GeoMagStationStateChangeDao();
Integer stateId = stateDao.getStateByProcessingState("Active")
.getStateId();
Integer k3hrId = dao.getStationK3hrStateId(
request.getStationCode(), request.getSynopticTime(), null);
logger.info("Inside ChangeStationStateRequest for "
+ request.getStationCode() + " stateId = " + stateId
+ " k3hrId = " + k3hrId);
// Check if station is active for the Kp calculation
// If so, delete the record from the station_indices_states table
// if not, add the record for this period
List<String> processingStates = dao.getKpStationStates(
request.getStationCode(), request.getSynopticTime());
if (processingStates != null) {
if (processingStates.contains("Active")) {
int numRowsDel = dao.delete(stateId, k3hrId);
if (numRowsDel > 0) {
// add record to table geomag_state_changes
GeoMagStationStateChange stateChange = new GeoMagStationStateChange();
stateChange.setStationCode(request.getStationCode());
stateChange
.setIssuedAction("Deactivated from Algorithm");
stateChange.setInsertTime(new Date());
stateChangeDao.persist(stateChange);
}
} else {
// add record to table geomag_k3hr_state
GeoMagK3hrState k3hrState = new GeoMagK3hrState();
k3hrState.setK3hrId(k3hrId);
k3hrState.setStateId(stateId);
dao.persist(k3hrState);
// add record to table geomag_station_state_changes
GeoMagStationStateChange stateChange = new GeoMagStationStateChange();
stateChange.setStationCode(request.getStationCode());
stateChange.setIssuedAction("Activated in Algorithm");
stateChange.setInsertTime(new Date());
stateChangeDao.persist(stateChange);
}
}
} catch (Exception e) {
rval = Boolean.FALSE;
logger.warning("Error while changing station state for "
+ request.getStationCode() + " Exception = "
+ e.getMessage() + " \n" + e.getStackTrace());
}
return rval;
}
}

View file

@ -0,0 +1,67 @@
package gov.noaa.nws.ncep.edex.plugin.geomag.handler;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveGeoMagDataRequest;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveGeoMagDataRequest.RetrieveGeoMagDataRequestType;
import java.util.logging.Logger;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
/**
*
* Handler for RetrieveGeoMagDataRequest.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 07/31/2014 R4078 sgurung Initial creation.
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
public class RetrieveGeoMagDataRequestHandler implements
IRequestHandler<RetrieveGeoMagDataRequest> {
private static Logger logger = Logger
.getLogger(RetrieveGeoMagDataRequestHandler.class.toString());
private GeoMagDao dao;
@Override
public Object handleRequest(RetrieveGeoMagDataRequest request)
throws Exception {
logger.info("RetrieveGeoMagDataRequest for " + request.getStationCode());
try {
dao = new GeoMagDao("geomag"); // PluginFactory.getInstance().getPluginDao(GeoMag);
if (RetrieveGeoMagDataRequestType.DATA_LIST.equals(request
.getRequestType())) {
return dao.getGeoMagRecords(request.getStationCode(),
request.getStartTime(), request.getEndTime(),
request.getSourceId());
} else if (RetrieveGeoMagDataRequestType.COUNT.equals(request
.getRequestType())) {
return dao.getGeoMagRecordsCount(request.getStationCode(),
request.getStartTime(), request.getEndTime(),
request.getSourceId());
}
} catch (Exception e) {
logger.warning("Error during RetrieveGeoMagDataRequestHandler request "
+ request.getStationCode()
+ ". Error: "
+ e.getMessage()
+ "\n" + e.getStackTrace());
}
return null;
}
}

View file

@ -1,12 +1,14 @@
package gov.noaa.nws.ncep.edex.plugin.geomag.handler;
import gov.noaa.nws.ncep.common.dataplugin.geomag.GeoMagK1min;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagK1minDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveK1minRequest;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveK1minRequest.RetrieveK1minRequestType;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
/**
@ -21,6 +23,8 @@ import com.raytheon.uf.common.serialization.comm.IRequestHandler;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 2014/02/12 #1110 qzhou Init
* 03/05/2014 R4078 sgurung Modified method handleRequest() to handle additional
* requests based on RetrieveK1minRequestTypes.
*
* </pre>
*
@ -37,20 +41,47 @@ public class RetrieveK1minRequestHandler implements
@Override
public Object handleRequest(RetrieveK1minRequest request) throws Exception {
List<GeoMagK1min> resultsList = null;
logger.info("RetrieveK1minRequest for " + request.getStationCode());
try {
dao = new GeoMagK1minDao();
resultsList = dao.getRangeK1min(request.getStationCode(),
request.getStartTime(), request.getEndTime());
if (RetrieveK1minRequestType.KP.equals(request.getRequestType())) {
List<Map<String, Object>> resultMaps = dao.getEstKpIndex1min(
request.getStationCodeList(), request.getStartTime(),
request.getEndTime());
DbQueryResponse response = new DbQueryResponse();
response.setResults(resultMaps);
return response;
} else if (RetrieveK1minRequestType.K.equals(request
.getRequestType())) {
return dao.getEstKIndex1min(request.getStationCodeList(),
request.getStartTime(), request.getEndTime());
} else if (RetrieveK1minRequestType.LATEST_K.equals(request
.getRequestType())) {
List<Map<String, Object>> resultMaps = dao.getLatestEstKIndex(
request.getStationCodeList(), request.getStartTime(),
request.getEndTime());
DbQueryResponse response = new DbQueryResponse();
response.setResults(resultMaps);
return response;
} else if (RetrieveK1minRequestType.LAST_DATA_DATE.equals(request
.getRequestType())) {
return dao.getLastDataDate(request.getStationCodeList(),
request.getStartTime(), request.getEndTime());
} else {
return dao.getRangeK1min(request.getStationCode(),
request.getStartTime(), request.getEndTime());
}
} catch (Exception e) {
logger.warning("Error retrieving K1min record for "
+ request.getStationCode());
}
return resultsList;
return null;
}
}

View file

@ -0,0 +1,73 @@
/**
* This code has unlimited rights, and is provided "as is" by the National Centers
* for Environmental Prediction, without warranty of any kind, either expressed or implied,
* including but not limited to the implied warranties of merchantability and/or fitness
* for a particular purpose.
*
* This code has been developed by the NCEP-SIB for use in the AWIPS2 system.
*
**/
package gov.noaa.nws.ncep.edex.plugin.geomag.handler;
import gov.noaa.nws.ncep.common.dataplugin.geomag.dao.GeoMagK3hrStateDao;
import gov.noaa.nws.ncep.common.dataplugin.geomag.request.RetrieveStationStateRequest;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
import com.raytheon.uf.common.serialization.comm.IRequestHandler;
/**
*
* Handler for RetrieveStationStateRequest.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 07/01/2014 R4078 sgurung Initial Creation
*
* </pre>
*
* @author sgurung
* @version 1.0
*/
public class RetrieveStationStateRequestHandler implements
IRequestHandler<RetrieveStationStateRequest> {
private static Logger logger = Logger
.getLogger(RetrieveStationStateRequestHandler.class.toString());
private GeoMagK3hrStateDao dao;
@Override
public Object handleRequest(RetrieveStationStateRequest request)
throws Exception {
logger.info("RetrieveStationStateRequest...");
try {
dao = new GeoMagK3hrStateDao();
if (request.getStationCodeList() != null) {
List<Map<String, Object>> resultMaps = dao.getKpStationsStates(
request.getStationCodeList(), request.getRefTime());
DbQueryResponse response = new DbQueryResponse();
response.setResults(resultMaps);
return response;
} else if (request.getStationCode() != null) {
List<String> results = dao.getKpStationStates(
request.getStationCode(), request.getRefTime());
return results;
}
} catch (Exception e) {
logger.warning("Error retrieving station state request...");
}
return null;
}
}

View file

@ -3,8 +3,9 @@
<geoMagStation>
<stationCode>BOU</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>0</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -36,8 +37,9 @@
<geoMagStation>
<stationCode>SIT</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -69,8 +71,9 @@
<geoMagStation>
<stationCode>NEW</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>0</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -102,8 +105,9 @@
<geoMagStation>
<stationCode>FRN</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>0</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -135,8 +139,9 @@
<geoMagStation>
<stationCode>FRD</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -168,8 +173,9 @@
<geoMagStation>
<stationCode>MEA</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -201,8 +207,9 @@
<geoMagStation>
<stationCode>OTT</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -234,8 +241,9 @@
<geoMagStation>
<stationCode>HAD</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -267,8 +275,9 @@
<geoMagStation>
<stationCode>CL2</stationCode>
<provider>USGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>0</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -300,14 +309,15 @@
<geoMagStation>
<stationCode>HAD</stationCode>
<provider>BGS</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<dataOrder>HDZF</dataOrder>
<location latitude="51.0" longitude="355.517"/>
<rawDataFormat>
<dataFormat conversionRequired="true">
<regex>^(\d{4})\s*(\d{3})\s(\d{2})\s*(\d{2})\s*(-?\d+\.?\d*)\s*(-?\d+\.?\d*)\s*(-?\d+\.?\d*)</regex>
<regex>^(\d{4})\s*(\d{3})\s*(\d{2})\s*(\d{2})\s*(-?\d+\.?\d*)\s*(-?\d+\.?\d*)\s*(-?\d+\.?\d*)</regex>
<group id="1" name="obsYear"/>
<group id="2" name="obsDayOfYear"/>
<group id="3" name="obsHour"/>
@ -321,8 +331,9 @@
<geoMagStation>
<stationCode>CNB</stationCode>
<provider>GA</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<dataOrder>XYZF</dataOrder>
<location latitude="-35.32" longitude="149.36"/>
@ -342,8 +353,9 @@
<geoMagStation>
<stationCode>NGK</stationCode>
<provider>GFZ</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<dataOrder>XYZF</dataOrder>
<location latitude="52.072" longitude="12.675"/>
@ -363,8 +375,9 @@
<geoMagStation>
<stationCode>WNG</stationCode>
<provider>GFZ</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<dataOrder>XYZF</dataOrder>
<location latitude="53.743" longitude="9.073"/>
@ -384,8 +397,9 @@
<geoMagStation>
<stationCode>CL2</stationCode>
<provider>IPGP</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>0</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="magworm" priority="102"/>
<source name="domsat" priority="103"/>
@ -417,8 +431,9 @@
<geoMagStation>
<stationCode>OTT</stationCode>
<provider>NRCAN</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="domsat" priority="103"/>
<dataOrder>XYZF</dataOrder>
@ -439,8 +454,9 @@
<geoMagStation>
<stationCode>MEA</stationCode>
<provider>NRCAN</provider>
<processKQDC>true</processKQDC>
<kpStation>true</kpStation>
<processKQDC>1</processKQDC>
<kpStation>1</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<source name="domsat" priority="103"/>
<dataOrder>XYZF</dataOrder>
@ -461,8 +477,9 @@
<geoMagStation>
<stationCode>JEJ</stationCode>
<provider>KOREA</provider>
<processKQDC>false</processKQDC>
<kpStation>false</kpStation>
<processKQDC>0</processKQDC>
<kpStation>0</kpStation>
<kStation>1</kStation>
<source name="direct" priority="101"/>
<dataOrder>XYZF</dataOrder>
<location latitude="33.427" longitude="126.296"/>

View file

@ -27,9 +27,11 @@ import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.geotools.referencing.operation.DefaultMathTransformFactory;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Index;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.crs.ProjectedCRS;
import org.opengis.referencing.operation.MathTransform;
@ -70,6 +72,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* PluginDataObject.
* Aug 06, 2013 2228 njensen Use deserialize(byte[])
* Jun 11, 2014 2061 bsteffen Remove IDecoderGettable
* Sep 08, 2014 sgilbert Correct CONUS image projection
*
* </pre>
*
@ -212,6 +215,16 @@ public class MosaicRecord extends PersistablePluginDataObject implements
@Transient
private Map<MosaicDataKey, MosaicDataPoint> symbologyData = new HashMap<MosaicDataKey, MosaicDataPoint>();
// public static final double GEMPAK_EARTH_RADIUS_KM = 6371.2213;
public static final double MOSAIC_EARTH_RADIUS_KM = 6380.0;
private static final int ALASKA_SOURCEID = 10051;
private static final int HAWAII_SOURCEID = 10052;
private static final DefaultMathTransformFactory dmtFactory = new DefaultMathTransformFactory();
public MosaicRecord() {
super();
this.nx = 0;
@ -518,7 +531,6 @@ public class MosaicRecord extends PersistablePluginDataObject implements
this.elevation = elevation;
}
/**
* @return the symbologyBlock
*/
@ -554,8 +566,17 @@ public class MosaicRecord extends PersistablePluginDataObject implements
}
public ProjectedCRS getCRS() {
return MapUtil.constructStereographic(MapUtil.AWIPS_EARTH_RADIUS,
MapUtil.AWIPS_EARTH_RADIUS, this.latitude, this.longitude);
if (this.getSourceId() != HAWAII_SOURCEID
&& this.getSourceId() != ALASKA_SOURCEID) {
return generateLambertConformal_2StandardParallel(
MosaicRecord.MOSAIC_EARTH_RADIUS_KM * 1000,
MosaicRecord.MOSAIC_EARTH_RADIUS_KM * 1000, 33.0, 45.0,
this.longitude, this.latitude);
} else {
return MapUtil.constructStereographic(MapUtil.AWIPS_EARTH_RADIUS,
MapUtil.AWIPS_EARTH_RADIUS, this.latitude, this.longitude);
}
}
/**
@ -764,4 +785,35 @@ public class MosaicRecord extends PersistablePluginDataObject implements
public String getPluginName() {
return "mosaic";
}
/*
* This method is temporary and will not be needed when an appropriate
* MapUtil method is available that allows different standard parallels.
*/
private ProjectedCRS generateLambertConformal_2StandardParallel(
double majorAxis, double minorAxis, double stdParallel1,
double stdParallel2, double lonOfOrigin, double latOfOrigin) {
ParameterValueGroup parameters = null;
try {
parameters = dmtFactory
.getDefaultParameters("Lambert_Conformal_Conic_2SP");
parameters.parameter("semi_major").setValue(majorAxis);
parameters.parameter("semi_minor").setValue(minorAxis);
parameters.parameter("latitude_of_origin").setValue(latOfOrigin);
parameters.parameter("standard_parallel_1").setValue(stdParallel1);
parameters.parameter("standard_parallel_2").setValue(stdParallel2);
parameters.parameter("longitude_of_origin").setValue(lonOfOrigin);
parameters.parameter("false_easting").setValue(0.0);
parameters.parameter("false_northing").setValue(0.0);
String name = "Lambert Conformal (SP: " + stdParallel1 + "/"
+ stdParallel2 + ", Origin: " + lonOfOrigin + ")";
return MapUtil.constructProjection(name, parameters);
} catch (Exception e) {
//
return null;
}
}
}

View file

@ -18,15 +18,18 @@ import org.opengis.referencing.crs.ProjectedCRS;
* A tiler class that will allow the user to take a radial container and create
* tiles at a particular zoom level.
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 09/2009 143 L. Lin Initial creation
* 12/2009 143 mgamazaychikov Made constructor and constructGridGeometry
* more suitable for raster images
* 01/2010 204 M. Li Set tileSize; correct geometry envelope
* <pre>
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 09/2009 143 L. Lin Initial creation
* 12/2009 143 mgamazaychikov Made constructor and constructGridGeometry more suitable for
* raster images
* 01/2010 204 M. Li Set tileSize; correct geometry envelope
* 09/2014 sgilbert Correct GridGeometry
* </pre>
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*
* @author L. Lin
* @version 1.0
*/
@ -36,11 +39,11 @@ public class MosaicTiler {
private int levels;
private int tileSize;
private int tileSizeX, tileSizeY;
private int fullResolution;
private int fullResolutionX, fullResolutionY;
private int actualArrayLength;
@ -51,10 +54,6 @@ public class MosaicTiler {
private MosaicRecord mosaicData;
private double maxExtentW;
private double maxExtentH;
private UnitConverter dataToImage;
public MosaicTiler(MosaicRecord data) {
@ -89,8 +88,8 @@ public class MosaicTiler {
this.levels = 1;
this.tileSizeX = data.getNy();
this.tileSizeY = data.getNx();
this.tileSize = data.getNy();
this.tileSize = data.getNy();
this.fullResolutionX = (int) (this.tileSizeX * Math.pow(2,
this.levels - 1));
this.fullResolutionY = (int) (this.tileSizeY * Math.pow(2,
@ -99,7 +98,6 @@ public class MosaicTiler {
blankImage = new byte[actualArrayLength];
Arrays.fill(blankImage, (byte) 0);
}
if (dataToImage == null) {
this.dataToImage = UnitConverter.IDENTITY;
@ -110,7 +108,6 @@ public class MosaicTiler {
this.dataToImage = dataToImage;
}
}
/**
@ -143,8 +140,8 @@ public class MosaicTiler {
}
/**
* Creates a full image of the mosaic data. The class needs to be constructed
* with the fullImage flag set to true for this to work.
* Creates a full image of the mosaic data. The class needs to be
* constructed with the fullImage flag set to true for this to work.
*
* @return A byte array of the full image
*/
@ -155,42 +152,41 @@ public class MosaicTiler {
public GridGeometry2D constructGridGeometry() {
ProjectedCRS crs = mosaicData.getCRS();
double minX, maxX, minY, maxY;
GridGeometry2D gridGeometry2D = null;
GeneralEnvelope generalEnvelope = new GeneralEnvelope(2);
generalEnvelope.setCoordinateReferenceSystem(crs);
maxExtentW = mosaicData.getResolution() * mosaicData.getNy();
maxExtentH = mosaicData.getResolution() * mosaicData.getNx();
// Assumes 0,0 point ( lat/lon of origin in CRS ) is at center of image
// and points at corner of cell
maxX = mosaicData.getResolution() * mosaicData.getNy();
maxY = mosaicData.getResolution() * mosaicData.getNx();
double halfResolution = mosaicData.getResolution() / 2.0;
maxX = (maxX / 2.0) - halfResolution;
maxY = (maxY / 2.0) - halfResolution;
minX = -maxX;
minY = -maxY;
maxX += mosaicData.getResolution();
maxY += mosaicData.getResolution();
generalEnvelope.setRange(0, minX, maxX);
generalEnvelope.setRange(1, minY, maxY);
if ("Raster".equals(mosaicData.getFormat())) {
maxExtentW /= 2;
maxExtentH /= 2;
gridGeometry2D = new GridGeometry2D(new GeneralGridEnvelope(
new int[] { 0, 0 }, new int[] { fullResolutionX,
fullResolutionY }, false), generalEnvelope);
} else if ("Radial".equals(mosaicData.getFormat())) {
gridGeometry2D = new GridGeometry2D(new GeneralGridEnvelope(
new int[] { 0, 0 }, new int[] { fullResolution,
fullResolution }, false), generalEnvelope);
}
generalEnvelope.setRange(0, -maxExtentW, maxExtentW);
generalEnvelope.setRange(1, -maxExtentH, maxExtentH);
if ("Raster".equals(mosaicData.getFormat())) {
gridGeometry2D = new GridGeometry2D(new GeneralGridEnvelope(new int[] {
0, 0 }, new int[] { fullResolutionX, fullResolutionY }, false),
generalEnvelope);
}
else if ("Radial".equals(mosaicData.getFormat())) {
gridGeometry2D = new GridGeometry2D(new GeneralGridEnvelope(new int[] {
0, 0 }, new int[] { fullResolution, fullResolution }, false),
generalEnvelope);
}
return gridGeometry2D;
}
public double getMaxExent() {
return maxExtentW;
}
/**
* Returns the actual width of the imagery. This is typically used for the
* full image.

View file

@ -2,7 +2,8 @@
*
* Ncscat Decoder
*
* This java class decodes Ascat quikscat (NESDIS File) raw data.
* This Java class decodes ocean winds scatterometer/radiometer (NESDIS File) raw data.
*
* HISTORY
*
* Date Author Description
@ -10,6 +11,7 @@
* 11/2009 Uma Josyula Initial creation
* 01/2011 B. Hebbard Handle ambiguity variants
* 07/2012 B. Hebbard Handle OSCAT / OSCAT_HI
* 10/2014 B. Hebbard Get reportType from NcscatMode, instead of if-then-else'ing over hardcode integer lengths
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*/
@ -67,7 +69,7 @@ public class NcscatDecoder extends AbstractDecoder {
NcscatProcessing sProcess = new NcscatProcessing();
sProcess.setInputFileName(plugin);
messageData = sProcess.separate(data);
recLength = NcscatProcessing.getRecordLength();
recLength = sProcess.getRecordLength();
if (messageData != null) {
record = new NcscatRecord();
@ -76,38 +78,7 @@ public class NcscatDecoder extends AbstractDecoder {
record.setEndTime(sProcess.getEndTime());
record.setRecordLength(recLength);
record.setDataTime(new DataTime(sProcess.getStartTime()));
if (record.getRecordLength() == 688) {
if (plugin.equalsIgnoreCase("oscat")) {
record.setReportType("oscat-hi");
} else {
record.setReportType("quikscat");
}
} else if (record.getRecordLength() == 1372) {
record.setReportType("quikscat-hi");
} else if (record.getRecordLength() == 382) {
if (plugin.equalsIgnoreCase("ascatx")) {
record.setReportType("Exasct");
} else {
record.setReportType("ascat");
}
} else if (record.getRecordLength() == 742) {
if (plugin.equalsIgnoreCase("ascatx")) {
record.setReportType("Exasct-hi");
} else {
record.setReportType("ascat-hi");
}
} else if (record.getRecordLength() == 328) {
record.setReportType("oscat");
} else if (record.getRecordLength() == 715) {
record.setReportType("wscat");
}
record.setReportType(sProcess.getNcscatMode().getReportType());
// If this is an (numbered) 'ambiguity' variant, add suffix to
// reportType
@ -178,20 +149,16 @@ public class NcscatDecoder extends AbstractDecoder {
}
// TODO: Review this temporary fix by BH to see if a broader
// refactor might be better.
// Problem: Without the added 'else' below, non-local variable
// "plugin" will
// retain its previous value if the pattern matcher fails above;
// this will happen
// if the file suffix/extension (after the ".") is shorter than 5
// characters.
// Scenario: A file with suffix ".ascatx" is ingested, then later a
// ".qsct" file.
// "plugin" will retain its previous value if the pattern matcher
// fails above; this will happen if the file suffix/extension (after
// the ".") is shorter than 5 characters. Scenario: A file with
// suffix ".ascatx" is ingested, then later a ".qsct" file.
// Variable "plugin" will be set to "ascatx" by the first, but will
// retain this
// same value for the second; logic in NcscatProcessing.doSeparate()
// will as a
// result interpret the big-endian ".qsct" data as little endian
// format.
// retain this same value for the second; logic in
// NcscatProcessing.doSeparate() will as a result interpret the
// big-endian ".qsct" data as little endian format.
// Alternate (better): Could make "plugin" local to this method
else {
plugin = "";
@ -200,20 +167,14 @@ public class NcscatDecoder extends AbstractDecoder {
// NcscatProcessing
// Handle ambiguity variants: In addition to files containing the
// primary
// (greatest likelihood) wind vector solutions, for some data types
// we also
// receive (typically 2 or 4) 'ambiguity' variants for the same
// point locations,
// but with (lesser likelihood) solutions. Since these cannot be
// distinguished
// from the primary files based on data format/content alone, we
// look for a
// (prearranged) telltale pattern somewhere in the file name. If
// found, we
// remember the indicated ambiguity number, for later tagging of the
// database
// record.
// primary (greatest likelihood) wind vector solutions, for some
// data types we also receive (typically 2 or 4) 'ambiguity'
// variants for the same point locations, but with (lesser
// likelihood) solutions. Since these cannot be distinguished from
// the primary files based on data format/content alone, we
// look for a (prearranged) telltale pattern somewhere in the file
// name. If found, we remember the indicated ambiguity number, for
// later tagging of the database record.
pattern = Pattern.compile("ambig([1-9])");
matcher = pattern.matcher(fileName);
if (matcher.find()) {

View file

@ -7,14 +7,18 @@
* <pre>
* Uma Josyula 11/2009 Creation
* B. Hebbard 07/2012 Handle OSCAT / OSCAT_HI
* B. Hebbard R4865/TTR984 10/2014 Tighten code that infers satellite type
* (from date/hour field recurrence) and
* date handling to prevent garbage from being
* interpreted as dates decades in the future.
* </pre>
*
* This code has been developed by the SIB for use in the AWIPS system.
*/
package gov.noaa.nws.ncep.edex.plugin.ncscat.util;
import gov.noaa.nws.ncep.common.dataplugin.ncscat.NcscatMode;
import gov.noaa.nws.ncep.common.dataplugin.ncscat.NcscatPoint;
import java.nio.ByteBuffer;
@ -24,369 +28,357 @@ import java.util.Calendar;
import java.util.List;
import java.util.NoSuchElementException;
import javax.xml.bind.JAXBException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import com.raytheon.uf.common.serialization.SerializationUtil;
public class NcscatProcessing {
private final Logger log = Logger.getLogger(getClass().getName());
private final Log theLogger = LogFactory.getLog(getClass());
private final Logger log = Logger.getLogger(getClass().getName());
private final Log theLogger = LogFactory.getLog(getClass());
private List<NcscatPoint> item;
List<Byte> newMessage=null;
NcscatPoint sPointObj ;
private Calendar endTime ;
private static int scatNumber ;
private Calendar startTime;
private static int recordLength;
private String inputFileName;
private List<NcscatPoint> item;
List<Byte> newMessage = null;
public NcscatProcessing() {
}
NcscatPoint sPointObj;
public byte[] separate(byte[] data) {
doSeparate(data);
try {
if(newMessage ==null){
return (byte[])null;
}
else {
byte[] tempBytes = listByteTobyteArray(newMessage);
return tempBytes;
}
private Calendar endTime;
} catch (NoSuchElementException e) {
return (byte[])null;
}
private int scatNumber;
}
private Calendar startTime;
private int recordLength;
/**
* @param message
* separate bulletins
*/
private void doSeparate(byte[] message) {
int ji=0;
int n = 0,doubleNcscat =0,scatXLen =0;
ByteBuffer byteBuffer = null;
byteBuffer = ByteBuffer.allocate(message.length);
byteBuffer.put(message,0,message.length);
int bitNum =0;
int tempLength=message.length;
int day,hour,min,sec;
private String inputFileName;
startTime = Calendar.getInstance();
endTime = Calendar.getInstance();
private NcscatMode ncscatMode;
// Attempt to discriminate type of data by looking for 'period' of repeating date+hour fields.
// TODO !! Guard against false negative which could occur if first 2 times straddle hour boundary,
// !! possibly by checking for match EITHER 1st-&-2nd OR 2nd-&-3rd
if ((byteBuffer.getShort(0) == byteBuffer.getShort(1484)) && (byteBuffer.getShort(2) == byteBuffer.getShort(1486))) {
// ASCAT_HI or EXASCT_HI (...which are big and little endian, respectively)
n=1476;
scatNumber=82;
recordLength=742;
}
else if((byteBuffer.getShort(0)== byteBuffer.getShort(764)) &&(byteBuffer.getShort(2)== byteBuffer.getShort(766))) {
// ASCAT or EXASCT (...which are big and little endian, respectively)
n=756;
scatNumber=42;
recordLength=382;
}
else if ((byteBuffer.getShort(0)== byteBuffer.getShort(1376)) &&(byteBuffer.getShort(2)== byteBuffer.getShort(1378))) {
// QUIKSCAT -OR- OSCAT_HI (...which are big and little endian, respectively)
n=1368;
scatNumber = 76;
recordLength =688;
}
else if ((byteBuffer.getShort(0) == byteBuffer.getShort(656)) && (byteBuffer.getShort(2) == byteBuffer.getShort(658))) {
// OSCAT
n=648;
scatNumber = 36;
recordLength = 328;
}
else if ((byteBuffer.getShort(0) == byteBuffer.getShort(2744)) && (byteBuffer.getShort(2) == byteBuffer.getShort(2746))) {
// QUIKSCAT_HI
n=2736;
recordLength = 1372;
scatNumber = 152;
}
else if((byteBuffer.getShort(56)== byteBuffer.getShort(1486)) &&(byteBuffer.getShort(58)== byteBuffer.getShort(1488))){
// WSAT
n=1422;
scatNumber=79;
recordLength=715;
//TODO: Review this temporary fix by BH to see if a broader refactor might be better.
// For WindSat -- which has a 56-byte header once per file, remove it from the
// message array here, so we don't have to mess with it separately later.
tempLength=message.length - 56;
byte[] xmessage = new byte[tempLength];
for (int i = 0; i<tempLength; i++) {
xmessage[i] = message[i+56];
public NcscatProcessing() {
}
public byte[] separate(byte[] data) {
doSeparate(data);
try {
if (newMessage == null) {
return (byte[]) null;
} else {
byte[] tempBytes = listByteTobyteArray(newMessage);
return tempBytes;
}
message = xmessage;
byteBuffer = null;
byteBuffer = ByteBuffer.allocate(tempLength);
byteBuffer.put(message,0,tempLength);
/* Original code as follows...
byteBuffer = null;
tempLength=message.length -56;
byteBuffer = ByteBuffer.allocate(tempLength);
byteBuffer.put(message,56,tempLength);
*/
//END of temporary fix by BH - Part 1 (compare Part 4)
}
//TODO: Review this temporary fix by BH to see if a broader refactor might be better.
// Endianess correction must be applied to the 4-short date/time field on each
// line. Here we use set the ByteOrder of the byteBuffer, so that the 4
// getShort(...) calls below will do the byte-flipping for us. We also
// remember byteOrder for a bit later... (Part 3)
//
ByteOrder byteOrder;
if ( (n == 1422) || // WSAT
((n == 1368) && "oscat".equalsIgnoreCase(getInputFileName())) || // OSCAT_HI
"ascatx".equalsIgnoreCase(getInputFileName()) ) { // EXASCT or EXASCT_HI
byteOrder = ByteOrder.LITTLE_ENDIAN;
}
else {
byteOrder = ByteOrder.BIG_ENDIAN;
}
byteBuffer.order(byteOrder);
//END of temporary fix by BH - Part 2 (new code added only)
try {
if(message!=null){
int dNcscatMult =0;
doubleNcscat = scatNumber*2;
scatXLen =doubleNcscat*9+8;
while (ji < tempLength) {
day = byteBuffer.getShort(ji) ;
hour= byteBuffer.getShort(ji+2);
min = byteBuffer.getShort(ji+4);
sec = byteBuffer.getShort(ji+6);
if (day<0) break;
if(ji<8){
//stTime = endTime;
startTime.set(Calendar.DAY_OF_YEAR, day);
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, min);
startTime.set(Calendar.SECOND, sec);
}
//else{
endTime.set(Calendar.DAY_OF_YEAR, day);
endTime.set(Calendar.HOUR_OF_DAY, hour);
endTime.set(Calendar.MINUTE, min);
endTime.set(Calendar.SECOND, sec);
//}
ji=ji+scatXLen;
}//for while
newMessage= new ArrayList<Byte>(tempLength);
while(bitNum<tempLength){
int consBitNum = bitNum;
while (bitNum<consBitNum+8)
{
//TODO: Review this temporary fix by BH to see if a broader refactor might be better.
// Here we again apply endianess correction to the 4-short date/time field on each
// line. Above (via the ByteBuffer) was just for determining startTime and endTime
// of the entire data set. Here we do it again as the 'message' array is moved to
// newMessage (ArrayList) for later return and eventual writing to the HDF5 data
// for each scan row. Note that the byte-swapping was already done below for the
// data fields in each row following the leading date/time (in the process of
// regrouping the data so data for each point is together); here we do it for the
// date as well (where no other regrouping is required).
//
int offsetInDate = bitNum - consBitNum; // 0 thru 7
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
// need to flip the 2 bytes of each short; map 0 1 2 3 4 5 6 7 to 1 0 3 2 5 4 7 6, respectively
offsetInDate = offsetInDate/2*2+(1-offsetInDate%2);
}
newMessage.add((Byte)message[consBitNum+offsetInDate]);
/* Original code as follows...
newMessage.add((Byte)message[bitNum]);
*/
//END of temporary fix by BH - Part 3
bitNum++;
}//date field 8 bytes
consBitNum = bitNum;
while((scatXLen*dNcscatMult+7)<=bitNum && bitNum<(scatXLen*(dNcscatMult+1))){
int calc=0;
for (int qNoIndex =0; qNoIndex<doubleNcscat;qNoIndex++){
for(int rou=0;rou<=8;rou++){
if(bitNum<tempLength){
calc=consBitNum+doubleNcscat*rou+qNoIndex;
//TODO: Review this temporary fix by BH to see if a broader refactor might be better.
// Problem with the following is it applies the 56-byte bias (for WindSat) to the
// address to copy from, but for the date transfer code to work above, bitNum
// must already have had this bias applied (fix above moved it), and so consBitNum
// -- the base address for this row of data, after the date field -- must also
// have already reflected this correction. (Note that the 56-byte header is once
// per file, rather than once per row.)
/* Original code [removed] as follows...
if(recordLength==715){
calc=calc+56;
}
*/
//END of temporary fix by BH - Part 4 (compare Part 1)
if(byteOrder == ByteOrder.LITTLE_ENDIAN) {// swap the bytes
newMessage.add(message[calc+1]);
bitNum++;
newMessage.add(message[calc]);//since 2 bytes form a short
bitNum++;
}
else{
newMessage.add(message[calc]);
bitNum++;
newMessage.add(message[calc+1]);//since 2 bytes form a short
bitNum++;
}
}//end of if
}//end of for
qNoIndex++;
}
dNcscatMult++;
}
}
}//if message is not null
}// end of try block
catch (Exception e) {
e.printStackTrace();
if (log.isInfoEnabled()) {
log.info("No valid records found!");
}
theLogger.warn("No valid records found!");
}
return;
}
} catch (NoSuchElementException e) {
return (byte[]) null;
}
}
/**
* processHDF5Data -- SHOULD NOT BE USED IN PRESENT FORM
* Please see NcscatResource.processHDF5Data(...)
* @param message
* separate bulletins
*/
private void doSeparate(byte[] message) {
ByteBuffer byteBuffer = ByteBuffer.allocate(message.length);
byteBuffer.put(message, 0, message.length);
int tempLength = message.length;
startTime = Calendar.getInstance();
startTime.setLenient(false); // guard against wild values
startTime.set(Calendar.MILLISECOND, 0);
endTime = Calendar.getInstance();
endTime.setLenient(false); // guard against wild values
endTime.set(Calendar.MILLISECOND, 0);
// Determine type of data (that is, which satellite and resolution)
// by examining it for unique consistency with known characteristics
NcscatMode matchedMode = NcscatMode.UNKNOWN;
for (NcscatMode mode : NcscatMode.values()) {
if (mode.consistentWith(byteBuffer)) {
matchedMode = mode;
break;
}
}
if (matchedMode == NcscatMode.UNKNOWN) {
// TODO: Log error/warning -- and quit?
}
ncscatMode = matchedMode;
// Set for historical compatibility...
scatNumber = ncscatMode.getPointsPerRow();
// assert ncscatMode.getBytesPerRow() % 2 == 0;
recordLength = ncscatMode.getBytesPerRow() / 2;
if (ncscatMode.getFileHeaderLength() > 0) {
// If there is a file header (separate from per-row headers), remove
// it from the message array here, so we don't have to mess with it
// separately later.
tempLength = message.length - ncscatMode.getFileHeaderLength();
byte[] xmessage = new byte[tempLength];
for (int i = 0; i < tempLength; i++) {
xmessage[i] = message[i + ncscatMode.getFileHeaderLength()];
}
message = xmessage;
byteBuffer.clear();
byteBuffer = null;
byteBuffer = ByteBuffer.allocate(tempLength);
byteBuffer.put(message, 0, tempLength);
}
// Endianess correction must be applied to the 4-short date/time field
// on each line. Here we set the ByteOrder of the byteBuffer, so
// that the 4 getShort(...) calls below will do the byte-flipping for
// us.
//
ByteOrder byteOrder = ncscatMode.getByteOrder();
byteBuffer.order(byteOrder);
try {
if (message != null) {
int ji = 0;
int dNcscatMult = 0;
int doubleNcscat = scatNumber * 2;
int scatXLen = doubleNcscat * 9 + 8;
int byteNum = 0;
// Make a pass through all rows in file, just to determine
// earliest and latest times
int day, hour, min, sec;
while (ji < tempLength) {
day = byteBuffer.getShort(ji);
hour = byteBuffer.getShort(ji + 2);
min = byteBuffer.getShort(ji + 4);
sec = byteBuffer.getShort(ji + 6);
if (day < 1 || day > 366 || hour < 0 || hour > 23
|| min < 0 || min > 59 || sec < 0 || sec > 60) {
// TODO log error?
break;// TODO continue?
}
if (ji < 8) { // first row
startTime.set(Calendar.DAY_OF_YEAR, day);
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, min);
startTime.set(Calendar.SECOND, sec);
}
// Don't know ahead of time which row will be last
// so set each time; last one will remain endTime
endTime.set(Calendar.DAY_OF_YEAR, day);
endTime.set(Calendar.HOUR_OF_DAY, hour);
endTime.set(Calendar.MINUTE, min);
endTime.set(Calendar.SECOND, sec);
ji = ji + scatXLen;
}// for while
// Time bounds scan done; now go back through the row data and
// rearrange as needed.
newMessage = new ArrayList<Byte>(tempLength);
while (byteNum < tempLength) {
int consByteNum = byteNum;
while (byteNum < consByteNum + 8) {
// Here we again apply endianess correction to the
// 4-short date/time field on each row. Above (via the
// ByteBuffer) was just for determining startTime and
// endTime of the entire data set. Here we do it again
// as the 'message' array is moved to newMessage
// (ArrayList) for later return and eventual writing to
// the HDF5 data for each scan row. Note that the
// byte-swapping is done below for the data fields in
// each row following the leading date/time (in the
// process of regrouping the data so data for each point
// is together); here we do it for the date as well
// (where no other regrouping is required).
//
int offsetInDate = byteNum - consByteNum; // 0 thru 7
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
// need to flip the 2 bytes of each short; map 0 1 2
// 3 4 5 6 7 to 1 0 3 2 5 4 7 6, respectively
offsetInDate = offsetInDate / 2 * 2
+ (1 - offsetInDate % 2);
}
newMessage.add((Byte) message[consByteNum
+ offsetInDate]);
byteNum++;
}// date field 8 bytes
// Done with row header (date/time); now start on the data
// for points in that row. (consByteNum is index of first
// byte of such data .)
consByteNum = byteNum;
// In the incoming data for a row, all values for each
// single parameter are grouped together (for all points in
// the row). The following code "shuffles" things so that
// all values for a single point are grouped together
// (that is, all parameters for a given point). In the
// process, proper endianess order is set for the two bytes
// making up each data value.
while ((scatXLen * dNcscatMult + 7) <= byteNum
&& byteNum < (scatXLen * (dNcscatMult + 1))) {
int calc = 0;
for (int qNoIndex = 0; qNoIndex < doubleNcscat; qNoIndex++) {
for (int rou = 0; rou <= 8; rou++) {
if (byteNum < tempLength) {
calc = consByteNum + doubleNcscat * rou
+ qNoIndex;
if (byteOrder == ByteOrder.LITTLE_ENDIAN) {
// swap the two bytes making up the
// short
newMessage.add(message[calc + 1]);
byteNum++;
newMessage.add(message[calc]);
byteNum++;
} else { // ByteOrder.BIG_ENDIAN
// preserve order of the two bytes
// making up the short
newMessage.add(message[calc]);
byteNum++;
newMessage.add(message[calc + 1]);
byteNum++;
}
} // end of if
} // end of for rou
qNoIndex++;
} // end of for qNoIndex
dNcscatMult++;
} // end of while
} // while (each row)
}// if message is not null
}// end of try block
catch (Exception e) {
e.printStackTrace();
if (log.isInfoEnabled()) {
log.info("No valid records found!");
}
theLogger.warn("No valid records found!");
}
return;
}
public NcscatMode getNcscatMode() {
return ncscatMode;
}
/**
* processHDF5Data -- SHOULD NOT BE USED IN PRESENT FORM Please see
* NcscatResource.processHDF5Data(...)
*
* @return List<NcscatPoint>
*
* @deprecated Please see NcscatResource.processHDF5Data(...)
*/
@Deprecated
public List<NcscatPoint> processHDF5Data(byte[] hdf5Msg) {
int ji = 0, bitNum = 0;
int day, hour, min, sec;
item = new ArrayList<NcscatPoint>();
// TODO - Caution! Separate startTime Calendar object needs to be
// allocated for each point row, since will be shared by all points
// in that row. See below.
startTime = Calendar.getInstance();
ByteBuffer byteBuffer = null;
byteBuffer = ByteBuffer.allocate(hdf5Msg.length);
byteBuffer.put(hdf5Msg, 0, hdf5Msg.length);
while (ji < hdf5Msg.length) {
public List<NcscatPoint> processHDF5Data(byte[] hdf5Msg){
int ji=0, bitNum=0;
int day,hour,min,sec;
item= new ArrayList<NcscatPoint>();
// TODO - Caution! Separate startTime Calendar object needs to be allocated
// for each point row, since will be shared by all points
// in that row. See below.
startTime = Calendar.getInstance();
ByteBuffer byteBuffer = null;
byteBuffer = ByteBuffer.allocate(hdf5Msg.length);
byteBuffer.put(hdf5Msg,0,hdf5Msg.length);
day = byteBuffer.getShort(bitNum);
hour = byteBuffer.getShort(bitNum + 2);
min = byteBuffer.getShort(bitNum + 4);
sec = byteBuffer.getShort(bitNum + 6);
ji = ji + 8;
bitNum = bitNum + 8;
// TODO - Caution! Need to allocate new startTime here...
startTime.set(Calendar.DAY_OF_YEAR, day);
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, min);
startTime.set(Calendar.SECOND, sec);
for (int j = ji; j < ji + scatNumber * 18
&& bitNum < hdf5Msg.length; j = j + 18) {
sPointObj = new NcscatPoint();
// TODO - continued - otherwise all points in all rows get same
// time here
sPointObj.setStTime(startTime);
sPointObj.setLat(byteBuffer.getShort(j));
sPointObj.setLon(byteBuffer.getShort(j + 2));
sPointObj.setIql(byteBuffer.getShort(j + 4));
sPointObj.setIsp(byteBuffer.getShort(j + 6));
sPointObj.setIdr(byteBuffer.getShort(j + 8));
sPointObj.setIrn(byteBuffer.getShort(j + 10));
sPointObj.setIb1(byteBuffer.getShort(j + 12));
sPointObj.setIb2(byteBuffer.getShort(j + 14));
sPointObj.setIb3(byteBuffer.getShort(j + 16));
bitNum = bitNum + 18;
item.add(sPointObj);
while ( ji < hdf5Msg.length) {
}// for
day = byteBuffer.getShort(bitNum) ;
hour= byteBuffer.getShort(bitNum+2);
min = byteBuffer.getShort(bitNum+4);
sec = byteBuffer.getShort(bitNum+6);
ji=ji+8;
bitNum=bitNum+8;
// TODO - Caution! Need to allocate new startTime here...
startTime.set(Calendar.DAY_OF_YEAR, day);
startTime.set(Calendar.HOUR_OF_DAY, hour);
startTime.set(Calendar.MINUTE, min);
startTime.set(Calendar.SECOND, sec);
for(int j=ji;j<ji+scatNumber*18 && bitNum <hdf5Msg.length;j=j+18){
sPointObj = new NcscatPoint();
// TODO - continued - otherwise all points in all rows get same time here
sPointObj.setStTime(startTime);
sPointObj.setLat(byteBuffer.getShort(j));
sPointObj.setLon(byteBuffer.getShort(j+2));
sPointObj.setIql(byteBuffer.getShort(j+4));
sPointObj.setIsp(byteBuffer.getShort(j+6));
sPointObj.setIdr(byteBuffer.getShort(j+8));
sPointObj.setIrn(byteBuffer.getShort(j+10));
sPointObj.setIb1(byteBuffer.getShort(j+12));
sPointObj.setIb2(byteBuffer.getShort(j+14));
sPointObj.setIb3(byteBuffer.getShort(j+16));
bitNum=bitNum+18;
item.add(sPointObj);
ji = bitNum;
}//for
}// for while
ji=bitNum;
return item;
}//for while
}
return item;
public Calendar getStartTime() {
return startTime;
}
}
public void setStartTime(Calendar startTime) {
this.startTime = startTime;
}
public Calendar getStartTime() {
return startTime;
}
public Calendar getEndTime() {
return endTime;
}
public void setEndTime(Calendar endTime) {
this.endTime = endTime;
}
public void setStartTime(Calendar startTime) {
this.startTime = startTime;
}
private static byte[] listByteTobyteArray(List<Byte> temp) {
byte[] byteArray = new byte[temp.size()];
int jkl = 0;
for (Byte current : temp) {
byteArray[jkl] = current;
jkl++;
}
public Calendar getEndTime() {
return endTime;
}
public void setEndTime(Calendar endTime) {
this.endTime = endTime;
}
return byteArray;
}
private static byte[] listByteTobyteArray(List<Byte> temp) {
byte[] byteArray = new byte[temp.size()];
int jkl=0;
for(Byte current:temp){
byteArray[jkl] =current;
jkl++;
}
public int getRecordLength() {
return recordLength;
}
return byteArray;
}
public void setRecordLength(int recordLength) {
this.recordLength = recordLength;
}
public static int getRecordLength() {
return recordLength;
}
public String getInputFileName() {
return inputFileName;
}
public static void setRecordLength(int recordLength) {
NcscatProcessing.recordLength = recordLength;
}
public String getInputFileName() {
return inputFileName;
}
public void setInputFileName(String inputFileName) {
this.inputFileName = inputFileName;
}
public void setInputFileName(String inputFileName) {
this.inputFileName = inputFileName;
}
}

View file

@ -13,6 +13,7 @@
* 09/2011 Chin Chen add batch parsing methods for better performance
* 09/2011 457 S. Gurung Renamed H5 to Nc and h5 to nc
* 12/2013 T. Lee Fixed TTCC Wmax pressure off by factor of 10
* 10/2014 T. Lee Fixed XXCC/XXDD indices to use TTCC/TTDD processing
*
* </pre>
*
@ -67,9 +68,9 @@ public class NcUairParser {
public static final int XXBB = 2;
public static final int XXCC = 9;
public static final int XXCC = 3;
public static final int XXDD = 10;
public static final int XXDD = 4;
/**
* Constructor

View file

@ -10,7 +10,8 @@
* 03/2010 210 L. Lin Initial coding
* 09/2011 457 S. Gurung Renamed H5 to Nc and h5 to nc
* 09/02/2014 Chin Chen fix surface height missing on some stations issue
*
* 10/2014 T. Lee Updated catch-all phrases for stnID
*
* </pre>
*
* This code has been developed by the SIB for use in the AWIPS2 system.
@ -336,7 +337,7 @@ public class NcUairShipMobile {
*/
public static void Dropsonde(String report) {
final String DROP = "61616 (AF|NOAA|NASA)(\\d{1,3}) (.*) OB (\\d{2}) 62626";
final String DROP = "61616 (AF|NOAA|NA)(\\d{1,3}) (.*) OB (\\d{2}) 62626";
Pattern dropPattern = Pattern.compile(DROP, Pattern.DOTALL);
Matcher dropMatcher = dropPattern.matcher(report);
@ -354,6 +355,10 @@ public class NcUairShipMobile {
+ dropMatcher.group(2);
stnId = dropMatcher.group(1) + dropMatcher.group(2)
+ dropMatcher.group(4);
} else {
System.out.println(" New dropsonde station found");
stationNumber = "99999";
stnId = "NEW_DROP";
}
// Chin: sfcElevSolution start
// if (drop2Matcher.find()) {

View file

@ -11,6 +11,9 @@ import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.raytheon.edex.exception.DecoderException;
import com.raytheon.edex.plugin.AbstractDecoder;
@ -33,22 +36,46 @@ import com.raytheon.uf.common.time.DataTime;
* 10/2013 B. Hebbard Modify model name inference from metafile name
* Aug 30, 2013 2298 rjpeter Make getPluginName abstract
* 6/2014 T. Lee Added HYSPLIT and fixed "other" modelName
* 08/2014 B. Hebbard Revise createDataTime() to correct end-of-month boundary bug
* 08/2014 B. Hebbard Enhance to use (cycle) time info from metafile name, if available
* 09/2014 B. Hebbard Normalize (shorten) metafile name to remove directory artifacts added during dataflow, so user will see that they're used to and will fit selection dialog column
* </pre>
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*/
public class NtransDecoder extends AbstractDecoder {
private final static int NTRANS_FILE_TITLE_SIZE = 32; // bytes
private final static int NTRANS_FRAME_LABEL_SIZE = 64;
private final static int NTRANS_FRAME_LABEL_TIME_SUBSTRING_SIZE = 9;
private final static int NTRANS_RESERVED_SPACE_SIZE = 38;
Calendar decodeTime = null;
private String normalizedMetafileName;
Integer yearFromFileName = null;
Integer monthFromFileName = null;
Integer dateFromFileName = null;
Integer hourFromFileName = null;
/**
* Constructor
*
* @throws DecoderException
*/
public NtransDecoder() throws DecoderException {
decodeTime = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
}
private class FrameHeader {
String validTimeString;
String frameHeaderTimeString;
String productNameString;
@ -78,17 +105,26 @@ public class NtransDecoder extends AbstractDecoder {
int fileMachineType = 0;
int frameSizeX = 0;
int frameSizeY = 0;
byte[] fileReservedSpace = new byte[38]; // TODO symbolic
byte[] fileReservedSpace = new byte[NTRANS_RESERVED_SPACE_SIZE]; // TODO
// symbolic
List<FrameHeader> frameHeaders = new ArrayList<FrameHeader>();
List<NtransRecord> records = new ArrayList<NtransRecord>();
try {
decodeTime = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
fileName = inputFile.getName();
normalizedMetafileName = normalizeMetafileName(fileName);
getTimeFromMetafileName(normalizedMetafileName);
inputStream = new FileInputStream(inputFile);
// Read the entire file
// TODO: Wish we didn't have to do that, but decode method
// wants to return all PDOs at once, so it's all got
// to sit in memory anyway. Propose architecture change (?)
@ -118,7 +154,7 @@ public class NtransDecoder extends AbstractDecoder {
// Read NTRANS metafile header
byte[] fileTitleBytes = new byte[32]; // TODO symbolic
byte[] fileTitleBytes = new byte[NTRANS_FILE_TITLE_SIZE];
byteBuffer.get(fileTitleBytes);
fileTitle = new String(fileTitleBytes).trim();
// System.out.println("[File title: " + fileTitle + "]");
@ -129,18 +165,18 @@ public class NtransDecoder extends AbstractDecoder {
frameSizeX = toUnsigned(byteBuffer.getShort());
frameSizeY = toUnsigned(byteBuffer.getShort());
byte[] fileReserved = new byte[38];
byte[] fileReserved = new byte[NTRANS_RESERVED_SPACE_SIZE];
byteBuffer.get(fileReserved);
// Read NTRANS frame headers (follow file header; precede frame
// contents)
for (int frame = 0; frame < fileMaxFrame; frame++) {
byte[] labelTitleBytes = new byte[64]; // TODO symbolic
byte[] labelTitleBytes = new byte[NTRANS_FRAME_LABEL_SIZE];
byteBuffer.get(labelTitleBytes);
StringBuffer sb = new StringBuffer();
for (int i = 0; (i < 64) && (labelTitleBytes[i] != 0x00); i++) { // TODO
// symbolic
for (int i = 0; (i < NTRANS_FRAME_LABEL_SIZE)
&& (labelTitleBytes[i] != 0x00); i++) {
sb.append((char) labelTitleBytes[i]);
}
String labelTitle = new String(sb);
@ -152,12 +188,14 @@ public class NtransDecoder extends AbstractDecoder {
// System.out.println("[startPos " + startPos + " endPos " +
// endPos + "]");
FrameHeader fh = new FrameHeader();
if (labelTitle.length() < 8) { // TODO check!
fh.validTimeString = labelTitle;
if (labelTitle.length() < NTRANS_FRAME_LABEL_TIME_SUBSTRING_SIZE) {
fh.frameHeaderTimeString = labelTitle;
fh.productNameString = "";
} else {
fh.validTimeString = labelTitle.substring(0, 9);
fh.productNameString = labelTitle.substring(9);
fh.frameHeaderTimeString = labelTitle.substring(0,
NTRANS_FRAME_LABEL_TIME_SUBSTRING_SIZE);
fh.productNameString = labelTitle
.substring(NTRANS_FRAME_LABEL_TIME_SUBSTRING_SIZE);
}
fh.startPos = startPos;
fh.endPos = endPos;
@ -184,7 +222,8 @@ public class NtransDecoder extends AbstractDecoder {
record.setReportType("NTRANS");
record.setModelName(inferModel(inputFile.getName()).replaceAll(
"_", "-"));
record.setMetafileName(inputFile.getName().replaceAll("_", "-"));
record.setMetafileName(normalizedMetafileName.replaceAll("_",
"-"));
record.setProductName(fh.productNameString
.trim()
.replaceAll("_", "-")
@ -195,8 +234,8 @@ public class NtransDecoder extends AbstractDecoder {
// TODO acceptable??
.replaceAll(",", "-").replaceAll("--", "-")
.replaceAll("--", "-")); // twice
record.setDataTime(createDataTime(fh.validTimeString));
record.setValidTimeString(fh.validTimeString);
record.setDataTime(createDataTime(fh.frameHeaderTimeString));
record.setValidTimeString(fh.frameHeaderTimeString);
record.setImageData(frameImage);
record.setImageSizeX(frameSizeX);
record.setImageSizeY(frameSizeY);
@ -241,146 +280,439 @@ public class NtransDecoder extends AbstractDecoder {
}
private DataTime createDataTime(String validTimeString) {
// Create a standard DataTime object, with proper timing
// determined from valid time string (e.g., "27/06V042")
// Get a Calendar object. Fields default to current time.
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
// Get components of validTimeString as 'int's
// TODO -- generalize to take "F" as well as "V" strings?
// if so, may want to put in central utilities.
// TODO -- use more general/flexible pattern matching?
// TODO -- improve error handling/recovery
// try {
String validDateString = validTimeString.substring(0, 2);
int validDate = Integer.parseInt(validDateString);
String validHourString = validTimeString.substring(3, 5);
int validHour = Integer.parseInt(validHourString);
String fcstHourString = validTimeString.substring(6, 9);
int fcstHour = Integer.parseInt(fcstHourString);
// }
// catch (Exception e) {
// TODO
// return new DataTime(calendar, 0);
public String normalizeMetafileName(String fileName) {
// Given..."gfs_gfs.20140901_gfs_20140901_12_ak"
// Want....................."gfs_20140901_12_ak"
//
// @formatter:off
// Darn... Following is thwarted by these cases:
// gfs_gfs.20140901_gfsver_20140901_18_na_mar
// ukmet.2014090_ukmet.2014090._ukmetver_20140901_00
// wave_wave.20140901_nww3_20140901_12
// wave_wave.20140902_nww3_20140902_00_akw
//
// final Pattern p = Pattern.compile("^(\\w+)_\\1\\.(\\d{6,8})_\\1_\\2");
// Matcher m = p.matcher(fileName);
// if (m.find()) {
// fileName = fileName.replaceFirst("^(\\w+)_\\1\\.(\\d{6,8})_", "");
// }
//
// @formatter:on
// So, instead we...
// Alter specific fields to set to valid time.
// TODO -- use cycle time string if available to set year, month
// but must be very careful about applying rules
// If the string constains a ".", then remove everything from start of
// string through the FIRST "_" following the LAST "."
calendar.set(Calendar.DAY_OF_MONTH, validDate);
calendar.set(Calendar.HOUR_OF_DAY, validHour);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
if (fileName.contains(".")) {
String[] splits = fileName.split("\\.");
String lastSplit = splits[splits.length - 1];
// "reluctant" (?) match to assure first "_"
return lastSplit.replaceFirst("^.*?_", "");
} else {
return fileName;
}
}
// Now subtract forecast hours to get initial (reference) or cycle time
private int normalizeYear(int shortYear) {
calendar.add(Calendar.HOUR_OF_DAY, -fcstHour);
// Year can be 2 digits. If so, select century to make it the one
// closest to the current year.
// Careful here: Calendar assumed valid time is in the current month
// (which, even with current data, could be off one month either way).
// (Yeah, I know it's overkill. But that's what we thought *last*
// century...)
// What we want for the month of the valid time is the latest month
// such that the (deduced) cycle time is not in the future (that is,
// not later than decode time "now").
if (shortYear > 99) {
return shortYear;
} else {
if (decodeTime == null) {
decodeTime = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
}
int currYear = decodeTime.get(Calendar.YEAR);
int currCentury = currYear / 100;
int breakpoint = (currYear + 50) % 100;
int derivedYear = currCentury * 100 + shortYear;
if (shortYear > breakpoint) {
derivedYear++;
}
return derivedYear;
}
}
// The following two steps are designed to get us there. (Note that
// either or both can execute.) First, if the inferred cycle time is
// in the past, try adding a month...
private int CalendarMonth(int goodOldMonthNumber) {
// Just to be proper (since we don't control the values
// of these "magic constants", and so can't assume they
// won't change out from under us (say, in the unlikely
// but possible case that Calendar decides to go with
// 1-based months (like the rest of the world) instead
// of 0-based ones. (We're 0-based [array] here, too, but
// WE control the order, and shield it from the caller.)
// @formatter:off
final int[] CalendarMonthConstants = {
Calendar.JANUARY,
Calendar.FEBRUARY,
Calendar.MARCH,
Calendar.APRIL,
Calendar.MAY,
Calendar.JUNE,
Calendar.JULY,
Calendar.AUGUST,
Calendar.SEPTEMBER,
Calendar.OCTOBER,
Calendar.NOVEMBER,
Calendar.DECEMBER,
};
return CalendarMonthConstants[goodOldMonthNumber - 1];
// @formatter:on
}
if (calendar.before(now)) {
calendar.add(Calendar.MONTH, 1);
private void getTimeFromMetafileName(String fileName) {
// NTRANS metafile names (almost?) always contain date and (sometimes)
// hour information. We assume that this refers to the cycle time of the
// model run which produced the images it contains. Since individual
// frame headers (contained within the body of the file) currently
// (2014-08) provide only valid times with date -- and no month or year
// -- taking these 'hints' from the file name, if available, allows us
// to handle legacy data properly, even if months or years old.
//
// This method operates on instance variables for both input and output.
//
// Input is fileName, which is assumed to have been set to the full name
// of the metafile currently being ingested, containing a substring of
// one of the following forms:
// @formatter:off
// YYYYMMDD
// YYYYMMDDHH
// YYYYMMDD_HH
// YYMMDD
// YYMMDD_HH
// @formatter:on
//
// Output takes the form of...
// yearFromFileName, monthFromFileName,
// dateFromFileName, hourFromFileName
// These are (boxed) Integer variables; a null value indicates no value
// is available for that field.
final Pattern p = Pattern.compile("((\\d\\d){3,4})_?(\\d\\d)?");
Matcher m = p.matcher(fileName);
String matchString = "";
String hourString = "";
String year = "";
String month = "";
String date = "";
String hour = "";
while (m.find()) {
if (m.group(0).length() >= matchString.length()) {
matchString = m.group(0);
String dateString = m.group(1).replaceFirst("_", "");
date = dateString.substring(dateString.length() - 2);
dateString = dateString.substring(0, dateString.length() - 2);
month = dateString.substring(dateString.length() - 2);
dateString = dateString.substring(0, dateString.length() - 2);
year = dateString.substring(dateString.length() - 2);
dateString = dateString.substring(0, dateString.length() - 2);
assert (dateString.isEmpty());
hourString = m.group(3);
}
}
// Now -- regardless of whether the previous step executed (no "else"
// here)
// if the inferred cycle time is in the future, back up one month.
if (!matchString.isEmpty()) {
try {
yearFromFileName = normalizeYear(Integer.parseInt(year));
monthFromFileName = Integer.parseInt(month);
dateFromFileName = Integer.parseInt(date);
if (!hourString.isEmpty()) {
hourFromFileName = Integer.parseInt(hourString);
}
} catch (Exception e) {
// TODO: ERROR
// Set *FromFileName back to null? Or not (leave partial partial
// parse results)?
}
}
}
if (calendar.after(now)) {
calendar.add(Calendar.MONTH, -1);
DataTime createDataTime(String frameHeaderTimeString,
String simulatedFileName, Calendar simulatedDecodeTime) {
decodeTime = simulatedDecodeTime;
return createDataTime(frameHeaderTimeString, simulatedFileName);
}
DataTime createDataTime(String frameHeaderTimeString,
String simulatedFileName) {
fileName = simulatedFileName;
normalizedMetafileName = normalizeMetafileName(fileName);
getTimeFromMetafileName(normalizedMetafileName);
return createDataTime(frameHeaderTimeString);
}
DataTime createDataTime(String frameHeaderTimeString) {
// Create a standard DataTime object, with proper timing
// determined from given time string (e.g., "27/06V042")
// (from the frame header), AND fields parsed earlier from
// the metafile name (and stored in instance variables),
// if available.
// --
// Get components of validframeHeaderTimeString as 'int's
// Be able to decode...
// 8, 6, 4, or 2 digits, followed by...
// "/" followed by...
// 2 digits followed by...
// "F" or "V" followed by...
// any number of digits? 2-3? 1-6?
// NOT with intervening spaces?
final Pattern p = Pattern
.compile("((\\d\\d){1,4})/(\\d\\d)(F|V)(\\d{1,4})");
Matcher m = p.matcher(frameHeaderTimeString);
boolean isV = false;
Integer centuryFromFrameHeader = null;
Integer yearFromFrameHeader = null;
Integer monthFromFrameHeader = null;
Integer dateFromFrameHeader = null;
Integer hourFromFrameHeader = null;
Integer fcstHour = null;
String dateString, hourString, fOrV, fcstHourString;
if (m.find()) {
dateString = m.group(1);
hourString = m.group(3);
fOrV = m.group(4);
fcstHourString = m.group(5);
} else {
return new DataTime(decodeTime, 0); // should be error indication
}
try {
switch (dateString.length()) {
case 8:
centuryFromFrameHeader = Integer.parseInt(dateString.substring(
0, 2));
dateString = dateString.substring(2);
// NO break;
case 6:
yearFromFrameHeader = Integer.parseInt(dateString.substring(0,
2));
dateString = dateString.substring(2);
if (centuryFromFrameHeader == null) {
yearFromFrameHeader = normalizeYear(yearFromFrameHeader);
} else {
yearFromFrameHeader += centuryFromFrameHeader * 100;
}
// NO break;
case 4:
monthFromFrameHeader = Integer.parseInt(dateString.substring(0,
2));
dateString = dateString.substring(2);
// NO break;
case 2:
dateFromFrameHeader = Integer.parseInt(dateString.substring(0,
2));
dateString = dateString.substring(2);
assert (dateString.isEmpty());
break;
default:
// ERROR
break;
}
hourFromFrameHeader = Integer.parseInt(hourString);
isV = fOrV.equalsIgnoreCase("V");
fcstHour = Integer.parseInt(fcstHourString);
} catch (Exception e) {
// TODO
return new DataTime(Calendar.getInstance(TimeZone
.getTimeZone("GMT")), 0);
}
// Establish upper bound on what the specified time means.
// For F-type string, that would be the cycle time.
// For V-type string, that would be the valid time.
// Start with the decode (system) time...
Calendar upperBoundTime = Calendar.getInstance(TimeZone
.getTimeZone("GMT"));
upperBoundTime.setTime(decodeTime.getTime());
// YEAR: If specified in the frame header, that takes priority...
if (yearFromFrameHeader != null) {
upperBoundTime.set(Calendar.YEAR, yearFromFrameHeader);
}
// ...otherwise use value from file name, if available...
else if (yearFromFileName != null) {
upperBoundTime.set(Calendar.YEAR, yearFromFileName);
}
// ...otherwise defaults to the current year.
// MONTH: If specified in the frame header, that takes priority...
if (monthFromFrameHeader != null) {
upperBoundTime.set(Calendar.MONTH,
CalendarMonth(monthFromFrameHeader));
}
// ...otherwise use value from file name, if available
else if (monthFromFileName != null) {
upperBoundTime
.set(Calendar.MONTH, CalendarMonth(monthFromFileName));
}
// ...otherwise defaults to current month
// DATE: If specified in the frame header, IGNORE FOR NOW...
// if (dateFromFrameHeader != null) {
// upperBoundTime.set(Calendar.DAY,
// CalendarMonth(monthFromFrameHeader));
// }
// else
// ...BUT do use value from file name, if available
if (dateFromFileName != null) {
upperBoundTime.set(Calendar.DAY_OF_MONTH, dateFromFileName);
}
// ...otherwise defaults to current date
// If we're dealing with a V-type string, we're determining the VALID
// time. Add forecast hours.
if (isV) {
upperBoundTime.add(Calendar.HOUR_OF_DAY, fcstHour);
}
// Now calculate the actual valid time, starting with the latest
// possible...
Calendar calculatedValidTime = Calendar.getInstance(TimeZone
.getTimeZone("GMT"));
calculatedValidTime.setTime(upperBoundTime.getTime());
// ...setting the date field to the specified date...
calculatedValidTime.set(Calendar.DATE, dateFromFrameHeader);
// ...but if greater than the latest possible valid date...
int latestPossibleValidDate = upperBoundTime.get(Calendar.DAY_OF_MONTH);
if (dateFromFrameHeader > latestPossibleValidDate) {
// ...then it must be that date in the PRIOR month...
calculatedValidTime.add(Calendar.MONTH, -1);
}
// Now set the hour field to the specified hour...
calculatedValidTime.set(Calendar.HOUR_OF_DAY, hourFromFrameHeader);
// ...and finally set sub-hour fields all to zero
calculatedValidTime.set(Calendar.MINUTE, 0);
calculatedValidTime.set(Calendar.SECOND, 0);
calculatedValidTime.set(Calendar.MILLISECOND, 0);
// Now calculate actual initial (reference) or cycle time
Calendar calculatedCycleTime = Calendar.getInstance(TimeZone
.getTimeZone("GMT"));
calculatedCycleTime.setTime(calculatedValidTime.getTime());
// Subtract forecast hours to get initial (reference) or cycle time
if (isV) {
calculatedCycleTime.add(Calendar.HOUR_OF_DAY, -fcstHour);
}
// Sanity check against file name date and hour (if known)
int calculatedCycleDate = calculatedCycleTime
.get(Calendar.DAY_OF_MONTH);
int calculatedCycleHour = calculatedCycleTime.get(Calendar.HOUR_OF_DAY);
if (dateFromFileName != null && dateFromFileName != calculatedCycleDate) {
// WARNING!!
logger.warn("Cycle date " + dateFromFileName
+ " from metafile name " + fileName + " differs from "
+ calculatedCycleDate + " inferred from frame header "
+ frameHeaderTimeString);
} else if (hourFromFileName != null
&& hourFromFileName != calculatedCycleHour) {
// WARNING!!
logger.warn("Cycle hour " + hourFromFileName
+ " from metafile name " + fileName + " differs from "
+ calculatedCycleHour + " inferred from frame header "
+ frameHeaderTimeString);
}
// Return DataTime, constructed from cycle time and forecast hour.
DataTime dataTime = new DataTime(calendar, fcstHour * 3600);
DataTime dataTime = new DataTime(calculatedCycleTime, fcstHour * 3600);
return dataTime;
}
private DataTime createDataTime(String initialTimeString,
String validTimeString) {
// FUTURE -- use initialTimeString to influence deduction of
// full initial (reference) time from validTimeString
// For now, initialTimeString not used...
return createDataTime(validTimeString);
/*
*
* // Create a standard DataTime object, with proper timing //
* determined from valid time string (e.g., "27/06V042")
*
* // Get components of validTimeString as 'int's // TODO -- generalize
* to take "F" as well as "V" strings? // if so, may want to put in
* central utilities. // TODO -- use more general/flexible pattern
* matching?
*
* String validDateString = validTimeString.substring(0, 1); int
* validDate = Integer.parseInt(validDateString); String validHourString
* = validTimeString.substring(3, 4); int validHour =
* Integer.parseInt(validHourString); String fcstHourString =
* validTimeString.substring(6, 8); int fcstHour =
* Integer.parseInt(fcstHourString);
*
* // Get a Calendar object. Fields default to current time.
*
* Calendar calendar = Calendar.getInstance();
*
* // Alter specific fields to set to valid time. // TODO -- use cycle
* time string if available to set year, month // but must be very
* careful about applying rules
*
* calendar.set(Calendar.DAY_OF_MONTH, validDate);
* calendar.set(Calendar.HOUR_OF_DAY, validHour);
* calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0);
* calendar.set(Calendar.MILLISECOND, 0);
*
* // Now subtract forecast hours to get initial (reference) time...
*
* calendar.add(Calendar.HOUR_OF_DAY, -fcstHour);
*
* // ...for DataTime constructor that wants it // (DataTime has many
* constructors, but none that // takes validTime and fcstHour)
*
* DataTime dataTime = new DataTime(calendar, fcstHour);
*
* return dataTime;
*/
}
private enum Model {
// TODO - Remove this, to make decoder agnostic w.r.t. list of available
// models.
// We do this temporarily because we don't yet know the possible formats
// of filename strings we're going to be fed, so for now we just look
// for
// known model names appearing anywhere in the file name.
// for known model names appearing anywhere in the file name.
// NOTE: Sequence is important only insofar as any model name must
// appear
// after all model names of which it is a proper substring.
// appear after all model names of which it is a proper substring.
// Also, OPC_ENC comes first, since its metafiles may contain other
// model substrings
OPC_ENS, CMCE_AVGSPR, CMCE, CMCVER, CMC, CPC, DGEX, ECENS_AVGSPR, ECENS, ECMWFVER, ECMWF_HR, ECMWF, ENSVER, FNMOCWAVE, GDAS, GEFS_AVGSPR, GEFS, GFSP, GFSVERP, GFSVER, GFS, GHM, HPCQPF, HPCVER, HWRF, ICEACCR, JMAP, JMA, MEDRT, NAEFS, NAM20, NAM44, NAMVER, NAM, NAVGEM, NOGAPS, NWW3P, NWW3, RAPP, RAP, SREFX, SST, UKMETVER, UKMET, VAFTAD
// @formatter:off
OPC_ENS,
CMCE_AVGSPR,
CMCE,
CMCVER,
CMC,
CPC,
DGEX,
ECENS_AVGSPR,
ECENS,
ECMWFVER,
ECMWF_HR,
ECMWF,
ENSVER,
FNMOCWAVE,
GDAS,
GEFS_AVGSPR,
GEFS,
GFSP,
GFSVERP,
GFSVER,
GFS,
GHM,
HPCQPF,
HPCVER,
HWRF,
ICEACCR,
JMAP,
JMA,
MEDRT,
NAEFS,
NAM20,
NAM44,
NAMVER,
NAM,
NAVGEM,
NOGAPS,
NWW3P,
NWW3,
RAPP,
RAP,
SREFX,
SST,
UKMETVER,
UKMET,
VAFTAD
// @formatter:on
};
private String inferModel(String fileName) {

View file

@ -238,7 +238,7 @@ public class MergeSounding2 implements ISerializableObject {
sndata.clear();
sndata.add(sl);
// System.out
// .println("return manatory level without merging!");
// .println("return mandatory level without merging!");
// printOut(sndata);
return sndata;
}

View file

@ -31,6 +31,9 @@ package gov.noaa.nws.ncep.edex.uengine.tasks.profile;
* 06/25/2014 Chin Chen support dropsonde
* 07/23/2014 Chin Chen Support PW
* 08/26/2014 Chin Chen index out of bound bug
* 10/03/2014 B. Hebbard Performance improvement: Pass level and pwRequired params to
* ObservedSoundingQuery.getObservedSndNcUairDataGeneric( ) so
* it can decide whether it can economize on DB params it needs
* </pre>
* Python Script example to query multiple locations at one request:
* The following 3 query examples, returns same results.
@ -1107,7 +1110,7 @@ public class NcSoundingDrv {
long t003 = System.currentTimeMillis();
uairRecordArrList = ObservedSoundingQuery
.getObservedSndNcUairDataGeneric(coordinateArray, stnIdArr,
rangeTimeStringLst, rangeTimeArr);
rangeTimeStringLst, rangeTimeArr, level, pwRequired);
long t004 = System.currentTimeMillis();
System.out.println("getObservedSndNcUairDataGeneric query took "
+ (t004 - t003) + "ms");
@ -1442,8 +1445,9 @@ public class NcSoundingDrv {
// }
returnedObject = cube;
// long t02 = System.currentTimeMillis();
// System.out.println("getSoundingData2Generic query took "+(t02-t01)+" ms in total");
long t02 = System.currentTimeMillis();
System.out.println("getSoundingData2Generic query took " + (t02 - t01)
+ " ms in total");
return returnedObject;
}
@ -1470,18 +1474,23 @@ public class NcSoundingDrv {
}
List<NcUairRecord[]> uairRecordArrList;
// long t003 = System.currentTimeMillis();
long t003 = System.currentTimeMillis();
uairRecordArrList = ObservedSoundingQuery
.getObservedSndNcUairDataGeneric(coordinateArray, stnIdArr,
rangeTimeStringLst, rangeTimeArr);
// long t004 = System.currentTimeMillis();
// System.out.println("getObservedSndNcUairDataGeneric API call took "+(t004-t003)+"ms");
rangeTimeStringLst, rangeTimeArr, level, pwRequired);
long t004 = System.currentTimeMillis();
System.out.println("getObservedSndNcUairDataGeneric API call took "
+ (t004 - t003) + "ms");
if (uairRecordArrList != null && uairRecordArrList.size() > 0) {
// long t005 = System.currentTimeMillis();
long t005 = System.currentTimeMillis();
soundingProfileList = processQueryReturnedNcUairData(
uairRecordArrList, useNcSoundingLayer2);
// long t006 = System.currentTimeMillis();
// System.out.println("getSoundingDataGeneric total sounding time merging for "+uairRecordArrList.size()+" profiles took "+(t006-t005)+"ms");
long t006 = System.currentTimeMillis();
System.out
.println("getSoundingDataGeneric total sounding time merging for "
+ uairRecordArrList.size()
+ " profiles took "
+ (t006 - t005) + "ms");
}
} else if (sndType.equals(PfcSndType.NAMSND.toString())

View file

@ -67,6 +67,9 @@ import com.vividsolutions.jts.geom.Coordinate;
* Jul 19, 2013 1992 bsteffen Remove redundant time columns from bufrua.
* Aug 30, 2013 2298 rjpeter Make getPluginName abstract
* June, 2014 Chin Chen Retrieved observed sounding with reftime
* Oct 03, 2014 B. Hebbard Performance improvement: getObservedSndNcUairDataGeneric( )
* limits DB param set to retrieve, in cases where possible
* (mandatory level and no PW-for-full-sounding)
* </pre>
*
* @author Chin Chen
@ -949,7 +952,8 @@ public class ObservedSoundingQuery {
*/
public static List<NcUairRecord[]> getObservedSndNcUairDataGeneric(
Coordinate[] coordArray, String[] stnIdArray,
List<String> soundingTimeStrList, long[] soundTimeLongArr) {
List<String> soundingTimeStrList, long[] soundTimeLongArr,
String level, int pwRequired) {
// List<NcSoundingProfile> soundingProfileList= new
// ArrayList<NcSoundingProfile>();
PointDataQuery request = null;
@ -963,8 +967,31 @@ public class ObservedSoundingQuery {
boolean queryByStn;
try {
request = new PointDataQuery("ncuair");
request.setParameters(NcUairToRecord.MAN_PARAMS_LIST);
// If a mandatory level is being requested, then we
// can speed things up significantly by getting only the
// TTAA/XXAA parameters from the datastore. Exceptions
// to this are made (a) if we need precipitable water for
// the entire sounding whose algorithm requires all data
// types, OR (b) we're only requesting data for a single
// station (as for Cloud Height) in which case performance
// isn't an issue.
boolean multipleStationsRequested = (coordArray != null && coordArray.length > 1)
|| (stnIdArray != null && stnIdArray.length > 1);
if (isMandatoryLevel(level) && pwRequired == 0
&& multipleStationsRequested) {
request.setParameters(NcUairToRecord.AA_ONLY_PARAMS_LIST);
// ...otherwise, we'd better grab the whole set
} else {
request.setParameters(NcUairToRecord.MAN_PARAMS_LIST);
}
request.addParameter("nil", String.valueOf(false), "=");
// The following may look wasteful if we only need one level,
// but requesting a specific level (1) requires spelling out
// parameters to which it applies, and more importantly
// (2) saves NO time on the resulting IDataStore request,
// because all levels are retrieved there anyway(!). See note
// in PointDataPluginDao.getPointData( ): "...for now, we
// will retrieve all levels and then post-process the result"
request.requestAllLevels();
String d = "";
for (String timeStr : soundingTimeStrList) {
@ -1006,8 +1033,10 @@ public class ObservedSoundingQuery {
long t001 = System.currentTimeMillis();
result = request.execute();
long t002 = System.currentTimeMillis();
// totalRqTime=totalRqTime+(t002-t001);
// System.out.println("getObservedSndNcUairDataGeneric data query alone took "+(t002-t001)+"ms");
// totalRqTime = totalRqTime + (t002 - t001);
System.out
.println("getObservedSndNcUairDataGeneric data query alone took "
+ (t002 - t001) + "ms");
if (result != null) {
long t003 = System.currentTimeMillis();
@ -1181,7 +1210,8 @@ public class ObservedSoundingQuery {
.add(pickedUairRecords
.toArray(new NcUairRecord[pickedUairRecords
.size()]));
// System.out.println("getObservedSndNcUairDataGeneric Number of records in PF="
// System.out
// .println("getObservedSndNcUairDataGeneric Number of records in PF="
// + pickedUairRecords.size());
}
}
@ -1189,16 +1219,36 @@ public class ObservedSoundingQuery {
}
long t004 = System.currentTimeMillis();
// System.out.println(" sorting return records took "+(t004-t003)+"ms");
System.out.println(" sorting return records took "
+ (t004 - t003) + "ms");
}
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println("getObservedSndNcUairDataGeneric Number profiles (record[]s) in finalRecordArrayList="+finalRecordArrayList.size());
// System.out
// .println("getObservedSndNcUairDataGeneric Number profiles (record[]s) in finalRecordArrayList="
// + finalRecordArrayList.size());
return finalRecordArrayList;
}
private static boolean isMandatoryLevel(String level) {
if (level == null) {
return false;
}
// alternate: final String mandatoryLevels =
// ".surface.1000.925.850.700.500.400.300.250.200.150.100.mb";
// return mandatoryLevels.contains/* IgnoreCase */("." + level + ".");
final String[] mandatoryLevels = { /* "surface", */"1000", "925",
"850", "700", "500", "400", "300", "250", "200", "150", "100" };
for (String s : mandatoryLevels) {
if (s.equals/* IgnoreCase */(level)) {
return true;
}
}
return false;
}
/*
* This method query ONE station's specific one dataType data only
*

View file

@ -47,7 +47,7 @@ import java.util.Set;
* 17-May-2011 M. Li Created a parseCINT to simplify CINT parsing.
* 07-Apr-2014 TTR-938 D.Sushon Added check for null string to constructor, fixing NullPointerException
* thrown when attempting to initialize with null String.
*
* 09-Sep-2014 TTR-852 A.Yuk remove restriction of contour lines =50 and make it unlimited contour lines.
*
* </pre>
*
@ -56,7 +56,7 @@ import java.util.Set;
* @see $GEMPAK/help/hlx/cint.hl2
*/
public class CINT {
/** The object responsible for parsing the CINT string */
private ContourStringParser cintParser;
@ -396,20 +396,44 @@ public class CINT {
if (interval == null || interval.isNaN()) {
interval = (cmax - cmin) / 10.0;
}
// Only allow less than 50 contour levels
if ((cmax - cmin) / interval > 50)
interval = (cmax - cmin) / 50;
// System.out.println(" cmax=="+cmax);
// Only allow less than 50 contour levels :
// comment out contour restriction. : IT WAs BAD Code to generate decimal point on contour labels.
/* if ((cmax - cmin) / interval > 50) {
interval = (cmax - cmin) / 50;
interval =(double) (int) ((cmax - cmin)/50) ; }
*/
contourInfo = new CINT(interval.toString() + "/"
+ cmin.toString() + "/" + cmax.toString());
cvalues = contourInfo
.getUniqueSortedContourValuesFromAllZoomLevels();
.getUniqueSortedContourValuesFromAllZoomLevels();
}
}
/********************************
int csize=cvalues.size();
System.out.println(" .................");
System.out.println(" .................");
System.out.println(" Contour level range is from "+cvalues.get(0)+" to "+cvalues.get(csize-1)+".");
System.out.println(" Contour interval "+interval+".");
System.out.println(" .................");
System.out.println(" .................");
// * capped contour lines to 50
if (csize > 50) {
System.out.println(" !!! Pay attention to CONTOUR INTERVAL.");
System.out.println(" Contour lines from "+cvalues.get(0)+" to "+cvalues.get(csize-1)+" are eliminated due to maximum contour allowance." );
while (cvalues.size()>50){cvalues.remove(50);}
System.out.println(" !!! Contours are being plotted to the first 50th lines.");
System.out.println(" Range of contour lines drawn is from "+cvalues.get(0)+" to "+cvalues.get(49)+".");
System.out.println(" !!! Contour lines are capped due to allowance of maximum contour lines of 50. ");
}
}
return cvalues;
System.out.println(" Contour level = "+cvalues.toString()+".");
***************************/
while (cvalues.size()>50){cvalues.remove(50);}
int csize=cvalues.size();
System.out.println(" Contour lines("+csize+ ") from "+cvalues.get(0)+" to "+cvalues.get(csize-1));
return cvalues;
}
/** @return boolean isCINTStringParsed */
@ -652,3 +676,4 @@ public class CINT {
}
}

View file

@ -4,53 +4,45 @@ import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import org.eclipse.swt.graphics.RGB;
/**
* TITLE is the title color, title line, and title string separated by slashes:
*
* title color / title line location / title string | short title
*
* If the title color is 0, a title is not plotted.
*
* The title line specifies the line on which the title will be written.
* The value of the title line has the following meanings:
*
* 0 bottom line
* -n n lines from bottom
* +n n lines from top
*
* If the line is not specified, the default is program dependent.
*
* The title string is the title to be written. If no title string is
* specified, a default title will be determined by the program.
*
* In the grid display programs, special characters will be replaced
* as follows:
* ^ Forecast date/time
* ~ Valid date/time
* @ Vertical level
* _ Grid function
* $ Nonzero scaling factor
* # Grid point location
* ? Day of the week flag
*
* If the information for which a character stands is not applicable to
* the program, nothing is output in its place. Zero values of the
* scaling factor are not displayed.
*
* If the "?" is included the abbreviated day of the week is added to the
* beginning of the date/time string. The day of the week flag must always
* be used in combination with either special character for specifying the
* date/time string. The result is the day of the week for the valid date/time.
*
* A short title may also be input by the user after a |. This is used
* to label the metafile frame in the NC device driver. If the short title
* is blank, a suitable label is generated for the frame. The day of the
* week is not included in the short title.
*
*
* TITLE is the title color, title line, and title string separated by slashes:
*
* title color / title line location / title string | short title
*
* If the title color is 0, a title is not plotted.
*
* The title line specifies the line on which the title will be written. The
* value of the title line has the following meanings:
*
* 0 bottom line -n n lines from bottom +n n lines from top
*
* If the line is not specified, the default is program dependent.
*
* The title string is the title to be written. If no title string is specified,
* a default title will be determined by the program.
*
* In the grid display programs, special characters will be replaced as follows:
* ^ Forecast date/time ~ Valid date/time @ Vertical level _ Grid function $
* Nonzero scaling factor # Grid point location ? Day of the week flag
*
* If the information for which a character stands is not applicable to the
* program, nothing is output in its place. Zero values of the scaling factor
* are not displayed.
*
* If the "?" is included the abbreviated day of the week is added to the
* beginning of the date/time string. The day of the week flag must always be
* used in combination with either special character for specifying the
* date/time string. The result is the day of the week for the valid date/time.
*
* A short title may also be input by the user after a |. This is used to label
* the metafile frame in the NC device driver. If the short title is blank, a
* suitable label is generated for the frame. The day of the week is not
* included in the short title.
*
*
* <p>
*<pre>
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
@ -58,107 +50,85 @@ import org.eclipse.swt.graphics.RGB;
* Nov 22,2010 X. Guo Check title old syntax with ^ and ~
* Mar 06,2013 683 Xiaochuan Handle 2 digit number for the colors
* set in title. Using default color when color
* number over 32.
*
* number over 32.
*
* </pre>
*
* @author xguo
* @version 1
* @see $GEMPAK/help/hlx/title.hl2
* @see $GEMPAK/help/hlx/title.hl2
*/
public class TITLE {
//Title Color
private RGB titleColor = new RGB(255, 0, 0);
//Title Line Location
private int titleLineLocation = 0;
// Title String
private String titleString = null;
public TITLE (String titleString) {
parseTitleString (titleString);
}
private void parseTitleString (String title) {
int col = 0;
String expression_1 = "[-+]?[0-9]";
String expression_2 = "[-+]?[0-9]{2}";
String tmp;
int colors_size = GempakColor.values().length;
if (title == null || title.trim().length() <= 0) return;
/*
* check '/' character in the title string and handle the current format
*/
if ( title.indexOf('/') >= 0 ) {
String[] titleStr = title.trim().split("/");
if ( titleStr.length >= 1 && titleStr[0] != null &&
titleStr[0].trim().length() > 0) {
tmp = titleStr[0].trim();
if ( tmp.matches(expression_1) || tmp.matches(expression_2)) {
col = Integer.valueOf(tmp);
}
}
if ( col > 0 && col <= colors_size) {
titleColor = GempakColor.convertToRGB(col);
}
else { // use white color when the number over size of GempakColor
titleColor = GempakColor.convertToRGB(1);
}
if ( titleStr.length >= 2 && titleStr[1] != null &&
titleStr[1].trim().length() > 0) {
tmp = titleStr[1].trim();
if ( tmp.matches(expression_1)) {
titleLineLocation = Integer.valueOf(tmp);
}
}
if ( titleStr.length >= 3 && titleStr[2] != null &&
titleStr[2].trim().length() > 0) {
titleString = checkOldTitleSyntax(titleStr[2].trim());
}
else {
titleString = "~ @ _$";
}
}
else {//use white color and whole string
titleColor = GempakColor.convertToRGB(1);
titleString = title.trim();
}
}
// Title Color
private RGB titleColor = new RGB(255, 0, 0);
/**
* Check for old syntax with ^ and ~
* @return String
*/
private String checkOldTitleSyntax ( String title ) {
String ttlstr = title;
int pos = ttlstr.indexOf('^');
if ( (ttlstr.charAt(0) == '~') && (pos > 0)) {
String tmpStr = ttlstr.substring(1,ttlstr.length());
pos --;
while ( pos > 0 ) {
tmpStr = tmpStr.substring(0, pos-1) + "~" + tmpStr.substring(pos + 1, tmpStr.length());
pos = tmpStr.indexOf('^');
}
ttlstr = tmpStr;
}
return ttlstr;
}
public RGB getTitleColor() {
return titleColor;
}
// Title Line Location
private int titleLineLocation = 0;
public int getTitleLineLoaction() {
return titleLineLocation;
}
// Title String
private String titleString = null;
public String getTitleString () {
return titleString;
}
public TITLE(String titleString) {
parseTitleString(titleString);
}
private void parseTitleString(String title) {
int col = 0;
String expression_1 = "[-+]?[0-9]";
String expression_2 = "[-+]?[0-9]{2}";
String tmp;
int colors_size = GempakColor.values().length;
if (title == null || title.trim().length() <= 0)
return;
/*
* check '/' character in the title string and handle the current format
*/
if (title.indexOf('/') >= 0) {
String[] titleStr = title.trim().split("/");
if (titleStr.length >= 1 && titleStr[0] != null
&& titleStr[0].trim().length() > 0) {
tmp = titleStr[0].trim();
if (tmp.matches(expression_1) || tmp.matches(expression_2)) {
col = Integer.valueOf(tmp);
}
}
if (col > 0 && col <= colors_size) {
titleColor = GempakColor.convertToRGB(col);
} else { // use white color when the number over size of GempakColor
titleColor = GempakColor.convertToRGB(1);
}
if (titleStr.length >= 2 && titleStr[1] != null
&& titleStr[1].trim().length() > 0) {
tmp = titleStr[1].trim();
if (tmp.matches(expression_1)) {
titleLineLocation = Integer.valueOf(tmp);
}
}
if (titleStr.length >= 3 && titleStr[2] != null
&& titleStr[2].trim().length() > 0) {
titleString = titleStr[2].trim();
} else {
titleString = "~ @ _$";
}
} else {// use white color and whole string
titleColor = GempakColor.convertToRGB(1);
titleString = title.trim();
}
}
public RGB getTitleColor() {
return titleColor;
}
public int getTitleLineLoaction() {
return titleLineLocation;
}
public String getTitleString() {
return titleString;
}
}

View file

@ -840,7 +840,7 @@
<Color red="255" green="255" blue="0" alpha="255"/>
<Point Lat="39.35390746604257" Lon="-73.2133975036754"/>
</Vector>
<Track skipFactorTextString="0" setTimeButtonSelected="true" pgenType="STORM_TRACK" pgenCategory="Track" lineWidth="1.0" intervalTimeTextString="01:00" intervalComboSelectedIndex="2" initialMarker="FILLED_DIAMOND" initialLinePattern="LINE_SOLID" fontStyleComboSelectedIndex="2" fontSizeComboSelectedIndex="2" fontSize="14.0" fontNameComboSelectedIndex="0" fontName="Courier" extrapMarker="FILLED_TRIANGLE" extrapLinePattern="LINE_SOLID" extraPointTimeDisplayOptionName="SKIP_FACTOR">
<Track skipFactorTextString="0" setTimeButtonSelected="true" pgenType="STORM_TRACK" pgenCategory="Track" lineWidth="1.0" intervalTimeTextString="00:30" intervalComboSelectedIndex="2" initialMarker="FILLED_DIAMOND" initialLinePattern="LINE_SOLID" fontStyleComboSelectedIndex="1" fontStyle="BOLD" fontSizeComboSelectedIndex="2" fontSize="14.0" fontNameComboSelectedIndex="0" fontName="Courier" extrapMarker="FILLED_TRIANGLE" extrapLinePattern="LINE_SOLID" extraPointTimeDisplayOptionName="SKIP_FACTOR">
<initialColor>
<Color red="255" green="0" blue="0" alpha="255"/>
</initialColor>

View file

@ -803,7 +803,7 @@
<Color red="255" green="255" blue="0" alpha="255"/>
<Point Lat="39.35390746604257" Lon="-73.2133975036754"/>
</Vector>
<Track skipFactorTextString="0" setTimeButtonSelected="true" pgenType="STORM_TRACK" pgenCategory="Track" lineWidth="1.0" intervalTimeTextString="01:00" intervalComboSelectedIndex="2" initialMarker="FILLED_DIAMOND" initialLinePattern="LINE_SOLID" fontStyleComboSelectedIndex="2" fontSizeComboSelectedIndex="2" fontSize="14.0" fontNameComboSelectedIndex="0" fontName="Courier" extrapMarker="FILLED_TRIANGLE" extrapLinePattern="LINE_SOLID" extraPointTimeDisplayOptionName="SKIP_FACTOR">
<Track skipFactorTextString="0" setTimeButtonSelected="true" pgenType="STORM_TRACK" pgenCategory="Track" lineWidth="1.0" intervalTimeTextString="00:30" intervalComboSelectedIndex="2" initialMarker="FILLED_DIAMOND" initialLinePattern="LINE_SOLID" fontStyleComboSelectedIndex="1" fontStyle="BOLD" fontSizeComboSelectedIndex="2" fontSize="14.0" fontNameComboSelectedIndex="0" fontName="Courier" extrapMarker="FILLED_TRIANGLE" extrapLinePattern="LINE_SOLID" extraPointTimeDisplayOptionName="SKIP_FACTOR">
<initialColor>
<Color red="255" green="0" blue="0" alpha="255"/>
</initialColor>

View file

@ -18,6 +18,7 @@
E. Safford/SAIC 06/07 rm "...UPDT TO CANCEL..."
B. Yin/SAIC 02/08 add tag number after cancellation
B. Yin 12/11 added new line for 'New' or 'Cor'
J. Wu 09/14 added new line for 'CAN'
-->
<xsl:template name="GetAttentionLine">
<xsl:param name="status"></xsl:param>
@ -25,14 +26,16 @@
<xsl:choose>
<xsl:when test="contains( $status, 'CAN')"> <!-- Cancel lines -->
<xsl:when test="contains( $status, 'CAN')"> <!-- Cancel lines -->
<xsl:element name="line"><xsl:attribute name="indent">0</xsl:attribute>
<xsl:choose>
<xsl:when test="contains( $airmet_outlook, 'AIRMET')">
<xsl:value-of select="$newline"/>
<xsl:text>CANCEL AIRMET. CONDS HV ENDED.</xsl:text>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$newline"/>
<xsl:text>CANCEL OUTLOOK.</xsl:text>
</xsl:otherwise>
</xsl:choose>

View file

@ -20,15 +20,19 @@
B. Yin/SAIC 08/06 distinguish smear and outlook
B. Yin/Chugach 12/11 changed 'Status' to 'issueType'
changed for-each condition for smears
J. Wu/SGT 10/14 TTR 714 - go through all smears (airmets & outlooks) in
one loop since the input XML format is different from
those in NMAP2
-->
<xsl:template name="GetStatus">
<xsl:param name="haz1">NO HAZARD1</xsl:param>
<xsl:param name="haz2">NO HAZARD2</xsl:param>
<xsl:param name="haz3">NO HAZARD3</xsl:param>
<xsl:for-each select="//Gfa[(@hazard = $haz1 or @hazard = $haz2 or @hazard = $haz3) and contains(@fcstHr,'-') and @isOutlook='false']">
<!-- <xsl:for-each select="//Gfa[(@hazard = $haz1 or @hazard = $haz2 or @hazard = $haz3) and contains(@fcstHr,'-') and @isOutlook='false']">
-->
<xsl:for-each select="//Gfa[(@hazard = $haz1 or @hazard = $haz2 or @hazard = $haz3) and contains(@fcstHr,'-') ]">
<xsl:if test="contains( @hazard, $haz1 ) or contains( @hazard, $haz2 ) or contains( @hazard, $haz3 )">
<xsl:choose>
<xsl:when test="@issueType = 'CAN'">
@ -46,8 +50,9 @@
</xsl:choose>
</xsl:if>
</xsl:for-each>
<xsl:for-each select="//outlook">
<!--
<xsl:for-each select="//outlook">
<xsl:if test="contains( hazard, $haz1 ) or contains( hazard, $haz2 ) or contains( hazard, $haz3 )">
<xsl:choose>
<xsl:when test="issueType = 'CAN'">
@ -65,7 +70,7 @@
</xsl:choose>
</xsl:if>
</xsl:for-each>
-->
</xsl:template>
<!--

View file

@ -141,15 +141,14 @@
</xsl:element>
</xsl:if>
<xsl:if test="contains( @issueType, 'CAN' ) or not(string-length($freqSevStatement) > 1)">
<!-- <xsl:if test="contains( @issueType, 'CAN' ) or not(string-length($freqSevStatement) > 1)">
<xsl:value-of select="$newline"/>
<!-- <xsl:if test="string-length($airTag) > 1">
<xsl:if test="string-length($airTag) > 1">
<xsl:element name="line">
<xsl:value-of select="$newline"/><xsl:value-of select="normalize-space($airTag)"/>.</xsl:element>
</xsl:if>
-->
</xsl:if>
-->
<!-- Add the attention line(s) -->
<xsl:call-template name="GetAttentionLine">
<xsl:with-param name="status"><xsl:value-of select="@issueType"/></xsl:with-param>

View file

@ -78,6 +78,7 @@ public abstract class AttrDlg extends Dialog implements IAttribute {
public static int ctrlBtnHeight = 28;
// public static int ctrlBtnWidth = 90;
// public static int ctrlBtnHeight = 30;
/**
@ -128,11 +129,24 @@ public abstract class AttrDlg extends Dialog implements IAttribute {
this.getButton(IDialogConstants.CANCEL_ID).setEnabled(false);
this.getButton(IDialogConstants.OK_ID).setEnabled(false);
this.getButton(IDialogConstants.CANCEL_ID).setLayoutData(
new GridData(ctrlBtnWidth, ctrlBtnHeight));
this.getButton(IDialogConstants.OK_ID).setLayoutData(
new GridData(ctrlBtnWidth, ctrlBtnHeight));
setDefaultControlButtonSize();
}
/**
* Set default size for control buttons.
*/
public void setDefaultControlButtonSize() {
setButtonSize(ctrlBtnWidth, ctrlBtnHeight);
}
/**
* Set size for control buttons.
*/
public void setButtonSize(int width, int height) {
this.getButton(IDialogConstants.CANCEL_ID).setLayoutData(
new GridData(width, height));
this.getButton(IDialogConstants.OK_ID).setLayoutData(
new GridData(width, height));
}
@Override

View file

@ -3169,6 +3169,10 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
private PgenContoursTool tool = null;
private Contours prevCont = null;
private Contours nowCont = null;
private ContourMinmaxAttrDlg(Shell parShell) throws VizException {
super(parShell);
@ -3238,11 +3242,54 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
if (apt instanceof PgenContoursTool) {
tool = (PgenContoursTool) apt;
}
if (tool != null) {
tool.resetUndoRedoCount();
PgenSession.getInstance().getCommandManager()
.addStackListener(tool);
}
// set the lat/lon from the current symbol.
DrawableElement de = drawingLayer.getSelectedDE();
if (de != null && de.getParent() instanceof ContourMinmax
&& de instanceof Symbol) {
super.setLatitude(((Symbol) de).getLocation().y);
super.setLongitude(((Symbol) de).getLocation().x);
}
/*
* Reset the listenser.
*/
for (Listener ls : undoBtn.getListeners(SWT.MouseDown)) {
undoBtn.removeListener(SWT.MouseDown, ls);
}
undoBtn.addListener(SWT.MouseDown, new Listener() {
@Override
public void handleEvent(Event event) {
if (undoBtn.getText().equalsIgnoreCase(UNDO_SYMBOL)) {
undoBtn.setText(REDO_SYMBOL);
drawingLayer.getCommandMgr().undo();
} else if (undoBtn.getText().equalsIgnoreCase(REDO_SYMBOL)) {
undoBtn.setText(UNDO_SYMBOL);
drawingLayer.getCommandMgr().redo();
}
/*
* Reset the currentContours for the ContoursAttrDlg.
*/
currentContours = prevCont;
prevCont = nowCont;
nowCont = currentContours;
mapEditor.refresh();
}
});
}
@Override
@ -3252,6 +3299,10 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
PgenSession.getInstance().getCommandManager()
.removeStackListener(tool);
}
prevCont = null;
nowCont = null;
return super.close();
}
@ -3262,15 +3313,34 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
protected void placeSymbol() {
if (tool != null) {
if (tool.getMouseHandler() instanceof PgenContoursHandler) {
/*
* Keep a copy of currentConoturs for "Undo". It chnages
* after call the "tool".
*/
prevCont = currentContours;
((PgenContoursHandler) tool.getMouseHandler())
.drawContourMinmax(new Coordinate(Double
.parseDouble(longitudeText.getText()),
Double.parseDouble(latitudeText.getText())));
placeBtn.setEnabled(false);
nowCont = currentContours; // Keep a copy for "Redo"
undoBtn.setEnabled(true);
undoBtn.setText("Undo Symbol");
((PgenContoursHandler) tool.getMouseHandler())
.drawContourMinmax(new Coordinate(Double
.parseDouble(longitudeText.getText()), Double
.parseDouble(latitudeText.getText())));
placeBtn.setEnabled(false);
undoBtn.setEnabled(true);
undoBtn.setText("Undo Symbol");
} else if (tool.getMouseHandler() instanceof PgenSelectHandler) {
minmaxTemplate = (gov.noaa.nws.ncep.ui.pgen.elements.Symbol) new DrawableElementFactory()
.create(DrawableType.SYMBOL, (IAttribute) this,
"Symbol", getActiveSymbolObjType(),
(Coordinate) null, null);
contoursAttrSettings.put(getActiveSymbolObjType(),
minmaxTemplate);
updateMinmaxAttributes();
placeBtn.setEnabled(false);
}
}
}
}
@ -3330,7 +3400,34 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
if (newEl != null && oldAdc.equals(de.getParent())) {
newEl.setParent(newAdc);
if (newEl instanceof Symbol) {
if (minmaxAttrDlg != null
&& minmaxAttrDlg.getShell() != null) {
if (minmaxAttrDlg.latitudeText.isEnabled()
&& minmaxAttrDlg.longitudeText
.isEnabled()) {
ArrayList<Coordinate> loc = new ArrayList<Coordinate>();
double lat = ((Symbol) newEl).getLocation().y;
double lon = ((Symbol) newEl).getLocation().x;
try {
lon = Double
.valueOf(minmaxAttrDlg.longitudeText
.getText());
lat = Double
.valueOf(minmaxAttrDlg.latitudeText
.getText());
} catch (Exception e) {
lon = ((Symbol) newEl).getLocation().x;
lat = ((Symbol) newEl).getLocation().y;
}
loc.add(new Coordinate(lon, lat));
newEl.setPoints(loc);
}
}
((DECollection) newAdc)
.replace(((ContourMinmax) newAdc)
.getSymbol(), newEl);
@ -3338,6 +3435,8 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
((ContourMinmax) newAdc).getSymbol().update(
minmaxTemplate);
((ContourMinmax) newAdc).getLabel().setAuto(true);
}
}
@ -3926,4 +4025,15 @@ public class ContoursAttrDlg extends AttrDlg implements IContours,
return typeChanged;
}
/**
* Update lat/lon and Undo button on SymbolAttrDlg.
*/
public void updateSymbolAttrOnGUI(Coordinate loc) {
if (minmaxAttrDlg != null && minmaxAttrDlg.getShell() != null) {
minmaxAttrDlg.setLatitude(loc.y);
minmaxAttrDlg.setLongitude(loc.x);
minmaxAttrDlg.enableUndoBtn(true);
}
}
}

View file

@ -68,9 +68,6 @@ import com.raytheon.uf.viz.core.exception.VizException;
*/
public class GfaFormatAttrDlg extends AttrDlg {
// private final static Logger logger =
// Logger.getLogger(GfaFormatAttrDlg.class);
private static final String ZULU = "ZULU";
private static final String TANGO = "TANGO";
@ -151,7 +148,6 @@ public class GfaFormatAttrDlg extends AttrDlg {
instance = new GfaFormatAttrDlg(parShell);
} catch (VizException e) {
// logger.error(e);
e.printStackTrace();
}
}
@ -306,12 +302,14 @@ public class GfaFormatAttrDlg extends AttrDlg {
@Override
public void createButtonsForButtonBar(Composite parent) {
super.createButtonsForButtonBar(parent);
this.getButton( OK_ID ).setText( SAVE_LABEL );
this.getButton( CANCEL_ID).setText( CANCEL_LABEL );
super.createButtonsForButtonBar(parent);
this.getButton(OK_ID).setText(SAVE_LABEL);
this.getButton(CANCEL_ID).setText(CANCEL_LABEL);
}
// createButton(parent, OK_ID, SAVE_LABEL, true);
// createButton(parent, CANCEL_ID, CANCEL_LABEL, false);
@Override
public void setDefaultControlButtonSize() {
setButtonSize(ctrlBtnWidth + 50, ctrlBtnHeight);
}
@Override

View file

@ -101,6 +101,9 @@ import com.vividsolutions.jts.geom.Polygon;
* 03/13 #928 B. Yin Made the button bar smaller.
* 04/13 #977 S. Gilbert PGEN Database support
* 09/13 TTR656 J. Wu Display for INTL_SIGMET converted from VGF.
* 09/14 TTR974 J. Wu update "editableAttrFromLine" in "setSigmet()".
* 10/14 TTR433 J. Wu Set input verification/output format for Phenom Lat/Lon.
* 10/14 TTR722 J. Wu Display TC center/Movement/FL level for ISOLATED TC.
* </pre>
*
* @author gzhang
@ -209,6 +212,16 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
private HashMap<Control, Control[]> controlEnablerMap = new HashMap<Control, Control[]>();
/**
* Colors to indicate if Phenom lat/lon input is in correct format.
*/
private final Color wrongFormatColor = Color.red;
private final Color rightFormatColor = Color.green;
/**
* Constructor.
*/
protected SigmetAttrDlg(Shell parShell) throws VizException {
super(parShell);
}
@ -764,11 +777,19 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
@Override
public void focusLost(FocusEvent e) {
if (SigmetAttrDlg.this.getEditableAttrPhenomLat() != null)
if (SigmetAttrDlg.this.getEditableAttrPhenomLat() != null) {
txtPheLat.setText(SigmetAttrDlg.this
.getEditableAttrPhenomLat());
else
txtPheLat.setText("???");
setBackgroundColor(txtPheLat, rightFormatColor);
} else {
/*
* "???" causes inconvenience for copy/paste. Instead,
* use Color as hint.
*/
// txtPheLat.setText("???");
txtPheLat.setText("");
setBackgroundColor(txtPheLat, wrongFormatColor);
}
}
});
@ -796,11 +817,19 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
@Override
public void focusLost(FocusEvent e) {
if (SigmetAttrDlg.this.getEditableAttrPhenomLon() != null)
if (SigmetAttrDlg.this.getEditableAttrPhenomLon() != null) {
txtPheLon.setText(SigmetAttrDlg.this
.getEditableAttrPhenomLon());
else
txtPheLon.setText("???");
setBackgroundColor(txtPheLon, rightFormatColor);
} else {
/*
* "???" causes inconvenience for copy/paste. Instead,
* use Color as hint.
*/
// txtPheLon.setText("???");
txtPheLon.setText("");
setBackgroundColor(txtPheLon, wrongFormatColor);
}
}
});
@ -1397,8 +1426,8 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
.getPoints().toArray(new Coordinate[] {});
/*
* Added "trim()" since SIGMETs VGFs has no "editableAttrFromLine" and it is
* defaulted as " " when converted into XML - (J. Wu).
* Added "trim()" since SIGMETs VGFs has no "editableAttrFromLine"
* and it is defaulted as " " when converted into XML - (J. Wu).
*/
if (coors != null) {
if (editableAttrFromLine == null
@ -1522,7 +1551,6 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
private String convertTimeStringPlusHourInHMS(String timeString,
int plusHour, boolean dayNeeded) {
Calendar c = Calendar.getInstance();
System.out.println("____________timeString: " + timeString);
c.set(Calendar.DAY_OF_MONTH,
Integer.parseInt(timeString.substring(0, 2)));
c.set(Calendar.HOUR_OF_DAY,
@ -1996,14 +2024,14 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
@Override
public void createButtonsForButtonBar(Composite parent) {
((GridLayout) parent.getLayout()).verticalSpacing = 0;
((GridLayout) parent.getLayout()).marginHeight = 3;
((GridLayout) parent.getLayout()).verticalSpacing = 0;
((GridLayout) parent.getLayout()).marginHeight = 3;
createButton(parent, IDialogConstants.OK_ID, "Save", true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
getButton(IDialogConstants.OK_ID).setLayoutData(
new GridData(ctrlBtnWidth, ctrlBtnHeight));
getButton(IDialogConstants.CANCEL_ID).setLayoutData(
@ -2204,18 +2232,25 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
Sigmet sig = ((Sigmet) SigmetAttrDlg.this.drawingLayer
.getSelectedDE());
if (SigmetAttrDlg.this.ISOLATED.equals(sig.getType())) {
/*
* TTR 722 - This "if" causes "ISOLATED" TC center not
* displaying. So we commented it out.
*
* if (SigmetAttrDlg.this.ISOLATED.equals(sig.getType())) {
* sb.append(" ").append("NEAR"); //
* sb.append(" ").append(sig.getLinePoints()[0].y); //
* sb.append(" ").append(sig.getLinePoints()[0].x); } else {
*/
if (SigmetAttrDlg.this.getEditableAttrPhenomLat() != null
&& SigmetAttrDlg.this.getEditableAttrPhenomLon() != null) {
sb.append(" ").append("NEAR");
// sb.append(" ").append(sig.getLinePoints()[0].y);
// sb.append(" ").append(sig.getLinePoints()[0].x);
} else {
if ( SigmetAttrDlg.this.getEditableAttrPhenomLat() != null
&& SigmetAttrDlg.this.getEditableAttrPhenomLon() != null ) {
sb.append(" ").append("NEAR");
sb.append(" ").append(SigmetAttrDlg.this.getEditableAttrPhenomLat());
sb.append(SigmetAttrDlg.this.getEditableAttrPhenomLon());
}
sb.append(" ").append(
SigmetAttrDlg.this.getEditableAttrPhenomLat());
sb.append(" ").append(
SigmetAttrDlg.this.getEditableAttrPhenomLon());
}
// }
sb.append(" ").append("AT ");
sb.append(getTimeStringPlusHourInHMS(0).substring(0, 4));// C
@ -2227,6 +2262,11 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
// --------------- movement
String movement = SigmetAttrDlg.this.getEditableAttrMovement();
if (movement == null) {
movement = "STNRY";
}
if ("STNRY".equals(movement)) {
sb.append(" ").append("STNR. ");
} else if ("MVG".equals(movement)) {
@ -2292,7 +2332,8 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
String tops = SigmetAttrDlg.this.getEditableAttrLevel();
if ("FCST".equals(tops) || isTropCyc) {
if ("FCST".equals(tops)) {
// if ("FCST".equals(tops) || isTropCyc) {
sb.append(tops.equals("-none-") ? "" : tops).append(" ");
sb.append(SigmetAttrDlg.this.getEditableAttrLevelInfo1())
.append(" ");
@ -2339,7 +2380,7 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
sb.append(" ").append("NM CENTER.");
} else {
sb.append(" ").append("WI ");
sb.append((int)SigmetAttrDlg.this.getWidth());
sb.append((int) SigmetAttrDlg.this.getWidth());
sb.append(" ").append("NM OF ");
for (int i = 0; i < lineArray.length - 1; i++)
sb.append(" ").append(lineArray[i]);
@ -2363,7 +2404,7 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
} else {// line with LINE_SEPERATER
sb.append(" ").append("WI ");
sb.append((int)SigmetAttrDlg.this.getWidth());
sb.append((int) SigmetAttrDlg.this.getWidth());
sb.append(" ").append("NM ");
sb.append(getLineTypeForSOL(lineType));// [lineArray.length-2]);//watch
// out for index
@ -2648,9 +2689,15 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
// ((Sigmet)sigmet).getType() ) );
}
}
if (txtInfo != null && !txtInfo.isDisposed() && s != null)
this.resetText(s, txtInfo);
// TTR 974 - "editableAttrFromLine" needs update as well.
if (sigmet != null && s != null) {
((Sigmet) sigmet).setEditableAttrFromLine(s);
}
}
private void init() {
@ -2787,9 +2834,45 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
withExpandedArea = false;// ???
}
/*
* This method validates the input lat or lon are in the specified formats
* as below since AWC receives info in various formats from TACs around the
* world) and be convertyed later into specified formats.
*
* This a new requirement from AWC as described in AWC Sept 2014 FIT test
* report for TTR 433 - J. Wu, Oct. 7th, 2014.
*
* "N", "S", and "" are literal; "dd" or "ddd" is degree; "mm" is minute;
* "p" is decimal degree; "(d)" is an optional degree longitude digit for
* longitudes with absolute value >= 100.0):
*
* A) "Phenom Lat" text box accepts a latitude north: Nddmm, ddmmN, dd.pN,
* Ndd.p, dd.p; Output is Nddmm.
*
* B)"Phenom Lat" text box accepts a latitude south: Sddmm, ddmmS, dd.pS,
* Sdd.p, dd.p; Output is Sddmm.
*
* C)"Phenom Lon" text box accepts a longitude west: W(d)ddmm, (d)ddmmW,
* (d)dd.pW, W(d)dd.p, -(d)dd.p; Output is W[0|1]ddmm.
*
* D)"Phenom Lon" text box accepts a longitude east: E(d)ddmm, (d)ddmmE,
* (d)dd.pE, E(d)dd.p, (d)dd.p; Output is E[0|1]ddmm.
*
* Note:
*
* (1) "N", "S", "E", "W" is not case-sensitive.
*
* (2) "N"/"S"/"E"/"W" should have been stripped of before sending in here.
*
* (3) A "-" should be placed at the beginning if "S" or "W" found in the
* input.
*/
private boolean validateLatLon(String coor, boolean isLat) {
String regexLat = "(-?[0-8]?[0-9](\\.\\d*)?)|-?90(\\.[0]*)?";
String regexLon = "(-?([1]?[0-7][1-9]|[1-9]?[0-9])?(\\.\\d*)?)|-?180(\\.[0]*)?";
// String regexLat = "(-?[0-8]?[0-9](\\.\\d*)?)|-?90(\\.[0]*)?";
// String regexLon =
// "(-?([1]?[0-7][1-9]|[1-9]?[0-9])?(\\.\\d*)?)|-?180(\\.[0]*)?";
String regexLat = "(-?[0-8]?[0-9](\\.)?(\\d*)?)|-?90(\\.)?([0]*)?";
String regexLon = "(-?([1]?[0-7][0-9]|[0]?[0-9]?[0-9])?(\\.)?(\\d*)?)|-?180(\\.)?([0]*)?";
java.util.regex.Matcher m;
if (isLat) {
@ -2860,11 +2943,13 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
Coordinate coor = coors[i];
result.append(coor.y >= 0 ? "N" : "S");
long y = ((int) Math.abs(coor.y)*100) + Math.round( Math.abs(coor.y-(int)(coor.y))*60);
long y = ((int) Math.abs(coor.y) * 100)
+ Math.round(Math.abs(coor.y - (int) (coor.y)) * 60);
result.append(new DecimalFormat(FOUR_ZERO).format(y));
result.append(coor.x >= 0 ? " E" : " W");
long x = ((int) Math.abs(coor.x))*100 + Math.round(Math.abs(coor.x-(int)(coor.x))*60);
long x = ((int) Math.abs(coor.x)) * 100
+ Math.round(Math.abs(coor.x - (int) (coor.x)) * 60);
result.append(new DecimalFormat(FIVE_ZERO).format(x));
@ -2943,28 +3028,143 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
return null;
}
/*
* This method validates the input lat or lon are in the specified formats
* and format it into a specfied form as described below:
*
* This a new requirement from AWC as described in AWC Sept 2014 FIT test
* report for TTR 433 - J. Wu, Oct. 7th, 2014.
*
* "N", "S", and "" are literal; "dd" or "ddd" is degree; "mm" is minute;
* "p" is decimal degree; "(d)" is an optional degree longitude digit for
* longitudes with absolute value >= 100.0):
*
* A) "Phenom Lat" text box accepts a latitude north: Nddmm, ddmmN, dd.pN,
* Ndd.p, dd.p; Output is Nddmm.
*
* B)"Phenom Lat" text box accepts a latitude south: Sddmm, ddmmS, dd.pS,
* Sdd.p, dd.p; Output is Sddmm.
*
* C)"Phenom Lon" text box accepts a longitude west: W(d)ddmm, (d)ddmmW,
* (d)dd.pW, W(d)dd.p, -(d)dd.p; Output is W[0|1]ddmm.
*
* D)"Phenom Lon" text box accepts a longitude east: E(d)ddmm, (d)ddmmE,
* (d)dd.pE, E(d)dd.p, (d)dd.p; Output is E[0|1]ddmm.
*
* Note: "N", "S", "E", "W" is not case-sensitive here.
*/
private String getPhenomLatLon(String input, boolean isLat) {
if (input.startsWith("S") || input.startsWith("s")
|| input.startsWith("W") || input.startsWith("w")
|| input.endsWith("S") || input.endsWith("s")
|| input.endsWith("W") || input.endsWith("w"))
input = input.toUpperCase();
if ((isLat && (input.startsWith("S") || input.endsWith("S")))
|| (!isLat && (input.startsWith("W") || input.endsWith("W")))) {
input = "-" + input;
}
/*
* remove characters that is not a digit, -, or decimal point.
*/
input = input.replaceAll("[^-0-9.]", "");
/*
* Format the output to the desired form.
*/
StringBuilder result = new StringBuilder();
if (!"".equals(input) && !"-".equals(input)
&& validateLatLon(input, isLat)) {
Double value = Double.parseDouble(input);
if (isLat) {
result.append(value >= 0.0 ? "N" : "S");
double y = (double) Math.abs(value);
result.append(y);
if (!input.contains(".")) {
/*
* Padding to make lat as "ddmm" and lon as "dddmm".
*/
String istr = input.replaceAll("-", "");
int len = istr.length();
String ostr = "";
int val = Integer.parseInt(istr);
if (isLat) {
if (len == 1) {
ostr += ("0" + istr + "00");
} else if (len == 2) {
if (val <= 90)
ostr += (istr + "00");
} else if (len == 3) {
if (val <= 900)
ostr += (istr + "0");
} else {
String tmp = istr.substring(0, 4);
if (Integer.parseInt(tmp) <= 9000) {
ostr += tmp;
}
}
} else {
if (len == 1) {
ostr += ("00" + istr + "00");
} else if (len == 2) {
ostr += ("0" + istr + "00");
} else if (len == 3) {
if (val <= 180) {
ostr += (istr + "00");
} else {
ostr += ("0" + istr + "0");
}
} else if (len == 4) {
if (val > 180) {
ostr += ("0" + istr);
} else if (val >= 100) {
ostr += (val + "00");
} else if (val >= 10) {
ostr += ("0" + val + "00");
} else {
ostr += ("00" + val + "00");
}
} else {
String tmp = istr.substring(0, 5);
if (Integer.parseInt(tmp) <= 18000) {
ostr += tmp;
}
}
}
if (ostr.length() > 0) {
if (isLat) {
result.append(input.startsWith("-") ? "S" : "N");
} else {
result.append(input.startsWith("-") ? "W" : "E");
}
}
result.append(ostr);
} else {
result.append(value >= 0.0 ? " E" : " W");
double x = (double) Math.abs(value);
result.append(x);
/*
* Convert to degree and minutes and then padding to make lat as
* "ddmm" and lon as "dddmm".
*/
Double value = Double.parseDouble(input);
int deg = value.intValue();
Double minute = (Math.abs(value - deg)) * 60.0;
int mm = (int) Math.round(minute);
deg = Math.abs(deg);
if (isLat) {
result.append(value >= 0.0 ? "N" : "S");
String dstr = (deg < 10) ? ("0" + deg) : ("" + deg);
result.append(dstr);
String mstr = (mm < 10) ? ("0" + mm) : ("" + mm);
result.append(mstr);
} else {
result.append(value >= 0.0 ? "E" : "W");
String dstr = (deg < 10) ? ("00" + deg)
: ((deg < 100) ? ("0" + deg) : ("" + deg));
result.append(dstr);
String mstr = (mm < 10) ? ("0" + mm) : ("" + mm);
result.append(mstr);
}
}
return result.toString().trim();
@ -3108,4 +3308,15 @@ public class SigmetAttrDlg extends AttrDlg implements ISigmet {
this.setEditableAttrSeqNum(sig.getEditableAttrSeqNum());
}
/*
* Sets the background color for a SWT control.
*/
private void setBackgroundColor(Control ww, Color color) {
org.eclipse.swt.graphics.Color clr = new org.eclipse.swt.graphics.Color(
ww.getDisplay(), color.getRed(), color.getGreen(),
color.getBlue());
ww.setBackground(clr);
clr.dispose();
}
}

View file

@ -81,6 +81,7 @@ import com.vividsolutions.jts.io.WKBReader;
* 11/12 #873 B. Yin Pass sigmet type "CONV_SIGMET" for snapping.
* 03/13 #928 B. Yin Made the button bar smaller.
* 04/29 #977 S. Gilbert PGEN Database support
* 04/29 #726 J. Wu Remove the line breaker when saving vor list into file.
* </pre>
*
* @author gzhang
@ -538,7 +539,7 @@ public class SigmetCommAttrDlg extends AttrDlg implements ISigmet {
txtInfo = new Text(top2, style);
txtInfo.setFont(txtfont);
attrControlMap.put("editableAttrFromLine", txtInfo);
GridData gData = new GridData(600, 48);
GridData gData = new GridData(650, 48);
gData.horizontalSpan = 8;
txtInfo.setLayoutData(gData);
txtInfo.setText(this.getEditableAttrFromLine());
@ -740,13 +741,13 @@ public class SigmetCommAttrDlg extends AttrDlg implements ISigmet {
@Override
public void createButtonsForButtonBar(Composite parent) {
((GridLayout) parent.getLayout()).verticalSpacing = 0;
((GridLayout) parent.getLayout()).marginHeight = 3;
((GridLayout) parent.getLayout()).verticalSpacing = 0;
((GridLayout) parent.getLayout()).marginHeight = 3;
createButton(parent, IDialogConstants.OK_ID, "Save", true);
createButton(parent, IDialogConstants.CANCEL_ID,
IDialogConstants.CANCEL_LABEL, false);
getButton(IDialogConstants.OK_ID).setLayoutData(
new GridData(ctrlBtnWidth, ctrlBtnHeight));
getButton(IDialogConstants.CANCEL_ID).setLayoutData(
@ -775,7 +776,8 @@ public class SigmetCommAttrDlg extends AttrDlg implements ISigmet {
if (dataURI != null) {
try {
StorageUtils.storeDerivedProduct(dataURI,
txtSave.getText(), "TEXT", txtInfo.getText());
txtSave.getText(), "TEXT", txtInfo.getText()
.replaceAll("-\n", "-"));
} catch (PgenStorageException e) {
StorageUtils.showError(e);
}
@ -801,13 +803,32 @@ public class SigmetCommAttrDlg extends AttrDlg implements ISigmet {
String forecaster = System.getProperty("user.name");
ProductTime refTime = new ProductTime();
Product defaultProduct = new Product(
SigmetCommAttrDlg.this.pgenType,
SigmetCommAttrDlg.this.pgenType, forecaster, null, refTime,
layerList);
// defaultProduct.addLayer(defaultLayer);
defaultProduct.setOutputFile(SigmetCommAttrDlg.this.drawingLayer
.buildActivityLabel(defaultProduct));
String pname = SigmetCommAttrDlg.this.drawingLayer
.getActiveProduct().getName();
String ptype = SigmetCommAttrDlg.this.drawingLayer
.getActiveProduct().getType();
pname = (pname == null) ? "Default" : pname;
ptype = (ptype == null) ? "Default" : ptype;
Product defaultProduct = new Product(pname, ptype, forecaster,
null, refTime, layerList);
/*
*
* Product defaultProduct = new Product(
* SigmetCommAttrDlg.this.pgenType, SigmetCommAttrDlg.this.pgenType,
* forecaster, null, refTime, layerList);
*/
String plabel = SigmetCommAttrDlg.this.drawingLayer
.getActiveProduct().getOutputFile();
if (plabel == null) {
plabel = SigmetCommAttrDlg.this.drawingLayer
.buildActivityLabel(defaultProduct);
}
defaultProduct.setOutputFile(plabel);
// defaultProduct.setOutputFile(SigmetCommAttrDlg.this.drawingLayer
// .buildActivityLabel(defaultProduct));
defaultProduct.setCenter(PgenUtil.getCurrentOffice());
try {
@ -838,7 +859,7 @@ public class SigmetCommAttrDlg extends AttrDlg implements ISigmet {
txtInfo = new Text(top, SWT.MULTI | SWT.BORDER | SWT.READ_ONLY
| SWT.WRAP);
txtInfo.setFont(txtfont);
GridData gData = new GridData(512, 300);
GridData gData = new GridData(672, 300);
gData.horizontalSpan = 3;
txtInfo.setLayoutData(gData);
txtInfo.setText(getFileContent());
@ -1048,9 +1069,9 @@ public class SigmetCommAttrDlg extends AttrDlg implements ISigmet {
try {
stateGeo = (MultiPolygon) wkbReader.read(wkb);
} catch (Exception e) {
System.out
.println("___ Error: SigmetCommAttrDlg: getAreaString(): "
+ e.getMessage());
// System.out
// .println("___ Error: SigmetCommAttrDlg: getAreaString(): "
// + e.getMessage());
}
if (stateGeo != null) {

View file

@ -69,9 +69,27 @@ public class DefaultElementContainer extends AbstractElementContainer {
public void draw(IGraphicsTarget target, PaintProperties paintProps,
DisplayProperties dprops, boolean needsCreate) {
if ((displayEls == null) || paintProps.isZooming())
/*
* For ghost drawing - "needsCreate && dprops == null" - It is always on
* the active layer so DiaplayProperties' "filled" should be true while
* "monoColor" should be false (using the element's color).
*/
if (needsCreate && dprops == null) {
dprops = new DisplayProperties(false, null, true);
}
// For normal drawing........
if ((displayEls == null) || paintProps.isZooming()) {
needsCreate = true;
/*
* TTR971 - needs to set display properties, otherwise the layer
* color may not take effect (e.g., after switching projection)
*/
def.setLayerDisplayAttr(dprops.getLayerMonoColor(),
dprops.getLayerColor(), dprops.getLayerFilled());
}
if (paintProps.getZoomLevel() != zoomLevel) {
needsCreate = true;
zoomLevel = paintProps.getZoomLevel();
@ -102,5 +120,4 @@ public class DefaultElementContainer extends AbstractElementContainer {
}
}
}

View file

@ -144,6 +144,9 @@ import com.vividsolutions.jts.operation.distance.DistanceOp;
* 05/14 TTR 995 J. Wu Make contour label auto-placement an option.
* 07/14 ? B. Yin Added support for dashed-line circle for TCM 12 feet sea.
* 08/14 ? B. Yin Fixed world wrap for TCM track and zero circle issues.
* 08/14 TTR972 J. Wu Draw filled object as filled only if either its layer's "filled" flag
* "true" or they are on the active layer, .
* 09/14 TTR750 J. Wu Draw track label with specified font styles.
* </pre>
*
* @author sgilbert
@ -525,6 +528,7 @@ public class DisplayElementFactory {
if (isFilled) {
list.add(createFill(pts));
}
/*
* Compile each IWireframeShape, create its LineDisplayElement, and add
* to IDisplayable return list
@ -2036,8 +2040,9 @@ public class DisplayElementFactory {
Text txt = new Text(null, track.getFontName(),
track.getFontSize(), TextJustification.LEFT_JUSTIFY,
pt.getLocation(), 0.0, TextRotation.SCREEN_RELATIVE,
new String[] { dtime }, FontStyle.BOLD, iniDspClr, 0,
3, false, DisplayType.NORMAL, "Text", "General Text");
new String[] { dtime }, track.getFontStyle(),
iniDspClr, 0, 3, false, DisplayType.NORMAL, "Text",
"General Text");
temps = createDisplayElements((IText) txt, paintProps);
slist.addAll(temps);
}
@ -2094,8 +2099,9 @@ public class DisplayElementFactory {
Text txt = new Text(null, track.getFontName(),
track.getFontSize(), TextJustification.LEFT_JUSTIFY,
pt.getLocation(), 0.0, TextRotation.SCREEN_RELATIVE,
new String[] { dtime }, FontStyle.BOLD, expDspClr, 0,
3, false, DisplayType.NORMAL, "Text", "General Text");
new String[] { dtime }, track.getFontStyle(),
expDspClr, 0, 3, false, DisplayType.NORMAL, "Text",
"General Text");
temps = createDisplayElements((IText) txt, paintProps);
slist.addAll(temps);
}
@ -4815,10 +4821,22 @@ public class DisplayElementFactory {
*/
private boolean getDisplayFillMode(Boolean filled) {
if (layerFilled) {
return layerFilled;
/*
* if (layerFilled) { return layerFilled; } else { return filled; }
*/
/*
* TTR 972 - to match NMAP2 behavior, non-filled elements will always be
* drawn as non-filled. Filled objects should be drawn as filled only
* when the "filled" flag for its layer is set to "true" or they are on
* the active layer, so it is necessary to set the "layerFilled" flag to
* true before generating displayables for such objects (see
* PgenResource.drawFilledElement()).
*/
if (filled && layerFilled) {
return true;
} else {
return filled;
return false;
}
}

View file

@ -7,118 +7,134 @@
*/
package gov.noaa.nws.ncep.ui.pgen.display;
import gov.noaa.nws.ncep.ui.pgen.display.IText.FontStyle;
import java.awt.Color;
import java.util.Calendar;
import gov.noaa.nws.ncep.ui.pgen.display.IText.FontStyle;
/**
* Interface used to get specific attributes of a PGEN Storm track object.
*
* @author sgilbert
*
*
*/
public interface ITrack extends ILine{
public interface ITrack extends ILine {
/**
* this enum stores the time display options for extra points
*/
public static enum ExtraPointTimeDisplayOption { SKIP_FACTOR, SHOW_FIRST_LAST, ON_ONE_HOUR, ON_HALF_HOUR };
/**
* this enum stores the time display options for extra points
*/
public static enum ExtraPointTimeDisplayOption {
SKIP_FACTOR, SHOW_FIRST_LAST, ON_ONE_HOUR, ON_HALF_HOUR
};
// /**
// * Defines available font styles
// * @return font style
// */
// public static enum FontStyle {
// REGULAR, BOLD, ITALIC, BOLD_ITALIC
// }
/**
* Gets a font style for text of track points
*/
public FontStyle getFontStyle() ;
/**
* Fets a boolean array that indicates if a time text of a extra point should be skipped
*/
public boolean[] getExtraPointTimeTextDisplayIndicator();
public FontStyle getFontStyle();
/**
* Gets extra point time display option
*/
public ExtraPointTimeDisplayOption getExtraPointTimeDisplayOption();
/**
* Gets color to plot the initial storm points
* @return color
*/
public Color getInitialColor();
/**
* Gets the line pattern used to display the initial storm points
* @return line pattern
*/
public String getInitialLinePattern();
/**
* Gets the marker used to display the initial storm points
* @return marker type
*/
public String getInitialMarker();
/**
* Gets the initial storm points and associated date/times
* @return track points
*/
public TrackPoint[] getInitialPoints();
/**
* Gets color to plot the extrapolated storm points
* @return color
*/
public Color getExtrapColor();
/**
* Gets the line pattern used to display the extrapolated storm points
* @return line pattern
*/
public String getExtrapLinePattern();
/**
* Gets the marker used to display the extrapolated storm points
* @return marker type
*/
public String getExtrapMarker();
/**
* Gets the extrapolated storm points and associated date/times
* @return track points
*/
public TrackPoint[] getExtrapPoints();
/**
* Gets the font used to display the location times
* @return font name
*/
public String getFontName();
/**
* Gets the size of the font
* @return font size
*/
public float getFontSize();
public Calendar getFirstTimeCalendar();
public Calendar getSecondTimeCalendar();
public boolean isSetTimeButtonSelected();
public int getExtraDrawingPointNumber();
public FontStyle getStyle();
public String getSkipFactorText();
public int getFontNameComboSelectedIndex();
public int getFontSizeComboSelectedIndex();
public int getFontStyleComboSelectedIndex();
public int getUnitComboSelectedIndex();
public int getRoundComboSelectedIndex();
public int getRoundDirComboSelectedIndex();
public String getIntervalTimeString();
/**
* Fets a boolean array that indicates if a time text of a extra point
* should be skipped
*/
public boolean[] getExtraPointTimeTextDisplayIndicator();
}
/**
* Gets extra point time display option
*/
public ExtraPointTimeDisplayOption getExtraPointTimeDisplayOption();
/**
* Gets color to plot the initial storm points
*
* @return color
*/
public Color getInitialColor();
/**
* Gets the line pattern used to display the initial storm points
*
* @return line pattern
*/
public String getInitialLinePattern();
/**
* Gets the marker used to display the initial storm points
*
* @return marker type
*/
public String getInitialMarker();
/**
* Gets the initial storm points and associated date/times
*
* @return track points
*/
public TrackPoint[] getInitialPoints();
/**
* Gets color to plot the extrapolated storm points
*
* @return color
*/
public Color getExtrapColor();
/**
* Gets the line pattern used to display the extrapolated storm points
*
* @return line pattern
*/
public String getExtrapLinePattern();
/**
* Gets the marker used to display the extrapolated storm points
*
* @return marker type
*/
public String getExtrapMarker();
/**
* Gets the extrapolated storm points and associated date/times
*
* @return track points
*/
public TrackPoint[] getExtrapPoints();
/**
* Gets the font used to display the location times
*
* @return font name
*/
public String getFontName();
/**
* Gets the size of the font
*
* @return font size
*/
public float getFontSize();
public Calendar getFirstTimeCalendar();
public Calendar getSecondTimeCalendar();
public boolean isSetTimeButtonSelected();
public int getExtraDrawingPointNumber();
public String getSkipFactorText();
public int getFontNameComboSelectedIndex();
public int getFontSizeComboSelectedIndex();
public int getFontStyleComboSelectedIndex();
public int getUnitComboSelectedIndex();
public int getRoundComboSelectedIndex();
public int getRoundDirComboSelectedIndex();
public String getIntervalTimeString();
}

View file

@ -15,59 +15,81 @@ import com.raytheon.uf.viz.core.map.IMapDescriptor;
/**
* An Element Container that can be used for most Symbol/Marker Elements.
* Recreation of the IDisplayable objects is only done if the layer DisplayProperties change.
* The raster images do not need to be recreated when panning or zooming.
* Recreation of the IDisplayable objects is only done if the layer
* DisplayProperties change. The raster images do not need to be recreated when
* panning or zooming.
*
* @author sgilbert
*
*
*/
public class RasterElementContainer extends AbstractElementContainer {
private DisplayProperties saveProps = null;
/**
* @param element
* @param mapDescriptor
* @param target
*/
public RasterElementContainer(DrawableElement element,
IMapDescriptor mapDescriptor, IGraphicsTarget target) {
super(element, mapDescriptor, target);
//
}
private DisplayProperties saveProps = null;
/*
* Draws to the given graphics target. Recreates the IDisplayable objects
* if the Layer properties change.
* @see gov.noaa.nws.ncep.ui.pgen.display.AbstractTBNL#draw(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties)
*/
@Override
public void draw(IGraphicsTarget target, PaintProperties paintProps,
DisplayProperties dprops) {
draw(target, paintProps, dprops, false);
}
/**
* @param element
* @param mapDescriptor
* @param target
*/
public RasterElementContainer(DrawableElement element,
IMapDescriptor mapDescriptor, IGraphicsTarget target) {
super(element, mapDescriptor, target);
//
}
/*
* Draws to the given graphics target. Recreates the IDisplayable objects
* if the Layer properties change.
* @see gov.noaa.nws.ncep.ui.pgen.display.AbstractTBNL#draw(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, boolean)
*/
@Override
public void draw(IGraphicsTarget target, PaintProperties paintProps,
DisplayProperties dprops, boolean needsCreate) {
if ( displayEls == null ) needsCreate = true;
if ( (dprops != null) && ! dprops.equals(saveProps) ) {
def.setLayerDisplayAttr(dprops.getLayerMonoColor(), dprops.getLayerColor(), dprops.getLayerFilled());
needsCreate = true;
}
if ( needsCreate ) createDisplayables(paintProps);
saveProps = dprops;
for ( IDisplayable each : displayEls ) {
each.draw(target, paintProps);
}
}
/*
* Draws to the given graphics target. Recreates the IDisplayable objects if
* the Layer properties change.
*
* @see
* gov.noaa.nws.ncep.ui.pgen.display.AbstractTBNL#draw(com.raytheon.uf.viz
* .core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties)
*/
@Override
public void draw(IGraphicsTarget target, PaintProperties paintProps,
DisplayProperties dprops) {
draw(target, paintProps, dprops, false);
}
/*
* Draws to the given graphics target. Recreates the IDisplayable objects if
* the Layer properties change.
*
* @see
* gov.noaa.nws.ncep.ui.pgen.display.AbstractTBNL#draw(com.raytheon.uf.viz
* .core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties, boolean)
*/
@Override
public void draw(IGraphicsTarget target, PaintProperties paintProps,
DisplayProperties dprops, boolean needsCreate) {
if (displayEls == null) {
needsCreate = true;
/*
* TTR971 - needs to set display properties, otherwise the layer
* color may not take effect (e.g., after switching projection)
*/
def.setLayerDisplayAttr(dprops.getLayerMonoColor(),
dprops.getLayerColor(), dprops.getLayerFilled());
}
if ((dprops != null) && !dprops.equals(saveProps)) {
def.setLayerDisplayAttr(dprops.getLayerMonoColor(),
dprops.getLayerColor(), dprops.getLayerFilled());
needsCreate = true;
}
if (needsCreate)
createDisplayables(paintProps);
saveProps = dprops;
for (IDisplayable each : displayEls) {
each.draw(target, paintProps);
}
}
}

View file

@ -154,6 +154,14 @@ public class TextDisplayElement implements IDisplayable {
target.drawShadedRect(box, bg, 1.0, null);
}
/*
* TTR 741 (10/2014) - Note, for single-line text, we could match it
* to Raytheon's text style. For multi-line text, we cannot match it
* to Raytheon's since it may add box, overline, underline to each
* line of text, not one single box, overline, or underline - so we
* may need to develop a new drawing method or ask Raytheon to
* provide support in GlTarget.
*/
switch (displayType) {
case NORMAL:
@ -161,19 +169,40 @@ public class TextDisplayElement implements IDisplayable {
break;
case BOX:
dstring.textStyle = TextStyle.BOXED;
// dstring.textStyle = TextStyle.BOXED;
if (dstring.getText().length > 1) {
target.drawRect(box, dstring.getColors()[0], 1.0f, 1.0);
} else {
dstring.textStyle = TextStyle.BOXED;
}
// target.drawRect(box, dstring.getColors()[0], 1.0f, 1.0);
break;
case OVERLINE:
dstring.textStyle = TextStyle.OVERLINE;
// dstring.textStyle = TextStyle.OVERLINE;
if (dstring.getText().length > 1) {
target.drawLine(box.getMinX(), box.getMinY(), 0.0,
box.getMaxX(), box.getMinY(), 0.0,
dstring.getColors()[0], 1.0f);
} else {
dstring.textStyle = TextStyle.OVERLINE;
}
// target.drawLine(box.getMinX(), box.getMinY(), 0.0,
// box.getMaxX(), box.getMinY(), 0.0,
// dstring.getColors()[0], 1.0f);
break;
case UNDERLINE:
dstring.textStyle = TextStyle.UNDERLINE;
// dstring.textStyle = TextStyle.UNDERLINE;
if (dstring.getText().length > 1) {
target.drawLine(box.getMinX(), box.getMaxY(), 0.0,
box.getMaxX(), box.getMaxY(), 0.0,
dstring.getColors()[0], 1.0f);
} else {
dstring.textStyle = TextStyle.UNDERLINE;
}
// target.drawLine(box.getMinX(), box.getMaxY(), 0.0,
// box.getMaxX(), box.getMaxY(), 0.0,
// dstring.getColors()[0], 1.0f);

View file

@ -134,6 +134,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* 12/13 TTR904 B. Yin Added back the water zone string for Watch county list
* 11/13 #1065 J. Wu Added Kink lines.
* 05/14 TTR995 J. Wu Set Text's 'auto" flag to false.
* 09/14 TTR716 J. Wu Use "-" for GFA Outlook's Vor text.
*
* </pre>
*
@ -735,6 +736,12 @@ public class ProductConverter {
gfa.setGfaValue("Type", fgfa.getType());
}
// textVOR
String vorStr = fgfa.getTextVor();
if (vorStr != null) {
gfa.setGfaVorText(nvl(vorStr));
}
String cig = fgfa.getCig();
if (cig != null) {
gfa.setGfaValue(Gfa.CIG, fgfa.getCig());
@ -1098,7 +1105,11 @@ public class ProductConverter {
}
// textVOR
fgfa.setTextVor(nvl(((Gfa) de).getGfaVorText()));
String vorStr = ((Gfa) de).getGfaVorText();
if (vorStr != null && ((Gfa) de).isOutlook()) {
vorStr = vorStr.replaceAll(" TO ", "-");
}
fgfa.setTextVor(nvl(vorStr));
fgfa.setFillPattern(nvl(((Gfa) de).getFillPattern()
.name()));

View file

@ -5,11 +5,11 @@
// Generated on: 2009.05.28 at 02:35:15 PM EDT
//
package gov.noaa.nws.ncep.ui.pgen.file;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
@ -17,11 +17,13 @@ import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
* <p>
* Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* The following schema fragment specifies the expected content contained within
* this class.
*
* <pre>
* &lt;complexType>
@ -38,6 +40,7 @@ import javax.xml.bind.annotation.XmlType;
* &lt;attribute name="extrapLinePattern" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;attribute name="extrapMarker" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;attribute name="fontName" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;attribute name="fontStyle" type="{http://www.w3.org/2001/XMLSchema}string" />
* &lt;attribute name="fontNameComboSelectedIndex" type="{http://www.w3.org/2001/XMLSchema}int" />
* &lt;attribute name="fontSize" type="{http://www.w3.org/2001/XMLSchema}float" />
* &lt;attribute name="fontSizeComboSelectedIndex" type="{http://www.w3.org/2001/XMLSchema}int" />
@ -60,68 +63,85 @@ import javax.xml.bind.annotation.XmlType;
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"initialColor",
"extrapColor",
"initialPoints",
"extrapPoints",
"extraPointTimeTextDisplayIndicator"
})
@XmlType(name = "", propOrder = { "initialColor", "extrapColor",
"initialPoints", "extrapPoints", "extraPointTimeTextDisplayIndicator" })
@XmlRootElement(name = "Track")
public class Track {
@XmlElement(required = true)
protected ColorType initialColor;
@XmlElement(required = true)
protected ColorType extrapColor;
@XmlElement(required = true)
protected List<TrackPoint> initialPoints;
@XmlElement(required = true)
protected List<TrackPoint> extrapPoints;
@XmlElement(type = Boolean.class)
protected List<Boolean> extraPointTimeTextDisplayIndicator;
@XmlAttribute
protected String extraPointTimeDisplayOptionName;
@XmlAttribute
protected String extrapLinePattern;
@XmlAttribute
protected String extrapMarker;
@XmlAttribute
protected String fontName;
@XmlAttribute
protected String fontStyle;
@XmlAttribute
protected Integer fontNameComboSelectedIndex;
@XmlAttribute
protected Float fontSize;
@XmlAttribute
protected Integer fontSizeComboSelectedIndex;
@XmlAttribute
protected Integer fontStyleComboSelectedIndex;
@XmlAttribute
protected String initialLinePattern;
@XmlAttribute
protected String initialMarker;
@XmlAttribute
protected Integer intervalComboSelectedIndex;
@XmlAttribute
protected String intervalTimeTextString;
@XmlAttribute
protected Float lineWidth;
@XmlAttribute
protected String pgenCategory;
@XmlAttribute
protected String pgenType;
@XmlAttribute
protected Boolean setTimeButtonSelected;
@XmlAttribute
protected String skipFactorTextString;
/**
* Gets the value of the initialColor property.
*
* @return
* possible object is
* {@link ColorType }
*
* @return possible object is {@link ColorType }
*
*/
public ColorType getInitialColor() {
return initialColor;
@ -131,9 +151,8 @@ public class Track {
* Sets the value of the initialColor property.
*
* @param value
* allowed object is
* {@link ColorType }
*
* allowed object is {@link ColorType }
*
*/
public void setInitialColor(ColorType value) {
this.initialColor = value;
@ -142,10 +161,8 @@ public class Track {
/**
* Gets the value of the extrapColor property.
*
* @return
* possible object is
* {@link ColorType }
*
* @return possible object is {@link ColorType }
*
*/
public ColorType getExtrapColor() {
return extrapColor;
@ -155,9 +172,8 @@ public class Track {
* Sets the value of the extrapColor property.
*
* @param value
* allowed object is
* {@link ColorType }
*
* allowed object is {@link ColorType }
*
*/
public void setExtrapColor(ColorType value) {
this.extrapColor = value;
@ -167,15 +183,16 @@ public class Track {
* Gets the value of the initialPoints property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the initialPoints property.
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the initialPoints property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getInitialPoints().add(newItem);
* getInitialPoints().add(newItem);
* </pre>
*
*
@ -196,15 +213,16 @@ public class Track {
* Gets the value of the extrapPoints property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the extrapPoints property.
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the extrapPoints property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getExtrapPoints().add(newItem);
* getExtrapPoints().add(newItem);
* </pre>
*
*
@ -225,21 +243,22 @@ public class Track {
* Gets the value of the extraPointTimeTextDisplayIndicator property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the extraPointTimeTextDisplayIndicator property.
* This accessor method returns a reference to the live list, not a
* snapshot. Therefore any modification you make to the returned list will
* be present inside the JAXB object. This is why there is not a
* <CODE>set</CODE> method for the extraPointTimeTextDisplayIndicator
* property.
*
* <p>
* For example, to add a new item, do as follows:
*
* <pre>
* getExtraPointTimeTextDisplayIndicator().add(newItem);
* getExtraPointTimeTextDisplayIndicator().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Boolean }
* Objects of the following type(s) are allowed in the list {@link Boolean }
*
*
*/
@ -253,10 +272,8 @@ public class Track {
/**
* Gets the value of the extraPointTimeDisplayOptionName property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getExtraPointTimeDisplayOptionName() {
return extraPointTimeDisplayOptionName;
@ -266,9 +283,8 @@ public class Track {
* Sets the value of the extraPointTimeDisplayOptionName property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setExtraPointTimeDisplayOptionName(String value) {
this.extraPointTimeDisplayOptionName = value;
@ -277,10 +293,8 @@ public class Track {
/**
* Gets the value of the extrapLinePattern property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getExtrapLinePattern() {
return extrapLinePattern;
@ -290,9 +304,8 @@ public class Track {
* Sets the value of the extrapLinePattern property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setExtrapLinePattern(String value) {
this.extrapLinePattern = value;
@ -301,10 +314,8 @@ public class Track {
/**
* Gets the value of the extrapMarker property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getExtrapMarker() {
return extrapMarker;
@ -314,9 +325,8 @@ public class Track {
* Sets the value of the extrapMarker property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setExtrapMarker(String value) {
this.extrapMarker = value;
@ -325,10 +335,8 @@ public class Track {
/**
* Gets the value of the fontName property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getFontName() {
return fontName;
@ -338,21 +346,39 @@ public class Track {
* Sets the value of the fontName property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setFontName(String value) {
this.fontName = value;
}
/**
* Gets the value of the fontStyle property.
*
* @return possible object is {@link String }
*
*/
public String getFontStyle() {
return fontStyle;
}
/**
* Sets the value of the fontStyle property.
*
* @param value
* allowed object is {@link String }
*
*/
public void setFontStyle(String value) {
this.fontStyle = value;
}
/**
* Gets the value of the fontNameComboSelectedIndex property.
*
* @return
* possible object is
* {@link Integer }
*
* @return possible object is {@link Integer }
*
*/
public Integer getFontNameComboSelectedIndex() {
return fontNameComboSelectedIndex;
@ -362,9 +388,8 @@ public class Track {
* Sets the value of the fontNameComboSelectedIndex property.
*
* @param value
* allowed object is
* {@link Integer }
*
* allowed object is {@link Integer }
*
*/
public void setFontNameComboSelectedIndex(Integer value) {
this.fontNameComboSelectedIndex = value;
@ -373,10 +398,8 @@ public class Track {
/**
* Gets the value of the fontSize property.
*
* @return
* possible object is
* {@link Float }
*
* @return possible object is {@link Float }
*
*/
public Float getFontSize() {
return fontSize;
@ -386,9 +409,8 @@ public class Track {
* Sets the value of the fontSize property.
*
* @param value
* allowed object is
* {@link Float }
*
* allowed object is {@link Float }
*
*/
public void setFontSize(Float value) {
this.fontSize = value;
@ -397,10 +419,8 @@ public class Track {
/**
* Gets the value of the fontSizeComboSelectedIndex property.
*
* @return
* possible object is
* {@link Integer }
*
* @return possible object is {@link Integer }
*
*/
public Integer getFontSizeComboSelectedIndex() {
return fontSizeComboSelectedIndex;
@ -410,9 +430,8 @@ public class Track {
* Sets the value of the fontSizeComboSelectedIndex property.
*
* @param value
* allowed object is
* {@link Integer }
*
* allowed object is {@link Integer }
*
*/
public void setFontSizeComboSelectedIndex(Integer value) {
this.fontSizeComboSelectedIndex = value;
@ -421,10 +440,8 @@ public class Track {
/**
* Gets the value of the fontStyleComboSelectedIndex property.
*
* @return
* possible object is
* {@link Integer }
*
* @return possible object is {@link Integer }
*
*/
public Integer getFontStyleComboSelectedIndex() {
return fontStyleComboSelectedIndex;
@ -434,9 +451,8 @@ public class Track {
* Sets the value of the fontStyleComboSelectedIndex property.
*
* @param value
* allowed object is
* {@link Integer }
*
* allowed object is {@link Integer }
*
*/
public void setFontStyleComboSelectedIndex(Integer value) {
this.fontStyleComboSelectedIndex = value;
@ -445,10 +461,8 @@ public class Track {
/**
* Gets the value of the initialLinePattern property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getInitialLinePattern() {
return initialLinePattern;
@ -458,9 +472,8 @@ public class Track {
* Sets the value of the initialLinePattern property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setInitialLinePattern(String value) {
this.initialLinePattern = value;
@ -469,10 +482,8 @@ public class Track {
/**
* Gets the value of the initialMarker property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getInitialMarker() {
return initialMarker;
@ -482,9 +493,8 @@ public class Track {
* Sets the value of the initialMarker property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setInitialMarker(String value) {
this.initialMarker = value;
@ -493,10 +503,8 @@ public class Track {
/**
* Gets the value of the intervalComboSelectedIndex property.
*
* @return
* possible object is
* {@link Integer }
*
* @return possible object is {@link Integer }
*
*/
public Integer getIntervalComboSelectedIndex() {
return intervalComboSelectedIndex;
@ -506,9 +514,8 @@ public class Track {
* Sets the value of the intervalComboSelectedIndex property.
*
* @param value
* allowed object is
* {@link Integer }
*
* allowed object is {@link Integer }
*
*/
public void setIntervalComboSelectedIndex(Integer value) {
this.intervalComboSelectedIndex = value;
@ -517,10 +524,8 @@ public class Track {
/**
* Gets the value of the intervalTimeTextString property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getIntervalTimeTextString() {
return intervalTimeTextString;
@ -530,9 +535,8 @@ public class Track {
* Sets the value of the intervalTimeTextString property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setIntervalTimeTextString(String value) {
this.intervalTimeTextString = value;
@ -541,10 +545,8 @@ public class Track {
/**
* Gets the value of the lineWidth property.
*
* @return
* possible object is
* {@link Float }
*
* @return possible object is {@link Float }
*
*/
public Float getLineWidth() {
return lineWidth;
@ -554,9 +556,8 @@ public class Track {
* Sets the value of the lineWidth property.
*
* @param value
* allowed object is
* {@link Float }
*
* allowed object is {@link Float }
*
*/
public void setLineWidth(Float value) {
this.lineWidth = value;
@ -565,10 +566,8 @@ public class Track {
/**
* Gets the value of the pgenCategory property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getPgenCategory() {
return pgenCategory;
@ -578,9 +577,8 @@ public class Track {
* Sets the value of the pgenCategory property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setPgenCategory(String value) {
this.pgenCategory = value;
@ -589,10 +587,8 @@ public class Track {
/**
* Gets the value of the pgenType property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getPgenType() {
return pgenType;
@ -602,9 +598,8 @@ public class Track {
* Sets the value of the pgenType property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setPgenType(String value) {
this.pgenType = value;
@ -613,10 +608,8 @@ public class Track {
/**
* Gets the value of the setTimeButtonSelected property.
*
* @return
* possible object is
* {@link Boolean }
*
* @return possible object is {@link Boolean }
*
*/
public Boolean isSetTimeButtonSelected() {
return setTimeButtonSelected;
@ -626,9 +619,8 @@ public class Track {
* Sets the value of the setTimeButtonSelected property.
*
* @param value
* allowed object is
* {@link Boolean }
*
* allowed object is {@link Boolean }
*
*/
public void setSetTimeButtonSelected(Boolean value) {
this.setTimeButtonSelected = value;
@ -637,10 +629,8 @@ public class Track {
/**
* Gets the value of the skipFactorTextString property.
*
* @return
* possible object is
* {@link String }
*
* @return possible object is {@link String }
*
*/
public String getSkipFactorTextString() {
return skipFactorTextString;
@ -650,9 +640,8 @@ public class Track {
* Sets the value of the skipFactorTextString property.
*
* @param value
* allowed object is
* {@link String }
*
* allowed object is {@link String }
*
*/
public void setSkipFactorTextString(String value) {
this.skipFactorTextString = value;

View file

@ -7,11 +7,17 @@
*/
package gov.noaa.nws.ncep.ui.pgen.file;
import gov.noaa.nws.ncep.ui.pgen.display.FillPatternList.FillPattern;
import gov.noaa.nws.ncep.ui.pgen.display.IText.FontStyle;
import gov.noaa.nws.ncep.ui.pgen.display.ITrack;
import gov.noaa.nws.ncep.ui.pgen.display.TrackPoint;
import gov.noaa.nws.ncep.ui.pgen.elements.Track;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.ArrayList;
import java.awt.Color;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
@ -22,318 +28,423 @@ import org.geotools.referencing.datum.DefaultEllipsoid;
import com.vividsolutions.jts.geom.Coordinate;
import gov.noaa.nws.ncep.ui.pgen.elements.Track;
import gov.noaa.nws.ncep.ui.pgen.display.ITrack;
import gov.noaa.nws.ncep.ui.pgen.display.TrackPoint;
import gov.noaa.nws.ncep.ui.pgen.display.FillPatternList.FillPattern;
/**
* Define a ProductConverter Class - some methods to convert the products between XML format
* and the actual in-memory PGEN products.
* Define a ProductConverter Class - some methods to convert the products
* between XML format and the actual in-memory PGEN products.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 02/2012 TTR456 Q. Zhou Added speed, dir. Default to kts, no round
* 02/2012 TTR456 Q. Zhou Added speed, dir. Default to kts, no round
* 09/2014 TTR750 J. Wu Use FontStyle instead of "index".
* </pre>
* */
public class TrackConverter {
// private final static org.apache.log4j.Logger log =
// org.apache.log4j.Logger.getLogger(TrackConverter.class);
/*
* Convert a XML file DrawableElement object to a list of PGEN in-memory
* DrawableElement objects
*/
public static List<Track> getTrackElementListByTrackBeanList (
List<gov.noaa.nws.ncep.ui.pgen.file.Track> trackBeanList) {
List<Track> trackElementList = new ArrayList<Track>(trackBeanList.size());
for(gov.noaa.nws.ncep.ui.pgen.file.Track trackBean : trackBeanList) {
Track trackElement = new Track();
trackElement.setInitialColor(getColorByColorTypeBean(trackBean.initialColor, true));
trackElement.setExtrapColor(getColorByColorTypeBean(trackBean.extrapColor, false));
trackElement.setInitTrackPoints(getTrackPointElementListByTrackPointBeanList(trackBean.getInitialPoints()).toArray(new TrackPoint[trackBean.getInitialPoints().size()]));
trackElement.setExtrapPoints(getTrackPointElementListByTrackPointBeanList(trackBean.getExtrapPoints()).toArray(new TrackPoint[trackBean.getExtrapPoints().size()]));
/*
* Now initialize track's firstTimeCalendar and secondTimeCalendar using initTrackPoints
*/
trackElement.setFirstTimeCalendar(getFirstOrSecondTimeCalendarByTrackBean(trackBean, true));
trackElement.setSecondTimeCalendar(getFirstOrSecondTimeCalendarByTrackBean(trackBean, false));
/*
* Important note: the following two method calls are necessary.
* 1. combine init and extrap points to allow PgenSource to go over every point for drawing
* 2. setLinePattern is from the parent class of Track, the name is kind of misleading
* It is hard coded now, for future, a new field is needed to the XSD file.
*/
trackElement.setLinePointsValue(trackElement.getInitialPoints(), trackElement.getExtrapPoints());
trackElement.setExtraPointTimeTextDisplayIndicator(getBooleanArrayByBooleanList(trackBean.extraPointTimeTextDisplayIndicator));
trackElement.setInitialLinePattern(trackBean.getInitialLinePattern());
trackElement.setExtrapLinePattern(trackBean.getExtrapLinePattern());
trackElement.setInitialMarker(trackBean.getInitialMarker());
trackElement.setExtrapMarker(trackBean.getExtrapMarker());
trackElement.setFontName(trackBean.getFontName());
if(trackBean.getLineWidth() != null)
trackElement.setLineWidth(trackBean.getLineWidth().floatValue());
else
trackElement.setLineWidth((float)1.0); //set a 1.0 as the default value
if(trackBean.getFontSize() != null)
trackElement.setFontSize(trackBean.getFontSize().floatValue());
else
trackElement.setFontSize((float)2.0); //set a 2.0 as the default value
if(trackBean.getPgenCategory() == null)
trackElement.setPgenCategory(Track.TRACK_PGEN_CATEGORY);
else
trackElement.setPgenCategory(trackBean.getPgenCategory());
if(trackBean.getPgenType() == null)
trackElement.setPgenType(Track.TRACK_PGEN_TYPE);
else
trackElement.setPgenType(trackBean.getPgenType());
/*
* add speed, dir. Default to kts, no round --Quan
*/
TrackPoint[] initPts = trackElement.getInitTrackPoints();
int initPtsLength = initPts.length;
Coordinate initPointBeforeLastInitPointCoordinate = initPts[initPtsLength - 2].getLocation();
Coordinate lastInitPointCoordinate = initPts[initPtsLength - 1].getLocation();
GeodeticCalculator gc = new GeodeticCalculator(DefaultEllipsoid.WGS84);
gc.setStartingGeographicPoint(initPointBeforeLastInitPointCoordinate.x,
initPointBeforeLastInitPointCoordinate.y);
gc.setDestinationGeographicPoint(lastInitPointCoordinate.x,
lastInitPointCoordinate.y);
double direction = gc.getAzimuth();
double distanceInMeter = gc.getOrthodromicDistance();
long timeDifference = initPts[initPtsLength - 1].getTime().getTimeInMillis() -
initPts[initPtsLength - 2].getTime().getTimeInMillis();
double speed = distanceInMeter / (double)timeDifference;
trackElement.setDirectionForExtraPoints(direction);
trackElement.setSpeed(speed);
/*
* add something related to line drawing
*/
trackElement.setSizeScale((double) 1.0);
trackElement.setSmoothFactor(0);
trackElement.setClosed(false);
trackElement.setFilled(false);
trackElement.setFillPattern(FillPattern.FILL_PATTERN_0);
/*
* The following attributes are necessary to fill values for the pop-up
* TrackAttiDlg window from the restored line images.
*/
boolean setTimeButtonSelectedFlag = true; // set the default value as TRUE
if(trackBean.isSetTimeButtonSelected() != null)
setTimeButtonSelectedFlag = trackBean.isSetTimeButtonSelected().booleanValue();
trackElement.setSetTimeButtonSelected(setTimeButtonSelectedFlag);
int intervalComboSelectedIndexValue = 0; //set the default value
if(trackBean.getIntervalComboSelectedIndex() != null)
intervalComboSelectedIndexValue = trackBean.getIntervalComboSelectedIndex().intValue();
trackElement.setIntervalComboSelectedIndex(intervalComboSelectedIndexValue);
trackElement.setIntervalTimeString(trackBean.getIntervalTimeTextString());
String extraPointTimeDisplayOptionName = ITrack.ExtraPointTimeDisplayOption.SKIP_FACTOR.name(); // set the default value
if(trackBean.getExtraPointTimeDisplayOptionName() != null)
extraPointTimeDisplayOptionName = trackBean.getExtraPointTimeDisplayOptionName();
trackElement.setExtraPointTimeDisplayOption(ITrack.ExtraPointTimeDisplayOption.valueOf(extraPointTimeDisplayOptionName));
String skipFactorTextString = "0"; //set the default value
if(trackBean.getSkipFactorTextString() != null)
skipFactorTextString = trackBean.getSkipFactorTextString();
trackElement.setSkipFactorTextString(skipFactorTextString);
int fontNameComboSelectedIndex = 0; //set the default value
if(trackBean.getFontNameComboSelectedIndex() != null)
fontNameComboSelectedIndex = trackBean.getFontNameComboSelectedIndex().intValue();
trackElement.setFontNameComboSelectedIndex(fontNameComboSelectedIndex);
int fontSizeComboSelectedIndex = 0; //set the default value
if(trackBean.getFontSizeComboSelectedIndex() != null)
fontSizeComboSelectedIndex = trackBean.getFontSizeComboSelectedIndex().intValue();
trackElement.setFontSizeComboSelectedIndex(fontSizeComboSelectedIndex);
int fontStyleComboSelectedIndex = 0; //set the default value
if(trackBean.getFontStyleComboSelectedIndex() != null)
fontStyleComboSelectedIndex = trackBean.getFontStyleComboSelectedIndex().intValue();
trackElement.setFontStyleComboSelectedIndex(fontStyleComboSelectedIndex);
trackElementList.add(trackElement);
}
// private final static org.apache.log4j.Logger log =
// org.apache.log4j.Logger.getLogger(TrackConverter.class);
/*
* Convert a XML file DrawableElement object to a list of PGEN in-memory
* DrawableElement objects
*/
public static List<Track> getTrackElementListByTrackBeanList(
List<gov.noaa.nws.ncep.ui.pgen.file.Track> trackBeanList) {
List<Track> trackElementList = new ArrayList<Track>(
trackBeanList.size());
for (gov.noaa.nws.ncep.ui.pgen.file.Track trackBean : trackBeanList) {
Track trackElement = new Track();
trackElement.setInitialColor(getColorByColorTypeBean(
trackBean.initialColor, true));
trackElement.setExtrapColor(getColorByColorTypeBean(
trackBean.extrapColor, false));
trackElement
.setInitTrackPoints(getTrackPointElementListByTrackPointBeanList(
trackBean.getInitialPoints())
.toArray(
new TrackPoint[trackBean.getInitialPoints()
.size()]));
trackElement
.setExtrapPoints(getTrackPointElementListByTrackPointBeanList(
trackBean.getExtrapPoints()).toArray(
new TrackPoint[trackBean.getExtrapPoints().size()]));
/*
* Now initialize track's firstTimeCalendar and secondTimeCalendar
* using initTrackPoints
*/
trackElement
.setFirstTimeCalendar(getFirstOrSecondTimeCalendarByTrackBean(
trackBean, true));
trackElement
.setSecondTimeCalendar(getFirstOrSecondTimeCalendarByTrackBean(
trackBean, false));
/*
* Important note: the following two method calls are necessary. 1.
* combine init and extrap points to allow PgenSource to go over
* every point for drawing 2. setLinePattern is from the parent
* class of Track, the name is kind of misleading It is hard coded
* now, for future, a new field is needed to the XSD file.
*/
trackElement.setLinePointsValue(trackElement.getInitialPoints(),
trackElement.getExtrapPoints());
trackElement
.setExtraPointTimeTextDisplayIndicator(getBooleanArrayByBooleanList(trackBean.extraPointTimeTextDisplayIndicator));
trackElement.setInitialLinePattern(trackBean
.getInitialLinePattern());
trackElement.setExtrapLinePattern(trackBean.getExtrapLinePattern());
trackElement.setInitialMarker(trackBean.getInitialMarker());
trackElement.setExtrapMarker(trackBean.getExtrapMarker());
trackElement.setFontName(trackBean.getFontName());
// TTR 950 - Font Style
int styleInd = 0;
FontStyle dstyle = FontStyle.BOLD;
if (trackBean.getFontStyle() != null) {
int jj = 0;
for (FontStyle ft : FontStyle.values()) {
if (ft == FontStyle.valueOf(trackBean.getFontStyle()
.toUpperCase())) {
styleInd = jj;
dstyle = ft;
break;
}
jj++;
}
}
trackElement.setFontStyle(dstyle);
trackElement.setFontStyleComboSelectedIndex(styleInd);
if (trackBean.getLineWidth() != null)
trackElement
.setLineWidth(trackBean.getLineWidth().floatValue());
else
trackElement.setLineWidth((float) 1.0); // set a 1.0 as the
// default value
if (trackBean.getFontSize() != null)
trackElement.setFontSize(trackBean.getFontSize().floatValue());
else
trackElement.setFontSize((float) 2.0); // set a 2.0 as the
// default value
if (trackBean.getPgenCategory() == null)
trackElement.setPgenCategory(Track.TRACK_PGEN_CATEGORY);
else
trackElement.setPgenCategory(trackBean.getPgenCategory());
if (trackBean.getPgenType() == null)
trackElement.setPgenType(Track.TRACK_PGEN_TYPE);
else
trackElement.setPgenType(trackBean.getPgenType());
/*
* add speed, dir. Default to kts, no round --Quan
*/
TrackPoint[] initPts = trackElement.getInitTrackPoints();
int initPtsLength = initPts.length;
Coordinate initPointBeforeLastInitPointCoordinate = initPts[initPtsLength - 2]
.getLocation();
Coordinate lastInitPointCoordinate = initPts[initPtsLength - 1]
.getLocation();
GeodeticCalculator gc = new GeodeticCalculator(
DefaultEllipsoid.WGS84);
gc.setStartingGeographicPoint(
initPointBeforeLastInitPointCoordinate.x,
initPointBeforeLastInitPointCoordinate.y);
gc.setDestinationGeographicPoint(lastInitPointCoordinate.x,
lastInitPointCoordinate.y);
double direction = gc.getAzimuth();
double distanceInMeter = gc.getOrthodromicDistance();
long timeDifference = initPts[initPtsLength - 1].getTime()
.getTimeInMillis()
- initPts[initPtsLength - 2].getTime().getTimeInMillis();
double speed = distanceInMeter / (double) timeDifference;
trackElement.setDirectionForExtraPoints(direction);
trackElement.setSpeed(speed);
/*
* add something related to line drawing
*/
trackElement.setSizeScale((double) 1.0);
trackElement.setSmoothFactor(0);
trackElement.setClosed(false);
trackElement.setFilled(false);
trackElement.setFillPattern(FillPattern.FILL_PATTERN_0);
/*
* The following attributes are necessary to fill values for the
* pop-up TrackAttiDlg window from the restored line images.
*/
boolean setTimeButtonSelectedFlag = true; // set the default value
// as TRUE
if (trackBean.isSetTimeButtonSelected() != null)
setTimeButtonSelectedFlag = trackBean.isSetTimeButtonSelected()
.booleanValue();
trackElement.setSetTimeButtonSelected(setTimeButtonSelectedFlag);
int intervalComboSelectedIndexValue = 0; // set the default value
if (trackBean.getIntervalComboSelectedIndex() != null)
intervalComboSelectedIndexValue = trackBean
.getIntervalComboSelectedIndex().intValue();
trackElement
.setIntervalComboSelectedIndex(intervalComboSelectedIndexValue);
trackElement.setIntervalTimeString(trackBean
.getIntervalTimeTextString());
String extraPointTimeDisplayOptionName = ITrack.ExtraPointTimeDisplayOption.SKIP_FACTOR
.name(); // set the default value
if (trackBean.getExtraPointTimeDisplayOptionName() != null)
extraPointTimeDisplayOptionName = trackBean
.getExtraPointTimeDisplayOptionName();
trackElement
.setExtraPointTimeDisplayOption(ITrack.ExtraPointTimeDisplayOption
.valueOf(extraPointTimeDisplayOptionName));
String skipFactorTextString = "0"; // set the default value
if (trackBean.getSkipFactorTextString() != null)
skipFactorTextString = trackBean.getSkipFactorTextString();
trackElement.setSkipFactorTextString(skipFactorTextString);
int fontNameComboSelectedIndex = 0; // set the default value
if (trackBean.getFontNameComboSelectedIndex() != null)
fontNameComboSelectedIndex = trackBean
.getFontNameComboSelectedIndex().intValue();
trackElement
.setFontNameComboSelectedIndex(fontNameComboSelectedIndex);
int fontSizeComboSelectedIndex = 0; // set the default value
if (trackBean.getFontSizeComboSelectedIndex() != null)
fontSizeComboSelectedIndex = trackBean
.getFontSizeComboSelectedIndex().intValue();
trackElement
.setFontSizeComboSelectedIndex(fontSizeComboSelectedIndex);
trackElementList.add(trackElement);
}
return trackElementList;
}
public static gov.noaa.nws.ncep.ui.pgen.file.Track getTrackBeanByTrackElement(
public static gov.noaa.nws.ncep.ui.pgen.file.Track getTrackBeanByTrackElement(
Track trackElement) {
gov.noaa.nws.ncep.ui.pgen.file.Track trackBean = new gov.noaa.nws.ncep.ui.pgen.file.Track();
gov.noaa.nws.ncep.ui.pgen.file.Track trackBean = new gov.noaa.nws.ncep.ui.pgen.file.Track();
trackBean.setInitialColor(getColorTypeBeanByColorElement(trackElement.getInitialColor()));
trackBean.setExtrapColor(getColorTypeBeanByColorElement(trackElement.getExtrapColor()));
if(trackElement.getInitialPoints() != null) {
for(TrackPoint currentTrackPoint : trackElement.getInitialPoints()) {
trackBean.getInitialPoints().add(getTrackPointBeanByTrackPointElement(currentTrackPoint));
}
}
if(trackElement.getExtrapPoints() != null) {
for(TrackPoint currentTrackPoint : trackElement.getExtrapPoints()) {
trackBean.getExtrapPoints().add(getTrackPointBeanByTrackPointElement(currentTrackPoint));
}
}
trackBean.getExtraPointTimeTextDisplayIndicator().addAll(getBooleanObjectList(trackElement.getExtraPointTimeTextDisplayIndicator()));
trackBean.setInitialColor(getColorTypeBeanByColorElement(trackElement
.getInitialColor()));
trackBean.setExtrapColor(getColorTypeBeanByColorElement(trackElement
.getExtrapColor()));
trackBean.setInitialLinePattern(trackElement.getInitialLinePattern());
trackBean.setExtrapLinePattern(trackElement.getExtrapLinePattern());
trackBean.setInitialMarker(trackElement.getInitialMarker());
trackBean.setExtrapMarker(trackElement.getExtrapMarker());
trackBean.setFontName(trackElement.getFontName());
trackBean.setFontSize(new Float(trackElement.getFontSize()));
trackBean.setLineWidth(new Float(trackElement.getLineWidth()));
trackBean.setPgenCategory(trackElement.getPgenCategory());
trackBean.setPgenType(trackElement.getPgenType());
/*
* The following attributes are not necessary to save the line images
* and late to restore them back on the map. However, they are necessary
* values to pop-up and set up the correct attributes of the TrackAttrDlg
*/
trackBean.setSetTimeButtonSelected(new Boolean(trackElement.isSetTimeButtonSelected()));
trackBean.setIntervalComboSelectedIndex(new Integer(trackElement.getIntervalComboSelectedIndex()));
trackBean.setIntervalTimeTextString(trackElement.getIntervalTimeString());
trackBean.setExtraPointTimeDisplayOptionName(trackElement.getExtraPointTimeDisplayOption().name());
trackBean.setSkipFactorTextString(trackElement.getSkipFactorTextString());
trackBean.setFontNameComboSelectedIndex(new Integer(trackElement.getFontNameComboSelectedIndex()));
trackBean.setFontSizeComboSelectedIndex(new Integer(trackElement.getFontSizeComboSelectedIndex()));
trackBean.setFontStyleComboSelectedIndex(new Integer(trackElement.getFontStyleComboSelectedIndex()));
return trackBean;
if (trackElement.getInitialPoints() != null) {
for (TrackPoint currentTrackPoint : trackElement.getInitialPoints()) {
trackBean
.getInitialPoints()
.add(getTrackPointBeanByTrackPointElement(currentTrackPoint));
}
}
if (trackElement.getExtrapPoints() != null) {
for (TrackPoint currentTrackPoint : trackElement.getExtrapPoints()) {
trackBean
.getExtrapPoints()
.add(getTrackPointBeanByTrackPointElement(currentTrackPoint));
}
}
trackBean.getExtraPointTimeTextDisplayIndicator().addAll(
getBooleanObjectList(trackElement
.getExtraPointTimeTextDisplayIndicator()));
trackBean.setInitialLinePattern(trackElement.getInitialLinePattern());
trackBean.setExtrapLinePattern(trackElement.getExtrapLinePattern());
trackBean.setInitialMarker(trackElement.getInitialMarker());
trackBean.setExtrapMarker(trackElement.getExtrapMarker());
trackBean.setFontName(trackElement.getFontName());
// Font style
int styleInd = 0;
FontStyle dstyle = FontStyle.BOLD;
if (trackElement.getFontStyle() != null) {
int jj = 0;
for (FontStyle ft : FontStyle.values()) {
if (ft == trackElement.getFontStyle()) {
styleInd = jj;
dstyle = ft;
break;
}
jj++;
}
}
trackBean.setFontStyle(dstyle.toString());
trackBean.setFontStyleComboSelectedIndex(styleInd);
trackBean.setFontSize(new Float(trackElement.getFontSize()));
trackBean.setLineWidth(new Float(trackElement.getLineWidth()));
trackBean.setPgenCategory(trackElement.getPgenCategory());
trackBean.setPgenType(trackElement.getPgenType());
/*
* The following attributes are not necessary to save the line images
* and late to restore them back on the map. However, they are necessary
* values to pop-up and set up the correct attributes of the
* TrackAttrDlg
*/
trackBean.setSetTimeButtonSelected(new Boolean(trackElement
.isSetTimeButtonSelected()));
trackBean.setIntervalComboSelectedIndex(new Integer(trackElement
.getIntervalComboSelectedIndex()));
trackBean.setIntervalTimeTextString(trackElement
.getIntervalTimeString());
trackBean.setExtraPointTimeDisplayOptionName(trackElement
.getExtraPointTimeDisplayOption().name());
trackBean.setSkipFactorTextString(trackElement
.getSkipFactorTextString());
trackBean.setFontNameComboSelectedIndex(new Integer(trackElement
.getFontNameComboSelectedIndex()));
trackBean.setFontSizeComboSelectedIndex(new Integer(trackElement
.getFontSizeComboSelectedIndex()));
return trackBean;
}
/*
* help methods for transferring objects back and forth between class objects and JAXB beans
* help methods for transferring objects back and forth between class
* objects and JAXB beans
*/
private static Calendar getFirstOrSecondTimeCalendarByTrackBean(gov.noaa.nws.ncep.ui.pgen.file.Track trackBean, boolean isFirstTimeCalendar) {
int indexOffSet = 1;
if(isFirstTimeCalendar)
indexOffSet++;
List<TrackPoint> trackPointElementList = getTrackPointElementListByTrackPointBeanList(trackBean.getInitialPoints());
if(trackPointElementList == null || trackPointElementList.size() < 2) {
// log.error("Retrieved List<TrackPoint> trackPointElementList is NULL or the initial points are less than 2 points");
return null;
}
int listSize = trackPointElementList.size();
return trackPointElementList.get(listSize - indexOffSet).getTime();
}
private static java.awt.Color getColorByColorTypeBean(gov.noaa.nws.ncep.ui.pgen.file.ColorType colorTypeBean,
boolean isInitColor) {
if(colorTypeBean == null || colorTypeBean.getColor() == null) {
if(isInitColor)
return new Color(0, 0, 255); //return a default color as Blue
else
return new Color(0, 192, 0); //return a green color as the default color for extrapPoint
}
gov.noaa.nws.ncep.ui.pgen.file.Color colorBean = colorTypeBean.getColor();
return new Color(colorBean.getRed(), colorBean.getGreen(), colorBean.getBlue(),
colorBean.getAlpha());
}
private static List<TrackPoint> getTrackPointElementListByTrackPointBeanList(List<gov.noaa.nws.ncep.ui.pgen.file.TrackPoint> trackPointBeanList) {
List<TrackPoint> trackPointElementList = new ArrayList<TrackPoint>(trackPointBeanList.size());
for(gov.noaa.nws.ncep.ui.pgen.file.TrackPoint trackPointBean : trackPointBeanList) {
java.util.Calendar currentCalendar = null;
if(trackPointBean.getTime() != null) {
currentCalendar = trackPointBean.getTime().toGregorianCalendar();
}
Coordinate currentCoordinate = getCoordinateByTrackPointBean(trackPointBean);
TrackPoint currentTrackPointElement = new TrackPoint(currentCoordinate, currentCalendar);
trackPointElementList.add(currentTrackPointElement);
}
return trackPointElementList;
}
private static Coordinate getCoordinateByTrackPointBean(gov.noaa.nws.ncep.ui.pgen.file.TrackPoint trackPointBean) {
Coordinate coordinate = new Coordinate();
if(trackPointBean.getLocation() != null) {
coordinate.x = trackPointBean.getLocation().getLongitude();
coordinate.y = trackPointBean.getLocation().getLatitude();
}
return coordinate;
}
private static boolean[] getBooleanArrayByBooleanList(List<Boolean> booleanList) {
boolean[] booleanArray = new boolean[booleanList.size()];
int arrayIndex = 0;
for(Boolean currentBoolean : booleanList) {
booleanArray[arrayIndex++] = currentBoolean.booleanValue();
}
return booleanArray;
private static Calendar getFirstOrSecondTimeCalendarByTrackBean(
gov.noaa.nws.ncep.ui.pgen.file.Track trackBean,
boolean isFirstTimeCalendar) {
int indexOffSet = 1;
if (isFirstTimeCalendar)
indexOffSet++;
List<TrackPoint> trackPointElementList = getTrackPointElementListByTrackPointBeanList(trackBean
.getInitialPoints());
if (trackPointElementList == null || trackPointElementList.size() < 2) {
// log.error("Retrieved List<TrackPoint> trackPointElementList is NULL or the initial points are less than 2 points");
return null;
}
int listSize = trackPointElementList.size();
return trackPointElementList.get(listSize - indexOffSet).getTime();
}
private static gov.noaa.nws.ncep.ui.pgen.file.ColorType getColorTypeBeanByColorElement(java.awt.Color colorElement) {
gov.noaa.nws.ncep.ui.pgen.file.ColorType colorTypeBean = new gov.noaa.nws.ncep.ui.pgen.file.ColorType();
gov.noaa.nws.ncep.ui.pgen.file.Color colorBean = new gov.noaa.nws.ncep.ui.pgen.file.Color();
colorBean.setAlpha(colorElement.getAlpha());
colorBean.setBlue(colorElement.getBlue());
colorBean.setRed(colorElement.getRed());
colorBean.setGreen(colorElement.getGreen());
colorTypeBean.setColor(colorBean);
return colorTypeBean;
private static java.awt.Color getColorByColorTypeBean(
gov.noaa.nws.ncep.ui.pgen.file.ColorType colorTypeBean,
boolean isInitColor) {
if (colorTypeBean == null || colorTypeBean.getColor() == null) {
if (isInitColor)
return new Color(0, 0, 255); // return a default color as Blue
else
return new Color(0, 192, 0); // return a green color as the
// default color for extrapPoint
}
gov.noaa.nws.ncep.ui.pgen.file.Color colorBean = colorTypeBean
.getColor();
return new Color(colorBean.getRed(), colorBean.getGreen(),
colorBean.getBlue(), colorBean.getAlpha());
}
private static gov.noaa.nws.ncep.ui.pgen.file.TrackPoint getTrackPointBeanByTrackPointElement(TrackPoint trackPointElement) {
gov.noaa.nws.ncep.ui.pgen.file.TrackPoint trackPointBean = new gov.noaa.nws.ncep.ui.pgen.file.TrackPoint();
if(trackPointElement.getTime() != null) {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(trackPointElement.getTime().getTimeInMillis());
try {
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory.newInstance().newXMLGregorianCalendar(gregorianCalendar);
trackPointBean.setTime(xmlGregorianCalendar);
} catch(DatatypeConfigurationException dce) {
// log.error("Error, instantiating XMLGregorianCalendar failed, error="+dce.getMessage());
}
}
if(trackPointElement.getLocation() != null) {
trackPointBean.location = new gov.noaa.nws.ncep.ui.pgen.file.TrackPoint.Location();
trackPointBean.getLocation().setLongitude(trackPointElement.getLocation().x);
trackPointBean.getLocation().setLatitude(trackPointElement.getLocation().y);
}
return trackPointBean;
private static List<TrackPoint> getTrackPointElementListByTrackPointBeanList(
List<gov.noaa.nws.ncep.ui.pgen.file.TrackPoint> trackPointBeanList) {
List<TrackPoint> trackPointElementList = new ArrayList<TrackPoint>(
trackPointBeanList.size());
for (gov.noaa.nws.ncep.ui.pgen.file.TrackPoint trackPointBean : trackPointBeanList) {
java.util.Calendar currentCalendar = null;
if (trackPointBean.getTime() != null) {
currentCalendar = trackPointBean.getTime()
.toGregorianCalendar();
}
Coordinate currentCoordinate = getCoordinateByTrackPointBean(trackPointBean);
TrackPoint currentTrackPointElement = new TrackPoint(
currentCoordinate, currentCalendar);
trackPointElementList.add(currentTrackPointElement);
}
return trackPointElementList;
}
private static Coordinate getCoordinateByTrackPointBean(
gov.noaa.nws.ncep.ui.pgen.file.TrackPoint trackPointBean) {
Coordinate coordinate = new Coordinate();
if (trackPointBean.getLocation() != null) {
coordinate.x = trackPointBean.getLocation().getLongitude();
coordinate.y = trackPointBean.getLocation().getLatitude();
}
return coordinate;
}
private static boolean[] getBooleanArrayByBooleanList(
List<Boolean> booleanList) {
boolean[] booleanArray = new boolean[booleanList.size()];
int arrayIndex = 0;
for (Boolean currentBoolean : booleanList) {
booleanArray[arrayIndex++] = currentBoolean.booleanValue();
}
return booleanArray;
}
private static gov.noaa.nws.ncep.ui.pgen.file.ColorType getColorTypeBeanByColorElement(
java.awt.Color colorElement) {
gov.noaa.nws.ncep.ui.pgen.file.ColorType colorTypeBean = new gov.noaa.nws.ncep.ui.pgen.file.ColorType();
gov.noaa.nws.ncep.ui.pgen.file.Color colorBean = new gov.noaa.nws.ncep.ui.pgen.file.Color();
colorBean.setAlpha(colorElement.getAlpha());
colorBean.setBlue(colorElement.getBlue());
colorBean.setRed(colorElement.getRed());
colorBean.setGreen(colorElement.getGreen());
colorTypeBean.setColor(colorBean);
return colorTypeBean;
}
private static gov.noaa.nws.ncep.ui.pgen.file.TrackPoint getTrackPointBeanByTrackPointElement(
TrackPoint trackPointElement) {
gov.noaa.nws.ncep.ui.pgen.file.TrackPoint trackPointBean = new gov.noaa.nws.ncep.ui.pgen.file.TrackPoint();
if (trackPointElement.getTime() != null) {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTimeInMillis(trackPointElement.getTime()
.getTimeInMillis());
try {
XMLGregorianCalendar xmlGregorianCalendar = DatatypeFactory
.newInstance().newXMLGregorianCalendar(
gregorianCalendar);
trackPointBean.setTime(xmlGregorianCalendar);
} catch (DatatypeConfigurationException dce) {
// log.error("Error, instantiating XMLGregorianCalendar failed, error="+dce.getMessage());
}
}
if (trackPointElement.getLocation() != null) {
trackPointBean.location = new gov.noaa.nws.ncep.ui.pgen.file.TrackPoint.Location();
trackPointBean.getLocation().setLongitude(
trackPointElement.getLocation().x);
trackPointBean.getLocation().setLatitude(
trackPointElement.getLocation().y);
}
return trackPointBean;
}
private static List<Boolean> getBooleanObjectList(boolean[] booleanArray) {
List<Boolean> booleanList = null;
if(booleanArray == null)
booleanList = new ArrayList<Boolean>();
else
booleanList = new ArrayList<Boolean>(booleanArray.length);
for(boolean booleanValue : booleanArray) {
Boolean booleanObject = new Boolean(booleanValue);
booleanList.add(booleanObject);
}
return booleanList;
List<Boolean> booleanList = null;
if (booleanArray == null)
booleanList = new ArrayList<Boolean>();
else
booleanList = new ArrayList<Boolean>(booleanArray.length);
for (boolean booleanValue : booleanArray) {
Boolean booleanObject = new Boolean(booleanValue);
booleanList.add(booleanObject);
}
return booleanList;
}
}
}

View file

@ -411,27 +411,52 @@
<xsd:sequence>
<xsd:element name="initialColor" type="ColorType"></xsd:element>
<xsd:element name="extrapColor" type="ColorType"></xsd:element>
<xsd:element name="initialPoints" type="TrackPoint" maxOccurs="unbounded" minOccurs="1"></xsd:element>
<xsd:element name="extrapPoints" type="TrackPoint" maxOccurs="unbounded" minOccurs="1"></xsd:element>
<xsd:element name="extraPointTimeTextDisplayIndicator" type="xsd:boolean" maxOccurs="unbounded" minOccurs="1"></xsd:element>
<xsd:element name="initialPoints" type="TrackPoint"
maxOccurs="unbounded" minOccurs="1">
</xsd:element>
<xsd:element name="extrapPoints" type="TrackPoint"
maxOccurs="unbounded" minOccurs="1">
</xsd:element>
<xsd:element name="extraPointTimeTextDisplayIndicator"
type="xsd:boolean" maxOccurs="unbounded" minOccurs="1">
</xsd:element>
</xsd:sequence>
<xsd:attribute name="initialLinePattern" type="xsd:string"></xsd:attribute>
<xsd:attribute name="initialLinePattern"
type="xsd:string">
</xsd:attribute>
<xsd:attribute name="extrapLinePattern" type="xsd:string"></xsd:attribute>
<xsd:attribute name="initialMarker" type="xsd:string"></xsd:attribute>
<xsd:attribute name="extrapMarker" type="xsd:string"></xsd:attribute>
<xsd:attribute name="lineWidth" type="xsd:float"></xsd:attribute>
<xsd:attribute name="fontName" type="xsd:string"></xsd:attribute>
<xsd:attribute name="fontStyle" type="xsd:string"></xsd:attribute>
<xsd:attribute name="fontSize" type="xsd:float"></xsd:attribute>
<xsd:attribute name="pgenType" type="xsd:string"></xsd:attribute>
<xsd:attribute name="pgenCategory" type="xsd:string"></xsd:attribute>
<xsd:attribute name="setTimeButtonSelected" type="xsd:boolean"></xsd:attribute>
<xsd:attribute name="intervalComboSelectedIndex" type="xsd:int"></xsd:attribute>
<xsd:attribute name="intervalTimeTextString" type="xsd:string"></xsd:attribute>
<xsd:attribute name="extraPointTimeDisplayOptionName" type="xsd:string"></xsd:attribute>
<xsd:attribute name="skipFactorTextString" type="xsd:string"></xsd:attribute>
<xsd:attribute name="fontNameComboSelectedIndex" type="xsd:int"></xsd:attribute>
<xsd:attribute name="fontSizeComboSelectedIndex" type="xsd:int"></xsd:attribute>
<xsd:attribute name="fontStyleComboSelectedIndex" type="xsd:int"></xsd:attribute>
<xsd:attribute name="setTimeButtonSelected"
type="xsd:boolean">
</xsd:attribute>
<xsd:attribute name="intervalComboSelectedIndex"
type="xsd:int">
</xsd:attribute>
<xsd:attribute name="intervalTimeTextString"
type="xsd:string">
</xsd:attribute>
<xsd:attribute name="extraPointTimeDisplayOptionName"
type="xsd:string">
</xsd:attribute>
<xsd:attribute name="skipFactorTextString"
type="xsd:string">
</xsd:attribute>
<xsd:attribute name="fontNameComboSelectedIndex"
type="xsd:int">
</xsd:attribute>
<xsd:attribute name="fontSizeComboSelectedIndex"
type="xsd:int">
</xsd:attribute>
<xsd:attribute name="fontStyleComboSelectedIndex"
type="xsd:int">
</xsd:attribute>
</xsd:complexType>
</xsd:element>

View file

@ -14,10 +14,10 @@ import gov.noaa.nws.ncep.ui.pgen.elements.Product;
import gov.noaa.nws.ncep.ui.pgen.file.FileTools;
import gov.noaa.nws.ncep.ui.pgen.file.ProductConverter;
import gov.noaa.nws.ncep.ui.pgen.file.Products;
import gov.noaa.nws.ncep.ui.pgen.rsc.PgenResource;
import gov.noaa.nws.ncep.ui.pgen.store.PgenStorageException;
import gov.noaa.nws.ncep.ui.pgen.store.StorageUtils;
import gov.noaa.nws.ncep.ui.pgen.tools.PgenCycleTool;
import gov.noaa.nws.ncep.ui.pgen.rsc.PgenResource;
import java.io.File;
import java.io.IOException;
@ -61,6 +61,7 @@ import com.vividsolutions.jts.geom.GeometryFactory;
* 05/13 #610 J. Wu Implemented FZLVL range (TTR425)
* 07/13 ? J. Wu Move state list ordering to GfaRules.
* 08/13 TTR714/715 J. Wu Fixed issue type and times.
* 10/14 TTR714 J. Wu Check issue type in get_status.xml.
*
* </pre>
*
@ -70,7 +71,9 @@ import com.vividsolutions.jts.geom.GeometryFactory;
public class GfaGenerate {
private static final String TEXT_TYPE = "TEXT";
private GeometryFactory gf = new GeometryFactory();
private GeometryFactory gf = new GeometryFactory();
private static final String ISSUE_TYPE_FROM_OUTLOOK = "ISSUE_TYPE_FROM_OUTLOOK";
// private final static Logger logger = Logger.getLogger(GfaGenerate.class);
@ -109,20 +112,22 @@ public class GfaGenerate {
/*
* Create an additional smear for the adjacent area.
*/
for ( Gfa g : all) {
Gfa sg = createAdjacentGfa( g );
for (Gfa g : all) {
Gfa sg = createAdjacentGfa(g);
adjusted.add( g );
adjusted.add(g);
if ( sg != null ) {
adjusted.add( sg );
if (sg != null) {
adjusted.add(sg);
}
}
/*
* Find issue type for an Airmet's associated Outlook
* Find issue type for an Airmet's associated Outlook. Note: TTR 714 -
* J. Wu: this may cause other issues. Instead, we should check the
* issue types in "get_status.xsl".
*/
trackOtlkIssueTypeToAirmet( adjusted );
// trackOtlkIssueTypeToAirmet(adjusted);
/*
* Find GFA smears in each area and hazard category, generate xml, and
@ -130,14 +135,14 @@ public class GfaGenerate {
*/
for (String category : categories) {
for (String area : areas) {
List<Gfa> ret = filterSelected( adjusted, area, category );
List<Gfa> ret = filterSelected(adjusted, area, category);
// If no issue/until times, assign them.
for (Gfa de : ret) {
if (!de.isSnapshot()
&& de.getAttribute(Gfa.ISSUE_TIME) == null) {
GfaRules.assignIssueTime( de );
GfaRules.assignIssueTime(de);
}
}
@ -154,24 +159,25 @@ public class GfaGenerate {
/*
* Find freezing range for this area!
*/
String fzlvlRange = findFreezingRange( all, ret, area, category );
String fzlvlRange = findFreezingRange(all, ret, area, category);
/*
* Note - needs to use a copy so it won't change the parent of
* the original G-Airmets, e.g. l.add( de ) will set the parent
* of the 'de" to be "l"!
*/
for ( Gfa gss : ret) {
Gfa gfaCopy = gss.copy();
String otlkIssueType = nvl( gfaCopy.getGfaValue( ISSUE_TYPE_FROM_OUTLOOK ) );
if ( !otlkIssueType.equals( "NRML" ) ) {
gfaCopy.setGfaIssueType( otlkIssueType );
}
if ( fzlvlRange != null ) {
gfaCopy.setGfaValue( Gfa.FZL_RANGE, fzlvlRange );
}
l.add( gfaCopy );
for (Gfa gss : ret) {
Gfa gfaCopy = gss.copy();
/*
* String otlkIssueType = nvl(gfaCopy
* .getGfaValue(ISSUE_TYPE_FROM_OUTLOOK)); if
* (!otlkIssueType.equals("NRML")) {
* gfaCopy.setGfaIssueType( otlkIssueType ); }
*/
if (fzlvlRange != null) {
gfaCopy.setGfaValue(Gfa.FZL_RANGE, fzlvlRange);
}
l.add(gfaCopy);
}
// l.add( ret );
@ -183,7 +189,7 @@ public class GfaGenerate {
// Needs to add an empty Gfa to carry the issue/until for proper
// formatting.
if (ret.size() == 0) {
addNullGfa( products, category, fzlvlRange );
addNullGfa(products, category, fzlvlRange);
}
String xml = SerializationUtil.marshalToXml(products);
@ -191,7 +197,7 @@ public class GfaGenerate {
if (sb.length() > 0 && !sb.toString().endsWith("\n\n")) {
sb.append("\n\n");
}
String prdXml = generateProduct(xml, category, area).trim();
temp.append(prdXml);
@ -233,7 +239,8 @@ public class GfaGenerate {
* @param cats
* @return
*/
private static List<Gfa> filterSelected( List<Gfa> all, String area, String category) {
private static List<Gfa> filterSelected(List<Gfa> all, String area,
String category) {
ArrayList<Gfa> ret = new ArrayList<Gfa>();
@ -258,6 +265,7 @@ public class GfaGenerate {
}
public String generateProduct(String prdxml, String category, String area) {
System.out.println("\nprdxml is:\n" + prdxml + "\n");
String xml1 = prdxml.replaceAll("TURB-HI", "TURB");
String xml = xml1.replaceAll("TURB-LO", "TURB");
@ -279,6 +287,7 @@ public class GfaGenerate {
transformer.transform(xmlSource, result);
res = result.getWriter().toString().trim();
System.out.println("\nres is:\n" + res + "\n");
} catch (Exception e) {
// logger.error( "", e );
@ -295,11 +304,13 @@ public class GfaGenerate {
}
/**
* Create a new smear for smears with two FA areas and re-order the state list.
* Create a new smear for smears with two FA areas and re-order the state
* list.
*
* The States in the primary area precede states in the adjacent area.
* The States in the primary area precede states in the adjacent area.
*
* @param g Gfa to be processed
* @param g
* Gfa to be processed
*
* @return
*/
@ -310,12 +321,12 @@ public class GfaGenerate {
String[] s = nvl(g.getGfaArea()).split("-");
if (s.length > 1) {
String sname = new String( s[1].trim() + "-" + s[0].trim() );
String sname = new String(s[1].trim() + "-" + s[0].trim());
// create an additional smear and re-order state list.
secondg = g.copy();
secondg.setGfaArea( sname );
GfaRules.reorderStateList( secondg );
secondg = g.copy();
secondg.setGfaArea(sname);
GfaRules.reorderStateList(secondg);
}
return secondg;
@ -362,12 +373,12 @@ public class GfaGenerate {
/*
* Adds an empty Gfa to the product so it can pass issue/until time for
* correct formatting. Freezing range should be set if provided.
* correct formatting. Freezing range should be set if provided.
*
* Note - this should be called only when there is no Gfa smears in the
* "prds".
*/
private void addNullGfa(Products prds, String category, String fzlRange ) {
private void addNullGfa(Products prds, String category, String fzlRange) {
gov.noaa.nws.ncep.ui.pgen.file.Gfa fgfa = new gov.noaa.nws.ncep.ui.pgen.file.Gfa();
@ -380,9 +391,9 @@ public class GfaGenerate {
fgfa.setFcstHr("0-6");
// If freezing range is provided, set it and set hazard type as "FZLVL".
if ( fzlRange != null ) {
fgfa.setHazard( "FZLVL" );
fgfa.setFzlRange( fzlRange );
if (fzlRange != null) {
fgfa.setHazard("FZLVL");
fgfa.setFzlRange(fzlRange);
}
//
@ -429,398 +440,395 @@ public class GfaGenerate {
}
/*
* Find the freezing range from FZLVL/M_FZLVL airmets.
* Find the freezing range from FZLVL/M_FZLVL airmets.
*/
private String findFreezingRange( List<Gfa> all, List<Gfa> selected,
String area, String cat ) {
if ( !cat.equalsIgnoreCase( "ZULU" ) ) {
return null;
}
String fzlRange = null;
String topStr = null;
String botStr = null;
/*
* If no FZLVL/M_FZLVL in this area, find range using those outside of
* this area, if any.
*/
if ( selected == null || selected.size() == 0 ) {
int[] extRange = findExernalFzlvlRange( all, area );
if ( extRange[0] != -1 ) {
topStr = padding( extRange[0] );
botStr = padding( extRange[1] );
}
}
else {
/*
* First - find the worst range from existing FZL_RANGE in FZLVL airmets.
* If no existing range found, then find the worst top/bottom from
* FZLVLs' levels ( top = level + 40 and bottom = level - 40)
* Second - find the worst top/bottom from M_FZLVLs
*
* Third - find the worst case range using info from step 1 and 2.
*
*/
int[] existingRange = findExistingFzlRange( all, selected, area );
int[] mfzlRange = findMfzlvlRange( all, selected, area );
private String findFreezingRange(List<Gfa> all, List<Gfa> selected,
String area, String cat) {
if ( existingRange[0] == -1 ) {
existingRange = findFzlvlLevelRange( all, selected, area );
}
if (!cat.equalsIgnoreCase("ZULU")) {
return null;
}
if ( existingRange[0] != -1 || mfzlRange[0] != -1 ) {
topStr = padding( Math.max( existingRange[0], mfzlRange[0] ) );
}
String fzlRange = null;
String topStr = null;
String botStr = null;
if ( existingRange[1] != 9999 || mfzlRange[1] != 9999 ){
botStr = padding( Math.min( existingRange[1], mfzlRange[1] ) );
}
}
// Now create a range string.
if ( topStr != null && botStr != null ) {
fzlRange = area + ";" + topStr + ";" + botStr;
}
return fzlRange;
}
/*
* Retrieve the worst FZLVL range from ranges existing in FZLVL airmet/outlook.
* Such existing range should be in the form as "MIA;160;40", retrievable as
* gfa.getGfaValue( Gfa.FZL_RANGE ).
*/
private int[] findExistingFzlRange( List<Gfa> all, List<Gfa> selected, String area ) {
int[] topBot = { -1, 9999 };
for ( Gfa elem : selected ) {
String gtype = elem.getGfaHazard();
if ( !gtype.equalsIgnoreCase("FZLVL") || elem.isSnapshot() ) {
continue;
}
String range1 = elem.getGfaValue( Gfa.FZL_RANGE );
if ( range1 != null ) {
String[] rangeInfo = range1.split(";");
if ( rangeInfo.length >= 3 && rangeInfo[0].equalsIgnoreCase( area ) ) {
int top1 = -1;
int bot1 = -1;
try {
top1 = Integer.parseInt( rangeInfo[1] );
}
catch ( Exception e ) {
e.printStackTrace();
}
if ( rangeInfo[2].equalsIgnoreCase("SFC") ) {
bot1 = 0;
}
else {
try {
bot1 = Integer.parseInt( rangeInfo[2] );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
if ( top1 >= 0 && bot1 >= 0 ) {
topBot[0] = Math.max( topBot[0], top1 );
topBot[1] = Math.min( topBot[1], bot1 );
}
}
}
}
return topBot;
}
/*
* Retrieve the worst range from existing top/bottom of M_FZLVL airmet/outlook.
* Such top/bottom are retrievable as gfa.getGfaTop() & gfa.getGfaBottom().
*/
private int[] findMfzlvlRange( List<Gfa> all, List<Gfa> selected, String area ) {
int[] topBot = { -1, 9999 };
for ( Gfa elem : selected ) {
String gtype = elem.getGfaHazard();
if ( !gtype.equalsIgnoreCase("M_FZLVL") || elem.isSnapshot() ) {
continue;
}
int top2 = -1;
int bot2 = -1;
if ( elem.getGfaTop() != null ) {
try {
top2 = Integer.parseInt( elem.getGfaTop() );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
String botStr = elem.getGfaBottom();
if ( botStr != null ) {
if ( botStr.equalsIgnoreCase( "SFC") ) {
bot2 = 0;
}
else {
try {
bot2 = Integer.parseInt( elem.getGfaBottom() );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
if ( top2 >= 0 && bot2 >= 0 ) {
topBot[0] = Math.max( topBot[0], top2 );
topBot[1] = Math.min( topBot[1], bot2 );
}
}
return topBot;
}
/*
* Retrieve the worst range from existing levels of FZLVL airmet/outlook.
* Such levels are retrievable as gfa.getGfaValue( Gfa.LEVEL ).
*/
private int[] findFzlvlLevelRange( List<Gfa> all, List<Gfa> selected, String area ) {
int[] topBot = { -1, 9999 };
for ( Gfa elem : selected ) {
String gtype = elem.getGfaHazard();
if ( !gtype.equalsIgnoreCase("FZLVL") || elem.isSnapshot() ) {
continue;
}
int top2 = -1;
int bot2 = -1;
String levelStr = elem.getGfaValue( Gfa.LEVEL );
int lvl = -1;
if ( levelStr != null ) {
if ( levelStr.equalsIgnoreCase( "SFC" ) ) {
top2 = 40;
bot2 = 0;
}
else {
try {
lvl = Integer.parseInt( levelStr );
}
catch ( Exception e ) {
e.printStackTrace();
}
if ( lvl >= 0 && lvl <= 40 ) {
top2 = 40;
bot2 = 0;
}
else {
top2 = lvl + 40;
bot2 = lvl - 40;
}
}
}
if ( top2 >= 0 && bot2 >= 0 ) {
topBot[0] = Math.max( topBot[0], top2 );
topBot[1] = Math.min( topBot[1], bot2 );
}
}
return topBot;
}
/*
* Find the top and base levels for a FA area that is not intersected by any FZLVL
* contours. It sorts all external fzlvls by distance from the area centroid, then
* uses the level from that contour. If the contour is to the left of the area then
* the answer is base = contour level, top = base + 040. If the contour is to the
* right of the area then the answer top = contour level, base = top - 040.
*
* See legacy af_getExternalFzlvlRng() in af_getAirmetXml.c.
*
* Note (1) only FZLVLs are used, not M_FZLVLs.
* (2) All FZLVLs are used, including snapshots.
*
*/
private int[] findExernalFzlvlRange( List<Gfa> all, String area ) {
int[] topBot = { -1, 9999 };
HashMap<String, Geometry> areaBnds = GfaClip.getInstance().getFaAreaBounds();
Coordinate center = gf.createLinearRing( areaBnds.get(area ).getCoordinates() ).getCentroid().getCoordinate();
Gfa closestGfa = null;
double minDist = Double.MAX_VALUE;
for ( Gfa elem : all ) {
String gtype = elem.getGfaHazard();
if ( !gtype.equalsIgnoreCase("FZLVL") ) {
continue;
}
// Find distance from the FA Area's centroid to this FZLVL.
double dist = distance( elem, center );
if ( dist < minDist ) {
minDist = dist;
closestGfa = elem;
/*
* If no FZLVL/M_FZLVL in this area, find range using those outside of
* this area, if any.
*/
if (selected == null || selected.size() == 0) {
int[] extRange = findExernalFzlvlRange(all, area);
if (extRange[0] != -1) {
topStr = padding(extRange[0]);
botStr = padding(extRange[1]);
}
}
if ( closestGfa != null ) {
boolean isLeft = GfaSnap.getInstance().atLeft( center, closestGfa.getLinePoints(),
closestGfa.isClosedLine(), 0.0 );
String levelStr = closestGfa.getGfaValue( Gfa.LEVEL );
int lvl = -1;
if ( levelStr != null ) {
if ( levelStr.equalsIgnoreCase( "SFC" ) ) {
} else {
/*
* First - find the worst range from existing FZL_RANGE in FZLVL
* airmets. If no existing range found, then find the worst
* top/bottom from FZLVLs' levels ( top = level + 40 and bottom =
* level - 40) Second - find the worst top/bottom from M_FZLVLs
*
* Third - find the worst case range using info from step 1 and 2.
*/
int[] existingRange = findExistingFzlRange(all, selected, area);
int[] mfzlRange = findMfzlvlRange(all, selected, area);
if (existingRange[0] == -1) {
existingRange = findFzlvlLevelRange(all, selected, area);
}
if (existingRange[0] != -1 || mfzlRange[0] != -1) {
topStr = padding(Math.max(existingRange[0], mfzlRange[0]));
}
if (existingRange[1] != 9999 || mfzlRange[1] != 9999) {
botStr = padding(Math.min(existingRange[1], mfzlRange[1]));
}
}
// Now create a range string.
if (topStr != null && botStr != null) {
fzlRange = area + ";" + topStr + ";" + botStr;
}
return fzlRange;
}
/*
* Retrieve the worst FZLVL range from ranges existing in FZLVL
* airmet/outlook. Such existing range should be in the form as
* "MIA;160;40", retrievable as gfa.getGfaValue( Gfa.FZL_RANGE ).
*/
private int[] findExistingFzlRange(List<Gfa> all, List<Gfa> selected,
String area) {
int[] topBot = { -1, 9999 };
for (Gfa elem : selected) {
String gtype = elem.getGfaHazard();
if (!gtype.equalsIgnoreCase("FZLVL") || elem.isSnapshot()) {
continue;
}
String range1 = elem.getGfaValue(Gfa.FZL_RANGE);
if (range1 != null) {
String[] rangeInfo = range1.split(";");
if (rangeInfo.length >= 3
&& rangeInfo[0].equalsIgnoreCase(area)) {
int top1 = -1;
int bot1 = -1;
try {
top1 = Integer.parseInt(rangeInfo[1]);
} catch (Exception e) {
e.printStackTrace();
}
if (rangeInfo[2].equalsIgnoreCase("SFC")) {
bot1 = 0;
} else {
try {
bot1 = Integer.parseInt(rangeInfo[2]);
} catch (Exception e) {
e.printStackTrace();
}
}
if (top1 >= 0 && bot1 >= 0) {
topBot[0] = Math.max(topBot[0], top1);
topBot[1] = Math.min(topBot[1], bot1);
}
}
}
}
return topBot;
}
/*
* Retrieve the worst range from existing top/bottom of M_FZLVL
* airmet/outlook. Such top/bottom are retrievable as gfa.getGfaTop() &
* gfa.getGfaBottom().
*/
private int[] findMfzlvlRange(List<Gfa> all, List<Gfa> selected, String area) {
int[] topBot = { -1, 9999 };
for (Gfa elem : selected) {
String gtype = elem.getGfaHazard();
if (!gtype.equalsIgnoreCase("M_FZLVL") || elem.isSnapshot()) {
continue;
}
int top2 = -1;
int bot2 = -1;
if (elem.getGfaTop() != null) {
try {
top2 = Integer.parseInt(elem.getGfaTop());
} catch (Exception e) {
e.printStackTrace();
}
}
String botStr = elem.getGfaBottom();
if (botStr != null) {
if (botStr.equalsIgnoreCase("SFC")) {
bot2 = 0;
} else {
try {
bot2 = Integer.parseInt(elem.getGfaBottom());
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (top2 >= 0 && bot2 >= 0) {
topBot[0] = Math.max(topBot[0], top2);
topBot[1] = Math.min(topBot[1], bot2);
}
}
return topBot;
}
/*
* Retrieve the worst range from existing levels of FZLVL airmet/outlook.
* Such levels are retrievable as gfa.getGfaValue( Gfa.LEVEL ).
*/
private int[] findFzlvlLevelRange(List<Gfa> all, List<Gfa> selected,
String area) {
int[] topBot = { -1, 9999 };
for (Gfa elem : selected) {
String gtype = elem.getGfaHazard();
if (!gtype.equalsIgnoreCase("FZLVL") || elem.isSnapshot()) {
continue;
}
int top2 = -1;
int bot2 = -1;
String levelStr = elem.getGfaValue(Gfa.LEVEL);
int lvl = -1;
if (levelStr != null) {
if (levelStr.equalsIgnoreCase("SFC")) {
top2 = 40;
bot2 = 0;
} else {
try {
lvl = Integer.parseInt(levelStr);
} catch (Exception e) {
e.printStackTrace();
}
if (lvl >= 0 && lvl <= 40) {
top2 = 40;
bot2 = 0;
} else {
top2 = lvl + 40;
bot2 = lvl - 40;
}
}
}
if (top2 >= 0 && bot2 >= 0) {
topBot[0] = Math.max(topBot[0], top2);
topBot[1] = Math.min(topBot[1], bot2);
}
}
return topBot;
}
/*
* Find the top and base levels for a FA area that is not intersected by any
* FZLVL contours. It sorts all external fzlvls by distance from the area
* centroid, then uses the level from that contour. If the contour is to the
* left of the area then the answer is base = contour level, top = base +
* 040. If the contour is to the right of the area then the answer top =
* contour level, base = top - 040.
*
* See legacy af_getExternalFzlvlRng() in af_getAirmetXml.c.
*
* Note (1) only FZLVLs are used, not M_FZLVLs. (2) All FZLVLs are used,
* including snapshots.
*/
private int[] findExernalFzlvlRange(List<Gfa> all, String area) {
int[] topBot = { -1, 9999 };
HashMap<String, Geometry> areaBnds = GfaClip.getInstance()
.getFaAreaBounds();
Coordinate center = gf
.createLinearRing(areaBnds.get(area).getCoordinates())
.getCentroid().getCoordinate();
Gfa closestGfa = null;
double minDist = Double.MAX_VALUE;
for (Gfa elem : all) {
String gtype = elem.getGfaHazard();
if (!gtype.equalsIgnoreCase("FZLVL")) {
continue;
}
// Find distance from the FA Area's centroid to this FZLVL.
double dist = distance(elem, center);
if (dist < minDist) {
minDist = dist;
closestGfa = elem;
}
}
if (closestGfa != null) {
boolean isLeft = GfaSnap.getInstance().atLeft(center,
closestGfa.getLinePoints(), closestGfa.isClosedLine(), 0.0);
String levelStr = closestGfa.getGfaValue(Gfa.LEVEL);
int lvl = -1;
if (levelStr != null) {
if (levelStr.equalsIgnoreCase("SFC")) {
lvl = 0;
}
else {
try {
lvl = Integer.parseInt( levelStr );
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
if ( lvl >= 0 ) {
if ( !isLeft ) { // FZLVL is at right of FA area
topBot[0] = lvl + 40;
topBot[1] = lvl;
}
else { // FZLVL is at left of FA area
topBot[0] = lvl;
topBot[1] = lvl - 40;
if ( topBot[1] < 0 ) topBot[1] = 0;
}
}
}
return topBot;
} else {
try {
lvl = Integer.parseInt(levelStr);
} catch (Exception e) {
e.printStackTrace();
}
}
}
if (lvl >= 0) {
if (!isLeft) { // FZLVL is at right of FA area
topBot[0] = lvl + 40;
topBot[1] = lvl;
} else { // FZLVL is at left of FA area
topBot[0] = lvl;
topBot[1] = lvl - 40;
if (topBot[1] < 0)
topBot[1] = 0;
}
}
}
return topBot;
}
/*
* Pad a value between 0 to 100 in format of "0xx".
*/
private String padding( int value ) {
StringBuilder str = new StringBuilder();
if ( value <= 0 ) {
str.append( "SFC" );
}
else {
if ( value < 100 ) {
str.append( "0" + value );
}
else {
str.append( value );
}
}
return str.toString();
* Pad a value between 0 to 100 in format of "0xx".
*/
private String padding(int value) {
StringBuilder str = new StringBuilder();
if (value <= 0) {
str.append("SFC");
} else {
if (value < 100) {
str.append("0" + value);
} else {
str.append(value);
}
}
return str.toString();
}
/*
* Find the distance from a given point to a Gfa line or polygon.
*/
private double distance( Gfa gfa, Coordinate loc ) {
* Find the distance from a given point to a Gfa line or polygon.
*/
private double distance(Gfa gfa, Coordinate loc) {
double dist = Double.MAX_VALUE;
double minDist = Double.MAX_VALUE;
Object pts[] = gfa.getPoints().toArray();
for ( int ii = 0; ii < pts.length; ii++ ) {
for (int ii = 0; ii < pts.length; ii++) {
if ( ii == pts.length - 1 ) {
if ( gfa.isClosedLine() ) {
dist = PgenResource.distanceFromLineSegment( loc,
if (ii == pts.length - 1) {
if (gfa.isClosedLine()) {
dist = PgenResource.distanceFromLineSegment(loc,
(Coordinate) pts[ii], (Coordinate) pts[0]);
}
else {
} else {
break;
}
}
else {
dist = PgenResource.distanceFromLineSegment( loc, (Coordinate) pts[ii],
(Coordinate) pts[ii + 1]);
} else {
dist = PgenResource.distanceFromLineSegment(loc,
(Coordinate) pts[ii], (Coordinate) pts[ii + 1]);
}
if ( dist < minDist ) {
if (dist < minDist) {
minDist = dist;
}
}
return minDist;
}
}
return minDist;
}
/**
* Find if a smear has an associated outlook that are generated from the same series of
* snapshots (with same hazard type, tag and desk.
* Find if a smear has an associated outlook that are generated from the
* same series of snapshots (with same hazard type, tag and desk.
*
* This is used to get around the issue when a pair of airmet and outlook is generated from
* the same series of snapshots, and the airmet's issue tyep is "NRML" while outlook's issue
* type is not "NRML". In this case, the formatted header should show the outlook's issue type.
* This is used to get around the issue when a pair of airmet and outlook is
* generated from the same series of snapshots, and the airmet's issue type
* is "NRML" while outlook's issue type is not "NRML". In this case, the
* formatted header should show the outlook's issue type.
*
* Note: TTR 714 - 10/2014: for the above case, we should modify
* "get_status.xsl" to get the formatted header by looping through all
* airmets and outlooks instead of modifying it here.
*
* @param all
* @return
*/
private static void trackOtlkIssueTypeToAirmet( List<Gfa> all ) {
private static void trackOtlkIssueTypeToAirmet(List<Gfa> all) {
for ( Gfa gg : all) {
gg.setGfaValue( ISSUE_TYPE_FROM_OUTLOOK, "NRML" );
if ( gg.isAirmet() && "NRML".equalsIgnoreCase( gg.getGfaIssueType() ) ) {
String akey = gg.getGfaHazard() + gg.getGfaTag() + gg.getGfaDesk();
for ( Gfa gotlk : all) {
if ( gotlk.isOutlook() && !("NRML".equalsIgnoreCase( gotlk.getGfaIssueType() ) ) ) {
String okey = gotlk.getGfaHazard() + gotlk.getGfaTag() + gotlk.getGfaDesk();
if ( okey.equals( akey ) ) {
gg.setGfaValue( ISSUE_TYPE_FROM_OUTLOOK, gotlk.getGfaIssueType() );
break;
}
}
}
}
for (Gfa gg : all) {
gg.setGfaValue(ISSUE_TYPE_FROM_OUTLOOK, "NRML");
if (gg.isAirmet() && "NRML".equalsIgnoreCase(gg.getGfaIssueType())) {
String akey = gg.getGfaHazard() + gg.getGfaTag()
+ gg.getGfaDesk();
for (Gfa gotlk : all) {
if (gotlk.isOutlook()
&& !("NRML".equalsIgnoreCase(gotlk
.getGfaIssueType()))) {
String okey = gotlk.getGfaHazard() + gotlk.getGfaTag()
+ gotlk.getGfaDesk();
if (okey.equals(akey)) {
gg.setGfaValue(ISSUE_TYPE_FROM_OUTLOOK,
gotlk.getGfaIssueType());
break;
}
}
}
}
}
}
}

View file

@ -7,6 +7,12 @@
*/
package gov.noaa.nws.ncep.ui.pgen.gfa;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.BOS;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.CHI;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.DFW;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.MIA;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.SFO;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.SLC;
import gov.noaa.nws.ncep.ui.pgen.PgenStaticDataProvider;
import java.awt.Color;
@ -20,8 +26,6 @@ import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.eclipse.swt.graphics.RGB;
import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.*;
/**
* Helper class to read the GFA configuration.
*
@ -41,379 +45,390 @@ import static gov.noaa.nws.ncep.ui.pgen.gfa.Gfa.*;
*/
public class GfaInfo {
// gui settings
private static Document doc;
// gui settings
private static Document doc;
public static final String HAZARD_XPATH = "/root/hazard";
public static final String FCSTHR_XPATH = "/root/fcstHr";
public static final String TAG_XPATH = "/root/tag";
public static final String DESK_XPATH = "/root/desk";
public static final String ISSUE_TYPE_XPATH = "/root/issueType";
public static final String GFA_OTLKGEN_RATIO_XPATH = "/root/gfaOtlkgenRatio";
public static final String AIRMET_ELEMENT_XPATH = "/airmetcycle/element";
public static final String GFA_SNAPSHOT = "snapshot";
public static final String GFA_SMEAR = "smear";
public static final String GFA_OUTLOOK = "outlook";
public static final String HAZARD_XPATH = "/root/hazard";
public static final int GFA_SMEAR_LINEWIDTH = 3;
public static final int GFA_OUTLOOK_LINEWIDTH = 4;
public static final int GFA_OTHER_LINEWIDTH = 2;
public static final String FCSTHR_XPATH = "/root/fcstHr";
/**
* Hazard type vs color array (index means the same as the position
* in fcstHr combo box)
*/
private static HashMap<String, RGB[]> rgbMap;
public static final String TAG_XPATH = "/root/tag";
/**
* Pairs like ("red", new RGB(255, 0, 0)) read from gfa.xml
*/
private static HashMap<String, RGB> definedColors;
/**
* Hazard categories
*/
private static HashMap<String, HazardCategory> hazardCategories;
public enum HazardCategory{
SIERRA, TANGO, ZULU, NONE;
}
public static final String DESK_XPATH = "/root/desk";
/**
* State orders in each FA area.
*/
private static HashMap<String, ArrayList<String> > stateOrderByArea;
/**
* Pairs like ("red", new RGB(255, 0, 0)) read from gfa.xml
*/
private static HashMap<String, RGB> fzlvlSfcColors;
/**
* Getter for the document.
*
* @return
*/
public static Document getDocument() {
if (doc == null) {
readOptions();
}
return doc;
}
public static final String ISSUE_TYPE_XPATH = "/root/issueType";
/**
* Read the menu configuration from gfa.xml file
*/
private static void readOptions() {
File gfainfoFile = PgenStaticDataProvider.getProvider().getStaticFile(
PgenStaticDataProvider.getProvider().getPgenLocalizationRoot() + "gfa.xml");
public static final String GFA_OTLKGEN_RATIO_XPATH = "/root/gfaOtlkgenRatio";
try {
SAXReader reader = new SAXReader();
doc = reader.read(gfainfoFile.getAbsoluteFile());
} catch (Exception e) {
e.printStackTrace();
}
}
public static final String AIRMET_ELEMENT_XPATH = "/airmetcycle/element";
/*
* This method is just to suppress warning
*/
@SuppressWarnings("unchecked")
public static List<Node> selectNodes(String xPath) {
return (List<Node>) GfaInfo.getDocument().selectNodes(xPath);
}
public static final String GFA_SNAPSHOT = "snapshot";
/**
* Creates an rgb map for hazard types and returns the corresponding color.
*
* @param hazard
* @return
*/
public static RGB getRGB(String hazard, int fcstHrIndex) {
if (rgbMap == null) {
loadColors();
}
public static final String GFA_SMEAR = "smear";
if (fcstHrIndex < 0 || fcstHrIndex >= rgbMap.get(hazard).length) {
// take last as default if parameter is out of range (fcstHr=Other)
fcstHrIndex = rgbMap.get(hazard).length-1;
}
public static final String GFA_OUTLOOK = "outlook";
return rgbMap.get(hazard)[fcstHrIndex];
}
/**
* Load colors.
*/
private static void loadColors() {
List<Node> colorNodes = selectNodes("/root/color/value");
public static final int GFA_SMEAR_LINEWIDTH = 3;
definedColors = new HashMap<String, RGB>();
for (Node n : colorNodes) {
int r = Integer.parseInt(n.valueOf("@r"));
int g = Integer.parseInt(n.valueOf("@g"));
int b = Integer.parseInt(n.valueOf("@b"));
// for example, <"red", (255,0,0)>
definedColors.put(n.valueOf("@name"), new RGB(r, g, b));
}
public static final int GFA_OUTLOOK_LINEWIDTH = 4;
List<Node> hazardNodes = selectNodes(HAZARD_XPATH);
List<Node> fcstHrNodes = selectNodes(FCSTHR_XPATH);
public static final int GFA_OTHER_LINEWIDTH = 2;
// hazard type vs. color array (index means the same as the position
// in fcstHr combo box)
rgbMap = new HashMap<String, RGB[]>();
/**
* Hazard type vs color array (index means the same as the position in
* fcstHr combo box)
*/
private static HashMap<String, RGB[]> rgbMap;
for (Node n : hazardNodes) {
RGB[] colors = new RGB[fcstHrNodes.size()];
int i = 0;
for (Node f : fcstHrNodes) {
String type = f.valueOf("@type"); // for example, "smear"
String colorStr = n.valueOf("@" + type); // for example,
// "blue"
colors[i++] = definedColors.get(colorStr);
}
rgbMap.put(n.valueOf("@name"), colors);
}
}
/**
* Pairs like ("red", new RGB(255, 0, 0)) read from gfa.xml
*/
private static HashMap<String, RGB> definedColors;
/**
* Returns the default colors for the hazard and forecast hour pair.
*
* @param hazard
* @param fcstHr
* @return Color[]
*/
public static Color[] getDefaultColors(String hazard, String fcstHr) {
RGB rgb = getDefaultRGB( hazard, fcstHr );
Color color = new Color(rgb.red, rgb.green, rgb.blue);
return new Color[]{color, color};
}
/**
* Hazard categories
*/
private static HashMap<String, HazardCategory> hazardCategories;
/**
* Returns the default color's RGB for the hazard and forecast hour pair.
*
* @param hazard
* @param fcstHr
* @return RGB
*/
public static RGB getDefaultRGB(String hazard, String fcstHr) {
if (definedColors == null) {
loadColors();
}
String xPath = HAZARD_XPATH + "[@name='" + hazard + "']";
List<Node> hazardNodes = selectNodes(xPath);
xPath = FCSTHR_XPATH + "[@name='" + fcstHr + "']";
List<Node> fcsthrNodes = selectNodes(xPath);
if (fcsthrNodes.size() != 1) {
try{
if(fcstHr.indexOf("-") == -1) { // snapshot
xPath = FCSTHR_XPATH + "[@name='0 Z']";
} else {
String second= fcstHr.split("-")[1];
String hour = second.split(":")[0];
if(Integer.parseInt(hour) <=6){ // smear
xPath = FCSTHR_XPATH + "[@name='0-6']";
} else { // outlook
xPath = FCSTHR_XPATH + "[@name='6-9']";
}
}
} catch (Exception e){
xPath = FCSTHR_XPATH + "[@name='Other']";
}
fcsthrNodes = selectNodes(xPath);
}
String gfaType = GFA_SNAPSHOT;
if ( fcsthrNodes.size() != 1 ) { //hard-coded
if ( fcstHr.indexOf("-") >= 0 ) {
String second= fcstHr.split("-")[1];
String hour = second.split(":")[0];
if(Integer.parseInt(hour) <=6) {
gfaType = GFA_SMEAR;
} else {
gfaType = GFA_OUTLOOK;
}
}
}
else {
gfaType = fcsthrNodes.get(0).valueOf("@type"); // from table
}
if (hazardNodes.size() != 1 ) {
throw new IllegalArgumentException("Please check hazard name");
}
String colorStr = hazardNodes.get(0).valueOf("@" + gfaType );
RGB rgb = definedColors.get(colorStr);
return rgb;
}
/**
* Returns the default line width for the forecast hour.
*
* @param fcstHr
* @return
*/
public static int getLineWidth(String fcstHr) {
String xPath = FCSTHR_XPATH + "[@name='" + fcstHr + "']";
List<Node> fcsthrNodes = selectNodes(xPath);
int lineWidth = GFA_OTHER_LINEWIDTH;
if ( fcsthrNodes.size() > 0 ) {
lineWidth = Integer.parseInt( fcsthrNodes.get(0).valueOf("@linewidth") );
}
else {
if ( fcstHr.indexOf("-") >= 0 ) {
String second= fcstHr.split("-")[1];
String hour = second.split(":")[0];
if( Integer.parseInt(hour) <= 6 ) {
lineWidth = GFA_SMEAR_LINEWIDTH;
} else {
lineWidth = GFA_OUTLOOK_LINEWIDTH;
}
}
}
public enum HazardCategory {
SIERRA, TANGO, ZULU, NONE;
}
return lineWidth;
}
public static boolean isFormat(String hazard){
if (definedColors == null) {
loadColors();
}
String xPath = HAZARD_XPATH + "[@name='" + hazard + "']";
List<Node> hazardNodes = selectNodes(xPath);
if (hazardNodes.size() != 1) {
throw new IllegalArgumentException("Please check hazard name");
}
String format = hazardNodes.get(0).valueOf("@format");
return !"false".equals(format);
}
/**
* State orders in each FA area.
*/
private static HashMap<String, ArrayList<String>> stateOrderByArea;
private static HashMap<String, HazardCategory> getHazardCategories() {
if(hazardCategories == null) {
hazardCategories = new HashMap<String, HazardCategory>();
List<Node> nodes = selectNodes(HAZARD_XPATH);
for(Node n: nodes){
String key = n.valueOf("@name");
String category = n.valueOf("@category");
HazardCategory cat = HazardCategory.valueOf(HazardCategory.class, category);
if(cat == null) cat = HazardCategory.NONE;
hazardCategories.put(key, cat);
}
}
return hazardCategories;
}
public static HazardCategory getHazardCategory(String hazard){
return getHazardCategories().get(hazard);
}
public static double getGfaOtlkgenRatio(){
List<Node> nodes = selectNodes(GFA_OTLKGEN_RATIO_XPATH);
Node n = nodes.get(0);
String rationStr = n.getStringValue();
return Double.parseDouble(rationStr);
}
/**
* Pairs like ("red", new RGB(255, 0, 0)) read from gfa.xml
*/
private static HashMap<String, RGB> fzlvlSfcColors;
/**
* Getter for the document.
*
* @return
*/
public static Document getDocument() {
if (doc == null) {
readOptions();
}
return doc;
}
/**
* Read the menu configuration from gfa.xml file
*/
private static void readOptions() {
File gfainfoFile = PgenStaticDataProvider.getProvider().getStaticFile(
PgenStaticDataProvider.getProvider().getPgenLocalizationRoot()
+ "gfa.xml");
try {
SAXReader reader = new SAXReader();
doc = reader.read(gfainfoFile.getAbsoluteFile());
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* This method is just to suppress warning
*/
@SuppressWarnings("unchecked")
public static List<Node> selectNodes(String xPath) {
return (List<Node>) GfaInfo.getDocument().selectNodes(xPath);
}
/**
* Creates an rgb map for hazard types and returns the corresponding color.
*
* @param hazard
* @return
*/
public static RGB getRGB(String hazard, int fcstHrIndex) {
if (rgbMap == null) {
loadColors();
}
if (fcstHrIndex < 0 || fcstHrIndex >= rgbMap.get(hazard).length) {
// take last as default if parameter is out of range (fcstHr=Other)
fcstHrIndex = rgbMap.get(hazard).length - 1;
}
return rgbMap.get(hazard)[fcstHrIndex];
}
/**
* Load colors.
*/
private static void loadColors() {
List<Node> colorNodes = selectNodes("/root/color/value");
definedColors = new HashMap<String, RGB>();
for (Node n : colorNodes) {
int r = Integer.parseInt(n.valueOf("@r"));
int g = Integer.parseInt(n.valueOf("@g"));
int b = Integer.parseInt(n.valueOf("@b"));
// for example, <"red", (255,0,0)>
definedColors.put(n.valueOf("@name"), new RGB(r, g, b));
}
List<Node> hazardNodes = selectNodes(HAZARD_XPATH);
List<Node> fcstHrNodes = selectNodes(FCSTHR_XPATH);
// hazard type vs. color array (index means the same as the position
// in fcstHr combo box)
rgbMap = new HashMap<String, RGB[]>();
for (Node n : hazardNodes) {
RGB[] colors = new RGB[fcstHrNodes.size()];
int i = 0;
for (Node f : fcstHrNodes) {
String type = f.valueOf("@type"); // for example, "smear"
String colorStr = n.valueOf("@" + type); // for example,
// "blue"
colors[i++] = definedColors.get(colorStr);
}
rgbMap.put(n.valueOf("@name"), colors);
}
}
/**
* Returns the default colors for the hazard and forecast hour pair.
*
* @param hazard
* @param fcstHr
* @return Color[]
*/
public static Color[] getDefaultColors(String hazard, String fcstHr) {
RGB rgb = getDefaultRGB(hazard, fcstHr);
Color color = new Color(rgb.red, rgb.green, rgb.blue);
return new Color[] { color, color };
}
/**
* Returns the default color's RGB for the hazard and forecast hour pair.
*
* @param hazard
* @param fcstHr
* @return RGB
*/
public static RGB getDefaultRGB(String hazard, String fcstHr) {
if (definedColors == null) {
loadColors();
}
String xPath = HAZARD_XPATH + "[@name='" + hazard + "']";
List<Node> hazardNodes = selectNodes(xPath);
xPath = FCSTHR_XPATH + "[@name='" + fcstHr + "']";
List<Node> fcsthrNodes = selectNodes(xPath);
if (fcsthrNodes.size() != 1) {
try {
if (fcstHr.indexOf("-") == -1) { // snapshot
xPath = FCSTHR_XPATH + "[@name='0 Z']";
} else {
String second = fcstHr.split("-")[1];
String hour = second.split(":")[0];
if (Integer.parseInt(hour) <= 6) { // smear
xPath = FCSTHR_XPATH + "[@name='0-6']";
} else { // outlook
xPath = FCSTHR_XPATH + "[@name='6-9']";
}
}
} catch (Exception e) {
xPath = FCSTHR_XPATH + "[@name='Other']";
}
fcsthrNodes = selectNodes(xPath);
}
String gfaType = GFA_SNAPSHOT;
if (fcsthrNodes.size() != 1) { // hard-coded
if (fcstHr.indexOf("-") >= 0) {
String second = fcstHr.split("-")[1];
String hour = second.split(":")[0];
if (Integer.parseInt(hour) <= 6) {
gfaType = GFA_SMEAR;
} else {
gfaType = GFA_OUTLOOK;
}
}
} else {
gfaType = fcsthrNodes.get(0).valueOf("@type"); // from table
}
if (hazardNodes.size() != 1) {
throw new IllegalArgumentException("Please check hazard name");
}
String colorStr = hazardNodes.get(0).valueOf("@" + gfaType);
RGB rgb = definedColors.get(colorStr);
return rgb;
}
/**
* Returns the default line width for the forecast hour.
*
* @param fcstHr
* @return
*/
public static int getLineWidth(String fcstHr) {
String xPath = FCSTHR_XPATH + "[@name='" + fcstHr + "']";
List<Node> fcsthrNodes = selectNodes(xPath);
int lineWidth = GFA_OTHER_LINEWIDTH;
if (fcsthrNodes.size() > 0) {
lineWidth = Integer.parseInt(fcsthrNodes.get(0).valueOf(
"@linewidth"));
} else {
if (fcstHr.indexOf("-") >= 0) {
String second = fcstHr.split("-")[1];
String hour = second.split(":")[0];
if (Integer.parseInt(hour) <= 6) {
lineWidth = GFA_SMEAR_LINEWIDTH;
} else {
lineWidth = GFA_OUTLOOK_LINEWIDTH;
}
}
}
return lineWidth;
}
public static boolean isFormat(String hazard) {
if (definedColors == null) {
loadColors();
}
String xPath = HAZARD_XPATH + "[@name='" + hazard + "']";
List<Node> hazardNodes = selectNodes(xPath);
if (hazardNodes.size() != 1) {
throw new IllegalArgumentException("Please check hazard name");
}
String format = hazardNodes.get(0).valueOf("@format");
return !"false".equals(format);
}
private static HashMap<String, HazardCategory> getHazardCategories() {
if (hazardCategories == null) {
hazardCategories = new HashMap<String, HazardCategory>();
List<Node> nodes = selectNodes(HAZARD_XPATH);
for (Node n : nodes) {
String key = n.valueOf("@name");
String category = n.valueOf("@category");
HazardCategory cat = HazardCategory.valueOf(
HazardCategory.class, category);
if (cat == null)
cat = HazardCategory.NONE;
hazardCategories.put(key, cat);
}
}
return hazardCategories;
}
public static HazardCategory getHazardCategory(String hazard) {
return getHazardCategories().get(hazard);
}
public static double getGfaOtlkgenRatio() {
List<Node> nodes = selectNodes(GFA_OTLKGEN_RATIO_XPATH);
Node n = nodes.get(0);
String rationStr = n.getStringValue();
return Double.parseDouble(rationStr);
}
/**
* Return the fixed ordered state list in each FA area.
*/
public static HashMap<String, ArrayList<String> > getStateOrderByArea() {
if ( stateOrderByArea == null ) {
stateOrderByArea = new HashMap<String, ArrayList<String> >();
ArrayList<String> bos = new ArrayList<String>();
String[] bosStr = new String[]{"ME","NH","VT","MA","RI","CT","NY",
"LO","PA","NJ","OH","LE","WV","MD",
"DC", "DE", "VA", "CSTL WTRS"};
for ( String st : bosStr ) {
bos.add( st );
}
stateOrderByArea.put( BOS, bos);
ArrayList<String> mia = new ArrayList<String>();
String[] miaStr = new String[]{"NC", "SC", "GA", "FL" , "CSTL WTRS"};
for ( String st : miaStr ) {
mia.add( st );
}
stateOrderByArea.put( MIA, mia );
public static HashMap<String, ArrayList<String>> getStateOrderByArea() {
ArrayList<String> chi = new ArrayList<String>();
String[] chiStr = new String[]{"ND", "SD", "NE", "KS", "MN", "IA",
"MO", "WI", "LM", "LS", "MI", "LH",
"IL", "IN", "KY"};
for ( String st : chiStr ) {
chi.add( st );
}
stateOrderByArea.put( CHI, chi );
if (stateOrderByArea == null) {
stateOrderByArea = new HashMap<String, ArrayList<String>>();
ArrayList<String> bos = new ArrayList<String>();
String[] bosStr = new String[] { "ME", "NH", "VT", "MA", "RI",
"CT", "NY", "LO", "NJ", "PA", "OH", "LE", "WV", "MD", "DC",
"DE", "VA", "CSTL WTRS" };
for (String st : bosStr) {
bos.add(st);
}
stateOrderByArea.put(BOS, bos);
ArrayList<String> dfw = new ArrayList<String>();
String[] dfwStr = new String[]{"OK", "TX", "AR", "TN", "LA", "MS",
"AL", "CSTL WTRS"};
for ( String st : dfwStr ) {
dfw.add( st );
}
stateOrderByArea.put( DFW, dfw );
ArrayList<String> slc = new ArrayList<String>();
String[] slcStr = new String[]{"ID", "MT", "WY", "NV", "UT", "CO",
"AZ", "NM"} ;
for ( String st : slcStr ) {
slc.add( st );
}
stateOrderByArea.put( SLC, slc );
ArrayList<String> sfo = new ArrayList<String>();
String[] sfoStr = new String[]{"WA", "OR", "CA", "CSTL WTRS"};
for ( String st : sfoStr ) {
sfo.add( st );
}
stateOrderByArea.put( SFO, sfo );
}
return stateOrderByArea;
}
/**
* Get colors for FZLVL SFC snapshot, smear, or outlook.
* Default is "sky".
*/
public static RGB getFzlvlSfcColor( String name ) {
ArrayList<String> mia = new ArrayList<String>();
String[] miaStr = new String[] { "NC", "SC", "GA", "FL",
"CSTL WTRS" };
for (String st : miaStr) {
mia.add(st);
}
stateOrderByArea.put(MIA, mia);
if ( definedColors == null ) {
loadColors();
}
List<Node> colorNodes = selectNodes("/root/fzlvlSFC/value");
if ( fzlvlSfcColors == null ) {
fzlvlSfcColors = new HashMap<String, RGB>();
for ( Node nd : colorNodes ) {
fzlvlSfcColors.put( nd.valueOf("@name"), definedColors.get( nd.valueOf("@nmapcolor") ) );
}
}
RGB clr = fzlvlSfcColors.get( name );
if ( clr == null ) clr = definedColors.get( "sky" );
return clr;
ArrayList<String> chi = new ArrayList<String>();
String[] chiStr = new String[] { "ND", "SD", "NE", "KS", "MN",
"IA", "MO", "WI", "LM", "LS", "MI", "LH", "IL", "IN", "KY" };
for (String st : chiStr) {
chi.add(st);
}
stateOrderByArea.put(CHI, chi);
ArrayList<String> dfw = new ArrayList<String>();
String[] dfwStr = new String[] { "OK", "TX", "AR", "TN", "LA",
"MS", "AL", "CSTL WTRS" };
for (String st : dfwStr) {
dfw.add(st);
}
stateOrderByArea.put(DFW, dfw);
ArrayList<String> slc = new ArrayList<String>();
String[] slcStr = new String[] { "ID", "MT", "WY", "NV", "UT",
"CO", "AZ", "NM" };
for (String st : slcStr) {
slc.add(st);
}
stateOrderByArea.put(SLC, slc);
ArrayList<String> sfo = new ArrayList<String>();
String[] sfoStr = new String[] { "WA", "OR", "CA", "CSTL WTRS" };
for (String st : sfoStr) {
sfo.add(st);
}
stateOrderByArea.put(SFO, sfo);
}
return stateOrderByArea;
}
/**
* Get colors for FZLVL SFC snapshot, smear, or outlook. Default is "sky".
*/
public static RGB getFzlvlSfcColor(String name) {
if (definedColors == null) {
loadColors();
}
List<Node> colorNodes = selectNodes("/root/fzlvlSFC/value");
if (fzlvlSfcColors == null) {
fzlvlSfcColors = new HashMap<String, RGB>();
for (Node nd : colorNodes) {
fzlvlSfcColors.put(nd.valueOf("@name"),
definedColors.get(nd.valueOf("@nmapcolor")));
}
}
RGB clr = fzlvlSfcColors.get(name);
if (clr == null)
clr = definedColors.get("sky");
return clr;
}
}
}

View file

@ -179,7 +179,7 @@ public class ProductManageDialog extends ProductDialog {
* Sets the title of the dialog.
*/
public void setTitle() {
shell.setText("Product Center");
shell.setText("Activity Center");
}
/**
@ -319,7 +319,7 @@ public class ProductManageDialog extends ProductDialog {
titleComp.setLayout(gl0);
Label prds = new Label(titleComp, SWT.NONE);
prds.setText("Products:");
prds.setText("Activities:");
/*
* if ( !compact ) { Button multiSaveBtn = new Button( titleComp,
@ -745,12 +745,8 @@ public class ProductManageDialog extends ProductDialog {
if (!compact) {
Button clrBtn = new Button(layersComp, SWT.PUSH);
if (lyr.isMonoColor()) {
clrBtn.setText("M/F");
} else {
clrBtn.setText("A/F");
}
clrBtn.setText(getDisplayString(lyr.isMonoColor(),
lyr.isFilled()));
setButtonColor(clrBtn, lyr.getColor());
clrBtn.setData(ii);
@ -852,12 +848,8 @@ public class ProductManageDialog extends ProductDialog {
protected void updateDisplayAttr(boolean mono, Color clr, boolean fill) {
if (colorModeBtnInUse >= 0) {
if (mono) {
colorModeBtns.get(colorModeBtnInUse).setText("M/F");
} else {
colorModeBtns.get(colorModeBtnInUse).setText("A/F");
}
colorModeBtns.get(colorModeBtnInUse).setText(
getDisplayString(mono, fill));
layerList.get(colorModeBtnInUse).setMonoColor(mono);
layerList.get(colorModeBtnInUse).setColor(clr);
@ -2188,4 +2180,25 @@ public class ProductManageDialog extends ProductDialog {
exitProductManage();
}
/*
* Build a string based on given Mono color and fill flags..
*/
private String getDisplayString(boolean monoClr, boolean fill) {
String dispStr = "";
if (monoClr) {
if (fill)
dispStr += "M/F ";
else
dispStr += "M/N";
} else {
if (fill)
dispStr += "A/F ";
else
dispStr += "A/N ";
}
return dispStr;
}
}

View file

@ -11,10 +11,10 @@ import gov.noaa.nws.ncep.ui.pgen.PgenUtil;
import gov.noaa.nws.ncep.ui.pgen.producttypes.PgenLayer;
import gov.noaa.nws.ncep.ui.pgen.producttypes.ProductType;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.awt.Color;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
@ -29,13 +29,13 @@ import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;
@ -49,7 +49,7 @@ import org.eclipse.swt.widgets.ToolItem;
* 09/09 #151 J. Wu Initial creation.
* 01/11 #151 J. Wu updated to show info in a product type.
* 09/11 #335 J. Wu updated with new activity type definition.
* 09/11 #335 J. Wu made cascading menu for activity type/subtype.
* 09/11 #335 J. Wu made cascading menu for activity type/subtype.
*
* </pre>
*
@ -60,497 +60,500 @@ import org.eclipse.swt.widgets.ToolItem;
public class ProductNameDialog extends ProductDialog {
private Text nameText = null;
private Combo typeCombo = null;
private Composite typeComp = null;
private Text typeText = null;
private ToolBar typeToolBar = null;
private Text forecasterText = null;
private Text centerText = null;
private Text nameText = null;
private Combo typeCombo = null;
private Composite typeComp = null;
private Text typeText = null;
private ToolBar typeToolBar = null;
private Text forecasterText = null;
private Text centerText = null;
private Button saveLayerBtn = null;
private Text outputFileTxt = null;
private Group layersGrp = null;
private String initialOutput = null;
private Text outputFileTxt = null;
private Group layersGrp = null;
private String initialOutput = null;
private ProductManageDialog prdManageDlg = null;
/**
/**
* Constructor.
*/
public ProductNameDialog( Shell parentShell, ProductManageDialog dlg ) {
super( parentShell );
prdManageDlg = dlg;
}
/**
* Sets the title of the dialog.
*/
public void setTitle() {
shell.setText( "Edit Product" );
public ProductNameDialog(Shell parentShell, ProductManageDialog dlg) {
super(parentShell);
prdManageDlg = dlg;
}
/**
* Creates the main layout for the shell.
* Sets the title of the dialog.
*/
public void setTitle() {
shell.setText("Edit Activity");
}
/**
* Creates the main layout for the shell.
*/
public void setLayout() {
GridLayout mainLayout = new GridLayout( 1, true );
GridLayout mainLayout = new GridLayout(1, true);
mainLayout.marginHeight = 1;
mainLayout.marginWidth = 1;
shell.setLayout( mainLayout );
shell.setLayout(mainLayout);
}
/**
* Set the default location.
* Set the default location.
*
* @param parent
*/
public void setDefaultLocation( Shell parent ) {
public void setDefaultLocation(Shell parent) {
if ( shellLocation == null ) {
Point pt = parent.getLocation();
shell.setLocation( pt.x + 420, pt.y + 200 );
} else {
shell.setLocation(shellLocation);
}
if (shellLocation == null) {
Point pt = parent.getLocation();
shell.setLocation(pt.x + 420, pt.y + 200);
} else {
shell.setLocation(shellLocation);
}
}
/**
* Initialize the dialog components.
*/
public void initializeComponents() {
// initialOutput = prdManageDlg.getPrdOutputFile( prdManageDlg.getActiveProduct() );
initialOutput = prdManageDlg.getActiveProduct().getOutputFile();
Composite main = new Composite( shell, SWT.NONE );
GridLayout gl1 = new GridLayout( 1, false );
main.setLayout( gl1 );
Composite top = new Composite( main, SWT.NONE );
GridLayout gl = new GridLayout( 2, false );
top.setLayout( gl );
GridData gd = new GridData( SWT.FILL, SWT.DEFAULT, true, false );
Label pname = new Label( top, SWT.NONE );
pname.setText( "Name:");
nameText = new Text( top, SWT.SINGLE | SWT.BORDER );
nameText.setLayoutData( new GridData( 100, 20 ) );
nameText.setEditable( true );
nameText.setText( prdManageDlg.getActiveProduct().getName() );
// initialOutput = prdManageDlg.getPrdOutputFile(
// prdManageDlg.getActiveProduct() );
initialOutput = prdManageDlg.getActiveProduct().getOutputFile();
Composite main = new Composite(shell, SWT.NONE);
GridLayout gl1 = new GridLayout(1, false);
main.setLayout(gl1);
Composite top = new Composite(main, SWT.NONE);
GridLayout gl = new GridLayout(2, false);
top.setLayout(gl);
GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false);
Label pname = new Label(top, SWT.NONE);
pname.setText("Name:");
nameText = new Text(top, SWT.SINGLE | SWT.BORDER);
nameText.setLayoutData(new GridData(100, 20));
nameText.setEditable(true);
nameText.setText(prdManageDlg.getActiveProduct().getName());
Label ptype = new Label(top, SWT.NONE);
ptype.setText("Type:");
Label ptype = new Label( top, SWT.NONE );
ptype.setText( "Type:");
String curType = prdManageDlg.getActiveProduct().getType();
typeComp = new Composite( top, SWT.LEFT );
typeComp.setLayout( new GridLayout( 2, false ) );
typeText = new Text( typeComp, SWT.LEFT | SWT.BORDER );
typeText.setSize( 300, 20 );
typeText.setText( curType );
typeText.setData( curType );
typeText.setEditable( false );
typeToolBar = new ToolBar( typeComp, SWT.HORIZONTAL );
final ToolItem ti = new ToolItem( typeToolBar, SWT.DROP_DOWN );
ti.setEnabled( true );
final Menu mu = new Menu( shell.getShell(), SWT.POP_UP );
MenuItem mi1 = new MenuItem( mu, SWT.PUSH, 0 );
mi1.setText( "Default" );
mi1.setData( "Default" );
mi1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
typeText.setText( ((MenuItem)e.widget).getData().toString() );
typeText.pack();
typeComp.pack();
typeComp.getParent().pack();
switchProductType( "Default" );
}
});
int ntyp = 1;
ArrayList<String> typeUsed = new ArrayList<String>();
for ( String ptypName : prdManageDlg.prdTypesMap.keySet() ) {
ProductType prdType = prdManageDlg.prdTypesMap.get( ptypName );
LinkedHashMap<String, String> subtypesNalias = prdManageDlg.getSubtypes( prdType.getType(), true );
if ( (ptypName.equals( prdType.getName() ) &&
!prdType.getType().equals( prdType.getName() ) ) ||
!prdManageDlg.hasSubtypes( subtypesNalias.values() ) ) {
MenuItem typeItem = new MenuItem( mu, SWT.PUSH, ntyp );
typeItem.setText( ptypName );
typeItem.setData( ptypName );
typeItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String typeName = ((MenuItem)e.widget).getData().toString();
typeText.setText( typeName );
typeText.pack();
typeComp.pack();
typeComp.getParent().pack();
switchProductType( typeName );
}
});
}
else {
if ( typeUsed.contains( prdType.getType() ) ) {
continue;
}
else {
typeUsed.add( prdType.getType() );
}
MenuItem typeItem = new MenuItem( mu, SWT.CASCADE, ntyp );
typeItem.setText( prdType.getType() );
Menu submenu = new Menu( typeItem );
typeItem.setMenu( submenu );
for ( String styp : subtypesNalias.keySet() ) {
MenuItem subtypeItem = new MenuItem( submenu, SWT.PUSH );
subtypeItem.setText( subtypesNalias.get( styp ) );
subtypeItem.setData( styp );
typeComp = new Composite(top, SWT.LEFT);
typeComp.setLayout(new GridLayout(2, false));
subtypeItem.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String typeName = ((MenuItem)e.widget).getData().toString();
typeText.setText( typeName );
typeText.pack();
typeComp.pack();
typeComp.getParent().pack();
switchProductType( typeName);
}
});
}
typeText = new Text(typeComp, SWT.LEFT | SWT.BORDER);
typeText.setSize(300, 20);
typeText.setText(curType);
typeText.setData(curType);
typeText.setEditable(false);
typeToolBar = new ToolBar(typeComp, SWT.HORIZONTAL);
final ToolItem ti = new ToolItem(typeToolBar, SWT.DROP_DOWN);
ti.setEnabled(true);
final Menu mu = new Menu(shell.getShell(), SWT.POP_UP);
MenuItem mi1 = new MenuItem(mu, SWT.PUSH, 0);
mi1.setText("Default");
mi1.setData("Default");
mi1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
typeText.setText(((MenuItem) e.widget).getData().toString());
typeText.pack();
typeComp.pack();
typeComp.getParent().pack();
switchProductType("Default");
}
ntyp++;
}
ti.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
Rectangle bounds = ti.getBounds();
Point point = typeToolBar.toDisplay( bounds.x, bounds.y + bounds.height );
mu.setLocation( point );
mu.setVisible( true );
}
});
Label pfst = new Label( top, SWT.NONE );
pfst.setText( "Forecaster:");
forecasterText = new Text( top, SWT.SINGLE | SWT.BORDER );
forecasterText.setLayoutData( new GridData( 100, 20 ) );
forecasterText.setEditable( true );
forecasterText.setText( prdManageDlg.getActiveProduct().getForecaster() );
Label pcnt = new Label( top, SWT.NONE );
pcnt.setText( "Center:");
centerText = new Text( top, SWT.SINGLE | SWT.BORDER );
centerText.setLayoutData( new GridData( 100, 20 ) );
centerText.setEditable( true );
centerText.setText( prdManageDlg.getActiveProduct().getCenter() );
Group typeInfoGrp = new Group( main, SWT.SHADOW_IN );
typeInfoGrp.setLayout( new GridLayout( 1, false) );
typeInfoGrp.setText( "Product Type Information" );
Composite bot1 = new Composite( typeInfoGrp, SWT.NONE );
bot1.setLayout( new GridLayout( 2, false) );
Composite bot2 = new Composite( typeInfoGrp, SWT.NONE );
bot2.setLayout( new GridLayout( 3, false) );
Label psave = new Label( bot1, SWT.NONE );
psave.setText( "Save Layers:");
saveLayerBtn = new Button( bot1, SWT.CHECK );
saveLayerBtn.setSelection( prdManageDlg.getActiveProduct().isSaveLayers() );
//Create a composite for output file name
Label outputLbl = new Label( bot2, SWT.LEFT );
outputLbl.setText("Output:");
outputFileTxt = new Text( bot2, SWT.SINGLE | SWT.BORDER );
outputFileTxt.setLayoutData( new GridData( 150, 20 ) );
outputFileTxt.setEditable( true );
if ( initialOutput != null ) {
outputFileTxt.setText( initialOutput );
}
else {
outputFileTxt.setText( "" );
}
int ntyp = 1;
ArrayList<String> typeUsed = new ArrayList<String>();
for (String ptypName : prdManageDlg.prdTypesMap.keySet()) {
Button browseBtn = new Button( bot2, SWT.PUSH );
browseBtn.setText( "Browse");
layersGrp = new Group( typeInfoGrp, SWT.NONE );
layersGrp.setLayout( new GridLayout( 1, false) );
layersGrp.setText( "Layers Defined");
String prevType = prdManageDlg.getActiveProduct().getType();
createLayersTemplate( layersGrp , prevType );
browseBtn.addSelectionListener( new SelectionAdapter() {
public void widgetSelected( SelectionEvent event ) {
createFileText( outputFileTxt, initialOutput );
ProductType prdType = prdManageDlg.prdTypesMap.get(ptypName);
LinkedHashMap<String, String> subtypesNalias = prdManageDlg
.getSubtypes(prdType.getType(), true);
if ((ptypName.equals(prdType.getName()) && !prdType.getType()
.equals(prdType.getName()))
|| !prdManageDlg.hasSubtypes(subtypesNalias.values())) {
MenuItem typeItem = new MenuItem(mu, SWT.PUSH, ntyp);
typeItem.setText(ptypName);
typeItem.setData(ptypName);
typeItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String typeName = ((MenuItem) e.widget).getData()
.toString();
typeText.setText(typeName);
typeText.pack();
typeComp.pack();
typeComp.getParent().pack();
switchProductType(typeName);
}
});
} else {
if (typeUsed.contains(prdType.getType())) {
continue;
} else {
typeUsed.add(prdType.getType());
}
MenuItem typeItem = new MenuItem(mu, SWT.CASCADE, ntyp);
typeItem.setText(prdType.getType());
Menu submenu = new Menu(typeItem);
typeItem.setMenu(submenu);
for (String styp : subtypesNalias.keySet()) {
MenuItem subtypeItem = new MenuItem(submenu, SWT.PUSH);
subtypeItem.setText(subtypesNalias.get(styp));
subtypeItem.setData(styp);
subtypeItem.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String typeName = ((MenuItem) e.widget).getData()
.toString();
typeText.setText(typeName);
typeText.pack();
typeComp.pack();
typeComp.getParent().pack();
switchProductType(typeName);
}
});
}
}
});
browseBtn.setEnabled( false );
ntyp++;
}
ti.addListener(SWT.Selection, new Listener() {
public void handleEvent(Event event) {
Rectangle bounds = ti.getBounds();
Point point = typeToolBar.toDisplay(bounds.x, bounds.y
+ bounds.height);
mu.setLocation(point);
mu.setVisible(true);
}
});
Label pfst = new Label(top, SWT.NONE);
pfst.setText("Forecaster:");
forecasterText = new Text(top, SWT.SINGLE | SWT.BORDER);
forecasterText.setLayoutData(new GridData(100, 20));
forecasterText.setEditable(true);
forecasterText.setText(prdManageDlg.getActiveProduct().getForecaster());
Label pcnt = new Label(top, SWT.NONE);
pcnt.setText("Center:");
centerText = new Text(top, SWT.SINGLE | SWT.BORDER);
centerText.setLayoutData(new GridData(100, 20));
centerText.setEditable(true);
centerText.setText(prdManageDlg.getActiveProduct().getCenter());
Group typeInfoGrp = new Group(main, SWT.SHADOW_IN);
typeInfoGrp.setLayout(new GridLayout(1, false));
typeInfoGrp.setText("Product Type Information");
Composite bot1 = new Composite(typeInfoGrp, SWT.NONE);
bot1.setLayout(new GridLayout(2, false));
Composite bot2 = new Composite(typeInfoGrp, SWT.NONE);
bot2.setLayout(new GridLayout(3, false));
Label psave = new Label(bot1, SWT.NONE);
psave.setText("Save Layers:");
saveLayerBtn = new Button(bot1, SWT.CHECK);
saveLayerBtn.setSelection(prdManageDlg.getActiveProduct()
.isSaveLayers());
// Create a composite for output file name
Label outputLbl = new Label(bot2, SWT.LEFT);
outputLbl.setText("Output:");
outputFileTxt = new Text(bot2, SWT.SINGLE | SWT.BORDER);
outputFileTxt.setLayoutData(new GridData(150, 20));
outputFileTxt.setEditable(true);
if (initialOutput != null) {
outputFileTxt.setText(initialOutput);
} else {
outputFileTxt.setText("");
}
Button browseBtn = new Button(bot2, SWT.PUSH);
browseBtn.setText("Browse");
layersGrp = new Group(typeInfoGrp, SWT.NONE);
layersGrp.setLayout(new GridLayout(1, false));
layersGrp.setText("Layers Defined");
String prevType = prdManageDlg.getActiveProduct().getType();
createLayersTemplate(layersGrp, prevType);
browseBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
createFileText(outputFileTxt, initialOutput);
}
});
browseBtn.setEnabled(false);
// Create control buttons
Composite centeredComp = new Composite( shell, SWT.NONE );
GridLayout gl2 = new GridLayout( 2, true );
centeredComp.setLayout( gl2 );
centeredComp.setLayoutData( gd );
Composite centeredComp = new Composite(shell, SWT.NONE);
GridLayout gl2 = new GridLayout(2, true);
centeredComp.setLayout(gl2);
centeredComp.setLayoutData(gd);
Button acceptBtn = new Button( centeredComp, SWT.NONE );
acceptBtn.setText( "Accept" );
acceptBtn.setLayoutData( gd );
acceptBtn.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
updateProduct();
close();
}
});
Button cancelBtn = new Button( centeredComp, SWT.NONE );
cancelBtn.setText( " Close " );
cancelBtn.setLayoutData( gd );
cancelBtn.addSelectionListener( new SelectionAdapter() {
Button acceptBtn = new Button(centeredComp, SWT.NONE);
acceptBtn.setText("Accept");
acceptBtn.setLayoutData(gd);
acceptBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
prdManageDlg.setOpenPrdNameDlg( false );
close();
updateProduct();
close();
}
});
}
/*
* Update the product attributes in the product control window.
*/
private void updateProduct() {
// selectProductType();
HashMap<String, String> attr = new HashMap<String, String>();
attr.put( "name", nameText.getText() );
attr.put( "type", typeText.getText() );
attr.put( "forecaster", forecasterText.getText() );
attr.put( "center", centerText.getText() );
if (saveLayerBtn.getSelection() ) {
attr.put( "saveLayers", "true" );
}
else {
attr.put( "saveLayers", "false" );
}
attr.put( "outputfile", outputFileTxt.getText() );
if ( prdManageDlg != null ) {
prdManageDlg.updateProductAttr( attr );
}
}
/*
* Select a product type with confirmation.
*/
private void selectProductType() {
if ( !(typeCombo.getText().equals( prdManageDlg.getActiveProduct().getType() ) ) ) {
/*
MessageDialog confirmDlg = new MessageDialog(
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
"Confirm type", null,
"Are you sure you want to switch from type " +
prdManageDlg.getActiveProduct().getType()
+ " to type " + typeCombo.getText() + "?",
MessageDialog.QUESTION, new String[]{"OK", "Cancel"}, 0);
confirmDlg.open();
if ( confirmDlg.getReturnCode() != MessageDialog.OK ) {
typeCombo.select( curType );
Button cancelBtn = new Button(centeredComp, SWT.NONE);
cancelBtn.setText(" Close ");
cancelBtn.setLayoutData(gd);
cancelBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent event) {
prdManageDlg.setOpenPrdNameDlg(false);
close();
}
*/
// typeCombo.select( curType );
});
}
/*
* Update the product attributes in the product control window.
*/
private void updateProduct() {
// selectProductType();
HashMap<String, String> attr = new HashMap<String, String>();
attr.put("name", nameText.getText());
attr.put("type", typeText.getText());
attr.put("forecaster", forecasterText.getText());
attr.put("center", centerText.getText());
if (saveLayerBtn.getSelection()) {
attr.put("saveLayers", "true");
} else {
attr.put("saveLayers", "false");
}
attr.put("outputfile", outputFileTxt.getText());
if (prdManageDlg != null) {
prdManageDlg.updateProductAttr(attr);
}
}
/*
* Select a product type with confirmation.
*/
private void selectProductType() {
if (!(typeCombo.getText().equals(prdManageDlg.getActiveProduct()
.getType()))) {
/*
* MessageDialog confirmDlg = new MessageDialog(
* PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
* "Confirm type", null,
* "Are you sure you want to switch from type " +
* prdManageDlg.getActiveProduct().getType() + " to type " +
* typeCombo.getText() + "?", MessageDialog.QUESTION, new
* String[]{"OK", "Cancel"}, 0);
*
* confirmDlg.open();
*
* if ( confirmDlg.getReturnCode() != MessageDialog.OK ) {
* typeCombo.select( curType ); }
*/
// typeCombo.select( curType );
}
}
/**
* Create a file/path input dialog with a Text and a "Browse" button.
*
* @param txt
* @return
*/
private void createFileText( Text txt, String initialFile ) {
String[] filterNames = new String[] { "*.xml", "All Files (*)" };
String[] filterExtensions = new String[] {"*.xml", "*" };
// String filterPath = PgenUtil.CURRENT_WORKING_DIRECTORY;
String filterPath = PgenUtil.getWorkingDirectory();
String defaultFile = new String( "default.xml" );
if ( initialFile != null ) {
int index = initialFile.lastIndexOf('/');
if ( index >= 0 ) {
defaultFile = initialFile.substring( index+1, initialFile.length() );
filterPath = initialFile.substring( 0, index);
}
else {
defaultFile = new String( initialFile );
}
}
String selectedFile = selectFile( shell, SWT.OPEN, filterNames,
filterExtensions, filterPath, defaultFile, true );
if ( selectedFile != null ) {
txt.setText( selectedFile );
}
}
/**
* Create a file selection dialog
*
* @param sh
* @param mode
* @param nameFilter
* @param extensionFilter
* @param pathFilter
* @param defaultFile
* @param overWrite
* @return dialog.open()
*/
private String selectFile( Shell sh, int mode, String[] nameFilter,
String[] extensionFilter, String pathFilter,
String defaultFile, boolean overWrite ) {
FileDialog dialog = new FileDialog( sh, mode );
dialog.setFilterNames( nameFilter );
dialog.setFilterExtensions( extensionFilter );
dialog.setFilterPath( pathFilter );
if ( defaultFile != null ) {
dialog.setFileName ( defaultFile );
}
dialog.setOverwrite( overWrite );
return dialog.open();
}
/*
* Create name, on/off, and color mode buttons for defined layers
}
/**
* Create a file/path input dialog with a Text and a "Browse" button.
*
* @param txt
* @return
*/
private void createLayersTemplate( Composite cmp, String typ ) {
Control[] wids = cmp.getChildren();
for ( int jj = 0; jj < wids.length; jj++ ) {
wids[jj].dispose();
}
cmp.pack();
shell.pack( true );
ProductType prdtype = prdManageDlg.prdTypesMap.get( typ );
if ( prdtype == null || prdtype.getPgenLayer() == null ||
prdtype.getPgenLayer().size() <= 0 ) {
return;
private void createFileText(Text txt, String initialFile) {
String[] filterNames = new String[] { "*.xml", "All Files (*)" };
String[] filterExtensions = new String[] { "*.xml", "*" };
// String filterPath = PgenUtil.CURRENT_WORKING_DIRECTORY;
String filterPath = PgenUtil.getWorkingDirectory();
String defaultFile = new String("default.xml");
if (initialFile != null) {
int index = initialFile.lastIndexOf('/');
if (index >= 0) {
defaultFile = initialFile.substring(index + 1,
initialFile.length());
filterPath = initialFile.substring(0, index);
} else {
defaultFile = new String(initialFile);
}
}
Composite layersComp = new Composite( cmp, SWT.NONE );
GridLayout gl = new GridLayout( 3, false );
String selectedFile = selectFile(shell, SWT.OPEN, filterNames,
filterExtensions, filterPath, defaultFile, true);
if (selectedFile != null) {
txt.setText(selectedFile);
}
}
/**
* Create a file selection dialog
*
* @param sh
* @param mode
* @param nameFilter
* @param extensionFilter
* @param pathFilter
* @param defaultFile
* @param overWrite
* @return dialog.open()
*/
private String selectFile(Shell sh, int mode, String[] nameFilter,
String[] extensionFilter, String pathFilter, String defaultFile,
boolean overWrite) {
FileDialog dialog = new FileDialog(sh, mode);
dialog.setFilterNames(nameFilter);
dialog.setFilterExtensions(extensionFilter);
dialog.setFilterPath(pathFilter);
if (defaultFile != null) {
dialog.setFileName(defaultFile);
}
dialog.setOverwrite(overWrite);
return dialog.open();
}
/*
* Create name, on/off, and color mode buttons for defined layers
*/
private void createLayersTemplate(Composite cmp, String typ) {
Control[] wids = cmp.getChildren();
for (int jj = 0; jj < wids.length; jj++) {
wids[jj].dispose();
}
cmp.pack();
shell.pack(true);
ProductType prdtype = prdManageDlg.prdTypesMap.get(typ);
if (prdtype == null || prdtype.getPgenLayer() == null
|| prdtype.getPgenLayer().size() <= 0) {
return;
}
Composite layersComp = new Composite(cmp, SWT.NONE);
GridLayout gl = new GridLayout(3, false);
gl.marginHeight = 1;
gl.marginWidth = 1;
gl.verticalSpacing = 1;
gl.horizontalSpacing = 10;
layersComp.setLayout( gl );
for ( PgenLayer lyr : prdtype.getPgenLayer() ) {
Button nameBtn = new Button( layersComp, SWT.PUSH );
nameBtn.setText( lyr.getName() );
Button dispBtn = new Button( layersComp, SWT.CHECK );
dispBtn.setSelection( lyr.isOnOff() );
dispBtn.setEnabled( false );
Button clrBtn = new Button( layersComp, SWT.PUSH );
clrBtn.setText( "A/F" );
Color clr = new Color( lyr.getColor().getRed(),
lyr.getColor().getGreen(),
lyr.getColor().getBlue(),
lyr.getColor().getAlpha() );
layersComp.setLayout(gl);
setButtonColor( clrBtn, clr );
}
cmp.pack();
shell.pack( true );
}
/*
* Switch to a new type
*/
private void switchProductType( String newType ) {
for (PgenLayer lyr : prdtype.getPgenLayer()) {
createLayersTemplate( layersGrp, newType );
nameText.setText( newType );
saveLayerBtn.setSelection( false );
outputFileTxt.setText( "" );
outputFileTxt.setEditable( false );
Button nameBtn = new Button(layersComp, SWT.PUSH);
nameBtn.setText(lyr.getName());
ProductType ptyp = prdManageDlg.prdTypesMap.get( newType );
if ( ptyp != null ) {
if ( ptyp.getPgenSave() != null ) {
if ( ptyp.getPgenSave().getOutputFile() != null ) {
outputFileTxt.setText( ptyp.getPgenSave().getOutputFile() );
}
if ( ptyp.getPgenSave().isSaveLayers() != null ) {
saveLayerBtn.setSelection( ptyp.getPgenSave().isSaveLayers() );
}
}
Button dispBtn = new Button(layersComp, SWT.CHECK);
dispBtn.setSelection(lyr.isOnOff());
dispBtn.setEnabled(false);
Button clrBtn = new Button(layersComp, SWT.PUSH);
clrBtn.setText("A/F");
Color clr = new Color(lyr.getColor().getRed(), lyr.getColor()
.getGreen(), lyr.getColor().getBlue(), lyr.getColor()
.getAlpha());
setButtonColor(clrBtn, clr);
}
cmp.pack();
shell.pack(true);
}
/*
* Switch to a new type
*/
private void switchProductType(String newType) {
createLayersTemplate(layersGrp, newType);
nameText.setText(newType);
saveLayerBtn.setSelection(false);
outputFileTxt.setText("");
outputFileTxt.setEditable(false);
ProductType ptyp = prdManageDlg.prdTypesMap.get(newType);
if (ptyp != null) {
if (ptyp.getPgenSave() != null) {
if (ptyp.getPgenSave().getOutputFile() != null) {
outputFileTxt.setText(ptyp.getPgenSave().getOutputFile());
}
if (ptyp.getPgenSave().isSaveLayers() != null) {
saveLayerBtn
.setSelection(ptyp.getPgenSave().isSaveLayers());
}
}
}
}
}

View file

@ -143,7 +143,9 @@ import com.vividsolutions.jts.geom.Point;
* 03/13 #927 B. Yin Implemented IContextMenuProvider interface
* 04/13 #874 B. Yin Added a method replaceElements with parameter parent.
* 04/13 #977 S. Gilbert PGEN Database support
* 11/13 TTR 752 J. Wu Add methods for CCFP text auto placement.
* 09/14 TTR972 J. Wu "Filled" object on the active layer should be
* drawn as "filled" even if the "filled" flag for
* the layer is "false".
* </pre>
*
* @author B. Yin
@ -1841,6 +1843,12 @@ public class PgenResource extends
dprops.setLayerMonoColor(layer.isMonoColor());
dprops.setLayerColor(layer.getColor());
dprops.setLayerFilled(layer.isFilled());
} else {
/*
* "Filled" should always be set to "true" for displaying the
* active layer.
*/
dprops.setLayerFilled(true);
}
Iterator<DrawableElement> iterator = layer.createDEIterator();
@ -1991,7 +1999,6 @@ public class PgenResource extends
PaintProperties paintProps, DisplayProperties dispProps) {
if (filters.acceptOnce(de)) {
if (!displayMap.containsKey(de)) {
AbstractElementContainer container = ElementContainerFactory
.createContainer(de, descriptor, target);

View file

@ -23,7 +23,6 @@ import gov.noaa.nws.ncep.ui.pgen.display.AbstractElementContainer;
import gov.noaa.nws.ncep.ui.pgen.display.DefaultElementContainer;
import gov.noaa.nws.ncep.ui.pgen.display.DisplayElementFactory;
import gov.noaa.nws.ncep.ui.pgen.elements.AbstractDrawableComponent;
import gov.noaa.nws.ncep.ui.pgen.elements.DECollection;
import gov.noaa.nws.ncep.ui.pgen.elements.DrawableElement;
import java.util.HashMap;
@ -38,36 +37,37 @@ import com.raytheon.uf.viz.core.map.IMapDescriptor;
* Ghost drawing for the pgen resource.
*
* <pre>
*
*
* SOFTWARE HISTORY
*
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Jun 15, 2012 bgonzale Initial creation
*
*
* </pre>
*
*
* @author bgonzale
* @version 1.0
* @version 1.0
*/
public class PgenResourceGhost {
public AbstractDrawableComponent component;
Map<Object, AbstractElementContainer> componentMap = new HashMap<Object, AbstractElementContainer>();
/**
* Draw the ghost
*
* @param target
* @param paintProps
* @param df
* @param descriptor
*/
public void draw( IGraphicsTarget target, PaintProperties paintProps,
DisplayElementFactory df, IMapDescriptor descriptor){
df.setLayerDisplayAttr( false, null, false );
public void draw(IGraphicsTarget target, PaintProperties paintProps,
DisplayElementFactory df, IMapDescriptor descriptor) {
df.setLayerDisplayAttr(false, null, false);
if (component != null) {
Iterator<DrawableElement> iterator = component
.createDEIterator();
Iterator<DrawableElement> iterator = component.createDEIterator();
int count = 0;
while (iterator.hasNext()) {
DrawableElement element = iterator.next();
@ -76,21 +76,27 @@ public class PgenResourceGhost {
}
}
}
/**
* Creates displayables for an element using an ElementContainer and call the
* displayables' draw() method to draw the element.
* @param target Graphic target
* @param paintProps Paint properties
* @param df Display element factory
* @param el Input drawable element
* Creates displayables for an element using an ElementContainer and call
* the displayables' draw() method to draw the element.
*
* @param target
* Graphic target
* @param paintProps
* Paint properties
* @param df
* Display element factory
* @param el
* Input drawable element
* @praram descriptor
*/
private void drawElement( IGraphicsTarget target, PaintProperties paintProps,
DisplayElementFactory df, DrawableElement el, IMapDescriptor descriptor){
private void drawElement(IGraphicsTarget target,
PaintProperties paintProps, DisplayElementFactory df,
DrawableElement el, IMapDescriptor descriptor) {
Object key = createKey(el);
AbstractElementContainer graphic = componentMap.get(key);
AbstractElementContainer graphic = componentMap.get(key);
if (graphic == null) {
graphic = new DefaultElementContainer(el, descriptor, target);
componentMap.put(key, graphic);
@ -99,16 +105,17 @@ public class PgenResourceGhost {
}
graphic.draw(target, paintProps, null, true);
}
private Object createKey(DrawableElement el) {
return el.getPgenCategory()+ ":"+el.getPgenType();
return el.getPgenCategory() + ":" + el.getPgenType();
}
/**
* Sets the ghost line for the PGEN drawing layer.
* @param ghost
*
* @param ghost
*/
public void setGhostLine(AbstractDrawableComponent ghost) {
this.component = ghost;
this.component = ghost;
}
}

View file

@ -197,6 +197,7 @@ public class PgenContoursTool extends AbstractPgenDrawingTool implements
if (button == 1) {
drawContourMinmax(loc);
((ContoursAttrDlg) attrDlg).updateSymbolAttrOnGUI(loc);
} else if (button == 3) {
points.clear();

View file

@ -26,7 +26,8 @@ Export-Package: gov.noaa.nws.ncep.viz.common,
gov.noaa.nws.ncep.viz.common.soundingQuery,
gov.noaa.nws.ncep.viz.common.staticPointDataSource,
gov.noaa.nws.ncep.viz.common.ui,
gov.noaa.nws.ncep.viz.common.ui.color
gov.noaa.nws.ncep.viz.common.ui.color,
gov.noaa.nws.ncep.viz.common.util
Import-Package: com.raytheon.uf.common.comm,
com.raytheon.uf.viz.application,
com.raytheon.viz.pointdata,

View file

@ -0,0 +1,38 @@
/*
* IPowerLegend
*
* Date created: 03 AUGUST 2014
*
* This code has been developed by the NCEP/SIB for use in the AWIPS2 system.
*/
package gov.noaa.nws.ncep.viz.common.display;
import com.raytheon.uf.viz.core.rsc.IResourceGroup;
/**
* Interface for group resource, which can be expanded in the legend.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 08/14 ? B. Yin Initial Creation.
*
* </pre>
*
* @author byin
*
*/
public interface IPowerLegend extends IResourceGroup {
public int getFuncKeyNum();
public boolean isNameExpanded();
public void setNameExpanded(boolean flag);
public void setVisibleForAllResources(boolean visible);
}

View file

@ -14,6 +14,7 @@ import javax.xml.bind.annotation.XmlRootElement;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 02/10/13 #972 Greg Hull Created
* 05/14/14 R4078 S. Gurung Added NMAP_RTKP_WORLD_DISPLAY (T1122)
*
* </pre>
*
@ -47,7 +48,13 @@ public enum NcDisplayType {
"BasicWX_US", "OVERLAY/GeoPolitical/default", false),
GRAPH_DISPLAY("GRAPH", "gov.noaa.nws.ncep.viz.ui.display.NCPaneManager",
"DefaultCanvas", "", true);
"DefaultCanvas", "", true),
// FOR GEOMAG RTKP WORLD ACTIVITY MAP
NMAP_RTKP_WORLD_DISPLAY("NC-MAP-GEOMAG",
"gov.noaa.nws.ncep.viz.ui.display.NCPaneManager", "World",
"OVERLAY/GeoPolitical/default", true);
// NC_TIME_SERIES_DISPLAY,
// NC_CROSS_SECTION_DISPLAY;

View file

@ -0,0 +1,209 @@
/**
* 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 gov.noaa.nws.ncep.viz.common.util;
/**
* Static methods to convert between AWIPS2 Date strings to GEMPAK DATTIM
* string. Also contains helper methods to convert forecast time between time
* hours and minutes representation to time in seconds.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Aug 29, 2014 jbernier Initial creation
*
* </pre>
*
* @author jbernier
* @version 1.0
*/
public class CommonDateFormatUtil {
public static final String AWIPS2_DATETIME_FORMAT = "YYYY-MM-dd HH:mm:ss.S",
GEMPAK_DATTIM_FORMAT = "yyMMdd/HHmm";
/**
*
* Converts AWIPS2 date time string into GEMPAK DATTIM string
*
* @param dbTime
* eg "2011-10-09 06:20:00.0 (1)"
* @return eq "111009/0620f00100"
*/
public static String dbtimeToDattim(String dbTime) {
StringBuilder aDattimBuilder = new StringBuilder(dbTime.substring(0,
AWIPS2_DATETIME_FORMAT.length()));
aDattimBuilder.delete(0, 2);
deleteAllChar(aDattimBuilder, "-");
deleteAllChar(aDattimBuilder, ":");
deleteAllChar(aDattimBuilder, ".0");
int indexOfDateTimeDelimiter = (dbTime.contains("_") ? aDattimBuilder
.indexOf("_") : aDattimBuilder.indexOf(" "));
aDattimBuilder.replace(indexOfDateTimeDelimiter,
indexOfDateTimeDelimiter + 1, "/");
if (dbTime.contains("(") && dbTime.contains(")")) {
aDattimBuilder.append("f").append(getForecastTimeString(dbTime));
}
return aDattimBuilder.toString();
}
private static void deleteAllChar(StringBuilder charSeq, String charToDelete) {
int startIndex = charSeq.indexOf(charToDelete);
while (startIndex >= 0 && startIndex < charSeq.length()) {
int endIndex = startIndex + charToDelete.length();
charSeq.delete(startIndex, endIndex);
startIndex = charSeq.indexOf(charToDelete);
}
}
/**
*
* Converts GEMPAK DATTIM string into AWIPS2 date time string
*
* @param aDattim
* eg "111009/0620f00100"
* @return eq "2011-10-09 06:20:00.0 (1)"
*/
public static String dattimToDbtime(String aDattim) {
StringBuilder dbTimeBuilder = new StringBuilder(
AWIPS2_DATETIME_FORMAT.length() + 10);
String[] dateTime = aDattim.substring(0, GEMPAK_DATTIM_FORMAT.length())
.split("/");
int date = Integer.parseInt(dateTime[0]), time = Integer
.parseInt(dateTime[1]);
dbTimeBuilder.append(String.format("20%02d-%02d-%02d %02d:%02d:00.0",
date / 10000, (date % 10000) / 100, date % 100, time / 100,
time % 100));
if ((aDattim = aDattim.toUpperCase()).contains("F")) {
int spaceIndex = dbTimeBuilder.indexOf(" ");
dbTimeBuilder.replace(spaceIndex, spaceIndex + 1, "_");
dbTimeBuilder.append("_(")
.append(getForecastColonTimeString(aDattim)).append(")");
}
return dbTimeBuilder.toString();
}
/**
*
* Utility method to return forecast time in seconds given either GEMPAK or
* AWIPS2 date time strings
*
* @param anyTimeString
* eg "140808/0620f00115" or "2014-08-08 06:20:00.0 (1:15)"
* @return eg 4500
*/
public static int getForecastTimeInSec(String anyTimeString) {
anyTimeString = anyTimeString.toUpperCase();
int forecastHrs = 0, forecastMins = 0;
if (anyTimeString.contains("F")) {
String forecastTime = anyTimeString.substring(anyTimeString
.indexOf("F") + 1);
forecastHrs = Integer.parseInt(forecastTime.substring(0,
"000".length()));
forecastMins = forecastTime.length() == 5 ? Integer
.parseInt(forecastTime.substring("000".length())) : 0;
} else if (anyTimeString.contains("(") && anyTimeString.contains(")")) {
String[] forecastTime = anyTimeString.substring(
anyTimeString.indexOf("(") + 1, anyTimeString.indexOf(")"))
.split(":");
forecastHrs = Integer.parseInt(forecastTime[0]);
forecastMins = forecastTime.length == 2 ? Integer
.parseInt(forecastTime[1]) : 0;
} else {
forecastHrs = 0;
forecastMins = 0;
}
return forecastHrs * 3600 + forecastMins * 60;
}
/**
*
* Utility method to return forecast time string formatted to HHHmm given
* either GEMPAK or AWIPS2 date time format string
*
* @param anyTimeFormat
* eg "140808/0620f00115" or "2014-08-08 06:20:00.0 (1:15)"
* @return eg "00115"
*/
public static String getForecastTimeString(String anyTimeFormat) {
int forecastTimeInSec = getForecastTimeInSec(anyTimeFormat);
return getForecastTimeString(forecastTimeInSec);
}
/**
*
* Utility method to return forecast time string formatted to HHHmm given a
* forecast time in seconds
*
* @param forecastTimeInSec
* eg 4500
* @return eg "00115"
*/
public static String getForecastTimeString(int forecastTimeInSec) {
int forecastHrs = forecastTimeInSec / 3600;
int forecastMins = forecastTimeInSec % 3600 / 60;
return String.format("%03d", forecastHrs)
+ (forecastMins > 0 ? String.format("%02d", forecastMins) : "");
}
/**
*
* Utility method to return forecast time string formatted to HHH:mm given
* either GEMPAK or AWIPS2 date time format string
*
* @param anyTimeFormat
* eg "140808/0620f00115" or "2014-08-08 06:20:00.0 (1:15)"
* @return eg "1:15"
*/
public static String getForecastColonTimeString(String anyTimeFormat) {
int forecastTimeInSec = getForecastTimeInSec(anyTimeFormat);
return getForecastColonTimeString(forecastTimeInSec);
}
/**
*
* Utility method to return forecast time string formatted to HHH:mm given a
* forecast time in seconds
*
* @param forecastTimeInSec
* eg 4500
* @return eg "1:15"
*/
public static String getForecastColonTimeString(int forecastTimeInSec) {
int forecastHrs = forecastTimeInSec / 3600;
int forecastMins = forecastTimeInSec % 3600 / 60;
return String.valueOf(forecastHrs)
+ (forecastMins > 0 ? ":" + String.format("%02d", forecastMins)
: "");
}
}

View file

@ -28,5 +28,6 @@ Export-Package: gov.noaa.nws.ncep.viz.gempak,
gov.noaa.nws.ncep.viz.gempak.grid.units,
gov.noaa.nws.ncep.viz.gempak.util
Import-Package: gov.noaa.nws.ncep.edex.common.ncinventory,
com.raytheon.uf.common.serialization,
gov.noaa.nws.ncep.common.log.logger,
com.raytheon.uf.common.serialization
gov.noaa.nws.ncep.viz.common.util

View file

@ -114,12 +114,6 @@
<gnam>VPTMP</gnam>
<scale>0</scale>
</parmeterinfo>
<parmeterinfo>
<name>Specific Humidity</name>
<units>kg kg**-1</units>
<gnam>SPFH</gnam>
<scale>2</scale>
</parmeterinfo>
<parmeterinfo>
<name>Relative Humidity</name>
<units>%</units>
@ -1999,11 +1993,17 @@
<gnam>VWND</gnam>
<scale>0</scale>
</parmeterinfo>
<parmeterinfo>
<name>Specific Humidity</name>
<units>kg/kg</units>
<gnam>SPFH</gnam>
<scale>0</scale>
</parmeterinfo>
<parmeterinfo>
<name>Specific humidity</name>
<units>kg kg**-1</units>
<units>kg/kg</units>
<gnam>SPCH</gnam>
<scale>2</scale>
<scale>0</scale>
</parmeterinfo>
<parmeterinfo>
<name>Total column water</name>

View file

@ -1,5 +1,6 @@
package gov.noaa.nws.ncep.viz.gempak.util;
import gov.noaa.nws.ncep.viz.common.util.CommonDateFormatUtil;
import gov.noaa.nws.ncep.viz.gempak.grid.jna.GridDiag;
import javax.measure.converter.UnitConverter;
@ -23,526 +24,404 @@ import com.vividsolutions.jts.geom.Polygon;
/**
* @author gamaz
*
*/
/**
* @author gamaz
*
*
*/
public class GempakGrid {
private static GridDiag gd = GridDiag.getInstance();
public final static String gempakPluginName = "gempak_gd"; // ghull added Dec 19, 2010
/**
* Gets the cycle times for a GEMPAK dataLocation from uEngine in YYMMDD_HHMM format.
*
* @param aDataLocation
* eg "$MODEL/gfs"
* @return
* @throws VizException
*/
public static String[] getGridCycleTimes( String aDataLocation,String gdFile ) throws VizException{
byte[] cycles = new byte[1024];
IntByReference iret = new IntByReference(0);
gd.gem.in_bdta_(iret);
gd.gem.gd_init_ (iret);
gd.gem.gdc_gcyc_(gdFile, cycles, iret);
if ( iret.getValue() == 0 ) {
String cycleTime = Native.toString(cycles);
String cycleTime1 = cycleTime.replaceAll("/", "_");
String []cycleTimes = cycleTime1.trim().split(";");
return cycleTimes;
}
else {
throw new VizException();
}
// long st1 = System.currentTimeMillis();
// StringBuilder query = new StringBuilder();
// query.append("import NcModelCycleQuery\n");
// query.append("req = NcModelCycleQuery.NcModelCycleQuery()\n");
// query.append("req.setDataLocation('" + aDataLocation + "')\n");
// query.append("req.setModelName('" + modelname + "')\n");
// query.append("return req.execute()");
//
// String script = query.toString();
// try {
// String cycleListStr = (String) Connector.getInstance().connect(
// script, null, 600000)[0];
//
// String[] cycleList = cycleListStr.split("\\|");
// long st2 = System.currentTimeMillis();
// System.out.println ("***get cycleTimes throught Connector took:" + (st2-st1));
// return cycleList;
// } catch (VizException e) {
// throw new VizException(e);
// }
}
/**
* Gets the available times for a GEMPAK dataLocation and a current cycle
* from uEngine in "YYYY-MM-DD HH:MM:SS.S (fHHH)" format.
*
* @param aDataLocation
* eg "$MODEL/gfs"
* @param aCurrentCycle
* eg "2010-11-28 18:00:00.0"
* @return
* @throws VizException
*/
public static String[] getAvailableGridTimes( String aDataLocation, String aCurrentCycle, String gdFile )
throws VizException{
byte[] availables = new byte[10000];
IntByReference iret = new IntByReference(0);
gd.gem.in_bdta_(iret);
gd.gem.gd_init_ (iret);
String cycle="";
if ( aCurrentCycle != null ){
String []dtStr = aCurrentCycle.split(" ");
cycle =dtStr[0].split("-")[1] + dtStr[0].split("-")[2] +"/" +dtStr[1].split(":")[0];
}
gd.gem.gdc_gtmf_(gdFile, cycle, availables, iret);
if ( iret.getValue() == 0 ) {
String availableTimes = Native.toString(availables);
String [] avaTimeStr = availableTimes.trim().split("\\|");
String [] avaTimesList = new String [avaTimeStr.length];
int i = 0;
for ( String ava:avaTimeStr) {
if ( ava.contains("F")) {
avaTimesList[i] = aCurrentCycle +" (" + Integer.parseInt(ava.split("F")[1]) + ")";
}
else {
avaTimesList[i] = aCurrentCycle +" (0)";
}
i ++;
}
return avaTimesList;
}
else {
throw new VizException();
}
// long st1 = System.currentTimeMillis();
// StringBuilder query = new StringBuilder();
// query.append("import NcModelAvailableTimesQuery\n");
// query.append("req = NcModelAvailableTimesQuery.NcModelAvailableTimesQuery()\n");
// query.append("req.setDataLocation('" + aDataLocation + "')\n");
// query.append("req.setModelName('" + modelName + "')\n");
// query.append("req.setCurrentCycle('" + aCurrentCycle + "')\n");
// query.append("return req.execute()");
//
// String script = query.toString();
// try {
// String avTimesListStr = (String) Connector.getInstance().connect(
// script, null, 600000)[0];
// String[] avTimesList = avTimesListStr.split("\\|");
// long st2 = System.currentTimeMillis();
// System.out.println ("===get availableTimes throught connector took:" + (st2-st1));
// return avTimesList;
// } catch (VizException e) {
// throw new VizException(e);
// }
}
/**
* Gets the navigation information from a GEMPAK grid file and returns the coverage object.
*
* @param aDataLocation
* eg "$MODEL/gfs"
* @param aCurrentCycle
* eg "2010-11-28 18:00:00.0"
* @return
* @throws VizException
*/
public static ISpatialObject getGridNavigation (String anAlias, String aDataLocation, String aCurrentCycle)
throws VizException{
int numberOfLayers = aDataLocation.split("/").length;
String model = aDataLocation.split("/")[numberOfLayers-1];
String gdfile = constructGridFilename (anAlias, aDataLocation,aCurrentCycle);
float[] rnav = getGridNavigationBlock (gdfile);
String proj = getGridProjection (rnav);
DefaultGeographicCRS WGS84 = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem crs;
String crsWKT;
Polygon geometry;
if (proj.equalsIgnoreCase("CED")) {
double minLat = MapUtil.correctLat(rnav[6]);
double maxLat = MapUtil.correctLat(rnav[8]);
double minLon = MapUtil.correctLon(rnav[7]);
double maxLon = MapUtil.correctLon(rnav[9]);
if (maxLon < minLon) {
maxLon += 360.0;
}
if (maxLon > 180) {
crs = new DefaultGeographicCRS(new DefaultGeodeticDatum("WGS84",
WGS84.getDatum().getEllipsoid(), new DefaultPrimeMeridian(
"DateLine", 180.0)), WGS84.getCoordinateSystem());
} else {
crs = WGS84;
}
crsWKT = crs.toWKT();
try {
geometry = MapUtil.createGeometry(minLat, minLon, maxLat, maxLon);
} catch (Exception e) {
throw new VizException("Error creating geometry", e);
}
CharSequence spacingUnit = "degree";
LatLonGridCoverage cov = new LatLonGridCoverage();
cov.setSpacingUnit(spacingUnit.toString());
cov.setDx(rnav[2]);
cov.setDy(rnav[3]);
int nx = (int) rnav[4];
cov.setNx(Integer.valueOf(nx));
int ny = (int) rnav[5];
cov.setNy(Integer.valueOf(ny));
cov.setCrs(crs);
cov.setCrsWKT(crsWKT);
cov.setGeometry(geometry);
cov.setLa1(minLat);
cov.setLa2(maxLat);
cov.setLo1(minLon);
cov.setLo2(maxLon);
cov.setName("GEMPAK " + model + rnav[2] + "x" + rnav[3]+ " " + spacingUnit + " grid");
cov.setGridGeometry(MapUtil.getGridGeometry(cov));
cov.setDescription("GEMPAK CED grid");
return cov;
}
else if (proj.equalsIgnoreCase("STR")) {
double majorAxis = 6371229.0;
double minorAxis = 6371229.0;
double lov = rnav[11];
double la1 = rnav[6];
double lo1 = rnav[7];
int nx = (int) rnav[4];
int ny = (int) rnav[5];
/* TODO calculate dx, dx */
double dx = 90.755;
double dy = 90.755;
crs = MapUtil.constructNorthPolarStereo(majorAxis, minorAxis, 60.0, lov);
crsWKT = crs.toWKT();
CharSequence spacingUnit = "km";
try {
Unit<?> spacingUnitObj = Unit.valueOf(spacingUnit);
if (spacingUnitObj.isCompatible(SI.METRE)) {
UnitConverter converter = spacingUnitObj
.getConverterTo(SI.METRE);
geometry = MapUtil.createGeometry(crs, la1, lo1, converter
.convert(dx), converter.convert(dy), nx, ny);
} else {
throw new VizException("Unable to convert " + spacingUnit
+ " to meters while creating geometry!");
}
} catch (Exception e) {
throw new VizException("Error creating geometry", e);
}
PolarStereoGridCoverage cov = new PolarStereoGridCoverage();
cov.setCrs(crs);
cov.setCrsWKT(crsWKT);
cov.setGeometry(geometry);
cov.setLa1(la1);
cov.setLo1(lo1);
cov.setLov(lov);
cov.setNx(Integer.valueOf(nx));
cov.setNy(Integer.valueOf(ny));
cov.setGridGeometry(MapUtil.getGridGeometry(cov));
cov.setName("GEMPAK " + model + rnav[2] + "x" + rnav[3]+ " " + spacingUnit + " grid");
cov.setDescription("GEMPAK STR grid");
return cov;
}
else if (proj.equalsIgnoreCase("LCC")) {
/* TODO add code for LCC proj */
double majorAxis = 6371229.0;
double minorAxis = 6371229.0;
double lov = rnav[11];
double latin1 = rnav[10];
double latin2 = rnav[12];
double la1 = rnav[6];
double lo1 = rnav[7];
int nx = (int) rnav[4];
int ny = (int) rnav[5];
CharSequence spacingUnit = "km";
double dx = 12.191;
double dy = 12.191;
crs = MapUtil.constructLambertConformal(majorAxis, minorAxis, latin1, latin2, lov, latin1);
crsWKT = crs.toWKT();
try {
Unit<?> spacingUnitObj = Unit.valueOf(spacingUnit);
if (spacingUnitObj.isCompatible(SI.METRE)) {
UnitConverter converter = spacingUnitObj
.getConverterTo(SI.METRE);
geometry = MapUtil.createGeometry(crs, la1, lo1, converter
.convert(dx), converter.convert(dy), nx, ny);
} else {
throw new VizException("Unable to convert " + spacingUnit
+ " to meters while creating geometry!");
}
private static GridDiag gd = GridDiag.getInstance();
} catch (Exception e) {
throw new VizException("Error creating geometry", e);
}
LambertConformalGridCoverage cov = new LambertConformalGridCoverage();
cov.setCrs(crs);
cov.setCrsWKT(crsWKT);
cov.setGeometry(geometry);
cov.setLa1(la1);
cov.setLo1(lo1);
cov.setLov(lov);
cov.setNx(Integer.valueOf(nx));
cov.setNy(Integer.valueOf(ny));
cov.setGridGeometry(MapUtil.getGridGeometry(cov));
cov.setName("GEMPAK " + model + rnav[2] + "x" + rnav[3]+ " " + spacingUnit + " grid");
cov.setDescription("GEMPAK LCC grid");
return cov;
}
else if (proj.equalsIgnoreCase("MER")) {
/* TODO add code for MER proj */
return null;
}
else {
return null;
}
}
/**
* Constructs a GEMPAK grid filename eg "gfs_2010112818f003"
*
* @param anAlias
* eg "GFS"
* @param aLocation
* eg "$MODEL/gfs"
* @param aTime
* eg "2010-11-28 18:00:00.0 (3)"
* @return
*/
private static String constructGridFilename(String anAlias, String aLocation, String aTime) {
try {
String fileNameTemplate = getGempakGridTemplate(anAlias);
IntByReference iret = new IntByReference(0);
byte[] theFileName = new byte[50];
String gTime = dbtimeToDattim(aTime);
String fullPath = aLocation+ "/" + fileNameTemplate;
gd.gem.cfl_mnam_ ( gTime, fullPath, theFileName, iret);
if ( iret.getValue () != 0 ) {
return null;
}
return Native.toString(theFileName);
} catch (VizException e) {
// TODO Auto-generated catch block
return null;
}
}
/**
* Extracts navigation block from GEMPAK grid
*
* @param aGridFile
* @return
*/
private static float [] getGridNavigationBlock(String aGridFile) {
float[] rnav = new float[20];
float[] anl = new float[20];
IntByReference wrtflg = new IntByReference(-1);
IntByReference mxanl = new IntByReference(1);
IntByReference mxnav = new IntByReference(20);
IntByReference iacss = new IntByReference(0);
IntByReference msxgrd = new IntByReference(0);
IntByReference iret = new IntByReference(0);
IntByReference mode = new IntByReference(0);
public final static String gempakPluginName = "gempak_gd"; // ghull added
// Dec 19, 2010
gd.gem.in_bdta_(iret);
gd.gem.gd_init_ (iret);
gd.gem.gg_init_ (mode,iret);
gd.gem.dg_intl_ (iret);
/**
* Gets the cycle times for a GEMPAK dataLocation from uEngine in
* YYMMDD_HHMM format.
*
* @param aDataLocation
* eg "$MODEL/gfs"
* @return
* @throws VizException
*/
public static String[] getGridCycleTimes(String aDataLocation, String gdFile)
throws VizException {
byte[] cycles = new byte[1024];
IntByReference iret = new IntByReference(0);
gd.gem.in_bdta_(iret);
gd.gem.gd_init_(iret);
gd.gem.gdc_gcyc_(gdFile, cycles, iret);
if (iret.getValue() == 0) {
String cycleTime = Native.toString(cycles);
String cycleTime1 = cycleTime.replaceAll("/", "_");
String[] cycleTimes = cycleTime1.trim().split(";");
return cycleTimes;
} else {
throw new VizException();
}
// long st1 = System.currentTimeMillis();
// StringBuilder query = new StringBuilder();
// query.append("import NcModelCycleQuery\n");
// query.append("req = NcModelCycleQuery.NcModelCycleQuery()\n");
// query.append("req.setDataLocation('" + aDataLocation + "')\n");
// query.append("req.setModelName('" + modelname + "')\n");
// query.append("return req.execute()");
//
// String script = query.toString();
// try {
// String cycleListStr = (String) Connector.getInstance().connect(
// script, null, 600000)[0];
//
// String[] cycleList = cycleListStr.split("\\|");
// long st2 = System.currentTimeMillis();
// System.out.println ("***get cycleTimes throught Connector took:" +
// (st2-st1));
// return cycleList;
// } catch (VizException e) {
// throw new VizException(e);
// }
}
gd.gem.gdc_open_ (aGridFile, wrtflg, mxanl, mxnav, iacss,
anl, rnav, msxgrd, iret);
return rnav;
}
/**
* Extracts grid projections from GEMPAK grid navigation block
*
* @param rnav
* @return
*/
private static String getGridProjection (float[] rnav) {
IntByReference iret = new IntByReference(0);
byte[] cproj = new byte[5];
IntByReference kx = new IntByReference(0);
IntByReference ky = new IntByReference(0);
gd.gem.grc_rnav_ (rnav, cproj, kx, ky, iret);
return Native.toString(cproj);
}
/**
* Serves as a wrapper for the legacy ctb_dtpath function
*
* @param anAlias
* eg "GFS"
* @return
*/
public static String getGempakGridPath ( String anAlias) throws VizException {
IntByReference iret = new IntByReference(0);
byte[] thePath = new byte[30];
gd.gem.ctb_dtpath_ (anAlias, thePath, iret);
if ( iret.getValue () != 0 ) {
throw new VizException("Alias " + anAlias + " not found in legacy datatype.tbl");
}
return Native.toString(thePath);
}
/**
* Serves as a wrapper for the legacy ctb_dttmpl function
*
* @param anAlias
* eg "GFS"
* @return
*/
public static String getGempakGridTemplate ( String anAlias) throws VizException {
IntByReference iret = new IntByReference(0);
byte[] theTemplate = new byte[50];
gd.gem.ctb_dttmpl_ (anAlias, theTemplate, iret);
if ( iret.getValue () != 0 ) {
throw new VizException("Alias " + anAlias + " not found in legacy datatype.tbl");
}
return Native.toString(theTemplate);
}
/**
*
* Converts AWIPS2 date time string into GEMPAK DATTIM string
*
* @param aTime
* eg "2011-10-09 06:20:00.0 (1)"
* @return
* eq "111009/0620f001"
*/
private static String dbtimeToDattim(String aTime) {
String aDattim = null;
String[] inputStringArray = new String[2];
CharSequence char0 = "(";
/*
* Process time contains forecast hour info
*/
if ( aTime.contains(char0) ) {
String zeroes = null;
int ind1 = aTime.indexOf("(");
int ind2 = aTime.indexOf(")");
if ( ind2-ind1 == 2 ) {
zeroes = "00";
}
else if ( ind2-ind1 == 3 ) {
zeroes = "0";
}
String str1 = aTime.substring(0, ind1-1);
String str2 = "";
if ( zeroes != null) {
str2 = "f"+zeroes+aTime.substring(ind1+1, ind2);
}
else {
str2 = "f"+aTime.substring(ind1+1, ind2);
}
if ( aTime.contains("_") ) {
inputStringArray = str1.split("_");
}
else if ( ! aTime.contains("_") ) {
inputStringArray = str1.split(" ");
}
/**
* Gets the available times for a GEMPAK dataLocation and a current cycle
* from uEngine in "YYYY-MM-DD HH:MM:SS.S (fHHH)" format.
*
* @param aDataLocation
* eg "$MODEL/gfs"
* @param aCurrentCycle
* eg "2010-11-28 18:00:00.0"
* @return
* @throws VizException
*/
public static String[] getAvailableGridTimes(String aDataLocation,
String aCurrentCycle, String gdFile) throws VizException {
byte[] availables = new byte[10000];
IntByReference iret = new IntByReference(0);
gd.gem.in_bdta_(iret);
gd.gem.gd_init_(iret);
String cycle = "";
if (aCurrentCycle != null) {
String[] dtStr = aCurrentCycle.split(" ");
cycle = dtStr[0].split("-")[1] + dtStr[0].split("-")[2] + "/"
+ dtStr[1].split(":")[0];
}
gd.gem.gdc_gtmf_(gdFile, cycle, availables, iret);
if (iret.getValue() == 0) {
String availableTimes = Native.toString(availables);
String[] avaTimeStr = availableTimes.trim().split("\\|");
String[] avaTimesList = new String[avaTimeStr.length];
int i = 0;
for (String ava : avaTimeStr) {
if (ava.contains("F")) {
avaTimesList[i] = aCurrentCycle + " ("
+ Integer.parseInt(ava.split("F")[1]) + ")";
} else {
avaTimesList[i] = aCurrentCycle + " (0)";
}
i++;
}
return avaTimesList;
} else {
throw new VizException();
}
// long st1 = System.currentTimeMillis();
// StringBuilder query = new StringBuilder();
// query.append("import NcModelAvailableTimesQuery\n");
// query.append("req = NcModelAvailableTimesQuery.NcModelAvailableTimesQuery()\n");
// query.append("req.setDataLocation('" + aDataLocation + "')\n");
// query.append("req.setModelName('" + modelName + "')\n");
// query.append("req.setCurrentCycle('" + aCurrentCycle + "')\n");
// query.append("return req.execute()");
//
// String script = query.toString();
// try {
// String avTimesListStr = (String) Connector.getInstance().connect(
// script, null, 600000)[0];
// String[] avTimesList = avTimesListStr.split("\\|");
// long st2 = System.currentTimeMillis();
// System.out.println ("===get availableTimes throught connector took:"
// + (st2-st1));
// return avTimesList;
// } catch (VizException e) {
// throw new VizException(e);
// }
}
/*
* YYYY-MM-DD HH:MM:SS.S (HHH)-> YYMMDD/HHMMfHHH
* 2009-10-22 16:00:00.0 (5)-> 091022/1600f005
* 0123456789 0123456789
*/
aDattim = inputStringArray[0].substring(2, 4)
+ inputStringArray[0].substring(5, 7)
+ inputStringArray[0].substring(8, 10) + "/"
+ inputStringArray[1].substring(0, 2)
+ inputStringArray[1].substring(3, 5) + str2;
}
/*
* Process time that does NOT contain forecast hour info
*/
else {
inputStringArray = aTime.split(" ");
/**
* Gets the navigation information from a GEMPAK grid file and returns the
* coverage object.
*
* @param aDataLocation
* eg "$MODEL/gfs"
* @param aCurrentCycle
* eg "2010-11-28 18:00:00.0"
* @return
* @throws VizException
*/
public static ISpatialObject getGridNavigation(String anAlias,
String aDataLocation, String aCurrentCycle) throws VizException {
int numberOfLayers = aDataLocation.split("/").length;
String model = aDataLocation.split("/")[numberOfLayers - 1];
String gdfile = constructGridFilename(anAlias, aDataLocation,
aCurrentCycle);
float[] rnav = getGridNavigationBlock(gdfile);
String proj = getGridProjection(rnav);
/*
* YYYY-MM-DD HH:MM:SS.S -> YYMMDD/HHMM
* 2009-01-20 02:25:00.0 -> 090120/0225
* 0123456789 0123456789
*/
aDattim = inputStringArray[0].substring(2, 4)
+ inputStringArray[0].substring(5, 7)
+ inputStringArray[0].substring(8, 10) + "/"
+ inputStringArray[1].substring(0, 2)
+ inputStringArray[1].substring(3, 5);
}
return aDattim;
}
/*
* Converts GEMPAK DATTIM string into AWIPS2 date time string
*/
public static String dattimToDbtime(String aDattim) {
aDattim = aDattim.toUpperCase();
String retDateTime = null;
String[] inputStringArray = new String[2];
CharSequence char0 = "F";
if ( aDattim.contains(char0) ) {
int ind1 = aDattim.indexOf("F00");
int addChars = 3;
if ( ind1 == -1 ) {
ind1 = aDattim.indexOf("F0");
addChars = 2;
}
if ( ind1 == -1 ) {
ind1 = aDattim.indexOf("F");
addChars = 1;
}
int ind2 = aDattim.length();
String str1 = aDattim.substring(0, ind1);
String str2 = aDattim.substring(ind1+addChars,ind2 );
inputStringArray = str1.split("/");
DefaultGeographicCRS WGS84 = DefaultGeographicCRS.WGS84;
CoordinateReferenceSystem crs;
String crsWKT;
Polygon geometry;
/*
* YYMMDD/HHMMfHHH -> YYYY-MM-DD HH:MM:SS.S
* 090120/0225f005 -> 2009-01-20 02:25:00.0
* 012345 0123
*/
retDateTime = "20" + inputStringArray[0].substring(0, 2) + "-"
+ inputStringArray[0].substring(2, 4) + "-"
+ inputStringArray[0].substring(4, 6) + "_"
+ inputStringArray[1].substring(0, 2) + ":"
+ inputStringArray[1].substring(2, 4) + ":00.0_("+ str2 + ")";
}
/*
* Process time that does NOT contain forecast hour info
*/
else {
inputStringArray = aDattim.split("/");
if (proj.equalsIgnoreCase("CED")) {
double minLat = MapUtil.correctLat(rnav[6]);
double maxLat = MapUtil.correctLat(rnav[8]);
double minLon = MapUtil.correctLon(rnav[7]);
double maxLon = MapUtil.correctLon(rnav[9]);
if (maxLon < minLon) {
maxLon += 360.0;
}
if (maxLon > 180) {
crs = new DefaultGeographicCRS(new DefaultGeodeticDatum(
"WGS84", WGS84.getDatum().getEllipsoid(),
new DefaultPrimeMeridian("DateLine", 180.0)),
WGS84.getCoordinateSystem());
} else {
crs = WGS84;
}
crsWKT = crs.toWKT();
try {
geometry = MapUtil.createGeometry(minLat, minLon, maxLat,
maxLon);
} catch (Exception e) {
throw new VizException("Error creating geometry", e);
}
CharSequence spacingUnit = "degree";
/*
* YYMMDD/HHMM -> YYYY-MM-DD HH:MM:SS.S
* 090120/0225 -> 2009-01-2002:25:00.0
* s012345 0123
*/
retDateTime = "20" + inputStringArray[0].substring(0, 2) + "-"
+ inputStringArray[0].substring(2, 4) + "-"
+ inputStringArray[0].substring(4, 6) + " "
+ inputStringArray[1].substring(0, 2) + ":"
+ inputStringArray[1].substring(2, 4) + ":00.0";
}
LatLonGridCoverage cov = new LatLonGridCoverage();
cov.setSpacingUnit(spacingUnit.toString());
cov.setDx(rnav[2]);
cov.setDy(rnav[3]);
int nx = (int) rnav[4];
cov.setNx(Integer.valueOf(nx));
int ny = (int) rnav[5];
cov.setNy(Integer.valueOf(ny));
cov.setCrs(crs);
cov.setCrsWKT(crsWKT);
cov.setGeometry(geometry);
cov.setLa1(minLat);
cov.setLa2(maxLat);
cov.setLo1(minLon);
cov.setLo2(maxLon);
cov.setName("GEMPAK " + model + rnav[2] + "x" + rnav[3] + " "
+ spacingUnit + " grid");
cov.setGridGeometry(MapUtil.getGridGeometry(cov));
cov.setDescription("GEMPAK CED grid");
return cov;
} else if (proj.equalsIgnoreCase("STR")) {
double majorAxis = 6371229.0;
double minorAxis = 6371229.0;
double lov = rnav[11];
double la1 = rnav[6];
double lo1 = rnav[7];
int nx = (int) rnav[4];
int ny = (int) rnav[5];
/* TODO calculate dx, dx */
double dx = 90.755;
double dy = 90.755;
crs = MapUtil.constructNorthPolarStereo(majorAxis, minorAxis, 60.0,
lov);
crsWKT = crs.toWKT();
CharSequence spacingUnit = "km";
try {
Unit<?> spacingUnitObj = Unit.valueOf(spacingUnit);
if (spacingUnitObj.isCompatible(SI.METRE)) {
UnitConverter converter = spacingUnitObj
.getConverterTo(SI.METRE);
geometry = MapUtil.createGeometry(crs, la1, lo1,
converter.convert(dx), converter.convert(dy), nx,
ny);
} else {
throw new VizException("Unable to convert " + spacingUnit
+ " to meters while creating geometry!");
}
} catch (Exception e) {
throw new VizException("Error creating geometry", e);
}
PolarStereoGridCoverage cov = new PolarStereoGridCoverage();
cov.setCrs(crs);
cov.setCrsWKT(crsWKT);
cov.setGeometry(geometry);
cov.setLa1(la1);
cov.setLo1(lo1);
cov.setLov(lov);
cov.setNx(Integer.valueOf(nx));
cov.setNy(Integer.valueOf(ny));
cov.setGridGeometry(MapUtil.getGridGeometry(cov));
cov.setName("GEMPAK " + model + rnav[2] + "x" + rnav[3] + " "
+ spacingUnit + " grid");
cov.setDescription("GEMPAK STR grid");
return cov;
} else if (proj.equalsIgnoreCase("LCC")) {
/* TODO add code for LCC proj */
double majorAxis = 6371229.0;
double minorAxis = 6371229.0;
double lov = rnav[11];
double latin1 = rnav[10];
double latin2 = rnav[12];
double la1 = rnav[6];
double lo1 = rnav[7];
int nx = (int) rnav[4];
int ny = (int) rnav[5];
CharSequence spacingUnit = "km";
double dx = 12.191;
double dy = 12.191;
crs = MapUtil.constructLambertConformal(majorAxis, minorAxis,
latin1, latin2, lov, latin1);
crsWKT = crs.toWKT();
try {
Unit<?> spacingUnitObj = Unit.valueOf(spacingUnit);
if (spacingUnitObj.isCompatible(SI.METRE)) {
UnitConverter converter = spacingUnitObj
.getConverterTo(SI.METRE);
geometry = MapUtil.createGeometry(crs, la1, lo1,
converter.convert(dx), converter.convert(dy), nx,
ny);
} else {
throw new VizException("Unable to convert " + spacingUnit
+ " to meters while creating geometry!");
}
return retDateTime;
}
} catch (Exception e) {
throw new VizException("Error creating geometry", e);
}
LambertConformalGridCoverage cov = new LambertConformalGridCoverage();
cov.setCrs(crs);
cov.setCrsWKT(crsWKT);
cov.setGeometry(geometry);
cov.setLa1(la1);
cov.setLo1(lo1);
cov.setLov(lov);
cov.setNx(Integer.valueOf(nx));
cov.setNy(Integer.valueOf(ny));
cov.setGridGeometry(MapUtil.getGridGeometry(cov));
cov.setName("GEMPAK " + model + rnav[2] + "x" + rnav[3] + " "
+ spacingUnit + " grid");
cov.setDescription("GEMPAK LCC grid");
return cov;
} else if (proj.equalsIgnoreCase("MER")) {
/* TODO add code for MER proj */
return null;
} else {
return null;
}
}
/**
* Constructs a GEMPAK grid filename eg "gfs_2010112818f003"
*
* @param anAlias
* eg "GFS"
* @param aLocation
* eg "$MODEL/gfs"
* @param aTime
* eg "2010-11-28 18:00:00.0 (3)"
* @return
*/
private static String constructGridFilename(String anAlias,
String aLocation, String aTime) {
try {
String fileNameTemplate = getGempakGridTemplate(anAlias);
IntByReference iret = new IntByReference(0);
byte[] theFileName = new byte[50];
String gTime = CommonDateFormatUtil.dbtimeToDattim(aTime);
String fullPath = aLocation + "/" + fileNameTemplate;
gd.gem.cfl_mnam_(gTime, fullPath, theFileName, iret);
if (iret.getValue() != 0) {
return null;
}
return Native.toString(theFileName);
} catch (VizException e) {
// TODO Auto-generated catch block
return null;
}
}
/**
* Extracts navigation block from GEMPAK grid
*
* @param aGridFile
* @return
*/
private static float[] getGridNavigationBlock(String aGridFile) {
float[] rnav = new float[20];
float[] anl = new float[20];
IntByReference wrtflg = new IntByReference(-1);
IntByReference mxanl = new IntByReference(1);
IntByReference mxnav = new IntByReference(20);
IntByReference iacss = new IntByReference(0);
IntByReference msxgrd = new IntByReference(0);
IntByReference iret = new IntByReference(0);
IntByReference mode = new IntByReference(0);
gd.gem.in_bdta_(iret);
gd.gem.gd_init_(iret);
gd.gem.gg_init_(mode, iret);
gd.gem.dg_intl_(iret);
gd.gem.gdc_open_(aGridFile, wrtflg, mxanl, mxnav, iacss, anl, rnav,
msxgrd, iret);
return rnav;
}
/**
* Extracts grid projections from GEMPAK grid navigation block
*
* @param rnav
* @return
*/
private static String getGridProjection(float[] rnav) {
IntByReference iret = new IntByReference(0);
byte[] cproj = new byte[5];
IntByReference kx = new IntByReference(0);
IntByReference ky = new IntByReference(0);
gd.gem.grc_rnav_(rnav, cproj, kx, ky, iret);
return Native.toString(cproj);
}
/**
* Serves as a wrapper for the legacy ctb_dtpath function
*
* @param anAlias
* eg "GFS"
* @return
*/
public static String getGempakGridPath(String anAlias) throws VizException {
IntByReference iret = new IntByReference(0);
byte[] thePath = new byte[30];
gd.gem.ctb_dtpath_(anAlias, thePath, iret);
if (iret.getValue() != 0) {
throw new VizException("Alias " + anAlias
+ " not found in legacy datatype.tbl");
}
return Native.toString(thePath);
}
/**
* Serves as a wrapper for the legacy ctb_dttmpl function
*
* @param anAlias
* eg "GFS"
* @return
*/
public static String getGempakGridTemplate(String anAlias)
throws VizException {
IntByReference iret = new IntByReference(0);
byte[] theTemplate = new byte[50];
gd.gem.ctb_dttmpl_(anAlias, theTemplate, iret);
if (iret.getValue() != 0) {
throw new VizException("Alias " + anAlias
+ " not found in legacy datatype.tbl");
}
return Native.toString(theTemplate);
}
}

View file

@ -17,4 +17,5 @@ WIND=18/1/1
TITLE=5/-1/~ @ AVERAGE HEIGHT
COLORS=3
MARKER=2
GRDLBL=1
GRDLBL=1
TEXT=

View file

@ -17,4 +17,5 @@ WIND=18/1/1
TITLE=5/-1/~ ^ @ AVERAGE TMPC
COLORS=3
MARKER=2
GRDLBL=1
GRDLBL=1
TEXT=

View file

@ -17,4 +17,5 @@ WIND=18/1/1
TITLE=5/-1/~ @ AVERAGE HEIGHT
COLORS=3
MARKER=2
GRDLBL=1
GRDLBL=1
TEXT=

View file

@ -2,5 +2,5 @@
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>SREF40</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>tp12c1</attrSetNames>
<attrSetNames>500mb_hght</attrSetNames>
</AttributeSetGroup>

View file

@ -1,6 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>WAVE4WNA_2</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>wave_height</attrSetNames>
</AttributeSetGroup>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>WAVE4WC_2</resource>
<resource>WAVEHURR10AK</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>wave_height</attrSetNames>
</AttributeSetGroup>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>WAVE10EP_2</resource>
<resource>WAVEHURR10EP</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>direction_of_wind_wave</attrSetNames>
</AttributeSetGroup>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>WAVE10WC_2</resource>
<resource>WAVEHURR10WC</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>wave_height</attrSetNames>
</AttributeSetGroup>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>WAVE30MGLOBAL</resource>
<resource>WAVEHURR10WNA</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>wave_height</attrSetNames>
</AttributeSetGroup>

View file

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AttributeSetGroup xmlns:ns2="http://www.example.org/productType">
<resource>WAVE4ENP_2</resource>
<resource>WAVEHURR15ENP</resource>
<attrSetGroupName>standard</attrSetGroupName>
<attrSetNames>primary_wave_dir</attrSetNames>
</AttributeSetGroup>

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