VLab Issue #3721 - NCEP CAVE plugin delivery for 14.3.1

Updates to various resource plugins such as ncgrid, plotdata, ncscat,
and ntrans

Change-Id: Ie04200519fad583d2b252ea161cb5c72eb90732c

Former-commit-id: f68dd77088 [formerly 5885bff027] [formerly 57cf6c4bd7] [formerly f68dd77088 [formerly 5885bff027] [formerly 57cf6c4bd7] [formerly e1b0c5f102 [formerly 57cf6c4bd7 [formerly 0832f7cdc3c6f020f5fe97dde01ed17cf98eebb2]]]]
Former-commit-id: e1b0c5f102
Former-commit-id: cba8b1a043 [formerly 042ca4e3ac] [formerly 0d91c5d0a324d8adfbae13dd01caa6ab04972096 [formerly 66295d65c5]]
Former-commit-id: b75bf4c3fb2ddd36a8e78f589932630ac1ec6283 [formerly f62acd10cc]
Former-commit-id: c133eb60b0
This commit is contained in:
Stephen Gilbert 2014-05-15 16:18:36 -04:00
parent 636cc864f0
commit fff3809e18
49 changed files with 12024 additions and 8191 deletions

View file

@ -2,351 +2,400 @@
*
*/
package gov.noaa.nws.ncep.gempak.parameterconversionlibrary;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Collections;
import gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer;
/**
* @author archana
*
* gov.noaa.nws.ncep.edex.common.sounding.NcSoundingLayer
*
* This java class provides sounding data data structure for used with NC sounding query.
* Each NcSoundingLayer contain one layer of sounding information (pressure, height, temp, dewpt, windS, windD) for
* one point (lat/lon) at a particular time (timeLine) and particular height.
* This code has been developed by the SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------- ------- -------- -----------
* A. Subramanian Created
* 03/2014 1116 T. Lee Added DPD to NcSoundingLayer
*
* </pre>
*/
public class PSLibrary {
/**
* Computes the cross totals index
* @param td850 - dewpoint at 850 mb ( in Celsius )
* @param t500 - temperature at 500 mb ( in Celsius )
* @return the difference between the dewpoint and the temperature if neither of them are missing
* and RMISSD ( -9999 ) otherwise.
*/
public static float psCtot ( float td850,float t500) {
/**
* Computes the cross totals index
*
* @param td850
* - dewpoint at 850 mb ( in Celsius )
* @param t500
* - temperature at 500 mb ( in Celsius )
* @return the difference between the dewpoint and the temperature if
* neither of them are missing and RMISSD ( -9999 ) otherwise.
*/
public static float psCtot(float td850, float t500) {
/*
* Compute the cross totals index by subtracting 500 mb
* temperature from the 850 mb dewpoint.
*/
return ( ( !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t500) )
? ( td850 - t500 ) : GempakConstants.RMISSD ) ;
}
/**
* Computes low, middle, and high elevation Haines indices
* from the temperature and the dewpoint.
* @param tc1 - temperature ( in Celsius )
* @param tc2 - temperature ( in Celsius )
* @param dwpc - dewpoint ( in Celsius )
* @param itype - Haines index:
* 1- Low
* 2 - Middle
* 3 - High
*
* @return
*/
public static float psHans ( float tc1, float tc2, float dwpc, float itype) {
float pshans = GempakConstants.RMISSD;
if ( !MissingValueTester.isDataValueMissing(tc1)
&& !MissingValueTester.isDataValueMissing(tc2)
&& !MissingValueTester.isDataValueMissing(dwpc)){
float a = GempakConstants.RMISSD;
float b = GempakConstants.RMISSD;
/* Compute the Haines index*/
if ( itype == 1 ) {
a = ( ( tc2 - tc1 ) - 3 ) * ( 2 / 5 ) + 1;
b = ( ( tc1 - dwpc ) - 5 ) * ( 2 / 5 ) + 1;
}
else if ( itype == 2 ) {
a = ( ( tc1 - tc2 ) - 5 ) * ( 2 / 6 ) + 1;
b = ( ( tc1 - dwpc ) - 5 ) * ( 2 / 8 ) + 1;
}
else if ( itype == 3 ) {
a = ( ( tc1 - tc2 ) - 17 ) * ( 2 / 5 ) + 1;
b = ( ( tc1 - dwpc ) - 14 ) * ( 2 / 7 ) + 1;
}
a = ( a > 0.9f ? a : 0.9f );
a = ( a < 3.1f ? a : 3.1f );
b = ( b > 0.9f ? b : 0.9f );
b = ( b < 3.1f ? b : 3.1f );
pshans = a+ b;
}
return pshans;
}
/*
* Compute the cross totals index by subtracting 500 mb temperature from
* the 850 mb dewpoint.
*/
return ((!MissingValueTester.isDataValueMissing(td850) && !MissingValueTester
.isDataValueMissing(t500)) ? (td850 - t500)
: GempakConstants.RMISSD);
}
/**
*
* Computes the 'K' index
* @param t850 - 850 mb temperature ( in Celsius )
* @param t700 - 700 mb temperature ( in Celsius )
* @param t500 - 500 mb temperature ( in Celsius )
* @param td850 - 850 mb dewpoint ( in Celsius )
* @param td700 - 700 mb dewpoint ( in Celsius )
* @return returns the 'K' index if all the input values are valid and
* RMISSD ( -9999 ) otherwise
*/
public static float pskinx ( float t850, float t700, float t500, float td850, float td700) {
float pskinx = GempakConstants.RMISSD;
if ( !MissingValueTester.isDataValueMissing(td700)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(t700)
&& !MissingValueTester.isDataValueMissing(t850)){
pskinx = ( t850 - t500 ) + td850 - ( t700 - td700 ) ;
}
return pskinx;
}
/**
* Computes the Showalter index
* @param t850 - 850 mb temperature ( in Celsius )
* @param td850 - 850 mb dewpoint ( in Celsius )
* @param t500 - 500 mb temperature ( in Celsius )
* @return the Showalter index if all the three input parameters are valid and the parcel temperature is computed correctly.
* Otherwise, it returns RMISSD (-9999).
*/
public static float psShow ( float t850, float td850, float t500 ){
float psshow = GempakConstants.RMISSD;
if ( !MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t850)){
float p850 = 850;
float p500 = 500;
float guess = 0;
/*
* Find equivalent potential temperature at the LCL using 850 mb
* temperature and dewpoint.
*/
float thtlcl = PRLibrary.prThte ( p850, t850, td850 );
/*Find parcel temperature along pseudoadiabat at 500 mb.
* The parcel temperature tp is the temperature in Celsius at 500 mb of a parcel,
* which lies on the moist adiabat determined by the sounding at 850 mb
*/
float tp = PRLibrary.prTmst ( thtlcl, p500, guess );
/*Subtract the parcel temperature from the temperature at 500 mb, is the parcel temperature is valid*/
if ( !MissingValueTester.isDataValueMissing( tp ) ){
psshow = PRLibrary.prTmck ( t500 ) - tp ;
}
}
return psshow;
}
/**
* Computes the vertical totals index
* @param t850 - 850 mb temperature ( in Celsius )
* @param t500 - 500 mb temperature ( in Celsius )
* @return the verticl totals index as a difference of the temperature at 850 mb and the temperature at 500 mb, if neither value is missing.
* Else it returns RMISSD (-9999)
*/
public static float psVtot ( float t850, float t500 ) {
return ( ( !MissingValueTester.isDataValueMissing( t500 ) && !MissingValueTester.isDataValueMissing( t850 ) )
? t850 - t500 : GempakConstants.RMISSD );
}
/**
* Computes the total Totals index from the temperature and dewpoint at 850 mb and the temperature at 500 mb
*
* @param t850 - 850 mb temperature ( in Celsius )
* @param td850 - 850 mb dewpoint ( in Celsius )
* @param t500 - 500 mb temperature ( in Celsius )
* @return the total totals index if none of the input parameters are missing and
* RMISSD (-9999) otherwise
*/
public static float psTotl ( float t850, float td850, float t500 ){
float pstotl = GempakConstants.RMISSD;
if ( !MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t850)){
/*Compute the vertical totals*/
float vtot = psVtot ( t850, t500 );
/*Compute the cross totals*/
float ctot = psCtot ( td850, t500 );
if ( !MissingValueTester.isDataValueMissing( ctot )
&& !MissingValueTester.isDataValueMissing( vtot ) ) {
pstotl = ctot + vtot;
}
}
return pstotl;
}
/**
* Computes the SWEAT index. Winds must be input in m/sec
* @param t850 - 850 mb temperature
* @param td850 - 850 mb dewpoint
* @param t500 - 500 mb temperature
* @param spd850 - 850 mb windspeed ( in m/sec )
* @param spd500 - 500 mb windspeed ( in m/sec )
* @param dir850 - 850 mb wind direction
* @param dir500 - 500 mb wind direction
* @return the SWEAT index if none of the inputs are missing and RMISSD ( -9999 ) otherwise
*/
public static float psSwet ( float t850, float td850, float t500, float spd850, float spd500, float dir850, float dir500 ){
float pssweat = GempakConstants.RMISSD;
if ( !MissingValueTester.isDataValueMissing( dir500 )
&& !MissingValueTester.isDataValueMissing(dir850)
&& !MissingValueTester.isDataValueMissing(spd500)
&& !MissingValueTester.isDataValueMissing(spd850)
&& !MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t850)){
/*
* (Non-Javadoc):
* All computations are from
* Miller, R.C., 1972: Notes on Severe Storm Forecasting Procedures of
* the Air Force Global Weather Central, AWS Tech. Report 200
*/
/*Convert meters per second to knots*/
float skt850 = PRLibrary.prMskn ( spd850 );
float skt500 = PRLibrary.prMskn( spd500 );
/* Compute the total totals index. If < 49, set term to zero.*/
float total = psTotl ( t850, td850, t500 );
float term2 = total - 49;
if ( total < 49 )
term2 = 0;
/* Compute shear term.*/
float dif = dir500 - dir850;
float s = ( float ) ( Math.sin ( dif * GempakConstants.DTR ) );
float shear = 125 * ( s + 0.2f );
/*Make various wind checks.*/
if ((dir850 < 130.) || (dir850 > 250.))
shear = 0;
if ((dir500 < 210.) || (dir500 > 310.))
shear = 0;
if ((skt500 < 15.) || (skt850 < 15. ))
shear = 0;
if (dif <= 0)
shear = 0;
/*Check for sub-zero dewpoint*/
float dwp850 = td850;
if ( dwp850 < 0 )
dwp850 = 0;
/*Calculate SWEAT index*/
pssweat = 12 * dwp850 + 20 * term2 + 2 * skt850 + skt500 + shear;
}
return pssweat;
}
/**
* Finds the most unstable level of a sounding from the surface to the input pressure level.
* @param listOfNcSoundingLayer - the list of NcSoundingLayer to search
* @param plev - input pressure level
* @return the most unstable level of a sounding from the surface to the input pressure level (plev),
* if plev is not -1 and all computations fall through correctly.Else it returns an empty NcSoundingLayer object
*/
public static NcSoundingLayer psUstb(List<NcSoundingLayer> listOfNcSoundingLayer, float plev ){
//TODO: update to find pressure value between 2 levels
NcSoundingLayer outputNcSoundingLayer = new NcSoundingLayer(GempakConstants.RMISSD, GempakConstants.RMISSD,GempakConstants.RMISSD,
GempakConstants.RMISSD,GempakConstants.RMISSD,GempakConstants.RMISSD,
GempakConstants.RMISSD,GempakConstants.RMISSD,GempakConstants.RMISSD,
/**
* Computes low, middle, and high elevation Haines indices from the
* temperature and the dewpoint.
*
* @param tc1
* - temperature ( in Celsius )
* @param tc2
* - temperature ( in Celsius )
* @param dwpc
* - dewpoint ( in Celsius )
* @param itype
* - Haines index: 1- Low 2 - Middle 3 - High
*
* @return
*/
public static float psHans(float tc1, float tc2, float dwpc, float itype) {
float pshans = GempakConstants.RMISSD;
if (!MissingValueTester.isDataValueMissing(tc1)
&& !MissingValueTester.isDataValueMissing(tc2)
&& !MissingValueTester.isDataValueMissing(dwpc)) {
float a = GempakConstants.RMISSD;
float b = GempakConstants.RMISSD;
/* Compute the Haines index */
if (itype == 1) {
a = ((tc2 - tc1) - 3) * (2 / 5) + 1;
b = ((tc1 - dwpc) - 5) * (2 / 5) + 1;
} else if (itype == 2) {
a = ((tc1 - tc2) - 5) * (2 / 6) + 1;
b = ((tc1 - dwpc) - 5) * (2 / 8) + 1;
} else if (itype == 3) {
a = ((tc1 - tc2) - 17) * (2 / 5) + 1;
b = ((tc1 - dwpc) - 14) * (2 / 7) + 1;
}
a = (a > 0.9f ? a : 0.9f);
a = (a < 3.1f ? a : 3.1f);
b = (b > 0.9f ? b : 0.9f);
b = (b < 3.1f ? b : 3.1f);
pshans = a + b;
}
return pshans;
}
/**
*
* Computes the 'K' index
*
* @param t850
* - 850 mb temperature ( in Celsius )
* @param t700
* - 700 mb temperature ( in Celsius )
* @param t500
* - 500 mb temperature ( in Celsius )
* @param td850
* - 850 mb dewpoint ( in Celsius )
* @param td700
* - 700 mb dewpoint ( in Celsius )
* @return returns the 'K' index if all the input values are valid and
* RMISSD ( -9999 ) otherwise
*/
public static float pskinx(float t850, float t700, float t500, float td850,
float td700) {
float pskinx = GempakConstants.RMISSD;
if (!MissingValueTester.isDataValueMissing(td700)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(t700)
&& !MissingValueTester.isDataValueMissing(t850)) {
pskinx = (t850 - t500) + td850 - (t700 - td700);
}
return pskinx;
}
/**
* Computes the Showalter index
*
* @param t850
* - 850 mb temperature ( in Celsius )
* @param td850
* - 850 mb dewpoint ( in Celsius )
* @param t500
* - 500 mb temperature ( in Celsius )
* @return the Showalter index if all the three input parameters are valid
* and the parcel temperature is computed correctly. Otherwise, it
* returns RMISSD (-9999).
*/
public static float psShow(float t850, float td850, float t500) {
float psshow = GempakConstants.RMISSD;
if (!MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t850)) {
float p850 = 850;
float p500 = 500;
float guess = 0;
/*
* Find equivalent potential temperature at the LCL using 850 mb
* temperature and dewpoint.
*/
float thtlcl = PRLibrary.prThte(p850, t850, td850);
/*
* Find parcel temperature along pseudoadiabat at 500 mb. The parcel
* temperature tp is the temperature in Celsius at 500 mb of a
* parcel, which lies on the moist adiabat determined by the
* sounding at 850 mb
*/
float tp = PRLibrary.prTmst(thtlcl, p500, guess);
/*
* Subtract the parcel temperature from the temperature at 500 mb,
* is the parcel temperature is valid
*/
if (!MissingValueTester.isDataValueMissing(tp)) {
psshow = PRLibrary.prTmck(t500) - tp;
}
}
return psshow;
}
/**
* Computes the vertical totals index
*
* @param t850
* - 850 mb temperature ( in Celsius )
* @param t500
* - 500 mb temperature ( in Celsius )
* @return the verticl totals index as a difference of the temperature at
* 850 mb and the temperature at 500 mb, if neither value is
* missing. Else it returns RMISSD (-9999)
*/
public static float psVtot(float t850, float t500) {
return ((!MissingValueTester.isDataValueMissing(t500) && !MissingValueTester
.isDataValueMissing(t850)) ? t850 - t500
: GempakConstants.RMISSD);
}
/**
* Computes the total Totals index from the temperature and dewpoint at 850
* mb and the temperature at 500 mb
*
* @param t850
* - 850 mb temperature ( in Celsius )
* @param td850
* - 850 mb dewpoint ( in Celsius )
* @param t500
* - 500 mb temperature ( in Celsius )
* @return the total totals index if none of the input parameters are
* missing and RMISSD (-9999) otherwise
*/
public static float psTotl(float t850, float td850, float t500) {
float pstotl = GempakConstants.RMISSD;
if (!MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t850)) {
/* Compute the vertical totals */
float vtot = psVtot(t850, t500);
/* Compute the cross totals */
float ctot = psCtot(td850, t500);
if (!MissingValueTester.isDataValueMissing(ctot)
&& !MissingValueTester.isDataValueMissing(vtot)) {
pstotl = ctot + vtot;
}
}
return pstotl;
}
/**
* Computes the SWEAT index. Winds must be input in m/sec
*
* @param t850
* - 850 mb temperature
* @param td850
* - 850 mb dewpoint
* @param t500
* - 500 mb temperature
* @param spd850
* - 850 mb windspeed ( in m/sec )
* @param spd500
* - 500 mb windspeed ( in m/sec )
* @param dir850
* - 850 mb wind direction
* @param dir500
* - 500 mb wind direction
* @return the SWEAT index if none of the inputs are missing and RMISSD (
* -9999 ) otherwise
*/
public static float psSwet(float t850, float td850, float t500,
float spd850, float spd500, float dir850, float dir500) {
float pssweat = GempakConstants.RMISSD;
if (!MissingValueTester.isDataValueMissing(dir500)
&& !MissingValueTester.isDataValueMissing(dir850)
&& !MissingValueTester.isDataValueMissing(spd500)
&& !MissingValueTester.isDataValueMissing(spd850)
&& !MissingValueTester.isDataValueMissing(t500)
&& !MissingValueTester.isDataValueMissing(td850)
&& !MissingValueTester.isDataValueMissing(t850)) {
/*
* (Non-Javadoc): All computations are from Miller, R.C., 1972:
* Notes on Severe Storm Forecasting Procedures of the Air Force
* Global Weather Central, AWS Tech. Report 200
*/
/* Convert meters per second to knots */
float skt850 = PRLibrary.prMskn(spd850);
float skt500 = PRLibrary.prMskn(spd500);
/* Compute the total totals index. If < 49, set term to zero. */
float total = psTotl(t850, td850, t500);
float term2 = total - 49;
if (total < 49)
term2 = 0;
/* Compute shear term. */
float dif = dir500 - dir850;
float s = (float) (Math.sin(dif * GempakConstants.DTR));
float shear = 125 * (s + 0.2f);
/* Make various wind checks. */
if ((dir850 < 130.) || (dir850 > 250.))
shear = 0;
if ((dir500 < 210.) || (dir500 > 310.))
shear = 0;
if ((skt500 < 15.) || (skt850 < 15.))
shear = 0;
if (dif <= 0)
shear = 0;
/* Check for sub-zero dewpoint */
float dwp850 = td850;
if (dwp850 < 0)
dwp850 = 0;
/* Calculate SWEAT index */
pssweat = 12 * dwp850 + 20 * term2 + 2 * skt850 + skt500 + shear;
}
return pssweat;
}
/**
* Finds the most unstable level of a sounding from the surface to the input
* pressure level.
*
* @param listOfNcSoundingLayer
* - the list of NcSoundingLayer to search
* @param plev
* - input pressure level
* @return the most unstable level of a sounding from the surface to the
* input pressure level (plev), if plev is not -1 and all
* computations fall through correctly.Else it returns an empty
* NcSoundingLayer object
*/
public static NcSoundingLayer psUstb(
List<NcSoundingLayer> listOfNcSoundingLayer, float plev) {
// TODO: update to find pressure value between 2 levels
NcSoundingLayer outputNcSoundingLayer = new NcSoundingLayer(
GempakConstants.RMISSD, GempakConstants.RMISSD,
GempakConstants.RMISSD, GempakConstants.RMISSD,
GempakConstants.RMISSD, GempakConstants.RMISSD,
GempakConstants.RMISSD, GempakConstants.RMISSD,
GempakConstants.RMISSD, GempakConstants.RMISSD,
GempakConstants.RMISSD, GempakConstants.RMISSD);
class PressureComparator implements Comparator < NcSoundingLayer>{
public int compare(NcSoundingLayer n1, NcSoundingLayer n2){
return Float.compare(n2.getPressure(), n1.getPressure());
}
}
if ( listOfNcSoundingLayer != null && listOfNcSoundingLayer.size() > 0 ){
Collections.sort(listOfNcSoundingLayer, new PressureComparator() );
NcSoundingLayer surfaceLevelNcSoundingLayer = listOfNcSoundingLayer.get( 0 );
float pressureAtSurfaceLevel = surfaceLevelNcSoundingLayer.getPressure();
NcSoundingLayer topLevelNcSoundingLayer = PCLibrary.pcFtop( listOfNcSoundingLayer );
float pressureAtTopLevel = topLevelNcSoundingLayer.getPressure();
class PressureComparator implements Comparator<NcSoundingLayer> {
public int compare(NcSoundingLayer n1, NcSoundingLayer n2) {
return Float.compare(n2.getPressure(), n1.getPressure());
}
}
if (listOfNcSoundingLayer != null && listOfNcSoundingLayer.size() > 0) {
Collections.sort(listOfNcSoundingLayer, new PressureComparator());
NcSoundingLayer surfaceLevelNcSoundingLayer = listOfNcSoundingLayer
.get(0);
float pressureAtSurfaceLevel = surfaceLevelNcSoundingLayer
.getPressure();
NcSoundingLayer topLevelNcSoundingLayer = PCLibrary
.pcFtop(listOfNcSoundingLayer);
float pressureAtTopLevel = topLevelNcSoundingLayer.getPressure();
if( plev > pressureAtSurfaceLevel)
return outputNcSoundingLayer;
else if ( plev == -1 || plev <= pressureAtTopLevel )
plev = pressureAtTopLevel;
if (plev > pressureAtSurfaceLevel)
return outputNcSoundingLayer;
else if (plev == -1 || plev <= pressureAtTopLevel)
plev = pressureAtTopLevel;
int sizeOfList = listOfNcSoundingLayer.size();
boolean done = false;
int lev = 0;
float eps = GempakConstants.RMISSD;
while (!done && lev < sizeOfList) {
NcSoundingLayer currNcSoundingLayer = listOfNcSoundingLayer
.get(lev);
float pressure = currNcSoundingLayer.getPressure();
float tmpc = currNcSoundingLayer.getTemperature();
float dwpc = currNcSoundingLayer.getDewpoint();
float thwc = PRLibrary.prThwc(pressure, tmpc, dwpc);
System.out.println("pressure = " + pressure);
System.out.println("thwc = " + thwc);
if (thwc > eps && (pressure >= plev)) {
eps = thwc;
outputNcSoundingLayer.setPressure(currNcSoundingLayer
.getPressure());
outputNcSoundingLayer.setTemperature(currNcSoundingLayer
.getTemperature());
outputNcSoundingLayer.setDewpoint(currNcSoundingLayer
.getDewpoint());
outputNcSoundingLayer.setWindSpeed(currNcSoundingLayer
.getWindSpeed());
outputNcSoundingLayer.setWindDirection(currNcSoundingLayer
.getWindDirection());
outputNcSoundingLayer.setWindU(currNcSoundingLayer
.getWindU());
outputNcSoundingLayer.setWindV(currNcSoundingLayer
.getWindV());
outputNcSoundingLayer.setGeoHeight(currNcSoundingLayer
.getGeoHeight());
outputNcSoundingLayer.setOmega(currNcSoundingLayer
.getOmega());
outputNcSoundingLayer.setSpecHumidity(currNcSoundingLayer
.getSpecHumidity());
System.out.println("Outdat: "
+ outputNcSoundingLayer.getPressure() + " "
+ outputNcSoundingLayer.getTemperature() + " "
+ outputNcSoundingLayer.getDewpoint() + " "
+ outputNcSoundingLayer.getWindSpeed() + " "
+ outputNcSoundingLayer.getWindDirection() + " "
+ outputNcSoundingLayer.getGeoHeight());
}
lev++;
if (pressure <= plev)
done = true;
}
}
System.out.println("From PS_USTB Outdat: "
+ outputNcSoundingLayer.getPressure() + " "
+ outputNcSoundingLayer.getTemperature() + " "
+ outputNcSoundingLayer.getDewpoint() + " "
+ outputNcSoundingLayer.getWindSpeed() + " "
+ outputNcSoundingLayer.getWindDirection() + " "
+ outputNcSoundingLayer.getGeoHeight());
return outputNcSoundingLayer;
}
int sizeOfList = listOfNcSoundingLayer.size();
boolean done = false;
int lev = 0;
float eps = GempakConstants.RMISSD;
while ( !done && lev < sizeOfList){
NcSoundingLayer currNcSoundingLayer = listOfNcSoundingLayer.get(lev);
float pressure = currNcSoundingLayer.getPressure();
float tmpc = currNcSoundingLayer.getTemperature();
float dwpc = currNcSoundingLayer.getDewpoint();
float thwc = PRLibrary.prThwc(pressure, tmpc, dwpc);
System.out.println("pressure = " + pressure);
System.out.println("thwc = " + thwc);
if ( thwc > eps && ( pressure >= plev ) ){
eps = thwc;
outputNcSoundingLayer.setPressure( currNcSoundingLayer.getPressure() );
outputNcSoundingLayer.setTemperature( currNcSoundingLayer.getTemperature() );
outputNcSoundingLayer.setDewpoint( currNcSoundingLayer.getDewpoint() );
outputNcSoundingLayer.setWindSpeed( currNcSoundingLayer.getWindSpeed() );
outputNcSoundingLayer.setWindDirection( currNcSoundingLayer.getWindDirection() );
outputNcSoundingLayer.setWindU( currNcSoundingLayer.getWindU() );
outputNcSoundingLayer.setWindV( currNcSoundingLayer.getWindV() );
outputNcSoundingLayer.setGeoHeight( currNcSoundingLayer.getGeoHeight() );
outputNcSoundingLayer.setOmega( currNcSoundingLayer.getOmega() );
outputNcSoundingLayer.setSpecHumidity( currNcSoundingLayer.getSpecHumidity() );
System.out.println("Outdat: "
+ outputNcSoundingLayer.getPressure() + " "
+ outputNcSoundingLayer.getTemperature() + " "
+ outputNcSoundingLayer.getDewpoint() + " "
+ outputNcSoundingLayer.getWindSpeed() + " "
+ outputNcSoundingLayer.getWindDirection() + " "
+ outputNcSoundingLayer.getGeoHeight() );
}
lev++;
if ( pressure <= plev )
done = true;
}
}
System.out.println("From PS_USTB Outdat: "
+ outputNcSoundingLayer.getPressure() + " "
+ outputNcSoundingLayer.getTemperature() + " "
+ outputNcSoundingLayer.getDewpoint() + " "
+ outputNcSoundingLayer.getWindSpeed() + " "
+ outputNcSoundingLayer.getWindDirection() + " "
+ outputNcSoundingLayer.getGeoHeight() );
return outputNcSoundingLayer;
}
}

View file

@ -16,6 +16,7 @@ Import-Package: com.vividsolutions.jts.geom,
com.vividsolutions.jts.operation.valid,
gov.noaa.nws.ncep.common.dataplugin.aww,
gov.noaa.nws.ncep.ui.pgen,
gov.noaa.nws.ncep.staticdataprovider,
gov.noaa.nws.ncep.viz.common.dbQuery,
gov.noaa.nws.ncep.viz.localization,
gov.noaa.nws.ncep.viz.resources,

View file

@ -8,6 +8,20 @@
package gov.noaa.nws.ncep.staticdataprovider;
import gov.noaa.nws.ncep.common.staticdata.CostalWater;
import gov.noaa.nws.ncep.common.staticdata.Cwa;
import gov.noaa.nws.ncep.common.staticdata.FAArea;
import gov.noaa.nws.ncep.common.staticdata.FARegion;
import gov.noaa.nws.ncep.common.staticdata.GreatLake;
import gov.noaa.nws.ncep.common.staticdata.IStaticDataProvider;
import gov.noaa.nws.ncep.common.staticdata.Rfc;
import gov.noaa.nws.ncep.common.staticdata.SPCCounty;
import gov.noaa.nws.ncep.common.staticdata.USState;
import gov.noaa.nws.ncep.edex.common.stationTables.StationTable;
import gov.noaa.nws.ncep.viz.common.dbQuery.NcDirectDbQuery;
import gov.noaa.nws.ncep.viz.localization.NcPathManager;
import gov.noaa.nws.ncep.viz.localization.NcPathManager.NcPathConstants;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
@ -27,22 +41,9 @@ import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.MultiPolygon;
import com.vividsolutions.jts.geom.Polygon;
import gov.noaa.nws.ncep.common.staticdata.CostalWater;
import gov.noaa.nws.ncep.common.staticdata.Cwa;
import gov.noaa.nws.ncep.common.staticdata.FAArea;
import gov.noaa.nws.ncep.common.staticdata.FARegion;
import gov.noaa.nws.ncep.common.staticdata.GreatLake;
import gov.noaa.nws.ncep.common.staticdata.IStaticDataProvider;
import gov.noaa.nws.ncep.common.staticdata.Rfc;
import gov.noaa.nws.ncep.common.staticdata.SPCCounty;
import gov.noaa.nws.ncep.common.staticdata.USState;
import gov.noaa.nws.ncep.edex.common.stationTables.StationTable;
import gov.noaa.nws.ncep.viz.common.dbQuery.NcDirectDbQuery;
import gov.noaa.nws.ncep.viz.localization.NcPathManager;
import gov.noaa.nws.ncep.viz.localization.NcPathManager.NcPathConstants;
/**
* Implementation of IStaticdataProvder interface. It contains methods that load static data.
* Implementation of IStaticdataProvder interface. It contains methods that load
* static data.
*
* <pre>
* SOFTWARE HISTORY
@ -52,307 +53,305 @@ import gov.noaa.nws.ncep.viz.localization.NcPathManager.NcPathConstants;
* 06/12 734 J. Zeng add getAllRfcs() and getAllCwas()
* 08/12 #770 Q. Zhou added loadContWatchNum()
* 01/13 #966 B. Yin Added methods to load bounds info.
* 04/14 TRAC 1112 S. Russell Added getActiveCounties()
*
* </pre>
*
* @author B. Yin
* @author B. Yin
*/
public class StaticDataProvider implements IStaticDataProvider {
static private StaticDataProvider dataProvider;
static private StaticDataProvider dataProvider;
static public IStaticDataProvider getInstance(){
if (dataProvider == null) dataProvider = new StaticDataProvider();
return dataProvider;
}
static public IStaticDataProvider getInstance() {
if (dataProvider == null)
dataProvider = new StaticDataProvider();
return dataProvider;
}
private StaticDataProvider(){
private StaticDataProvider() {
}
}
static public void start(){
};
static public void start() {
};
@Override
public StationTable getSfStnTbl() {
return StationTableProvider.getSfStnTbl();
}
@Override
public StationTable getSfStnTbl() {
return StationTableProvider.getSfStnTbl();
}
@Override
public StationTable getAnchorTbl() {
return StationTableProvider.getAnchorTbl();
}
@Override
public StationTable getAnchorTbl() {
return StationTableProvider.getAnchorTbl();
}
@Override
public StationTable getVorTbl() {
return StationTableProvider.getVorTbl();
}
@Override
public StationTable getVorTbl() {
return StationTableProvider.getVorTbl();
}
@Override
public StationTable getVolcanoTbl() {
return StationTableProvider.getVolcanoTbl();
}
@Override
public StationTable getVolcanoTbl() {
return StationTableProvider.getVolcanoTbl();
}
@Override
public HashMap<String, Set<String>> getClstTbl() {
return StationTableProvider.getClstTbl();
}
@Override
public HashMap<String, Set<String>> getClstTbl() {
return StationTableProvider.getClstTbl();
}
@Override
public List<SPCCounty> getSPCCounties(){
return SPCCountyProvider.getSPCCounties();
}
@Override
public List<SPCCounty> getSPCCounties() {
return SPCCountyProvider.getSPCCounties();
}
@Override
public SPCCounty findCounty(String fips) {
return SPCCountyProvider.findCounty(fips);
@Override
public SPCCounty findCounty(String fips) {
return SPCCountyProvider.findCounty(fips);
}
}
@Override
public List<SPCCounty> getCountiesInGeometry(Geometry geo) {
return SPCCountyProvider.getCountiesInGeometry(geo);
}
@Override
public List<SPCCounty> getCountiesInGeometry(Geometry geo) {
return SPCCountyProvider.getCountiesInGeometry(geo);
}
@Override
public String getPgenLocalizationRoot() {
return NcPathConstants.PGEN_ROOT;
}
@Override
public String getPgenLocalizationRoot() {
return NcPathConstants.PGEN_ROOT;
}
@Override
public String getFileAbsolutePath(String fileLoczlizationPath) {
return NcPathManager.getInstance().getStaticFile( fileLoczlizationPath ).getAbsolutePath();
}
@Override
public String getFileAbsolutePath(String fileLoczlizationPath) {
return NcPathManager.getInstance().getStaticFile(fileLoczlizationPath).getAbsolutePath();
}
@Override
public File getFile(String fileLoczlizationPath) {
return NcPathManager.getInstance().getStaticFile( fileLoczlizationPath );
}
@Override
public File getFile(String fileLoczlizationPath) {
return NcPathManager.getInstance().getStaticFile(fileLoczlizationPath);
}
@Override
public LocalizationFile getStaticLocalizationFile(String fileName) {
return NcPathManager.getInstance().getStaticLocalizationFile( fileName );
@Override
public LocalizationFile getStaticLocalizationFile(String fileName) {
return NcPathManager.getInstance().getStaticLocalizationFile(fileName);
}
}
@Override
public File getStaticFile(String fname) {
return NcPathManager.getInstance().getStaticFile( fname );
@Override
public File getStaticFile(String fname) {
return NcPathManager.getInstance().getStaticFile(fname);
}
}
@Override
public File getGeogFile() {
return NcPathManager.getInstance().getStaticFile(
NcPathConstants.GEOG_TBL );
}
@Override
public File getGeogFile() {
return NcPathManager.getInstance().getStaticFile(NcPathConstants.GEOG_TBL);
}
@Override
public File getSfcStnFile() {
return NcPathManager.getInstance().getStaticFile(
NcPathConstants.SFSTNS_TBL );
}
@Override
public File getSfcStnFile() {
return NcPathManager.getInstance().getStaticFile(NcPathConstants.SFSTNS_TBL);
}
@Override
public LocalizationContext getLocalizationContext(LocalizationType type,
LocalizationLevel level) {
return NcPathManager.getInstance().getContext(type, level);
}
@Override
public LocalizationContext getLocalizationContext(LocalizationType type, LocalizationLevel level) {
return NcPathManager.getInstance().getContext(type, level);
}
@Override
public LocalizationFile getLocalizationFile(LocalizationContext context,
String fileName) {
return NcPathManager.getInstance().getLocalizationFile(context,
fileName);
}
@Override
public LocalizationFile getLocalizationFile(LocalizationContext context, String fileName) {
return NcPathManager.getInstance().getLocalizationFile(context, fileName);
}
@Override
public File getFirBoundsFile() {
return NcPathManager.getInstance().getStaticFile(
NcPathConstants.PGEN_FIR_BOUNDS) ;
}
@Override
public File getFirBoundsFile() {
return NcPathManager.getInstance().getStaticFile(NcPathConstants.PGEN_FIR_BOUNDS);
}
@Override
public List<Object[]> queryNcepDB(String field, String table) {
List<Object[]> list = null;
String query = "Select AsBinary(the_geom_0_016), "+field+" FROM "+table;//mapdata.states";
try {
list = NcDirectDbQuery.executeQuery( query, "ncep", QueryLanguage.SQL);
}
catch (Exception e ){
System.out.println("___ Error: SigmetCommAttrDlg: initAllStates(): "+e.getMessage());
list = new ArrayList<Object[]>();
}
return list;
}
@Override
public List<Object[]> queryNcepDB(String field, String table) {
List<Object[]> list = null;
String query = "Select AsBinary(the_geom_0_016), " + field + " FROM " + table;// mapdata.states";
@Override
public HashMap<String, String> getZoneMap() {
// query used to grab forecast zones from EDEX Database
// TODO - move column/table names to config file so query is not hardwired in code
String zoneQuery = "select state,zone,cwa from mapdata.zone;";
HashMap<String, String> zoneMap = new HashMap<String,String>();
QueryResult results = null;
try {
results = NcDirectDbQuery.executeMappedQuery(zoneQuery, "maps", QueryLanguage.SQL);
QueryResultRow[] rows = results.getRows();
Map<String,Integer> columns = results.getColumnNames();
//System.out.println("column nmaes: "+columns.keySet().toString());
for ( QueryResultRow row : rows ) {
Object state = row.getColumn( columns.get("state") );
Object zone = row.getColumn( columns.get("zone") );
Object cwa = row.getColumn( columns.get("cwa") );
if ( state!=null && zone!=null && cwa!=null ) {
zoneMap.put(state.toString()+"Z"+zone.toString(), cwa.toString());
}
}
}
catch ( VizException ve ) {
ve.printStackTrace();
}
return zoneMap;
}
try {
list = NcDirectDbQuery.executeQuery(query, "ncep", QueryLanguage.SQL);
} catch (Exception e) {
System.out.println("___ Error: SigmetCommAttrDlg: initAllStates(): " + e.getMessage());
list = new ArrayList<Object[]>();
}
@Override
public List<USState> getAllstates() {
return USStateProvider.getAllStates();
}
return list;
}
@Override
public List<USState> loadStateTable(){
return USStateProvider.loadStateTable();
}
@Override
public ArrayList<USState> statesInGeometry(Geometry geo) {
return USStateProvider.statesInGeometry(geo);
}
@Override
public List<Rfc> getAllRfcs() {
return RfcProvider.getAllRfcs();
}
@Override
public HashMap<String, String> getZoneMap() {
@Override
public List<Rfc> loadRfcTable() {
return RfcProvider.loadRfcTable();
}
// query used to grab forecast zones from EDEX Database
// TODO - move column/table names to config file so query is not
// hardwired in code
String zoneQuery = "select state,zone,cwa from mapdata.zone;";
@Override
public ArrayList<Rfc> rfcsInGeometry(Geometry geo) {
return RfcProvider.rfcsInGeometry(geo);
}
@Override
public List<Cwa> getAllCwas() {
return CwaProvider.getAllCwas();
}
HashMap<String, String> zoneMap = new HashMap<String, String>();
QueryResult results = null;
@Override
public List<Cwa> loadCwaTable() {
return CwaProvider.loadCwaTable();
}
@Override
public ArrayList<Cwa> cwasInGeometry(Geometry geo) {
return CwaProvider.cwasInGeometry(geo);
}
@Override
public HashMap<String, String> getStateAbrvMap() {
HashMap<String, String> stMap = new HashMap<String,String>();
String queryStates = "Select state,name FROM mapdata.states;";
try {
List<Object[]> states = NcDirectDbQuery.executeQuery(
queryStates, "maps", QueryLanguage.SQL);
try {
results = NcDirectDbQuery.executeMappedQuery(zoneQuery, "maps", QueryLanguage.SQL);
QueryResultRow[] rows = results.getRows();
Map<String, Integer> columns = results.getColumnNames();
// System.out.println("column nmaes: "+columns.keySet().toString());
for (QueryResultRow row : rows) {
Object state = row.getColumn(columns.get("state"));
Object zone = row.getColumn(columns.get("zone"));
Object cwa = row.getColumn(columns.get("cwa"));
if (state != null && zone != null && cwa != null) {
zoneMap.put(state.toString() + "Z" + zone.toString(), cwa.toString());
}
}
} catch (VizException ve) {
ve.printStackTrace();
}
for ( Object[] st : states ){
if ( st[0] !=null && st[1] != null){
stMap.put((String)st[0], (String)st[1]);
}
}
}
catch (Exception e ){
System.out.println("db exception reading state tables!");
e.printStackTrace();
}
return stMap;
}
return zoneMap;
}
@Override
public List<FAArea> getFAAreas() {
return FAAreaProvider.getFAAreas();
}
@Override
public List<USState> getAllstates() {
return USStateProvider.getAllStates();
}
@Override
public List<FARegion> getFARegions() {
return FARegionProvider.getFARegions();
@Override
public List<USState> loadStateTable() {
return USStateProvider.loadStateTable();
}
}
@Override
public ArrayList<USState> statesInGeometry(Geometry geo) {
return USStateProvider.statesInGeometry(geo);
}
@Override
public List<FAArea> getFAAreaX() {
return FAAreaProvider.getFAAreaX();
@Override
public List<Rfc> getAllRfcs() {
return RfcProvider.getAllRfcs();
}
}
@Override
public List<Rfc> loadRfcTable() {
return RfcProvider.loadRfcTable();
}
@Override
public List<GreatLake> getGreatLakes() {
return GreatLakeProvider.getGreatLakes();
}
@Override
public ArrayList<Rfc> rfcsInGeometry(Geometry geo) {
return RfcProvider.rfcsInGeometry(geo);
}
@Override
public List<CostalWater> getCostalWaters() {
return CostalWaterProvider.getCostalWaters();
// TRAC 1112
@Override
public List<String> getActiveCounties(int watchNum, List<SPCCounty> oldCountyList) {
return new WatchActiveCounties().getActiveCounties(watchNum, oldCountyList);
}
}
@Override
public List<Cwa> getAllCwas() {
return CwaProvider.getAllCwas();
}
@Override
public ArrayList<MultiPolygon> getG2GBounds(String tableAlias,
String columnName, String columnValue) {
return G2GBoundsProvider.getG2GBounds(tableAlias, columnName, columnValue);
}
@Override
public List<Cwa> loadCwaTable() {
return CwaProvider.loadCwaTable();
}
@Override
public boolean isRfcLoaded() {
return RfcProvider.isRfcLoaded();
}
@Override
public ArrayList<Cwa> cwasInGeometry(Geometry geo) {
return CwaProvider.cwasInGeometry(geo);
}
@Override
public List<String> loadContWatchNum() {
// TODO Auto-generated method stub
List<String> watchNum = new ArrayList<String>();
try {
watchNum = ContinuingWatch.loadContWatchNum();
} catch (VizException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return watchNum;
}
@Override
public HashMap<String, String> getStateAbrvMap() {
HashMap<String, String> stMap = new HashMap<String, String>();
String queryStates = "Select state,name FROM mapdata.states;";
try {
List<Object[]> states = NcDirectDbQuery.executeQuery(queryStates, "maps", QueryLanguage.SQL);
@Override
public List<String> getBoundsTableList() {
return BoundsProvider.getBoundsList();
}
for (Object[] st : states) {
if (st[0] != null && st[1] != null) {
stMap.put((String) st[0], (String) st[1]);
}
}
} catch (Exception e) {
System.out.println("db exception reading state tables!");
e.printStackTrace();
}
return stMap;
}
@Override
public List<String> getBoundsNames( String table ) {
return BoundsProvider.loadBoundsNames( table );
}
@Override
public List<FAArea> getFAAreas() {
return FAAreaProvider.getFAAreas();
}
@Override
public Polygon loadBounds(String boundsTable, String boundsName) {
return BoundsProvider.loadBounds( boundsTable, boundsName );
@Override
public List<FARegion> getFARegions() {
return FARegionProvider.getFARegions();
}
}
@Override
public List<FAArea> getFAAreaX() {
return FAAreaProvider.getFAAreaX();
}
@Override
public List<GreatLake> getGreatLakes() {
return GreatLakeProvider.getGreatLakes();
}
@Override
public List<CostalWater> getCostalWaters() {
return CostalWaterProvider.getCostalWaters();
}
@Override
public ArrayList<MultiPolygon> getG2GBounds(String tableAlias, String columnName, String columnValue) {
return G2GBoundsProvider.getG2GBounds(tableAlias, columnName, columnValue);
}
@Override
public boolean isRfcLoaded() {
return RfcProvider.isRfcLoaded();
}
@Override
public List<String> loadContWatchNum() {
// TODO Auto-generated method stub
List<String> watchNum = new ArrayList<String>();
try {
watchNum = ContinuingWatch.loadContWatchNum();
} catch (VizException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return watchNum;
}
@Override
public List<String> getBoundsTableList() {
return BoundsProvider.getBoundsList();
}
@Override
public List<String> getBoundsNames(String table) {
return BoundsProvider.loadBoundsNames(table);
}
@Override
public Polygon loadBounds(String boundsTable, String boundsName) {
return BoundsProvider.loadBounds(boundsTable, boundsName);
}
}

View file

@ -0,0 +1,351 @@
package gov.noaa.nws.ncep.staticdataprovider;
import gov.noaa.nws.ncep.common.dataplugin.aww.AwwFips;
import gov.noaa.nws.ncep.common.dataplugin.aww.AwwRecord;
import gov.noaa.nws.ncep.common.dataplugin.aww.AwwUgc;
import gov.noaa.nws.ncep.common.dataplugin.aww.AwwVtec;
import gov.noaa.nws.ncep.common.staticdata.SPCCounty;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequest.OrderMode;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
import com.raytheon.uf.viz.core.requests.ThriftClient;
/**
* Data retrieval from the AWW tables by report type (WCN) and by watch number.
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 2104 Mar 21 TRAC 1112 srussell Initial creation
*
* ----------------------------------------------------------------------------
* Possible aw_vtec.action values:
* ----------------------------------------------------------------------------
* NEW - Brand new product
* CON - Continues for a subset of counties (usually issued in segmented
* fashion with CAN).
* CAN - Cancels part or all of the area in the product.
* EXP - Watch expiration statement, this is different than a CAN in the
* sense that it does not stop immediately but at the initial
* expiration time of the watch.
* EXT - Extends the time a watch is valid for
* EXA - Extends the area a watch is valid for
* EXB - Extends the area and time a watch is valid for
*
* http://www.nws.noaa.gov/directives/sym/pd01005011curr.pdf
* -----------------------------------------------------------------------------
*
* </pre>
*
* @author srussell
* @version 1.0
*/
public class WatchActiveCounties {
private final static TimeZone utc = TimeZone.getTimeZone("UTC");
/* Queries Aww tables by report type and by watch number. Once it gets the
* AWW records, it will loop through the records and get the latest county
* UGCs. It will skip the UGCs with the action code CAN (canceled). It
* will return a list of active county UGCs. */
public List<String> getActiveCounties(int watchNum, List<SPCCounty> watchBoxCountyList) {
List<String> ugcList = new ArrayList<String>();
List<WatchRecord> watchRecords = new ArrayList<WatchRecord>();
HashMap<String, RequestConstraint> constraints = new HashMap<String, RequestConstraint>();
String pluginName = "aww";
String reportType = "WATCH COUNTY NOTIFICATION";
String orderBy = "issueTime,issueOffice";
String likeClause = "%" + watchNum + "%";
ConstraintType like = ConstraintType.LIKE;
constraints.put("pluginName", new RequestConstraint(pluginName));
constraints.put("reportType", new RequestConstraint(reportType));
constraints.put("watchNumber", new RequestConstraint(likeClause, like));
DbQueryRequest request = new DbQueryRequest();
request.setConstraints(constraints);
request.setOrderByField(orderBy, OrderMode.ASC);
try {
DbQueryResponse response = (DbQueryResponse) ThriftClient.sendRequest(request);
if (response == null) {
return ugcList;
}
List<Map<String, Object>> responseList = response.getResults();
AwwRecord awwRecord = null;
// Retrieve the latest watch records from the database for this watch
for (Map<String, Object> eachResponse : responseList) {
Collection<Object> recordObj = eachResponse.values();
for (Object pdo : recordObj) {
if (pdo instanceof AwwRecord) {
awwRecord = (AwwRecord) pdo;
addWatchRecord(watchRecords, awwRecord, watchNum);
}
}
}
// Copy the county ID strings out of the watch box county list
for (SPCCounty county : watchBoxCountyList) {
ugcList.add(county.getUgcId());
}
// Update the list of counties from the watch box list, with values
// the values retrieved from the database.
updateWatchBoxCountyList(ugcList, watchRecords);
} catch (Exception e) {
e.printStackTrace();
}
return ugcList;
}
private static void updateWatchBoxCountyList(List<String> ugcList, List<WatchRecord> watchRecords) {
String ugc = null;
String action = null;
Calendar eventEndTime = null;
Calendar currentTime = null;
for (WatchRecord wr : watchRecords) {
ugc = wr.getUgc();
action = wr.getAction();
// New county put into the watch
if (action.equalsIgnoreCase("NEW")) {
if (!ugcList.contains(ugc)) {
ugcList.add(ugc);
}
}
// County watch cancelled
else if (action.equalsIgnoreCase("CAN")) {
ugcList.remove(ugc);
}
// County watch "expired"
else if (action.equalsIgnoreCase("EXP")) {
eventEndTime = wr.getEventEndTime();
eventEndTime.setTimeZone(utc);
currentTime = Calendar.getInstance(utc);
if (ugcList.contains(ugc) && eventEndTime.before(currentTime)) {
ugcList.remove(ugc);
}
}
}
}
private void addWatchRecord(List<WatchRecord> watchRecords, AwwRecord aww, int watchNum) {
if (aww == null) {
return;
}
WatchRecord county = null;
int watchNumInUGC = -1;
Set<AwwUgc> ugcSet = aww.getAwwUGC();
String wfo = aww.getIssueOffice();
Calendar issueTime = aww.getIssueTime();
// For each AwwUgc
for (AwwUgc ugc : ugcSet) {
watchNumInUGC = -1;
try {
// Get the watch number from the UGC
watchNumInUGC = Integer.parseInt(ugc.getEventTrackingNumber());
} catch (NumberFormatException e) {
continue;
}
// If watch number in the UGC does NOT match the one in the query
if (watchNumInUGC != watchNum) {
continue;
}
Set<AwwVtec> vtec = ugc.getAwwVtecLine();
if (vtec.isEmpty()) {
continue;
}
// Get the vtec.action
AwwVtec one_vtec = vtec.iterator().next();
String action = one_vtec.getAction();
// Get the UGC
Set<AwwFips> fipsSet = ugc.getAwwFIPS();
for (AwwFips fips : fipsSet) {
county = this.new WatchRecord();
county.setUgc(fips.getFips());
county.setWfo(wfo);
county.setAction(action);
county.setIssueTIme(issueTime);
if (action.equalsIgnoreCase("EXP")) {
county.setEventEndTime(one_vtec.getEventEndTime());
}
if (!watchRecords.contains(county)) {
watchRecords.add(county);
}
}
}
}// end function addAwwUgc
private class WatchRecord {
private String ugc = null;
private String wfo = null;
private String action = null;
private Calendar eventEndTime = null;
private Calendar issueTime = null;
public WatchRecord() {
}
public String getUgc() {
return ugc;
}
public void setUgc(String ugc) {
this.ugc = ugc;
}
public String getWfo() {
return wfo;
}
public void setWfo(String wfo) {
this.wfo = wfo;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public Calendar getEventEndTime() {
return eventEndTime;
}
public void setEventEndTime(Calendar eventEndTime) {
this.eventEndTime = eventEndTime;
}
public Calendar getIssueTime() {
return issueTime;
}
public void setIssueTIme(Calendar issueTime) {
this.issueTime = issueTime;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((action == null) ? 0 : action.hashCode());
result = prime * result + ((eventEndTime == null) ? 0 : eventEndTime.hashCode());
result = prime * result + ((issueTime == null) ? 0 : issueTime.hashCode());
result = prime * result + ((ugc == null) ? 0 : ugc.hashCode());
result = prime * result + ((wfo == null) ? 0 : wfo.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof WatchRecord)) {
return false;
}
WatchRecord other = (WatchRecord) obj;
if (!getOuterType().equals(other.getOuterType())) {
return false;
}
if (action == null) {
if (other.action != null) {
return false;
}
} else if (!action.equals(other.action)) {
return false;
}
if (eventEndTime == null) {
if (other.eventEndTime != null) {
return false;
}
} else if (!eventEndTime.equals(other.eventEndTime)) {
return false;
}
if (issueTime == null) {
if (other.issueTime != null) {
return false;
}
} else if (!issueTime.equals(other.issueTime)) {
return false;
}
if (ugc == null) {
if (other.ugc != null) {
return false;
}
} else if (!ugc.equals(other.ugc)) {
return false;
}
if (wfo == null) {
if (other.wfo != null) {
return false;
}
} else if (!wfo.equals(other.wfo)) {
return false;
}
return true;
}
private WatchActiveCounties getOuterType() {
return WatchActiveCounties.this;
}
}
}// end class WatchActiveCounties

View file

@ -140,7 +140,6 @@ import com.vividsolutions.jts.operation.distance.DistanceOp;
* this class
* 11/13 TTR 752 J. Wu added methods to compute an element's range record.
* 12/13 #1089 B. Yin Modify watch to display county list
* 02/14 #2819 R. Anderson Removed unnecessary .clone() call
* 02/14 #2819 R. Anderson Removed unnecessary .clone() call
* </pre>
*
@ -648,110 +647,6 @@ public class DisplayElementFactory {
ArrayList<IDisplayable> dlist = new ArrayList<IDisplayable>();
List<SPCCounty> counties = watchBox.getOriginalCountyList();
<<<<<<< HEAD
if ( counties == null || counties.isEmpty()){ //if the watch is not issued yet, the original county list is not set.
counties = watchBox.getCountyList();
}
if ( counties != null && !counties.isEmpty()){
if ( watchBox.getFillFlag() ){
Geometry cntyUnion = null;;
Color[] colors = null;
Collection<Geometry> gCollection = new ArrayList<Geometry>();
//draw county border
for ( SPCCounty cnty : counties ){
Geometry countyGeo = cnty.getShape();
colors = watchBox.getColors();
colors[1] = watchBox.getFillColor();
for ( int ii = 0; ii < countyGeo.getNumGeometries(); ii ++ ){
Polygon poly = (Polygon)countyGeo.getGeometryN(ii);
List<Coordinate> pts = new ArrayList<Coordinate>(Arrays.asList(poly.getCoordinates()));
Line cntyBorder = new Line(null, colors,.5f,.5,true,
false, pts, 0,
FillPattern.FILL_PATTERN_6,"Lines","LINE_SOLID");
ArrayList<IDisplayable> cntyLine = createDisplayElements(cntyBorder,paintProps);
dlist.addAll(cntyLine);
}
if ( countyGeo != null ){
gCollection.add(countyGeo.buffer(.02));
}
}
//Merge counties together and fill the whole area
GeometryFactory gf = new GeometryFactory();
if ( gCollection.size() > 1 ){
GeometryCollection geometryCollection =
(GeometryCollection) gf.buildGeometry( gCollection );
cntyUnion = geometryCollection.union();
}
else cntyUnion = gf.buildGeometry( gCollection );
IShadedShape theShadedShape = target.createShadedShape(false, iDescriptor, true);
// IWireframeShape theWireframeShape = target.createWireframeShape(false, mapDescriptor);
JTSCompiler compiler = new JTSCompiler( theShadedShape,
null, iDescriptor, PointStyle.CROSS);
try {
compiler.handle(cntyUnion,
new RGB(colors[1].getRed(), colors[1].getGreen(), colors[1].getBlue()));
if ( elem.getFillPattern() != FillPattern.TRANSPARENCY &&
elem.getFillPattern() != FillPattern.SOLID ) {
FillPatternList fpl = new FillPatternList();
byte[] fpattern = fpl.getFillPattern(elem.getFillPattern());
theShadedShape.setFillPattern(fpattern);
}
theShadedShape.compile();
// theWireframeShape.compile();
//dlist.add(new LineDisplayElement(theWireframeShape, colors[1], .5f));
dlist.add( new FillDisplayElement(theShadedShape, 1f ));
} catch (VizException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
for ( SPCCounty cnty : counties ){
Symbol cSymbol = new Symbol(null, watchBox.getColors(),
watchBox.getWatchSymbolWidth(), watchBox.getWatchSymbolSize(), false,
cnty.getCentriod(), "Marker", watchBox.getWatchSymbolType());
ArrayList<IDisplayable> cList = createDisplayElements(cSymbol,paintProps);
dlist.addAll(cList);
}
}
}
//if already issued, draw the list of active counties with OCTAGON symbols.
if (watchBox.getIssueFlag() != 0 ){
List<SPCCounty> activeCounties = watchBox.getCountyList();
if ( activeCounties != null && !activeCounties.isEmpty()){
for ( SPCCounty cnty : activeCounties ){
Symbol cSymbol = new Symbol(null, IWatchBox.WATCH_LIST_COLOR,
3, 2, false,
cnty.getCentriod(), "Marker", "OCTAGON");
ArrayList<IDisplayable> cList = createDisplayElements(cSymbol,paintProps);
dlist.addAll(cList);
}
}
}
=======
if (counties == null || counties.isEmpty()) { // if the watch is not
// issued yet, the
// original county list is
@ -814,9 +709,8 @@ public class DisplayElementFactory {
iDescriptor, PointStyle.CROSS);
try {
compiler.handle(cntyUnion,
new RGB(colors[1].getRed(), colors[1].getGreen(),
colors[1].getBlue()));
compiler.handle(cntyUnion, new RGB(colors[1].getRed(),
colors[1].getGreen(), colors[1].getBlue()));
if (elem.getFillPattern() != FillPattern.TRANSPARENCY
&& elem.getFillPattern() != FillPattern.SOLID) {
@ -868,7 +762,6 @@ public class DisplayElementFactory {
}
}
>>>>>>> d3a1e1a... VLab Issue #3721 - NCEP CAVE plugin delivery for 14.3.1
Coordinate[] points = watchBox.getLinePoints();
ArrayList<Coordinate> ptsList = new ArrayList<Coordinate>();

View file

@ -1,5 +1,7 @@
package gov.noaa.nws.ncep.viz.common.area;
import gov.noaa.nws.ncep.edex.util.McidasCRSBuilder;
import org.geotools.coverage.grid.GeneralGridEnvelope;
import org.geotools.coverage.grid.GeneralGridGeometry;
import org.geotools.coverage.grid.GridEnvelope2D;
@ -21,10 +23,11 @@ import com.raytheon.uf.common.serialization.adapters.GridGeometrySerialized;
*
* <pre>
*
* SOFTWARE HISTORY
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 11/2013 1066 G. Hull Created.
* 03/2014 TTR957 B. Yin Handle native satellite navigation.
*
* </pre>
*
@ -52,7 +55,7 @@ public class NcGridGeometryAdapter extends GridGeometryAdapter {
try {
crs = CRS.parseWKT(v.CRS);
} catch (Exception e) {
crs = null;
crs = McidasCRSBuilder.constructCRSfromWKT(v.CRS);
}
if (crs == null) {

View file

@ -17,6 +17,7 @@ package gov.noaa.nws.ncep.viz.common.ui;
* ------------ ---------- ----------- --------------------------
* Nov 3,2010 324 X. Guo Initial Creation
* Dec 6,2010 X. Guo Change clean up function
* Apr22,2014 1129 B. Hebbard Move maxHi/maxLo from here to GridRelativeHiLoDisplay so can handle relative to current extent
*
* </pre>
*
@ -25,6 +26,7 @@ package gov.noaa.nws.ncep.viz.common.ui;
*/
public class HILORelativeMinAndMaxLocator {
// Grid point values array
protected float[] grid;
@ -40,12 +42,6 @@ public class HILORelativeMinAndMaxLocator {
// Search Interpolation
private boolean gridInterp;
// Maximum number of highs
private int gridMaxHi;
// Maximum number of lows
private int gridMaxLo;
// Lower bound on maximum
private float gridLowerMax;
@ -119,8 +115,8 @@ public class HILORelativeMinAndMaxLocator {
// HILO Min/Max locator construct
public HILORelativeMinAndMaxLocator(float[] gridData, int col, int row,
int radius, boolean interp, int maxHi, int maxLo, float maxLowerBd,
float maxUpperBd, float minLowerBd, float minUpperBd) {
int radius, boolean interp, float maxLowerBd, float maxUpperBd,
float minLowerBd, float minUpperBd) {
isHiLoRelativeMinAndMaxLocated = false;
grid = gridData;
@ -130,8 +126,6 @@ public class HILORelativeMinAndMaxLocator {
if ((isHiLoRelativeMinAndMaxLocated = checkGridValues())) {
setGridRadius(radius);
gridInterp = interp;
gridMaxHi = maxHi;
gridMaxLo = maxLo;
gridLowerMax = maxLowerBd;
gridUpperMax = maxUpperBd;
gridLowerMin = minLowerBd;
@ -153,10 +147,10 @@ public class HILORelativeMinAndMaxLocator {
}
/**
* 9999 Find the extrema
* Find the extrema
*/
private boolean findExtrema() {
int mm, nextr;
int mm;
float rmin, rmax;
xExtr = new float[GRID_MXM];
yExtr = new float[GRID_MXM];
@ -166,30 +160,27 @@ public class HILORelativeMinAndMaxLocator {
if (mm == 0) {
rmin = gridLowerMin;
rmax = gridUpperMin;
nextr = gridMaxLo;
} else {
rmin = gridLowerMax;
rmax = gridUpperMax;
nextr = gridMaxHi;
}
chkGribPoint(mm, rmin, rmax);
// Sort extrema
sortExtrema(mm);
clusterLocator();
int ifinct = Math.min(numOfExtr, nextr);
if (mm == 0) {
loadMinGridValues(ifinct);
loadMinGridValues();
} else {
loadMaxGridValues(ifinct);
loadMaxGridValues();
}
}
return true;
}
/**
* Check each point and see if it is present and visible
* Check each point and see if it is present
*/
private void chkGribPoint(int mm, float min, float max) {
int i, j, cidx, cidx1, ii, jj;
@ -201,7 +192,8 @@ public class HILORelativeMinAndMaxLocator {
for (j = gridRadius + 1; j <= gridRow - gridRadius; j++) {
for (i = gridRadius + 1; i <= gridCol - gridRadius; i++) {
cidx = (j - 1) * gridCol + i - 1;
// Check the grid point is present and visible
// Check the grid point is present. (No visibility check
// possible at this stage.)
if (!checkGridMissingValues(grid[cidx])) {
ok = true;
alleq = true;
@ -293,11 +285,11 @@ public class HILORelativeMinAndMaxLocator {
/**
* Load minimum grid values
*/
private void loadMinGridValues(int ifinct) {
dgMinCol = new float[ifinct];
dgMinRow = new float[ifinct];
dgMinVal = new float[ifinct];
for (int k = 0; k < ifinct; k++) {
private void loadMinGridValues() {
dgMinCol = new float[numOfExtr];
dgMinRow = new float[numOfExtr];
dgMinVal = new float[numOfExtr];
for (int k = 0; k < numOfExtr; k++) {
dgMinCol[k] = xExtr[k];
dgMinRow[k] = yExtr[k];
dgMinVal[k] = vExtr[k];
@ -307,11 +299,11 @@ public class HILORelativeMinAndMaxLocator {
/**
* Load maximum grid values
*/
private void loadMaxGridValues(int ifinct) {
dgMaxCol = new float[ifinct];
dgMaxRow = new float[ifinct];
dgMaxVal = new float[ifinct];
for (int k = 0; k < ifinct; k++) {
private void loadMaxGridValues() {
dgMaxCol = new float[numOfExtr];
dgMaxRow = new float[numOfExtr];
dgMaxVal = new float[numOfExtr];
for (int k = 0; k < numOfExtr; k++) {
dgMaxCol[k] = xExtr[k];
dgMaxRow[k] = yExtr[k];
dgMaxVal[k] = vExtr[k];
@ -616,8 +608,6 @@ public class HILORelativeMinAndMaxLocator {
+ gridRow);
System.out.println(" Radius:" + gridRadius + " interp:"
+ gridInterp);
System.out.println(" Max number of highs:" + gridMaxHi
+ " Max number of lows:" + gridMaxLo);
System.out.println(" Lower Bound on Max:" + gridLowerMax
+ " Upper Bound on Max:" + gridUpperMax);
System.out.println(" Lower Bound on Min:" + gridLowerMin

View file

@ -8,11 +8,6 @@ Eclipse-RegisterBuddy: gov.noaa.nws.ncep.viz.resources, org.apache.velocity, com
Eclipse-BuddyPolicy: ext, global
Require-Bundle: org.eclipse.ui,
org.eclipse.core.runtime,
com.raytheon.viz.pointdata;bundle-version="1.11.17",
org.geotools;bundle-version="2.5.2",
javax.measure;bundle-version="1.0.0",
com.raytheon.uf.common.colormap;bundle-version="1.11.17",
com.raytheon.uf.viz.core;bundle-version="1.11.17",
com.raytheon.viz.core;bundle-version="1.11.17",
gov.noaa.nws.ncep.ui.pgen;bundle-version="1.0.0",
gov.noaa.nws.ncep.viz.resources,
@ -23,11 +18,7 @@ Require-Bundle: org.eclipse.ui,
gov.noaa.nws.ncep.edex.common;bundle-version="1.0.0",
com.raytheon.viz.ui;bundle-version="1.11.22",
gov.noaa.nws.ncep.viz.ui.display;bundle-version="1.0.0",
gov.noaa.nws.ncep.viz.localization;bundle-version="1.0.0",
com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0",
com.raytheon.uf.common.gridcoverage;bundle-version="1.0.0",
com.raytheon.uf.common.serialization,
com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1161",
gov.noaa.nws.ncep.common.log;bundle-version="1.0.0",
gov.noaa.nws.ncep.viz.gempak;bundle-version="1.0.0",
gov.noaa.nws.ncep.viz.gempak.nativelib;bundle-version="1.0.0",
@ -39,14 +30,9 @@ Export-Package: gov.noaa.nws.ncep.viz.rsc.ncgrid,
gov.noaa.nws.ncep.viz.rsc.ncgrid.contours,
gov.noaa.nws.ncep.viz.rsc.ncgrid.rsc
Import-Package: com.raytheon.uf.common.comm,
com.raytheon.uf.common.dataplugin.level,
com.raytheon.uf.common.pointdata,
com.raytheon.viz.core.contours.util,
com.raytheon.viz.grid.inv,
com.sun.jna,
com.sun.jna.ptr,
gov.noaa.nws.ncep.common.log.logger,
gov.noaa.nws.ncep.common.tools,
gov.noaa.nws.ncep.viz.gempak.grid.inv,
gov.noaa.nws.ncep.viz.gempak.grid.mapper,
gov.noaa.nws.ncep.viz.gempak.grid.units

View file

@ -2,203 +2,218 @@ package gov.noaa.nws.ncep.viz.rsc.ncgrid.contours;
public class ContourAttributes {
private String glevel;
private String gvcord;
private String skip;
private String filter;
private String scale;
private String gdpfun;
private String type;
private String cint;
private String line;
private String fint;
private String fline;
private String hilo;
private String hlsym;
private String wind;
private String marker;
private String clrbar;
private String text;
private String glevel;
public String getGlevel() {
return glevel;
}
private String gvcord;
public void setGlevel(String glevel) {
this.glevel = glevel;
}
private String skip;
public String getGvcord() {
return gvcord;
}
private String filter;
public void setGvcord(String gvcord) {
this.gvcord = gvcord;
}
private String scale;
public String getSkip() {
return skip;
}
private String gdpfun;
public void setSkip(String skip) {
this.skip = skip;
}
private String type;
public String getFilter() {
return filter;
}
private String cint;
public void setFilter(String filter) {
this.filter = filter;
}
private String line;
public String getScale() {
return scale;
}
private String fint;
public void setScale(String scale) {
this.scale = scale;
}
private String fline;
public String getGdpfun() {
return gdpfun;
}
private String hilo;
public void setGdpfun(String gdpfun) {
this.gdpfun = gdpfun;
}
private String hlsym;
public String getType() {
return type;
}
private String wind;
public void setType(String type) {
this.type = type;
}
private String marker;
public String getCint() {
return cint;
}
private String clrbar;
public void setCint(String cint) {
this.cint = cint;
}
private String text;
public String getLine() {
return line;
}
private String colors;
public void setLine(String line) {
this.line = line;
}
public String getGlevel() {
return glevel;
}
public String getFint() {
return fint;
}
public void setGlevel(String glevel) {
this.glevel = glevel;
}
public void setFint(String fint) {
this.fint = fint;
}
public String getGvcord() {
return gvcord;
}
public String getFline() {
return fline;
}
public void setGvcord(String gvcord) {
this.gvcord = gvcord;
}
public void setFline(String fline) {
this.fline = fline;
}
public String getSkip() {
return skip;
}
public String getHilo() {
return hilo;
}
public void setSkip(String skip) {
this.skip = skip;
}
public void setHilo(String hilo) {
this.hilo = hilo;
}
public String getFilter() {
return filter;
}
public String getHlsym() {
return hlsym;
}
public void setFilter(String filter) {
this.filter = filter;
}
public void setHlsym(String hlsym) {
this.hlsym = hlsym;
}
public String getScale() {
return scale;
}
public String getWind() {
return wind;
}
public void setScale(String scale) {
this.scale = scale;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getGdpfun() {
return gdpfun;
}
public String getMarker() {
return marker;
}
public void setGdpfun(String gdpfun) {
this.gdpfun = gdpfun;
}
public void setMarker(String marker) {
this.marker = marker;
}
/**
* @return the clrbar
*/
public final String getClrbar() {
return clrbar;
}
public String getType() {
return type;
}
/**
* @param clrbar the clrbar to set
*/
public final void setClrbar(String clrbar) {
this.clrbar = clrbar;
}
public String getText() {
return text;
}
public void setType(String type) {
this.type = type;
}
public void setText(String text) {
this.text = text;
}
public String getCint() {
return cint;
}
public boolean isMatch ( ContourAttributes attr) {
boolean match = false;
if ( this.glevel.trim().equalsIgnoreCase(attr.getGlevel())&&
this.gvcord.trim().equalsIgnoreCase(attr.getGvcord()) &&
this.skip.trim().equalsIgnoreCase(attr.getSkip()) &&
this.filter.trim().equalsIgnoreCase(attr.getFilter()) &&
this.scale.trim().equalsIgnoreCase(attr.getScale()) &&
this.gdpfun.trim().equalsIgnoreCase(attr.getGdpfun()) &&
this.type.trim().equalsIgnoreCase(attr.getType())&&
this.cint.trim().equalsIgnoreCase(attr.getCint()) &&
this.line.trim().equalsIgnoreCase(attr.getLine()) &&
this.fint.trim().equalsIgnoreCase(attr.getFint()) &&
this.fline.trim().equalsIgnoreCase(attr.getFline()) &&
this.hilo.trim().equalsIgnoreCase(attr.getHilo()) &&
this.hlsym.trim().equalsIgnoreCase(attr.getHlsym()) &&
this.wind.trim().equalsIgnoreCase(attr.getWind()) &&
this.marker.trim().equalsIgnoreCase(attr.getMarker()) &&
this.clrbar.trim().equalsIgnoreCase(attr.getClrbar()) &&
this.text.trim().equalsIgnoreCase(attr.getText())) {
match = true;
}
return match;
}
public void setCint(String cint) {
this.cint = cint;
}
public String getLine() {
return line;
}
public void setLine(String line) {
this.line = line;
}
public String getFint() {
return fint;
}
public void setFint(String fint) {
this.fint = fint;
}
public String getFline() {
return fline;
}
public void setFline(String fline) {
this.fline = fline;
}
public String getHilo() {
return hilo;
}
public void setHilo(String hilo) {
this.hilo = hilo;
}
public String getHlsym() {
return hlsym;
}
public void setHlsym(String hlsym) {
this.hlsym = hlsym;
}
public String getWind() {
return wind;
}
public void setWind(String wind) {
this.wind = wind;
}
public String getMarker() {
return marker;
}
public void setMarker(String marker) {
this.marker = marker;
}
/**
* @return the clrbar
*/
public final String getClrbar() {
return clrbar;
}
/**
* @param clrbar
* the clrbar to set
*/
public final void setClrbar(String clrbar) {
this.clrbar = clrbar;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
/**
* @param colors
*/
public String getColors() {
return colors;
}
public void setColors(String colors) {
this.colors = colors;
}
public boolean isMatch(ContourAttributes attr) {
boolean match = false;
if (this.glevel.trim().equalsIgnoreCase(attr.getGlevel())
&& this.gvcord.trim().equalsIgnoreCase(attr.getGvcord())
&& this.skip.trim().equalsIgnoreCase(attr.getSkip())
&& this.filter.trim().equalsIgnoreCase(attr.getFilter())
&& this.scale.trim().equalsIgnoreCase(attr.getScale())
&& this.gdpfun.trim().equalsIgnoreCase(attr.getGdpfun())
&& this.type.trim().equalsIgnoreCase(attr.getType())
&& this.cint.trim().equalsIgnoreCase(attr.getCint())
&& this.line.trim().equalsIgnoreCase(attr.getLine())
&& this.fint.trim().equalsIgnoreCase(attr.getFint())
&& this.fline.trim().equalsIgnoreCase(attr.getFline())
&& this.hilo.trim().equalsIgnoreCase(attr.getHilo())
&& this.hlsym.trim().equalsIgnoreCase(attr.getHlsym())
&& this.wind.trim().equalsIgnoreCase(attr.getWind())
&& this.marker.trim().equalsIgnoreCase(attr.getMarker())
&& this.clrbar.trim().equalsIgnoreCase(attr.getClrbar())
&& this.text.trim().equalsIgnoreCase(attr.getText())
&& this.colors.trim().equalsIgnoreCase(attr.getColors())) {
match = true;
}
return match;
}
}

View file

@ -129,6 +129,8 @@ import com.vividsolutions.jts.linearref.LocationIndexedLine;
* Sep 17, 2013 #1036 S. Gurung Added TEXT attribute related changes to create labels with various parameters
* Oct 30, 2013 #1045 S. Gurung Fix for FINT/FLINE parsing issues
* Aug 27, 2013 2262 bsteffen Convert to use new StrmPak.
* Apr 23, 2014 #856 pswamy Missing color fill in grid diagnostics.
* Apr 30, 2014 862 pswamy Grid Precipitable Water Contour Labels needs two decimal points
*
* </pre>
*
@ -619,7 +621,7 @@ public class ContourSupport {
}
}
DecimalFormat df = new DecimalFormat("0.#");
DecimalFormat df = new DecimalFormat("0.##");
double[] loc = { 0.0, 0.0 };
if (actualLength > 0) {
@ -1154,10 +1156,17 @@ public class ContourSupport {
if (!(fint.equalsIgnoreCase(cint))) {
fvalues = FINT.parseFINT(fint, zoomLevelIndex,
cntrData.minValue, cntrData.getMaxValue());
} else if (contourGroup.cvalues != null) {
fvalues = contourGroup.cvalues;
} else {
if ((contourGroup.cvalues != null)
&& (contourGroup.cvalues.size() != 0)) {
fvalues = contourGroup.cvalues;
} else {
fvalues = FINT.parseFINT(fint, zoomLevelIndex,
cntrData.minValue, cntrData.getMaxValue());
}
}
}
if (contourGroup.fvalues.size() == 0 && fvalues != null) {
contourGroup.fvalues.addAll(fvalues);
} else if (contourGroup.fvalues.size() > 0) {

View file

@ -19,6 +19,8 @@
******************************************************************************************/
package gov.noaa.nws.ncep.viz.rsc.ncgrid.contours;
import gov.noaa.nws.ncep.common.tools.IDecoderConstantsN;
import java.nio.FloatBuffer;
import org.eclipse.swt.graphics.RGB;
@ -42,8 +44,6 @@ import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.map.IMapDescriptor;
import com.vividsolutions.jts.geom.Coordinate;
import gov.noaa.nws.ncep.common.tools.IDecoderConstantsN;
/**
* Display grid point values
*
@ -55,6 +55,7 @@ import gov.noaa.nws.ncep.common.tools.IDecoderConstantsN;
* June, 2010 164 M. Li Initial creation
* October,2011 X. Guo Display grid point in GRID_CENTER
* Apr, 2013 B. Yin Don't plot missing values
* 02/04/2014 936 T. Lee Implemented textSize
*
* </pre>
*
@ -72,11 +73,13 @@ public class GridPointValueDisplay implements IRenderable {
private RGB color;
private int textSize;
private FloatBuffer displayValues;
private IFont font;
public GridPointValueDisplay(FloatBuffer values, RGB color,
public GridPointValueDisplay(FloatBuffer values, RGB color, int textSize,
IMapDescriptor descriptor, ISpatialObject gridLocation) {
this.displayValues = values;
@ -84,6 +87,7 @@ public class GridPointValueDisplay implements IRenderable {
this.gridGeometryOfGrid = MapUtil.getGridGeometry(gridLocation);
this.gridDims = new int[] { gridLocation.getNx(), gridLocation.getNy() };
this.color = color;
this.textSize = textSize;
}
/*
@ -100,7 +104,8 @@ public class GridPointValueDisplay implements IRenderable {
if (paintProps.isZooming()) {
return;
}
font = target.initializeFont("Monospace", 10,
font = target.initializeFont("Monospace", textSize,
new IFont.Style[] { IFont.Style.BOLD });
IExtent screenExtentInPixels = paintProps.getView().getExtent();
@ -122,8 +127,9 @@ public class GridPointValueDisplay implements IRenderable {
for (int i = 0; i < gridDims[0]; i += interv + 1) {
for (int j = 0; j < gridDims[1]; j += interv + 1) {
if (displayValues.get((i + (j * this.gridDims[0])) ) == IDecoderConstantsN.GRID_MISSING) continue;
if (displayValues.get((i + (j * this.gridDims[0]))) == IDecoderConstantsN.GRID_MISSING)
continue;
ReferencedCoordinate c = new ReferencedCoordinate(
new Coordinate(i, j), this.gridGeometryOfGrid,
Type.GRID_CENTER);

View file

@ -20,10 +20,12 @@ import com.raytheon.uf.common.geospatial.ISpatialObject;
import com.raytheon.uf.common.geospatial.MapUtil;
import com.raytheon.uf.common.geospatial.ReferencedCoordinate;
import com.raytheon.uf.common.geospatial.ReferencedObject.Type;
import com.raytheon.uf.viz.core.IExtent;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.IGraphicsTarget.HorizontalAlignment;
import com.raytheon.uf.viz.core.IGraphicsTarget.TextStyle;
import com.raytheon.uf.viz.core.IGraphicsTarget.VerticalAlignment;
import com.raytheon.uf.viz.core.PixelExtent;
import com.raytheon.uf.viz.core.drawables.IFont;
import com.raytheon.uf.viz.core.drawables.IRenderable;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
@ -40,7 +42,8 @@ import com.vividsolutions.jts.geom.Coordinate;
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Nov 24, 2010 363 X. Guo Initial creation
* Aut 17, 2012 655 B. Hebbard Added paintProps as parameter to IDisplayable draw (2)
* Aug 17, 2012 655 B. Hebbard Added paintProps as parameter to IDisplayable draw (2)
* Apr 22, 2014 1129 B. Hebbard Handle maxHi/maxLo here (instead of HILORelativeMinAndMaxLocator) to make extent-sensitive
*
* </pre>
*
@ -58,6 +61,12 @@ public class GridRelativeHiLoDisplay implements IRenderable {
private HILORelativeMinAndMaxLocator hiloLocator;
// Maximum number of highs to display
private int maxHi;
// Maximum number of lows to display
private int maxLo;
private TextStringParser textMarkerString;
private TextStringParser textValueString;
@ -66,7 +75,7 @@ public class GridRelativeHiLoDisplay implements IRenderable {
private SymbolLocationSet gridPointLoSymbolSet = null;
// Hi/L symbol overtical/horizontal offset parameters
// Hi/Lo symbol vertical/horizontal offset parameters
private double symbolHiHight = 0.0;
private double symbolLoHight = 0.0;
@ -74,24 +83,26 @@ public class GridRelativeHiLoDisplay implements IRenderable {
private int charPix = 4;
private double vertRatio;
private double xOffset = 0;
Rectangle2D charSize;
public GridRelativeHiLoDisplay(HILOBuilder hiloBuild,
HILORelativeMinAndMaxLocator hiloLocator,
HILORelativeMinAndMaxLocator hiloLocator, int maxHi, int maxLo,
TextStringParser markerStr, TextStringParser valueStr,
IMapDescriptor descriptor, ISpatialObject gridLocation) {
this.descriptor = descriptor;
this.gridGeometryOfGrid = MapUtil.getGridGeometry(gridLocation);
this.hiloBuild = hiloBuild;
this.hiloLocator = hiloLocator;
this.maxHi = maxHi;
this.maxLo = maxLo;
this.textMarkerString = markerStr;
this.textValueString = valueStr;
if (ContourSupport.getCentralMeridian(descriptor) == 0.0){
xOffset = 360.;
}
if (ContourSupport.getCentralMeridian(descriptor) == 0.0) {
xOffset = 360.;
}
initHiLoSymbolSet();
// display ();
}
@ -137,7 +148,7 @@ public class GridRelativeHiLoDisplay implements IRenderable {
}
if (hiloBuild.getSymbolHiPlotValue()) {
plotGridHiValue(target);
plotGridHiValue(target, paintProps);
}
}
@ -161,7 +172,7 @@ public class GridRelativeHiLoDisplay implements IRenderable {
}
if (hiloBuild.getSymbolLoPlotValue()) {
plotGridLoValue(target);
plotGridLoValue(target, paintProps);
}
}
@ -182,8 +193,10 @@ public class GridRelativeHiLoDisplay implements IRenderable {
new IFont.Style[] { IFont.Style.BOLD });
charSize = target.getStringBounds(font, "N");
symbolHiHight = charSize.getHeight() * charPix;
PixelExtent correctedExtent = getCorrectedExtent(paintProps);
for (int i = 0; i < tmp1.length; i++) {
int pointsPlotted = 0;
for (int i = 0; i < tmp1.length && pointsPlotted < maxHi; i++) {
ReferencedCoordinate c = new ReferencedCoordinate(
new Coordinate((double) tmp1[i] - 1,
@ -191,13 +204,17 @@ public class GridRelativeHiLoDisplay implements IRenderable {
Type.GRID_CENTER);
try {
double[] d = this.descriptor.worldToPixel(new double[] {
(double) c.asLatLon().x > 180 ? c.asLatLon().x - xOffset: c.asLatLon().x,
(double) c.asLatLon().x > 180 ? c.asLatLon().x
- xOffset : c.asLatLon().x,
(double) c.asLatLon().y });
target.drawString(font, text, d[0], d[1], 0.0,
TextStyle.NORMAL, hiloBuild.getColorHi(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
if (correctedExtent.contains(d[0], d[1])) {
target.drawString(font, text, d[0], d[1], 0.0,
TextStyle.NORMAL, hiloBuild.getColorHi(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
pointsPlotted++;
}
} catch (TransformException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@ -226,23 +243,29 @@ public class GridRelativeHiLoDisplay implements IRenderable {
new IFont.Style[] { IFont.Style.BOLD });
charSize = target.getStringBounds(font, "N");
symbolLoHight = charSize.getHeight() * charPix;
PixelExtent correctedExtent = getCorrectedExtent(paintProps);
for (int i = 0; i < tmp1.length; i++) {
int pointsPlotted = 0;
for (int i = 0; i < tmp1.length && pointsPlotted < maxLo; i++) {
ReferencedCoordinate c = new ReferencedCoordinate(
new Coordinate((double) tmp1[i] - 1,
(double) tmp2[i] - 1), this.gridGeometryOfGrid,
Type.GRID_CENTER);
try {
double[] d = this.descriptor.worldToPixel(new double[] {
(double) c.asLatLon().x > 180 ? c.asLatLon().x - xOffset: c.asLatLon().x,
(double) c.asLatLon().y });
// System.out.println("Low longitude: " + c.asLatLon().x );
target.drawString(font, text, d[0], d[1], 0.0,
TextStyle.NORMAL, hiloBuild.getColorLo(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
(double) c.asLatLon().x > 180 ? c.asLatLon().x
- xOffset : c.asLatLon().x,
(double) c.asLatLon().y });
// System.out.println("Low longitude: " + c.asLatLon().x );
if (correctedExtent.contains(d[0], d[1])) {
target.drawString(font, text, d[0], d[1], 0.0,
TextStyle.NORMAL, hiloBuild.getColorLo(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
pointsPlotted++;
}
} catch (TransformException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@ -256,8 +279,11 @@ public class GridRelativeHiLoDisplay implements IRenderable {
/**
* Plot High grid values
*
* @param paintProps
*/
private void plotGridHiValue(IGraphicsTarget target) throws VizException {
private void plotGridHiValue(IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
float[] tmp1 = hiloLocator.getMaxColPositions();
if (tmp1.length > 0) {
@ -273,7 +299,10 @@ public class GridRelativeHiLoDisplay implements IRenderable {
// offY += charSize.getHeight()*charPix;
offY = charSize.getHeight() * vertRatio;
}
for (int i = 0; i < tmp1.length; i++) {
PixelExtent correctedExtent = getCorrectedExtent(paintProps);
int pointsPlotted = 0;
for (int i = 0; i < tmp1.length && pointsPlotted < maxHi; i++) {
String text = convertFloat2String(tmp3[i],
hiloBuild.getSymbolHiNumOfDecPls());
@ -283,13 +312,16 @@ public class GridRelativeHiLoDisplay implements IRenderable {
Type.GRID_CENTER);
try {
double[] d = this.descriptor.worldToPixel(new double[] {
(double) c.asLatLon().x > 180 ? c.asLatLon().x - xOffset: c.asLatLon().x,
(double) c.asLatLon().x > 180 ? c.asLatLon().x
- xOffset : c.asLatLon().x,
(double) c.asLatLon().y });
target.drawString(font, text, d[0], d[1] + offY, 0.0,
TextStyle.NORMAL, hiloBuild.getColorHi(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
if (correctedExtent.contains(d[0], d[1])) {
target.drawString(font, text, d[0], d[1] + offY, 0.0,
TextStyle.NORMAL, hiloBuild.getColorHi(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
pointsPlotted++;
}
} catch (TransformException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@ -303,8 +335,11 @@ public class GridRelativeHiLoDisplay implements IRenderable {
/**
* Plot Low grid values
*
* @param paintProps
*/
private void plotGridLoValue(IGraphicsTarget target) throws VizException {
private void plotGridLoValue(IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
float[] tmp1 = hiloLocator.getMinColPositions();
if (tmp1.length > 0) {
@ -320,7 +355,10 @@ public class GridRelativeHiLoDisplay implements IRenderable {
charSize = target.getStringBounds(font, "N");
offY = charSize.getHeight() * vertRatio;
}
for (int i = 0; i < tmp1.length; i++) {
PixelExtent correctedExtent = getCorrectedExtent(paintProps);
int pointsPlotted = 0;
for (int i = 0; i < tmp1.length && pointsPlotted < maxLo; i++) {
String text = convertFloat2String(tmp3[i],
hiloBuild.getSymbolLoNumOfDecPls());
@ -330,13 +368,16 @@ public class GridRelativeHiLoDisplay implements IRenderable {
Type.GRID_CENTER);
try {
double[] d = this.descriptor.worldToPixel(new double[] {
(double) c.asLatLon().x > 180 ? c.asLatLon().x - xOffset: c.asLatLon().x,
(double) c.asLatLon().x > 180 ? c.asLatLon().x
- xOffset : c.asLatLon().x,
(double) c.asLatLon().y });
target.drawString(font, text, d[0], d[1] + offY, 0.0,
TextStyle.NORMAL, hiloBuild.getColorLo(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
if (correctedExtent.contains(d[0], d[1])) {
target.drawString(font, text, d[0], d[1] + offY, 0.0,
TextStyle.NORMAL, hiloBuild.getColorLo(),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
pointsPlotted++;
}
} catch (TransformException e) {
// TODO Auto-generated catch block
e.printStackTrace();
@ -348,6 +389,26 @@ public class GridRelativeHiLoDisplay implements IRenderable {
}
}
private PixelExtent getCorrectedExtent(PaintProperties paintProps) {
// Get view extent, for clipping purposes
IExtent extent = paintProps.getView().getExtent();
double extentMaxX = (extent.getMaxX() < 0 ? 0 : extent.getMaxX());
double extentMinX = (extent.getMinX() < 0 ? 0 : extent.getMinX());
double extentMaxY = (extent.getMaxY() < 0 ? 0 : extent.getMaxY());
double extentMinY = (extent.getMinY() < 0 ? 0 : extent.getMinY());
extentMaxX = (extentMaxX > 19999 ? 19999 : extentMaxX);
extentMinX = (extentMinX > 19999 ? 19999 : extentMinX);
extentMaxY = (extentMaxY > 9999 ? 9999 : extentMaxY);
extentMinY = (extentMinY > 9999 ? 9999 : extentMinY);
PixelExtent correctedExtent = new PixelExtent(extentMinX, extentMaxX,
extentMinY, extentMaxY);
return correctedExtent;
}
/**
* Initialize Hi/Lo Symbol set
*/
@ -539,6 +600,8 @@ public class GridRelativeHiLoDisplay implements IRenderable {
+ ((hiloBuild.getSymbolHiPlotValue()) ? "T" : "F"));
System.out.println(" precision\t\t"
+ hiloBuild.getSymbolHiNumOfDecPls());
System.out.println(" Limit number of visible maxima to display:"
+ maxHi);
float[] tmp = hiloLocator.getMaxColPositions();
if (tmp.length > 0) {
System.out.println(" Number of maxima found:" + tmp.length);
@ -581,6 +644,8 @@ public class GridRelativeHiLoDisplay implements IRenderable {
+ ((hiloBuild.getSymbolLoPlotValue()) ? "T" : "F"));
System.out.println(" precision\t\t"
+ hiloBuild.getSymbolLoNumOfDecPls());
System.out.println(" Limit number of visible minima to display:"
+ maxLo);
tmp = hiloLocator.getMinColPositions();
if (tmp.length > 0) {
System.out.println(" Number of minima found:" + tmp.length);
@ -628,10 +693,10 @@ public class GridRelativeHiLoDisplay implements IRenderable {
.println("==================================================");
}
public void setDescriptor(IMapDescriptor descriptor) {
this.descriptor = descriptor;
if (ContourSupport.getCentralMeridian(descriptor) == 0.0){
xOffset = 360.;
}
}
public void setDescriptor(IMapDescriptor descriptor) {
this.descriptor = descriptor;
if (ContourSupport.getCentralMeridian(descriptor) == 0.0) {
xOffset = 360.;
}
}
}

View file

@ -146,9 +146,10 @@ public class GriddedVectorDisplay extends AbstractGriddedDisplay<Coordinate> {
lineWidth = 1;
String windAttr = attrs.getWind();
if (windAttr != null && !windAttr.isEmpty()) {
if (windAttr.contains("bk")) {
windAttr = windAttr.replace("bk", "");
}
// TTR 880, remove all chars except 0-9,.,/
windAttr = windAttr.replaceAll("[^0-9./]", "");
String[] attr = windAttr.trim().split("/");
colorIndex = Integer.parseInt(attr[0].trim());
if (attr.length >= 2 && !attr[1].trim().isEmpty()) {

View file

@ -7,7 +7,6 @@ package gov.noaa.nws.ncep.viz.rsc.ncgrid.dgdriv;
import gov.noaa.nws.ncep.common.log.logger.NcepLogger;
import gov.noaa.nws.ncep.common.log.logger.NcepLoggerManager;
import gov.noaa.nws.ncep.edex.common.dataRecords.NcFloatDataRecord;
import gov.noaa.nws.ncep.viz.gempak.grid.inv.NcGridInventory;
import gov.noaa.nws.ncep.viz.gempak.grid.jna.GridDiag;
import gov.noaa.nws.ncep.viz.gempak.grid.jna.GridDiag.gempak;
import gov.noaa.nws.ncep.viz.gempak.grid.units.GempakGridParmInfoLookup;
@ -25,30 +24,28 @@ import gov.noaa.nws.ncep.viz.rsc.ncgrid.rsc.NcgridResourceData;
import java.io.File;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.measure.converter.ConversionException;
import org.geotools.coverage.grid.GridGeometry2D;
import com.raytheon.uf.common.comm.CommunicationException;
import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.grid.dataquery.GridQueryAssembler;
import com.raytheon.uf.common.dataplugin.grid.datastorage.GridDataRetriever;
import com.raytheon.uf.common.dataplugin.level.Level;
import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType;
import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
import com.raytheon.uf.common.datastorage.DataStoreFactory;
import com.raytheon.uf.common.datastorage.IDataStore;
import com.raytheon.uf.common.datastorage.Request;
import com.raytheon.uf.common.datastorage.StorageException;
import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
import com.raytheon.uf.common.datastorage.records.IDataRecord;
import com.raytheon.uf.common.geospatial.ISpatialObject;
import com.raytheon.uf.common.geospatial.util.GridGeometryWrapChecker;
import com.raytheon.uf.common.gridcoverage.Corner;
@ -60,7 +57,6 @@ import com.raytheon.uf.common.gridcoverage.PolarStereoGridCoverage;
import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.common.units.UnitConv;
import com.raytheon.uf.viz.core.comm.Connector;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.requests.ThriftClient;
import com.sun.jna.Native;
@ -122,6 +118,8 @@ import com.sun.jna.ptr.IntByReference;
* 09/26/2012 X. Guo Fixed missing value problems
* 04/26/2013 B. Yin Fixed the world wrap problems
* 11/2013 845 T. Lee Implemented parameter scaling
* 04/11/2014 981 D.Sushon Code cleanup, enforce explicit use of curly-brackets {}
* 04/14/2014 S. Gilbert Remove dataUri from query - cleanup old unused methods.
* </pre>
*
* @author tlee
@ -135,7 +133,7 @@ public class Dgdriv {
private static GridDiag gd;
private String gdfile, gdpfun, gdattim, glevel, gvcord, scale, garea, proj,
private String gdfile, gdpfun, gdattim, glevel, gvcord, scale, garea,
dataSource;
private boolean scalar, arrowVector, flop, flip;
@ -150,8 +148,6 @@ public class Dgdriv {
private ArrayList<DataTime> dataForecastTimes;
private static Connector conn;
private NcgridDataCache cacheData;
private static NcgribLogger ncgribLogger = NcgribLogger.getInstance();;
@ -159,7 +155,7 @@ public class Dgdriv {
public static final int LLMXGD = 1000000; // Max # grid points
/*
* TODO Work around solution - need to find away to set logging level
* TODO Work around solution - need to find a way to set logging level
* programmatically
*/
private static final DecimalFormat forecastHourFormat = new DecimalFormat(
@ -197,7 +193,6 @@ public class Dgdriv {
gvcord = "";
scale = "";
garea = "";
proj = "";
ncgribPreferences = null;
subgSpatialObj = null;
scalar = false;
@ -205,12 +200,6 @@ public class Dgdriv {
flop = true;
flip = true;
dataForecastTimes = new ArrayList<DataTime>();
try {
conn = Connector.getInstance();
} catch (VizException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setResourceData(NcgridResourceData rscData) {
@ -267,10 +256,6 @@ public class Dgdriv {
this.garea = garea.toUpperCase();
}
public void setProj(String proj) {
this.proj = proj;
}
public void setDataSource(String dataSource) {
this.dataSource = dataSource.trim().toUpperCase();
if (this.dataSource.contains("GEMPAK")) {
@ -407,11 +392,15 @@ public class Dgdriv {
@Override
public boolean callback(String msg) {
String sep = "::";
if (!nativeLogging)
if (!nativeLogging) {
return true;
}
int lvl = checkNativeLoggerLevel(msg);
if (lvl > nativeLogLevel)
if (lvl > nativeLogLevel) {
return true;
}
if (msg.contains("|debug")) {
String logMessage = msg.split("\\|")[0] + ":"
+ msg.split(sep)[1];
@ -457,7 +446,6 @@ public class Dgdriv {
float[] rData;
if (gData == null) {
addData = true;
// rData = retrieveData(dataURI);
rData = retrieveDataFromRetriever(dataURI);
if (rData == null) {
errorURI = msg;
@ -492,9 +480,10 @@ public class Dgdriv {
// logger.info ("*****flip grid data*****");
gd.gem.db_returndata(flipData(rData, nx, ny),
datSize);
} else
} else {
gd.gem.db_returndata(checkMissingData(rData),
datSize);
}
} else {
logger.debug("retrieve data size(" + rDataSize
+ ") mismatch with navigation nx=" + nx
@ -555,7 +544,6 @@ public class Dgdriv {
try {
// logger.debug("request datauri for:" + msg );
long t0 = System.currentTimeMillis();
// String dataURI = getDataURI(msg);
String dataURI = getDataURIFromAssembler(msg);
gd.gem.db_returnduri(dataURI);
long t1 = System.currentTimeMillis();
@ -634,7 +622,6 @@ public class Dgdriv {
*/
this.gdfile = getTaggedGdfile();
proces = true;
// System.out.println();
/*
* TODO Work around solution - need to find away to set logging level
@ -718,15 +705,16 @@ public class Dgdriv {
if (!isEns) {
gd.gem.db_wsetevtname_(gdfile.split(":")[1], iret);
}
}
gd.gem.dgc_nfil_(gdfile, "", iret);
if (iret.getValue() != 0) {
gd.gem.erc_wmsg("DG", iret, "", ier);
proces = false;
}
}
long t06 = System.currentTimeMillis();
// System.out.println("dgc_nfil took " + (t06-t05));
logger.debug("dgc_nfil took: " + (t06 - t05));
@ -792,7 +780,9 @@ public class Dgdriv {
* if (proces) { gd.gem.dgc_fixa_ ( garea, proj, gareabuf, prjbuf,
* iret); if ( iret.getValue () != 0 ) { gd.gem.erc_wmsg ("DG", iret,
* "", ier); proces = false; } }
*/long t09 = System.currentTimeMillis();
*/
long t09 = System.currentTimeMillis();
logger.debug("dgc_fixa took: " + (t09 - t09a));
/*
@ -840,6 +830,7 @@ public class Dgdriv {
proces = false;
}
}
logger.debug("kx:" + kx.getValue() + " ky:" + ky.getValue());
float[] ugrid = null;
float[] vgrid = null;
@ -898,8 +889,9 @@ public class Dgdriv {
if (flop) {
// logger.info ("====flop grid data 1=====");
fds.setXdata(flopData(ugrid, igx.getValue(), igy.getValue()));
} else
} else {
fds.setXdata(revertGempakData2CAVE(ugrid));
}
fds.setDimension(2);
fds.setSizes(new long[] { igx.getValue(), igy.getValue() });
fds.setVector(false);
@ -912,8 +904,9 @@ public class Dgdriv {
if (flop) {
// logger.info ("====flop grid data =====");
fds.setYdata(flopData(vgrid, igx.getValue(), igy.getValue()));
} else
} else {
fds.setYdata(revertGempakData2CAVE(vgrid));
}
fds.setDimension(2);
fds.setSizes(new long[] { igx.getValue(), igy.getValue() });
fds.setVector(true);
@ -925,7 +918,6 @@ public class Dgdriv {
long t1 = System.currentTimeMillis();
logger.debug("Scaling took: " + (t1 - t013));
// System.out.println("Scaling took:" + (t1-t013));
// printInfoMessage(t1 - t0);
return fds;
} else {
/*
@ -945,7 +937,6 @@ public class Dgdriv {
}
return null;
}
}
private void prepareGridDTInfo() {
@ -960,7 +951,7 @@ public class Dgdriv {
+ "_db";
}
IntByReference iret = new IntByReference(0);
// System.out.println();
gd.gem.db_seta2dtinfo_(alias, path, template, iret);
}
@ -998,7 +989,7 @@ public class Dgdriv {
if (perturbationNum != null) {
sba.append(":" + perturbationNum);
}
// System.out.println();
sba.append("|");
sbt.append(getEnsembleTemplate(ensName, perturbationNum));
sbt.append("|");
@ -1031,7 +1022,7 @@ public class Dgdriv {
String template = sbt.toString().substring(0,
sbt.toString().length() - 1);
IntByReference iret = new IntByReference(0);
// System.out.println();
logger.debug("prepareEnsembleDTInfo: alias=" + alias + ", path=" + path
+ ",template=" + template);
gd.gem.db_seta2dtinfo_(alias, path, template, iret);
@ -1080,36 +1071,6 @@ public class Dgdriv {
logger.debug("getEnsembleTemplate(" + ensTemplate + ") for(" + ensName
+ "," + perturbationNum + ")");
return ensTemplate;
/*
* StringBuilder query = new StringBuilder();
* query.append("import GempakEnsembleTemplateGenerator\n");
* query.append(
* "query = GempakEnsembleTemplateGenerator.GempakEnsembleTemplateGenerator('grid')\n"
* ); query.append("query.setEnsembleName('" + ensName + "')\n"); if (
* perturbationNum != null ) { //
* query.append("query.setEnsembleEventName('" +
* perturbationNum.toLowerCase() + "')\n");
* query.append("query.setEnsemblePerturbationNumber('" +
* Integer.parseInt(perturbationNum) + "')\n"); }
*
* query.append("return query.execute()\n");
*
* String scriptToRun = query.toString(); long t0 =
* System.currentTimeMillis();
*
* Object[] pdoList; try { pdoList = conn.connect(scriptToRun, null,
* 60000); String ensTemplate = (String) pdoList[0]; long t1 =
* System.currentTimeMillis(); //
* System.out.println("\tgetEnsembleTemplate took: " + (t1-t0));
* logger.info("getEnsembleTemplate("+ ensTemplate +") took: " +
* (t1-t0)); return ensTemplate; } catch (VizException e) { // TODO
* Auto-generated catch block e.printStackTrace(); return null; }
*/
}
private String getEnsTime(String string) {
// TODO Auto-generated method stub
return string;
}
private String getTaggedGdfile() {
@ -1132,7 +1093,7 @@ public class Dgdriv {
this.gdfileOriginal.indexOf("{") + 1,
this.gdfileOriginal.indexOf("}")).split(",");
StringBuilder strb = new StringBuilder();
// System.out.println();
for (int igd = 0; igd < gdfileArray.length; igd++) {
strb.append(tag);
strb.append(gdfileArray[igd]);
@ -1500,89 +1461,12 @@ public class Dgdriv {
return outGridFlopped;
}
private String getEnsTimes() {
String tmp1 = this.gdfile.substring(this.gdfile.indexOf("{") + 1,
this.gdfile.indexOf("}"));
String[] tmp = tmp1.split(",");
String tmp2 = "";
for (String st : tmp) {
String tmp3[] = st.split("\\|");
tmp2 = tmp2 + tmp3[1];
tmp2 = tmp2 + "|";
}
String returnStr = tmp2.substring(0, tmp2.length() - 1);
return returnStr;
}
private void printInfoMessage(long t) {
String gdFile;
if (this.gdfile.startsWith("{") && this.gdfile.endsWith("}")) {
gdFile = this.gdfile.substring(this.gdfile.indexOf("{") + 1,
this.gdfile.indexOf("}"));
} else {
gdFile = this.gdfile;
}
StringBuilder toprint = new StringBuilder();
// System.out.print ( "\nCalculating " + gdFile.toUpperCase() + " ");
toprint.append("Requesting " + gdFile.toUpperCase() + " ");
/*
* if (this.vector) { // System.out.print(this.gvect.toUpperCase());
* toprint.append(this.gvect.toUpperCase()); } else { //
* System.out.print(this.gfunc.toUpperCase());
* toprint.append(this.gfunc.trim().toUpperCase()); }
*/
toprint.append(this.gdpfun.trim().toUpperCase());
// System.out.print ( " ^" + this.gdattim + " @" + this.glevel + " %" +
// this.gvcord.toUpperCase());
// System.out.print (" has taken --> " + t + " ms\n");
// //System.out.println("\nMin: " + resultMin + " Max: " + resultMax
// + "\n");
toprint.append(" ^" + this.gdattim + " @" + this.glevel + " %"
+ this.gvcord.toUpperCase());
toprint.append(" from " + this.dataSource + " took: " + t + " ms\n");
// toprint.append("\nMin: " + resultMin + " Max: " + resultMax +
// "\n");
// System.out.println(toprint.toString());
logger.debug(toprint.toString());
}
private static float[] retrieveData(String dataURI) throws VizException {
long t001 = System.currentTimeMillis();
IDataRecord dr = null;
try {
String fileName = getFilename(dataURI);
String dataset = "Data";
Request request = Request.ALL;
IDataStore ds = DataStoreFactory.getDataStore(new File(fileName));
dr = ds.retrieve("", dataURI + "/" + dataset, request);
// dr = ds.retrieve(dataURI ,dataset, request);
float[] data = (float[]) dr.getDataObject();
long t002 = System.currentTimeMillis();
if (ncgribLogger.enableDiagnosticLogs())
logger.info("***Reading " + dataURI + " from hdf5 took: "
+ (t002 - t001));
// System.out.println("Reading from hdf5 took: " + (t002-t001));
return data;
} catch (Exception e) {
throw new VizException("Error retrieving data for record:"
+ dataURI, e);
}
}
int scale_parm = 1;
private float[] retrieveDataFromRetriever(String dataURI)
throws VizException {
long t001 = System.currentTimeMillis();
IDataRecord dr = null;
// create GridDataRetriever using datauri
// setUnit for parameter
// setWorldWrapColumns (1);
@ -1610,29 +1494,33 @@ public class Dgdriv {
// ignore deserializer exception.use default units
}
long t002 = System.currentTimeMillis();
if (ncgribLogger.enableDiagnosticLogs())
if (ncgribLogger.enableDiagnosticLogs()) {
logger.info("***Initialize GridDataRetriever for " + dataURI
+ " took: " + (t002 - t001));
}
try {
t001 = System.currentTimeMillis();
FloatDataRecord dataRecord = dataRetriever.getDataRecord();
float[] data = dataRecord.getFloatData();
if (isWorldWrap) {
if (ncgribLogger.enableDiagnosticLogs())
if (ncgribLogger.enableDiagnosticLogs()) {
logger.info("===new coverage nx:"
+ dataRetriever.getCoverage().getNx() + " ny:"
+ dataRetriever.getCoverage().getNy());
}
setSubgSpatialObj((ISpatialObject) dataRetriever.getCoverage());
}
t002 = System.currentTimeMillis();
if (ncgribLogger.enableDiagnosticLogs())
if (ncgribLogger.enableDiagnosticLogs()) {
logger.info("***Reading " + dataURI + " from hdf5 took: "
+ (t002 - t001) + ", return size:" + data.length);
}
return data;
} catch (StorageException s) {
if (ncgribLogger.enableDiagnosticLogs())
if (ncgribLogger.enableDiagnosticLogs()) {
logger.info("???? getDataRecord --- throw StorageException");
}
return null;
}
}
@ -1648,14 +1536,14 @@ public class Dgdriv {
String fhrs = tmStr[2].substring(tmStr[2].indexOf("(") + 1,
tmStr[2].indexOf(")"));
String fhStr;
if (fhrs == null)
if (fhrs == null) {
fhStr = "000";
else {
} else {
int number = 0;
try {
number = Integer.parseInt(fhrs);
} catch (NumberFormatException e) {
//
}
fhStr = forecastHourFormat.format(number);
}
@ -1681,8 +1569,9 @@ public class Dgdriv {
// + File.separator + sb.toString());
// }
if (file != null)
if (file != null) {
filename = file.getAbsolutePath();
}
return filename;
}
@ -1913,16 +1802,21 @@ public class Dgdriv {
private String executeScript(String scriptToRun) throws VizException {
if (scriptToRun == null)
if (scriptToRun == null) {
return null;
}
logger.debug("executeScript: scriptToRun=" + scriptToRun);
String[] parms = scriptToRun.split("\\|");
if (parms.length < 4)
if (parms.length < 4) {
return null;
}
String modelName = parms[0];
String dbTag = parms[1];
String eventName = parms[2];
String tmStr = constructTimeStr(parms[3]);
// String tmStr = constructTimeStr(parms[3]);
DataTime dtime = constructDataTime(parms[3]);
// logger.info("executeScript:modelname=" + modelName + " dbTag=" +dbTag
// + " eventName="+eventName + " time=" + tmStr);
@ -1935,15 +1829,17 @@ public class Dgdriv {
rcMap.put(GridDBConstants.ENSEMBLE_ID_QUERY, new RequestConstraint(
eventName, ConstraintType.EQUALS));
}
rcMap.put(GridDBConstants.DATA_URI_QUERY, new RequestConstraint(tmStr,
ConstraintType.LIKE));
rcMap.put(GridDBConstants.DATA_TIME_QUERY,
new RequestConstraint(dtime.getURIString(),
ConstraintType.EQUALS));
DbQueryRequest request = new DbQueryRequest();
request.addRequestField(GridDBConstants.REF_TIME_QUERY);
request.addRequestField(GridDBConstants.FORECAST_TIME_QUERY);
request.setDistinct(true);
request.setConstraints(rcMap);
long t0 = System.currentTimeMillis();
String retFileNames = "";
try {
DbQueryResponse response = (DbQueryResponse) ThriftClient
@ -1956,6 +1852,7 @@ public class Dgdriv {
// empty list to simplify code
responseList = new ArrayList<Map<String, Object>>(0);
}
String prefix = modelName + "_" + dbTag + "_" + eventName + "_";
for (int i = 0; i < responseList.size(); i++) {
Object fhrValue = responseList.get(i).get(
@ -1971,201 +1868,69 @@ public class Dgdriv {
String dt = dts[0].replace("-", "");
String hh = dts[1].split(":")[0];
if (retFileNames.length() > 0)
if (retFileNames.length() > 0) {
retFileNames = retFileNames + "|";
}
retFileNames = retFileNames + prefix + dt + hh + "f"
+ forecastHourFormat.format(fhr);
}
}
} catch (VizException e) {
//
}
return retFileNames;
}
private String constructTimeStr(String gempakTimeStr) {
String gempakTimeStrCycle = gempakTimeStr.split("f")[0];
gempakTimeStrCycle = gempakTimeStrCycle.replace("[0-9]", "%");
if (gempakTimeStrCycle.length() < 10)
return null;
/*
* Convert Gempak time string YYMMDD/HHMMfHHH to DataTime
*/
private DataTime constructDataTime(String gempakTimeStr) {
String gempakTimeStrFFF = gempakTimeStr.split("f")[1];
gempakTimeStrFFF = gempakTimeStrFFF.replace("[0-9]", "%");
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd/HH");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
String[] times = gempakTimeStr.split("f");
DataTime dt;
String timeStr;
try {
int fhr = Integer.parseInt(gempakTimeStrFFF) / 3600;
timeStr = gempakTimeStrCycle.substring(0, 4) + "-"
+ gempakTimeStrCycle.substring(4, 6) + "-"
+ gempakTimeStrCycle.substring(6, 8) + "_"
+ gempakTimeStrCycle.substring(8, 10) + "%_(" + fhr + ")%";
} catch (NumberFormatException e) {
timeStr = gempakTimeStrCycle.substring(0, 4) + "-"
+ gempakTimeStrCycle.substring(4, 6) + "-"
+ gempakTimeStrCycle.substring(6, 8) + "_"
+ gempakTimeStrCycle.substring(8, 10) + "%_("
+ gempakTimeStrFFF;
Date date = sdf.parse(times[0]);
int fhr = Integer.parseInt(times[1]) * 3600;
dt = new DataTime(date, fhr);
} catch (Exception e) {
dt = null;
}
return timeStr;
return dt;
}
private String getDataURI(String parameters) throws VizException {
long t0 = System.currentTimeMillis();
String datauri = cacheData.getDataURI(parameters);
if (datauri != null) {
if (ncgribLogger.enableDiagnosticLogs()) {
long t00 = System.currentTimeMillis();
logger.info("++++ getDataURI for(" + parameters
+ ") from cache took: " + (t00 - t0));
}
return datauri;
}
// get all param/vcord units
// call GridQueryAssembler to get request constrains
String[] parmList = parameters.split("\\|");
logger.debug("enter getDataUri - parameters:" + parameters);
HashMap<String, RequestConstraint> rcMap = new HashMap<String, RequestConstraint>();
rcMap.put(GridDBConstants.PLUGIN_NAME, new RequestConstraint(
GridDBConstants.GRID_TBL_NAME));
rcMap.put(GridDBConstants.MODEL_NAME_QUERY, new RequestConstraint(
parmList[0]));
if (!parmList[1].isEmpty()) {
if (isEnsCategory) {
if (!parmList[1].equalsIgnoreCase("null"))
rcMap.put(GridDBConstants.ENSEMBLE_ID_QUERY,
new RequestConstraint(parmList[1]));
} else {
if (gridRscData.getEnsembelMember() != null) {
rcMap.put(GridDBConstants.ENSEMBLE_ID_QUERY,
new RequestConstraint(parmList[1]));
} else {
rcMap.put(GridDBConstants.EVENT_NAME_QUERY,
new RequestConstraint(parmList[1]));
}
}
}
rcMap.put(GridDBConstants.PARAMETER_QUERY, new RequestConstraint(
parmList[2]));
rcMap.put(GridDBConstants.LEVEL_ID_QUERY, new RequestConstraint(
parmList[3]));
// This is now querying modelInfo.level.levelonevalue (a Double) instead
// of glevel1 (an int)
// so to get the constraint to work we will need ".0"
// TODO : hack until we do this the right way.
//
String ll1 = null, ll2 = null;
if (parmList[4].contains(":")) {
ll1 = parmList[4].split(":")[0];
ll2 = parmList[4].split(":")[1];
} else {
ll1 = parmList[4];
}
if (ll1 == null && ll2 == null)
return null;
if (ll1 != null) {
rcMap.put(GridDBConstants.LEVEL_ONE_QUERY, new RequestConstraint(
ll1 + ".0"));
}
if (ll2 != null) {
rcMap.put(GridDBConstants.LEVEL_TWO_QUERY, new RequestConstraint(
ll2 + ".0"));
}
// request all the params stored in the inventory.
ArrayList<String> rslts = NcGridInventory.getInstance()
.searchNcGridInventory(
rcMap,
NcGridInventory.getInstance().inventoryParamNames
.toArray(new String[0]));// GridDBConstants.LEVEL_TWO_QUERY
// );
long t11 = System.currentTimeMillis();
if (rslts == null || rslts.isEmpty()) {
if (ncgribLogger.enableDiagnosticLogs())
logger.info("???????query NcGridInventory DB return NULL for ("
+ parmList[0] + "," + parmList[1] + "," + parmList[2]
+ "," + parmList[3] + "," + parmList[4] + ")===");
return null;
}
if (ncgribLogger.enableDiagnosticLogs())
logger.info("NcGridInventory.searchNcGridInventory:rslts="
+ rslts.toString() + " took: " + (t11 - t0));
String[] tmpStr = rslts.get(0).split("/");
// HACK: the inventory uses modelInfo.level to store the levels because
// they are in the URI and not glevels
// but the uengin script won't work querying the
// modelInfo.level.leveltwovalue (???) so we have to query
// glevel2 (an int) instead of the double modelInfo.level
String lvl1 = tmpStr[6];
String lvl2 = tmpStr[7];
if (lvl2.equals(Level.getInvalidLevelValueAsString())) {
lvl2 = "-9999.0";
}
String refTimeg = parmList[5].toUpperCase().split("F")[0];
String refTime = GempakGrid.dattimToDbtime(refTimeg);
refTime = refTime.substring(0, refTime.length() - 2);
String fcstTimeg = parmList[5].toUpperCase().split("F")[1];
String fcstTime = Integer
.toString(((Integer.parseInt(fcstTimeg)) * 3600));
rcMap.remove(GridDBConstants.LEVEL_TWO_QUERY);
rcMap.remove(GridDBConstants.LEVEL_ONE_QUERY);
rcMap.put(GridDBConstants.LEVEL_TWO_QUERY, new RequestConstraint(lvl2));
rcMap.put(GridDBConstants.LEVEL_ONE_QUERY, new RequestConstraint(lvl1));
rcMap.put(GridDBConstants.REF_TIME_QUERY,
new RequestConstraint(refTime));
rcMap.put(GridDBConstants.FORECAST_TIME_QUERY, new RequestConstraint(
fcstTime));
DbQueryRequest request = new DbQueryRequest();
request.addRequestField(GridDBConstants.DATA_URI_QUERY);
request.setConstraints(rcMap);
DbQueryResponse response = (DbQueryResponse) ThriftClient
.sendRequest(request);
// extract list of results
List<Map<String, Object>> responseList = null;
if (response != null) {
responseList = response.getResults();
} else {
// empty list to simplify code
responseList = new ArrayList<Map<String, Object>>(0);
}
if (responseList.size() > 0) {
Object dURI = responseList.get(0).get(
GridDBConstants.DATA_URI_QUERY);
if (dURI != null && dURI instanceof String) {
datauri = (String) dURI;
}
}
long t1 = System.currentTimeMillis();
if (ncgribLogger.enableDiagnosticLogs()) {
if (datauri != null)
logger.info("### getDataURI(" + datauri + ") for(" + parameters
+ ") reftime:" + refTime + "("
+ Integer.parseInt(fcstTimeg) + ") took: " + (t1 - t0));
else
logger.info("??? getDataURI(null) for(" + parameters
+ ") reftime:" + refTime + "("
+ Integer.parseInt(fcstTimeg) + ") took: " + (t1 - t0));
}
// datauri = rec.getDataURI();
if (datauri != null)
cacheData.addDataURI(parameters, datauri);
return datauri;
}
// private String constructTimeStr(String gempakTimeStr) {
// String gempakTimeStrCycle = gempakTimeStr.split("f")[0];
// gempakTimeStrCycle = gempakTimeStrCycle.replace("[0-9]", "%");
// if (gempakTimeStrCycle.length() < 10) {
// return null;
// }
//
// String gempakTimeStrFFF = gempakTimeStr.split("f")[1];
// gempakTimeStrFFF = gempakTimeStrFFF.replace("[0-9]", "%");
//
// String timeStr;
// try {
// int fhr = Integer.parseInt(gempakTimeStrFFF) / 3600;
//
// timeStr = gempakTimeStrCycle.substring(0, 4) + "-"
// + gempakTimeStrCycle.substring(4, 6) + "-"
// + gempakTimeStrCycle.substring(6, 8) + "_"
// + gempakTimeStrCycle.substring(8, 10) + "%_(" + fhr + ")%";
// } catch (NumberFormatException e) {
// timeStr = gempakTimeStrCycle.substring(0, 4) + "-"
// + gempakTimeStrCycle.substring(4, 6) + "-"
// + gempakTimeStrCycle.substring(6, 8) + "_"
// + gempakTimeStrCycle.substring(8, 10) + "%_("
// + gempakTimeStrFFF;
// }
// return timeStr;
// }
private String getDataURIFromAssembler(String parameters)
throws VizException {
@ -2186,31 +1951,27 @@ public class Dgdriv {
logger.info("++++ getRequestConstraint for(" + parameters
+ ") took: " + (t01 - t0));
}
if (rcMap == null)
if (rcMap == null) {
return null;
}
t0 = System.currentTimeMillis();
DbQueryRequest request = new DbQueryRequest();
request.addRequestField(GridDBConstants.DATA_URI_QUERY);
// request.addRequestField(GridDBConstants.DATA_URI_QUERY);
request.setConstraints(rcMap);
DbQueryResponse response = (DbQueryResponse) ThriftClient
.sendRequest(request);
// extract list of results
List<Map<String, Object>> responseList = null;
if (response != null) {
responseList = response.getResults();
PluginDataObject[] pdos = response
.getEntityObjects(PluginDataObject.class);
if (pdos.length > 0) {
datauri = pdos[0].getDataURI();
} else {
// empty list to simplify code
responseList = new ArrayList<Map<String, Object>>(0);
}
if (responseList.size() > 0) {
Object dURI = responseList.get(0).get(
GridDBConstants.DATA_URI_QUERY);
if (dURI != null && dURI instanceof String) {
datauri = (String) dURI;
}
datauri = null;
// System.out.println(request);
// System.out.println("NOTHING FOUND!!!!!!!!!!!!!!!!!!!!!!!!");
}
long t1 = System.currentTimeMillis();
if (ncgribLogger.enableDiagnosticLogs()) {
String[] parmList = parameters.split("\\|");
@ -2218,21 +1979,21 @@ public class Dgdriv {
String refTime = GempakGrid.dattimToDbtime(refTimeg);
refTime = refTime.substring(0, refTime.length() - 2);
String fcstTimeg = parmList[5].toUpperCase().split("F")[1];
String fcstTime = Integer
.toString(((Integer.parseInt(fcstTimeg)) * 3600));
if (datauri != null)
if (datauri != null) {
logger.info("### getDataURIFromAssembler(" + datauri + ") for("
+ parameters + ") reftime:" + refTime + "("
+ Integer.parseInt(fcstTimeg) + ") took: " + (t1 - t0));
else
} else {
logger.info("??? getDataURIFromAssembler(null) for("
+ parameters + ") reftime:" + refTime + "("
+ Integer.parseInt(fcstTimeg) + ") took: " + (t1 - t0));
}
}
// datauri = rec.getDataURI();
if (datauri != null)
if (datauri != null) {
cacheData.addDataURI(parameters, datauri);
}
return datauri;
}
@ -2257,8 +2018,10 @@ public class Dgdriv {
StringBuilder sba = new StringBuilder();
String[] gdfileArray = gdfile1.substring(gdfile1.indexOf("{") + 1,
gdfile1.indexOf("}")).split(",");
if (gdfileArray.length == 0)
if (gdfileArray.length == 0) {
return gdfile1;
}
sba.append("{");
for (int igd = 0; igd < gdfileArray.length; igd++) {
if (!gdfileArray[igd].contains(":")) {
@ -2293,8 +2056,9 @@ public class Dgdriv {
if (cnt == members.size()) {
sba.append(String.valueOf(mbrWt + weight
- sumWts));
} else
} else {
sba.append(String.valueOf(mbrWt));
}
sba.append("%");
}
sba.append(model);
@ -2304,8 +2068,9 @@ public class Dgdriv {
sba.append("|");
sba.append(cycleTime);
}
if (cnt < members.size())
if (cnt < members.size()) {
sba.append(",");
}
}
} else {
sba.append(gdfileArray[igd]);
@ -2313,8 +2078,9 @@ public class Dgdriv {
} else {
sba.append(gdfileArray[igd]);
}
if (igd < (gdfileArray.length - 1))
if (igd < (gdfileArray.length - 1)) {
sba.append(",");
}
}
sba.append("}");
return sba.toString();
@ -2346,6 +2112,7 @@ public class Dgdriv {
queryList.put(GridDBConstants.DATA_TIME_QUERY,
new RequestConstraint(dataForecastTimes.get(0).toString()));
}
DbQueryRequest request = new DbQueryRequest();
request.addRequestField(GridDBConstants.NAVIGATION_QUERY);
request.setLimit(1);
@ -2361,6 +2128,7 @@ public class Dgdriv {
// empty list to simplify code
responseList = new ArrayList<Map<String, Object>>(0);
}
ISpatialObject cov = null;
if (responseList.size() > 0) {
Object spatialObj = responseList.get(0).get(
@ -2374,24 +2142,9 @@ public class Dgdriv {
navStr = getGridNavigationContent(cov);
}
} catch (VizException e) {
//
}
/*
* LayerProperty prop = new LayerProperty();
* prop.setDesiredProduct(ResourceType.PLAN_VIEW); try {
* prop.setEntryQueryParameters(queryList, false);
* prop.setNumberOfImages(1);
*
* String script = null; script = ScriptCreator.createScript(prop);
*
* if (script == null) { return null; }
* //System.out.println("HERESMYQUERY: "+script); Object[] pdoList =
* Connector.getInstance().connect(script, null, 60000); if ( pdoList
* !=null && pdoList.length>0 ) { ISpatialObject cov = ((GridRecord)
* pdoList[0]).getLocation(); navStr = getGridNavigationContent ( cov);
* } } catch( VizException e) { return null; }
*/
return navStr;
}
@ -2429,8 +2182,9 @@ public class Dgdriv {
if (!parmList[1].isEmpty()) {
if (isEnsCategory) {
if (!parmList[1].equalsIgnoreCase("null"))
if (!parmList[1].equalsIgnoreCase("null")) {
qAssembler.setEnsembleId(parmList[1]);
}
} else {
if (gridRscData.getEnsembelMember() != null) {
qAssembler.setEnsembleId(parmList[1]);
@ -2450,6 +2204,7 @@ public class Dgdriv {
scale_vcord = (int) Math.pow(10, Integer
.valueOf(gempakVcordInfo.getParmScale((parmList[3]))));
} catch (NumberFormatException e) {
//
}
}
@ -2460,8 +2215,9 @@ public class Dgdriv {
} else {
ll1 = parmList[4];
}
if (ll1 == null && ll2 == null)
if (ll1 == null && ll2 == null) {
return null;
}
if (ll1 != null) {
Double level1;
try {

View file

@ -4,22 +4,18 @@
package gov.noaa.nws.ncep.viz.rsc.ncscat.rsc;
import java.nio.ByteOrder;
import java.util.EnumSet;
/**
* 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...
* 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.
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
@ -27,65 +23,98 @@ import java.util.EnumSet;
* 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.
*
* </pre>
*
* @author bhebbard
* @author bhebbard
* @version 1.0
*/
public enum NcscatMode {
QUIKSCAT ( 76, true, ByteOrder.BIG_ENDIAN ),
QUIKSCAT_HI ( 152, true, ByteOrder.BIG_ENDIAN ),
ASCAT ( 42, false, ByteOrder.BIG_ENDIAN ),
ASCAT_HI ( 82, false, ByteOrder.BIG_ENDIAN ),
EXASCT ( 42, false, ByteOrder.LITTLE_ENDIAN ),
EXASCT_HI ( 82, false, ByteOrder.LITTLE_ENDIAN ),
OSCAT ( 36, true, ByteOrder.BIG_ENDIAN ),
OSCAT_HI ( 76, true, ByteOrder.LITTLE_ENDIAN ),
WSCAT ( 79, true, ByteOrder.LITTLE_ENDIAN ),
UNKNOWN ( 76, true, ByteOrder.BIG_ENDIAN );
private int pointsPerRow ; // number of Wind Vector Cell in each scan row across satellite track
private boolean isWindFrom ; // is the numeric wind direction the "from" (meteorological) direction?
private ByteOrder byteOrder ; // endianess of data in the byte stream
//TODO: could add more here, to simplify (switch) code with more table driven logic. But see above note about .xml/.prm...
// Constructor
NcscatMode (int pointsPerRow, boolean isWindFrom, ByteOrder byteOrder) {
this.pointsPerRow = pointsPerRow;
this.isWindFrom = isWindFrom;
this.byteOrder = byteOrder ;
}
public int getPointsPerRow() {
return pointsPerRow ;
}
public boolean isWindFrom() {
return isWindFrom ;
}
public ByteOrder getByteOrder() {
return byteOrder ;
}
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;
// @formatter:off
QUIKSCAT ( 76, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN ),
QUIKSCAT_HI ( 152, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN ),
ASCAT ( 42, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN ),
ASCAT_HI ( 82, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN ),
EXASCT ( 42, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.LITTLE_ENDIAN ),
EXASCT_HI ( 82, WindDirectionSense.OCEANOGRAPHIC, LongitudeCoding.UNSIGNED, ByteOrder.LITTLE_ENDIAN ),
OSCAT ( 36, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN ),
OSCAT_HI ( 76, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.LITTLE_ENDIAN ),
WSCAT ( 79, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.SIGNED, ByteOrder.LITTLE_ENDIAN ),
UNKNOWN ( 76, WindDirectionSense.METEOROLOGICAL, LongitudeCoding.UNSIGNED, ByteOrder.BIG_ENDIAN );
// @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
// TODO: could add more here, to simplify (switch) code with more table
// driven logic. But see above note about .xml/.prm...
// Constructor
NcscatMode(int pointsPerRow, WindDirectionSense windDirectionSense,
LongitudeCoding longitudeCoding, ByteOrder byteOrder) {
this.pointsPerRow = pointsPerRow;
this.windDirectionSense = windDirectionSense;
this.longitudeCoding = longitudeCoding;
this.byteOrder = byteOrder;
}
public int getPointsPerRow() {
return pointsPerRow;
}
public WindDirectionSense getWindDirectionSense() {
return windDirectionSense;
}
public LongitudeCoding getLongitudeCoding() {
return longitudeCoding;
}
public ByteOrder getByteOrder() {
return byteOrder;
}
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 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)
}
}

View file

@ -12,6 +12,8 @@ import gov.noaa.nws.ncep.viz.resources.AbstractNatlCntrsResource;
import gov.noaa.nws.ncep.viz.resources.INatlCntrsResource;
import gov.noaa.nws.ncep.viz.resources.colorBar.ColorBarResource;
import gov.noaa.nws.ncep.viz.resources.colorBar.ColorBarResourceData;
import gov.noaa.nws.ncep.viz.rsc.ncscat.rsc.NcscatMode.LongitudeCoding;
import gov.noaa.nws.ncep.viz.rsc.ncscat.rsc.NcscatMode.WindDirectionSense;
import gov.noaa.nws.ncep.viz.ui.display.ColorBar;
import gov.noaa.nws.ncep.viz.ui.display.NCMapDescriptor;
@ -38,15 +40,14 @@ import com.raytheon.uf.common.datastorage.records.IDataRecord;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.viz.core.IExtent;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.PixelExtent;
import com.raytheon.uf.viz.core.IGraphicsTarget.HorizontalAlignment;
import com.raytheon.uf.viz.core.IGraphicsTarget.TextStyle;
import com.raytheon.uf.viz.core.PixelExtent;
import com.raytheon.uf.viz.core.drawables.IFont;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.drawables.ResourcePair;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.geom.PixelCoordinate;
import com.raytheon.uf.viz.core.map.IMapDescriptor;
import com.raytheon.uf.viz.core.rsc.LoadProperties;
import com.raytheon.uf.viz.core.rsc.ResourceProperties;
import com.vividsolutions.jts.geom.Coordinate;
@ -73,6 +74,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* 17 Aug 2012 655 B. Hebbard Added paintProps as parameter to IDisplayable draw
* 12/19/2012 #960 Greg Hull override propertiesChanged() to update colorBar.
* 30 May 2013 B. Hebbard Merge changes by RTS in OB13.3.1 for DataStoreFactory.getDataStore(...)
* 11 Apr 2014 1128 B. Hebbard Prevent overflow if unsigned longitude >= 327.68W (32768)
*
* </pre>
*
@ -80,8 +82,8 @@ import com.vividsolutions.jts.geom.Coordinate;
* @version 1.0
*/
public class NcscatResource extends
AbstractNatlCntrsResource<NcscatResourceData, NCMapDescriptor> implements
INatlCntrsResource {
AbstractNatlCntrsResource<NcscatResourceData, NCMapDescriptor>
implements INatlCntrsResource {
// DEBUG boolean OVERRIDErainQcFlag = true;
// DEBUG boolean OVERRIDEhighWindSpeedFlag = true;
@ -93,10 +95,12 @@ public class NcscatResource extends
private Unit<?> windSpeedUnits = NonSI.KNOT;
protected ColorBarResource cbar1Resource;
protected ResourcePair cbar1RscPair;
protected ResourcePair cbar1RscPair;
protected ColorBarResource cbar2Resource;
protected ResourcePair cbar2RscPair;
protected ResourcePair cbar2RscPair;
private class FrameData extends AbstractFrameData {
ArrayList<NcscatRowData> frameRows = new ArrayList<NcscatRowData>();
@ -106,8 +110,8 @@ public class NcscatResource extends
frameRows = new ArrayList<NcscatRowData>();
}
public boolean updateFrameData(IRscDataObject rscDataObj ) {
PluginDataObject pdo = ((DfltRecordRscDataObj)rscDataObj).getPDO();
public boolean updateFrameData(IRscDataObject rscDataObj) {
PluginDataObject pdo = ((DfltRecordRscDataObj) rscDataObj).getPDO();
NcscatRecord nsRecord = (NcscatRecord) pdo;
@ -119,7 +123,7 @@ public class NcscatResource extends
}
else {
// ...convert into point data suitable for paint, grouped by rows...
// ...convert to point data for paint, grouped by rows...
ArrayList<NcscatRowData> rowsDataFromPdo = processHDF5Data(hdf5Data);
// ...and add to existing row data for this frame
frameRows.addAll(rowsDataFromPdo);
@ -131,18 +135,18 @@ public class NcscatResource extends
// Given the NcscatRecord, locate the associated HDF5 data...
File location = HDF5Util.findHDF5Location(nsRecord);
//TODO... Investigate: Why is the following statement needed?
// Starting in OB13.5.3, the PDO (nsRecord) has a non-null, but bogus,
// value in its dataURI field at this point (and earlier,
// as soon as it is deserialized after return from the metadata
// query). nsRecord.getDataURI() below will get this bad value, leading
// to failure on the ds.retrieve(...). Instead we force it to
// synthesize the dataURI -- which getDataURI() does correctly --
// by setting the field to null first. But why is this happening,
// and why only in OB13.5.3, and why only for some resources...? (bh)
// (see also NTRANS resource)
nsRecord.setDataURI(null); // force getDataURI() to construct one
// TODO... Investigate: Why is the following statement needed?
// Starting in OB13.5.3, the PDO (nsRecord) has a non-null, but
// bogus, value in its dataURI field at this point (and earlier,
// as soon as it is deserialized after return from the metadata
// query). nsRecord.getDataURI() below will get this bad value,
// leading to failure on the ds.retrieve(...). Instead we force
// it to synthesize the dataURI -- which getDataURI() does
// correctly -- by setting the field to null first. But why is
// this happening, and why only in OB13.5.3, and why only for
// some resources...? (bh) (see also NTRANS resource)
nsRecord.setDataURI(null); // force getDataURI() to construct one
String group = nsRecord.getDataURI();
String dataset = "Ncscat";
@ -167,10 +171,11 @@ public class NcscatResource extends
private ArrayList<NcscatRowData> processHDF5Data(byte[] hdf5Msg) {
// Note: This code lifted from NcscatProcessing.processHDFData, modified
// to (1) return point data in structures already optimized for paint()
// and (2) preserve intermediate organization by rows. Some further
// optimization may be desirable. (TODO)
// Note: This code lifted from NcscatProcessing.processHDFData,
// modified to (1) return point data in structures already
// optimized for paint() and (2) preserve intermediate
// organization by rows. Some further optimization may
// be desirable. (TODO)
final int shortsPerPoint = 9;
final int bytesPerPoint = 2 * shortsPerPoint;
@ -184,10 +189,10 @@ public class NcscatResource extends
byteBuffer.put(hdf5Msg, 0, hdf5Msg.length);
while (ji < hdf5Msg.length) {
day = byteBuffer.getShort(byteNumber);
day = byteBuffer.getShort(byteNumber);
hour = byteBuffer.getShort(byteNumber + 2);
min = byteBuffer.getShort(byteNumber + 4);
sec = byteBuffer.getShort(byteNumber + 6);
min = byteBuffer.getShort(byteNumber + 4);
sec = byteBuffer.getShort(byteNumber + 6);
ji += 8;
byteNumber += 8;
Calendar startTime = Calendar.getInstance();
@ -215,12 +220,11 @@ public class NcscatResource extends
// sPointObj.setIb3(byteBuffer.getShort(j+16));
byteNumber += bytesPerPoint;
// returnList.add(sPointObj);
// Above code put things into a NcscatPoint (common with decoder);
// now convert to a NcscatPointData (local class) optimized for
// display via paint(), and add to the row
// Above code put things into a NcscatPoint (common with
// decoder); now convert to a NcscatPointData (local class)
// optimized for display via paint(), and add to the row
rowData.points.add(new NcscatPointData(sPointObj));
// sPointObj
}// for
} // for
ji = byteNumber;
@ -228,7 +232,7 @@ public class NcscatResource extends
// rows in this HDF5 message
returnList.add(rowData);
}// while
} // while
return returnList;
}
@ -236,9 +240,10 @@ public class NcscatResource extends
}
// Structure containing displayable information for a
// singpointData.rainQcFlag && ncscatResourceData.use2ndColorForRainEnablele
// displayable element -- that is, a single point observation.
// @formatter:off
private class NcscatPointData {
Coordinate location; // lat/lon of this point
float direction; // "from" direction in bulletin
@ -254,22 +259,32 @@ public class NcscatResource extends
// (For example, don't want to flip direction at every paint().)
public NcscatPointData(NcscatPoint point) {
location = new Coordinate(point.getLon() / 100.0,
point.getLat() / 100.0);
// TODO: Probably OK to leave as is, but...
if (location.x > 180.0f) // deal with possible...
location.x -= 360.0f;
if (location.x < -180.0f) // ...novel longitude coding
location.x += 360.0f;
int scaledLatitude = point.getLat(); // signed int from signed short
int scaledLongitude = point.getLon(); // signed int from either signed short, OR...
if (ncscatMode.getLongitudeCoding() == LongitudeCoding.UNSIGNED) {
if (scaledLongitude < 0) { // ...*unsigned* short
scaledLongitude += 65536; // aka 1<<16
}
if (scaledLongitude > 18000) { // unsigned longitude comes in as 0--360 east of Greenwich
scaledLongitude -= 36000; // convert to -180 -- +180
}
}
location = new Coordinate(scaledLongitude / 100.0, // de-scale and float
scaledLatitude / 100.0);
direction = point.getIdr() / 100.0f;
if (ncscatMode.isWindFrom()) {
direction = direction > 180.0f ? // reverse direction sense
// some (but not all) data sources require us to...
if (ncscatMode.getWindDirectionSense() == WindDirectionSense.METEOROLOGICAL) {
direction = direction > 180.0f ? // ...reverse direction sense
direction - 180.0f
: direction + 180.0f;
}
speed = point.getIsp() / 100.0f;
speed *= (3600.0f / 1852.0f); // m/s --> kt //TODO: Use Unit conversions...?
int qualityBits = point.getIql();
switch (ncscatMode) {
case QUIKSCAT:
case QUIKSCAT_HI:
@ -305,7 +320,10 @@ public class NcscatResource extends
lowWindSpeedFlag = false;
availRedunFlag = false;
break;
case OSCAT: // Don't have...
case OSCAT_HI: // ...these flags
case UNKNOWN:
default:
rainQcFlag = false;
highWindSpeedFlag = false;
lowWindSpeedFlag = false;
@ -315,18 +333,21 @@ public class NcscatResource extends
}
private boolean getBit (int bits, int bitNum) {
int masks[] = {0x8000, 0x4000, 0x2000, 0x1000,
0x0800, 0x0400, 0x0200, 0x0100,
0x0080, 0x0040, 0x0020, 0x0010,
0x0008, 0x0004, 0x0002, 0x0001};
int mask = masks[bitNum];
return (bits & mask) != 0;
int masks[] = {0x8000, 0x4000, 0x2000, 0x1000,
0x0800, 0x0400, 0x0200, 0x0100,
0x0080, 0x0040, 0x0020, 0x0010,
0x0008, 0x0004, 0x0002, 0x0001};
int mask = masks[bitNum];
return (bits & mask) != 0;
}
}
// @formatter:on
// Structure grouping displayable information for a single row element
//
private class NcscatRowData {
Calendar rowTime; // timestamp on this row
Calendar rowTime; // timestamp on this row
ArrayList<NcscatPointData> points; // individual points in row
public NcscatRowData(Calendar rowTime) {
@ -363,26 +384,31 @@ public class NcscatResource extends
ncscatResourceData.setNcscatMode();
ncscatMode = ncscatResourceData.getNcscatMode();
queryRecords();
// create a system resource for the colorBar and add it to the resource list.
//
cbar1RscPair = ResourcePair.constructSystemResourcePair(
new ColorBarResourceData( ncscatResourceData.getColorBar1() ) );
// create a system resource for the colorBar and add it to the resource
// list.
//
cbar1RscPair = ResourcePair
.constructSystemResourcePair(new ColorBarResourceData(
ncscatResourceData.getColorBar1()));
getDescriptor().getResourceList().add( cbar1RscPair );
getDescriptor().getResourceList().instantiateResources( getDescriptor(), true );
getDescriptor().getResourceList().add(cbar1RscPair);
getDescriptor().getResourceList().instantiateResources(getDescriptor(),
true);
cbar1Resource = (ColorBarResource) cbar1RscPair.getResource();
cbar2RscPair = ResourcePair.constructSystemResourcePair(
new ColorBarResourceData( ncscatResourceData.getColorBar2() ) );
getDescriptor().getResourceList().add( cbar2RscPair );
getDescriptor().getResourceList().instantiateResources( getDescriptor(), true );
cbar2RscPair = ResourcePair
.constructSystemResourcePair(new ColorBarResourceData(
ncscatResourceData.getColorBar2()));
getDescriptor().getResourceList().add(cbar2RscPair);
getDescriptor().getResourceList().instantiateResources(getDescriptor(),
true);
cbar2Resource = (ColorBarResource) cbar2RscPair.getResource();
if( !ncscatResourceData.use2ndColorForRainEnable ) {
getDescriptor().getResourceList().remove( cbar2RscPair );
if (!ncscatResourceData.use2ndColorForRainEnable) {
getDescriptor().getResourceList().remove(cbar2RscPair);
}
}
@ -435,51 +461,63 @@ public class NcscatResource extends
double speed = 0.0;
double direction = 0.0;
// ...or option-dependent values invariant across all points
float lineWidth = (float) (ncscatResourceData.arrowWidth * 1.0); // tune to match NMAP
double sizeScale = ncscatResourceData.arrowSize * 0.135; // tune to match NMAP
double arrowHeadSize = ncscatResourceData.headSize * 0.2; // tune to match NMAP
double rainQcCircleRadiusPixels = ncscatResourceData.arrowSize / screenToWorldRatio * 0.46; // tune to match NMAP
// ...or option-dependent values invariant across all points.
// Note constants in the following are "tuned" to match NMAP
float lineWidth = (float) (ncscatResourceData.arrowWidth * 1.0);
double sizeScale = ncscatResourceData.arrowSize * 0.135;
double arrowHeadSize = ncscatResourceData.headSize * 0.2;
double rainQcCircleRadiusPixels = ncscatResourceData.arrowSize
/ screenToWorldRatio * 0.46;
// Arrow type
String pgenCategory = "Vector";
String pgenType = ncscatResourceData.arrowStyle.getPgenType();
VectorType vc = ncscatResourceData.arrowStyle.getVectorType();
boolean directionOnly = ncscatResourceData.arrowStyle.getDirectionOnly();
boolean directionOnly = ncscatResourceData.arrowStyle
.getDirectionOnly();
// TODO: Unify this with above. For now, do some arrow-style-specific fine tuning...
// TODO: Unify this with above. For now, do some arrow-style-specific
// fine tuning...
switch (ncscatResourceData.arrowStyle) {
case DIRECTIONAL_ARROW:
case REGULAR_ARROW:
sizeScale *= 1.5;
break;
sizeScale *= 1.5;
break;
case WIND_BARB:
break;
default:
break;
}
// User tells us how many rows -- and points within each row -- to
// *skip* in between ones that get displayed; add one to get full
// cycle interval...
int interval = ncscatResourceData.skipEnable ? ncscatResourceData.skipValue + 1
// ...OR if skip option not selected, auto-compute interval (1<=x<=6) based on
// zoom and user-specified density (i.e., selectable progressive disclosure)
: Math.max(Math.min((int) (50 / screenToWorldRatio / ncscatResourceData.densityValue), 6), 1);
///System.out.println("interval = " + interval);
///System.out.println("S:W = " + screenToWorldRatio +
/// " interval = " + interval +
/// " density = " + ncscatResourceData.densityValue);
// ...OR if skip option not selected, auto-compute interval
// (1<=x<=6) based on zoom and user-specified density
// (i.e., selectable progressive disclosure)
: Math.max(
Math.min(
(int) (50 / screenToWorldRatio / ncscatResourceData.densityValue),
6), 1);
// /System.out.println("interval = " + interval);
// /System.out.println("S:W = " + screenToWorldRatio +
// / " interval = " + interval +
// / " density = " + ncscatResourceData.densityValue);
int lastTimestampedMinute = -99; // flag so we only timestamp each
// minute once
// Loop through the (preprocessed) NCSCAT data records
// (This should be fast.)
ArrayList<NcscatRowData> frameRows = currFrameData.frameRows;
// Loop over ROWS in the satellite track...
for (int rowCount = 0; rowCount < frameRows.size(); rowCount++) {
NcscatRowData rowData = frameRows.get(rowCount);
for (int rowNumber = 0; rowNumber < frameRows.size(); rowNumber++) {
boolean displayRow = (rowCount % interval == 0);
NcscatRowData rowData = frameRows.get(rowNumber);
boolean displayRow = (rowNumber % interval == 0);
// Loop over POINTS in this row...
@ -488,35 +526,49 @@ public class NcscatResource extends
double yAtMaxXOfRow = 0.0;
double yAtMinXOfRow = 0.0;
for (int pointCount = 0; pointCount < rowData.points.size(); pointCount += interval) {
for (int pointNumber = 0; pointNumber < rowData.points.size(); pointNumber += interval) {
// DEBUG pointData.rainQcFlag=OVERRIDErainQcFlag;
// DEBUG pointData.highWindSpeedFlag=OVERRIDEhighWindSpeedFlag;
// DEBUG pointData.lowWindSpeedFlag=OVERRIDElowWindSpeedFlag;
// DEBUG pointData.availRedunFlag=OVERRIDEavailRedunFlag;
// Display point if consistent with skip interval, data flags,
// and user options...
NcscatPointData pointData = rowData.points.get(pointCount);
if ((!pointData.availRedunFlag || ncscatResourceData.availabilityFlagEnable)
&& (!pointData.rainQcFlag || ncscatResourceData.rainFlagEnable)
&& (!pointData.highWindSpeedFlag || ncscatResourceData.highWindSpeedEnable)
&& (!pointData.lowWindSpeedFlag || ncscatResourceData.lowWindSpeedEnable)
&& pointData.speed > 0.0f) {
// If point is consistent with data flags and user options...
NcscatPointData pointData = rowData.points.get(pointNumber);
if ((!pointData.availRedunFlag || ncscatResourceData.availabilityFlagEnable)
&& (!pointData.rainQcFlag || ncscatResourceData.rainFlagEnable)
&& (!pointData.highWindSpeedFlag || ncscatResourceData.highWindSpeedEnable)
&& (!pointData.lowWindSpeedFlag || ncscatResourceData.lowWindSpeedEnable)
&& pointData.speed > 0.0f) {
location = pointData.location;
double[] locLatLon = { location.x, location.y };
double[] locPix = this.descriptor.worldToPixel(locLatLon);
// ...and is currently in visible range
if (locPix != null
&& correctedExtent.contains(locPix[0], locPix[1])) {
// Remember left- and right-most point locations of row,
// for possible time stamp line -- *even if we are not
// displaying the points in this row*
if (locPix[0] > maxXOfRow) {
maxXOfRow = locPix[0];
yAtMaxXOfRow = locPix[1];
}
if (locPix[0] < minXOfRow) {
minXOfRow = locPix[0];
yAtMinXOfRow = locPix[1];
}
if (displayRow) {
// Now we are "go" to display the point (build its
// wind vector and, if applicable, draw associated
// circle)
speed = pointData.speed;
direction = pointData.direction;
ColorBar colorBarToUse = pointData.rainQcFlag
&& ncscatResourceData.use2ndColorForRainEnable ? colorBar2
: colorBar1;
: colorBar1;
color = getColorForSpeed(speed, colorBarToUse);
colors = new Color[] { new Color(color.red, color.green, color.blue) };
colors = new Color[] { new Color(color.red,
color.green, color.blue) };
windVectors.add(new Vector(null, colors, lineWidth,
sizeScale, clear, location, vc, speed,
direction, arrowHeadSize, directionOnly,
@ -526,18 +578,12 @@ public class NcscatResource extends
PixelCoordinate pixelLoc = new PixelCoordinate(
descriptor.worldToPixel(new double[] {
location.x, location.y }));
target.drawCircle(pixelLoc.getX(), pixelLoc.getY(), pixelLoc.getZ(),
rainQcCircleRadiusPixels, color, lineWidth);
target.drawCircle(pixelLoc.getX(),
pixelLoc.getY(), pixelLoc.getZ(),
rainQcCircleRadiusPixels, color,
lineWidth);
}
}
if (locPix[0] > maxXOfRow) {
maxXOfRow = locPix[0];
yAtMaxXOfRow = locPix[1];
}
if (locPix[0] < minXOfRow) {
minXOfRow = locPix[0];
yAtMinXOfRow = locPix[1];
}
}
}
}
@ -556,15 +602,16 @@ public class NcscatResource extends
minuteOfDay != lastTimestampedMinute) {
// Draw time line/string for the first row within that minute,
// IF any point of that row is within visible range.
// (Note: *Not* the same as the first row with visible point
// within that minute.)
lastTimestampedMinute = minuteOfDay; // Been here; done this
// (Note: This is *not* the same as the first row with visible
// point within that minute.)
lastTimestampedMinute = minuteOfDay; // Been here; done this
if (maxXOfRow - minXOfRow <= 2000
&& // TODO: Find a better way to prevent wraparound
// Visible?
// Visible?
correctedExtent.contains(minXOfRow, yAtMinXOfRow)
&& correctedExtent.contains(maxXOfRow, yAtMaxXOfRow)) {
// Draw line across track -- or as much as is currently visible...
// Draw line across track -- or as much as is currently
// visible...
target.drawLine(minXOfRow, yAtMinXOfRow, 0.0, maxXOfRow,
yAtMaxXOfRow, 0.0,
ncscatResourceData.timeStampColor,
@ -588,15 +635,17 @@ public class NcscatResource extends
font.dispose();
// Display wind vectors for all points
// Draw the combined wind vectors for all points
DisplayElementFactory df = new DisplayElementFactory(target, getNcMapDescriptor());
ArrayList<IDisplayable> displayEls = df.createDisplayElements(windVectors, paintProps);
DisplayElementFactory df = new DisplayElementFactory(target,
getNcMapDescriptor());
ArrayList<IDisplayable> displayEls = df.createDisplayElements(
windVectors, paintProps);
for (IDisplayable each : displayEls) {
each.draw(target, paintProps);
each.dispose();
}
}
private RGB getColorForSpeed(double speed, ColorBar colorBar) {
@ -612,57 +661,61 @@ public class NcscatResource extends
// if( font != null ) {
// font.dispose();
// }
getDescriptor().getResourceList().remove( cbar1RscPair );
getDescriptor().getResourceList().remove( cbar2RscPair );
getDescriptor().getResourceList().remove(cbar1RscPair);
getDescriptor().getResourceList().remove(cbar2RscPair);
}
public void resourceAttrsModified() {
// update the colorbarPainters with possibly new colorbars
boolean isCbar2Enabled =
(getDescriptor().getResourceList().indexOf( cbar2RscPair ) != -1 );
//
if( ncscatResourceData.use2ndColorForRainEnable && !isCbar2Enabled ) {
cbar2RscPair = ResourcePair.constructSystemResourcePair(
new ColorBarResourceData( ncscatResourceData.getColorBar2() ) );
boolean isCbar2Enabled = (getDescriptor().getResourceList().indexOf(
cbar2RscPair) != -1);
//
if (ncscatResourceData.use2ndColorForRainEnable && !isCbar2Enabled) {
cbar2RscPair = ResourcePair
.constructSystemResourcePair(new ColorBarResourceData(
ncscatResourceData.getColorBar2()));
getDescriptor().getResourceList().add( cbar2RscPair );
getDescriptor().getResourceList().instantiateResources( getDescriptor(), true );
getDescriptor().getResourceList().add(cbar2RscPair);
getDescriptor().getResourceList().instantiateResources(
getDescriptor(), true);
cbar2Resource = (ColorBarResource) cbar2RscPair.getResource();
}
else if( !ncscatResourceData.use2ndColorForRainEnable && isCbar2Enabled ) {
// this will cause the ResourceCatalog to dispose of the resource so we will
// need to create a new one here.
getDescriptor().getResourceList().remove( cbar2RscPair );
cbar2RscPair = null;
cbar2Resource = null;
} else if (!ncscatResourceData.use2ndColorForRainEnable
&& isCbar2Enabled) {
// this will cause the ResourceCatalog to dispose of the resource so
// we will
// need to create a new one here.
getDescriptor().getResourceList().remove(cbar2RscPair);
cbar2RscPair = null;
cbar2Resource = null;
}
cbar1Resource.setColorBar(ncscatResourceData.getColorBar1());
if( cbar2Resource != null ) {
cbar2Resource.setColorBar(ncscatResourceData.getColorBar2());
if (cbar2Resource != null) {
cbar2Resource.setColorBar(ncscatResourceData.getColorBar2());
}
}
@Override
public void propertiesChanged(ResourceProperties updatedProps) {
if( cbar1RscPair != null ) {
cbar1RscPair.getProperties().setVisible( updatedProps.isVisible() );
}
if( cbar2RscPair != null ) {
cbar2RscPair.getProperties().setVisible( updatedProps.isVisible() );
}
}
@Override
public String getName() {
String legendString = super.getName();
FrameData fd = (FrameData) getCurrentFrame();
if (fd == null || fd.getFrameTime() == null || fd.frameRows.size() == 0) {
return legendString + "-No Data";
}
return legendString + " "+ NmapCommon.getTimeStringFromDataTime( fd.getFrameTime(), "/");
}
public void propertiesChanged(ResourceProperties updatedProps) {
if (cbar1RscPair != null) {
cbar1RscPair.getProperties().setVisible(updatedProps.isVisible());
}
if (cbar2RscPair != null) {
cbar2RscPair.getProperties().setVisible(updatedProps.isVisible());
}
}
@Override
public String getName() {
String legendString = super.getName();
FrameData fd = (FrameData) getCurrentFrame();
if (fd == null || fd.getFrameTime() == null || fd.frameRows.size() == 0) {
return legendString + "-No Data";
}
return legendString + " "
+ NmapCommon.getTimeStringFromDataTime(fd.getFrameTime(), "/");
}
}

View file

@ -10,7 +10,7 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
@ -19,13 +19,12 @@ import com.raytheon.uf.viz.core.exception.VizException;
/**
* @author bhebbard
*
*
*/
public interface INcCommand {
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException;
}
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException;
}

View file

@ -24,6 +24,39 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.BeginMetafile;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.BeginPicture;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.BeginPictureBody;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.CGM;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.CGMDisplay;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.CgmException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ColourIndexPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ColourModel;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ColourPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ColourSelectionMode;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ColourValueExtent;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Command;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.EdgeWidthSpecificationMode;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.EndMetafile;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.EndPicture;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.IBeginMetafileNameExtractor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ICgmExtractor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ICommandListener;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.IndexPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.IntegerPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.LineWidthSpecificationMode;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.MarkerSizeSpecificationMode;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Message;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Messages;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.RealPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.RestrictedTextType;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ScalingMode;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ScalingMode.Mode;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.VDCExtent;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.VDCIntegerPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.VDCRealPrecision;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.VDCType;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import java.io.BufferedInputStream;
@ -48,412 +81,420 @@ import java.util.zip.GZIPInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.*;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.ScalingMode.*;
/**
* @author bhebbard adapted from CGM.java by BBN
*
*
*/
public class NcCGM extends CGM implements Cloneable {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
private List<Command> commands;
private List<Command> commands;
private final List<ICommandListener> commandListeners = new ArrayList<ICommandListener>();
private final List<ICommandListener> commandListeners = new ArrayList<ICommandListener>();
private final static int INITIAL_NUM_COMMANDS = 500;
private final static int MAX_COMMANDS_PER_IMAGE = 999999;
private final static int INITIAL_NUM_COMMANDS = 500;
public NcCGM() {
// empty constructor //TODO: Remove?
}
private final static int MAX_COMMANDS_PER_IMAGE = 999999;
public NcCGM(File cgmFile) throws IOException {
// NO LONGER NEEDED
if (cgmFile == null)
throw new NullPointerException("unexpected null parameter");
public NcCGM() {
// empty constructor //TODO: Remove?
}
InputStream inputStream;
String cgmFilename = cgmFile.getName();
if (cgmFilename.endsWith(".cgm.gz") || cgmFilename.endsWith(".cgmz")) {
inputStream = new GZIPInputStream(new FileInputStream(cgmFile));
}
else {
inputStream = new FileInputStream(cgmFile);
}
DataInputStream in = new DataInputStream(new BufferedInputStream(inputStream));
read(in);
in.close();
}
public NcCGM(File cgmFile) throws IOException {
// NO LONGER NEEDED
if (cgmFile == null)
throw new NullPointerException("unexpected null parameter");
public void read(DataInput in) throws IOException {
reset();
this.commands = new ArrayList<Command>(INITIAL_NUM_COMMANDS);
int com = 0;
Command c;
do {
if (com++ > MAX_COMMANDS_PER_IMAGE) {
logger.error("Exceeded maxiumum CGM commands (" +
MAX_COMMANDS_PER_IMAGE +
") for one image; adding EndPicture command automatically]");
c = new EndPicture(0,5,0,in);
break;
}
try {
c = NcCommand.read(in);
}
catch (Exception e) {
c = null;
logger.error("Exception occurred interpreting CGM bytecode");
e.printStackTrace();
}
if (c == null) continue; // or should we add as null command?
if (c instanceof NcLineWidth || c instanceof NcTextAlignment) {
logger.info("[CGM command #" + com + " completed] " + c.toString());
}
logger.debug("[CGM command #" + com + " completed] " + c.toString());
InputStream inputStream;
String cgmFilename = cgmFile.getName();
if (cgmFilename.endsWith(".cgm.gz") || cgmFilename.endsWith(".cgmz")) {
inputStream = new GZIPInputStream(new FileInputStream(cgmFile));
} else {
inputStream = new FileInputStream(cgmFile);
}
DataInputStream in = new DataInputStream(new BufferedInputStream(
inputStream));
read(in);
in.close();
}
for (ICommandListener listener : this.commandListeners) {
listener.commandProcessed(c);
}
public void read(DataInput in) throws IOException {
reset();
this.commands = new ArrayList<Command>(INITIAL_NUM_COMMANDS);
int com = 0;
Command c;
do {
if (com++ > MAX_COMMANDS_PER_IMAGE) {
logger.error("Exceeded maxiumum CGM commands ("
+ MAX_COMMANDS_PER_IMAGE
+ ") for one image; adding EndPicture command automatically]");
c = new EndPicture(0, 5, 0, in);
break;
}
// get rid of all arguments after we read them
c.cleanUpArguments();
try {
c = NcCommand.read(in);
} catch (Exception e) {
c = null;
logger.error("Exception occurred interpreting CGM bytecode");
e.printStackTrace();
}
this.commands.add(c);
if (c instanceof EndMetafile) {
logger.warn("[Unexpected CGM EndMetafile command encountered]");
}
if (c instanceof EndPicture) {
logger.debug("[CGM EndPicture command: Picture is completed]");
}
else if (!(c instanceof INcCommand)) {
if (!(c instanceof BeginPicture) && !(c instanceof BeginPictureBody)) {
logger.warn("Unsupported CGM command encountered -- " + c +"]");
}
}
} while (!(c instanceof EndPicture));
}
if (c == null)
continue; // or should we add as null command?
/**
* Splits a CGM file containing several CGM files into pieces. Each single
* CGM file will be extracted to an own file. The name of that file is
* provided by the given {@code extractor}.
*
* @param cgmFile
* The CGM file to split
* @param outputDir
* The output directory to use. Must exist and be writable.
* @param extractor
* The extractor in charge of naming the split CGM files
* @throws IOException
* If the given CGM file could not be read or there was an error
* splitting the file
*/
public static void split(File cgmFile, File outputDir,
IBeginMetafileNameExtractor extractor) throws IOException {
if (cgmFile == null || outputDir == null || extractor == null)
throw new NullPointerException("unexpected null argument");
if (c instanceof NcLineWidth || c instanceof NcTextAlignment) {
logger.info("[CGM command #" + com + " completed] "
+ c.toString());
}
if (!outputDir.isDirectory())
throw new IllegalArgumentException("outputDir must be a directory");
logger.debug("[CGM command #" + com + " completed] "
+ c.toString());
if (!outputDir.canWrite())
throw new IllegalArgumentException("outputDir must be writable");
for (ICommandListener listener : this.commandListeners) {
listener.commandProcessed(c);
}
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(cgmFile, "r");
FileChannel channel = randomAccessFile.getChannel();
// get rid of all arguments after we read them
c.cleanUpArguments();
Command c;
long startPosition = 0;
long currentPosition = 0;
String currentFileName = null;
this.commands.add(c);
while ((c = Command.read(randomAccessFile)) != null) {
if (c instanceof BeginMetafile) {
// the CGM files will be cut at the begin meta file command
if (currentFileName != null) {
dumpToFile(outputDir, extractor, channel, startPosition,
currentPosition, currentFileName);
}
startPosition = currentPosition;
BeginMetafile beginMetafile = (BeginMetafile) c;
currentFileName = beginMetafile.getFileName();
}
currentPosition = randomAccessFile.getFilePointer();
}
if (c instanceof EndMetafile) {
logger.warn("[Unexpected CGM EndMetafile command encountered]");
}
if (c instanceof EndPicture) {
logger.debug("[CGM EndPicture command: Picture is completed]");
} else if (!(c instanceof INcCommand)) {
if (!(c instanceof BeginPicture)
&& !(c instanceof BeginPictureBody)) {
logger.warn("Unsupported CGM command encountered -- " + c
+ "]");
}
}
if (currentFileName != null) {
dumpToFile(outputDir, extractor, channel, startPosition,
currentPosition, currentFileName);
}
}
finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
}
} while (!(c instanceof EndPicture));
private static void dumpToFile(File outputDir,
IBeginMetafileNameExtractor extractor, FileChannel channel,
long startPosition, long currentPosition, String currentFileName)
throws IOException {
// dump the CGM file
MappedByteBuffer byteBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, startPosition,
currentPosition - startPosition);
writeFile(byteBuffer, outputDir, extractor
.extractFileName(currentFileName));
// don't forget to regularly clear the messages that
// we're not really using here
Messages.getInstance().reset();
}
}
/**
* Splits a CGM file containing several CGM files into pieces. The given
* extractor is in charge of dealing with the extracted CGM file.
*
* @param cgmFile
* The CGM file to split
* @param extractor
* An extractor that knows what to do with the extracted CGM file
* @throws IOException
* If an error happened reading the CGM file
* @throws CgmException
* If an error happened during the handling of the extracted CGM
* file
*/
public static void split(File cgmFile, ICgmExtractor extractor)
throws IOException, CgmException {
if (cgmFile == null || extractor == null)
throw new NullPointerException("unexpected null argument");
/**
* Splits a CGM file containing several CGM files into pieces. Each single
* CGM file will be extracted to an own file. The name of that file is
* provided by the given {@code extractor}.
*
* @param cgmFile
* The CGM file to split
* @param outputDir
* The output directory to use. Must exist and be writable.
* @param extractor
* The extractor in charge of naming the split CGM files
* @throws IOException
* If the given CGM file could not be read or there was an error
* splitting the file
*/
public static void split(File cgmFile, File outputDir,
IBeginMetafileNameExtractor extractor) throws IOException {
if (cgmFile == null || outputDir == null || extractor == null)
throw new NullPointerException("unexpected null argument");
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(cgmFile, "r");
FileChannel channel = randomAccessFile.getChannel();
if (!outputDir.isDirectory())
throw new IllegalArgumentException("outputDir must be a directory");
Command c;
long startPosition = 0;
long currentPosition = 0;
String currentFileName = null;
if (!outputDir.canWrite())
throw new IllegalArgumentException("outputDir must be writable");
while ((c = Command.read(randomAccessFile)) != null) {
if (c instanceof BeginMetafile) {
// the CGM files will be cut at the begin meta file command
if (currentFileName != null) {
dumpToStream(extractor, channel, startPosition,
currentPosition, currentFileName);
}
startPosition = currentPosition;
BeginMetafile beginMetafile = (BeginMetafile) c;
currentFileName = beginMetafile.getFileName();
}
currentPosition = randomAccessFile.getFilePointer();
}
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(cgmFile, "r");
FileChannel channel = randomAccessFile.getChannel();
// don't forget to also dump the last file
if (currentFileName != null) {
dumpToStream(extractor, channel, startPosition,
currentPosition, currentFileName);
}
}
finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
}
Command c;
long startPosition = 0;
long currentPosition = 0;
String currentFileName = null;
private static void dumpToStream(ICgmExtractor extractor,
FileChannel channel, long startPosition, long currentPosition,
String currentFileName) throws IOException, CgmException {
// dump the CGM file
MappedByteBuffer byteBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, startPosition, currentPosition
- startPosition);
while ((c = Command.read(randomAccessFile)) != null) {
if (c instanceof BeginMetafile) {
// the CGM files will be cut at the begin meta file command
if (currentFileName != null) {
dumpToFile(outputDir, extractor, channel,
startPosition, currentPosition, currentFileName);
}
startPosition = currentPosition;
BeginMetafile beginMetafile = (BeginMetafile) c;
currentFileName = beginMetafile.getFileName();
}
currentPosition = randomAccessFile.getFilePointer();
}
byte[] byteArray = new byte[(int) (currentPosition - startPosition)];
byteBuffer.get(byteArray);
extractor.handleExtracted(extractor.extractFileName(currentFileName),
new ByteArrayInputStream(byteArray), byteArray.length);
// don't forget to regularly clear the messages that
// we're not really using here
Messages.getInstance().reset();
}
if (currentFileName != null) {
dumpToFile(outputDir, extractor, channel, startPosition,
currentPosition, currentFileName);
}
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
}
/**
* Writes the given bytes to a file
*
* @param byteBuffer
* The bytes to write to the file
* @param outputDir
* The output directory to use, assumed to be existing and
* writable
* @param fileName
* The file name to use
* @throws IOException
* On I/O error
*/
private static void writeFile(ByteBuffer byteBuffer, File outputDir,
String fileName) throws IOException {
File outputFile = new File(outputDir, fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
FileChannel channel = out.getChannel();
channel.write(byteBuffer);
out.close();
}
finally {
if (out != null) {
out.close();
}
}
}
private static void dumpToFile(File outputDir,
IBeginMetafileNameExtractor extractor, FileChannel channel,
long startPosition, long currentPosition, String currentFileName)
throws IOException {
// dump the CGM file
MappedByteBuffer byteBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, startPosition, currentPosition
- startPosition);
writeFile(byteBuffer, outputDir,
extractor.extractFileName(currentFileName));
// don't forget to regularly clear the messages that
// we're not really using here
Messages.getInstance().reset();
}
/**
* Adds the given listener to the list of command listeners
* @param listener The listener to add
*/
public void addCommandListener(ICommandListener listener) {
this.commandListeners.add(listener);
}
/**
* Splits a CGM file containing several CGM files into pieces. The given
* extractor is in charge of dealing with the extracted CGM file.
*
* @param cgmFile
* The CGM file to split
* @param extractor
* An extractor that knows what to do with the extracted CGM file
* @throws IOException
* If an error happened reading the CGM file
* @throws CgmException
* If an error happened during the handling of the extracted CGM
* file
*/
public static void split(File cgmFile, ICgmExtractor extractor)
throws IOException, CgmException {
if (cgmFile == null || extractor == null)
throw new NullPointerException("unexpected null argument");
/**
* All the command classes with static data need to be reset here
*/
private void reset() {
ColourIndexPrecision.reset();
ColourModel.reset();
ColourPrecision.reset();
ColourSelectionMode.reset();
ColourValueExtent.reset();
EdgeWidthSpecificationMode.reset();
IndexPrecision.reset();
IntegerPrecision.reset();
LineWidthSpecificationMode.reset();
MarkerSizeSpecificationMode.reset();
RealPrecision.reset();
RestrictedTextType.reset();
VDCIntegerPrecision.reset();
VDCRealPrecision.reset();
VDCType.reset();
RandomAccessFile randomAccessFile = null;
try {
randomAccessFile = new RandomAccessFile(cgmFile, "r");
FileChannel channel = randomAccessFile.getChannel();
Messages.getInstance().reset();
}
Command c;
long startPosition = 0;
long currentPosition = 0;
String currentFileName = null;
public List<Message> getMessages() {
return Messages.getInstance();
}
while ((c = Command.read(randomAccessFile)) != null) {
if (c instanceof BeginMetafile) {
// the CGM files will be cut at the begin meta file command
if (currentFileName != null) {
dumpToStream(extractor, channel, startPosition,
currentPosition, currentFileName);
}
startPosition = currentPosition;
BeginMetafile beginMetafile = (BeginMetafile) c;
currentFileName = beginMetafile.getFileName();
}
currentPosition = randomAccessFile.getFilePointer();
}
public void paint(CGMDisplay d) {
for (Command c : this.commands) {
if (filter(c)) {
c.paint(d);
}
}
}
// don't forget to also dump the last file
if (currentFileName != null) {
dumpToStream(extractor, channel, startPosition,
currentPosition, currentFileName);
}
} finally {
if (randomAccessFile != null) {
randomAccessFile.close();
}
}
}
private boolean filter(Command c) {
return true;
// List<Class<?>> classes = new ArrayList<Class<?>>();
// //classes.add(PolygonElement.class);
// classes.add(Text.class);
// //classes.add(CircleElement.class);
//
// for (Class<?> clazz: classes) {
// if (clazz.isInstance(c))
// return false;
// }
//
// return true;
}
private static void dumpToStream(ICgmExtractor extractor,
FileChannel channel, long startPosition, long currentPosition,
String currentFileName) throws IOException, CgmException {
// dump the CGM file
MappedByteBuffer byteBuffer = channel.map(
FileChannel.MapMode.READ_ONLY, startPosition, currentPosition
- startPosition);
/**
* Returns the size of the CGM graphic.
* @return The dimension or null if no {@link VDCExtent} command was found.
*/
public Dimension getSize() {
// default to 96 DPI which is the Microsoft Windows default DPI setting
return getSize(96);
}
byte[] byteArray = new byte[(int) (currentPosition - startPosition)];
byteBuffer.get(byteArray);
extractor.handleExtracted(extractor.extractFileName(currentFileName),
new ByteArrayInputStream(byteArray), byteArray.length);
// don't forget to regularly clear the messages that
// we're not really using here
Messages.getInstance().reset();
}
/**
* Returns the size of the CGM graphic taking into account a specific DPI setting
* @param dpi The DPI value to use
* @return The dimension or null if no {@link VDCExtent} command was found.
*/
public Dimension getSize(double dpi) {
Point2D.Double[] extent = extent();
if (extent == null)
return null;
/**
* Writes the given bytes to a file
*
* @param byteBuffer
* The bytes to write to the file
* @param outputDir
* The output directory to use, assumed to be existing and
* writable
* @param fileName
* The file name to use
* @throws IOException
* On I/O error
*/
private static void writeFile(ByteBuffer byteBuffer, File outputDir,
String fileName) throws IOException {
File outputFile = new File(outputDir, fileName);
FileOutputStream out = null;
try {
out = new FileOutputStream(outputFile);
FileChannel channel = out.getChannel();
channel.write(byteBuffer);
out.close();
} finally {
if (out != null) {
out.close();
}
}
}
double factor = 1;
/**
* Adds the given listener to the list of command listeners
*
* @param listener
* The listener to add
*/
public void addCommandListener(ICommandListener listener) {
this.commandListeners.add(listener);
}
ScalingMode scalingMode = getScalingMode();
if (scalingMode != null) {
Mode mode = scalingMode.getMode();
if (ScalingMode.Mode.METRIC.equals(mode)) {
double metricScalingFactor = scalingMode.getMetricScalingFactor();
if (metricScalingFactor != 0) {
// 1 inch = 25,4 millimeter
factor = (dpi * metricScalingFactor) / 25.4;
}
}
}
/**
* All the command classes with static data need to be reset here
*/
private void reset() {
ColourIndexPrecision.reset();
ColourModel.reset();
ColourPrecision.reset();
ColourSelectionMode.reset();
ColourValueExtent.reset();
EdgeWidthSpecificationMode.reset();
IndexPrecision.reset();
IntegerPrecision.reset();
LineWidthSpecificationMode.reset();
MarkerSizeSpecificationMode.reset();
RealPrecision.reset();
RestrictedTextType.reset();
VDCIntegerPrecision.reset();
VDCRealPrecision.reset();
VDCType.reset();
int width = (int)Math.ceil((Math.abs(extent[1].x - extent[0].x) * factor));
int height = (int)Math.ceil((Math.abs(extent[1].y - extent[0].y) * factor));
Messages.getInstance().reset();
}
return new Dimension(width, height);
}
public List<Message> getMessages() {
return Messages.getInstance();
}
public Point2D.Double[] extent() {
for (Command c : this.commands) {
if (c instanceof VDCExtent) {
Point2D.Double[] extent = ((VDCExtent) c).extent();
return extent;
}
}
return null;
}
public void paint(CGMDisplay d) {
for (Command c : this.commands) {
if (filter(c)) {
c.paint(d);
}
}
}
private ScalingMode getScalingMode() {
for (Command c : this.commands) {
if (c instanceof ScalingMode) {
return (ScalingMode)c;
}
}
return null;
}
private boolean filter(Command c) {
return true;
// List<Class<?>> classes = new ArrayList<Class<?>>();
// //classes.add(PolygonElement.class);
// classes.add(Text.class);
// //classes.add(CircleElement.class);
//
// for (Class<?> clazz: classes) {
// if (clazz.isInstance(c))
// return false;
// }
//
// return true;
}
public void showCGMCommands() {
showCGMCommands(System.out);
}
/**
* Returns the size of the CGM graphic.
*
* @return The dimension or null if no {@link VDCExtent} command was found.
*/
public Dimension getSize() {
// default to 96 DPI which is the Microsoft Windows default DPI setting
return getSize(96);
}
public void showCGMCommands(PrintStream stream) {
for (Command c : this.commands) {
stream.println("Command: " + c);
}
}
/**
* Returns the size of the CGM graphic taking into account a specific DPI
* setting
*
* @param dpi
* The DPI value to use
* @return The dimension or null if no {@link VDCExtent} command was found.
*/
public Dimension getSize(double dpi) {
Point2D.Double[] extent = extent();
if (extent == null)
return null;
public List<Command> getCommands() {
return Collections.unmodifiableList(this.commands);
}
double factor = 1;
ScalingMode scalingMode = getScalingMode();
if (scalingMode != null) {
Mode mode = scalingMode.getMode();
if (ScalingMode.Mode.METRIC.equals(mode)) {
double metricScalingFactor = scalingMode
.getMetricScalingFactor();
if (metricScalingFactor != 0) {
// 1 inch = 25,4 millimeter
factor = (dpi * metricScalingFactor) / 25.4;
}
}
}
int width = (int) Math
.ceil((Math.abs(extent[1].x - extent[0].x) * factor));
int height = (int) Math
.ceil((Math.abs(extent[1].y - extent[0].y) * factor));
return new Dimension(width, height);
}
public Point2D.Double[] extent() {
for (Command c : this.commands) {
if (c instanceof VDCExtent) {
Point2D.Double[] extent = ((VDCExtent) c).extent();
return extent;
}
}
return null;
}
private ScalingMode getScalingMode() {
for (Command c : this.commands) {
if (c instanceof ScalingMode) {
return (ScalingMode) c;
}
}
return null;
}
public void showCGMCommands() {
showCGMCommands(System.out);
}
public void showCGMCommands(PrintStream stream) {
for (Command c : this.commands) {
stream.println("Command: " + c);
}
}
public List<Command> getCommands() {
return Collections.unmodifiableList(this.commands);
}
}

View file

@ -3,6 +3,9 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.CharacterHeight;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -15,44 +18,50 @@ import com.raytheon.uf.viz.core.drawables.IFont.Style;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.CharacterHeight;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcCharacterHeight extends CharacterHeight implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcCharacterHeight(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcCharacterHeight(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, com.raytheon.uf.viz.core.drawables.IDescriptor, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
// Only change if different from the current size
if (ib.currentFont.getFontSize() != this.characterHeight) { //TODO
String currentFontNames = ib.currentFont.getFontName();
Style[] styles = ib.currentFont.getStyle();
//ib.currentFont.dispose(); //TODO:recycle after paint
ib.currentFont = target.initializeFont(currentFontNames,
(float) this.characterHeight, styles);
}
}
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* com.raytheon.uf.viz.core.drawables.IDescriptor,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
// Only change if different from the current size
if (ib.currentFont.getFontSize() != this.characterHeight) { // TODO
String currentFontNames = ib.currentFont.getFontName();
Style[] styles = ib.currentFont.getStyle();
// ib.currentFont.dispose(); //TODO:recycle after paint
ib.currentFont = target.initializeFont(currentFontNames,
(float) this.characterHeight, styles);
}
}
}

View file

@ -4,7 +4,7 @@
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.CircleElement;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -13,7 +13,6 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.raytheon.uf.viz.core.DrawableCircle;
import com.raytheon.uf.viz.core.DrawableString;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
@ -21,45 +20,58 @@ import com.raytheon.uf.viz.core.exception.VizException;
/**
* @author bhebbard
*
*
*/
public class NcCircleElement extends CircleElement implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcCircleElement(int ec, int eid, int l, DataInput in) throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcCircleElement(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, com.raytheon.uf.viz.core.drawables.IDescriptor, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
// Used only to draw (teeny) circles to mark lat/lon lines?
// If not, will need to revisit assumptions below... TODO
DrawableCircle dc = new DrawableCircle();
double[] newpoint = ib.scalePoint(this.center.x, this.center.y);
dc.setCoordinates(newpoint[0],newpoint[1]);
dc.radius = this.radius;
//dc.screenRadius = this.radius;
dc.filled = true; //TODO -- SJ says this is what was intended; not encoded in CGM?
dc.numberOfPoints = 6; // 8? 16? lower values improve performance (a lot)
dc.basics.color = ib.currentLineColor; //TODO use currentCircleColor? or...?
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* com.raytheon.uf.viz.core.drawables.IDescriptor,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
// Used only to draw (teeny) circles to mark lat/lon lines?
// If not, will need to revisit assumptions below... TODO
DrawableCircle dc = new DrawableCircle();
double[] newpoint = ib.scalePoint(this.center.x, this.center.y);
dc.setCoordinates(newpoint[0], newpoint[1]);
dc.radius = this.radius;
// dc.screenRadius = this.radius;
dc.filled = true; // TODO -- SJ says this is what was intended; not
// encoded in CGM?
dc.numberOfPoints = 6; // 8? 16? lower values improve performance (a
// lot)
dc.basics.color = ib.currentLineColor; // TODO use currentCircleColor?
// or...?
ib.circles.add(dc);
//target.drawCircle(dc);
//logger.debug("Circle has been drawn -- " + this);
}
// target.drawCircle(dc);
// logger.debug("Circle has been drawn -- " + this);
}
}

View file

@ -3,33 +3,33 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import java.io.*;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.FillColour;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.FillColour;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcFillColour extends FillColour implements INcCommand {
public NcFillColour(int ec, int eid, int l, DataInput in)
public NcFillColour(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
// TODO Auto-generated constructor stub
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps, IDescriptor descriptor, ImageBuilder ib)
throws VizException {
ib.currentFillColor = GempakColor.convertToRGB(this.colorIndex);
}
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
ib.currentFillColor = GempakColor.convertToRGB(this.colorIndex);
}
}

View file

@ -3,7 +3,11 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import java.io.*;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.InteriorStyle;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -13,49 +17,53 @@ import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.InteriorStyle;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcInteriorStyle extends InteriorStyle implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcInteriorStyle(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib)
throws VizException {
switch (this.style) {
case SOLID: //TODO: For now, SOLID is assumed for all filled polygons
break;
case HOLLOW:
case PATTERN:
case HATCH:
case EMPTY:
case GEOMETRIC_PATTERN:
case INTERPOLATED:
logger.warn("Paint not implemented for CGM command: " + this);
break;
}
}
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
switch (this.style) {
case SOLID: // TODO: For now, SOLID is assumed for all filled polygons
break;
case HOLLOW:
case PATTERN:
case HATCH:
case EMPTY:
case GEOMETRIC_PATTERN:
case INTERPOLATED:
logger.warn("Paint not implemented for CGM command: " + this);
break;
}
}
}

View file

@ -3,6 +3,10 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.LineColour;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -11,27 +15,22 @@ import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.LineColour;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcLineColour extends LineColour implements INcCommand {
public NcLineColour(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
public NcLineColour(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor,
ImageBuilder ib) throws VizException {
ib.currentLineColor = GempakColor.convertToRGB(this.colorIndex);
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
ib.currentLineColor = GempakColor.convertToRGB(this.colorIndex);
}
}

View file

@ -3,6 +3,9 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.LineWidth;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -11,35 +14,37 @@ import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.LineWidth;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcLineWidth extends LineWidth implements INcCommand {
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcLineWidth(int ec, int eid, int l, DataInput in) throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcLineWidth(int ec, int eid, int l, DataInput in) throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor,
ImageBuilder ib) throws VizException {
ib.currentLineWidth = this.width / 1.0; // TODO ??
}
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
ib.currentLineWidth = this.width / 1.0; // TODO ??
}
}

View file

@ -3,10 +3,10 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import java.awt.Graphics2D;
import java.awt.geom.Path2D;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.PolygonElement;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.io.DataInput;
import java.io.IOException;
import java.util.ArrayList;
@ -14,7 +14,6 @@ import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.swt.graphics.RGB;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.drawables.IDescriptor;
@ -25,111 +24,113 @@ import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LineString;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.PolygonElement;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcPolygonElement extends PolygonElement implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
static List<double[]> currentDraw = new ArrayList<double[]>();
static List<double[]> currentDraw = new ArrayList<double[]>();
private GeometryFactory gf;
private GeometryFactory gf;
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcPolygonElement(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
gf = new GeometryFactory(); //TODO move!?
// TODO Auto-generated constructor stub
gf = new GeometryFactory(); // TODO move!?
// TODO Auto-generated constructor stub
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib)
throws VizException {
if (ib.shadedShapeReady) return; // work already done
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
PathIterator pi = this.polygon.getPathIterator(null);
while (pi.isDone() == false) {
//processCurrentSegment(pi, shadedShape, ib);
processCurrentSegment(pi, ib.shadedShape, ib);
pi.next();
}
if (currentDraw.size() > 1) {
// Just in case SEG_CLOSE missing at end
//terminatePolygon(shadedShape, ib);
terminatePolygon(ib.shadedShape, ib);
}
currentDraw.clear();
//shadedShape.compile();
//ib.shadedShapes.add(shadedShape);
}
if (ib.shadedShapeReady)
return; // work already done
private void processCurrentSegment(PathIterator pi, IShadedShape shadedShape,
ImageBuilder ib) {
double[] coordinates = new double[6];
int type = pi.currentSegment(coordinates);
switch (type) {
case PathIterator.SEG_MOVETO:
//System.out.println("move to " + coordinates[0] + ", " + coordinates[1]);
currentDraw.clear();
currentDraw.add( ib.scalePoint(coordinates) );
break;
case PathIterator.SEG_LINETO:
//System.out.println("line to " + coordinates[0] + ", " + coordinates[1]);
currentDraw.add( ib.scalePoint(coordinates) );
break;
case PathIterator.SEG_QUADTO:
//System.out.println("quadratic to " + coordinates[0] + ", " + coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3]);
//TODO -- error / not supported
break;
case PathIterator.SEG_CUBICTO:
//System.out.println("cubic to " + coordinates[0] + ", " + coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3] + ", " + coordinates[4] + ", " + coordinates[5]);
//TODO -- error / not supported
break;
case PathIterator.SEG_CLOSE:
terminatePolygon(shadedShape, ib);
break;
default:
break;
}
}
PathIterator pi = this.polygon.getPathIterator(null);
private void terminatePolygon(IShadedShape shadedShape, ImageBuilder ib) {
if (currentDraw.size() > 1) {
Coordinate[] coords = new Coordinate[currentDraw.size()];
for (int j=0; j<currentDraw.size(); j++) {
coords[j] = new Coordinate(currentDraw.get(j)[0],
1000.000 - //TODO why?
currentDraw.get(j)[1]);
}
LineString[] lineStrings = new LineString[] { gf.createLineString(coords) };
shadedShape.addPolygon(lineStrings, ib.currentFillColor);
}
currentDraw.clear();
}
while (pi.isDone() == false) {
// processCurrentSegment(pi, shadedShape, ib);
processCurrentSegment(pi, ib.shadedShape, ib);
pi.next();
}
if (currentDraw.size() > 1) {
// Just in case SEG_CLOSE missing at end
// terminatePolygon(shadedShape, ib);
terminatePolygon(ib.shadedShape, ib);
}
currentDraw.clear();
// shadedShape.compile();
// ib.shadedShapes.add(shadedShape);
}
private void processCurrentSegment(PathIterator pi,
IShadedShape shadedShape, ImageBuilder ib) {
double[] coordinates = new double[6];
int type = pi.currentSegment(coordinates);
switch (type) {
case PathIterator.SEG_MOVETO:
// System.out.println("move to " + coordinates[0] + ", " +
// coordinates[1]);
currentDraw.clear();
currentDraw.add(ib.scalePoint(coordinates));
break;
case PathIterator.SEG_LINETO:
// System.out.println("line to " + coordinates[0] + ", " +
// coordinates[1]);
currentDraw.add(ib.scalePoint(coordinates));
break;
case PathIterator.SEG_QUADTO:
// System.out.println("quadratic to " + coordinates[0] + ", " +
// coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3]);
// TODO -- error / not supported
break;
case PathIterator.SEG_CUBICTO:
// System.out.println("cubic to " + coordinates[0] + ", " +
// coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3] + ", " + coordinates[4]
// + ", " + coordinates[5]);
// TODO -- error / not supported
break;
case PathIterator.SEG_CLOSE:
terminatePolygon(shadedShape, ib);
break;
default:
break;
}
}
private void terminatePolygon(IShadedShape shadedShape, ImageBuilder ib) {
if (currentDraw.size() > 1) {
Coordinate[] coords = new Coordinate[currentDraw.size()];
for (int j = 0; j < currentDraw.size(); j++) {
coords[j] = new Coordinate(currentDraw.get(j)[0], 1000.000 - // TODO
// why?
currentDraw.get(j)[1]);
}
LineString[] lineStrings = new LineString[] { gf
.createLineString(coords) };
shadedShape.addPolygon(lineStrings, ib.currentFillColor);
}
currentDraw.clear();
}
}

View file

@ -1,5 +1,9 @@
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Polyline;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder.WireframeKey;
import java.awt.geom.PathIterator;
import java.io.DataInput;
import java.io.IOException;
@ -15,85 +19,95 @@ import com.raytheon.uf.viz.core.drawables.IWireframeShape;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Polyline;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
public class NcPolyline extends Polyline implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
static List<double[]> currentDraw = new ArrayList<double[]>();
static List<double[]> currentDraw = new ArrayList<double[]>();
public NcPolyline(int ec, int eid, int l, DataInput in) throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
public NcPolyline(int ec, int eid, int l, DataInput in) throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib)
throws VizException {
IWireframeShape wireframeForThisColor = ib.wireframes.get(ib.currentLineColor);
if (wireframeForThisColor == null) {
wireframeForThisColor = target.createWireframeShape(false, descriptor);
ib.wireframes.put(ib.currentLineColor, wireframeForThisColor);
}
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
PathIterator pi = this.path.getPathIterator(null);
WireframeKey key = ib.new WireframeKey(ib.currentLineColor,
ib.currentLineWidth);
while (pi.isDone() == false) {
processCurrentSegment(pi, wireframeForThisColor, ib);
pi.next();
}
// if no close command
if (currentDraw.size() > 1) {
wireframeForThisColor.addLineSegment(currentDraw.toArray(new double[0][0]));
}
currentDraw.clear();
}
public static void processCurrentSegment(PathIterator pi, IWireframeShape wireframeForThisColor, ImageBuilder ib) {
double[] coordinates = new double[6];
int type = pi.currentSegment(coordinates);
switch (type) {
case PathIterator.SEG_MOVETO:
//System.out.println("move to " + coordinates[0] + ", " + coordinates[1]);
if (currentDraw.size() > 1) {
wireframeForThisColor.addLineSegment(currentDraw.toArray(new double[0][0]));
}
currentDraw.clear();
currentDraw.add( ib.scalePoint(coordinates) );
break;
case PathIterator.SEG_LINETO:
//System.out.println("line to " + coordinates[0] + ", " + coordinates[1]);
currentDraw.add( ib.scalePoint(coordinates) );
break;
case PathIterator.SEG_QUADTO:
//System.out.println("quadratic to " + coordinates[0] + ", " + coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3]);
//TODO -- error / not supported
break;
case PathIterator.SEG_CUBICTO:
//System.out.println("cubic to " + coordinates[0] + ", " + coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3] + ", " + coordinates[4] + ", " + coordinates[5]);
//TODO -- error / not supported
break;
case PathIterator.SEG_CLOSE:
//System.out.println("close");
if (currentDraw.size() > 1) {
wireframeForThisColor.addLineSegment(currentDraw.toArray(new double[0][0]));
}
currentDraw.clear();
break;
default:
break;
}
IWireframeShape wireframeForThisKey = ib.wireframes.get(key);
if (wireframeForThisKey == null) {
wireframeForThisKey = target
.createWireframeShape(false, descriptor);
ib.wireframes.put(key, wireframeForThisKey);
}
PathIterator pi = this.path.getPathIterator(null);
while (pi.isDone() == false) {
processCurrentSegment(pi, wireframeForThisKey, ib);
pi.next();
}
// if no close command
if (currentDraw.size() > 1) {
wireframeForThisKey.addLineSegment(currentDraw
.toArray(new double[0][0]));
}
currentDraw.clear();
}
public static void processCurrentSegment(PathIterator pi,
IWireframeShape wireframeForThisKey, ImageBuilder ib) {
double[] coordinates = new double[6];
int type = pi.currentSegment(coordinates);
switch (type) {
case PathIterator.SEG_MOVETO:
// System.out.println("move to " + coordinates[0] + ", " +
// coordinates[1]);
if (currentDraw.size() > 1) {
wireframeForThisKey.addLineSegment(currentDraw
.toArray(new double[0][0]));
}
currentDraw.clear();
currentDraw.add(ib.scalePoint(coordinates));
break;
case PathIterator.SEG_LINETO:
// System.out.println("line to " + coordinates[0] + ", " +
// coordinates[1]);
currentDraw.add(ib.scalePoint(coordinates));
break;
case PathIterator.SEG_QUADTO:
// System.out.println("quadratic to " + coordinates[0] + ", " +
// coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3]);
// TODO -- error / not supported
break;
case PathIterator.SEG_CUBICTO:
// System.out.println("cubic to " + coordinates[0] + ", " +
// coordinates[1] + ", "
// + coordinates[2] + ", " + coordinates[3] + ", " + coordinates[4]
// + ", " + coordinates[5]);
// TODO -- error / not supported
break;
case PathIterator.SEG_CLOSE:
// System.out.println("close");
if (currentDraw.size() > 1) {
wireframeForThisKey.addLineSegment(currentDraw
.toArray(new double[0][0]));
}
currentDraw.clear();
break;
default:
break;
}
}
}

View file

@ -4,7 +4,7 @@
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Text;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -38,13 +38,19 @@ public class NcText extends Text implements INcCommand {
* @throws IOException
*/
public NcText(int ec, int eid, int l, DataInput in) throws IOException {
// To handle little-endian strings, we need to bump an odd length ("l") parameter
// up one to make it even (ending on two-byte CGM word boundary), so that we
// get the last character. (Will be flipped into place later.) Note that
// special case of l=31 indicates "long form" (string length >=31 char, to
// be specified in following 2-byte integer), so the parent constructor for
// Command has also been modified to interpret l=32 fed up to it as a signal
// to handle as l=31, then "bump" the long-form length it reads (from next
// To handle little-endian strings, we need to bump an odd length ("l")
// parameter
// up one to make it even (ending on two-byte CGM word boundary), so
// that we
// get the last character. (Will be flipped into place later.) Note that
// special case of l=31 indicates "long form" (string length >=31 char,
// to
// be specified in following 2-byte integer), so the parent constructor
// for
// Command has also been modified to interpret l=32 fed up to it as a
// signal
// to handle as l=31, then "bump" the long-form length it reads (from
// next
// 2 bytes) up to even value if needed.
super(ec, eid, (l + 1) / 2 * 2, in);
}

View file

@ -3,6 +3,9 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.TextAlignment;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -14,91 +17,99 @@ import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.TextAlignment;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcTextAlignment extends TextAlignment implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcTextAlignment(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcTextAlignment(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, com.raytheon.uf.viz.core.drawables.IDescriptor, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
// Map/convert CGM-style text alignments to their IGraphicsTarget equivalents.
switch (this.horizontalAlignment) {
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* com.raytheon.uf.viz.core.drawables.IDescriptor,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
// Map/convert CGM-style text alignments to their IGraphicsTarget
// equivalents.
switch (this.horizontalAlignment) {
case NORMAL_HORIZONTAL:
//TODO: Following is sort of a hack, to deal with the way legacy
// NTRANS metafiles are created by the NC driver code. A horizontal
// alignment of CENTER appears to be coded (intentionally or otherwise)
// in the legacy generated CGM by a *vertical* alignment value of CAP.
// TODO: Following is sort of a hack, to deal with the way legacy
// NTRANS metafiles are created by the NC driver code. A horizontal
// alignment of CENTER appears to be coded (intentionally or
// otherwise)
// in the legacy generated CGM by a *vertical* alignment value of
// CAP.
// Might want to investigate, and possibly bring legacy code to CGM
// compliance.
if (this.verticalAlignment == TextAlignment.VerticalAlignment.CAP) {
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.CENTER;
}
else {
} else {
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.LEFT;
}
break;
case LEFT:
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.LEFT;
break;
case CONTINOUS_HORIZONTAL: //TODO??
case CENTRE:
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.CENTER;
break;
case RIGHT:
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.RIGHT;
break;
default:
//TODO fail
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.CENTER;
break;
}
switch (this.verticalAlignment) {
case TOP:
case CAP: //TODO??
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.TOP;
case LEFT:
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.LEFT;
break;
case CONTINOUS_HORIZONTAL: // TODO??
case CENTRE:
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.CENTER;
break;
case RIGHT:
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.RIGHT;
break;
default:
// TODO fail
ib.horizontalAlignment = IGraphicsTarget.HorizontalAlignment.CENTER;
break;
}
switch (this.verticalAlignment) {
case TOP:
case CAP: // TODO??
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.TOP;
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.BOTTOM;
break;
case HALF:
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.MIDDLE;
case HALF:
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.MIDDLE;
break;
case NORMAL_VERTICAL:
case CONTINOUS_VERTICAL: //TODO??
case BASE: //TODO??
case BOTTOM:
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.BOTTOM;
case NORMAL_VERTICAL:
case CONTINOUS_VERTICAL: // TODO??
case BASE: // TODO??
case BOTTOM:
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.BOTTOM;
break;
default:
//TODO fail
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.BOTTOM;
break;
}
}
default:
// TODO fail
ib.verticalAlignment = IGraphicsTarget.VerticalAlignment.BOTTOM;
break;
}
}
}

View file

@ -3,6 +3,10 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.TextColour;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -11,36 +15,39 @@ import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.TextColour;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcTextColour extends TextColour implements INcCommand {
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcTextColour(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcTextColour(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, com.raytheon.uf.viz.core.drawables.IDescriptor, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
ib.currentTextColor = GempakColor.convertToRGB(this.colorIndex);
}
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* com.raytheon.uf.viz.core.drawables.IDescriptor,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
ib.currentTextColor = GempakColor.convertToRGB(this.colorIndex);
}
}

View file

@ -3,6 +3,9 @@
*/
package gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.TextFontIndex;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder;
import java.io.DataInput;
import java.io.IOException;
@ -14,41 +17,48 @@ import com.raytheon.uf.viz.core.drawables.IDescriptor;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.TextFontIndex;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder;
/**
* @author bhebbard
*
*
*/
public class NcTextFontIndex extends TextFontIndex implements INcCommand {
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private static boolean notWarned = true;
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcTextFontIndex(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
private static boolean notWarned = true;
/* (non-Javadoc)
* @see gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf.viz.core.IGraphicsTarget, com.raytheon.uf.viz.core.drawables.PaintProperties, com.raytheon.uf.viz.core.drawables.IDescriptor, gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
if (notWarned) {
logger.warn("Paint not implemented for CGM command: " + this);
notWarned = false;
}
}
/**
* @param ec
* @param eid
* @param l
* @param in
* @throws IOException
*/
public NcTextFontIndex(int ec, int eid, int l, DataInput in)
throws IOException {
super(ec, eid, l, in);
// TODO Auto-generated constructor stub
}
/*
* (non-Javadoc)
*
* @see
* gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand#paint(com.raytheon.uf
* .viz.core.IGraphicsTarget,
* com.raytheon.uf.viz.core.drawables.PaintProperties,
* com.raytheon.uf.viz.core.drawables.IDescriptor,
* gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.NtransResource.ImageBuilder)
*/
@Override
public void paint(IGraphicsTarget target, PaintProperties paintProps,
IDescriptor descriptor, ImageBuilder ib) throws VizException {
if (notWarned) {
logger.warn("Paint not implemented for CGM command: " + this);
notWarned = false;
}
}
}

View file

@ -0,0 +1,172 @@
/**
* 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.rsc.ntrans.rsc;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.swt.graphics.RGB;
import com.raytheon.uf.viz.core.DrawableCircle;
import com.raytheon.uf.viz.core.DrawableString;
import com.raytheon.uf.viz.core.IGraphicsTarget.HorizontalAlignment;
import com.raytheon.uf.viz.core.IGraphicsTarget.TextStyle;
import com.raytheon.uf.viz.core.IGraphicsTarget.VerticalAlignment;
import com.raytheon.uf.viz.core.drawables.IFont;
import com.raytheon.uf.viz.core.drawables.IShadedShape;
import com.raytheon.uf.viz.core.drawables.IWireframeShape;
/**
* TODO Add Description
*
* <pre>
*
* SOFTWARE HISTORY
*
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* Mar 30, 2014 bhebbard Initial creation
*
* </pre>
*
* @author bhebbard
* @version 1.0
*/
// ------------------------------------------------------------
public class ImageBuilder {
// This class holds the state of the image while it's under
// construction by sequential execution of the CGM commands.
public class WireframeKey {
public RGB color;
public double width;
public WireframeKey(RGB color, double width) {
this.color = color;
this.width = width;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + getOuterType().hashCode();
result = prime * result + ((color == null) ? 0 : color.hashCode());
long temp;
temp = Double.doubleToLongBits(width);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
WireframeKey other = (WireframeKey) obj;
if (!getOuterType().equals(other.getOuterType()))
return false;
if (color == null) {
if (other.color != null)
return false;
} else if (!color.equals(other.color))
return false;
if (Double.doubleToLongBits(width) != Double
.doubleToLongBits(other.width))
return false;
return true;
}
private ImageBuilder getOuterType() {
return ImageBuilder.this;
}
}
public Map<WireframeKey, IWireframeShape> wireframes = new HashMap<WireframeKey, IWireframeShape>();
public RGB currentLineColor = new RGB(255, 255, 255);
public double currentLineWidth = 1.0;
public List<DrawableString> strings = new ArrayList<DrawableString>();
public RGB currentTextColor = new RGB(255, 255, 255);
public IFont currentFont = null;
public TextStyle textStyle = TextStyle.NORMAL;
public HorizontalAlignment horizontalAlignment = HorizontalAlignment.CENTER;
public VerticalAlignment verticalAlignment = VerticalAlignment.TOP;
public List<DrawableCircle> circles = new ArrayList<DrawableCircle>();
public RGB currentCircleColor = new RGB(255, 0, 0);
public IShadedShape shadedShape;
public RGB currentFillColor = new RGB(0, 255, 0);
public boolean shadedShapeReady = false; // if true, shaded shape
// constructed on
// first paint of this frame
// are already saved
// (in PictureInfo), and so we
// can skip
// regeneration on subsequent
// paints
public double scale = 1.0;
public double scaleNoZoom = 1.0;
public double[] scalePoint(double[] oldpoint) {
return scalePoint(oldpoint[0], oldpoint[1]);
}
public double[] scalePointNoZoom(double[] oldpoint) {
return scalePointNoZoom(oldpoint[0], oldpoint[1]);
}
public double[] scalePoint(double x, double y) {
double[] newpoint = new double[2];
newpoint[0] = x * scale;
newpoint[1] = 1000.000 - y * scale; // TODO: Avoid hardcoding 1000
return newpoint;
}
public double[] scalePointNoZoom(double x, double y) {
double[] newpoint = new double[2];
newpoint[0] = x * scaleNoZoom; // TODO plus translation
newpoint[1] = 1000.000 - y * scaleNoZoom; // TODO plus translation
return newpoint;
}
}

View file

@ -4,12 +4,12 @@ import gov.noaa.nws.ncep.common.dataplugin.ntrans.NtransRecord;
import gov.noaa.nws.ncep.viz.common.ui.NmapCommon;
import gov.noaa.nws.ncep.viz.resources.AbstractNatlCntrsResource;
import gov.noaa.nws.ncep.viz.resources.INatlCntrsResource;
import gov.noaa.nws.ncep.viz.resources.AbstractNatlCntrsResource.IRscDataObject;
import gov.noaa.nws.ncep.viz.resources.manager.ResourceName;
import gov.noaa.nws.ncep.viz.rsc.ntrans.jcgm.Command;
import gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.INcCommand;
import gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.NcCGM;
import gov.noaa.nws.ncep.viz.rsc.ntrans.ncgm.NcText;
import gov.noaa.nws.ncep.viz.rsc.ntrans.rsc.ImageBuilder.WireframeKey;
import gov.noaa.nws.ncep.viz.ui.display.NCNonMapDescriptor;
import java.io.ByteArrayInputStream;
@ -18,34 +18,23 @@ import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
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.eclipse.swt.graphics.RGB;
import com.raytheon.uf.common.dataplugin.HDF5Util;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType;
import com.raytheon.uf.common.datastorage.DataStoreFactory;
import com.raytheon.uf.common.datastorage.IDataStore;
import com.raytheon.uf.common.datastorage.Request;
import com.raytheon.uf.common.datastorage.StorageException;
import com.raytheon.uf.common.datastorage.records.IDataRecord;
import com.raytheon.uf.common.time.DataTime;
import com.raytheon.uf.viz.core.DrawableCircle;
import com.raytheon.uf.viz.core.IExtent;
import com.raytheon.uf.viz.core.IGraphicsTarget;
import com.raytheon.uf.viz.core.PixelExtent;
import com.raytheon.uf.viz.core.rsc.LoadProperties;
import com.raytheon.uf.viz.core.rsc.ResourceType;
import com.raytheon.uf.viz.core.DrawableCircle;
import com.raytheon.uf.viz.core.DrawableString;
import com.raytheon.uf.viz.core.IGraphicsTarget.HorizontalAlignment;
import com.raytheon.uf.viz.core.IGraphicsTarget.TextStyle;
import com.raytheon.uf.viz.core.IGraphicsTarget.VerticalAlignment;
import com.raytheon.uf.viz.core.catalog.LayerProperty;
import com.raytheon.uf.viz.core.catalog.ScriptCreator;
import com.raytheon.uf.viz.core.comm.Connector;
@ -55,12 +44,14 @@ import com.raytheon.uf.viz.core.drawables.IShadedShape;
import com.raytheon.uf.viz.core.drawables.IWireframeShape;
import com.raytheon.uf.viz.core.drawables.PaintProperties;
import com.raytheon.uf.viz.core.exception.VizException;
import com.raytheon.uf.viz.core.rsc.LoadProperties;
import com.raytheon.uf.viz.core.rsc.ResourceType;
/**
* NtransResource - Resource for Display of NTRANS Metafiles.
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*
* This code has been developed by the SIB for use in the AWIPS2 system.
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
@ -70,472 +61,447 @@ import com.raytheon.uf.viz.core.exception.VizException;
* 30 Apr 2013 838 B. Hebbard IOC version (for OB13.4.1)
* 30 May 2013 838 B. Hebbard Update for compatibility with changes by RTS in OB13.3.1
* [ DataStoreFactory.getDataStore(...) parameter ]
*
*
* </pre>
*
* @author bhebbard
* @author bhebbard
* @version 1.0
*/
public class NtransResource extends AbstractNatlCntrsResource<NtransResourceData, NCNonMapDescriptor>
implements INatlCntrsResource {
private NtransResourceData ntransResourceData;
public class NtransResource extends
AbstractNatlCntrsResource<NtransResourceData, NCNonMapDescriptor>
implements INatlCntrsResource {
private String legendStr = "NTRANS "; // init so not-null
private NtransResourceData ntransResourceData;
private IFont font = null;
private String legendStr = "NTRANS "; // init so not-null
private final Log logger = LogFactory.getLog(this.getClass()); //TODO static better??
private IFont font = null;
private class NtransDisplayablePictureInfo { // CGM calls it a "picture".
// This is just a container holding the ready-to-paint information for
// a single NTRANS image.
NtransRecord ntransRecord ; // the metadata record (PDO)
NcCGM cgm; // constructed "jcgm" representation of the image
public IShadedShape shadedShape; // shaded shapes (filled polygons) get special
// handling due to memory (heap runaway) issues;
// once generated (at first paint), cache here
// for future paints, instead of regenerating each time
public NtransDisplayablePictureInfo(NtransRecord nr, NcCGM nc) {
ntransRecord = nr;
cgm = nc;
shadedShape = null;
}
public void dispose() {
if (shadedShape != null) {
shadedShape.dispose();
}
}
}
private final Log logger = LogFactory.getLog(this.getClass()); // TODO
// static
// better??
private class FrameData extends AbstractFrameData {
// FrameData holds the displayable information for a single frame (time).
NtransDisplayablePictureInfo pictureInfo;
private class NtransDisplayablePictureInfo { // CGM calls it a "picture".
// This is just a container holding the ready-to-paint information for
// a single NTRANS image.
NtransRecord ntransRecord; // the metadata record (PDO)
public FrameData(DataTime frameTime, int timeInt) {
super( frameTime, timeInt );
}
NcCGM cgm; // constructed "jcgm" representation of the image
public boolean updateFrameData(IRscDataObject rscDataObj) {
if( !(rscDataObj instanceof DfltRecordRscDataObj) ) {
logger.error("NtransResource.updateFrameData expecting DfltRecordRscDataObj "
+ " instead of: " + rscDataObj.getClass().getName() );
return false;
}
public IShadedShape shadedShape; // shaded shapes (filled polygons) get
// special
// handling due to memory (heap
// runaway) issues;
// once generated (at first paint),
// cache here
// for future paints, instead of
// regenerating each time
// TODO : check that the cycle times match.
if( pictureInfo != null ) {
System.out.println("adding record to frame that has already been populated");
// add code here to check if the new data is a better time match. if not then discard and
// if so dispose of the existing data and process the new record
return false;
}
// Get PDO from the given RDO
DfltRecordRscDataObj ntransRDO = (DfltRecordRscDataObj) rscDataObj;
NtransRecord nr = (NtransRecord) ntransRDO.getPDO();
// Get image data HDF5.
long t0 = System.currentTimeMillis();
byte[] imageBytes = getCgmFromNtrans(nr);
long t1 = System.currentTimeMillis();
if (imageBytes == null) {
logger.error("NtransResource.updateFrameData imageBytes from NtransRecord is null ");
return false;
}
// Fix endianess if needed
boolean flipped = false;
if (imageBytes[0] == 96) { //TODO clean up and/or move to decoder?
imageBytes = shuffleByteArray(imageBytes);
flipped = true;
}
// Construct "jcgm" representation of the image
NcCGM cgm = new NcCGM();
InputStream is = new ByteArrayInputStream(imageBytes);
DataInput di = new DataInputStream(is);
try {
long t2 = System.currentTimeMillis();
cgm.read(di);
long t3 = System.currentTimeMillis();
logger.info("CGM image " + nr.getImageByteCount() +
" bytes retrieved from HDF5 in " + (t1-t0) + " ms"
+ " and parsed in " + (t3-t2) + " ms");
} catch (Exception e) {
logger.info("CGM image " + nr.getImageByteCount() +
" bytes retrieved from HDF5 in " + (t1-t0) + " ms");
logger.error("EXCEPTION occurred interpreting CGM"
+ " for metafile " + nr.getMetafileName()
+ " product " + nr.getProductName());
e.printStackTrace();
}
// Endianess revisited
if (flipped) { // if we shuffled the bytes before parsing...
flipStrings(cgm); // ...then unshuffle the strings (now we know where they are)
}
//TODO Add optional (cool) debug dump of CGM representation
// cgm.showCGMCommands();
// Save away just the info needed to draw this frame
pictureInfo = new NtransDisplayablePictureInfo(nr, cgm);
return true;
public NtransDisplayablePictureInfo(NtransRecord nr, NcCGM nc) {
ntransRecord = nr;
cgm = nc;
shadedShape = null;
}
private void flipStrings(NcCGM cgm) {
for (Command c : cgm.getCommands()) {
if (c instanceof NcText) {
NcText nct = (NcText) c;
nct.flipString();
}
}
}
private byte[] getCgmFromNtrans(NtransRecord nr) {
// Given the NcscatRecord, locate the associated HDF5 data...
File location = HDF5Util.findHDF5Location(nr);
//TODO... Investigate: Why is the following statement needed?
// Starting in OB13.5.3, the PDO (nr) has a non-null, but bogus,
// value in its dataURI field at this point (and earlier,
// as soon as it is deserialized after return from the metadata
// query). nr.getDataURI() below will get this bad value, leading
// to failure on the ds.retrieve(...). Instead we force it to
// synthesize the dataURI -- which getDataURI() does correctly --
// by setting the field to null first. But why is this happening,
// and why only in OB13.5.3, and why only for some resources...? (bh)
// (see also NCSCAT resource)
nr.setDataURI(null); // force it to construct one
String group = nr.getDataURI();
//String uri = nr.getDataURI();
String dataset = "NTRANS";
// get filename and directory for IDataStore
//String dir = nr.getHDFPathProvider().getHDFPath(nr.getPluginName(), nr);
//String filename = nr.getHDFPathProvider().getHDFFileName(nr.getPluginName(), nr);
//File file = new File(dir, filename);
// ...and retrieve it
IDataStore ds = DataStoreFactory.getDataStore(location);
IDataRecord dr = null;
//IDataRecord[] dr;
try {
dr = ds.retrieve(group, dataset, Request.ALL);
//dr = ds.retrieve(uri);
} catch (FileNotFoundException e) {
logger.error("[EXCEPTION occurred retrieving CGM"
+ " for metafile " + nr.getMetafileName()
+ " product " + nr.getProductName() + "]");
e.printStackTrace();
return null;
} catch (StorageException e) {
logger.error("[EXCEPTION occurred retrieving CGM"
+ " for metafile " + nr.getMetafileName()
+ " product " + nr.getProductName() + "]");
e.printStackTrace();
return null;
}
//return (byte[]) dr[0].getDataObject();
return (byte[]) dr.getDataObject();
}
public void dispose() {
if (pictureInfo != null) {
pictureInfo.dispose();
}
super.dispose();
}
public void dispose() {
if (shadedShape != null) {
shadedShape.dispose();
}
}
}
// ------------------------------------------------------------
public class ImageBuilder {
// This class holds the state of the image while it's under
// construction by sequential execution of the CGM commands.
public Map<RGB,IWireframeShape> wireframes = new HashMap<RGB,IWireframeShape>();
public RGB currentLineColor = new RGB(255,255,255);
public double currentLineWidth = 1.0;
public List<DrawableString> strings = new ArrayList<DrawableString>();
public RGB currentTextColor = new RGB(255,255,255);
public IFont currentFont = null;
public TextStyle textStyle = TextStyle.NORMAL;
public HorizontalAlignment horizontalAlignment = HorizontalAlignment.CENTER;
public VerticalAlignment verticalAlignment = VerticalAlignment.TOP;
public List<DrawableCircle> circles = new ArrayList<DrawableCircle>();
public RGB currentCircleColor = new RGB(255, 0, 0);
public IShadedShape shadedShape;
public RGB currentFillColor = new RGB(0, 255, 0);
public boolean shadedShapeReady = false; // if true, shaded shape constructed on
// first paint of this frame are already saved
// (in PictureInfo), and so we can skip
// regeneration on subsequent paints
public double scale = 1.0;
public double scaleNoZoom = 1.0;
public double[] scalePoint (double[] oldpoint) {
return scalePoint (oldpoint[0],oldpoint[1]);
}
public double[] scalePointNoZoom (double[] oldpoint) {
return scalePointNoZoom (oldpoint[0],oldpoint[1]);
}
public double[] scalePoint(double x, double y) {
double[] newpoint = new double[2];
newpoint[0] = x * scale;
newpoint[1] = 1000.000 - y * scale; // TODO: Avoid hardcoding 1000
return newpoint;
}
private class FrameData extends AbstractFrameData {
public double[] scalePointNoZoom(double x, double y) {
double[] newpoint = new double[2];
newpoint[0] = x * scaleNoZoom; // TODO plus translation
newpoint[1] = 1000.000 - y * scaleNoZoom; // TODO plus translation
return newpoint;
}
// FrameData holds the displayable information for a single frame
// (time).
NtransDisplayablePictureInfo pictureInfo;
public FrameData(DataTime frameTime, int timeInt) {
super(frameTime, timeInt);
}
public boolean updateFrameData(IRscDataObject rscDataObj) {
if (!(rscDataObj instanceof DfltRecordRscDataObj)) {
logger.error("NtransResource.updateFrameData expecting DfltRecordRscDataObj "
+ " instead of: " + rscDataObj.getClass().getName());
return false;
}
// TODO : check that the cycle times match.
if (pictureInfo != null) {
System.out
.println("adding record to frame that has already been populated");
// add code here to check if the new data is a better time
// match. if not then discard and
// if so dispose of the existing data and process the new record
return false;
}
// Get PDO from the given RDO
DfltRecordRscDataObj ntransRDO = (DfltRecordRscDataObj) rscDataObj;
NtransRecord nr = (NtransRecord) ntransRDO.getPDO();
// Get image data HDF5.
long t0 = System.currentTimeMillis();
byte[] imageBytes = getCgmFromNtrans(nr);
long t1 = System.currentTimeMillis();
if (imageBytes == null) {
logger.error("NtransResource.updateFrameData imageBytes from NtransRecord is null ");
return false;
}
// Fix endianess if needed
boolean flipped = false;
if (imageBytes[0] == 96) { // TODO clean up and/or move to decoder?
imageBytes = shuffleByteArray(imageBytes);
flipped = true;
}
// Construct "jcgm" representation of the image
NcCGM cgm = new NcCGM();
InputStream is = new ByteArrayInputStream(imageBytes);
DataInput di = new DataInputStream(is);
try {
long t2 = System.currentTimeMillis();
cgm.read(di);
long t3 = System.currentTimeMillis();
logger.info("CGM image " + nr.getImageByteCount()
+ " bytes retrieved from HDF5 in " + (t1 - t0) + " ms"
+ " and parsed in " + (t3 - t2) + " ms");
} catch (Exception e) {
logger.info("CGM image " + nr.getImageByteCount()
+ " bytes retrieved from HDF5 in " + (t1 - t0) + " ms");
logger.error("EXCEPTION occurred interpreting CGM"
+ " for metafile " + nr.getMetafileName() + " product "
+ nr.getProductName());
e.printStackTrace();
}
// Endianess revisited
if (flipped) { // if we shuffled the bytes before parsing...
flipStrings(cgm); // ...then unshuffle the strings (now we know
// where they are)
}
// TODO Add optional (cool) debug dump of CGM representation
// cgm.showCGMCommands();
// Save away just the info needed to draw this frame
pictureInfo = new NtransDisplayablePictureInfo(nr, cgm);
return true;
}
private void flipStrings(NcCGM cgm) {
for (Command c : cgm.getCommands()) {
if (c instanceof NcText) {
NcText nct = (NcText) c;
nct.flipString();
}
}
}
private byte[] getCgmFromNtrans(NtransRecord nr) {
// Given the NcscatRecord, locate the associated HDF5 data...
File location = HDF5Util.findHDF5Location(nr);
// TODO... Investigate: Why is the following statement needed?
// Starting in OB13.5.3, the PDO (nr) has a non-null, but bogus,
// value in its dataURI field at this point (and earlier,
// as soon as it is deserialized after return from the metadata
// query). nr.getDataURI() below will get this bad value, leading
// to failure on the ds.retrieve(...). Instead we force it to
// synthesize the dataURI -- which getDataURI() does correctly --
// by setting the field to null first. But why is this happening,
// and why only in OB13.5.3, and why only for some resources...?
// (bh)
// (see also NCSCAT resource)
nr.setDataURI(null); // force it to construct one
String group = nr.getDataURI();
// String uri = nr.getDataURI();
String dataset = "NTRANS";
// get filename and directory for IDataStore
// String dir =
// nr.getHDFPathProvider().getHDFPath(nr.getPluginName(), nr);
// String filename =
// nr.getHDFPathProvider().getHDFFileName(nr.getPluginName(), nr);
// File file = new File(dir, filename);
// ...and retrieve it
IDataStore ds = DataStoreFactory.getDataStore(location);
IDataRecord dr = null;
// IDataRecord[] dr;
try {
dr = ds.retrieve(group, dataset, Request.ALL);
// dr = ds.retrieve(uri);
} catch (FileNotFoundException e) {
logger.error("[EXCEPTION occurred retrieving CGM"
+ " for metafile " + nr.getMetafileName() + " product "
+ nr.getProductName() + "]");
e.printStackTrace();
return null;
} catch (StorageException e) {
logger.error("[EXCEPTION occurred retrieving CGM"
+ " for metafile " + nr.getMetafileName() + " product "
+ nr.getProductName() + "]");
e.printStackTrace();
return null;
}
// return (byte[]) dr[0].getDataObject();
return (byte[]) dr.getDataObject();
}
public void dispose() {
if (pictureInfo != null) {
pictureInfo.dispose();
}
super.dispose();
}
}
// ------------------------------------------------------------
// ------------------------------------------------------------
/**
* Create an NTRANS Metafile display resource.
*
* @throws VizException
*/
public NtransResource(NtransResourceData resourceData,
LoadProperties loadProperties) throws VizException {
super(resourceData, loadProperties);
ntransResourceData = (NtransResourceData) resourceData;
LoadProperties loadProperties) throws VizException {
super(resourceData, loadProperties);
ntransResourceData = (NtransResourceData) resourceData;
// set the legend from the metafileName and productName
// NOTE : this assumes that the request type of EQUALS (ie only one kind of metafileName and productName) (??)
// NOTE : this assumes that the request type of EQUALS (ie only one kind
// of metafileName and productName) (??)
//
if( ntransResourceData.getMetadataMap().containsKey("metafileName") &&
ntransResourceData.getMetadataMap().containsKey("productName") ) {
legendStr =
" " + ntransResourceData.getMetadataMap().get("metafileName").getConstraintValue() +
" / " + ntransResourceData.getMetadataMap().get("productName").getConstraintValue();
if (ntransResourceData.getMetadataMap().containsKey("metafileName")
&& ntransResourceData.getMetadataMap().containsKey(
"productName")) {
legendStr = " "
+ ntransResourceData.getMetadataMap().get("metafileName")
.getConstraintValue()
+ " / "
+ ntransResourceData.getMetadataMap().get("productName")
.getConstraintValue();
}
}
protected AbstractFrameData createNewFrame( DataTime frameTime, int timeInt ) {
return (AbstractFrameData) new FrameData( frameTime, timeInt );
protected AbstractFrameData createNewFrame(DataTime frameTime, int timeInt) {
return (AbstractFrameData) new FrameData(frameTime, timeInt);
}
// query all the data in the db matching the request constraints (ie modelName, metaFile, and productName)
// query all the data in the db matching the request constraints (ie
// modelName, metaFile, and productName)
// and also match the selected cycle time.
//
//
public void initResource(IGraphicsTarget grphTarget) throws VizException {
// set initial display values from resource attributes (as if after modification)
//resourceAttrsModified();
long t0 = System.currentTimeMillis();
ResourceName rscName = getResourceData().getResourceName();
// set the constraints for the query.
String[] dts = rscName.getCycleTime().toString().split(" ");
String cycleTimeStr = dts[0] + " " + dts[1].substring(0, dts[1].length()-2);
// set initial display values from resource attributes (as if after
// modification)
// resourceAttrsModified();
long t0 = System.currentTimeMillis();
HashMap<String, RequestConstraint> reqConstraintsMap =
new HashMap<String, RequestConstraint>( ntransResourceData.getMetadataMap() );
RequestConstraint timeConstraint = new RequestConstraint( cycleTimeStr );
reqConstraintsMap.put("dataTime.refTime", timeConstraint );
ResourceName rscName = getResourceData().getResourceName();
LayerProperty prop = new LayerProperty();
prop.setDesiredProduct(ResourceType.PLAN_VIEW);
prop.setEntryQueryParameters( reqConstraintsMap, false);
prop.setNumberOfImages(15000); // TODO: max # records ?? should we cap this ?
String script = null;
script = ScriptCreator.createScript(prop);
// set the constraints for the query.
String[] dts = rscName.getCycleTime().toString().split(" ");
String cycleTimeStr = dts[0] + " "
+ dts[1].substring(0, dts[1].length() - 2);
if (script == null)
return;
HashMap<String, RequestConstraint> reqConstraintsMap = new HashMap<String, RequestConstraint>(
ntransResourceData.getMetadataMap());
Object[] pdoList = Connector.getInstance().connect(script, null, 60000);
RequestConstraint timeConstraint = new RequestConstraint(cycleTimeStr);
reqConstraintsMap.put("dataTime.refTime", timeConstraint);
for( Object pdo : pdoList ) {
for( IRscDataObject dataObject : processRecord( pdo ) ) {
newRscDataObjsQueue.add(dataObject);
}
}
LayerProperty prop = new LayerProperty();
prop.setDesiredProduct(ResourceType.PLAN_VIEW);
prop.setEntryQueryParameters(reqConstraintsMap, false);
prop.setNumberOfImages(15000); // TODO: max # records ?? should we cap
// this ?
String script = null;
script = ScriptCreator.createScript(prop);
//
setAllFramesAsPopulated();
logger.info("Metadata records for " + this.newRscDataObjsQueue.size() +
" images retrieved from DB in " +
(System.currentTimeMillis()-t0) + " ms");
if (script == null)
return;
Object[] pdoList = Connector.getInstance().connect(script, null, 60000);
for (Object pdo : pdoList) {
for (IRscDataObject dataObject : processRecord(pdo)) {
newRscDataObjsQueue.add(dataObject);
}
}
//
setAllFramesAsPopulated();
logger.info("Metadata records for " + this.newRscDataObjsQueue.size()
+ " images retrieved from DB in "
+ (System.currentTimeMillis() - t0) + " ms");
}
public void paintFrame(AbstractFrameData frameData, IGraphicsTarget target, PaintProperties paintProps) throws VizException {
public void paintFrame(AbstractFrameData frameData, IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
FrameData fd = (FrameData) frameData;
FrameData fd = (FrameData) frameData;
if ( target != null && paintProps != null ) {
NtransDisplayablePictureInfo pictureInfo = fd.pictureInfo;
if (pictureInfo == null) return;
if (target != null && paintProps != null) {
NtransDisplayablePictureInfo pictureInfo = fd.pictureInfo;
// Paint it
if (this.font == null) {
this.font = target.initializeFont("Monospace", 12, new IFont.Style[] { Style.BOLD});
}
ImageBuilder ib = new ImageBuilder();
ib.currentFont = this.font;
ib.scale = 1000.000 / (double) pictureInfo.ntransRecord.getImageSizeX(); //TODO avoid hardcoding 1000
if (pictureInfo.shadedShape != null) {
// if we've saved shaded shapes from a previous paint, NcPolygonElement
// can skip generating them all over again
ib.shadedShapeReady = true;
}
else {
ib.shadedShape = target.createShadedShape(
false, // mutable
descriptor.getGridGeometry(),
false); // tesselate
}
if (pictureInfo == null)
return;
double screenToWorldRatio = paintProps.getCanvasBounds().width
/ paintProps.getView().getExtent().getWidth();
ib.scaleNoZoom = ib.scale / screenToWorldRatio;
ib.scaleNoZoom = ib.scale * paintProps.getZoomLevel();
// Paint it
if (this.font == null) {
this.font = target.initializeFont("Monospace", 12,
new IFont.Style[] { Style.BOLD });
}
ImageBuilder ib = new ImageBuilder();
ib.currentFont = this.font;
ib.scale = 1000.000 / (double) pictureInfo.ntransRecord
.getImageSizeX(); // TODO avoid hardcoding 1000
if (pictureInfo.shadedShape != null) {
// if we've saved shaded shapes from a previous paint,
// NcPolygonElement
// can skip generating them all over again
ib.shadedShapeReady = true;
} else {
ib.shadedShape = target.createShadedShape(false, // mutable
descriptor.getGridGeometry(), false); // tesselate
}
double screenToWorldRatio = paintProps.getCanvasBounds().width
/ paintProps.getView().getExtent().getWidth();
ib.scaleNoZoom = ib.scale / screenToWorldRatio;
ib.scaleNoZoom = ib.scale * paintProps.getZoomLevel();
IExtent screenExtent = paintProps.getView().getExtent();
IExtent mapExtent = new PixelExtent(descriptor.getGridGeometry().getGridRange());
IExtent mapExtent = new PixelExtent(descriptor.getGridGeometry()
.getGridRange());
for (Command c : pictureInfo.cgm.getCommands()) {
if (c instanceof INcCommand) {
((INcCommand) c).paint(target, paintProps, descriptor, ib);
}
}
// Shaded Shape (filled polygons) was deferred. Paint it now.
// if first paint of this image, save away shaded shape for future use
if (! ib.shadedShapeReady /* OR pictureInfo.shadedShape == null */) {
ib.shadedShape.compile();
//pictureInfo.completedShadedShapes = ib.shadedShapes.toArray(new IShadedShape[ib.shadedShapes.size()]);
pictureInfo.shadedShape = ib.shadedShape;
ib.shadedShapeReady = true;
}
float alpha = 1.0f; //TODO verify
float brightness = 1.0f;
target.drawShadedShape(pictureInfo.shadedShape, alpha, brightness);
//TODO now that we don't dispose on each paint, need to do on resource termination?
//for (IShadedShape ss : ib.shadedShapes) {
// ss.dispose();
//}
// Wireframes were deferred. Paint them now.
for (RGB color : ib.wireframes.keySet()) {
IWireframeShape wireframeForThisColor = ib.wireframes.get(color);
if (wireframeForThisColor == null) {
//TODO assert
}
else {
wireframeForThisColor.compile();
//TODO to be correct, should be lineWidth in effect at individual wireframe paints
target.drawWireframeShape(wireframeForThisColor, color, (float) ib.currentLineWidth);
wireframeForThisColor.dispose();
}
}
// Strings were deferred. Paint them now.
target.drawStrings(ib.strings);
// Circles were deferred. Paint them now.
target.drawCircle(ib.circles.toArray(new DrawableCircle[ib.circles.size()]));
for (Command c : pictureInfo.cgm.getCommands()) {
if (c instanceof INcCommand) {
((INcCommand) c).paint(target, paintProps, descriptor, ib);
}
}
/* -- Greg's handy outline box...
RGB color = new RGB( 250, 10, 10 );
if( font == null ) {
font = target.initializeFont("Monospace", 14, new IFont.Style[] { IFont.Style.BOLD});
}
PixelCoordinate textLoc = new PixelCoordinate( 500, 500, 0 );
target.drawString(font,
"CGM IMAGE", textLoc.getX(),
textLoc.getY(), 0.0,
TextStyle.NORMAL,
new RGB( 255, 255, 200 ),
HorizontalAlignment.CENTER,
VerticalAlignment.MIDDLE, 0.0);
// Shaded Shape (filled polygons) was deferred. Paint it now.
// if first paint of this image, save away shaded shape for future
// use
if (!ib.shadedShapeReady /* OR pictureInfo.shadedShape == null */) {
ib.shadedShape.compile();
// pictureInfo.completedShadedShapes =
// ib.shadedShapes.toArray(new
// IShadedShape[ib.shadedShapes.size()]);
pictureInfo.shadedShape = ib.shadedShape;
ib.shadedShapeReady = true;
}
float alpha = 1.0f; // TODO verify
float brightness = 1.0f;
target.drawShadedShape(pictureInfo.shadedShape, alpha, brightness);
// TODO now that we don't dispose on each paint, need to do on
// resource termination?
// for (IShadedShape ss : ib.shadedShapes) {
// ss.dispose();
// }
// Wireframes were deferred. Paint them now.
for (WireframeKey key : ib.wireframes.keySet()) {
IWireframeShape wireframeForThisKey = ib.wireframes.get(key);
if (wireframeForThisKey == null) {
// TODO assert
} else {
wireframeForThisKey.compile();
// TODO to be correct, should be lineWidth in effect at
// individual wireframe paints
target.drawWireframeShape(wireframeForThisKey, key.color,
(float) key.width);
wireframeForThisKey.dispose();
}
}
// Strings were deferred. Paint them now.
target.drawStrings(ib.strings);
// Circles were deferred. Paint them now.
target.drawCircle(ib.circles.toArray(new DrawableCircle[ib.circles
.size()]));
/*
* -- Greg's handy outline box...
*
* RGB color = new RGB( 250, 10, 10 );
*
* if( font == null ) { font = target.initializeFont("Monospace",
* 14, new IFont.Style[] { IFont.Style.BOLD}); } PixelCoordinate
* textLoc = new PixelCoordinate( 500, 500, 0 );
* target.drawString(font, "CGM IMAGE", textLoc.getX(),
* textLoc.getY(), 0.0, TextStyle.NORMAL, new RGB( 255, 255, 200 ),
* HorizontalAlignment.CENTER, VerticalAlignment.MIDDLE, 0.0);
*
* target.drawLine(0.0f, 0.0f, 0.0f, 0.0f, 1000.0f, 0.0f, color,
* 1.0f ); target.drawLine(0.0f, 0.0f, 0.0f, 1000.0f, 0.0f, 0.0f,
* color, 1.0f ); target.drawLine(1000.0f, 0.0f, 0.0f, 1000.0f,
* 1000.0f, 0.0f, color, 1.0f ); target.drawLine(0.0f, 1000.0f,
* 0.0f, 1000.0f, 1000.0f, 0.0f, color, 1.0f ); color = new
* RGB(0,255,0); target.drawLine(10.0f, 10.0f, 10.0f, 10.0f, 990.0f,
* 10.0f, color, 1.0f ); target.drawLine(10.0f, 10.0f, 10.0f,
* 990.0f, 10.0f, 10.0f, color, 1.0f ); target.drawLine(990.0f,
* 10.0f, 10.0f, 990.0f, 990.0f, 10.0f, color, 1.0f );
* target.drawLine(10.0f, 990.0f, 10.0f, 990.0f, 990.0f, 10.0f,
* color, 1.0f );
*/
}
target.drawLine(0.0f, 0.0f, 0.0f, 0.0f, 1000.0f, 0.0f, color, 1.0f );
target.drawLine(0.0f, 0.0f, 0.0f, 1000.0f, 0.0f, 0.0f, color, 1.0f );
target.drawLine(1000.0f, 0.0f, 0.0f, 1000.0f, 1000.0f, 0.0f, color, 1.0f );
target.drawLine(0.0f, 1000.0f, 0.0f, 1000.0f, 1000.0f, 0.0f, color, 1.0f );
color = new RGB(0,255,0);
target.drawLine(10.0f, 10.0f, 10.0f, 10.0f, 990.0f, 10.0f, color, 1.0f );
target.drawLine(10.0f, 10.0f, 10.0f, 990.0f, 10.0f, 10.0f, color, 1.0f );
target.drawLine(990.0f, 10.0f, 10.0f, 990.0f, 990.0f, 10.0f, color, 1.0f );
target.drawLine(10.0f, 990.0f, 10.0f, 990.0f, 990.0f, 10.0f, color, 1.0f );
*/
}
}
private byte[] shuffleByteArray(byte[] image) {
// Flip every even byte with its odd sibling (endianess reversal)
byte [] returnArray = new byte[image.length];
for (int i = 0 ; i < image.length ; i = i + 2 ) {
returnArray[i] = image[i+1];
returnArray[i+1] = image[i];
}
return returnArray;
}
public void resourceAttrsModified() {
//TODO??
// Flip every even byte with its odd sibling (endianess reversal)
byte[] returnArray = new byte[image.length];
for (int i = 0; i < image.length; i = i + 2) {
returnArray[i] = image[i + 1];
returnArray[i + 1] = image[i];
}
return returnArray;
}
public void resourceAttrsModified() {
// TODO??
}
@Override
public String getName() {
FrameData fd = (FrameData) getCurrentFrame();
if (fd == null || fd.getFrameTime() == null
|| fd.pictureInfo == null
|| fd.pictureInfo.cgm == null) {
return legendStr + "-No Data";
}
return legendStr + " "
+ NmapCommon.getTimeStringFromDataTime( fd.getFrameTime(), "/");
}
public String getName() {
FrameData fd = (FrameData) getCurrentFrame();
if (fd == null || fd.getFrameTime() == null || fd.pictureInfo == null
|| fd.pictureInfo.cgm == null) {
return legendStr + "-No Data";
}
return legendStr + " "
+ NmapCommon.getTimeStringFromDataTime(fd.getFrameTime(), "/");
}
}

View file

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<resourceGroup xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<resource>
<loadProperties>
</loadProperties>
<properties isSystemResource="false" isBlinking="false"
isMapLayer="false" isHoverOn="false" isVisible="true" />
<resourceData xsi:type="NC-PlotResourceData"
retrieveData="false" isUpdatingOnMetadataOnly="false"
isRequeryNecessaryOnTimeMatch="false">
<legendColor>${legendColor}</legendColor>
<legendString>${legendString}</legendString>
<spiFile>${spiFile}</spiFile>
<levelKey>Surface</levelKey>
<plotDensity>${plotDensity}</plotDensity>
${plotModel}
${conditionalFilter}
<frameSpan>${frameSpan}</frameSpan>
<timeMatchMethod>${timeMatchMethod}</timeMatchMethod>
<timelineGenMethod>${timelineGenMethod}</timelineGenMethod>
<dfltNumFrames>${dfltNumFrames}</dfltNumFrames>
<dfltTimeRange>${dfltTimeRange}</dfltTimeRange>
<metadataMap>
<mapping key="matrixType">
<constraint constraintValue="${matrixType}" constraintType="IN" />
</mapping>
<mapping key="pluginName">
<constraint constraintValue="${pluginName}" constraintType="EQUALS" />
</mapping>
</metadataMap>
</resourceData>
</resource>
</resourceGroup>

View file

@ -19,6 +19,11 @@
editDialogClass="gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.EditPlotDataAttrsDialog"
name="UpperAirPlot">
</nc-resource>
<nc-resource
class="gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.PlotResourceData"
editDialogClass="gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.EditPlotDataAttrsDialog"
name="MatrixPlot">
</nc-resource>
</extension>
<extension
@ -181,6 +186,54 @@
paramType="IMPLEMENTATION_PARAM">
</nc-resourceParameter>
<nc-resourceParameter
paramClass="PlotModel"
paramName="plotModel"
paramType="EDITABLE_ATTRIBUTE"
ncResourceName="MatrixPlot">
</nc-resourceParameter>
<nc-resourceParameter
paramClass="java.lang.Integer"
paramName="plotDensity"
paramType="EDITABLE_ATTRIBUTE"
defaultValue="20"
ncResourceName="MatrixPlot">
</nc-resourceParameter>
<nc-resourceParameter
paramClass="ConditionalFilter"
paramName="conditionalFilter"
defaultValue=""
paramType="EDITABLE_ATTRIBUTE"
ncResourceName="MatrixPlot">
</nc-resourceParameter>
<nc-resourceParameter
ncResourceName="MatrixPlot"
paramClass="String"
paramName="matrixType"
paramType="REQUEST_CONSTRAINT">
</nc-resourceParameter>
<nc-resourceParameter
ncResourceName="MatrixPlot"
paramClass="String"
paramName="spiFile"
paramType="IMPLEMENTATION_PARAM">
</nc-resourceParameter>
<nc-resourceParameter
ncResourceName="MatrixPlot"
paramClass="String"
paramName="legendString"
defaultValue="MatrixPlot"
paramType="IMPLEMENTATION_PARAM">
</nc-resourceParameter>
<nc-resourceParameter
ncResourceName="MatrixPlot"
paramClass="RGB"
paramName="legendColor"
defaultValue="RGB {155, 155, 155}"
paramType="IMPLEMENTATION_PARAM">
</nc-resourceParameter>
</extension>

View file

@ -927,7 +927,7 @@ public class NcPlotImageCreator {
Collection<Station> stnColl, String plotUnit,
double symbolSize, Color[] windVectorColorArray,
String metPrm1, String metPrm2, PlotModelElement pme) {
Tracer.print("> Entry " + Tracer.shortTimeString(this.dataTime)
Tracer.printX("> Entry " + Tracer.shortTimeString(this.dataTime)
+ " with " + stnColl.size() + " stations" + " metPrm1 "
+ metPrm1 + " metPrm2 " + metPrm2);
Map<Coordinate, IVector> localVectorPosToVectorMap = new HashMap<Coordinate, IVector>(
@ -1040,7 +1040,7 @@ public class NcPlotImageCreator {
}
}
ss.release();
Tracer.print("< Exit " + Tracer.shortTimeString(this.dataTime));
Tracer.printX("< Exit " + Tracer.shortTimeString(this.dataTime));
return localVectorPosToVectorMap;
}
@ -1050,7 +1050,7 @@ public class NcPlotImageCreator {
double symbolSize, Color[] windVectorColorArray,
double[] stationLoc) {
Tracer.print("> Entry");
Tracer.printX("> Entry");
AbstractMetParameter windSpeed = null, windDir = null;
Vector vector = null;
@ -1089,7 +1089,7 @@ public class NcPlotImageCreator {
e.printStackTrace();
}
Tracer.print("< Exit" + " returning "
Tracer.printX("< Exit" + " returning "
+ ((vector == null) ? "NULL" : "a vector"));
return vector;

View file

@ -27,6 +27,7 @@ import gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.TimeLogger;
import gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.Tracer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
@ -34,6 +35,8 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Semaphore;
@ -64,9 +67,12 @@ import com.raytheon.viz.pointdata.PointDataRequest;
* ------------ ---------- ----------- --------------------------
* 05/20/2013?? 988 Archana.S Initial creation.
* 02/26/2014 1061 B. Hebbard Don't block on JobPool cancel, so CAVE doesn't freeze if resource unloaded during long retrieval
* 04/01/2014 1040 B. Hebbard In requestUpperAirData, (1) clear displayStationPlotBoolList for each new station, (2) call cond filter check with newInstance vs. metPrm
* 04/08/2014 1127 B. Hebbard In requestSurfaceData, exclude only those obs returned from HDF5 that don't match desired time; fix dataTime association; removed redundant dataTimes from constraint
*/
public class NcPlotModelHdf5DataRequestor {
StringBuffer sb = new StringBuffer();
private Map<String, RequestConstraint> constraintMap;
@ -119,9 +125,11 @@ public class NcPlotModelHdf5DataRequestor {
//
private HashMap<String, PlotParameterDefn> prioritySelectionsMap = null;
private String latDbName = "latitude";
private static final String latDbName = "latitude";
private String lonDbName = "longitude";
private static final String lonDbName = "longitude";
private static final String refTimeDbName = "refTime";
private Map<String, String> metParamNameToDbNameMap = null;
@ -227,7 +235,6 @@ public class NcPlotModelHdf5DataRequestor {
e.printStackTrace();
}
Tracer.print("< Exit");
}
public ConditionalFilter getConditionalFilter() {
@ -278,14 +285,11 @@ public class NcPlotModelHdf5DataRequestor {
if (!dbParamsMap.containsKey(dbPrmName))
dbParamsMap.put(dbPrmName, condColoringParam);
}
setOfCondColoringParamNames.add(thisPlotParamDefn
.getMetParamName());
}
}
}
}
Tracer.print("< Exit");
}
@ -324,8 +328,9 @@ public class NcPlotModelHdf5DataRequestor {
synchronized (stationSet) {
for (Station station : stationSet) {
if (station.listOfParamsToPlot == null
|| station.listOfParamsToPlot.isEmpty())
|| station.listOfParamsToPlot.isEmpty()) {
continue;
}
List<Boolean> displayPlotBoolList = new ArrayList<Boolean>(
station.listOfParamsToPlot.size());
@ -379,7 +384,6 @@ public class NcPlotModelHdf5DataRequestor {
condMetParam = addToDerivedParamsList(
eachPlotParamDefn.getDeriveParams(),
eachPlotParamDefn);
} else {
MetParameterFactory.getInstance().alias(
eachPlotParamDefn.getMetParamName(),
@ -393,22 +397,17 @@ public class NcPlotModelHdf5DataRequestor {
dbParamsMap.put(dbParamName, condMetParam);
setOfDBParamNamesForHdf5Query.add(dbParamName);
}
}
determineParameterNamesForHdf5Query();
}
}
}
Tracer.print("< Exit");
}
public Boolean doesStationPassTheFilterForThisMetParam(
AbstractMetParameter metPrm) {
Tracer.print("> Entry");
Tracer.printX("> Entry " + metPrm);
Boolean displayStationPlot = true;
Set<String> condPlotParamNameSet = condFilterMap.keySet();
@ -424,8 +423,9 @@ public class NcPlotModelHdf5DataRequestor {
RequestConstraint reqConstraint = condFilterMap
.get(condPlotParamName);
if (reqConstraint == null)
if (reqConstraint == null) {
continue;
}
AbstractMetParameter condMetParam = MetParameterFactory
.getInstance().createParameter(
@ -495,7 +495,7 @@ public class NcPlotModelHdf5DataRequestor {
}
}
}
Tracer.print("< Exit");
Tracer.printX("< Exit " + (displayStationPlot ? "YES" : "NO"));
return displayStationPlot;
}
@ -540,8 +540,9 @@ public class NcPlotModelHdf5DataRequestor {
// ??derived
if (plotPrmDefn.getDeriveParams() != null) {
// TODO Do anything here at all?
} else
} else {
continue;
}
} else if (dbParamsMap.containsKey(dbPrmName)) {
continue;
} else { // if( !dbPrmName.equals("derived" ) ) {
@ -617,6 +618,7 @@ public class NcPlotModelHdf5DataRequestor {
setOfDBParamNamesForHdf5Query.add(latDbName);
setOfDBParamNamesForHdf5Query.add(lonDbName);
setOfDBParamNamesForHdf5Query.add(refTimeDbName);
}
@ -641,6 +643,7 @@ public class NcPlotModelHdf5DataRequestor {
setOfDBParamNamesForHdf5Query.add(latDbName);
setOfDBParamNamesForHdf5Query.add(lonDbName);
setOfDBParamNamesForHdf5Query.add(refTimeDbName);
if (derivedParamsList != null && !derivedParamsList.isEmpty())
derivedParamsList.clear();
@ -892,7 +895,6 @@ public class NcPlotModelHdf5DataRequestor {
}
if (this.derivedParamsList != null && !this.derivedParamsList.isEmpty()) {
determineDBParamNamesForDerivedParameters();
}
this.parameters = new String[setOfDBParamNamesForHdf5Query.size()];
@ -928,7 +930,6 @@ public class NcPlotModelHdf5DataRequestor {
if (rangeTimeLst.contains(stnTime) == false) {
rangeTimeLst.add(stnTime);
}
}
}
NcSoundingQuery2 sndingQuery;
@ -999,13 +1000,20 @@ public class NcPlotModelHdf5DataRequestor {
List<NcSoundingProfile> listOfSoundingProfiles = sndingCube
.getSoundingProfileList();
if (listOfSoundingProfiles == null
|| listOfSoundingProfiles.isEmpty())
|| listOfSoundingProfiles.isEmpty()) {
return null;
}
synchronized (listOfSoundingProfiles) {
for (NcSoundingProfile sndingProfile : listOfSoundingProfiles) {
Station currentStation = mapOfStnidsWithStns
.get(sndingProfile.getStationId());
/*
* Next station gets a fresh start when considering
* conditional filters.
*/
displayStationPlotBoolList.clear();
/*
* Clear the existing list of parameters to plot in each
* station - to guarantee an updated list if there is a
@ -1038,12 +1046,14 @@ public class NcPlotModelHdf5DataRequestor {
for (String dbPrmName : setOfDBParamNamesForHdf5Query) {
AbstractMetParameter metPrm = dbParamsMap
.get(dbPrmName);
if (metPrm == null)
if (metPrm == null) {
continue;
}
AbstractMetParameter newInstance = newInstance(metPrm);
if (newInstance == null)
if (newInstance == null) {
continue;
}
// TODO : the station lat/lon, elev, name and id
// should be set in the sounding profile
// but currently isn't. So instead we will get the
@ -1052,13 +1062,14 @@ public class NcPlotModelHdf5DataRequestor {
if (soundingParamsMap.containsKey(key)) {
AbstractMetParameter queriedParam = soundingParamsMap
.get(key);
if (newInstance.hasStringValue())
if (newInstance.hasStringValue()) {
newInstance.setStringValue(queriedParam
.getStringValue());
else
} else {
newInstance.setValue(
queriedParam.getValue(),
queriedParam.getUnit());
}
}
else if (newInstance.getMetParamName().equals(
@ -1109,7 +1120,7 @@ public class NcPlotModelHdf5DataRequestor {
if (condFilterMap != null
&& !condFilterMap.isEmpty()) {
displayStationPlotBoolList
.add(doesStationPassTheFilterForThisMetParam(metPrm));
.add(doesStationPassTheFilterForThisMetParam(newInstance));
}
// boolean found = false;
@ -1145,8 +1156,9 @@ public class NcPlotModelHdf5DataRequestor {
}
AbstractMetParameter clonedDerivedPrm = newInstance(derivedParam);// .getClass().newInstance();
if (clonedDerivedPrm == null)
if (clonedDerivedPrm == null) {
continue;
}
if (paramsToPlot.containsKey(derivedParam
.getMetParamName())) {
@ -1180,9 +1192,10 @@ public class NcPlotModelHdf5DataRequestor {
.getMetParamName().compareTo(
condMetParamName) == 0) {
if (condDerivedParamToCheck
.hasValidValue())
.hasValidValue()) {
displayStationPlotBoolList
.add(doesStationPassTheFilterForThisMetParam(condDerivedParamToCheck));
}
}
}
@ -1226,17 +1239,19 @@ public class NcPlotModelHdf5DataRequestor {
}
synchronized (mapOfStnidsWithStns) {
if (displayStationPlot)
if (displayStationPlot) {
mapOfStnidsWithStns.put(
currentStation.info.stationId,
currentStation);
else
} else {
mapOfStnidsWithStns
.remove(currentStation.info.stationId);
}
}
} else
} else {
mapOfStnidsWithStns.put(currentStation.info.stationId,
currentStation);
}
}
}
@ -1252,6 +1267,7 @@ public class NcPlotModelHdf5DataRequestor {
Tracer.print("> Entry " + Tracer.shortTimeString(time));
// sem1.acquireUninterruptibly();
Map<String, Station> stationMap = new HashMap<String, Station>(
listOfStationsRequestingForData.size());
if (listOfStationsRequestingForData != null
@ -1264,32 +1280,29 @@ public class NcPlotModelHdf5DataRequestor {
Map<String, RequestConstraint> map = new HashMap<String, RequestConstraint>();
map.put("pluginName", constraintMap.get("pluginName"));
Tracer.print(Tracer.shortTimeString(time) + " putting "
Tracer.print(Tracer.shortTimeString(time) + " putting '"
+ constraintMap.get("pluginName")
+ " as pluginName entry in map");
+ "' as pluginName entry in map");
DataTime[] dt = new DataTime[listSize];
String[] stationIds = new String[listSize];
RequestConstraint rc = new RequestConstraint();
RequestConstraint timeConstraint = new RequestConstraint();
timeConstraint.setConstraintType(ConstraintType.IN);
rc.setConstraintType(ConstraintType.IN);
int index = 0;
PluginPlotProperties plotProp = PluginPlotProperties
.getPluginProperties(map);
Tracer.print(Tracer.shortTimeString(time) + " plotProp "
+ plotProp);
Map<String, DataTime> stationIdToDataTimeMap = new HashMap<String, DataTime>(
listSize);
synchronized (listOfStationsRequestingForData) {
for (Station currentStation : listOfStationsRequestingForData) {
dt[index] = currentStation.info.dataTime;
// if( index == 0 ){
// System.out.println("\n for the frame " +
// time.toString() + "dt[0] = " + dt[0].toString());
// }
stationIds[index] = currentStation.info.stationId;
// Remember association between stationId and its (one!)
// matched time for this frame. Will use to filter out
// multiple station returns (in case of shared obs
// times) later.
stationIdToDataTimeMap.put(
currentStation.info.stationId,
currentStation.info.dataTime);
if (plotProp.hasDistinctStationId) {
Tracer.print(Tracer.shortTimeString(time)
@ -1297,17 +1310,16 @@ public class NcPlotModelHdf5DataRequestor {
+ currentStation.info.stationId
+ " plotProp.hasDistinctStationId TRUE; adding stationId to constraint value list ");
rc.addToConstraintValueList(currentStation.info.stationId);
timeConstraint
.addToConstraintValueList(currentStation.info.dataTime
.toString());
} else
// timeConstraint strings added all at once below
} else {
Tracer.print(Tracer.shortTimeString(time)
+ " "
+ currentStation.info.stationId
+ " plotProp.hasDistinctStationId FALSE; adding dataURI "
+ currentStation.info.dataURI
+ " to constraint value list");
rc.addToConstraintValueList(currentStation.info.dataURI);
rc.addToConstraintValueList(currentStation.info.dataURI);
}
Tracer.print(Tracer.shortTimeString(time)
+ " "
@ -1320,7 +1332,6 @@ public class NcPlotModelHdf5DataRequestor {
currentStation.info.longitude),
currentStation);
++index;
}
}
@ -1328,36 +1339,18 @@ public class NcPlotModelHdf5DataRequestor {
Tracer.print(Tracer.shortTimeString(time)
+ " Done with station loop; plotProp.hasDistinctStationId TRUE; adding location.stationId-to-rc entry to map");
map.put("location.stationId", rc);
// if (dt.length > 1 && !dt[0].equals(dt[1])) { //TODO: wtf?
// Tracer.print(Tracer.shortTimeString(time)
// + " dt.length ("
// + dt.length
// + ") > 1 AND dt[0] ("
// + dt[0]
// + ") != dt[1] ("
// + dt[1]
// + "); replacing dataTime-to-rc entry in map with RC "
// + timeConstraint);
// sort data times and remove duplicates...
SortedSet<DataTime> allDataTimesSortedSet = new TreeSet<DataTime>(
stationIdToDataTimeMap.values());
// ...and convert to strings for time request constraint
List<String> allDataTimesAsStrings = new ArrayList<String>(
allDataTimesSortedSet.size());
for (DataTime dt : allDataTimesSortedSet) {
allDataTimesAsStrings.add(dt.toString());
}
timeConstraint
.setConstraintValueList(allDataTimesAsStrings);
map.put("dataTime", timeConstraint);
// } else {
// map.remove("dataTime");
// String timeStr = new String(dt[0].toString());
// RequestConstraint rct = new RequestConstraint(timeStr);
// // TODO
// // temporary
// // for
// // debug
// Tracer.print(Tracer.shortTimeString(time)
// + " dt.length ("
// + dt.length
// + ") == 0 OR dt[0] ("
// + dt[0]
// +
// ") == dt[1]; replacing dataTime-to-rc entry in map with RC based on timeStr "
// + timeStr);
// map.put("dataTime", rct);
// // map.put("dataTime", new RequestConstraint(timeStr));
// }
} else {
Tracer.print(Tracer.shortTimeString(time)
+ " Done with station loop; plotProp.hasDistinctStationId FALSE; putting dataURI-to-rc entry in map with rc "
@ -1387,7 +1380,7 @@ public class NcPlotModelHdf5DataRequestor {
int pdcSize = -1;
if (pdc == null) {
if (dt != null && dt.length > 0) {
if (!stationIdToDataTimeMap.isEmpty()) {
sem1.acquireUninterruptibly();
@ -1398,9 +1391,15 @@ public class NcPlotModelHdf5DataRequestor {
+ " Plugin "
+ this.plugin
+ " Parameters "
+ this.parameters + " Stations " + stationIds);
+ this.parameters
+ " Stations "
+ stationIdToDataTimeMap.keySet().toArray(
new String[0]));
pdc = PointDataRequest.requestPointDataAllLevels(
this.plugin, this.parameters, stationIds, map);
this.plugin,
this.parameters,
stationIdToDataTimeMap.keySet().toArray(
new String[0]), map);
Tracer.print("Done with call PointDataRequest.requestPointDataAllLevels(...) for frame: "
+ Tracer.shortTimeString(time)
+ "HDF5 query map = "
@ -1408,20 +1407,27 @@ public class NcPlotModelHdf5DataRequestor {
+ " Plugin "
+ this.plugin
+ " Parameters "
+ this.parameters + " Stations " + stationIds);
+ this.parameters
+ " Stations "
+ stationIdToDataTimeMap.keySet().toArray(
new String[0]));
sem1.release();
}
}
if (pdc != null) {
Tracer.print("We have a non-null PDC for frame: "
+ Tracer.shortTimeString(time)
+ "HDF5 query map = " + map + " Plugin "
+ this.plugin + " Parameters " + this.parameters
+ " Stations " + stationIds + " PDC content: "
+ pdc);
+ " HDF5 query map = "
+ map
+ " Plugin "
+ this.plugin
+ " Parameters "
+ Arrays.toString(this.parameters)
+ " Stations "
+ Arrays.toString(stationIdToDataTimeMap.keySet()
.toArray(new String[0])) + " PDC " + pdc);
pdcSize = pdc.getAllocatedSz();
Tracer.print("PDC for frame "
+ Tracer.shortTimeString(time)
@ -1438,89 +1444,74 @@ public class NcPlotModelHdf5DataRequestor {
return stationMap.values();
}
int stationMapSize = stationIds.length;
if (pdcSize > stationMapSize) {
Tracer.print(Tracer.shortTimeString(time) + " pdcSize "
+ pdcSize + " > stationMapSize " + stationMapSize
+ " setting pdcSize = stationMapSize");
pdcSize = stationMapSize;
}
Tracer.print("Size of stationMap: " + stationMap.size());
Tracer.print("Number of stationIds: "
+ stationIdToDataTimeMap.keySet()
.toArray(new String[0]).length);
Tracer.print("pdcSize: " + pdcSize);
for (int uriCounter = 0; uriCounter < pdcSize; uriCounter++) {
PointDataView pdv = pdc.readRandom(uriCounter);
if (pdv == null) { // ???
if (pdv == null) { // ??
Tracer.print(Tracer.shortTimeString(time)
+ " PDV is null for station " + uriCounter
+ " -- skipping");
continue;
}
DataTime dataTime = dt[uriCounter];
String key = new String(formatLatLonKey(
pdv.getFloat(latDbName), pdv.getFloat(lonDbName)));
Station currentStation = stationMap.get(key);
if (currentStation == null) {
Tracer.print(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " stationMap entry not found for key " + key
+ " -- skipping");
continue;
}
// TODO remove
boolean jfk = currentStation.info.stationId
.equalsIgnoreCase("KJFK");
String stationId = currentStation.info.stationId;
DataTime dataTime = stationIdToDataTimeMap.get(stationId);
DataTime retrievedDataTime = new DataTime(new Date(
pdv.getLong(refTimeDbName)));
// Since the constraints we use (if
// plotProp.hasDistinctStationId) are "stationID" IN
// list-of-all-stationIDs -AND- dataTime IN
// list-of-all-dataTimes, a station could be retrieved
// for more data times than its unique time-matched time
// (for this frame) -- IF it happens to share another data
// time with another station legitimately time-matched to
// that other time. Here we check to make sure the time
// we retrieved is the one we wanted for this station;
// if not, ignore this obs. (An obs with the desired
// time should appear elsewhere in the PDC).
if (!dataTime.equals(retrievedDataTime)) {
Tracer.print(Tracer.shortTimeString(time)
+ " Retrieved dataTime for station "
+ stationId + " is " + retrievedDataTime
+ " but matched dataTime is " + dataTime
+ " -- skipping");
continue;
}
Semaphore sm = new Semaphore(1);
sm.acquireUninterruptibly();
synchronized (paramsToPlot) {
Set<String> pkeySet = paramsToPlot.keySet();
Tracer.printX(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " paramsToPlot for "
+ currentStation.info.stationId + ": "
+ pkeySet);
synchronized (pkeySet) {
try {
for (String prmToPlotKey : pkeySet) {
if (jfk)
Tracer.print(Tracer
.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " "
+ " from pkeySet updating prmToPlot(Key) "
+ prmToPlotKey);
AbstractMetParameter prmToPlot = paramsToPlot
.get(prmToPlotKey);
if (prmToPlot != null) {
if (jfk)
Tracer.print(Tracer
.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " "
+ " prmToPlot non-null "
+ prmToPlot);
prmToPlot.setValueToMissing();
paramsToPlot.put(prmToPlot.getClass()
.getSimpleName(), prmToPlot);
} else {
if (jfk)
Tracer.print(Tracer
.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " "
+ " from pkeySet updating prmToPlot(Key) "
+ " -- prmToPlot is NULL -- skipping!!!");
// Tracer... prmToPlot==null
}
}
@ -1534,25 +1525,11 @@ public class NcPlotModelHdf5DataRequestor {
0);
synchronized (setOfDBParamNamesForHdf5Query) {
Tracer.print(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " setOfDBParamNamesForHdf5Query for "
+ currentStation.info.stationId + ": "
+ setOfDBParamNamesForHdf5Query);
for (String dbPrm : setOfDBParamNamesForHdf5Query) {
AbstractMetParameter metPrm = dbParamsMap
.get(dbPrm);
if (metPrm == null) {
if (jfk)
Tracer.print(Tracer.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " "
+ " NULL metPrm return from dbParamsMap for key -- skipping"
+ dbPrm);
continue;
}
@ -1595,57 +1572,20 @@ public class NcPlotModelHdf5DataRequestor {
} catch (Exception e) {
Tracer.print("param " + dbPrm + " not found.");
}
if (jfk)
Tracer.print(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " " + currentStation.info.stationId
+ " " + " before setMetParamFromPDV "
+ dbPrm + " " + metPrm);
/*
* Set the value for Met parameters from the
* corresponding database value
*/
setMetParamFromPDV(metPrm, pdv, dbPrm, dataTime);
if (jfk)
Tracer.print(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " " + currentStation.info.stationId
+ " " + " after setMetParamFromPDV "
+ dbPrm + " " + metPrm);
// if(
// metPrm.getMetParamName().compareTo("StationID")
// == 0 ){
// if(metPrm.getStringValue().compareTo(currentStation.info.stationId)
// != 0 ){
// System.out.println("ttd");
// }
// }
if (paramsToPlot.containsKey(metPrm
.getMetParamName())) {
if (jfk)
Tracer.print(Tracer.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " "
+ " paramsToPlot contains metPrm; putting "
+ metPrm.getMetParamName()
+ " into paramsToPlot");
paramsToPlot.put(metPrm.getMetParamName(),
metPrm);
}
dbParamsMap.put(dbPrm, metPrm);
if (jfk)
Tracer.print(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " " + currentStation.info.stationId
+ " " + " after put " + dbPrm + " "
+ metPrm + " into dbParamsMap");
if (condFilterMap != null
&& !condFilterMap.isEmpty()) {
@ -1709,12 +1649,12 @@ public class NcPlotModelHdf5DataRequestor {
.getMetParamName().compareTo(
condMetParamName) == 0) {
if (condDerivedParamToCheck
.hasValidValue())
.hasValidValue()) {
displayStationPlotBoolList
.add(doesStationPassTheFilterForThisMetParam(condDerivedParamToCheck));
}
}
}
}
}
}
@ -1726,22 +1666,10 @@ public class NcPlotModelHdf5DataRequestor {
*/
if (!currentStation.listOfParamsToPlot.isEmpty()) {
currentStation.listOfParamsToPlot.clear();
if (jfk)
Tracer.print(Tracer.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " CLEARING nonempty listOfParamsToPlot for "
+ currentStation.info.stationId);
}
sm.acquireUninterruptibly();
metParamsToDisplay = new ArrayList<AbstractMetParameter>(
paramsToPlot.values());
if (jfk)
Tracer.print(Tracer.shortTimeString(time) + " "
+ Tracer.shortTimeString(dataTime)
+ " metParamsToDisplay for "
+ currentStation.info.stationId + " "
+ metParamsToDisplay);
synchronized (metParamsToDisplay) {
try {
for (AbstractMetParameter metParam : metParamsToDisplay) {
@ -1756,36 +1684,11 @@ public class NcPlotModelHdf5DataRequestor {
* the AbstractMetParametervalues from
* paramsToPlot
*/
if (jfk)
Tracer.print(Tracer.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " " + " trying to add metParam "
+ metParam);
AbstractMetParameter newPrm = newInstance(metParam);
if (newPrm == null) {
if (jfk)
Tracer.print(Tracer
.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " "
+ " newPrm NULL from newInstance -- skipping!!! "
+ metParam);
continue;
}
currentStation.listOfParamsToPlot.add(newPrm);
if (jfk)
Tracer.print(Tracer.shortTimeString(time)
+ " "
+ Tracer.shortTimeString(dataTime)
+ " "
+ currentStation.info.stationId
+ " " + " added newPrm " + newPrm);
}
} catch (Exception e) {
@ -1821,7 +1724,6 @@ public class NcPlotModelHdf5DataRequestor {
*/
if (condFilterMap != null && !condFilterMap.isEmpty()) {
displayStationPlot = true;
synchronized (displayStationPlotBoolList) {
for (Boolean b : displayStationPlotBoolList) {
@ -1830,16 +1732,16 @@ public class NcPlotModelHdf5DataRequestor {
}
synchronized (stationMap) {
if (displayStationPlot)
if (displayStationPlot) {
stationMap.put(key, currentStation);
else
} else {
stationMap.remove(key);
}
}
} else
} else {
stationMap.put(key, currentStation);
}
// if( currentStation.info.stationId.compareTo("KJFK") == 0
// || currentStation.info.stationId.compareTo("KEYW") == 0 )
// System.out.println( "\nFor frame: " + time.toString() +
// " stn dataTime: "
// + currentStation.info.dataTime.toString() +":"
@ -1874,7 +1776,6 @@ public class NcPlotModelHdf5DataRequestor {
}
} catch (VizException e) {
e.printStackTrace();
} catch (DataCubeException e1) {
@ -1885,7 +1786,11 @@ public class NcPlotModelHdf5DataRequestor {
// sem1.release();
Tracer.print("< Exit " + Tracer.shortTimeString(time));
String stations = "";
for (Station s : stationMap.values()) {
stations += (" " + s.info.stationId);
}
Tracer.print("< Exit " + Tracer.shortTimeString(time) + stations);
return (stationMap.values());
}
@ -1999,8 +1904,9 @@ public class NcPlotModelHdf5DataRequestor {
.getMetParamName()) == 0) {
AbstractMetParameter newPrm = newInstance(thisCondColorParam);
if (newPrm == null)
if (newPrm == null) {
continue;
}
currentStation.setOfConditionalColorParams.add(newPrm);
}

View file

@ -249,7 +249,7 @@ public final class ProgressiveDisclosure {
}
public synchronized boolean checkAndUpdateProgDisclosureProperties() {
Tracer.print("> Entry");
Tracer.printX("> Entry");
boolean update = updateNextPaint;
final IDisplayPane activePane = NcDisplayMngr
@ -261,7 +261,7 @@ public final class ProgressiveDisclosure {
VizApp.runSync(new Runnable() {
@Override
public void run() {
Tracer.print("> Entry");
Tracer.printX("> Entry");
if (activePane != null) {
canvasBounds = activePane.getBounds();
@ -341,7 +341,7 @@ public final class ProgressiveDisclosure {
// if(canvasBounds.height != progDiscTask.canvasWidth)
updateNextPaint = false;
Tracer.print("< Exit");
Tracer.printX("< Exit");
return update;
}

View file

@ -129,6 +129,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* Added code to plot stations within 25% of the area outside of the current display area.
* 05/20/2013 988 Archana.S Refactored this class for performance improvement
* 11/07/2013 sgurung Added fix for "no data for every other frame" issue (earlier fix was added to 13.5.2 on 10/24/2013)
* 03/18/2013 1064 B. Hebbard Added handling of matrixType request constraint, for PAFM
* </pre>
*
* @author brockwoo
@ -984,7 +985,7 @@ public class NcPlotResource2 extends
public void paintFrame(AbstractFrameData fd, final IGraphicsTarget target,
PaintProperties paintProps) throws VizException {
Tracer.print("> Entry");
Tracer.printX("> Entry");
currPaintProp = paintProps;
if (fd == null)
return;
@ -1146,7 +1147,7 @@ public class NcPlotResource2 extends
+ frameData.getShortFrameTime());
}
ss.release();
Tracer.print("< Exit");
Tracer.printX("< Exit");
}
public void initResource(IGraphicsTarget aTarget) throws VizException {
@ -1185,13 +1186,13 @@ public class NcPlotResource2 extends
}
protected AbstractFrameData createNewFrame(DataTime frameTime, int timeInt) {
Tracer.print("> Entry");
Tracer.print("> Entry " + Tracer.shortTimeString(frameTime));
FrameData newFrame = new FrameData(frameTime, timeInt);
if (df == null)
if (df == null) // TODO why do this here??
df = new DisplayElementFactory(NcDisplayMngr
.getActiveNatlCntrsEditor().getActiveDisplayPane()
.getTarget(), getDescriptor());
Tracer.print("< Exit");
Tracer.print("< Exit " + Tracer.shortTimeString(frameTime));
return newFrame;
}
@ -1761,9 +1762,22 @@ public class NcPlotResource2 extends
FrameData firstFrame = (FrameData) getFrame(datatimeList.get(0));
String tableName = this.metadataMap.get("pluginName")
.getConstraintValue();
String query = "select distinct(" + tableName + ".forecastTime), "
+ tableName + ".rangeEnd" + " from " + tableName
+ " where reftime = '" + cycleTimeStr + "';";
String matrixType = null;
RequestConstraint matrixTypeRC = this.metadataMap.get("matrixType");
if (matrixTypeRC != null) {
matrixType = matrixTypeRC.getConstraintValue();
}
String query = "";
if (matrixType == null || matrixType.isEmpty()) {
query = "select distinct(" + tableName + ".forecastTime), "
+ tableName + ".rangeEnd" + " from " + tableName
+ " where reftime = '" + cycleTimeStr + "';";
} else {
query = "select distinct(" + tableName + ".forecastTime), "
+ tableName + ".rangeEnd" + " from " + tableName
+ " where matrixtype = '" + matrixType + "'"
+ " AND reftime = '" + cycleTimeStr + "';";
}
try {
List<Object[]> results = null;
results = DirectDbQuery.executeQuery(query, "metadata",
@ -1845,6 +1859,14 @@ public class NcPlotResource2 extends
frameRCMap.put("pluginName",
metadataMap
.get("pluginName"));
matrixTypeRC = this.metadataMap
.get("matrixType"); // redundant?
if (matrixTypeRC != null) {
frameRCMap.put("matrixType",
matrixTypeRC);
}
frameRCMap
.put("dataTime.fcstTime",
new RequestConstraint(

View file

@ -38,7 +38,9 @@ package gov.noaa.nws.ncep.viz.rsc.plotdata.rsc;
import gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.NcPlotResource2.Station;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.DecimalFormat;
@ -50,6 +52,9 @@ import java.util.Date;
import com.raytheon.uf.common.time.DataTime;
public class Tracer {
private static boolean enabled = false;
// save it static to have it available on every call
private static Method m;
@ -60,9 +65,8 @@ public class Tracer {
Calendar cal = Calendar.getInstance();
String logFileName = /*
* "/export/cdbsrv/bhebbard/pointdatadisplay/" +
*/dateFormat.format(cal.getTime());
String logFileName = "/export/cdbsrv/bhebbard/pointdatadisplay/"
+ dateFormat.format(cal.getTime());
private static PrintWriter writer = null;
@ -95,37 +99,41 @@ public class Tracer {
}
public static void print(String message) {
long elapsedTime = 0;
if (startTime < 0) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
Calendar cal = Calendar.getInstance();
String logFileName = /*
* "/export/cdbsrv/bhebbard/pointdatadisplay/"
* +
*/dateFormat.format(cal.getTime());
/*
* try { writer = new PrintWriter(logFileName, "UTF-8"); } catch
* (FileNotFoundException e) { // TODO Auto-generated catch block.
* Please revise as // appropriate. //
* statusHandler.handle(Priority.PROBLEM, //
* e.getLocalizedMessage(), e); System.out.println("[" +
* "FileNotFoundException" + "] " + message); } catch
* (UnsupportedEncodingException e) { // TODO Auto-generated catch
* block. Please revise as // appropriate. //
* statusHandler.handle(Priority.PROBLEM, //
* e.getLocalizedMessage(), e); System.out.println("[" +
* "UnsupportedEncodingException" + "] " + message); }
* System.out.println("[Logging to " + logFileName + "]");
*/
startTime = System.nanoTime();
} else {
elapsedTime = (System.nanoTime() - startTime) / 1000000;
if (enabled) {
long elapsedTime = 0;
if (startTime < 0) {
DateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd-HH-mm-ss");
Calendar cal = Calendar.getInstance();
String logFileName = "/export/cdbsrv/bhebbard/pointdatadisplay/"
+ dateFormat.format(cal.getTime());
try {
writer = new PrintWriter(logFileName, "UTF-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block. Please revise as
// appropriate.
// statusHandler.handle(Priority.PROBLEM,
// e.getLocalizedMessage(), e);
System.out.println("[" + "FileNotFoundException" + "] "
+ message);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block. Please revise as
// appropriate.
// statusHandler.handle(Priority.PROBLEM,
// e.getLocalizedMessage(), e);
System.out.println("[" + "UnsupportedEncodingException"
+ "] " + message);
}
System.out.println("[Logging to " + logFileName + "]");
startTime = System.nanoTime();
} else {
elapsedTime = (System.nanoTime() - startTime) / 1000000;
}
System.out.println("[" + elapsedTime + getMethodName(1) + "] "
+ message);
writer.println("[" + elapsedTime + getMethodName(1) + "] "
+ message);
}
/*
* System.out.println("[" + elapsedTime + getMethodName(1) + "] " +
* message); writer.println("[" + elapsedTime + getMethodName(1) + "] "
* + message);
*/
}
public static void printX(String message) {
@ -139,7 +147,7 @@ public class Tracer {
Date frameDate = dt.getRefTime();
DecimalFormat df = new DecimalFormat("00");
String returnString = Integer.toString(frameDate.getDate()) + "/"
+ df.format(frameDate.getHours() + 5) // TODOhorror!!
+ df.format(frameDate.getHours() + 4) // TODOhorror!!
+ df.format(frameDate.getMinutes());
if (dt.getFcstTime() != 0) {
returnString += "(" + dt.getFcstTime() + ")";

View file

@ -41,6 +41,7 @@ import com.raytheon.uf.common.colormap.prefs.ColorMapParameters;
import com.raytheon.uf.common.colormap.prefs.DataMappingPreferences;
import com.raytheon.uf.common.colormap.prefs.DataMappingPreferences.DataMappingEntry;
import com.raytheon.uf.common.dataplugin.PluginDataObject;
import com.raytheon.uf.common.dataplugin.satellite.SatelliteRecord;
import com.raytheon.uf.common.dataplugin.satellite.units.counts.DerivedWVPixel;
import com.raytheon.uf.common.dataplugin.satellite.units.generic.GenericPixel;
import com.raytheon.uf.common.dataplugin.satellite.units.goes.PolarPrecipWaterPixel;
@ -115,6 +116,7 @@ import com.vividsolutions.jts.geom.Coordinate;
* satellite projections in the McidasFileBasedTileSet
* 05/20/2013 862 ghull implement IAreaProviderCapable
* Nov 14, 2013 2393 bclement changed how numLevels is calculated for mcidas
* 03/12/2014 920 pswamy Implemented changes to fix GINI VIS image display problems.
* </pre>
*
* @author chammack
@ -193,11 +195,16 @@ public abstract class AbstractSatelliteResource extends
.getPDO();
if (!(satRec instanceof ISpatialEnabled)) {
System.out
.println("AbstractSatelliteResource.updateFrameData: PDO "
+ satRec.getClass().toString()
+ " doesn't implement ISpatialEnabled");
return false;
if (satRec instanceof SatelliteRecord) {
gridGeom = baseGeom = ((SatelliteRecord) satRec)
.getGridGeometry();
} else {
System.out
.println("AbstractSatelliteResource.updateFrameData: PDO "
+ satRec.getClass().toString()
+ " doesn't implement ISpatialEnabled");
return false;
}
} else {
if (baseCoverage == null) {
baseCoverage = ((ISpatialEnabled) satRec)
@ -207,6 +214,8 @@ public abstract class AbstractSatelliteResource extends
frameCoverage = ((ISpatialEnabled) satRec)
.getSpatialObject();
}
gridGeom = baseGeom = MapUtil
.getGridGeometry(getSpatialObject());
}
synchronized (this) {
@ -234,8 +243,6 @@ public abstract class AbstractSatelliteResource extends
/*
* for remapped projections such as MER, LCC, STR
*/
gridGeom = baseGeom = MapUtil
.getGridGeometry(getSpatialObject());
tileSet = baseTile = new McidasFileBasedTileSet(
satRec, "Data", numLevels, 256, gridGeom,
AbstractSatelliteResource.this,
@ -431,6 +438,8 @@ public abstract class AbstractSatelliteResource extends
} else {
dataUnit = new GenericPixel();
}
} else if (this instanceof GiniSatResource) {
dataUnit = null;
} else
dataUnit = new GenericPixel();
@ -507,8 +516,15 @@ public abstract class AbstractSatelliteResource extends
} else {
numLevels = 1;
int newSzX = ((ISpatialEnabled) record).getSpatialObject().getNx();
int newSzY = ((ISpatialEnabled) record).getSpatialObject().getNy();
int newSzX = 0;
int newSzY = 0;
if (record instanceof ISpatialEnabled) {
newSzX = ((ISpatialEnabled) record).getSpatialObject().getNx();
newSzY = ((ISpatialEnabled) record).getSpatialObject().getNy();
} else if (record instanceof SatelliteRecord) {
newSzX = ((SatelliteRecord) record).getCoverage().getNx();
newSzY = ((SatelliteRecord) record).getCoverage().getNy();
}
while ((newSzX > 512 && newSzY > 512)) {
newSzX /= 2;

View file

@ -3,6 +3,7 @@ package gov.noaa.nws.ncep.viz.tools.plotModelMngr;
import gov.noaa.nws.ncep.viz.common.ui.UserEntryDialog;
import gov.noaa.nws.ncep.viz.rsc.plotdata.plotModels.PlotModelMngr;
import gov.noaa.nws.ncep.viz.rsc.plotdata.plotModels.elements.PlotModel;
import gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.EditPlotModelComposite;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
@ -19,20 +20,21 @@ import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.EditPlotModelComposite;
/**
* UI for editing Plot Models.
*
* UI for editing Plot Models.
*
*
*
* <pre>
* SOFTWARE HISTORY
* Date Ticket# Engineer Description
* ------------ ---------- ----------- --------------------------
* 10/15/2009 172 M. Li Initial creation.
* 10/15/2009 172 M. Li Initial creation.
* 12/05/2009 217 Greg Hull Use EditPlotModelComposite
* 07/26/2010 285 Q. Zhou modified editPlotModelComposit
* 03/08/2011 425 Greg Hull add a Save As button
* 03/10/2013 921 S. Russell TTR 921. Commented out "Save" button
* 03/11/2013 921 S. Russell TTR 921. Append "COPY" during "Save As"
*
* </pre>
*
@ -41,144 +43,137 @@ import gov.noaa.nws.ncep.viz.rsc.plotdata.rsc.EditPlotModelComposite;
*/
public class EditPlotModelDialog extends Dialog {
protected Shell shell;
protected String dlgTitle = "Edit Plot Model";
protected boolean ok=false;
protected Shell shell;
private PlotModel editedPlotModel = null;
public EditPlotModelDialog(Shell parentShell, PlotModel pm ) {
super(parentShell);
dlgTitle = "Edit Plot Model " + pm.getPlugin()+"/"+pm.getName();
editedPlotModel = new PlotModel( pm );
}
protected String dlgTitle = "Edit Plot Model";
public void createShell( int x, int y ) {
shell = new Shell( getParent(), SWT.DIALOG_TRIM | SWT.RESIZE );
shell.setText( dlgTitle );
GridLayout mainLayout = new GridLayout(1, true);
mainLayout.marginHeight = 1;
mainLayout.marginWidth = 1;
shell.setLayout(mainLayout);
shell.setLocation(x, y);
// TTR 921
protected String pltmdlnmsffx = "COPY";
Composite editPlotModelComp = new EditPlotModelComposite( shell, SWT.NONE, editedPlotModel, null );
protected boolean ok = false;
GridData gd = new GridData();
private PlotModel editedPlotModel = null;
Composite okCanComp = new Composite( shell, SWT.NONE );
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
okCanComp.setLayoutData( gd );
public EditPlotModelDialog(Shell parentShell, PlotModel pm) {
super(parentShell);
dlgTitle = "Edit Plot Model " + pm.getPlugin() + "/" + pm.getName();
editedPlotModel = new PlotModel(pm);
}
okCanComp.setLayout( new FormLayout() );
public void createShell(int x, int y) {
Button canBtn = new Button( okCanComp, SWT.PUSH );
canBtn.setText(" Cancel ");
FormData fd = new FormData();
fd.width = 80;
fd.bottom = new FormAttachment( 100, -5 );
fd.left = new FormAttachment( 25, -40 );
canBtn.setLayoutData( fd );
shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.RESIZE);
shell.setText(dlgTitle);
GridLayout mainLayout = new GridLayout(1, true);
mainLayout.marginHeight = 1;
mainLayout.marginWidth = 1;
shell.setLayout(mainLayout);
shell.setLocation(x, y);
canBtn.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
ok=false;
shell.dispose();
}
});
Composite editPlotModelComp = new EditPlotModelComposite(shell, SWT.NONE, editedPlotModel, null);
Button saveBtn = new Button( okCanComp, SWT.PUSH );
saveBtn.setText(" Save ");
fd = new FormData();
fd.width = 80;
fd.bottom = new FormAttachment( 100, -5 );
fd.left = new FormAttachment( 50, -40 );
saveBtn.setLayoutData( fd );
GridData gd = new GridData();
saveBtn.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
ok=true;
shell.dispose();
}
});
Composite okCanComp = new Composite(shell, SWT.NONE);
gd = new GridData();
gd.grabExcessHorizontalSpace = true;
gd.horizontalAlignment = SWT.FILL;
okCanComp.setLayoutData(gd);
Button saveAsBtn = new Button( okCanComp, SWT.PUSH );
saveAsBtn.setText("Save As...");
fd = new FormData();
fd.width = 90;
fd.bottom = new FormAttachment( 100, -5 );
fd.left = new FormAttachment( 75, -40 );
saveAsBtn.setLayoutData( fd );
okCanComp.setLayout(new FormLayout());
saveAsBtn.addSelectionListener( new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
// pop up a dialog to prompt for the new name
UserEntryDialog entryDlg = new UserEntryDialog( shell,
"Save As",
"Save Plot Model As:",
editedPlotModel.getName() );
Button canBtn = new Button(okCanComp, SWT.PUSH);
canBtn.setText(" Cancel ");
FormData fd = new FormData();
fd.width = 80;
fd.bottom = new FormAttachment(100, -5);
fd.left = new FormAttachment(25, -40);
canBtn.setLayoutData(fd);
canBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
ok = false;
shell.dispose();
}
});
/*
* // TTR 921 Button saveBtn = new Button( okCanComp, SWT.PUSH );
* saveBtn.setText(" Save "); fd = new FormData(); fd.width = 80;
* fd.bottom = new FormAttachment( 100, -5 ); fd.left = new
* FormAttachment( 50, -40 ); saveBtn.setLayoutData( fd );
*
* saveBtn.addSelectionListener( new SelectionAdapter() { public void
* widgetSelected(SelectionEvent e) { ok=true; shell.dispose(); } });
*/
Button saveAsBtn = new Button(okCanComp, SWT.PUSH);
saveAsBtn.setText("Save As...");
fd = new FormData();
fd.width = 90;
fd.bottom = new FormAttachment(100, -5);
fd.left = new FormAttachment(75, -40);
saveAsBtn.setLayoutData(fd);
saveAsBtn.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
String pmname = editedPlotModel.getName() + pltmdlnmsffx;
// pop up a dialog to prompt for the new name
UserEntryDialog entryDlg = new UserEntryDialog(shell, "Save As", "Save Plot Model As:", pmname);
String newPltMdlName = entryDlg.open();
if( newPltMdlName == null || // cancel pressed
newPltMdlName.isEmpty() ) {
return;
if (newPltMdlName == null || // cancel pressed
newPltMdlName.isEmpty()) {
return;
}
// if this plotModel already exists, prompt to overwrite
//
if( PlotModelMngr.getInstance().getPlotModel(
editedPlotModel.getPlugin(), newPltMdlName ) != null ) {
if (PlotModelMngr.getInstance().getPlotModel(editedPlotModel.getPlugin(), newPltMdlName) != null) {
MessageDialog confirmDlg = new MessageDialog(shell, "Confirm", null,
"A '"+newPltMdlName+"' Plot Model already exists.\n\nDo you want to overwrite it?",
MessageDialog.QUESTION,
new String[]{"Yes", "No"}, 0);
confirmDlg.open();
MessageDialog confirmDlg = new MessageDialog(shell, "Confirm", null, "A '" + newPltMdlName + "' Plot Model already exists.\n\nDo you want to overwrite it?",
MessageDialog.QUESTION, new String[] { "Yes", "No" }, 0);
confirmDlg.open();
if( confirmDlg.getReturnCode() == MessageDialog.CANCEL ) {
return;
}
if (confirmDlg.getReturnCode() == MessageDialog.CANCEL) {
return;
}
}
editedPlotModel.setName( newPltMdlName );
ok=true;
editedPlotModel.setName(newPltMdlName);
ok = true;
shell.dispose();
}
});
}
});
}
}
public void open() {
open( getParent().getLocation().x +10,
getParent().getLocation().y +10);
}
public void open() {
open(getParent().getLocation().x + 10, getParent().getLocation().y + 10);
}
public Object open( int x, int y) {
Display display = getParent().getDisplay();
public Object open(int x, int y) {
Display display = getParent().getDisplay();
createShell(x,y);
createShell(x, y);
initWidgets();
initWidgets();
shell.pack();
shell.open();
shell.pack();
shell.open();
while( !shell.isDisposed() ) {
if( !display.readAndDispatch() ) {
display.sleep();
}
}
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
return ( ok ? editedPlotModel : null );
}
return (ok ? editedPlotModel : null);
}
public void initWidgets() {
}
public void initWidgets() {
}
}

View file

@ -6,7 +6,6 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.junit.Ignore;
import org.junit.Test;
/**
@ -20,13 +19,14 @@ import org.junit.Test;
* values is generated correctly.
* 15-Jun-2010 174 Archana.S Updated test-cases per changes in the code design
* 02-Aug-2010 174 Archana.S Updated test-cases per changes in the code design
* 07-Apr-2014 TTR-938 D. Sushon Added test to verify TTR-938 fix,
* removed assertEquals for cases that are massaged/handled upstream
* </pre>
*
* @author Archana.S
* @version 1
*/
// TODO fix?
@Ignore
// TODO fix? @Ignore
public class CINTTest {
private static final double ALLOWABLE_DOUBLE_DELTA = 0.0001;
@ -47,14 +47,16 @@ public class CINTTest {
* contourInterval/minContourValue/maxContourValue
*/
public void testPositiveContourIntervalWithMinMaxValues() {
testCaseNumber = 1;
// testCaseNumber = 1;
CINT cint = new CINT("10/0.5/9");
CINT cint = new CINT("10/.5/9");
assertEquals(cint.isCINTStringParsed(), true);
testList = new ArrayList<Double>(Arrays.asList(0.5, 9.0));
testList = new ArrayList<Double>(Arrays.asList(.5, 9.));// Collections.emptyList();
keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
assertEquals(keySetList, testList);
// assertEquals(testList, keySetList);// this is a special case that
// can't be correctly handled at this level, upstream code provides full
// range when a value is unknown
assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
.doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
@ -367,7 +369,9 @@ public class CINTTest {
assertEquals(cint.isCINTStringParsed(), true);
testList = new ArrayList<Double>(Arrays.asList(-0.6));
keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
// assertEquals(keySetList,testList);
// assertEquals(keySetList,testList); //this test needs to be handled
// upstream, if no min/max range specified, CINT can't see what the
// data's range is
System.out.println("=====================Test-Case " + testCaseNumber
+ "a ========================");
@ -385,7 +389,9 @@ public class CINTTest {
testList2 = new ArrayList<Double>(Arrays.asList(0.7));
keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
// assertEquals(keySetList,testList);
// assertEquals(keySetList,testList); //this test needs to be handled
// upstream, if no min/max range specified, CINT can't see what the
// data's range is
System.out.println("=====================Test-Case " + testCaseNumber
+ "b ========================");
@ -418,8 +424,10 @@ public class CINTTest {
.doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
.doubleValue(), 70, ALLOWABLE_DOUBLE_DELTA);
//
testList = new ArrayList<Double>(Arrays.asList(10.0, 30.0, 50.0, 60.0));
// testList = new ArrayList<Double>(Arrays.asList(10.0, 30.0, 50.0,
// 60.0));<-- as inherited, doesn't look right or agree w/legacy/testin;
// fixing to:
testList = new ArrayList<Double>(Arrays.asList(20.0, 40.0, 60.0));
keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
assertEquals(keySetList, testList);
@ -542,7 +550,8 @@ public class CINTTest {
assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
.doubleValue(), 20, ALLOWABLE_DOUBLE_DELTA);
testList = new ArrayList<Double>(Arrays.asList(5.0, 10.0, 15.0, 20.0));
// assertEquals(cint2.getContourValuesList(),testList);
assertEquals(cint2.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL),
testList);
System.out.println("=====================Test-Case " + testCaseNumber
+ "b========================");
@ -799,14 +808,12 @@ public class CINTTest {
ALLOWABLE_DOUBLE_DELTA);
assertEquals(0.0000001, cint.getContourInterval(CINT.FIFTH_ZOOM_LEVEL)
.doubleValue(), ALLOWABLE_DOUBLE_DELTA);
// testList = new ArrayList<Double>(Arrays.asList(0.00009999));
// keySetList =
// cint.getContourValuesListAsDouble(CINT.FOURTH_ZOOM_LEVEL);
// assertEquals(testList,keySetList);
// testList = new ArrayList<Double>(Arrays.asList(0.0000001));
// keySetList =
// cint.getContourValuesListAsDouble(CINT.FIFTH_ZOOM_LEVEL);
assertEquals(testList, keySetList);
testList = new ArrayList<Double>(Arrays.asList(0.00009999));
keySetList = cint.getContourValuesListAsDouble(CINT.FOURTH_ZOOM_LEVEL);
// assertEquals(testList, keySetList);
testList = new ArrayList<Double>(Arrays.asList(0.0000001));
keySetList = cint.getContourValuesListAsDouble(CINT.FIFTH_ZOOM_LEVEL);
// assertEquals(testList, keySetList);
testList = new ArrayList<Double>(Arrays.asList(-6.0, -4.0, -2.0, 0.0,
2.0, 4.0, 6.0, 30.0, 50.0, 60.0, 80.0));
keySetList = cint.getUniqueSortedContourValuesFromAllZoomLevels();
@ -830,6 +837,8 @@ public class CINTTest {
System.out
.println("The unique contour values sorted in ascending order: "
+ cint.getUniqueSortedContourValuesFromAllZoomLevelsAsString());
testCaseNumber++;
}
/*
@ -859,6 +868,8 @@ public class CINTTest {
+ cint.getCintHashMap(CINT.FOURTH_ZOOM_LEVEL));
System.out.println("The HashMap at 5th zoom level"
+ cint.getCintHashMap(CINT.FIFTH_ZOOM_LEVEL));
testCaseNumber++;
}
/*
@ -875,6 +886,67 @@ public class CINTTest {
CINT cint = new CINT("2/-6/6/3 > > 60=abc; 80=def > > ");
System.out.println("Is CINT String parsed correctly? "
+ cint.isCINTStringParsed());
assertEquals(false, cint.isCINTStringParsed());
testCaseNumber++;
}
@Test
public void testTTR938() {
{
CINT cint = new CINT("1/-23.5/-22.5");
System.out.println("=====================Test-Case "
+ testCaseNumber
+ ", retest TTR 938 ========================");
System.out.println("The input string = "
+ cint.getUserInputString());
System.out.println("Is the contour data string parsed correctly? "
+ cint.isCINTStringParsed());
assertEquals(cint.isCINTStringParsed(), true);
System.out.println("Contour Interval = "
+ cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL));
System.out.println("Minimum Contour Level = "
+ cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL));
System.out.println("Maximum Contour Level = "
+ cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL));
List<Double> contourList = cint
.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
System.out
.println("Contour values list as double= " + contourList);
System.out.println("Set of contour values with padding digits = "
+ cint.getContourLabelsForZoomLevel(CINT.FIRST_ZOOM_LEVEL));
System.out.println("HashMap at first zoom level = "
+ cint.getCintHashMap(CINT.FIRST_ZOOM_LEVEL));
assertEquals(-23.0,
cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL)
.get(0), ALLOWABLE_DOUBLE_DELTA);
}
CINT cint2 = new CINT("1/22.5/23.5");
System.out.println("The input string = "
+ cint2.getUserInputString());
System.out.println("Is the contour data string parsed correctly? "
+ cint2.isCINTStringParsed());
assertEquals(cint2.isCINTStringParsed(), true);
System.out.println("Contour Interval = "
+ cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL));
System.out.println("Minimum Contour Level = "
+ cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL));
System.out.println("Maximum Contour Level = "
+ cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL));
List<Double> contourList = cint2
.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
System.out.println("Contour values list as double= " + contourList);
System.out.println("Set of contour values with padding digits = "
+ cint2.getContourLabelsForZoomLevel(CINT.FIRST_ZOOM_LEVEL));
System.out.println("HashMap at first zoom level = "
+ cint2.getCintHashMap(CINT.FIRST_ZOOM_LEVEL));
assertEquals(23.0,
cint2.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL)
.get(0), ALLOWABLE_DOUBLE_DELTA);
testCaseNumber++;
}
}

View file

@ -2,243 +2,290 @@ package gov.noaa.nws.ncep.gempak.parameters.intext;
import static org.junit.Assert.assertEquals;
import org.junit.Ignore;
import org.junit.Test;
/**
* TEXT format: size/font/width/hwflgs
*
* TEXT format: size/font/width/hwflgs (used by HLSYM) OR size/font/width/border/rotation/justification/hwflgs (used by TEXT)
*
*/
// TODO fix?
@Ignore
public class TextStringParserTest {
private static int testCaseNumber = 1;
private static int testCaseNumber=1;
@Test
public void testTextInputStringParse1 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with blank string----------------");
@Test
public void testTextInputStringParse1() {
TextStringParser txt = new TextStringParser("");
if ( ! txt.isTextParsed()) {
assertEquals (txt.isTextParsed(),false);
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse2 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with sizes----------------");
System.out.println("------------------Test-case " + testCaseNumber
+ " with blank string----------------");
TextStringParser txt = new TextStringParser("1.286");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 1.286f);
assertEquals (txt.getTextSize(), 18);
assertEquals (txt.getTextFont(), 1);
assertEquals (txt.getTextWidth(), 2);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse3 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size name ----------------");
TextStringParser txt = new TextStringParser("");
TextStringParser txt = new TextStringParser("tin");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 0.714f);
assertEquals (txt.getTextSize(), 10);
assertEquals (txt.getTextFont(), 1);
assertEquals (txt.getTextWidth(), 2);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse4 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/font ----------------");
if (!txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), false);
TextStringParser txt = new TextStringParser("1.286/2");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 1.286f);
assertEquals (txt.getTextSize(), 18);
assertEquals (txt.getTextFont(), 2);
assertEquals (txt.getTextWidth(), 2);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse5 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/invalid font ----------------");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
}
testCaseNumber++;
}
TextStringParser txt = new TextStringParser("1.286/5");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 1.286f);
assertEquals (txt.getTextSize(), 18);
assertEquals (txt.getTextFont(), 1);
assertEquals (txt.getTextWidth(), 2);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse6 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/ font / width ----------------");
@Test
public void testHLSYMInputStringParse2() {
TextStringParser txt = new TextStringParser("1.714/3/8");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 1.714f);
assertEquals (txt.getTextSize(), 24);
assertEquals (txt.getTextFont(), 3);
assertEquals (txt.getTextWidth(), 8);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse7 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/ font / width /hw flag ----------------");
System.out.println("------------------Test-case " + testCaseNumber
+ " with sizes----------------");
TextStringParser txt = new TextStringParser("2.429/2/8/HW");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 2.429f);
assertEquals (txt.getTextSize(), 34);
assertEquals (txt.getTextFont(), 2);
assertEquals (txt.getTextWidth(), 8);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testHLSYMInputStringParse8 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/ font / width /hw flag ----------------");
TextStringParser txt = new TextStringParser("1.286");
TextStringParser txt = new TextStringParser("2.429/2/8/SW");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getSymbolMarkerSize(), 2.429f);
assertEquals (txt.getTextSize(), 34);
assertEquals (txt.getTextFont(), 2);
assertEquals (txt.getTextWidth(), 8);
assertEquals (txt.getTextHWFlag(), "SW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testTEXTInputStringParse9 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/ font/ widthborder/ rotation/ justification /hw flag ----------------");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 1.286f);
assertEquals(txt.getTextSize(), 18);
assertEquals(txt.getTextFont(), 1);
assertEquals(txt.getTextWidth(), 2);
assertEquals(txt.getTextHWFlag(), "HW");
TextStringParser txt = new TextStringParser("2.429/3/8/221/N/L/HW");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getTextSize(), 34);
assertEquals (txt.getTextFont(), 3);
assertEquals (txt.getTextWidth(), 8);
assertEquals (txt.getTextBorder(), 221);
assertEquals (txt.getTextRotation(), 'N');
assertEquals (txt.getTextJustification(), 'L');
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text border : " + txt.getTextBorder() );
System.out.println ( " Text rotation : " + txt.getTextRotation() );
System.out.println ( " Text justification : " + txt.getTextJustification() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
@Test
public void testTEXTInputStringParse10 () {
System.out.println("------------------Test-case "+ testCaseNumber +" with size/ font/ widthborder/ rotation/ justification /hw flag ----------------");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
@Test
public void testHLSYMInputStringParse3() {
System.out.println("------------------Test-case " + testCaseNumber
+ " with size name ----------------");
TextStringParser txt = new TextStringParser("tin");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 0.714f);
assertEquals(txt.getTextSize(), 10);
assertEquals(txt.getTextFont(), 1);
assertEquals(txt.getTextWidth(), 2);
assertEquals(txt.getTextHWFlag(), "HW");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
@Test
public void testHLSYMInputStringParse4() {
System.out.println("------------------Test-case " + testCaseNumber
+ " with size/font ----------------");
TextStringParser txt = new TextStringParser("1.286/2");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 1.286f);
assertEquals(txt.getTextSize(), 18);
assertEquals(txt.getTextFont(), 2);
assertEquals(txt.getTextWidth(), 2);
assertEquals(txt.getTextHWFlag(), "HW");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
@Test
public void testHLSYMInputStringParse5() {
System.out.println("------------------Test-case " + testCaseNumber
+ " with size/invalid font ----------------");
TextStringParser txt = new TextStringParser("1.286/5");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 1.286f);
assertEquals(txt.getTextSize(), 18);
assertEquals(txt.getTextFont(), 1);
assertEquals(txt.getTextWidth(), 2);
assertEquals(txt.getTextHWFlag(), "HW");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
@Test
public void testHLSYMInputStringParse6() {
System.out.println("------------------Test-case " + testCaseNumber
+ " with size/ font / width ----------------");
TextStringParser txt = new TextStringParser("1.714/3/8");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 1.714f);
assertEquals(txt.getTextSize(), 24);
assertEquals(txt.getTextFont(), 3);
assertEquals(txt.getTextWidth(), 8);
assertEquals(txt.getTextHWFlag(), "HW");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
@Test
public void testHLSYMInputStringParse7() {
System.out.println("------------------Test-case " + testCaseNumber
+ " with size/ font / width /hw flag ----------------");
TextStringParser txt = new TextStringParser("2.429/2/8/HW");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 2.429f);
assertEquals(txt.getTextSize(), 34);
assertEquals(txt.getTextFont(), 2);
assertEquals(txt.getTextWidth(), 8);
assertEquals(txt.getTextHWFlag(), "HW");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
@Test
public void testHLSYMInputStringParse8() {
System.out.println("------------------Test-case " + testCaseNumber
+ " with size/ font / width /hw flag ----------------");
TextStringParser txt = new TextStringParser("2.429/2/8/SW");
if (txt.isTextParsed()) {
assertEquals(txt.isTextParsed(), true);
assertEquals(txt.getSymbolMarkerSize(), 2.429f);
assertEquals(txt.getTextSize(), 34);
assertEquals(txt.getTextFont(), 2);
assertEquals(txt.getTextWidth(), 8);
assertEquals(txt.getTextHWFlag(), "SW");
System.out.println("--User Input Text parameter:"
+ txt.getInputTextString());
System.out.println("-----------------------------");
System.out.println(" Symbol/Marker size : "
+ txt.getSymbolMarkerSize());
System.out.println(" Text size : " + txt.getTextSize());
System.out.println(" Text font : " + txt.getTextFont());
System.out.println(" Text width : " + txt.getTextWidth());
System.out.println(" Text hwflg : " + txt.getTextHWFlag());
}
testCaseNumber++;
}
TextStringParser txt = new TextStringParser("1/23/8////HW");
if ( txt.isTextParsed() ) {
assertEquals (txt.isTextParsed(),true);
assertEquals (txt.getTextSize(), 14);
//assertEquals (txt.getTextFont(), 3);
//assertEquals (txt.getTextStyle(), 2);
assertEquals (txt.getTextWidth(), 8);
assertEquals (txt.getTextHWFlag(), "HW");
System.out.println ( "--User Input Text parameter:" + txt.getInputTextString() );
System.out.println ( "-----------------------------" );
System.out.println ( " Symbol/Marker size : " + txt.getSymbolMarkerSize() );
System.out.println ( " Text size : " + txt.getTextSize() );
System.out.println ( " Text font : " + txt.getTextFont() );
System.out.println ( " Text style : " + txt.getTextStyle() );
System.out.println ( " Text width : " + txt.getTextWidth() );
System.out.println ( " Text border : " + txt.getTextBorder() );
System.out.println ( " Text rotation : " + txt.getTextRotation() );
System.out.println ( " Text justification : " + txt.getTextJustification() );
System.out.println ( " Text hwflg : " + txt.getTextHWFlag() );
}
testCaseNumber ++;
}
}