diff --git a/RadarServer/build.rcm/customTargets.xml b/RadarServer/build.rcm/customTargets.xml index 8394f04df5..3ec14fe57a 100644 --- a/RadarServer/build.rcm/customTargets.xml +++ b/RadarServer/build.rcm/customTargets.xml @@ -88,6 +88,7 @@ + diff --git a/RadarServer/com.raytheon.rcm.feature/feature.xml b/RadarServer/com.raytheon.rcm.feature/feature.xml index 1ab17e3d94..b01cdbfbe0 100644 --- a/RadarServer/com.raytheon.rcm.feature/feature.xml +++ b/RadarServer/com.raytheon.rcm.feature/feature.xml @@ -42,6 +42,13 @@ install-size="0" version="0.0.0" unpack="false"/> + + + + + + + diff --git a/cave/build/cave/customTargets.xml b/cave/build/cave/customTargets.xml index e3644b19ad..3d9b0e43c5 100644 --- a/cave/build/cave/customTargets.xml +++ b/cave/build/cave/customTargets.xml @@ -112,6 +112,11 @@ + + + + + diff --git a/cave/build/p2-build.xml b/cave/build/p2-build.xml index eafc720c43..c9d3bd9fb5 100644 --- a/cave/build/p2-build.xml +++ b/cave/build/p2-build.xml @@ -147,6 +147,8 @@ + + + + + + + + + + + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/DefaultRadarCodedMessage.xml b/cave/build/static/common/cave/etc/bundles/DefaultRadarCodedMessage.xml index 66449903f5..fc9f67dd1c 100644 --- a/cave/build/static/common/cave/etc/bundles/DefaultRadarCodedMessage.xml +++ b/cave/build/static/common/cave/etc/bundles/DefaultRadarCodedMessage.xml @@ -36,16 +36,16 @@ - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/NOHRSC-SNOW.xml b/cave/build/static/common/cave/etc/bundles/NOHRSC-SNOW.xml index a6308b54af..73c2fba99c 100644 --- a/cave/build/static/common/cave/etc/bundles/NOHRSC-SNOW.xml +++ b/cave/build/static/common/cave/etc/bundles/NOHRSC-SNOW.xml @@ -36,22 +36,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/SingleGrib.xml b/cave/build/static/common/cave/etc/bundles/SingleGrib.xml index 55dde2f7c5..dacf73d2de 100644 --- a/cave/build/static/common/cave/etc/bundles/SingleGrib.xml +++ b/cave/build/static/common/cave/etc/bundles/SingleGrib.xml @@ -11,22 +11,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/HPC6hrQPF.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/HPC6hrQPF.xml index d4fb13d686..fc26987777 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/HPC6hrQPF.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/HPC6hrQPF.xml @@ -27,17 +27,17 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD-PPFFG.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD-PPFFG.xml index 6c1c974062..83ac282080 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD-PPFFG.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD-PPFFG.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD120hr.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD120hr.xml index 7b0169f733..ada2bf8143 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD120hr.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD120hr.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD48hr.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD48hr.xml index ea887acf73..db3eba6fa5 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD48hr.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD48hr.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD6hr.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD6hr.xml index 50b534fd7d..c95d380949 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD6hr.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/HPCqpfNDFD6hr.xml @@ -27,17 +27,17 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN-PPBN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN-PPBN.xml index db19c6f002..e970dae138 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN-PPBN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN-PPBN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + @@ -61,18 +61,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN.xml index 2be7cf63d8..37a9522360 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PPAN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PPBN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PPBN.xml index 7adb9fe952..36185fa748 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PPBN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PPBN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PPNN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PPNN.xml index 8c85f6c2b6..b781edef44 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PPNN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PPNN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN-PTBN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN-PTBN.xml index de4c562641..20512cf731 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN-PTBN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN-PTBN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + @@ -61,18 +61,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN.xml index 33b9887ba8..457bb89cdc 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PTAN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PTBN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PTBN.xml index 8a19a2015c..ae6e92d985 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PTBN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PTBN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/miscGrids/PTNN.xml b/cave/build/static/common/cave/etc/bundles/miscGrids/PTNN.xml index e7a470b00d..dad59c6847 100644 --- a/cave/build/static/common/cave/etc/bundles/miscGrids/PTNN.xml +++ b/cave/build/static/common/cave/etc/bundles/miscGrids/PTNN.xml @@ -27,18 +27,18 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/500Height.xml b/cave/build/static/common/cave/etc/bundles/volume/500Height.xml index 41d2d03a25..1dc5b4b1e4 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/500Height.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/500Height.xml @@ -41,22 +41,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -81,22 +81,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -122,22 +122,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -162,22 +162,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -202,22 +202,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -242,22 +242,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -282,22 +282,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -323,22 +323,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -364,22 +364,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -405,22 +405,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -444,22 +444,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -482,22 +482,22 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/DefaultFamily.xml b/cave/build/static/common/cave/etc/bundles/volume/DefaultFamily.xml index 87b7b3ff13..7367463aab 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/DefaultFamily.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/DefaultFamily.xml @@ -15,22 +15,22 @@ - + - + - + - + - + - + @@ -49,22 +49,22 @@ - + - + - + - + - + - + @@ -83,19 +83,19 @@ - + - + - + - + - + @@ -114,22 +114,22 @@ - + - + - + - + - + - + @@ -148,22 +148,22 @@ - + - + - + - + - + - + @@ -182,22 +182,22 @@ - + - + - + - + - + - + @@ -216,22 +216,22 @@ - + - + - + - + - + - + @@ -250,19 +250,19 @@ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/DefaultFourPanel.xml b/cave/build/static/common/cave/etc/bundles/volume/DefaultFourPanel.xml index b3e83660a1..f017b6068c 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/DefaultFourPanel.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/DefaultFourPanel.xml @@ -14,22 +14,22 @@ - + - + - + - + - + - + @@ -48,22 +48,22 @@ - + - + - + - + - + - + @@ -88,22 +88,22 @@ - + - + - + - + - + - + @@ -124,19 +124,19 @@ - + - + - + - + - + @@ -161,22 +161,22 @@ - + - + - + - + - + - + @@ -196,22 +196,22 @@ - + - + - + - + - + - + @@ -236,22 +236,22 @@ - + - + - + - + - + - + @@ -270,22 +270,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/DefaultStdEnv.xml b/cave/build/static/common/cave/etc/bundles/volume/DefaultStdEnv.xml index 3422d953b9..1ad3b2728b 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/DefaultStdEnv.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/DefaultStdEnv.xml @@ -15,19 +15,19 @@ - + - + - + - + - + @@ -46,19 +46,19 @@ - + - + - + - + - + @@ -77,19 +77,19 @@ - + - + - + - + - + @@ -108,19 +108,19 @@ - + - + - + - + - + @@ -139,19 +139,19 @@ - + - + - + - + - + @@ -170,19 +170,19 @@ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/DefaultSurface.xml b/cave/build/static/common/cave/etc/bundles/volume/DefaultSurface.xml index a76c608382..544ddff7db 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/DefaultSurface.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/DefaultSurface.xml @@ -11,22 +11,22 @@ - + - + - + - + - + - + @@ -46,22 +46,22 @@ - + - + - + - + - + - + @@ -81,22 +81,22 @@ - + - + - + - + - + - + @@ -116,22 +116,22 @@ - + - + - + - + - + - + @@ -151,22 +151,22 @@ - + - + - + - + - + - + @@ -186,22 +186,22 @@ - + - + - + - + - + - + @@ -221,22 +221,22 @@ - + - + - + - + - + - + @@ -259,22 +259,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiRes.xml b/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiRes.xml index 5197d5902c..b0ac14ef71 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiRes.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiRes.xml @@ -35,24 +35,24 @@ - + - + - + - + - + - + @@ -68,22 +68,22 @@ - + - + - + - + - + - + @@ -103,14 +103,14 @@ - + - + - + @@ -125,22 +125,22 @@ - + - + - + - + - + - + @@ -160,24 +160,24 @@ - + - + - + - + - + - + @@ -193,22 +193,22 @@ - + - + - + - + - + - + @@ -224,22 +224,22 @@ - + - + - + - + - + - + @@ -259,14 +259,14 @@ - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiResFourPanel.xml b/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiResFourPanel.xml index 8888bae1c5..7478c6d458 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiResFourPanel.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ECMWFHiResFourPanel.xml @@ -14,22 +14,22 @@ - + - + - + - + - + - + @@ -50,24 +50,24 @@ - + - + - + - + - + - + @@ -94,22 +94,22 @@ - + - + - + - + - + - + @@ -130,22 +130,22 @@ - + - + - + - + - + - + @@ -172,14 +172,14 @@ - + - + - + @@ -199,22 +199,22 @@ - + - + - + - + - + - + @@ -241,22 +241,22 @@ - + - + - + - + - + - + @@ -277,24 +277,24 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ECMWFLowRes.xml b/cave/build/static/common/cave/etc/bundles/volume/ECMWFLowRes.xml index e4386d7a9f..e8242c19df 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ECMWFLowRes.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ECMWFLowRes.xml @@ -35,24 +35,24 @@ - + - + - + - + - + - + @@ -68,22 +68,22 @@ - + - + - + - + - + - + @@ -103,14 +103,14 @@ - + - + - + @@ -125,22 +125,22 @@ - + - + - + - + - + - + @@ -160,24 +160,24 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/LimitedFamily.xml b/cave/build/static/common/cave/etc/bundles/volume/LimitedFamily.xml index 75fa2dadbb..2c43d347b8 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/LimitedFamily.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/LimitedFamily.xml @@ -15,22 +15,22 @@ - + - + - + - + - + - + @@ -49,22 +49,22 @@ - + - + - + - + - + - + @@ -83,14 +83,14 @@ - + - + - + @@ -108,22 +108,22 @@ - + - + - + - + - + - + @@ -142,22 +142,22 @@ - + - + - + - + - + - + @@ -176,22 +176,22 @@ - + - + - + - + - + - + @@ -210,19 +210,19 @@ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/MSLPress.xml b/cave/build/static/common/cave/etc/bundles/volume/MSLPress.xml index 237800647b..5b7953e92d 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/MSLPress.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/MSLPress.xml @@ -36,19 +36,19 @@ - + - + - + - + - + @@ -68,19 +68,19 @@ - + - + - + - + - + @@ -100,19 +100,19 @@ - + - + - + - + - + @@ -132,19 +132,19 @@ - + - + - + - + - + @@ -164,19 +164,19 @@ - + - + - + - + - + @@ -196,19 +196,19 @@ - + - + - + - + - + @@ -228,19 +228,19 @@ - + - + - + - + - + @@ -260,19 +260,19 @@ - + - + - + - + - + @@ -292,19 +292,19 @@ - + - + - + - + - + @@ -324,19 +324,19 @@ - + - + - + - + - + @@ -355,19 +355,19 @@ - + - + - + - + - + @@ -386,19 +386,19 @@ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyA.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyA.xml index 4c3d6ed899..7bfb35758e 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyA.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyA.xml @@ -32,22 +32,22 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + @@ -61,22 +61,22 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + @@ -93,22 +93,22 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + @@ -128,22 +128,22 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + @@ -166,19 +166,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -199,19 +199,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -232,19 +232,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -265,19 +265,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -298,24 +298,24 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + @@ -336,19 +336,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -369,20 +369,20 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -403,19 +403,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -436,19 +436,19 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + @@ -471,23 +471,23 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + @@ -510,23 +510,23 @@ ModFamA| |N|Conv: NonSupercell Tor Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyB.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyB.xml index 6e57d71239..dff95859dd 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyB.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyB.xml @@ -29,22 +29,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -58,22 +58,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -90,22 +90,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -125,22 +125,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -163,19 +163,19 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + @@ -190,22 +190,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -222,23 +222,23 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -258,22 +258,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -296,20 +296,20 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + @@ -324,22 +324,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -356,22 +356,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -391,22 +391,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -429,20 +429,20 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + @@ -463,19 +463,19 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + @@ -490,22 +490,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -522,22 +522,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + @@ -557,22 +557,22 @@ ModFamB| |N|Conv: Storm Init Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyC.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyC.xml index c0a0d99ab2..10a80f7b61 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyC.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyC.xml @@ -36,22 +36,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -72,19 +72,19 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + @@ -105,22 +105,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -141,19 +141,19 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + @@ -168,22 +168,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -200,23 +200,23 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -236,22 +236,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -274,20 +274,20 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + @@ -309,23 +309,23 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -346,23 +346,23 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -383,23 +383,23 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -420,23 +420,23 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -457,23 +457,23 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -494,22 +494,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -530,22 +530,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -566,22 +566,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -602,22 +602,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -638,22 +638,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + @@ -674,22 +674,22 @@ ModFamC| |N|Conv: Hail Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyD.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyD.xml index 26e76a4310..fb9cb3d22b 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyD.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyD.xml @@ -43,22 +43,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -72,22 +72,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -104,22 +104,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -139,22 +139,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -171,22 +171,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -203,22 +203,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -238,22 +238,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -270,22 +270,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -302,22 +302,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -337,22 +337,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -369,22 +369,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -401,22 +401,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -436,22 +436,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -468,22 +468,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -500,22 +500,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -535,22 +535,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -573,19 +573,19 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + @@ -606,23 +606,23 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -643,20 +643,20 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + @@ -677,19 +677,19 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + @@ -704,22 +704,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -736,22 +736,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -771,22 +771,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -809,22 +809,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -845,22 +845,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -881,22 +881,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -917,22 +917,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -953,22 +953,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -983,22 +983,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1015,22 +1015,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1050,22 +1050,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1088,22 +1088,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1124,22 +1124,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1154,22 +1154,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1186,22 +1186,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1221,22 +1221,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1259,22 +1259,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1289,22 +1289,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1321,22 +1321,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1356,22 +1356,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1388,22 +1388,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1420,22 +1420,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1455,22 +1455,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1487,22 +1487,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1519,22 +1519,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + @@ -1554,22 +1554,22 @@ ModFamD| |N|Winter: Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyE.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyE.xml index 74d65b9f6f..7464274f08 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyE.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyE.xml @@ -31,19 +31,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -64,19 +64,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -98,19 +98,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -139,19 +139,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -172,19 +172,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -205,19 +205,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -246,19 +246,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -279,19 +279,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -312,19 +312,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -353,19 +353,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -386,19 +386,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -419,19 +419,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -453,19 +453,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + @@ -486,19 +486,19 @@ ModFamE| |N|Winter: PV/Trop Family| |OTHER | | \ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyF.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyF.xml index 09d284cd8a..0bdaad187d 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyF.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyF.xml @@ -29,22 +29,22 @@ - + - + - + - + - + - + @@ -80,22 +80,22 @@ - + - + - + - + - + - + @@ -118,22 +118,22 @@ - + - + - + - + - + - + @@ -158,22 +158,22 @@ - + - + - + - + - + - + @@ -196,22 +196,22 @@ - + - + - + - + - + - + @@ -234,22 +234,22 @@ - + - + - + - + - + - + @@ -272,22 +272,22 @@ - + - + - + - + - + - + @@ -315,22 +315,22 @@ - + - + - + - + - + - + @@ -366,22 +366,22 @@ - + - + - + - + - + - + @@ -404,22 +404,22 @@ - + - + - + - + - + - + @@ -444,22 +444,22 @@ - + - + - + - + - + - + @@ -482,22 +482,22 @@ - + - + - + - + - + - + @@ -520,22 +520,22 @@ - + - + - + - + - + - + @@ -558,22 +558,22 @@ - + - + - + - + - + - + @@ -601,22 +601,22 @@ - + - + - + - + - + - + @@ -652,22 +652,22 @@ - + - + - + - + - + - + @@ -690,22 +690,22 @@ - + - + - + - + - + - + @@ -730,22 +730,22 @@ - + - + - + - + - + - + @@ -768,22 +768,22 @@ - + - + - + - + - + - + @@ -806,22 +806,22 @@ - + - + - + - + - + - + @@ -844,22 +844,22 @@ - + - + - + - + - + - + @@ -887,22 +887,22 @@ - + - + - + - + - + - + @@ -938,22 +938,22 @@ - + - + - + - + - + - + @@ -976,22 +976,22 @@ - + - + - + - + - + - + @@ -1016,22 +1016,22 @@ - + - + - + - + - + - + @@ -1054,22 +1054,22 @@ - + - + - + - + - + - + @@ -1092,22 +1092,22 @@ - + - + - + - + - + - + @@ -1130,22 +1130,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyH.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyH.xml index c41df6f892..6fbc209871 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyH.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyH.xml @@ -48,19 +48,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -81,19 +81,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -114,19 +114,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -141,22 +141,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -173,22 +173,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -208,19 +208,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -243,20 +243,20 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -271,22 +271,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -303,20 +303,20 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -336,19 +336,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -371,19 +371,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -398,22 +398,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -430,23 +430,23 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -466,22 +466,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -498,22 +498,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -530,23 +530,23 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -566,22 +566,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -604,22 +604,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -640,22 +640,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -676,22 +676,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -712,22 +712,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -748,22 +748,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -784,22 +784,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -820,22 +820,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -856,22 +856,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -892,22 +892,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -928,22 +928,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -964,22 +964,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -1000,19 +1000,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -1027,22 +1027,22 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + - + @@ -1059,19 +1059,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + @@ -1091,19 +1091,19 @@ ModFamH | | N|Conv: QLCS/Wind Family| | OTHER| | - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyI.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyI.xml index b36a1a68f2..03d0fba0c1 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyI.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyI.xml @@ -32,20 +32,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -66,23 +66,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -103,20 +103,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -137,23 +137,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -174,23 +174,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -219,20 +219,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -253,23 +253,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -290,20 +290,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -324,23 +324,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -361,23 +361,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -406,20 +406,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -440,23 +440,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -477,20 +477,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -511,23 +511,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -548,23 +548,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -592,20 +592,20 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -626,23 +626,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -663,19 +663,19 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + @@ -696,23 +696,23 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + @@ -733,22 +733,22 @@ ModFamI| |N|Winter: Big3 Fn Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyJ.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyJ.xml index fe939b7120..9bd3b15ea5 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyJ.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyJ.xml @@ -31,20 +31,20 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -65,22 +65,22 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + - + @@ -101,22 +101,22 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + - + @@ -137,22 +137,22 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + - + @@ -180,20 +180,20 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -214,20 +214,20 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -256,19 +256,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -289,19 +289,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -322,19 +322,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -355,19 +355,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -389,19 +389,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -422,19 +422,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -463,19 +463,19 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -496,20 +496,20 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + @@ -530,20 +530,20 @@ ModFamJ| |N|Winter: Snow Growth Family| |OTHER | | \ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyL.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyL.xml index b586af6e14..5a68a6157c 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyL.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyL.xml @@ -34,19 +34,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -68,19 +68,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -101,19 +101,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -134,19 +134,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -168,19 +168,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -201,19 +201,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -234,19 +234,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -267,19 +267,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -300,19 +300,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -333,19 +333,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -374,22 +374,22 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + - + @@ -410,19 +410,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -443,22 +443,22 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + - + @@ -479,19 +479,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -512,19 +512,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -546,19 +546,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -579,20 +579,20 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -613,20 +613,20 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -647,20 +647,20 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -681,20 +681,20 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -723,23 +723,23 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + - + @@ -761,19 +761,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -794,19 +794,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -827,20 +827,20 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -861,19 +861,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -902,22 +902,22 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + - + @@ -938,19 +938,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -971,19 +971,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -1004,22 +1004,22 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + - + @@ -1040,19 +1040,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + @@ -1073,19 +1073,19 @@ ModFamL| |N|Winter: PType Family| |OTHER | | \ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyM.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyM.xml index 5bcb7d0164..8a847ff9f7 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyM.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyM.xml @@ -24,22 +24,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -60,22 +60,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -96,22 +96,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -132,22 +132,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -168,22 +168,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -211,22 +211,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -247,22 +247,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -283,22 +283,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -319,22 +319,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -355,22 +355,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -398,22 +398,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -434,22 +434,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -470,22 +470,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -506,22 +506,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -542,22 +542,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -585,22 +585,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -621,22 +621,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -657,22 +657,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -693,22 +693,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + @@ -729,22 +729,22 @@ ModFamM| |N|Winter: Big3 Qn Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyU.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyU.xml index c889eb0f27..ed14cd5b97 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyU.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyU.xml @@ -39,22 +39,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -68,22 +68,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -100,22 +100,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -135,22 +135,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -167,22 +167,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -199,22 +199,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -234,22 +234,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -266,22 +266,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -298,22 +298,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -333,22 +333,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -365,22 +365,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -397,22 +397,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -432,22 +432,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -464,22 +464,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -496,22 +496,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -531,22 +531,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -569,19 +569,19 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + @@ -596,22 +596,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -628,22 +628,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -663,22 +663,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -701,22 +701,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -737,22 +737,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -773,22 +773,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -809,22 +809,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -845,22 +845,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -875,22 +875,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -907,22 +907,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -942,22 +942,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -980,22 +980,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1016,22 +1016,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1046,22 +1046,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1078,22 +1078,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1113,22 +1113,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1151,22 +1151,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1181,22 +1181,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1213,22 +1213,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1248,22 +1248,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1280,22 +1280,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1312,22 +1312,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1347,22 +1347,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1379,22 +1379,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1411,22 +1411,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + @@ -1446,22 +1446,22 @@ ModFamU| |N|Briefing Family| |OTHER | | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyV.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyV.xml index 338c6abba8..b7fe7fff6a 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyV.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyV.xml @@ -40,22 +40,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -76,19 +76,19 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + @@ -109,20 +109,20 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + @@ -137,22 +137,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -170,23 +170,23 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -206,22 +206,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -244,19 +244,19 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + @@ -277,22 +277,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -313,22 +313,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -343,22 +343,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -376,22 +376,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -411,22 +411,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -449,23 +449,23 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -481,22 +481,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -514,22 +514,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -549,22 +549,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -587,22 +587,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -623,22 +623,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -659,22 +659,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -695,22 +695,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -731,22 +731,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -767,22 +767,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -804,20 +804,20 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + @@ -838,22 +838,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -874,22 +874,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -904,22 +904,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + @@ -937,19 +937,19 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + @@ -969,22 +969,22 @@ ModFamV | | N|Conv: Severe Type Family| | OTHER| | \ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyW.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyW.xml index fdae584acd..11ae214077 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyW.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyW.xml @@ -40,22 +40,22 @@ - + - + - + - + - + - + @@ -76,19 +76,19 @@ - + - + - + - + - + @@ -109,19 +109,19 @@ - + - + - + - + - + @@ -137,22 +137,22 @@ - + - + - + - + - + - + @@ -169,22 +169,22 @@ - + - + - + - + - + - + @@ -204,22 +204,22 @@ - + - + - + - + - + - + @@ -237,22 +237,22 @@ - + - + - + - + - + - + @@ -269,22 +269,22 @@ - + - + - + - + - + - + @@ -304,22 +304,22 @@ - + - + - + - + - + - + @@ -342,22 +342,22 @@ - + - + - + - + - + - + @@ -373,22 +373,22 @@ - + - + - + - + - + - + @@ -405,22 +405,22 @@ - + - + - + - + - + - + @@ -440,22 +440,22 @@ - + - + - + - + - + - + @@ -479,22 +479,22 @@ - + - + - + - + - + - + @@ -515,22 +515,22 @@ - + - + - + - + - + - + @@ -546,22 +546,22 @@ - + - + - + - + - + - + @@ -578,22 +578,22 @@ - + - + - + - + - + - + @@ -613,22 +613,22 @@ - + - + - + - + - + - + @@ -646,22 +646,22 @@ - + - + - + - + - + - + @@ -678,22 +678,22 @@ - + - + - + - + - + - + @@ -713,22 +713,22 @@ - + - + - + - + - + - + @@ -751,22 +751,22 @@ - + - + - + - + - + - + @@ -787,19 +787,19 @@ - + - + - + - + - + @@ -820,19 +820,19 @@ - + - + - + - + - + @@ -853,19 +853,19 @@ - + - + - + - + - + @@ -886,19 +886,19 @@ - + - + - + - + - + @@ -919,22 +919,22 @@ - + - + - + - + - + - + @@ -955,22 +955,22 @@ - + - + - + - + - + - + @@ -991,22 +991,22 @@ - + - + - + - + - + - + @@ -1027,22 +1027,22 @@ - + - + - + - + - + - + @@ -1063,22 +1063,22 @@ - + - + - + - + - + - + @@ -1095,22 +1095,22 @@ - + - + - + - + - + - + @@ -1127,22 +1127,22 @@ - + - + - + - + - + - + @@ -1162,22 +1162,22 @@ - + - + - + - + - + - + @@ -1196,22 +1196,22 @@ - + - + - + - + - + - + @@ -1228,22 +1228,22 @@ - + - + - + - + - + - + @@ -1263,22 +1263,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyX.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyX.xml index ff0c7f4966..13ea2f7a5c 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyX.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyX.xml @@ -15,22 +15,22 @@ - + - + - + - + - + - + @@ -51,19 +51,19 @@ - + - + - + - + - + @@ -84,19 +84,19 @@ - + - + - + - + - + @@ -112,22 +112,22 @@ - + - + - + - + - + - + @@ -144,22 +144,22 @@ - + - + - + - + - + - + @@ -179,22 +179,22 @@ - + - + - + - + - + - + @@ -217,19 +217,19 @@ - + - + - + - + - + @@ -250,22 +250,22 @@ - + - + - + - + - + - + @@ -286,23 +286,23 @@ - + - + - + - + - + - + @@ -323,22 +323,22 @@ - + - + - + - + - + - + @@ -360,22 +360,22 @@ - + - + - + - + - + - + @@ -396,19 +396,19 @@ - + - + - + - + - + @@ -429,19 +429,19 @@ - + - + - + - + - + @@ -462,23 +462,23 @@ - + - + - + - + - + - + @@ -499,23 +499,23 @@ - + - + - + - + - + - + @@ -537,22 +537,22 @@ - + - + - + - + - + - + @@ -574,22 +574,22 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyY.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyY.xml index b0c9c7f21a..1bb9f5a9cd 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyY.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyY.xml @@ -26,22 +26,22 @@ - + - + - + - + - + - + @@ -62,22 +62,22 @@ - + - + - + - + - + - + @@ -98,22 +98,22 @@ - + - + - + - + - + - + @@ -129,22 +129,22 @@ - + - + - + - + - + - + @@ -161,22 +161,22 @@ - + - + - + - + - + - + @@ -196,22 +196,22 @@ - + - + - + - + - + - + @@ -229,22 +229,22 @@ - + - + - + - + - + - + @@ -261,22 +261,22 @@ - + - + - + - + - + - + @@ -296,22 +296,22 @@ - + - + - + - + - + - + @@ -329,22 +329,22 @@ - + - + - + - + - + - + @@ -361,22 +361,22 @@ - + - + - + - + - + - + @@ -396,22 +396,22 @@ - + - + - + - + - + - + @@ -434,19 +434,19 @@ - + - + - + - + - + @@ -475,19 +475,19 @@ - + - + - + - + - + @@ -508,19 +508,19 @@ - + - + - + - + - + @@ -541,22 +541,22 @@ - + - + - + - + - + - + @@ -577,19 +577,19 @@ - + - + - + - + - + @@ -612,22 +612,22 @@ - + - + - + - + - + - + @@ -644,22 +644,22 @@ - + - + - + - + - + - + @@ -679,22 +679,22 @@ - + - + - + - + - + - + @@ -717,19 +717,19 @@ - + - + - + - + - + @@ -750,19 +750,19 @@ - + - + - + - + - + @@ -792,19 +792,19 @@ - + - + - + - + - + @@ -825,19 +825,19 @@ - + - + - + - + - + @@ -858,20 +858,20 @@ - + - + - + - + - + @@ -892,23 +892,23 @@ - + - + - + - + - + - + @@ -929,23 +929,23 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyYY.xml b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyYY.xml index 4a04ec061f..67c3e4954d 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyYY.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/ModelFamilyYY.xml @@ -37,19 +37,19 @@ - + - + - + - + - + @@ -70,19 +70,19 @@ - + - + - + - + - + @@ -103,19 +103,19 @@ - + - + - + - + - + @@ -131,22 +131,22 @@ - + - + - + - + - + - + @@ -163,22 +163,22 @@ - + - + - + - + - + - + @@ -198,22 +198,22 @@ - + - + - + - + - + - + @@ -231,22 +231,22 @@ - + - + - + - + - + - + @@ -263,22 +263,22 @@ - + - + - + - + - + - + @@ -298,22 +298,22 @@ - + - + - + - + - + - + @@ -331,22 +331,22 @@ - + - + - + - + - + - + @@ -363,22 +363,22 @@ - + - + - + - + - + - + @@ -398,22 +398,22 @@ - + - + - + - + - + - + @@ -431,22 +431,22 @@ - + - + - + - + - + - + @@ -463,22 +463,22 @@ - + - + - + - + - + - + @@ -498,22 +498,22 @@ - + - + - + - + - + - + @@ -537,19 +537,19 @@ - + - + - + - + - + @@ -570,19 +570,19 @@ - + - + - + - + - + @@ -603,22 +603,22 @@ - + - + - + - + - + - + @@ -639,19 +639,19 @@ - + - + - + - + - + @@ -672,19 +672,19 @@ - + - + - + - + - + @@ -705,19 +705,19 @@ - + - + - + - + - + @@ -733,22 +733,22 @@ - + - + - + - + - + - + @@ -765,22 +765,22 @@ - + - + - + - + - + - + @@ -800,22 +800,22 @@ - + - + - + - + - + - + @@ -838,19 +838,19 @@ - + - + - + - + - + @@ -871,19 +871,19 @@ - + - + - + - + - + @@ -904,22 +904,22 @@ - + - + - + - + - + - + @@ -940,23 +940,23 @@ - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/UKMET.xml b/cave/build/static/common/cave/etc/bundles/volume/UKMET.xml index f04961513a..20449dce3b 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/UKMET.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/UKMET.xml @@ -15,22 +15,22 @@ - + - + - + - + - + - + @@ -49,22 +49,22 @@ - + - + - + - + - + - + @@ -83,19 +83,19 @@ - + - + - + - + - + @@ -114,22 +114,22 @@ - + - + - + - + - + - + @@ -148,22 +148,22 @@ - + - + - + - + - + - + @@ -182,22 +182,22 @@ - + - + - + - + - + - + @@ -216,19 +216,19 @@ - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/bundles/volume/UKMETFourPanel.xml b/cave/build/static/common/cave/etc/bundles/volume/UKMETFourPanel.xml index 8a717745be..fc85d0ceb4 100644 --- a/cave/build/static/common/cave/etc/bundles/volume/UKMETFourPanel.xml +++ b/cave/build/static/common/cave/etc/bundles/volume/UKMETFourPanel.xml @@ -14,22 +14,22 @@ - + - + - + - + - + - + @@ -48,22 +48,22 @@ - + - + - + - + - + - + @@ -96,23 +96,23 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -136,20 +136,20 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + @@ -174,22 +174,22 @@ - + - + - + - + - + - + @@ -222,23 +222,23 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + @@ -262,23 +262,23 @@ retrieveData="true" isUpdatingOnMetadataOnly="false" isRequeryNecessaryOnTimeMatch="true"> - + - + - + - + - + - + diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseAlaska.xml b/cave/build/static/common/cave/etc/menus/upperair/baseAlaska.xml index 019d9de459..daa46844e2 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseAlaska.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseAlaska.xml @@ -20,7 +20,7 @@ --> diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseCanadaEastern.xml b/cave/build/static/common/cave/etc/menus/upperair/baseCanadaEastern.xml index 47048c0dec..b032982927 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseCanadaEastern.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseCanadaEastern.xml @@ -65,7 +65,7 @@ diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseCanadaNorth.xml b/cave/build/static/common/cave/etc/menus/upperair/baseCanadaNorth.xml index 4bc4ebf133..6c3d0eccba 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseCanadaNorth.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseCanadaNorth.xml @@ -20,7 +20,7 @@ --> diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseEastNPN.xml b/cave/build/static/common/cave/etc/menus/upperair/baseEastNPN.xml index 01d6023e72..c82cdb053e 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseEastNPN.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseEastNPN.xml @@ -41,7 +41,7 @@ /profiler/%/3000/74752/% @@ -55,7 +55,7 @@ /profiler/%/3000/74648/% @@ -118,7 +118,7 @@ /profiler/%/3000/74556/% diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseJapan.xml b/cave/build/static/common/cave/etc/menus/upperair/baseJapan.xml index 1278ee935b..5059c2c680 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseJapan.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseJapan.xml @@ -30,9 +30,9 @@ - + @@ -158,12 +158,12 @@ diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseMexico.xml b/cave/build/static/common/cave/etc/menus/upperair/baseMexico.xml index 01b6a6b107..6a73a1b55b 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseMexico.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseMexico.xml @@ -82,7 +82,7 @@ - + diff --git a/cave/build/static/common/cave/etc/menus/upperair/basePacificWest.xml b/cave/build/static/common/cave/etc/menus/upperair/basePacificWest.xml index 6e030771ab..31857a57ca 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/basePacificWest.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/basePacificWest.xml @@ -27,7 +27,7 @@ - + @@ -75,7 +75,7 @@ @@ -90,7 +90,7 @@ @@ -100,7 +100,7 @@ @@ -115,9 +115,9 @@ - + @@ -110,7 +110,7 @@ diff --git a/cave/build/static/common/cave/etc/menus/upperair/baseUSWestern.xml b/cave/build/static/common/cave/etc/menus/upperair/baseUSWestern.xml index 6c2a17173d..0b8403fd01 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/baseUSWestern.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/baseUSWestern.xml @@ -40,7 +40,7 @@ diff --git a/cave/build/static/common/cave/etc/menus/upperair/index.xml b/cave/build/static/common/cave/etc/menus/upperair/index.xml index 75ccaa69bf..2fa24f57ed 100644 --- a/cave/build/static/common/cave/etc/menus/upperair/index.xml +++ b/cave/build/static/common/cave/etc/menus/upperair/index.xml @@ -21,7 +21,7 @@ - + primaryModel=gefs availableModels=gefs:01,02;gfs;nam12 -pluginName=ncgrib +pluginName=grid Forecast,Global,Ensemble EnsembleFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/GFS_ENS.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/GFS_ENS.xml index 8d1dc479e3..9babedc824 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/GFS_ENS.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/GFS_ENS.xml @@ -7,7 +7,7 @@ primaryModel=gfs availableModels=gfs -pluginName=ncgrib +pluginName=grid Forecast,Global,Ensemble EnsembleFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/NAM_00.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/NAM_00.xml index 5184859ff8..875d5a1a0c 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/NAM_00.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/ENSEMBLE/NAM_00.xml @@ -7,7 +7,7 @@ primaryModel=nam availableModels=nam;gefs:01,02,03,04,05,07,09;gfs;ruc80 -pluginName=ncgrib +pluginName=grid Forecast,Ensemble EnsembleFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/CMC/CMC.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/CMC/CMC.xml index a2289715d6..901ab27561 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/CMC/CMC.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/CMC/CMC.xml @@ -6,8 +6,8 @@ GRID GDFILE=cmc -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Global ModelFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFG/ECMWFG.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFG/ECMWFG.xml index 8c4fdb2b1c..f715a443d5 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFG/ECMWFG.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFG/ECMWFG.xml @@ -6,8 +6,8 @@ GRID GDFILE=ecmwfg -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Global ModelFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFT/ECMWFT.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFT/ECMWFT.xml index 85d49aa33e..705a88b9d3 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFT/ECMWFT.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/ECMWFT/ECMWFT.xml @@ -6,8 +6,8 @@ GRID GDFILE=ecmwft -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Global ModelFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/FNMOCWAVE/FNMOCWAVE.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/FNMOCWAVE/FNMOCWAVE.xml index 677259dd5a..61cb7871df 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/FNMOCWAVE/FNMOCWAVE.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/FNMOCWAVE/FNMOCWAVE.xml @@ -6,8 +6,8 @@ GRID GDFILE=fnmocwave -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Global ModelFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NOGAPS/NOGAPS.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NOGAPS/NOGAPS.xml index 6de101713d..262c020ac8 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NOGAPS/NOGAPS.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NOGAPS/NOGAPS.xml @@ -6,8 +6,8 @@ GRID GDFILE=nogaps -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Global ModelFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NWW3/NWW3.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NWW3/NWW3.xml index ff3062a052..e9822aa96a 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NWW3/NWW3.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/NWW3/NWW3.xml @@ -6,8 +6,8 @@ GRID GDFILE=nww3 -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Global ModelFcstGridContours diff --git a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/RAP/RAP.xml b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/RAP/RAP.xml index ef7242a1ac..880992793a 100644 --- a/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/RAP/RAP.xml +++ b/cave/build/static/common/cave/etc/ncep/ResourceDefns/GRID/RAP/RAP.xml @@ -5,8 +5,8 @@ GRID GDFILE=rap -pluginName=ncgrib -eventName=% +pluginName=grid +info.secondaryId=% Forecast,Regional ModelFcstGridContours diff --git a/cave/com.raytheon.uf.viz.acarssounding/src/com/raytheon/uf/viz/acarssounding/ACARSSoundingDataCubeAdapter.java b/cave/com.raytheon.uf.viz.acarssounding/src/com/raytheon/uf/viz/acarssounding/ACARSSoundingDataCubeAdapter.java index b1ce8f2863..cb1aee5b46 100644 --- a/cave/com.raytheon.uf.viz.acarssounding/src/com/raytheon/uf/viz/acarssounding/ACARSSoundingDataCubeAdapter.java +++ b/cave/com.raytheon.uf.viz.acarssounding/src/com/raytheon/uf/viz/acarssounding/ACARSSoundingDataCubeAdapter.java @@ -49,6 +49,25 @@ import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator; import com.raytheon.viz.pointdata.util.AbstractPointDataInventory; import com.raytheon.viz.pointdata.util.PointDataCubeAdapter; +/** + * + * Acarssounding data does not use the point data api, to get derived parameters + * to work with acarssounding data this class will intercept point data + * requests, and request all sounding layers from the db and reconstruct the + * data to fit in a PointDataContainer. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 26, 2012            bsteffen     Initial javadoc
+ * 
+ * 
+ * + * @version 1.0 + */ public class ACARSSoundingDataCubeAdapter extends PointDataCubeAdapter { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(ACARSSoundingDataCubeAdapter.class); @@ -120,8 +139,7 @@ public class ACARSSoundingDataCubeAdapter extends PointDataCubeAdapter { } @Override - protected PointDataContainer getBaseRecords( - Collection baseParameters, + public PointDataContainer getBaseRecords(Collection baseParameters, Map queryParams) throws VizException { List baseParams = new ArrayList(baseParameters); String script = ScriptCreator.createScript(queryParams, 1000, "select"); diff --git a/cave/com.raytheon.uf.viz.alertviz/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.alertviz/META-INF/MANIFEST.MF index a01b3154bd..2ddef764b0 100644 --- a/cave/com.raytheon.uf.viz.alertviz/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.alertviz/META-INF/MANIFEST.MF @@ -13,7 +13,6 @@ Require-Bundle: org.eclipse.ui, com.raytheon.uf.viz.core;visibility:=reexport, com.raytheon.uf.common.status, org.jep;bundle-version="1.0.0", - com.raytheon.uf.common.status, com.raytheon.uf.common.message;bundle-version="1.11.11", com.raytheon.uf.common.alertviz, javax.jms;bundle-version="1.0.0", diff --git a/cave/com.raytheon.uf.viz.cloudheight/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.cloudheight/META-INF/MANIFEST.MF index 423d05397c..cf9b62e717 100644 --- a/cave/com.raytheon.uf.viz.cloudheight/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.cloudheight/META-INF/MANIFEST.MF @@ -10,16 +10,6 @@ Eclipse-BuddyPolicy: ext, global Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, com.raytheon.uf.common.pointdata, - com.raytheon.uf.common.serialization;bundle-version="1.11.17", - com.raytheon.uf.common.localization;bundle-version="1.11.17", - com.raytheon.uf.common.status;bundle-version="1.11.17", - com.raytheon.uf.viz.core;bundle-version="1.11.17", - com.raytheon.uf.viz.sounding;bundle-version="1.11.17", - com.raytheon.uf.common.time;bundle-version="1.11.17", - com.raytheon.uf.common.geospatial;bundle-version="1.11.17", - org.geotools;bundle-version="2.5.8", - com.raytheon.edex.meteolib;bundle-version="1.11.17", - com.raytheon.uf.common.dataplugin;bundle-version="1.11.17", com.raytheon.uf.viz.d2d.core;bundle-version="1.11.17", com.raytheon.viz.ui;bundle-version="1.11.17", com.raytheon.viz.skewt;bundle-version="1.11.17", @@ -28,8 +18,9 @@ Require-Bundle: org.eclipse.ui, com.raytheon.uf.common.sounding;bundle-version="1.0.0", javax.measure;bundle-version="1.0.0", com.raytheon.uf.common.dataplugin.level;bundle-version="1.12.1174", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.12.1174", - com.raytheon.uf.common.dataplugin.satellite;bundle-version="1.0.0" + com.raytheon.uf.common.dataplugin.satellite;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0", + com.raytheon.uf.common.parameter;bundle-version="1.0.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.viz.cloudheight, diff --git a/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/data/CloudHeightData.java b/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/data/CloudHeightData.java index 0f8a522b1f..bed0a996f8 100644 --- a/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/data/CloudHeightData.java +++ b/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/data/CloudHeightData.java @@ -29,12 +29,6 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; -import com.raytheon.uf.common.localization.FileUpdatedMessage; -import com.raytheon.uf.common.localization.ILocalizationFileObserver; -import com.raytheon.uf.common.localization.IPathManager; -import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; -import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; -import com.raytheon.uf.common.localization.LocalizationFile; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -68,8 +62,6 @@ public class CloudHeightData implements ISerializableObject { private static final String DATA_FILE = CLOUDHEIGHT_DATA_DIR + File.separator + "values.xml"; - private static LocalizationFile cloudHeightDir; - private static CloudHeightData theData = null; @XmlAccessorType(XmlAccessType.NONE) @@ -101,26 +93,9 @@ public class CloudHeightData implements ISerializableObject { public static synchronized CloudHeightData getCloudHeightData() { if (theData == null) { - IPathManager pm = PathManagerFactory.getPathManager(); theData = new CloudHeightData(); - cloudHeightDir = pm.getLocalizationFile(pm.getContext( - LocalizationType.CAVE_STATIC, LocalizationLevel.BASE), - CLOUDHEIGHT_DATA_DIR); - - ILocalizationFileObserver observer = new ILocalizationFileObserver() { - @Override - public void fileUpdated(FileUpdatedMessage message) { - if (DATA_FILE.equals(message.getFileName())) { - populateData(theData, PathManagerFactory - .getPathManager().getStaticFile(DATA_FILE)); - } - } - }; - - // load data - observer.fileUpdated(new FileUpdatedMessage(null, DATA_FILE, null)); - - // TODO: cloudHeightDir.addFileUpdatedObserver(observer); + populateData(theData, PathManagerFactory.getPathManager() + .getStaticFile(DATA_FILE)); } return theData; } diff --git a/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/impl/ModelCloudHeightSourceImplementation.java b/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/impl/ModelCloudHeightSourceImplementation.java index e4b9a3bac2..d19c06292b 100644 --- a/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/impl/ModelCloudHeightSourceImplementation.java +++ b/cave/com.raytheon.uf.viz.cloudheight/src/com/raytheon/uf/viz/cloudheight/impl/ModelCloudHeightSourceImplementation.java @@ -31,9 +31,10 @@ import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType; @@ -57,7 +58,7 @@ import com.raytheon.viz.core.map.GeoUtil; import com.vividsolutions.jts.geom.Coordinate; /** - * Grib model cloud height sounding implementation + * Grid model cloud height sounding implementation * *
  * 
@@ -76,6 +77,12 @@ import com.vividsolutions.jts.geom.Coordinate;
 public class ModelCloudHeightSourceImplementation extends
         AbstractCloudHeightSourceImpl {
 
+    private static final String PARAM_TEMP = "T";
+
+    private static final String PARAM_DEWPOINT = "DpT";
+
+    private static final String PARAM_HEIGHT = "GH";
+
     private Map soundingMap = new HashMap();
 
     private Job hdf5Job = null;
@@ -100,8 +107,7 @@ public class ModelCloudHeightSourceImplementation extends
         for (PluginDataObject pdo : objects) {
             float[] data = (float[]) pdo.getMessageData();
             if (data != null) {
-                Double level = ((GribRecord) pdo).getModelInfo()
-                        .getLevelOneValue();
+                Double level = ((GridRecord) pdo).getLevel().getLevelonevalue();
                 SoundingLayer layer = layerMap.get(level);
                 if (layer == null) {
                     layer = new SoundingLayer();
@@ -110,14 +116,14 @@ public class ModelCloudHeightSourceImplementation extends
                 }
 
                 float val = data[index];
-                String param = ((GribRecord) pdo).getModelInfo()
-                        .getParameterAbbreviation();
+                String param = ((GridRecord) pdo).getParameter()
+                        .getAbbreviation();
 
-                if ("T".equals(param)) {
+                if (PARAM_TEMP.equals(param)) {
                     layer.setTemperature(val);
-                } else if ("GH".equals(param)) {
+                } else if (PARAM_HEIGHT.equals(param)) {
                     layer.setGeoHeight(val);
-                } else if ("DpT".equals(param)) {
+                } else if (PARAM_DEWPOINT.equals(param)) {
                     layer.setDewpoint(val);
                 }
             }
@@ -142,20 +148,21 @@ public class ModelCloudHeightSourceImplementation extends
     @Override
     protected HashMap constructMetadataMap() {
         HashMap requestMap = new HashMap();
-        requestMap.put("pluginName", new RequestConstraint("grib"));
-        requestMap.put("modelInfo.modelName",
+        requestMap.put(GridConstants.PLUGIN_NAME, new RequestConstraint(
+                GridConstants.GRID));
+        requestMap.put(GridConstants.DATASET_ID,
                 new RequestConstraint(source.getName()));
 
         RequestConstraint params = new RequestConstraint();
         params.setConstraintType(ConstraintType.IN);
-        params.addToConstraintValueList("T");
-        params.addToConstraintValueList("GH");
-        params.addToConstraintValueList("DpT");
-        requestMap.put("modelInfo.parameterAbbreviation", params);
-        requestMap.put("modelInfo.level.masterLevel.name",
-                new RequestConstraint("MB"));
-        requestMap.put("modelInfo.level.leveltwovalue", new RequestConstraint(
-                Level.getInvalidLevelValueAsString()));
+        params.addToConstraintValueList(PARAM_TEMP);
+        params.addToConstraintValueList(PARAM_HEIGHT);
+        params.addToConstraintValueList(PARAM_DEWPOINT);
+        requestMap.put(GridConstants.PARAMETER_ABBREVIATION, params);
+        requestMap.put(GridConstants.MASTER_LEVEL_NAME, new RequestConstraint(
+                "MB"));
+        requestMap.put(GridConstants.LEVEL_TWO,
+                new RequestConstraint(Level.getInvalidLevelValueAsString()));
         return requestMap;
     }
 
@@ -170,7 +177,7 @@ public class ModelCloudHeightSourceImplementation extends
     protected synchronized VerticalSounding createSoundingInternal(
             Coordinate latLon, final DataTime time,
             final PluginDataObject[] pdos) {
-        GribRecord pdo = (GribRecord) pdos[0];
+        GridRecord pdo = (GridRecord) pdos[0];
 
         final ISpatialObject spatial = pdo.getSpatialObject();
 
@@ -256,7 +263,7 @@ public class ModelCloudHeightSourceImplementation extends
      */
     @Override
     protected long getValidTimeInterval() {
-        GridModel gm = GribModelLookup.getInstance().getModelByName(
+        DatasetInfo gm = DatasetInfoLookup.getInstance().getInfo(
                 source.getName());
         // TODO: Why is Laps null?
         int dt = gm != null ? gm.getDt() : 1;
diff --git a/cave/com.raytheon.uf.viz.collaboration.product/src/com/raytheon/uf/viz/collaboration/product/CollaborationLocalizationAdapter.java b/cave/com.raytheon.uf.viz.collaboration.product/src/com/raytheon/uf/viz/collaboration/product/CollaborationLocalizationAdapter.java
index c75a221d11..3072bb245d 100644
--- a/cave/com.raytheon.uf.viz.collaboration.product/src/com/raytheon/uf/viz/collaboration/product/CollaborationLocalizationAdapter.java
+++ b/cave/com.raytheon.uf.viz.collaboration.product/src/com/raytheon/uf/viz/collaboration/product/CollaborationLocalizationAdapter.java
@@ -26,6 +26,7 @@ import com.raytheon.uf.common.localization.LocalizationContext;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
 import com.raytheon.uf.common.localization.LocalizationFile;
+import com.raytheon.uf.common.localization.LocalizationFile.ModifiableLocalizationFile;
 import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException;
 
 /**
@@ -47,20 +48,6 @@ import com.raytheon.uf.common.localization.exception.LocalizationOpFailedExcepti
 
 public class CollaborationLocalizationAdapter implements ILocalizationAdapter {
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @see
-     * com.raytheon.uf.common.localization.ILocalizationAdapter#getDirNameForType
-     * (
-     * com.raytheon.uf.common.localization.LocalizationContext.LocalizationType)
-     */
-    @Override
-    public String getDirNameForType(LocalizationType type) {
-        // TODO Auto-generated method stub
-        return null;
-    }
-
     /*
      * (non-Javadoc)
      * 
@@ -108,13 +95,12 @@ public class CollaborationLocalizationAdapter implements ILocalizationAdapter {
      * (non-Javadoc)
      * 
      * @see
-     * com.raytheon.uf.common.localization.ILocalizationAdapter#save(java.io
-     * .File, com.raytheon.uf.common.localization.LocalizationContext,
-     * java.lang.String)
+     * com.raytheon.uf.common.localization.ILocalizationAdapter#save(com.raytheon
+     * .uf.common.localization.LocalizationFile. ModifiableLocalizationFile)
      */
     @Override
-    public boolean save(File localFile, LocalizationContext context,
-            String fileName) throws LocalizationOpFailedException {
+    public boolean save(ModifiableLocalizationFile file)
+            throws LocalizationOpFailedException {
         // TODO Auto-generated method stub
         return false;
     }
@@ -182,13 +168,12 @@ public class CollaborationLocalizationAdapter implements ILocalizationAdapter {
      * (non-Javadoc)
      * 
      * @see
-     * com.raytheon.uf.common.localization.ILocalizationAdapter#delete(java.
-     * io.File, com.raytheon.uf.common.localization.LocalizationContext,
-     * java.lang.String)
+     * com.raytheon.uf.common.localization.ILocalizationAdapter#delete(com.raytheon
+     * .uf.common.localization.LocalizationFile. ModifiableLocalizationFile)
      */
     @Override
-    public boolean delete(File file, LocalizationContext context,
-            String fileName) throws LocalizationOpFailedException {
+    public boolean delete(ModifiableLocalizationFile file)
+            throws LocalizationOpFailedException {
         // TODO Auto-generated method stub
         return false;
     }
diff --git a/cave/com.raytheon.uf.viz.collaboration.ui/src/com/raytheon/uf/viz/collaboration/ui/session/AbstractSessionView.java b/cave/com.raytheon.uf.viz.collaboration.ui/src/com/raytheon/uf/viz/collaboration/ui/session/AbstractSessionView.java
index 8cce57947c..c63c6f557e 100644
--- a/cave/com.raytheon.uf.viz.collaboration.ui/src/com/raytheon/uf/viz/collaboration/ui/session/AbstractSessionView.java
+++ b/cave/com.raytheon.uf.viz.collaboration.ui/src/com/raytheon/uf/viz/collaboration/ui/session/AbstractSessionView.java
@@ -24,11 +24,13 @@ import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
+import java.text.SimpleDateFormat;
 import java.util.ArrayList;
-import java.util.Calendar;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.TimeZone;
 
 import org.eclipse.jface.action.Action;
 import org.eclipse.jface.action.IToolBarManager;
@@ -103,6 +105,8 @@ public abstract class AbstractSessionView extends CaveFloatingView {
 
     private static final String SESSION_IMAGE_KEY = "sessionId.key";
 
+    private SimpleDateFormat dateFormatter = new SimpleDateFormat("HH:mm:ss");
+
     /**
      * Mapping of images used in the view so they are not constantly created and
      * allowing them to be disposed.
@@ -146,6 +150,7 @@ public abstract class AbstractSessionView extends CaveFloatingView {
         userIds = CollaborationUtils.getIds();
         fonts = new HashMap();
         colors = new HashMap();
+        dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC"));
     }
 
     protected void initComponents(Composite parent) {
@@ -330,9 +335,8 @@ public abstract class AbstractSessionView extends CaveFloatingView {
                         .getAdapter(IWorkbenchSiteProgressService.class);
                 service.warnOfContentChange();
 
-                Calendar cal = Calendar.getInstance();
-                cal.setTimeInMillis(timestamp);
-                String time = String.format("%1$tI:%1$tM:%1$tS %1$Tp", cal);
+                Date date = new Date(timestamp);
+                String time = dateFormatter.format(date);
 
                 String name = connection.getContactsManager().getDisplayName(
                         userId);
@@ -596,9 +600,8 @@ public abstract class AbstractSessionView extends CaveFloatingView {
         VizApp.runAsync(new Runnable() {
             @Override
             public void run() {
-                Calendar cal = Calendar.getInstance();
-                cal.setTimeInMillis(System.currentTimeMillis());
-                String time = String.format("%1$tI:%1$tM:%1$tS %1$Tp", cal);
+                Date date = new Date();
+                String time = dateFormatter.format(date);
                 string.insert(0, "(" + time + ") : ");
                 if (messagesText.getCharCount() != 0) {
                     string.insert(0, "\n");
diff --git a/cave/com.raytheon.uf.viz.common.core.feature/feature.xml b/cave/com.raytheon.uf.viz.common.core.feature/feature.xml
index 7791a0ca03..929a26b48c 100644
--- a/cave/com.raytheon.uf.viz.common.core.feature/feature.xml
+++ b/cave/com.raytheon.uf.viz.common.core.feature/feature.xml
@@ -63,13 +63,6 @@
          version="0.0.0"
          unpack="false"/>
 
-   
-
    
+         version="0.0.0"/>
+         
+   
 
    
+         version="0.0.0"/>
 
    
+         
+   
 
    
 
+   
+
+   
+
 
diff --git a/cave/com.raytheon.uf.viz.core.feature/feature.xml b/cave/com.raytheon.uf.viz.core.feature/feature.xml
index 8bd3c7cee6..888cdfab55 100644
--- a/cave/com.raytheon.uf.viz.core.feature/feature.xml
+++ b/cave/com.raytheon.uf.viz.core.feature/feature.xml
@@ -92,6 +92,32 @@
          install-size="0"
          version="0.0.0"/>
 
+   
+
+   
+
+   
+
+   
+
    
 
-   
-
    
 
+   
+
 
diff --git a/cave/com.raytheon.uf.viz.core/META-INF/services/com.raytheon.uf.common.serialization.comm.IRequestRouter b/cave/com.raytheon.uf.viz.core/META-INF/services/com.raytheon.uf.common.serialization.comm.IRequestRouter
deleted file mode 100644
index fac02f9c2a..0000000000
--- a/cave/com.raytheon.uf.viz.core/META-INF/services/com.raytheon.uf.common.serialization.comm.IRequestRouter
+++ /dev/null
@@ -1 +0,0 @@
-com.raytheon.uf.viz.core.requests.ServerRequestRouter
\ No newline at end of file
diff --git a/cave/com.raytheon.uf.viz.core/build.properties b/cave/com.raytheon.uf.viz.core/build.properties
index b2c38e2262..e1ef112c75 100644
--- a/cave/com.raytheon.uf.viz.core/build.properties
+++ b/cave/com.raytheon.uf.viz.core/build.properties
@@ -6,4 +6,5 @@ bin.includes = META-INF/,\
                config.xml,\
                scriptTemplates/,\
                schema/,\
-               log4j-viz-core.xml
+               log4j-viz-core.xml,\
+               res/
diff --git a/cave/com.raytheon.uf.viz.core/META-INF/spring/viz.xml b/cave/com.raytheon.uf.viz.core/res/spring/viz.xml
similarity index 74%
rename from cave/com.raytheon.uf.viz.core/META-INF/spring/viz.xml
rename to cave/com.raytheon.uf.viz.core/res/spring/viz.xml
index 1ba7778794..31ec949fb6 100644
--- a/cave/com.raytheon.uf.viz.core/META-INF/spring/viz.xml
+++ b/cave/com.raytheon.uf.viz.core/res/spring/viz.xml
@@ -1,10 +1,10 @@
 
+  
 	
 	   
 	   
@@ -26,7 +26,7 @@
    
-      
+      
       
       
       
@@ -34,4 +34,18 @@
      -->
 
    
+   
+   
+
+    
+        
+    
+
+    
+        
+        
+    
+
 
\ No newline at end of file
diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/IGraphicsTarget.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/IGraphicsTarget.java
index f685a10688..c936d755ce 100644
--- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/IGraphicsTarget.java
+++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/IGraphicsTarget.java
@@ -731,6 +731,8 @@ public interface IGraphicsTarget extends IImagingExtension {
      */
     public IView getView();
 
+    /**
+
     /**
      * Use drawStrings(DrawableString parameters)
      */
diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizApp.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizApp.java
index b5dae705bf..51f946ad63 100644
--- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizApp.java
+++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizApp.java
@@ -48,13 +48,20 @@ import com.raytheon.uf.viz.core.localization.LocalizationManager;
  *    Date          Ticket#     Engineer    Description
  *    ------------	----------	-----------	--------------------------
  *    7/1/06                    chammack    Initial Creation.
+ *    Sep 12, 2012  1167        djohnson    Add datadelivery servers.
  * 
  * 
* * @author chammack * */ -public class VizApp { +public final class VizApp { + + /** + * Disabled constructor. + */ + private VizApp() { + } private static final String USER_FLAG = "-u"; @@ -66,6 +73,12 @@ public class VizApp { private static String pypiesServer; + private static String dataDeliveryServer; + + private static String dataDeliveryLcmServer; + + private static String dataDeliveryQueryServer; + private static String serverDataDir; static { diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizServers.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizServers.java new file mode 100644 index 0000000000..a56ef70b32 --- /dev/null +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/VizServers.java @@ -0,0 +1,80 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.core; + +import java.util.Collections; +import java.util.Map; + +/** + * Provides the ability to retrieve server locations. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 5, 2012  1302      djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class VizServers { + + private static final VizServers INSTANCE = new VizServers(); + + /** + * @return the instance + */ + public static VizServers getInstance() { + return INSTANCE; + } + + private Map serverLocations; + + private VizServers() { + } + + /** + * Retrieves a server location. + * + * @param key + * the key used as the server name + * @return the location of the server + * @throws NullPointerException + * if the server locations have not been initialized yet + */ + public String getServerLocation(final String key) { + if (serverLocations == null) { + throw new NullPointerException("serverLocations must not be null!"); + } + return serverLocations.get(key); + } + + /** + * @param serverLocations2 + */ + public void setServerLocations(Map serverLocations2) { + this.serverLocations = Collections.unmodifiableMap(serverLocations2); + } +} diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/IUserManager.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/IUserManager.java index af71a8e8db..fc0d61f4ec 100644 --- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/IUserManager.java +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/IUserManager.java @@ -19,7 +19,11 @@ **/ package com.raytheon.uf.viz.core.auth; +import java.util.List; + import com.raytheon.uf.common.auth.user.IAuthenticationData; +import com.raytheon.uf.common.auth.user.IPermission; +import com.raytheon.uf.common.auth.user.IRole; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.viz.core.requests.INotAuthHandler; @@ -32,6 +36,7 @@ import com.raytheon.uf.viz.core.requests.INotAuthHandler; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * May 21, 2010 mschenke Initial creation + * Nov 06, 2012 1302 djohnson Add ability to get roles/permissions for an application. * * * @@ -46,7 +51,7 @@ public interface IUserManager { * * @return */ - public IUser getUserObject(); + IUser getUserObject(); /** * Update the user object with the authentication data update @@ -54,7 +59,7 @@ public interface IUserManager { * @param user * @param authData */ - public void updateUserObject(IUser user, IAuthenticationData authData); + void updateUserObject(IUser user, IAuthenticationData authData); /** * Get the handler for UserNotAuthenticated and UserNotAuthorized response @@ -62,5 +67,22 @@ public interface IUserManager { * * @return */ - public INotAuthHandler getNotAuthHandler(); + INotAuthHandler getNotAuthHandler(); + + /** + * Get the list of permissions. + * + * @param application + * the application + * + * @return the permissions + */ + List getPermissions(String application); + + /** + * Get the list of roles. + * + * @return the list of roles + */ + List getRoles(String application); } diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/UserController.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/UserController.java index 5e92aa0102..a6f50a0a6e 100644 --- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/UserController.java +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/auth/UserController.java @@ -19,6 +19,9 @@ **/ package com.raytheon.uf.viz.core.auth; +import java.util.Collections; +import java.util.List; + import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtension; @@ -29,6 +32,8 @@ import org.eclipse.core.runtime.Platform; import com.raytheon.uf.common.auth.resp.UserNotAuthenticated; import com.raytheon.uf.common.auth.resp.UserNotAuthorized; import com.raytheon.uf.common.auth.user.IAuthenticationData; +import com.raytheon.uf.common.auth.user.IPermission; +import com.raytheon.uf.common.auth.user.IRole; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; @@ -45,6 +50,7 @@ import com.raytheon.uf.viz.core.requests.INotAuthHandler; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * May 21, 2010 mschenke Initial creation + * Nov 06, 2012 1302 djohnson Add ability to retrieve the {@link IUserManager}. * * * @@ -53,12 +59,12 @@ import com.raytheon.uf.viz.core.requests.INotAuthHandler; */ public class UserController { - private static transient IUFStatusHandler statusHandler = UFStatus + private static IUFStatusHandler statusHandler = UFStatus .getHandler(UserController.class, "CAVE"); private static final String EXTENSION_POINT = "com.raytheon.uf.viz.core.userManager"; - private static IUserManager manager = null; + private static IUserManager manager; static { IExtensionRegistry registry = Platform.getExtensionRegistry(); @@ -124,10 +130,24 @@ public class UserController { }; } + /** + * {@inheritDoc} + */ + @Override + public List getPermissions(String application) { + return Collections.emptyList(); + } + + @Override + public List getRoles(String application) { + return Collections.emptyList(); + } + }; } } + public static IUser getUserObject() { return manager.getUserObject(); } @@ -140,4 +160,10 @@ public class UserController { return manager.getNotAuthHandler(); } + /** + * @return the manager + */ + public static IUserManager getManager() { + return manager; + } } diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/CAVELocalizationAdapter.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/CAVELocalizationAdapter.java index 0bfb188ed8..d4962390be 100644 --- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/CAVELocalizationAdapter.java +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/CAVELocalizationAdapter.java @@ -20,6 +20,9 @@ package com.raytheon.uf.viz.core.localization; import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; @@ -34,7 +37,9 @@ import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.LocalizationFile.ModifiableLocalizationFile; import com.raytheon.uf.common.localization.LocalizationInternalFile; +import com.raytheon.uf.common.localization.LockingFileInputStream; import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException; import com.raytheon.uf.common.localization.msgs.AbstractUtilityCommand; import com.raytheon.uf.common.localization.msgs.AbstractUtilityResponse; @@ -72,15 +77,12 @@ public class CAVELocalizationAdapter implements ILocalizationAdapter { this.contexts = new HashMap(); } - /* - * (non-Javadoc) + /** + * Returns a directory name for the localization type * - * @see - * com.raytheon.uf.common.localization.ILocalizationAdapter#getDirNameForType - * ( - * com.raytheon.uf.common.localization.LocalizationContext.LocalizationType) + * @param type + * @return */ - @Override public String getDirNameForType(LocalizationType type) { if (type == LocalizationType.COMMON_STATIC) { return "common"; @@ -228,21 +230,39 @@ public class CAVELocalizationAdapter implements ILocalizationAdapter { * (non-Javadoc) * * @see - * com.raytheon.uf.common.localization.ILocalizationAdapter#save(java.io - * .File, com.raytheon.uf.common.localization.LocalizationContext, - * java.lang.String) + * com.raytheon.uf.common.localization.ILocalizationAdapter#save(com.raytheon + * .uf.common.localization.LocalizationFile. ModifiableLocalizationFile) */ @Override - public boolean save(File localFile, LocalizationContext context, - String fileName) throws LocalizationOpFailedException { - if (context.getLocalizationLevel().isSystemLevel()) { - throw new UnsupportedOperationException( - "Saving to the System Level, " - + context.getLocalizationLevel() - + ", is not supported."); + public boolean save(ModifiableLocalizationFile file) + throws LocalizationOpFailedException { + File localFile = file.getLocalFile(); + if (localFile.isDirectory() == false && localFile.exists()) { + InputStream in = null; + try { + in = new LockingFileInputStream(localFile); + long serverModTime = manager.upload(file.getContext(), + file.getFileName(), in, localFile.length()); + // Success! set potentially changed fields + file.setTimeStamp(new Date(serverModTime)); + file.setIsAvailableOnServer(true); + file.setIsDirectory(false); + return true; + } catch (FileNotFoundException e) { + throw new LocalizationOpFailedException( + "Error saving file, does not exist"); + } finally { + // Make sure to close input stream + if (in != null) { + try { + in.close(); + } catch (IOException e) { + // Ignore close exception + } + } + } } - - return manager.upload(context, fileName, localFile); + return false; } /* @@ -443,16 +463,26 @@ public class CAVELocalizationAdapter implements ILocalizationAdapter { * (non-Javadoc) * * @see - * com.raytheon.uf.common.localization.ILocalizationAdapter#delete(java. - * io.File, com.raytheon.uf.common.localization.LocalizationContext, - * java.lang.String) + * com.raytheon.uf.common.localization.ILocalizationAdapter#delete(com.raytheon + * .uf.common.localization.LocalizationFile. ModifiableLocalizationFile) */ @Override - public boolean delete(File file, LocalizationContext context, - String fileName) throws LocalizationOpFailedException { - file.delete(); - return !file.exists() && manager.delete(context, fileName); + public boolean delete(ModifiableLocalizationFile file) + throws LocalizationOpFailedException { + long deleteTime = manager.delete(file.getContext(), file.getFileName()); + // Made it here! file on server succesfully deleted! Delete local file + // reference. If that fails, doesn't matter since file does not exist! + File localFile = file.getLocalFile(); + localFile.delete(); + + // Reset fields + file.setTimeStamp(new Date(deleteTime)); + file.setIsAvailableOnServer(false); + file.setFileChecksum(null); + file.setIsDirectory(false); + + return true; } private ListResponse convertResponse(ListResponseEntry entry, diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationInitializer.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationInitializer.java index f4c6173d71..92c4199739 100644 --- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationInitializer.java +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationInitializer.java @@ -32,6 +32,7 @@ import com.raytheon.uf.common.localization.msgs.GetServersRequest; import com.raytheon.uf.common.localization.msgs.GetServersResponse; import com.raytheon.uf.common.util.FileUtil; import com.raytheon.uf.viz.core.VizApp; +import com.raytheon.uf.viz.core.VizServers; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.requests.ThriftClient; @@ -47,6 +48,7 @@ import com.raytheon.uf.viz.core.requests.ThriftClient; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Nov 5, 2009 mschenke Initial creation + * Sep 12, 2012 1167 djohnson Add datadelivery servers. * * * @@ -115,6 +117,6 @@ public class LocalizationInitializer { VizApp.setJmsServer(resp.getJmsServer()); VizApp.setPypiesServer(resp.getPypiesServer()); VizApp.setServerDataDir(resp.getServerDataDir()); - + VizServers.getInstance().setServerLocations(resp.getServerLocations()); } } diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationManager.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationManager.java index b1b59f8ed8..a4520a3e5e 100644 --- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationManager.java +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/localization/LocalizationManager.java @@ -22,10 +22,9 @@ package com.raytheon.uf.viz.core.localization; import java.io.File; import java.io.FileFilter; -import java.io.FileInputStream; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; @@ -51,8 +50,8 @@ import com.raytheon.uf.common.localization.ILocalizationAdapter; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationFile; -import com.raytheon.uf.common.localization.LockingFileInputStream; import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException; +import com.raytheon.uf.common.localization.msgs.AbstractPrivilegedUtilityCommand; import com.raytheon.uf.common.localization.msgs.AbstractUtilityResponse; import com.raytheon.uf.common.localization.msgs.DeleteUtilityCommand; import com.raytheon.uf.common.localization.msgs.DeleteUtilityResponse; @@ -73,9 +72,9 @@ import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.viz.application.ProgramArguments; import com.raytheon.uf.viz.core.VizApp; +import com.raytheon.uf.viz.core.VizServers; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.requests.PrivilegedRequestFactory; -import com.raytheon.uf.viz.core.requests.ServerRequestException; import com.raytheon.uf.viz.core.requests.ThriftClient; /** @@ -90,7 +89,8 @@ import com.raytheon.uf.viz.core.requests.ThriftClient; * Jul 30, 2007 njensen Refactored. * Feb 12, 2008 chammack Removed base configuration * Mar 26, 2008 njensen Added rename() and getFileContents(). - * May 19, 2007 #1127 randerso Implemented error handling + * May 19, 2007 #1127 randerso Implemented error handling + * Sep 12, 2012 1167 djohnson Add datadelivery servers. * * * @@ -130,6 +130,8 @@ public class LocalizationManager implements IPropertyChangeListener { /** The current localization site */ private String currentSite; + private boolean nationalCenter; + private boolean overrideSite; /** Was the alert server launched within cave? */ @@ -224,6 +226,8 @@ public class LocalizationManager implements IPropertyChangeListener { VizApp.setJmsServer(resp.getJmsServer()); VizApp.setPypiesServer(resp.getPypiesServer()); VizApp.setServerDataDir(resp.getServerDataDir()); + VizServers.getInstance().setServerLocations( + resp.getServerLocations()); } catch (VizException e) { statusHandler.handle(UFStatus.Priority.SIGNIFICANT, "Error connecting to localization server", e); @@ -392,6 +396,12 @@ public class LocalizationManager implements IPropertyChangeListener { .getString("-site").toUpperCase(); this.overrideSite = true; } + + this.nationalCenter = false; + + if (ProgramArguments.getInstance().getString("-nc") != null) { + this.nationalCenter = true; + } } private void checkForServerOverride() { @@ -525,6 +535,13 @@ public class LocalizationManager implements IPropertyChangeListener { } + /** + * Retrieves the LocalizationFile contents from the localization server. + * Locks on the file + * + * @param file + * @throws LocalizationOpFailedException + */ protected void retrieve(LocalizationFile file) throws LocalizationOpFailedException { try { @@ -697,150 +714,145 @@ public class LocalizationManager implements IPropertyChangeListener { } /** - * Uploads a file to EDEX through the UtilitySrv + * Uploads a stream as a file to EDEX through the UtilitySrv. It is the + * responsibility of the caller to close the stream * * @param context - * the context to upload to * @param filename - * the name of the file - * @param bytes - * the contents of the file - * @return - * @throws LocalizationCommunicationException + * @param in + * @param streamLength + * @return the new server time stamp * @throws LocalizationOpFailedException */ - protected boolean upload(LocalizationContext context, String filename, - FileInputStream fin, long totalSize) + protected long upload(LocalizationContext context, String filename, + InputStream in, long streamLength) throws LocalizationOpFailedException { - boolean success = true; + if (context.getLocalizationLevel().isSystemLevel()) { + throw new UnsupportedOperationException( + "Saving to the System Level, " + + context.getLocalizationLevel() + + ", is not supported."); + } + + LocalizationStreamPutRequest request; try { - LocalizationStreamPutRequest request = PrivilegedRequestFactory + request = PrivilegedRequestFactory .constructPrivilegedRequest(LocalizationStreamPutRequest.class); - request.setMyContextName(getContextName(context + request.setMyContextName(LocalizationManager.getContextName(context .getLocalizationLevel())); request.setContext(context); request.setFileName(filename); - request.setOffset(0); - boolean finished = false; - byte[] bytes = new byte[512 * 1024]; - int totalRead = 0; - while (!finished) { - request.setOffset(totalRead); - int read = fin.read(bytes, 0, bytes.length); + } catch (VizException e) { + throw new LocalizationOpFailedException( + "Could not construct privileged utility request", e); + } + + long serverModTime = -1; + // Create byte[] buffer + byte[] bytes = new byte[512 * 1024]; + // initial offset = 0 + int offset = 0; + do { + // set current offset + request.setOffset(offset); + try { + // read in data from input stream + int read = in.read(bytes, 0, bytes.length); if (read > 0) { - totalRead += read; - bytes = Arrays.copyOf(bytes, read); - request.setBytes(bytes); - request.setEnd(totalRead == totalSize); + // byte read, trim if necessary + offset += read; + if (read < bytes.length) { + bytes = Arrays.copyOf(bytes, read); + } } else { - request.setBytes(new byte[0]); - request.setEnd(true); + bytes = new byte[0]; + // Should be case but paranoia takes over + offset = (int) streamLength; } - - if (request.isEnd()) { - finished = true; - } - - success = (ThriftClient.sendLocalizationRequest(request) != null); - } - } catch (ServerRequestException e) { - statusHandler.handle(Priority.PROBLEM, e.getMessage(), e); - success = false; - } catch (Exception e) { - e.printStackTrace(); - statusHandler.handle(Priority.PROBLEM, - "Error uploading file to server", e); - success = false; - } finally { - try { - fin.close(); + request.setBytes(bytes); + request.setEnd(offset == streamLength); } catch (IOException e) { - // ignore message - } - } - - return success; - } - - /** - * Uploads a file to the edex through the UtilitySrv - * - * @param context - * the context to upload to - * @param filename - * the name of the file - * @param localFile - * the local file, used to send the contents of the file to the - * service - * @return - * @throws LocalizationOpFailedException - * @throws LocalizationCommunicationException - */ - protected boolean upload(LocalizationContext context, String path, - File localFile) throws LocalizationOpFailedException { - if (localFile.isDirectory()) { - // TODO: Someday upload entire directory structure onto - // server? - } else if (localFile.exists()) { - // Upload single file - try { - return upload(context, path, new LockingFileInputStream( - localFile), localFile.length()); - } catch (FileNotFoundException e) { throw new LocalizationOpFailedException( - "Error opening input stream on localization file", e); + "Could not save file, failed to read in contents", e); } - } - return true; + + try { + Number modTime = (Number) ThriftClient + .sendLocalizationRequest(request); + if (modTime != null) { + serverModTime = modTime.longValue(); + } + } catch (VizException e) { + throw new LocalizationOpFailedException( + "Error storing file contents to server: " + + e.getLocalizedMessage(), e); + } + + } while (request.isEnd() == false); + return serverModTime; } /** - * Deletes a localization file + * Deletes a localization file from localization server * * @param context * the context to the file * @param filename * the name of the file - * @return + * @return modified time on server * @throws LocalizationOpFailedException - * @throws LocalizationCommunicationException */ - protected boolean delete(LocalizationContext context, String filename) + protected long delete(LocalizationContext context, String filename) throws LocalizationOpFailedException { - // Build list commands - DeleteUtilityCommand[] commands = new DeleteUtilityCommand[1]; - - commands[0] = new DeleteUtilityCommand(context, filename); - commands[0].setMyContextName(getContextName(context - .getLocalizationLevel())); - - PrivilegedUtilityRequestMessage deleteRequest = null; + PrivilegedUtilityRequestMessage request; try { - deleteRequest = PrivilegedRequestFactory + request = PrivilegedRequestFactory .constructPrivilegedRequest(PrivilegedUtilityRequestMessage.class); - deleteRequest.setCommands(commands); } catch (VizException e) { throw new LocalizationOpFailedException( - "Error constructing privileged utility request", e); + "Could not construct privileged utility request", e); } - AbstractUtilityResponse[] responseList = makeRequest(deleteRequest); - if (responseList == null) { - return false; - } - for (AbstractUtilityResponse response : responseList) { - if (!(response instanceof DeleteUtilityResponse)) { + DeleteUtilityCommand command = new DeleteUtilityCommand(context, + filename); + command.setMyContextName(getContextName(context.getLocalizationLevel())); + AbstractPrivilegedUtilityCommand[] commands = new AbstractPrivilegedUtilityCommand[] { command }; + request.setCommands(commands); + try { + UtilityResponseMessage response = (UtilityResponseMessage) ThriftClient + .sendLocalizationRequest(request); + if (response == null) { throw new LocalizationOpFailedException( - "Unexpected type returned" - + response.getClass().getName()); + "No response received for delete command"); } - - // DeleteUtilityResponse deleteResponse = (DeleteUtilityResponse) - // response; - // TODO log this + AbstractUtilityResponse[] responses = response.getResponses(); + if (responses == null || responses.length != commands.length) { + throw new LocalizationOpFailedException( + "Unexpected return type from delete: Expected " + + commands.length + " responses, received " + + (responses != null ? responses.length : null)); + } + AbstractUtilityResponse rsp = responses[0]; + if (rsp instanceof DeleteUtilityResponse) { + DeleteUtilityResponse dur = (DeleteUtilityResponse) rsp; + if (dur.getErrorText() != null) { + throw new LocalizationOpFailedException( + "Error processing delete command: " + + dur.getErrorText()); + } + // Yay, successful execution! + return dur.getTimeStamp(); + } else { + throw new LocalizationOpFailedException( + "Unexpected return type from delete: Expected " + + DeleteUtilityResponse.class + " received " + + (rsp != null ? rsp.getClass() : null)); + } + } catch (VizException e) { + throw new LocalizationOpFailedException( + "Error processing delete command: " + + e.getLocalizedMessage(), e); } - - return true; } /** @@ -946,4 +958,8 @@ public class LocalizationManager implements IPropertyChangeListener { public boolean isOverrideSite() { return overrideSite; } + + public boolean isNationalCenter() { + return nationalCenter; + } } diff --git a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/requests/ThriftClient.java b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/requests/ThriftClient.java index 22bcb88135..a8f5cf0a1e 100644 --- a/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/requests/ThriftClient.java +++ b/cave/com.raytheon.uf.viz.core/src/com/raytheon/uf/viz/core/requests/ThriftClient.java @@ -17,6 +17,7 @@ import com.raytheon.uf.common.auth.resp.UserNotAuthorized; import com.raytheon.uf.common.comm.CommunicationException; import com.raytheon.uf.common.comm.HttpClient; import com.raytheon.uf.common.comm.NetworkStatistics; +import com.raytheon.uf.common.serialization.ExceptionWrapper; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; import com.raytheon.uf.common.serialization.comm.IServerRequest; @@ -24,7 +25,6 @@ import com.raytheon.uf.common.serialization.comm.RemoteServiceRequest; import com.raytheon.uf.common.serialization.comm.RequestWrapper; import com.raytheon.uf.common.serialization.comm.ServiceException; import com.raytheon.uf.common.serialization.comm.response.ServerErrorResponse; -import com.raytheon.uf.common.serialization.comm.util.ExceptionWrapper; import com.raytheon.uf.viz.core.VizApp; import com.raytheon.uf.viz.core.auth.UserController; import com.raytheon.uf.viz.core.exception.VizCommunicationException; @@ -61,8 +61,9 @@ import com.raytheon.uf.viz.core.localization.LocalizationManager; * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Aug 3, 2009 mschenke Initial creation - * Jul 24, 2012 njensen Enhanced logging + * Aug 3, 2009 mschenke Initial creation + * Jul 24, 2012 njensen Enhanced logging + * Nov 15, 2012 1322 djohnson Publicize ability to specify specific httpAddress. * * * @@ -268,7 +269,7 @@ public class ThriftClient { return rval; } - private static Object sendRequest(IServerRequest request, String httpAddress) + public static Object sendRequest(IServerRequest request, String httpAddress) throws VizException { return sendRequest(request, httpAddress, "/thrift"); } diff --git a/cave/com.raytheon.uf.viz.cots.feature/feature.xml b/cave/com.raytheon.uf.viz.cots.feature/feature.xml index 25456a2cc0..10e5cf6d94 100644 --- a/cave/com.raytheon.uf.viz.cots.feature/feature.xml +++ b/cave/com.raytheon.uf.viz.cots.feature/feature.xml @@ -23,6 +23,13 @@ install-size="0" version="0.0.0"/> + + - - + + diff --git a/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/browser/GFEDataDefinition.java b/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/browser/GFEDataDefinition.java index c5b071e70a..c3f6bbac7d 100644 --- a/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/browser/GFEDataDefinition.java +++ b/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/browser/GFEDataDefinition.java @@ -30,8 +30,6 @@ import java.util.Set; import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType; -import com.raytheon.uf.viz.core.catalog.CatalogQuery; -import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.DisplayType; import com.raytheon.uf.viz.core.rsc.ResourceType; import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability; @@ -44,7 +42,7 @@ import com.raytheon.viz.grid.rsc.GridLoadProperties; /** * - * TODO Add Description + * Request GFE data from the product browser * *
  * 
@@ -77,8 +75,7 @@ public class GFEDataDefinition extends
     public GFEDataDefinition() {
         productName = "gfe";
         displayName = "GFE";
-        order = new String[] { GFEUtil.PLUGIN_NAME, SITE_ID, MODEL_NAME,
-                PARM_NAME, PARM_LEVEL };
+        order = new String[] { SITE_ID, MODEL_NAME, PARM_NAME, PARM_LEVEL };
         order = getOrder();
         loadProperties = new GridLoadProperties();
         loadProperties.setResourceType(getResourceType());
@@ -114,13 +111,10 @@ public class GFEDataDefinition extends
      */
     @Override
     public List buildProductList(List historyList) {
-        String[] parameters = getParmIds(getProductParameters(new String[0],
-                null));
+        String[] parameters = queryData(GFEUtil.PARM_ID,
+                getProductParameters(new String[0], null));
         List result = new ArrayList();
         for (String orderString : order) {
-            if (orderString == order[0]) {
-                continue;
-            }
             List labels = formatData(orderString,
                     parameters);
             for (ProductBrowserLabel label : labels) {
@@ -137,8 +131,8 @@ public class GFEDataDefinition extends
         if (!isEnabled()) {
             return null;
         }
-        String[] parameters = getParmIds(getProductParameters(new String[0],
-                null));
+        String[] parameters = queryData(GFEUtil.PARM_ID,
+                getProductParameters(new String[0], null));
 
         if (parameters != null) {
             if (parameters.length > 0) {
@@ -153,24 +147,9 @@ public class GFEDataDefinition extends
     }
 
     @Override
-    public List populateData(String[] selection) {
-        List parameters = null;
-        boolean product = false;
-        String param = order[selection.length];
-
-        if (selection.length == order.length - 1) {
-            product = true;
-        }
-
-        String[] temp = getParmIds(getProductParameters(selection, null));
-        parameters = formatData(param, temp);
-        if (parameters != null) {
-            for (ProductBrowserLabel label : parameters) {
-                label.setProduct(product);
-                label.setDefinition(this);
-            }
-        }
-        return parameters;
+    protected String[] queryData(String param,
+            HashMap queryList) {
+        return super.queryData(GFEUtil.PARM_ID, queryList);
     }
 
     @Override
@@ -205,15 +184,6 @@ public class GFEDataDefinition extends
         return finalLabels;
     }
 
-    private String[] getParmIds(Map queryList) {
-        String param = GFEUtil.PARM_ID;
-        try {
-            return CatalogQuery.performQuery(param, queryList);
-        } catch (VizException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
     @Override
     public HashMap getProductParameters(
             String[] selection, String[] order) {
@@ -228,20 +198,23 @@ public class GFEDataDefinition extends
         String parmLevel = "%";
 
         HashMap queryList = new HashMap();
-        queryList.put(order[0], new RequestConstraint(productName));
-        for (int i = 1; i < selection.length; i++) {
-            if (order[i].equals(SITE_ID)) {
-                siteId = selection[i];
-            } else if (order[i].equals(MODEL_NAME)) {
-                modelName = selection[i];
-            } else if (order[i].equals(MODEL_TIME)) {
-                modelTime = selection[i];
-            } else if (order[i].equals(DB_TYPE)) {
-                dbType = selection[i];
-            } else if (order[i].equals(PARM_NAME)) {
-                parmName = selection[i];
-            } else if (order[i].equals(PARM_LEVEL)) {
-                parmLevel = selection[i];
+        queryList.put(PLUGIN_NAME, new RequestConstraint(productName));
+        if (selection.length > 1) {
+            String[] usedSelection = realignSelection(selection);
+            for (int i = 0; i < usedSelection.length; i++) {
+                if (order[i].equals(SITE_ID)) {
+                    siteId = usedSelection[i];
+                } else if (order[i].equals(MODEL_NAME)) {
+                    modelName = usedSelection[i];
+                } else if (order[i].equals(MODEL_TIME)) {
+                    modelTime = usedSelection[i];
+                } else if (order[i].equals(DB_TYPE)) {
+                    dbType = usedSelection[i];
+                } else if (order[i].equals(PARM_NAME)) {
+                    parmName = usedSelection[i];
+                } else if (order[i - 1].equals(PARM_LEVEL)) {
+                    parmLevel = usedSelection[i];
+                }
             }
         }
         String parmId = String.format(GFEUtil.PARM_ID_FORMAT, parmName,
diff --git a/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/rsc/GFEGridResource.java b/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/rsc/GFEGridResource.java
index a338d86cbf..51cf7c4b98 100644
--- a/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/rsc/GFEGridResource.java
+++ b/cave/com.raytheon.uf.viz.d2d.gfe/src/com/raytheon/uf/viz/d2d/gfe/rsc/GFEGridResource.java
@@ -19,6 +19,7 @@
  **/
 package com.raytheon.uf.viz.d2d.gfe.rsc;
 
+import java.util.Arrays;
 import java.util.List;
 
 import org.geotools.coverage.grid.GridGeometry2D;
@@ -58,8 +59,6 @@ import com.raytheon.viz.grid.rsc.general.GeneralGridData;
  */
 public class GFEGridResource extends AbstractGridResource {
 
-    private GridGeometry2D gridGeometry;
-
     private ParmID parmId;
 
     protected GFEGridResource(GFEGridResourceData resourceData,
@@ -80,9 +79,6 @@ public class GFEGridResource extends AbstractGridResource {
             GFERecord gfeRecord = (GFERecord) pdo;
             if (parmId == null) {
                 parmId = gfeRecord.getParmId();
-                populateGridParmInfo(gfeRecord);
-                gridGeometry = MapUtil.getGridGeometry(gfeRecord.getGridInfo()
-                        .getGridLoc());
             }
             super.addDataObject(pdo);
         }
@@ -106,27 +102,26 @@ public class GFEGridResource extends AbstractGridResource {
     }
 
     @Override
-    public GridGeometry2D getGridGeometry() {
-        return gridGeometry;
-    }
-
-    @Override
-    public GeneralGridData getData(DataTime time, List pdos)
-            throws VizException {
+    public List getData(DataTime time,
+            List pdos) throws VizException {
         if (pdos == null) {
             return null;
         }
         GFERecord gfeRecord = (GFERecord) pdos.get(0);
         IGridSlice slice = GFEUtil.getSlice(gfeRecord);
+        populateGridParmInfo(gfeRecord);
+        GridGeometry2D gridGeometry = MapUtil.getGridGeometry(gfeRecord
+                .getGridInfo().getGridLoc());
         if (slice instanceof VectorGridSlice) {
             VectorGridSlice vSlice = (VectorGridSlice) slice;
-            return GeneralGridData.createVectorData(vSlice.getMagGrid()
-                    .getBuffer(), vSlice.getDirGrid().getBuffer(), slice
-                    .getGridInfo().getUnitObject());
+            return Arrays.asList(GeneralGridData.createVectorData(gridGeometry,
+                    vSlice.getMagGrid().getBuffer(), vSlice.getDirGrid()
+                            .getBuffer(), slice.getGridInfo().getUnitObject()));
         } else if (slice instanceof ScalarGridSlice) {
             ScalarGridSlice sSlice = (ScalarGridSlice) slice;
-            return GeneralGridData.createScalarData(sSlice.getScalarGrid()
-                    .getBuffer(), slice.getGridInfo().getUnitObject());
+            return Arrays.asList(GeneralGridData.createScalarData(gridGeometry,
+                    sSlice.getScalarGrid().getBuffer(), slice.getGridInfo()
+                            .getUnitObject()));
         } else if (slice == null) {
             throw new VizException("Unable to load GFE Slice Data");
         } else {
diff --git a/cave/com.raytheon.uf.viz.d2d.nsharp/src/com/raytheon/uf/viz/d2d/nsharp/rsc/GribNSharpResourceData.java b/cave/com.raytheon.uf.viz.d2d.nsharp/src/com/raytheon/uf/viz/d2d/nsharp/rsc/GribNSharpResourceData.java
index ed98f7c188..aeae7f7119 100644
--- a/cave/com.raytheon.uf.viz.d2d.nsharp/src/com/raytheon/uf/viz/d2d/nsharp/rsc/GribNSharpResourceData.java
+++ b/cave/com.raytheon.uf.viz.d2d.nsharp/src/com/raytheon/uf/viz/d2d/nsharp/rsc/GribNSharpResourceData.java
@@ -76,7 +76,7 @@ public class GribNSharpResourceData extends D2DNSharpResourceData {
         String refTimeStr = formatTimestamp(stnInfo.getReftime());
         String validTimeStr = formatTimestamp(stnInfo.getRangestarttime());
         NcSoundingCube cube = NcSoundingQuery.mdlSoundingQueryByLatLon(
-                refTimeStr, validTimeStr, latLon, "grib", getSoundingType(),
+                refTimeStr, validTimeStr, latLon, "grid", getSoundingType(),
                 false, "-1");
         if (cube != null && !cube.getSoundingProfileList().isEmpty()) {
             NcSoundingProfile profileList = cube.getSoundingProfileList()
diff --git a/cave/com.raytheon.uf.viz.d2d.ui/src/com/raytheon/uf/viz/d2d/ui/map/SideView.java b/cave/com.raytheon.uf.viz.d2d.ui/src/com/raytheon/uf/viz/d2d/ui/map/SideView.java
index 8326b0ff29..b7952fcaca 100644
--- a/cave/com.raytheon.uf.viz.d2d.ui/src/com/raytheon/uf/viz/d2d/ui/map/SideView.java
+++ b/cave/com.raytheon.uf.viz.d2d.ui/src/com/raytheon/uf/viz/d2d/ui/map/SideView.java
@@ -93,8 +93,6 @@ import com.vividsolutions.jts.geom.Coordinate;
  *      Oct  22, 2009   #3348       bsteffen    limit number of frames in sidepane rather than reseting
  *      Jul 1, 2010     #6146       bkowal      Updates the legend mode so that smaller panes will 
  *                                              now include a legend
- *      Nov 20, 2012   DR 15524    M.Porricelli Changed so interactive screens still editable when
- *                                              swapped to side panel
  * 
  * 
* @@ -604,12 +602,11 @@ public class SideView extends ViewPart implements IMultiPaneEditor, if (editableResource != null) { EditableManager.makeEditable(editableResource, false); } - - this.editableResource = editableResource; if (this.editableResource != null) { EditableManager.makeEditable(this.editableResource, true); } - + this.editableResource = editableResource; + theEditor.getBackgroundColor().setColor(BGColorMode.EDITOR, myRenderables[0].getBackgroundColor()); diff --git a/cave/com.raytheon.uf.viz.d2d.xy.adapters/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.d2d.xy.adapters/META-INF/MANIFEST.MF index 2aba46657d..f4e82edc0c 100644 --- a/cave/com.raytheon.uf.viz.d2d.xy.adapters/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.d2d.xy.adapters/META-INF/MANIFEST.MF @@ -9,71 +9,33 @@ Eclipse-RegisterBuddy: com.raytheon.viz.core, com.raytheon.uf.viz.core Eclipse-BuddyPolicy: ext, global Require-Bundle: org.eclipse.core.runtime, com.raytheon.uf.viz.xy.crosssection;bundle-version="1.0.0", - com.raytheon.uf.viz.xy.timeheight;bundle-version="1.0.0", - com.raytheon.uf.viz.xy.varheight;bundle-version="1.12.1174" + com.raytheon.uf.viz.xy.varheight;bundle-version="1.12.1174", + com.raytheon.uf.viz.core;bundle-version="1.12.1174", + com.raytheon.uf.viz.xy;bundle-version="1.12.1174", + com.raytheon.viz.core;bundle-version="1.12.1174", + com.raytheon.viz.core.graphing;bundle-version="1.12.1174", + com.raytheon.uf.viz.xy.timeseries;bundle-version="1.12.1174", + javax.measure;bundle-version="1.0.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: com.raytheon.edex.plugin.bufrmos.common, - com.raytheon.edex.plugin.modelsounding.common, - com.raytheon.edex.util, - com.raytheon.uf.common.dataplugin, - com.raytheon.uf.common.dataplugin.acarssounding, - com.raytheon.uf.common.dataplugin.bufrua, - com.raytheon.uf.common.dataplugin.goessounding, - com.raytheon.uf.common.dataplugin.grib, +Import-Package: com.raytheon.uf.common.dataplugin, + com.raytheon.uf.common.dataplugin.grid, com.raytheon.uf.common.dataplugin.level, - com.raytheon.uf.common.dataplugin.obs.metar, - com.raytheon.uf.common.dataplugin.profiler, com.raytheon.uf.common.dataplugin.radar, com.raytheon.uf.common.dataplugin.radar.util, com.raytheon.uf.common.dataquery.requests, com.raytheon.uf.common.datastorage, com.raytheon.uf.common.datastorage.records, com.raytheon.uf.common.geospatial, + com.raytheon.uf.common.gridcoverage, + com.raytheon.uf.common.parameter, com.raytheon.uf.common.pointdata, - com.raytheon.uf.common.serialization, com.raytheon.uf.common.status, com.raytheon.uf.common.time, - com.raytheon.uf.viz.core, - com.raytheon.uf.viz.core.catalog, - com.raytheon.uf.viz.core.datastructure, - com.raytheon.uf.viz.core.exception, - com.raytheon.uf.viz.core.interp, - com.raytheon.uf.viz.core.level, - com.raytheon.uf.viz.core.map, - com.raytheon.uf.viz.core.rsc, - com.raytheon.uf.viz.core.rsc.capabilities, - com.raytheon.uf.viz.core.style.level, - com.raytheon.uf.viz.d2d.xy.adapters, com.raytheon.uf.viz.objectiveanalysis.rsc, - com.raytheon.uf.viz.xy, - com.raytheon.uf.viz.xy.crosssection.adapter, - com.raytheon.uf.viz.xy.crosssection.rsc, - com.raytheon.uf.viz.xy.graph, - com.raytheon.uf.viz.xy.timeseries.adapter, - com.raytheon.uf.viz.xy.timeseries.rsc, - com.raytheon.uf.viz.xy.varheight.adapter, - com.raytheon.uf.viz.xy.varheight.rsc, - com.raytheon.viz.core.graphing.util, - com.raytheon.viz.core.graphing.xy, - com.raytheon.viz.core.map, - com.raytheon.viz.core.slice.request, com.raytheon.viz.grid, com.raytheon.viz.grid.inv, com.raytheon.viz.radar.util, - com.vividsolutions.jts.geom, - javax.measure.converter, - javax.measure.unit, - org.eclipse.swt.graphics, - org.geotools.coverage.grid, - org.geotools.geometry, - org.geotools.referencing, - org.geotools.referencing.operation.matrix, - org.geotools.referencing.operation.transform, - org.opengis.metadata.spatial, - org.opengis.referencing, - org.opengis.referencing.crs, - org.opengis.referencing.datum, - org.opengis.referencing.operation + org.eclipse.swt.graphics Export-Package: com.raytheon.uf.viz.d2d.xy.adapters, com.raytheon.uf.viz.d2d.xy.adapters.crosssection, com.raytheon.uf.viz.d2d.xy.adapters.timeseries, diff --git a/cave/com.raytheon.uf.viz.d2d.xy.adapters/plugin.xml b/cave/com.raytheon.uf.viz.d2d.xy.adapters/plugin.xml index 0f2cef867a..544c7f5099 100644 --- a/cave/com.raytheon.uf.viz.d2d.xy.adapters/plugin.xml +++ b/cave/com.raytheon.uf.viz.d2d.xy.adapters/plugin.xml @@ -4,9 +4,9 @@ + adapter="com.raytheon.uf.viz.d2d.xy.adapters.crosssection.GridCSAdapter" + class="com.raytheon.uf.common.dataplugin.grid.GridRecord" + name="Grid Cross Section Adapter"> + adapter="com.raytheon.uf.viz.d2d.xy.adapters.timeseries.GridTimeSeriesAdapter" + class="com.raytheon.uf.common.dataplugin.grid.GridRecord" + name="Grid Time Series Adapter"> + adapter="com.raytheon.uf.viz.d2d.xy.adapters.varheight.GridVarHeightAdapter" + class="com.raytheon.uf.common.dataplugin.grid.GridRecord" + name="Grid Var Height Adapter"> * @@ -80,18 +80,21 @@ import com.vividsolutions.jts.geom.Coordinate; * @version 1.0 */ -public class GribCSAdapter extends AbstractCrossSectionAdapter { +public class GridCSAdapter extends AbstractCrossSectionAdapter { private static final long serialVersionUID = 1L; protected String yParameter = null; - protected Map> yRecords = new HashMap>(); + protected Map> yRecords = new HashMap>(); private Unit unit; private CoordinateReferenceSystem crs; + private Map> rectangleCache = new HashMap>( + 4); + /* * (non-Javadoc) * @@ -103,10 +106,9 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { public String getParameterName() { String name = null; if (records != null && !records.isEmpty()) { - GribModel modelInfo = records.get(0).getModelInfo(); - name = modelInfo.getParameterName(); + name = records.get(0).getParameter().getName(); if (name == null || name.isEmpty()) { - name = modelInfo.getParameterAbbreviation(); + name = records.get(0).getParameter().getAbbreviation(); } } return name; @@ -136,13 +138,13 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { throws VizException { DataTime recordTime = currentTime.clone(); recordTime.setLevelValue(null); - Set yRecords = getYRecords(recordTime); - Map xMap = new HashMap(); + Set yRecords = getYRecords(recordTime); + Map xMap = new HashMap(); synchronized (records) { - for (GribRecord rec : records) { + for (GridRecord rec : records) { if (rec.getDataTime().equals(recordTime)) { - xMap.put(rec.getModelInfo().getLevel(), rec); + xMap.put(rec.getLevel(), rec); } } } @@ -151,10 +153,10 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { return null; } - Map yMap = new HashMap(); - for (GribRecord rec : yRecords) { + Map yMap = new HashMap(); + for (GridRecord rec : yRecords) { if (rec.getDataTime().equals(recordTime)) { - yMap.put(rec.getModelInfo().getLevel(), rec); + yMap.put(rec.getLevel(), rec); } } @@ -167,76 +169,66 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { int nx = (int) geometry.getGridRange2D().getWidth(); int ny = (int) geometry.getGridRange2D().getHeight(); - - ISpatialObject area = records.get(0).getSpatialObject(); - - Rectangle requestArea = null; - Coordinate[] coordinates = GeoUtil.splitLine(nx, - descriptor.getLine(currentTime).getCoordinates()); - - for (Coordinate c : coordinates) { - DirectPosition2D point = null; - try { - point = PointUtil.determineExactIndex(c, area.getCrs(), - MapUtil.getGridGeometry(area)); - } catch (Exception e) { - throw new VizException(e); - } - if (requestArea == null) { - requestArea = new Rectangle((int) Math.floor(point.x), - (int) Math.floor(point.y), 1, 1); - } else { - requestArea.add(point); + Map> recordsByLocation = new HashMap>(); + for (GridRecord record : xMap.values()) { + List list = recordsByLocation.get(record + .getLocation()); + if (list == null) { + list = new ArrayList(); + recordsByLocation.put(record.getLocation(), list); } + list.add(record); } - requestArea.height += 1; - requestArea.width += 1; - requestArea = requestArea.intersection(new Rectangle(0, 0, - area.getNx(), area.getNy())); - if (requestArea.isEmpty()) { - throw new VizException( - "Invalid line position. Check that the line is within the grib boundaries."); - } - Request request = Request.buildSlab( - new int[] { (int) requestArea.getMinX(), - (int) requestArea.getMinY() }, - new int[] { (int) requestArea.getMaxX(), - (int) requestArea.getMaxY() }); - List pdos = new ArrayList( - xMap.size() * 2); - pdos.addAll(xMap.values()); - pdos.addAll(yMap.values()); - - DataCubeContainer.getDataRecords(pdos, request, null); - - List result = new ArrayList(); - for (int i = 0; i < nx; i++) { - DirectPosition2D point = null; - try { - point = PointUtil.determineExactIndex(coordinates[i], - area.getCrs(), MapUtil.getGridGeometry(area)); - } catch (Exception e) { - throw new VizException(e); + for (GridRecord record : yMap.values()) { + List list = recordsByLocation.get(record + .getLocation()); + if (list == null) { + list = new ArrayList(); + recordsByLocation.put(record.getLocation(), list); } - if (!requestArea.contains(point)) { + list.add(record); + } + for (Entry> entry : recordsByLocation + .entrySet()) { + Request request = getRequest(entry.getKey(), currentTime, geometry); + if (request == null) { continue; } + DataCubeContainer.getDataRecords(entry.getValue(), request, null); + + } + Coordinate[] coordinates = GeoUtil.splitLine(nx, + descriptor.getLine(currentTime).getCoordinates()); + List result = new ArrayList(); + for (int i = 0; i < nx; i++) { List> dataLists = new ArrayList>( result.size()); for (Level level : xMap.keySet()) { - GribRecord yRecord = yMap.get(level); + GridRecord yRecord = yMap.get(level); FloatDataRecord yRec = (FloatDataRecord) (((IDataRecord[]) yRecord .getMessageData())[0]); - GribRecord xRecord = xMap.get(level); + GridRecord xRecord = xMap.get(level); IDataRecord[] results = (IDataRecord[]) xRecord .getMessageData(); - - float yVal = InterpUtils.getInterpolatedData(requestArea, - point.x, point.y, yRec.getFloatData()); + DirectPosition2D yPoint = null; + try { + yPoint = PointUtil.determineExactIndex(coordinates[i], + yRecord.getLocation().getCrs(), + MapUtil.getGridGeometry(yRecord.getLocation())); + } catch (Exception e) { + throw new VizException(e); + } + Rectangle yRect = getRectangle(yRecord.getLocation(), + currentTime, geometry); + if (!yRect.contains(yPoint)) { + continue; + } + float yVal = InterpUtils.getInterpolatedData(yRect, yPoint.x, + yPoint.y, yRec.getFloatData()); yVal = (float) yRecord - .getModelInfo() - .getParameterUnitObject() + .getParameter() + .getUnit() .getConverterTo( descriptor.getHeightScale().getParameterUnit()) .convert(yVal); @@ -246,12 +238,23 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { while (dataLists.size() < results.length) { dataLists.add(new ArrayList()); } - double speed = Float.NaN; - double direction = Double.NaN; + DirectPosition2D xPoint = null; + try { + xPoint = PointUtil.determineExactIndex(coordinates[i], + xRecord.getLocation().getCrs(), + MapUtil.getGridGeometry(xRecord.getLocation())); + } catch (Exception e) { + throw new VizException(e); + } + Rectangle xRect = getRectangle(xRecord.getLocation(), + currentTime, geometry); + if (!xRect.contains(xPoint)) { + continue; + } for (int c = 0; c < results.length; c++) { FloatDataRecord xRec = (FloatDataRecord) results[c]; - float xVal = InterpUtils.getInterpolatedData(requestArea, - point.x, point.y, xRec.getFloatData()); + float xVal = InterpUtils.getInterpolatedData(xRect, + xPoint.x, xPoint.y, xRec.getFloatData()); if (xVal <= -9999) { continue; } @@ -269,20 +272,72 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { float[] column = InterpUtils.makeColumn(dataList, ny, graph, descriptor.getHeightScale().getMinVal() < descriptor .getHeightScale().getMaxVal(), -999999f); + for (int j = 0; j < column.length; j++) { floatData[j * nx + i] = column[j]; } } } - return result; } + private Rectangle getRectangle(GridCoverage location, DataTime time, + GridGeometry2D geometry) throws VizException { + Map timeCache = rectangleCache.get(location); + if (timeCache == null) { + timeCache = new HashMap(); + rectangleCache.put(location, timeCache); + } + Rectangle rectangle = timeCache.get(time); + if (rectangle == null) { + Coordinate[] coordinates = GeoUtil.splitLine(geometry + .getGridRange2D().width, descriptor.getLine(time) + .getCoordinates()); + + for (Coordinate c : coordinates) { + DirectPosition2D point = null; + try { + point = PointUtil.determineExactIndex(c, location.getCrs(), + MapUtil.getGridGeometry(location)); + } catch (Exception e) { + throw new VizException(e); + } + if (rectangle == null) { + rectangle = new Rectangle((int) Math.floor(point.x), + (int) Math.floor(point.y), 1, 1); + } else { + rectangle.add(point); + } + } + + rectangle.height += 1; + rectangle.width += 1; + rectangle = rectangle.intersection(new Rectangle(0, 0, location + .getNx(), location.getNy())); + timeCache.put(time, rectangle); + } + + return rectangle; + } + + private Request getRequest(GridCoverage location, DataTime time, + GridGeometry2D geometry) throws VizException { + Rectangle rectangle = getRectangle(location, time, geometry); + if (rectangle.isEmpty()) { + return null; + } + return Request.buildSlab( + new int[] { (int) rectangle.getMinX(), + (int) rectangle.getMinY() }, + new int[] { (int) rectangle.getMaxX(), + (int) rectangle.getMaxY() }); + } + public void addRecord(PluginDataObject pdo) { super.addRecord(pdo); - if (pdo != null && pdo instanceof GribRecord) { - unit = ((GribRecord) pdo).getModelInfo().getParameterUnitObject(); - crs = ((GribRecord) pdo).getSpatialObject().getCrs(); + if (pdo != null && pdo instanceof GridRecord) { + unit = ((GridRecord) pdo).getParameter().getUnit(); + crs = ((GridRecord) pdo).getSpatialObject().getCrs(); } yRecords.remove(pdo.getDataTime()); } @@ -292,9 +347,9 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { super.remove(time); } - private Set getYRecords(DataTime time) throws VizException { + private Set getYRecords(DataTime time) throws VizException { synchronized (yRecords) { - Set yRecords = this.yRecords.get(time); + Set yRecords = this.yRecords.get(time); if (yRecords != null) { return yRecords; } @@ -315,9 +370,9 @@ public class GribCSAdapter extends AbstractCrossSectionAdapter { property.setSelectedEntryTimes(new DataTime[] { time }); List recs = DataCubeContainer.getData(property, 60000); - yRecords = new HashSet(recs.size()); + yRecords = new HashSet(recs.size()); for (Object obj : recs) { - yRecords.add((GribRecord) obj); + yRecords.add((GridRecord) obj); } this.yRecords.put(time, yRecords); if (yRecords.isEmpty()) { diff --git a/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/timeseries/GribTimeSeriesAdapter.java b/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/timeseries/GridTimeSeriesAdapter.java similarity index 76% rename from cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/timeseries/GribTimeSeriesAdapter.java rename to cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/timeseries/GridTimeSeriesAdapter.java index 39905a785d..6e496227bf 100644 --- a/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/timeseries/GribTimeSeriesAdapter.java +++ b/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/timeseries/GridTimeSeriesAdapter.java @@ -23,6 +23,7 @@ import java.awt.Point; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; @@ -31,13 +32,14 @@ import javax.measure.converter.UnitConverter; import javax.measure.unit.Unit; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.common.geospatial.ISpatialObject; import com.raytheon.uf.common.geospatial.MapUtil; import com.raytheon.uf.common.geospatial.PointUtil; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -54,7 +56,7 @@ import com.raytheon.viz.core.graphing.xy.XYWindImageData; import com.raytheon.viz.grid.GridLevelTranslator; /** - * TODO Add Description + * Adapter providing a TimeSeries view of GridData. * *
  * 
@@ -69,14 +71,14 @@ import com.raytheon.viz.grid.GridLevelTranslator;
  * @version 1.0
  */
 
-public class GribTimeSeriesAdapter extends
-        AbstractTimeSeriesAdapter {
+public class GridTimeSeriesAdapter extends
+        AbstractTimeSeriesAdapter {
     private static final IUFStatusHandler statusHandler = UFStatus
-            .getHandler(GribTimeSeriesAdapter.class);
+            .getHandler(GridTimeSeriesAdapter.class);
 
-    private Map cache = new WeakHashMap();
+    private Map cache = new WeakHashMap();
 
-    protected Map> recordsByTime = new HashMap>();
+    protected Map> recordsByTime = new HashMap>();
 
     /** the level I would prefer to use **/
     protected Level preferredLevel = null;
@@ -127,30 +129,29 @@ public class GribTimeSeriesAdapter extends
      */
     @Override
     public XYDataList loadData() throws VizException {
-        ArrayList gribs = null;
+        ArrayList gribs = null;
         synchronized (recordsByTime) {
             // get available times
             Set times = recordsByTime.keySet();
             // set initial size of gribs
-            gribs = new ArrayList(times.size());
+            gribs = new ArrayList(times.size());
             // get the best record from each time ( use only one record for a
             // point in time )
             for (DataTime key : times) {
-                Set records = recordsByTime.get(key);
-                GribRecord[] allRecords = records
-                        .toArray(new GribRecord[records.size()]);
-                GribRecord bestRecord = null;
+                Set records = recordsByTime.get(key);
+                GridRecord[] allRecords = records
+                        .toArray(new GridRecord[records.size()]);
+                GridRecord bestRecord = null;
                 // if only one record, use it
                 if (allRecords.length == 1) {
                     bestRecord = allRecords[0];
                 } else if (records.size() > 1) {
                     // get the first record, or the one that matches the
                     // preferredLevel
-                    for (GribRecord rec : allRecords) {
+                    for (GridRecord rec : allRecords) {
                         if (bestRecord == null) {
                             bestRecord = rec;
-                        } else if (rec.getModelInfo().getLevel()
-                                .equals(preferredLevel)) {
+                        } else if (rec.getLevel().equals(preferredLevel)) {
                             bestRecord = rec;
                             break;
                         }
@@ -162,7 +163,26 @@ public class GribTimeSeriesAdapter extends
                 }
             }
         }
-        return loadInternal(gribs.toArray(new GribRecord[gribs.size()]));
+        HashMap> gridsByLocation = new HashMap>();
+        for (GridRecord grid : gribs) {
+            List list = gridsByLocation.get(grid.getLocation());
+            if (list == null) {
+                list = new ArrayList();
+                gridsByLocation.put(grid.getLocation(), list);
+            }
+            list.add(grid);
+        }
+        XYDataList result = null;
+        for (List list : gridsByLocation.values()) {
+            XYDataList newResult = loadInternal(list
+                    .toArray(new GridRecord[list.size()]));
+            if (result == null) {
+                result = newResult;
+            } else {
+                result.getData().addAll(newResult.getData());
+            }
+        }
+        return result;
     }
 
     @Override
@@ -175,26 +195,25 @@ public class GribTimeSeriesAdapter extends
      */
     @Override
     public XYDataList loadRecord(PluginDataObject pdo) throws VizException {
-        GribRecord[] gribs = new GribRecord[1];
-        gribs[0] = (GribRecord) pdo;
+        GridRecord[] gribs = new GridRecord[1];
+        gribs[0] = (GridRecord) pdo;
         return loadInternal(gribs);
     }
 
     @Override
     public void addRecord(PluginDataObject pdo) {
         // store off records by level
-        if (pdo instanceof GribRecord) {
+        if (pdo instanceof GridRecord) {
             synchronized (recordsByTime) {
-                GribRecord record = (GribRecord) pdo;
+                GridRecord record = (GridRecord) pdo;
 
                 // set preferredLevel to first level
                 if (preferredLevel == null) {
-                    preferredLevel = record.getModelInfo().getLevel();
-                    preferredUnit = record.getModelInfo()
-                            .getParameterUnitObject();
-                    parameterName = record.getModelInfo().getParameterName();
-                    parameterAbbreviation = record.getModelInfo()
-                            .getParameterAbbreviation();
+                    preferredLevel = record.getLevel();
+                    preferredUnit = record.getParameter().getUnit();
+                    parameterName = record.getParameter().getName();
+                    parameterAbbreviation = record.getParameter()
+                            .getAbbreviation();
                     if (parameterName == null || parameterName.isEmpty()) {
                         if (parameterAbbreviation == null) {
                             parameterAbbreviation = "";
@@ -204,27 +223,27 @@ public class GribTimeSeriesAdapter extends
                 }
 
                 // add Unit to levelUnitMap if needed ( quick look-ups )
-                Level lvl = record.getModelInfo().getLevel();
+                Level lvl = record.getLevel();
                 Unit unit = levelUnitMap.get(lvl);
                 if (unit == null) {
-                    unit = record.getModelInfo().getParameterUnitObject();
+                    unit = record.getParameter().getUnit();
                     levelUnitMap.put(lvl, unit);
                 }
 
                 // add record to records by time
-                Set recordsAtTime = recordsByTime.get(record
+                Set recordsAtTime = recordsByTime.get(record
                         .getDataTime());
                 if (recordsAtTime == null) {
-                    recordsAtTime = new HashSet();
+                    recordsAtTime = new HashSet();
                     recordsByTime.put(record.getDataTime(), recordsAtTime);
                 }
                 recordsAtTime.add(record);
             }
         } else {
             // this shouldn't happen, code expects all pdo's for
-            // GribTimeSeriesAdapter to be GribRecords
+            // GribTimeSeriesAdapter to be GridRecords
             String message = "Unexpected PluginDataObject type; got "
-                    + pdo.getClass().getName() + " expected GribRecord";
+                    + pdo.getClass().getName() + " expected GridRecord";
             statusHandler.handle(Priority.PROBLEM, message, new Exception(
                     message));
         }
@@ -233,7 +252,7 @@ public class GribTimeSeriesAdapter extends
     @Override
     public boolean hasRecord(PluginDataObject pdo) {
         synchronized (recordsByTime) {
-            Set possibleRecords = recordsByTime.get(pdo
+            Set possibleRecords = recordsByTime.get(pdo
                     .getDataTime());
             if (possibleRecords != null && possibleRecords.contains(pdo)) {
                 return true;
@@ -242,7 +261,7 @@ public class GribTimeSeriesAdapter extends
         }
     }
 
-    private XYDataList loadInternal(GribRecord[] gribs) throws VizException {
+    private XYDataList loadInternal(GridRecord[] gribs) throws VizException {
         ArrayList data = new ArrayList();
 
         ISpatialObject area = gribs[0].getSpatialObject();
@@ -266,7 +285,7 @@ public class GribTimeSeriesAdapter extends
 
         boolean isIcon = displayType == DisplayType.ICON;
 
-        for (GribRecord rec : gribs) {
+        for (GridRecord rec : gribs) {
 
             IDataRecord[] records = cache.get(rec);
             if (records == null) {
@@ -278,15 +297,8 @@ public class GribTimeSeriesAdapter extends
 
             // received a (wind) vector result
             if (records.length > 1) {
-                double rotation = 0;
-                if ((rec.getResCompFlags() == null)
-                        || (rec.getResCompFlags() & 8) != 0) {
-                    rotation = 180 - MapUtil.rotation(
-                            resourceData.getCoordinate(),
-                            rec.getSpatialObject());
-                }
                 float[] vectorDirections = (float[]) records[1].getDataObject();
-                vectorDirection = vectorDirections[0] + rotation;
+                vectorDirection = vectorDirections[0];
                 isVectorData = true;
             }
 
@@ -298,9 +310,8 @@ public class GribTimeSeriesAdapter extends
             XYData dataPoint = null;
 
             // do I need to convert?
-            if (!rec.getModelInfo().getLevel().equals(preferredLevel)) {
-                Unit dataUnit = levelUnitMap.get(rec.getModelInfo()
-                        .getLevel());
+            if (!rec.getLevel().equals(preferredLevel)) {
+                Unit dataUnit = levelUnitMap.get(rec.getLevel());
                 if (!dataUnit.equals(preferredUnit)) {
                     // convert
                     UnitConverter conv = dataUnit.getConverterTo(preferredUnit);
diff --git a/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/varheight/GribVarHeightAdapter.java b/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/varheight/GridVarHeightAdapter.java
similarity index 54%
rename from cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/varheight/GribVarHeightAdapter.java
rename to cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/varheight/GridVarHeightAdapter.java
index 5644b9ae57..6da703c340 100644
--- a/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/varheight/GribVarHeightAdapter.java
+++ b/cave/com.raytheon.uf.viz.d2d.xy.adapters/src/com/raytheon/uf/viz/d2d/xy/adapters/varheight/GridVarHeightAdapter.java
@@ -21,10 +21,12 @@ package com.raytheon.uf.viz.d2d.xy.adapters.varheight;
 
 import java.awt.Rectangle;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Set;
 
 import javax.measure.unit.Unit;
@@ -32,15 +34,17 @@ import javax.measure.unit.Unit;
 import org.geotools.geometry.DirectPosition2D;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.dataplugin.level.Level;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
 import com.raytheon.uf.common.datastorage.Request;
 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.MapUtil;
 import com.raytheon.uf.common.geospatial.PointUtil;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
+import com.raytheon.uf.common.status.IUFStatusHandler;
+import com.raytheon.uf.common.status.UFStatus;
+import com.raytheon.uf.common.status.UFStatus.Priority;
 import com.raytheon.uf.common.time.DataTime;
 import com.raytheon.uf.viz.core.catalog.LayerProperty;
 import com.raytheon.uf.viz.core.datastructure.DataCubeContainer;
@@ -54,7 +58,8 @@ import com.raytheon.viz.core.slice.request.HeightScale;
 import com.raytheon.viz.grid.inv.GridInventory;
 
 /**
- * TODO Add Description
+ * Adapter for Grid data that returns the value of a variable at multiple
+ * heights.
  * 
  * 
  * 
@@ -69,9 +74,11 @@ import com.raytheon.viz.grid.inv.GridInventory;
  * @version 1.0
  */
 
-public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
+public class GridVarHeightAdapter extends AbstractVarHeightAdapter {
+    private static final IUFStatusHandler statusHandler = UFStatus
+            .getHandler(GridVarHeightAdapter.class);
 
-    protected HashMap> yRecordMap = new HashMap>();
+    protected HashMap> yRecordMap = new HashMap>();
 
     /*
      * (non-Javadoc)
@@ -83,11 +90,11 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
     @Override
     public String getParameterName() {
         synchronized (records) {
-            String name = ((GribRecord) records.iterator().next())
-                    .getModelInfo().getParameterName();
+            String name = ((GridRecord) records.iterator().next())
+                    .getParameter().getName();
             if (name == null || name.isEmpty()) {
-                name = ((GribRecord) records.iterator().next()).getModelInfo()
-                        .getParameterAbbreviation();
+                name = ((GridRecord) records.iterator().next()).getParameter()
+                        .getAbbreviation();
             }
             return name;
 
@@ -106,8 +113,8 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
             if (records == null || records.size() == 0) {
                 return null;
             }
-            return ((GribRecord) records.iterator().next()).getModelInfo()
-                    .getParameterUnitObject();
+            return ((GridRecord) records.iterator().next()).getParameter()
+                    .getUnit();
 
         }
     }
@@ -126,10 +133,10 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
 
         Set keys = yRecordMap.keySet();
         for (DataTime key : keys) {
-            Set aRecord = yRecordMap.get(key);
+            Set aRecord = yRecordMap.get(key);
             if (!aRecord.isEmpty()) {
-                return ((GribRecord) aRecord.iterator().next()).getModelInfo()
-                        .getParameterUnitObject();
+                return ((GridRecord) aRecord.iterator().next()).getParameter()
+                        .getUnit();
             }
         }
         return null;
@@ -146,33 +153,31 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
     public List loadData(DataTime currentTime) throws VizException {
         populateYRecords();
 
-        ArrayList needsRequested = new ArrayList();
+        ArrayList hasData = new ArrayList(
+                records.size());
 
-        Map xMap = new HashMap();
-        ISpatialObject area = null;
+        Map xMap = new HashMap();
         synchronized (records) {
 
-            for (GribRecord rec : records) {
-                area = rec.getSpatialObject();
+            for (GridRecord rec : records) {
                 if (rec.getDataTime().equals(currentTime)) {
-                    xMap.put(rec.getModelInfo().getLevel(), rec);
-                    if (rec.getMessageData() == null) {
-                        needsRequested.add(rec);
+                    xMap.put(rec.getLevel(), rec);
+                    if (rec.getMessageData() != null) {
+                        hasData.add(rec);
                     }
                 }
             }
         }
-        Map yMap = new HashMap();
+        Map yMap = new HashMap();
 
         synchronized (yRecordMap) {
 
-            Set yRecords = yRecordMap.get(currentTime);
-
+            Set yRecords = yRecordMap.get(currentTime);
             if (yRecords != null) {
-                for (GribRecord rec : yRecords) {
-                    yMap.put(rec.getModelInfo().getLevel(), rec);
-                    if (rec.getMessageData() == null) {
-                        needsRequested.add(rec);
+                for (GridRecord rec : yRecords) {
+                    yMap.put(rec.getLevel(), rec);
+                    if (rec.getMessageData() != null) {
+                        hasData.add(rec);
                     }
                 }
             }
@@ -188,62 +193,74 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
             return dataList;
         }
 
-        DirectPosition2D point = null;
-        try {
-            point = PointUtil.determineExactIndex(resourceData.getPoint(),
-                    area.getCrs(), MapUtil.getGridGeometry(area));
-        } catch (Exception e) {
-            throw new VizException(e);
+        Map> recordsByLocation = new HashMap>(
+                4);
+        for (GridRecord record : xMap.values()) {
+            if (hasData.contains(record)) {
+                continue;
+            }
+            List list = recordsByLocation.get(record
+                    .getLocation());
+            if (list == null) {
+                list = new ArrayList(xMap.size() * 2);
+                recordsByLocation.put(record.getLocation(), list);
+            }
+            list.add(record);
         }
-        Rectangle requestArea = new Rectangle((int) Math.floor(point.x),
-                (int) Math.floor(point.y), 2, 2);
-        requestArea = requestArea.intersection(new Rectangle(0, 0,
-                area.getNx(), area.getNy()));
-        if (requestArea.isEmpty()) {
-            throw new VizException("Invalid point position("
-                    + resourceData.getPoint()
-                    + "). Check that the point is within the grib boundaries.");
+
+        for (GridRecord record : yMap.values()) {
+            if (hasData.contains(record)) {
+                continue;
+            }
+            List list = recordsByLocation.get(record
+                    .getLocation());
+            if (list == null) {
+                list = new ArrayList(yMap.size());
+                recordsByLocation.put(record.getLocation(), list);
+            }
+            list.add(record);
         }
-        Request request = Request.buildSlab(
-                new int[] { (int) requestArea.getMinX(),
-                        (int) requestArea.getMinY() },
-                new int[] { (int) requestArea.getMaxX(),
-                        (int) requestArea.getMaxY() });
 
-        List pdos = new ArrayList(
-                xMap.size() * 2);
-        pdos.addAll(xMap.values());
-        pdos.addAll(yMap.values());
+        for (Entry> entry : recordsByLocation
+                .entrySet()) {
+            Request request = getRequest(entry.getKey());
+            if (request == null) {
+                continue;
+            }
+            DataCubeContainer.getDataRecords(entry.getValue(), request, null);
 
-        // only request pdos without data
-        pdos.retainAll(needsRequested);
-
-        DataCubeContainer.getDataRecords(pdos, request, null);
+        }
 
         for (Level level : xMap.keySet()) {
-            GribRecord yRecord = yMap.get(level);
+            GridRecord yRecord = yMap.get(level);
 
             FloatDataRecord yRec = (FloatDataRecord) ((IDataRecord[]) yRecord
                     .getMessageData())[0];
-            float yVal = InterpUtils.getInterpolatedData(requestArea, point.x,
-                    point.y, yRec.getFloatData());
+            DirectPosition2D yPoint = getPoint(yRecord.getLocation());
+            Rectangle yRect = getRectangle(yRecord.getLocation());
+            float yVal = InterpUtils.getInterpolatedData(yRect, yPoint.x,
+                    yPoint.y, yRec.getFloatData());
             if (yVal <= -9999) {
                 continue;
             }
-            GribRecord xRecord = xMap.get(level);
+            GridRecord xRecord = xMap.get(level);
+            DirectPosition2D xPoint = getPoint(xRecord.getLocation());
+            Rectangle xRect = getRectangle(xRecord.getLocation());
             IDataRecord[] results = ((IDataRecord[]) xRecord.getMessageData());
-            if (results.length == 4) {
+            if (results == null) {
+                continue;
+            } else if (results.length == 4) {
                 FloatDataRecord speedRec = (FloatDataRecord) results[0];
                 FloatDataRecord dirRec = (FloatDataRecord) results[1];
-                float speed = InterpUtils.getInterpolatedData(requestArea,
-                        point.x, point.y, speedRec.getFloatData());
-                float dir = InterpUtils.getInterpolatedData(requestArea,
-                        point.x, point.y, dirRec.getFloatData());
+                float speed = InterpUtils.getInterpolatedData(xRect, xPoint.x,
+                        xPoint.y, speedRec.getFloatData());
+                float dir = InterpUtils.getInterpolatedData(xRect, xPoint.x,
+                        xPoint.y, dirRec.getFloatData());
                 dataList.add(new XYWindImageData(speed, yVal, speed, dir));
             } else {
                 FloatDataRecord xRec = (FloatDataRecord) results[0];
-                float xVal = InterpUtils.getInterpolatedData(requestArea,
-                        point.x, point.y, xRec.getFloatData());
+                float xVal = InterpUtils.getInterpolatedData(xRect, xPoint.x,
+                        xPoint.y, xRec.getFloatData());
                 if (xVal <= -9999) {
                     continue;
                 }
@@ -251,9 +268,73 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
             }
         }
 
+        if (dataList.isEmpty()) {
+            statusHandler.handle(Priority.INFO, "No data found for point "
+                    + resourceData.getPoint() + ", at time " + currentTime
+                    + ", please verify point is within bounds of the data.");
+            return Collections.emptyList();
+        }
+
         return dataList;
     }
 
+    /**
+     * Retrive the coordinate in grid space(defined by location) where this
+     * adapter is expected to load data.
+     * 
+     * @param location
+     * @return
+     * @throws VizException
+     */
+    private DirectPosition2D getPoint(GridCoverage location)
+            throws VizException {
+        try {
+            return PointUtil.determineExactIndex(resourceData.getPoint(),
+                    location.getCrs(), location.getGridGeometry());
+        } catch (Exception e) {
+            throw new VizException(e);
+        }
+
+    }
+
+    /**
+     * find the rectangle in grid space(defined by location) where this adapter
+     * should request data, the rectangle is formed by adding enough space
+     * around the point to perform bilinear interpolation.
+     * 
+     * @param location
+     * @return
+     * @throws VizException
+     */
+    private Rectangle getRectangle(GridCoverage location) throws VizException {
+        DirectPosition2D point = getPoint(location);
+        Rectangle rectangle = new Rectangle((int) Math.floor(point.x),
+                (int) Math.floor(point.y), 2, 2);
+        rectangle = rectangle.intersection(new Rectangle(0, 0,
+                location.getNx(), location.getNy()));
+        return rectangle;
+    }
+
+    /**
+     * Find the datastore request needed to get data for GridRecords with the
+     * provided location.
+     * 
+     * @param location
+     * @return
+     * @throws VizException
+     */
+    private Request getRequest(GridCoverage location) throws VizException {
+        Rectangle rectangle = getRectangle(location);
+        if (rectangle.isEmpty()) {
+            return null;
+        }
+        return Request.buildSlab(
+                new int[] { (int) rectangle.getMinX(),
+                        (int) rectangle.getMinY() },
+                new int[] { (int) rectangle.getMaxX(),
+                        (int) rectangle.getMaxY() });
+    }
+
     public void addRecord(PluginDataObject pdo) {
         DataTime key = pdo.getDataTime().clone();
         key.setLevelValue(null);
@@ -309,13 +390,13 @@ public class GribVarHeightAdapter extends AbstractVarHeightAdapter {
             List recs = DataCubeContainer.getData(property, 60000);
 
             for (Object obj : recs) {
-                GribRecord gRecord = (GribRecord) obj;
-                Set recordSet = yRecordMap.get(gRecord
+                GridRecord gRecord = (GridRecord) obj;
+                Set recordSet = yRecordMap.get(gRecord
                         .getDataTime());
                 if (recordSet != null) {
                     recordSet.add(gRecord);
                 } else {
-                    recordSet = new HashSet();
+                    recordSet = new HashSet();
                     recordSet.add(gRecord);
                     yRecordMap.put(gRecord.getDataTime(), recordSet);
                 }
diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.datastorage.remote/META-INF/MANIFEST.MF
deleted file mode 100644
index c64c52b630..0000000000
--- a/cave/com.raytheon.uf.viz.datastorage.remote/META-INF/MANIFEST.MF
+++ /dev/null
@@ -1,12 +0,0 @@
-Manifest-Version: 1.0
-Bundle-ManifestVersion: 2
-Bundle-Name: Thrift Plug-in
-Bundle-SymbolicName: com.raytheon.uf.viz.datastorage.remote
-Bundle-Version: 1.12.1174.qualifier
-Bundle-Vendor: RAYTHEON
-Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Require-Bundle: com.raytheon.uf.common.datastorage;bundle-version="1.11.12",
- com.raytheon.uf.common.datastorage.remote;bundle-version="1.0.0",
- com.raytheon.uf.common.serialization.comm;bundle-version="1.0.0",
- com.raytheon.uf.viz.core;bundle-version="1.11.12"
-Export-Package: com.raytheon.uf.viz.datastorage.remote
diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/com.raytheon.uf.viz.datastorage.remote.ecl b/cave/com.raytheon.uf.viz.datastorage.remote/com.raytheon.uf.viz.datastorage.remote.ecl
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/src/com/raytheon/uf/viz/datastorage/remote/RemoteDataStore.java b/cave/com.raytheon.uf.viz.datastorage.remote/src/com/raytheon/uf/viz/datastorage/remote/RemoteDataStore.java
deleted file mode 100644
index 0936f0d3db..0000000000
--- a/cave/com.raytheon.uf.viz.datastorage.remote/src/com/raytheon/uf/viz/datastorage/remote/RemoteDataStore.java
+++ /dev/null
@@ -1,259 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.uf.viz.datastorage.remote;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.util.Map;
-
-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.StorageProperties;
-import com.raytheon.uf.common.datastorage.StorageProperties.Compression;
-import com.raytheon.uf.common.datastorage.StorageStatus;
-import com.raytheon.uf.common.datastorage.records.IDataRecord;
-import com.raytheon.uf.common.datastorage.remote.requests.ThriftDataRequest;
-import com.raytheon.uf.common.datastorage.remote.requests.ThriftDataResponse;
-import com.raytheon.uf.viz.core.exception.VizException;
-import com.raytheon.uf.viz.core.requests.ThriftClient;
-
-/**
- * Creates RetrieveDataRequests and sends them to the edex server.
- * 
- * 
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Aug 3, 2009            mschenke     Initial creation
- * 
- * 
- * - * @author mschenke - * @version 1.0 - */ - -public class RemoteDataStore implements IDataStore { - - private File file; - - private boolean useLocking; - - public RemoteDataStore(File file, boolean useLocking) { - this.file = file; - this.useLocking = useLocking; - } - - @Override - public String[] getDatasets(String group) throws StorageException, - FileNotFoundException { - ThriftDataRequest request = new ThriftDataRequest(); - request.setFile(file.getAbsolutePath()); - request.setUseLocking(useLocking); - request.setMethod("getDatasets"); - request.setParameterTypes(new String[] { String.class.getName() }); - request.setParameters(new Object[] { group }); - try { - ThriftDataResponse response = (ThriftDataResponse) ThriftClient - .sendRequest(request); - if (response.getDatasets() == null) { - throw new VizException("response object was null"); - } - return response.getDatasets(); - } catch (VizException e) { - throw new StorageException("unable to retrieve data over http", - null, e); - } - } - - @Override - public IDataRecord[] retrieve(String group) throws StorageException, - FileNotFoundException { - ThriftDataRequest request = new ThriftDataRequest(); - request.setFile(file.getAbsolutePath()); - request.setUseLocking(useLocking); - request.setMethod("retrieve"); - request.setParameterTypes(new String[] { String.class.getName() }); - request.setParameters(new Object[] { group }); - try { - ThriftDataResponse response = (ThriftDataResponse) ThriftClient - .sendRequest(request); - if (response.getRecords() == null) { - throw new VizException("response object was null"); - } - return response.getRecords(); - } catch (VizException e) { - throw new StorageException("unable to retrieve data over http", - null, e); - } - } - - @Override - public IDataRecord[] retrieve(String group, boolean includeInterpolated) - throws StorageException, FileNotFoundException { - ThriftDataRequest request = new ThriftDataRequest(); - request.setFile(file.getAbsolutePath()); - request.setUseLocking(useLocking); - request.setMethod("retrieve"); - request.setParameterTypes(new String[] { String.class.getName(), - boolean.class.getName() }); - request.setParameters(new Object[] { group, includeInterpolated }); - try { - ThriftDataResponse response = (ThriftDataResponse) ThriftClient - .sendRequest(request); - if (response.getRecords() == null) { - throw new VizException("response object was null"); - } - return response.getRecords(); - } catch (VizException e) { - throw new StorageException("unable to retrieve data over http", - null, e); - } - } - - @Override - public IDataRecord retrieve(String group, String dataset, Request request) - throws StorageException, FileNotFoundException { - ThriftDataRequest req = new ThriftDataRequest(); - req.setFile(file.getAbsolutePath()); - req.setUseLocking(useLocking); - req.setMethod("retrieve"); - req.setParameterTypes(new String[] { String.class.getName(), - String.class.getName(), Request.class.getName() }); - req.setParameters(new Object[] { group, dataset, request }); - try { - ThriftDataResponse response = (ThriftDataResponse) ThriftClient - .sendRequest(req); - if (response.getRecord() == null) { - throw new VizException("response object was null"); - } - return response.getRecord(); - } catch (VizException e) { - throw new StorageException("unable to retrieve data over http", - null, e); - } - } - - @Override - public IDataRecord[] retrieveDatasets(String[] datasetGroupPath, - Request request) throws StorageException, FileNotFoundException { - ThriftDataRequest req = new ThriftDataRequest(); - req.setFile(file.getAbsolutePath()); - req.setUseLocking(useLocking); - req.setMethod("retrieveDatasets"); - req.setParameterTypes(new String[] { String[].class.getName(), - Request.class.getName() }); - req.setParameters(new Object[] { datasetGroupPath, request }); - try { - ThriftDataResponse response = (ThriftDataResponse) ThriftClient - .sendRequest(req); - if (response.getRecords() == null) { - throw new VizException("response object was null"); - } - return response.getRecords(); - } catch (VizException e) { - throw new StorageException("unable to retrieve data over http", - null, e); - } - } - - @Override - public IDataRecord[] retrieveGroups(String[] groups, Request request) - throws StorageException, FileNotFoundException { - ThriftDataRequest req = new ThriftDataRequest(); - req.setFile(file.getAbsolutePath()); - req.setUseLocking(useLocking); - req.setMethod("retrieveGroups"); - req.setParameterTypes(new String[] { String[].class.getName(), - Request.class.getName() }); - req.setParameters(new Object[] { groups, request }); - try { - ThriftDataResponse response = (ThriftDataResponse) ThriftClient - .sendRequest(req); - if (response.getRecords() == null) { - throw new VizException("response object was null"); - } - return response.getRecords(); - } catch (VizException e) { - throw new StorageException("unable to retrieve data over http", - null, e); - } - } - - @Override - public void addDataRecord(IDataRecord dataset, StorageProperties properties) - throws StorageException { - throw new StorageException("Operation not supported", dataset); - } - - @Override - public void addDataRecord(IDataRecord dataset) throws StorageException { - throw new StorageException("Operation not supported", dataset); - } - - @Override - public void delete(String... location) throws StorageException, - FileNotFoundException { - throw new StorageException("Operation not supported", null); - } - - @Override - public StorageStatus store() throws StorageException { - throw new StorageException("Operation not supported", null); - } - - @Override - public StorageStatus store(StoreOp storeOp) throws StorageException { - throw new StorageException("Operation not supported", null); - } - - @Override - public void createLinks(Map links) - throws StorageException, FileNotFoundException { - throw new StorageException("Operation not supported", null); - - } - - @Override - public void deleteFiles(String[] datesToDelete) throws StorageException, - FileNotFoundException { - throw new StorageException("Operation not supported", null); - } - - @Override - public void createDataset(IDataRecord rec) throws StorageException, - FileNotFoundException { - throw new StorageException("Operation not supported", null); - } - - @Override - public void repack(Compression compression) throws StorageException { - throw new StorageException("Operation not supported", null); - } - - @Override - public void copy(String outputDir, Compression compression, - String timestampCheck, int minMillisSinceLastChange, - int maxMillisSinceLastChange) throws StorageException { - throw new StorageException("Operation not supported", null); - } - -} diff --git a/cave/com.raytheon.uf.viz.derivparam.python/src/com/raytheon/uf/viz/derivparam/python/MasterDerivScript.java b/cave/com.raytheon.uf.viz.derivparam.python/src/com/raytheon/uf/viz/derivparam/python/MasterDerivScript.java index f98f52cad2..494bfd7f9a 100644 --- a/cave/com.raytheon.uf.viz.derivparam.python/src/com/raytheon/uf/viz/derivparam/python/MasterDerivScript.java +++ b/cave/com.raytheon.uf.viz.derivparam.python/src/com/raytheon/uf/viz/derivparam/python/MasterDerivScript.java @@ -61,7 +61,7 @@ public class MasterDerivScript extends PythonInterpreter { private static final String DATA_NAME = "Data"; - private Map prevArgs = new HashMap(); + private final Map> prevArgs = new HashMap>(); /** * Constructor @@ -86,7 +86,14 @@ public class MasterDerivScript extends PythonInterpreter { throws JepException { this.prevArgs.clear(); executeFunctionInternal(name, args); - cleanupGlobals(); + jep.eval("globalsRef=globals()"); + for (List pArgs : prevArgs.values()) { + for (String arg : pArgs) { + jep.eval(arg + " = None"); + jep.eval("del globalsRef['" + arg + "']"); + } + } + this.prevArgs.clear(); return getExecutionResult(); } @@ -122,7 +129,7 @@ public class MasterDerivScript extends PythonInterpreter { protected void evaluateArgument(String argName, Object argValue) throws JepException { if (prevArgs.containsKey(argValue)) { - jep.eval(argName + " = " + prevArgs.get(argValue)); + jep.eval(argName + " = " + prevArgs.get(argValue).get(0)); } else if (argValue instanceof List) { @SuppressWarnings({ "rawtypes" }) List valList = (List) argValue; @@ -222,7 +229,7 @@ public class MasterDerivScript extends PythonInterpreter { // create a list of arrays jep.eval(argName + " = []"); for (int argIdx = 0; argIdx < valList.length; argIdx++) { - IDataRecord val = (IDataRecord) valList[argIdx]; + IDataRecord val = valList[argIdx]; jep.eval(argName + ".append(None)"); // setNumeric won't work with indexed objects evaluateArgument("__tmp", val); @@ -248,7 +255,12 @@ public class MasterDerivScript extends PythonInterpreter { } else { super.evaluateArgument(argName, argValue); } - prevArgs.put(argValue, argName); + List pArgs = prevArgs.get(argValue); + if (pArgs == null) { + pArgs = new ArrayList(); + prevArgs.put(argValue, pArgs); + } + pArgs.add(argName); } /** diff --git a/cave/com.raytheon.uf.viz.derivparam/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.derivparam/META-INF/MANIFEST.MF index f3db5554a2..20faa2eb66 100644 --- a/cave/com.raytheon.uf.viz.derivparam/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.derivparam/META-INF/MANIFEST.MF @@ -7,26 +7,25 @@ Bundle-Activator: com.raytheon.uf.viz.derivparam.Activator Bundle-Vendor: RAYTHEON Require-Bundle: org.eclipse.core.runtime, javax.measure, - com.raytheon.uf.common.dataquery, com.raytheon.uf.viz.core;bundle-version="1.12.1174", com.raytheon.uf.common.datastorage;bundle-version="1.12.1174", - com.raytheon.uf.common.pointdata;bundle-version="1.12.1174" + com.raytheon.uf.common.pointdata;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin.level;bundle-version="1.12.1174", + com.raytheon.uf.common.util;bundle-version="1.12.1174" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Eclipse-RegisterBuddy: com.raytheon.uf.common.serialization -Import-Package: com.raytheon.edex.meteoLib, - com.raytheon.edex.util, - com.raytheon.uf.common.comm, +Import-Package: com.raytheon.uf.common.comm, com.raytheon.uf.common.dataplugin, - com.raytheon.uf.common.dataplugin.level, - com.raytheon.uf.common.dataplugin.persist, com.raytheon.uf.common.derivparam.tree, + com.raytheon.uf.common.geospatial, com.raytheon.uf.common.localization, - com.raytheon.uf.common.message.response, com.raytheon.uf.common.serialization, com.raytheon.uf.common.serialization.adapters, com.raytheon.uf.common.status, - com.raytheon.uf.common.time + com.raytheon.uf.common.time, + com.vividsolutions.jts.geom, + org.opengis.referencing.crs Export-Package: com.raytheon.uf.viz.derivparam, com.raytheon.uf.viz.derivparam.data, com.raytheon.uf.viz.derivparam.inv, diff --git a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/TP6hr.xml b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/TP6hr.xml index c93d707390..454959cbb7 100644 --- a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/TP6hr.xml +++ b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/TP6hr.xml @@ -22,11 +22,8 @@ - - - - - + + diff --git a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Tstk.xml b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Tstk.xml index e8e1e04ac2..6b5e4375b1 100644 --- a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Tstk.xml +++ b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Tstk.xml @@ -31,7 +31,7 @@ - + diff --git a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Twstk.xml b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Twstk.xml index d3466d4dd0..468e3a403d 100644 --- a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Twstk.xml +++ b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/Twstk.xml @@ -27,7 +27,7 @@ - + diff --git a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/WD.xml b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/WD.xml index ae575d5d3c..9682239ceb 100644 --- a/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/WD.xml +++ b/cave/com.raytheon.uf.viz.derivparam/localization/derivedParameters/definitions/WD.xml @@ -18,7 +18,7 @@ See_the_AWIPS_II_Master_Rights_File_("Master_Rights_File.pdf")_for further_licensing_information. --> - + diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractDataCubeAdapter.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractDataCubeAdapter.java index aa292d8c95..fea9a392ed 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractDataCubeAdapter.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractDataCubeAdapter.java @@ -24,19 +24,15 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; import com.raytheon.uf.common.dataquery.requests.DbQueryRequestSet; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType; import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequestSet; import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; import com.raytheon.uf.common.dataquery.responses.DbQueryResponseSet; import com.raytheon.uf.common.datastorage.Request; @@ -48,8 +44,10 @@ import com.raytheon.uf.viz.core.datastructure.IDataCubeAdapter; import com.raytheon.uf.viz.core.datastructure.VizDataCubeException; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.requests.ThriftClient; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode.Dependency; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.MetadataContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; /** * Abstract data cube adapter for standard data type that uses derived @@ -99,55 +97,67 @@ public abstract class AbstractDataCubeAdapter implements IDataCubeAdapter { @Override public List> timeQuery(List requests) throws VizException { - int mapSize = (int) (requests.size() * 1) + 1; - Map> cache = new HashMap>( - mapSize); - LinkedHashMap queries = new LinkedHashMap( - mapSize); - - for (TimeQueryRequest request : requests) { - List requestNodes = evaluateRequestConstraints(request - .getQueryTerms()); - // pull out time queries and bulk submit - for (AbstractRequestableLevelNode requestNode : requestNodes) { - getTimeQuery(request, requestNode, false, queries, cache, null); - } - } - - // set the results back into the cache's - TimeQueryRequestSet reqSet = new TimeQueryRequestSet(); - reqSet.setRequests(queries.values().toArray( - new TimeQueryRequest[queries.size()])); - @SuppressWarnings("unchecked") - List> qResponses = (List>) ThriftClient - .sendRequest(reqSet); - int index = 0; - for (AbstractRequestableLevelNode node : queries.keySet()) { - // put results into cache - node.setTimeQueryResults(false, qResponses.get(index++), cache, - null); - } - List> finalResponse = new ArrayList>( + List containers = new ArrayList( + requests.size()); + List> requestLists = new ArrayList>( + requests.size()); + List fullList = new ArrayList( requests.size()); for (TimeQueryRequest request : requests) { - List requestNodes = evaluateRequestConstraints(request + AvailabilityContainer container = createAvailabilityContainer(request + .getQueryTerms()); + List requestNodes = evaluateRequestConstraints(request + .getQueryTerms()); + // pull out time queries and bulk submit + for (AbstractRequestableNode requestNode : requestNodes) { + container.prepareRequests(requestNode); + } + containers.add(container); + List containerRequests = container + .getAvailabilityRequests(); + requestLists.add(containerRequests); + fullList.addAll(containerRequests); + } + + // bulk up all the requests. + DbQueryRequestSet requestSet = new DbQueryRequestSet(); + requestSet.setQueries(fullList.toArray(new DbQueryRequest[0])); + DbQueryResponseSet responseSet = (DbQueryResponseSet) ThriftClient + .sendRequest(requestSet); + DbQueryResponse[] responses = responseSet.getResults(); + int responseIndex = 0; + List> finalResponse = new ArrayList>( + requests.size()); + for (int i = 0; i < requests.size(); i += 1) { + TimeQueryRequest request = requests.get(i); + AvailabilityContainer container = containers.get(i); + // set the bulked responses back into the container + List containerRequests = requestLists.get(i); + Map responseMap = new HashMap( + (int) (containerRequests.size() / 0.75) + 1, 0.75f); + for (int j = 0; j < containerRequests.size(); j += 1) { + responseMap.put(containerRequests.get(j), + responses[responseIndex++]); + } + container.setAvailabilityResponses(responseMap); + List requestNodes = evaluateRequestConstraints(request .getQueryTerms()); // pull the actual results from the cache Set results = new HashSet(64); - for (AbstractRequestableLevelNode requestNode : requestNodes) { - Set times = requestNode.timeQuery(request, false, - cache, null); - if (times == AbstractRequestableLevelNode.TIME_AGNOSTIC) { - // TODO: include time agnostic query in main bulk query as - // each pressure level will cause a separate query - List temp = timeAgnosticQuery(request - .getQueryTerms()); - if (temp != null) { - results.addAll(temp); + for (AbstractRequestableNode requestNode : requestNodes) { + Set avialability = container + .getAvailability(requestNode); + for (TimeAndSpace ast : avialability) { + if (ast.isTimeAgnostic()) { + List temp = timeAgnosticQuery(request + .getQueryTerms()); + if (temp != null) { + results.addAll(temp); + } + break; + } else { + results.add(ast.getTime()); } - break; - } else { - results.addAll(times); } } if (!request.isMaxQuery() || results.isEmpty()) { @@ -162,35 +172,6 @@ public abstract class AbstractDataCubeAdapter implements IDataCubeAdapter { return finalResponse; } - protected void getTimeQuery( - TimeQueryRequest originalRequest, - AbstractRequestableLevelNode req, - boolean latestOnly, - LinkedHashMap queries, - Map> cache, - Map> latestOnlyCache) - throws VizException { - List depends = req.getDependencies(); - if (depends.isEmpty()) { - // is source node - TimeQueryRequest myQ = req.getTimeQuery(originalRequest, - latestOnly, cache, latestOnlyCache); - if (myQ != null) { - queries.put(req, myQ); - } - } else { - for (Dependency dep : depends) { - // TODO: Optimize dTime/fTime to use bulk query mechanism, - // small case that is a not easy to get right with a bulk - // query - if (dep.timeOffset == 0 || !latestOnly) { - getTimeQuery(originalRequest, dep.node, latestOnly, - queries, cache, latestOnlyCache); - } - } - } - } - /* * (non-Javadoc) * @@ -232,94 +213,41 @@ public abstract class AbstractDataCubeAdapter implements IDataCubeAdapter { @Override public List getData(LayerProperty property, int timeOut) throws VizException { - List requests = evaluateRequestConstraints(property + List requests = evaluateRequestConstraints(property .getEntryQueryParameters(false)); - int mapSize = (int) (requests.size() * 1.25) + 1; - Map> cache = new HashMap>( - mapSize); - LinkedHashMap queries = new LinkedHashMap( - mapSize); - for (AbstractRequestableLevelNode req : requests) { - getDataQuery(req, property, timeOut, queries, cache); - } - DbQueryRequestSet reqSet = new DbQueryRequestSet(); - reqSet.setQueries(queries.values().toArray( - new DbQueryRequest[queries.size()])); - DbQueryResponseSet qSetResponse = (DbQueryResponseSet) ThriftClient - .sendRequest(reqSet); - DbQueryResponse[] qResponses = qSetResponse.getResults(); - int index = 0; - for (AbstractRequestableLevelNode node : queries.keySet()) { - // put results into cache - node.setDataQueryResults(qResponses[index++], cache); + Set availability = null; + if (property.getSelectedEntryTime() != null) { + availability = new HashSet(); + for (DataTime time : property.getSelectedEntryTime()) { + availability.add(new TimeAndSpace(time)); + } + } else { + availability = AvailabilityContainer.AGNOSTIC_SET; } // pull the actual results from the cache - List requesters = new ArrayList( - requests.size()); - for (AbstractRequestableLevelNode request : requests) { - requesters.addAll(request.getData(property, timeOut, cache)); + List requesters = new ArrayList(); + MetadataContainer container = createMetadataContainer(property + .getEntryQueryParameters(false)); + for (AbstractRequestableNode request : requests) { + container.prepareRequests(request, availability); + } + for (AbstractRequestableNode request : requests) { + requesters.addAll(container.getData(request, availability)); } return getData(property, requesters); } - protected void getDataQuery( - AbstractRequestableLevelNode req, - LayerProperty property, - int timeOut, - LinkedHashMap queries, - Map> cache) - throws VizException { - List depends = req.getDependencies(); - if (depends.isEmpty()) { - // is source node - DbQueryRequest myQ = req.getDataQuery(property, timeOut, cache); - if (myQ != null) { - addDataQuery(req, myQ, queries); - } - } else { - for (Dependency dep : depends) { - // TODO: Optimize dTime/fTime to use bulk query mechanism, - // small case that is a not easy to get right with a bulk - // query - if (dep.timeOffset == 0) { - getDataQuery(dep.node, property, timeOut, queries, cache); - } - } - } + protected MetadataContainer createMetadataContainer( + Map constraints) { + return new MetadataContainer(constraints, + createAvailabilityContainer(constraints)); } - private void addDataQuery(AbstractRequestableLevelNode req, - DbQueryRequest query, - LinkedHashMap queries) { - DbQueryRequest curQuery = queries.get(req); - if (curQuery == null) { - queries.put(req, query); - } else { - // merge - // assume same DB, fields, etc, should only be different - // time constraints since its the same node - RequestConstraint curDTs = curQuery.getConstraints() - .get("dataTime"); - RequestConstraint myDTs = query.getConstraints().get("dataTime"); - if (curDTs != null && myDTs != null) { - // only merge if both require dataTimes, otherwise one - // would be constrained when it needs everything, also - // assuming both to be in lists and needing to be merged - curDTs.setConstraintType(ConstraintType.IN); - Pattern split = Pattern.compile(","); - - String[] curVals = split.split(curDTs.getConstraintValue()); - String[] myVals = split.split(myDTs.getConstraintValue()); - HashSet dups = new HashSet(curVals.length - + myVals.length); - dups.addAll(Arrays.asList(curVals)); - dups.addAll(Arrays.asList(myVals)); - curDTs.setConstraintValueList(dups.toArray(new String[dups - .size()])); - } - } + protected AvailabilityContainer createAvailabilityContainer( + Map constraints) { + return new AvailabilityContainer(constraints); } /* @@ -374,7 +302,7 @@ public abstract class AbstractDataCubeAdapter implements IDataCubeAdapter { * @param constraints * @return */ - protected abstract List evaluateRequestConstraints( + protected abstract List evaluateRequestConstraints( Map constraints); /** diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractRequestableData.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractRequestableData.java index 56848715bc..43944d258d 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractRequestableData.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AbstractRequestableData.java @@ -25,11 +25,17 @@ import java.util.List; import javax.measure.unit.Unit; import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.geospatial.ISpatialObject; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; /** - * TODO Add Description + * AbstractRequestableData is the base metadata class for derived parameters. It + * represents a single data value for a given source/parameter/level/time/space + * combination. As well as representing the metadata it also provides a + * getDataValue method which should return a dataValue that can be used in + * derived parameters to calculate other parameters. * *
  * 
@@ -56,7 +62,9 @@ public abstract class AbstractRequestableData {
 
     protected Level level;
 
-    protected DataTime dataTime;
+    protected DataTime dataTime = TimeAndSpace.TIME_AGNOSTIC;
+
+    protected ISpatialObject space = TimeAndSpace.SPACE_AGNOSTIC;
 
     public AbstractRequestableData() {
 
@@ -69,6 +77,7 @@ public abstract class AbstractRequestableData {
         this.unit = that.unit;
         this.level = that.level;
         this.dataTime = that.dataTime;
+        this.space = that.space;
     }
 
     // Object can be a plugin specific argument that will be passed through the
@@ -153,6 +162,14 @@ public abstract class AbstractRequestableData {
         this.level = level;
     }
 
+    public ISpatialObject getSpace() {
+        return space;
+    }
+
+    public void setSpace(ISpatialObject space) {
+        this.space = space;
+    }
+
     /**
      * @return the dataTime
      */
@@ -168,6 +185,10 @@ public abstract class AbstractRequestableData {
         this.dataTime = dataTime;
     }
 
+    public TimeAndSpace getTimeAndSpace() {
+        return new TimeAndSpace(dataTime, space);
+    }
+
     public List getDependencies() {
         return Collections.emptyList();
     }
diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AliasRequestableData.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AliasRequestableData.java
index 8dcc8e6697..d6746510be 100644
--- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AliasRequestableData.java
+++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/AliasRequestableData.java
@@ -31,7 +31,9 @@ import com.raytheon.uf.common.datastorage.records.IDataRecord;
 import com.raytheon.uf.viz.core.exception.VizException;
 
 /**
- * TODO Add Description
+ * Represents a simple alias, where a parameter represents the same data as
+ * another parameter. This does automatic unit conversion if the source data is
+ * in a different unit than this object.
  * 
  * 
  * 
@@ -53,6 +55,7 @@ public class AliasRequestableData extends AbstractRequestableData {
     public AliasRequestableData(AbstractRequestableData sourceRecord) {
         this.sourceRecord = sourceRecord;
         this.dataTime = sourceRecord.getDataTime();
+        this.space = sourceRecord.space;
     }
 
     public Object getDataValue(Object arg) throws VizException {
diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/FloatRequestableData.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/FloatRequestableData.java
index 611e9e8e10..0ebd23edcf 100644
--- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/FloatRequestableData.java
+++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/data/FloatRequestableData.java
@@ -19,8 +19,10 @@
  **/
 package com.raytheon.uf.viz.derivparam.data;
 
+import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace;
+
 /**
- * TODO Add Description
+ * RequestableData object for a single constant float value.
  * 
  * 
  * 
@@ -41,6 +43,8 @@ public class FloatRequestableData extends AbstractRequestableData {
 
     public FloatRequestableData(Float value) {
         this.value = value;
+        this.dataTime = TimeAndSpace.TIME_AGNOSTIC;
+        this.space = TimeAndSpace.SPACE_AGNOSTIC;
     }
 
     public Float getDataValue() {
diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AbstractInventory.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AbstractInventory.java
index c5079e13d2..c399c04e02 100644
--- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AbstractInventory.java
+++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AbstractInventory.java
@@ -60,12 +60,11 @@ import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator;
 import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator.DerivParamUpdateListener;
 import com.raytheon.uf.viz.derivparam.library.IDerivParamField;
 import com.raytheon.uf.viz.derivparam.library.LevelType;
-import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
 import com.raytheon.uf.viz.derivparam.tree.AliasLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.CompositeAverageLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.DerivedLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.ModelRunLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.OrLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.StaticDataLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.TimeRangeLevelNode;
@@ -73,7 +72,10 @@ import com.raytheon.uf.viz.derivparam.tree.UnionLevelNode;
 
 /**
  * 
- * TODO Add Description
+ * The Inventory is responsible for managing what parameters can be derived. It
+ * maintains a dataTree which contains all the base parameter as well as any
+ * previously used derived parameters. It can dynamically calculate what
+ * parameters can be derived using the walk tree method.
  * 
  * 
  * 
@@ -310,7 +312,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                             request.add(result);
                         }
                     }
-                    AbstractDerivedLevelNode newNode = createDerivedNode(desc,
+                    AbstractDerivedDataNode newNode = createDerivedNode(desc,
                             method, lNode.getLevel(), request, sNode);
                     pNode.getChildNodes().put(lNode.getValue(), newNode);
                 }
@@ -568,7 +570,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
      * @throws InterruptedException
      *             thrown if the thread was interupted during execution.
      */
-    protected synchronized List walkTree(
+    protected synchronized List walkTree(
             Class> clazz,
             Collection sourcesToProcess,
             Collection paramsToProcess,
@@ -604,7 +606,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                 }
             }
         }
-        List results = new ArrayList();
+        List results = new ArrayList();
         Set nodata = new HashSet(derParLibrary.size());
         Deque stack = new ArrayDeque();
         Iterator sit = sourcesToProcess.iterator();
@@ -630,7 +632,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                     Iterator lit = levelsToProcess.iterator();
                     while (lit.hasNext()) {
                         Level level = lit.next();
-                        AbstractRequestableLevelNode result = null;
+                        AbstractRequestableNode result = null;
                         if (derive) {
                             try {
                                 result = resolveNode(node, param, level, stack,
@@ -641,7 +643,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                             }
                         } else {
                             ParameterNode pNode = node.getChildNode(param);
-                            result = (AbstractRequestableLevelNode) (pNode == null ? null
+                            result = (AbstractRequestableNode) (pNode == null ? null
                                     : pNode.getChildNode(Long.toString(level
                                             .getId())));
                         }
@@ -652,10 +654,10 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                         if (!includeConstant) {
                             if (result.isConstant()) {
                                 continue;
-                            } else if (result instanceof AbstractDerivedLevelNode) {
+                            } else if (result instanceof AbstractDerivedDataNode) {
                                 // if we don't want constant fields I assume we
                                 // also don't want internal fields
-                                if (((AbstractDerivedLevelNode) result)
+                                if (((AbstractDerivedDataNode) result)
                                         .getDesc().isInternal()) {
                                     continue;
                                 }
@@ -683,10 +685,10 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                         } else {
                             if (sourceAliases.containsKey(source)) {
                                 boolean supplement = false;
-                                List choices = new ArrayList();
+                                List choices = new ArrayList();
                                 for (String aliasModel : sourceAliases
                                         .get(source)) {
-                                    AbstractRequestableLevelNode alias = null;
+                                    AbstractRequestableNode alias = null;
                                     if (derive) {
                                         try {
                                             alias = resolveNode(
@@ -700,7 +702,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                                     } else {
                                         ParameterNode pNode = node
                                                 .getChildNode(param);
-                                        alias = (AbstractRequestableLevelNode) (pNode == null ? null
+                                        alias = (AbstractRequestableNode) (pNode == null ? null
                                                 : pNode.getChildNode(Long
                                                         .toString(level.getId())));
                                     }
@@ -762,7 +764,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
      * @return
      * @throws VizCommunicationException
      */
-    protected synchronized AbstractRequestableLevelNode resolveNode(
+    protected synchronized AbstractRequestableNode resolveNode(
             SourceNode sourceNode, String param, Level level,
             Deque stack, Set nodata)
             throws VizCommunicationException {
@@ -774,7 +776,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                     && !stack.isEmpty()) {
                 stack.getFirst().autoAverage = true;
             }
-            return (AbstractRequestableLevelNode) lNode;
+            return (AbstractRequestableNode) lNode;
         }
         DerivParamDesc desc = derParLibrary.get(param);
         if (desc == null) {
@@ -799,7 +801,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
         }
         // Any time this function returns after this point it must pop se, or
         // else!
-        AbstractDerivedLevelNode autoAveragedNode = null;
+        AbstractDerivedDataNode autoAveragedNode = null;
         stack.push(se);
         List methods = desc.getMethods();
         if (methods != null) {
@@ -871,7 +873,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                             || ((method.getFrameworkMethod() == FrameworkMethod.UNION || method
                                     .getFrameworkMethod() == FrameworkMethod.OR) && request
                                     .size() > 0)) {
-                        AbstractDerivedLevelNode newNode = createDerivedNode(
+                        AbstractDerivedDataNode newNode = createDerivedNode(
                                 desc, method, level, request, sourceNode);
                         if (newNode != null) {
                             pNode = sourceNode.getChildNode(param);
@@ -910,10 +912,10 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                 throw new VizCommunicationException(e);
             }
 
-            List nodes = new ArrayList();
+            List nodes = new ArrayList();
             int endCount = 0;
-            AbstractRequestableLevelNode target = resolveNode(sourceNode,
-                    param, upperLevel, stack, nodata);
+            AbstractRequestableNode target = resolveNode(sourceNode, param,
+                    upperLevel, stack, nodata);
             if (target != null) {
                 endCount += 1;
                 nodes.add(target);
@@ -1120,12 +1122,12 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
             DerivParamField field, Deque stack,
             Set nodata) throws VizCommunicationException;
 
-    protected abstract AbstractDerivedLevelNode getImportNode(
+    protected abstract AbstractDerivedDataNode getImportNode(
             AbstractRequestableData nodeToImport, SourceNode destSourceNode,
             DerivParamDesc desc, DerivParamMethod method, Level level);
 
-    protected abstract AbstractDerivedLevelNode getImportNode(
-            AbstractRequestableLevelNode nodeToImport,
+    protected abstract AbstractDerivedDataNode getImportNode(
+            AbstractRequestableNode nodeToImport,
             String nodeToImportSourceName, SourceNode destSourceNode,
             DerivParamDesc desc, DerivParamMethod method, Level level);
 
@@ -1142,7 +1144,7 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
      * @param source
      * @return
      */
-    protected AbstractDerivedLevelNode createDerivedNode(DerivParamDesc desc,
+    protected AbstractDerivedDataNode createDerivedNode(DerivParamDesc desc,
             DerivParamMethod method, Level level, List fields,
             SourceNode source) {
         switch (method.getMethodType()) {
@@ -1158,9 +1160,9 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                     node.putStaticField(method.getFields().get(k),
                             (AbstractRequestableData) obj);
                 }
-                if (obj instanceof AbstractRequestableLevelNode) {
+                if (obj instanceof AbstractRequestableNode) {
                     node.putField((DerivParamField) method.getFields().get(k),
-                            (AbstractRequestableLevelNode) obj);
+                            (AbstractRequestableNode) obj);
                 }
             }
             return node;
@@ -1177,10 +1179,9 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                     data.setUnit(desc.getUnit());
                     return new StaticDataLevelNode(level, desc, method, data,
                             source.getValue());
-                } else if (field instanceof AbstractRequestableLevelNode) {
-                    return new AliasLevelNode(
-                            (AbstractRequestableLevelNode) field, desc, method,
-                            source.getValue(), level);
+                } else if (field instanceof AbstractRequestableNode) {
+                    return new AliasLevelNode((AbstractRequestableNode) field,
+                            desc, method, source.getValue(), level);
                 }
                 return null;
             }
@@ -1201,21 +1202,26 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                 if (field instanceof AbstractRequestableData) {
                     return getImportNode((AbstractRequestableData) field,
                             source, desc, method, level);
-                } else if (field instanceof AbstractRequestableLevelNode) {
-                    return getImportNode((AbstractRequestableLevelNode) field,
+                } else if (field instanceof AbstractRequestableNode) {
+                    return getImportNode((AbstractRequestableNode) field,
                             importSource, source, desc, method, level);
                 }
                 return null;
             }
             case MODELRUN:
-                return new ModelRunLevelNode(
-                        (AbstractRequestableLevelNode) fields.get(0), desc,
-                        method, source.getValue(), level);
+                if (source.getDt() <= 0) {
+                    return null;
+                }
+                AbstractRequestableNode sourceLevelNode = (AbstractRequestableNode) fields
+                        .get(0);
+                return new TimeRangeLevelNode(sourceLevelNode, desc, method,
+                        source.getValue(), (Integer) null, 0, source.getDt(),
+                        level);
             case TIMERANGE:
                 if (source.getDt() <= 0) {
                     return null;
                 }
-                AbstractRequestableLevelNode sourceNode = (AbstractRequestableLevelNode) fields
+                AbstractRequestableNode sourceNode = (AbstractRequestableNode) fields
                         .get(0);
                 Float startTime = ((FloatRequestableData) fields.get(1))
                         .getDataValue();
@@ -1226,18 +1232,18 @@ public abstract class AbstractInventory implements DerivParamUpdateListener {
                         endTime.intValue(), source.getDt(), level);
             case SUPPLEMENT:
             case OR:
-                List choices = new ArrayList(
+                List choices = new ArrayList(
                         fields.size());
                 for (Object obj : fields) {
-                    choices.add((AbstractRequestableLevelNode) obj);
+                    choices.add((AbstractRequestableNode) obj);
                 }
                 return new OrLevelNode(level, desc, method, source.getValue(),
                         choices);
             case UNION:
-                List nodes = new ArrayList(
+                List nodes = new ArrayList(
                         fields.size());
                 for (Object obj : fields) {
-                    nodes.add((AbstractRequestableLevelNode) obj);
+                    nodes.add((AbstractRequestableNode) obj);
                 }
                 return new UnionLevelNode(level, desc, method,
                         source.getValue(), nodes);
diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AvailabilityContainer.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AvailabilityContainer.java
new file mode 100644
index 0000000000..96956a5a5a
--- /dev/null
+++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/AvailabilityContainer.java
@@ -0,0 +1,216 @@
+/**
+ * This software was developed and / or modified by Raytheon Company,
+ * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
+ * 
+ * U.S. EXPORT CONTROLLED TECHNICAL DATA
+ * This software product contains export-restricted data whose
+ * export/transfer/disclosure is restricted by U.S. law. Dissemination
+ * to non-U.S. persons whether in the United States or abroad requires
+ * an export license or other authorization.
+ * 
+ * Contractor Name:        Raytheon Company
+ * Contractor Address:     6825 Pine Street, Suite 340
+ *                         Mail Stop B8
+ *                         Omaha, NE 68106
+ *                         402.291.0100
+ * 
+ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
+ * further licensing information.
+ **/
+package com.raytheon.uf.viz.derivparam.inv;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
+import com.raytheon.uf.common.dataquery.requests.DbQueryRequestSet;
+import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
+import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
+import com.raytheon.uf.common.dataquery.responses.DbQueryResponseSet;
+import com.raytheon.uf.viz.core.exception.VizException;
+import com.raytheon.uf.viz.core.requests.ThriftClient;
+import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode.Dependency;
+
+/**
+ * Object for determining the vailability(in time and space) when a
+ * AbstractRequestableNode can provide data. Specifically the node recursively
+ * determines all dependencies and bulks requests for performance reason,
+ * maintaining a cache of time to avoid any redundant requests.
+ * 
+ * 
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Apr 11, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class AvailabilityContainer { + + public static final Set AGNOSTIC_SET = Collections + .unmodifiableSet(new HashSet(Arrays + .asList(new TimeAndSpace()))); + + protected final Map originalConstraints; + + protected Map requestCache = new HashMap(); + + protected Map> availabilityCache = new HashMap>(); + + public AvailabilityContainer( + Map originalConstraints) { + this.originalConstraints = originalConstraints; + } + + /** + * Get the availability in Time and space for a given node. + * + * @param node + * @return + * @throws VizException + */ + public synchronized Set getAvailability( + AbstractRequestableNode node) throws VizException { + return getAvailability(node, true); + } + + /** + * recursively determine avaialbilty for a node and its dependencies, + * doRequests should only be true for the first call, after that all + * requests will have already been handled. + * + * @param node + * @param doRequests + * @return + * @throws VizException + */ + private Set getAvailability(AbstractRequestableNode node, + boolean doRequests) throws VizException { + if (availabilityCache.containsKey(node)) { + return availabilityCache.get(node); + } + if (doRequests) { + prepareRequests(node); + processRequests(); + } + + if (node instanceof AbstractBaseDataNode) { + + if (availabilityCache.containsKey(node)) { + return availabilityCache.get(node); + } else { + throw new IllegalStateException( + "DataNode should have been handled in processRequests"); + } + } else if (node instanceof AbstractDerivedDataNode) { + AbstractDerivedDataNode dataNode = (AbstractDerivedDataNode) node; + for (Dependency d : dataNode.getDependencies()) { + getAvailability(d.node, false); + } + Set availability = dataNode + .getAvailability(availabilityCache); + availabilityCache.put(node, availability); + return availability; + } else { + throw new IllegalStateException( + "Cannot determine availability of unknown Unknown node type : " + + node.getClass().getSimpleName()); + } + } + + /** + * This will prepare the container to request availability for the given + * node. If this node is a derived node it will evaluate what data is needed + * so that when getData is called it can bulk request all data. If + * availability is needed for multiple nodes than calling this multiple + * times before ever calling getAvailability will maximize the efficiency of + * bulk requests. + * + * @param node + * @param availability + * @throws VizException + */ + public synchronized void prepareRequests(AbstractRequestableNode node) { + if (availabilityCache.containsKey(node) + || requestCache.containsKey(node)) { + return; + } + if (node instanceof AbstractBaseDataNode) { + AbstractBaseDataNode dataNode = (AbstractBaseDataNode) node; + requestCache.put(dataNode, + dataNode.getAvailabilityRequest(originalConstraints)); + } else if (node instanceof AbstractDerivedDataNode) { + AbstractDerivedDataNode dataNode = (AbstractDerivedDataNode) node; + for (Dependency d : dataNode.getDependencies()) { + prepareRequests(d.node); + } + } + + } + + /** + * process all requests, in bulk if possible. + * + * @throws VizException + */ + protected void processRequests() throws VizException { + List requests = getAvailabilityRequests(); + DbQueryRequestSet requestSet = new DbQueryRequestSet(); + requestSet.setQueries(requests.toArray(new DbQueryRequest[0])); + DbQueryResponseSet responseSet = (DbQueryResponseSet) ThriftClient + .sendRequest(requestSet); + DbQueryResponse[] responses = responseSet.getResults(); + Map responseMap = new HashMap( + (int) (responses.length / 0.75) + 1, 0.75f); + for (int i = 0; i < responses.length; i++) { + responseMap.put(requests.get(i), responses[i]); + } + setAvailabilityResponses(responseMap); + } + + public synchronized List getAvailabilityRequests() { + List requests = new ArrayList( + requestCache.size()); + for (Entry entry : requestCache + .entrySet()) { + if (availabilityCache.containsKey(entry.getKey())) { + continue; + } else if (entry.getValue() != null) { + requests.add(entry.getValue()); + } + } + return requests; + } + + public synchronized void setAvailabilityResponses( + Map responses) throws VizException { + for (Entry entry : requestCache + .entrySet()) { + DbQueryResponse response = null; + if (availabilityCache.containsKey(entry.getKey())) { + continue; + } else if (entry.getValue() != null) { + response = responses.get(entry.getValue()); + } + availabilityCache.put(entry.getKey(), entry.getKey() + .getAvailability(originalConstraints, response)); + } + } + +} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/MetadataContainer.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/MetadataContainer.java new file mode 100644 index 0000000000..b2833f77a0 --- /dev/null +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/MetadataContainer.java @@ -0,0 +1,234 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.derivparam.inv; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; +import com.raytheon.uf.common.dataquery.requests.DbQueryRequestSet; +import com.raytheon.uf.common.dataquery.requests.RequestConstraint; +import com.raytheon.uf.common.dataquery.responses.DbQueryResponseSet; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.core.requests.ThriftClient; +import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode.Dependency; + +/** + * Class is responsible for pulling AbstractRequestableData out of + * AbstractRequestableNode objects. This class manages caching and bulk + * requesting to ensure that derived parameter requests are fully optimized. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Apr 11, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class MetadataContainer { + + protected final Map originalConstraints; + + protected final AvailabilityContainer availabilityContainer; + + protected Map> availCache = new HashMap>(); + + protected Map> dataCache = new HashMap>(); + + public MetadataContainer( + Map originalConstraints, + AvailabilityContainer availabilityContainer) { + this.originalConstraints = originalConstraints; + this.availabilityContainer = availabilityContainer; + } + + /** + * This will prepare the container to request data for the given node. If + * this node is a derived node it will evaluate what data is needed so that + * when getData is called it can bulk request all data. If data is needed + * for multiple nodes than calling this multiple times before ever calling + * getData will maximize the efficiency of bulk requests. + * + * @param node + * @param availability + * @throws VizException + */ + public synchronized void prepareRequests(AbstractRequestableNode node, + Set availability) throws VizException { + generateAvailability(node, availability); + } + + /** + * get the requestable data for a node with the given availability. For + * non-derived nodes this is simple, for derived nodes this container will + * attempt to fully optimize and cache all data requests. + * + * @param node + * @param availability + * @return + * @throws VizException + */ + public synchronized Set getData( + AbstractRequestableNode node, Set availability) + throws VizException { + return getData(node, availability, true); + } + + /** + * recursively called to get data, but don't reprocess availability at every + * level, only for the first in the chain of recursive calls. + * + * @param node + * @param availability + * @param doRequests + * @return + * @throws VizException + */ + private Set getData(AbstractRequestableNode node, + Set availability, boolean doRequests) + throws VizException { + if (dataCache.containsKey(node)) { + return dataCache.get(node); + } else if (availability == null || availability.isEmpty()) { + Set data = Collections.emptySet(); + dataCache.put(node, data); + return data; + } + if (doRequests) { + generateAvailability(node, availability); + processRequests(); + } + if (node instanceof AbstractBaseDataNode) { + if (dataCache.containsKey(node)) { + return dataCache.get(node); + } else { + throw new IllegalStateException( + "DataNode should have been handled in processRequests"); + } + } else if (node instanceof AbstractDerivedDataNode) { + AbstractDerivedDataNode dataNode = (AbstractDerivedDataNode) node; + for (Dependency d : dataNode.getDependencies()) { + getData(d.node, availCache.get(d.node), false); + } + Set data = dataNode.getData(availability, + dataCache); + dataCache.put(node, data); + return data; + } else { + throw new IllegalStateException( + "Cannot determine availability of unknown Unknown node type : " + + node.getClass().getSimpleName()); + } + } + + /** + * Walk through all dependencies for a node and calculate the TimeAndSpace + * where data is needed to get data for the requested TimeAndSpace. + * + * @param node + * @param availability + * @throws VizException + */ + private void generateAvailability(AbstractRequestableNode node, + Set availability) throws VizException { + Set c = availCache.get(node); + if (c != null) { + if (c.containsAll(availability)) { + return; + } + c.addAll(availability); + } else { + c = new HashSet(availability); + availCache.put(node, c); + } + if (node instanceof AbstractDerivedDataNode) { + AbstractDerivedDataNode derivedNode = (AbstractDerivedDataNode) node; + Map> avail = derivedNode + .getDataDependency(new HashSet(availability), + availabilityContainer); + + for (Entry> entry : avail + .entrySet()) { + AbstractRequestableNode n = entry.getKey(); + Set a = entry.getValue(); + generateAvailability(n, a); + } + } + } + + /** + * use the availCache to determine what nodes need data and attempt to bulk + * all requests. + * + * @throws VizException + */ + protected void processRequests() throws VizException { + List nodes = new ArrayList(); + List requests = new ArrayList(); + for (AbstractRequestableNode node : availCache.keySet()) { + if (dataCache.containsKey(node)) { + continue; + } + if (node instanceof AbstractBaseDataNode) { + AbstractBaseDataNode dataNode = (AbstractBaseDataNode) node; + DbQueryRequest request = dataNode.getDataRequest( + originalConstraints, availCache.get(node)); + if (request != null) { + nodes.add(dataNode); + requests.add(request); + } else { + dataCache.put( + node, + dataNode.getData(originalConstraints, + availCache.get(node), null)); + } + } + } + if (requests.isEmpty()) { + return; + } + DbQueryRequestSet requestSet = new DbQueryRequestSet(); + requestSet.setQueries(requests.toArray(new DbQueryRequest[0])); + DbQueryResponseSet responseSet = (DbQueryResponseSet) ThriftClient + .sendRequest(requestSet); + for (int i = 0; i < nodes.size(); i++) { + AbstractBaseDataNode node = nodes.get(i); + dataCache.put(node, node.getData(originalConstraints, + availCache.get(node), responseSet.getResults()[i])); + } + } +} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/TimeAndSpace.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/TimeAndSpace.java new file mode 100644 index 0000000000..746b7528fc --- /dev/null +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/TimeAndSpace.java @@ -0,0 +1,186 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.derivparam.inv; + +import org.opengis.referencing.crs.CoordinateReferenceSystem; + +import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.time.DataTime; +import com.vividsolutions.jts.geom.Geometry; + +/** + * Represents a time and space(location) where data can exist. This is used in + * derived parameters for data types to report when and where data can be + * loaded. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Apr 11, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class TimeAndSpace { + + /** + * A constant to represent the time for data that does not change over time + * or that is available for all times, an example would be topography which + * generally does not change on a day to day basis. + */ + public static final DataTime TIME_AGNOSTIC = new DataTime() { + + private static final long serialVersionUID = 1L; + + @Override + public boolean equals(Object obj) { + return this == obj; + } + + @Override + public String toString() { + return "TIME_AGNOSTIC"; + } + + }; + + /** + * A constant to represent the space for data that does not change over + * space or that is available for all spaces, an example would be radar + * elevation angle for a grid coverage, this can be calculated for any + * gridcoverage. + */ + public static final ISpatialObject SPACE_AGNOSTIC = new ISpatialObject() { + + private static final long serialVersionUID = 1L; + + @Override + public Integer getNy() { + return null; + } + + @Override + public Integer getNx() { + return null; + } + + @Override + public Geometry getGeometry() { + return null; + } + + @Override + public CoordinateReferenceSystem getCrs() { + return null; + } + + @Override + public String toString() { + return "SPACE_AGNOSTIC"; + } + + }; + + private final DataTime time; + + private final ISpatialObject space; + + public TimeAndSpace() { + this(TIME_AGNOSTIC, SPACE_AGNOSTIC); + } + + public TimeAndSpace(DataTime time) { + this(time, SPACE_AGNOSTIC); + + } + + public TimeAndSpace(ISpatialObject space) { + this(TIME_AGNOSTIC, space); + } + + public TimeAndSpace(DataTime time, ISpatialObject space) { + this.time = time; + this.space = space; + } + + public DataTime getTime() { + return time; + } + + public ISpatialObject getSpace() { + return space; + } + + public boolean isTimeAgnostic() { + return this.time == TIME_AGNOSTIC; + } + + public boolean isSpaceAgnostic() { + return space == SPACE_AGNOSTIC; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((space == null) ? 0 : space.hashCode()); + result = prime * result + ((time == null) ? 0 : time.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + TimeAndSpace other = (TimeAndSpace) obj; + if (space == null) { + if (other.space != null) + return false; + } else if (!space.equals(other.space)) + return false; + if (time == null) { + if (other.time != null) + return false; + } else if (!time.equals(other.time)) + return false; + return true; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("AvailSpT: Time: "); + sb.append(time); + sb.append(", Space: "); + sb.append(space); + return sb.toString(); + } + +} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/TimeAndSpaceMatcher.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/TimeAndSpaceMatcher.java new file mode 100644 index 0000000000..c56e252c96 --- /dev/null +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/inv/TimeAndSpaceMatcher.java @@ -0,0 +1,348 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.derivparam.inv; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.time.DataTime; + +/** + * The primary function of this class is two find the intersection between two + * collections of TimeAndSpace objects. This will compare all the TimeAndSpace + * objects in each collection and find "matches". The simplest matches are when + * both time and space objects are equal. More complex matches can be created + * when times are equal but one is time agnostic or spaces are equal and one is + * space agnostic. Finally if for one of the Collections contains a time and + * space agnostic TimeAndSpace than it will match everything. + * + * Time matching is a little more complex than space because you can configure + * ignoreRange and validMatch so that times can be considered matching even if + * they aren't identical, as long as they are referencing a similar time, for + * more information see the setters for those flags. + * + * When determining matches this will choose the most specific match. For + * example if a TimeAndSpace object can match an object that matches space but + * only matches validTime or it can match an object that matches space but is + * time agnostic, then it will choose the valid time match since that is more + * specific than the agnostic. This order is defined by the natural order of the + * MatchType enum. + * + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 8, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class TimeAndSpaceMatcher { + + private boolean ignoreRange = false; + + private boolean matchValid = false; + + /** + * When ignore range is true then times with different ranges are considered + * matching if they are the same in all other ways, when false times are + * considered nonmatching if the range is not identical. + * + * @param ignoreRange + */ + public void setIgnoreRange(boolean ignoreRange) { + this.ignoreRange = ignoreRange; + } + + /** + * When match valid is true then dataTimes are compared based off valid + * time, when it is false the refTime and forecast time are considered + * sperately and both must match to create a match. Even when matchValid is + * true, if there is a time where forecast and refTime amtch it will be + * prefered to a time where only validTime matches + * + * @param matchValid + */ + public void setMatchValid(boolean matchValid) { + this.matchValid = matchValid; + } + + /** + * Perform the match operation. The result is returned as a map, where the + * key is the intersected TimeAndSpace and the values are a MatchResult that + * contains the SpaceAndTime needed from each collection to represent that + * time. + * + * @param times1 + * @param times2 + * @return + */ + public Map match( + Collection times1, Collection times2) { + Map result = new HashMap(); + for (TimeAndSpace t1 : times1) { + for (TimeAndSpace t2 : times2) { + MatchResult res = createMatchResult(t1, t2); + if (res != null) { + MatchResult prev = result.get(res.getMerge()); + if (prev == null + || prev.getMatchValue().compareTo( + res.getMatchValue()) > 0) { + result.put(res.getMerge(), res); + } + } + } + } + return result; + } + + /** + * Given two TimeAndSpace objects attempts to determine what they have in + * common, if anything and return a MatchResult or null if there is no + * match. + * + * @param t1 + * @param t2 + * @return + */ + private MatchResult createMatchResult(TimeAndSpace t1, TimeAndSpace t2) { + MatchType matchValue; + DataTime time = null; + ISpatialObject space = null; + // first determine what space a match between these two times would have + boolean spaceAgn = false; + if (t1.getSpace().equals(t2.getSpace())) { + // If they match that is best + space = t1.getSpace(); + } else if (t1.isSpaceAgnostic()) { + // space agnostic will match something with space. + spaceAgn = true; + space = t2.getSpace(); + } else if (t2.isSpaceAgnostic()) { + // again one is agnostic + spaceAgn = true; + space = t1.getSpace(); + } else { + // no spatial match, means no match at all. + return null; + } + + // Next determine how well the times match + if (t1.isTimeAgnostic()) { + // When one is agnostic it will match anything. + time = t2.getTime(); + matchValue = spaceAgn ? MatchType.AGNOSTIC_MATCH + : MatchType.SPACE_MATCH; + } else if (t2.isTimeAgnostic()) { + // again one is agnostic + time = t1.getTime(); + matchValue = spaceAgn ? MatchType.AGNOSTIC_MATCH + : MatchType.SPACE_MATCH; + } else if (t1.getTime().equals(t2.getTime())) { + // A perfect time match is always best. + time = t1.getTime(); + matchValue = spaceAgn ? MatchType.TIME_MATCH : MatchType.BOTH_MATCH; + } else if (ignoreRange + && t1.getTime().getMatchRef() == t2.getTime().getMatchRef() + && t1.getTime().getMatchFcst() == t2.getTime().getMatchFcst()) { + // If the ignoreRanfe flag is set then it is still considered a + // match even if the ranges are different. + time = new DataTime(t1.getTime().getRefTime(), t1.getTime() + .getFcstTime()); + matchValue = spaceAgn ? MatchType.TIME_IGNORE_RANGE + : MatchType.BOTH_IGNORE_RANGE; + } else if (matchValid + && t1.getTime().getMatchValid() == t2.getTime().getMatchValid()) { + // finally last valid allows us to mix different + // refTime/forecastTimes as long as valid matches. + if (t1.getTime().getMatchRef() > t2.getTime().getMatchRef()) { + time = new DataTime(t1.getTime().getRefTime(), t1.getTime() + .getFcstTime()); + } else { + time = new DataTime(t2.getTime().getRefTime(), t2.getTime() + .getFcstTime()); + } + matchValue = spaceAgn ? MatchType.TIME_VALID : MatchType.BOTH_VALID; + } else { + return null; + } + return new MatchResult(t1, t2, new TimeAndSpace(time, space), + matchValue); + } + + /** + * + * Class to contain the result of a match operation for 2 matching + * TimeAndSpace objects + * + *
+     * 
+     * SOFTWARE HISTORY
+     * 
+     * Date         Ticket#    Engineer    Description
+     * ------------ ---------- ----------- --------------------------
+     * Sep 27, 2012            bsteffen     Initial creation
+     * 
+     * 
+ * + * @author bsteffen + * @version 1.0 + */ + public static class MatchResult { + + /** + * The TimeAndSpace from the first collection that matches + */ + private final TimeAndSpace t1; + + /** + * The TimeAndSpace from the second collection that matches + */ + private final TimeAndSpace t2; + + /** + * The TimeAndSpace from the first collection that matches + */ + private final TimeAndSpace merge; + + /** + * How good of a match is this. + */ + private final MatchType matchValue; + + public MatchResult(TimeAndSpace t1, TimeAndSpace t2, + TimeAndSpace merge, MatchType matchValue) { + this.t1 = t1; + this.t2 = t2; + this.merge = merge; + this.matchValue = matchValue; + } + + public TimeAndSpace get1() { + return t1; + } + + public TimeAndSpace get2() { + return t2; + } + + public TimeAndSpace getMerge() { + return merge; + } + + public MatchType getMatchValue() { + return matchValue; + } + + } + + /** + * + * An enum which represents the quality of the match, The best matches are + * when both Time and Space objects are matches, but there are other + * matches, usually involving either Time or Space agnostic that are not as + * ideal but are suitable. + * + *
+     * 
+     * SOFTWARE HISTORY
+     * 
+     * Date         Ticket#    Engineer    Description
+     * ------------ ---------- ----------- --------------------------
+     * Sep 27, 2012            bsteffen     Initial creation
+     * 
+     * 
+ * + * @author bsteffen + * @version 1.0 + */ + public static enum MatchType { + + // Time and space match perfectly + BOTH_MATCH, + + // Space matches perfectly but time only matches if you ignore range + BOTH_IGNORE_RANGE, + + // Space matches perfectly but time only matches valid time + BOTH_VALID, + + // one is space agnostic and time matches + TIME_MATCH, + + // one is space agnostic but time only matches if you ignore range + TIME_IGNORE_RANGE, + + // one is space agnostic but time only matches valid time + TIME_VALID, + + // space matches perfectly and one is time agnostic + SPACE_MATCH, + + // one is both time and space agnostic so they match even though + // they have nothing in common + AGNOSTIC_MATCH; + + } + + /** + * Given the result of a match this will pull out the unique SpaceAndTime + * objects that matched from the second Collection passed to match. + * + * @param matchResults + * @return + */ + public static Set getAll2( + Map matchResults) { + Set result = new HashSet( + matchResults.size()); + for (MatchResult mr : matchResults.values()) { + result.add(mr.get2()); + } + return result; + } + + /** + * Given the result of a match this will pull out the unique SpaceAndTime + * objects that matched from the first Collection passed to match. + * + * @param matchResults + * @return + */ + public static Set getAll1( + Map matchResults) { + Set result = new HashSet( + matchResults.size()); + for (MatchResult mr : matchResults.values()) { + result.add(mr.get1()); + } + return result; + } +} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/library/ValidLevelGenerator.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/library/ValidLevelGenerator.java index 2e7888f7a6..9a394f5b83 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/library/ValidLevelGenerator.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/library/ValidLevelGenerator.java @@ -33,6 +33,9 @@ import com.raytheon.uf.common.dataplugin.level.CompareType; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.dataplugin.level.MasterLevel; +import com.raytheon.uf.common.dataplugin.level.mapping.LevelMapper; +import com.raytheon.uf.common.util.mapping.Mapper; +import com.raytheon.uf.common.util.mapping.MultipleMappingException; import com.raytheon.uf.viz.core.exception.VizCommunicationException; import com.raytheon.uf.viz.core.level.LevelMapping; import com.raytheon.uf.viz.core.level.LevelMappingFactory; @@ -62,6 +65,8 @@ public class ValidLevelGenerator { private LevelFactory lf; + private LevelMapper lm; + private Map> masterLevels; private Set validLevels; @@ -71,6 +76,7 @@ public class ValidLevelGenerator { public ValidLevelGenerator() { lmf = LevelMappingFactory.getInstance(); lf = LevelFactory.getInstance(); + lm = LevelMapper.getInstance(); } public Set generateLevels(String validLevelsString) @@ -78,7 +84,6 @@ public class ValidLevelGenerator { masterLevels = new HashMap>(); validLevels = new HashSet(); masterLevelsHandled = new HashSet(); - if (validLevelsString != null && validLevelsString.length() > 0) { String[] levelTokenArray = validLevelsString.split(","); List tokensToProcess = new ArrayList( @@ -291,7 +296,13 @@ public class ValidLevelGenerator { } case MasterLevel: { MasterLevel ml = lf.getMasterLevel(token); - + if (ml == null) { + try { + ml = lm.lookupMasterLevel(token, Mapper.DEPRECATED); + } catch (MultipleMappingException e) { + ml = lf.getMasterLevel(e.getArbitraryMapping()); + } + } if (negate) { for (Entry> entry : masterLevels .entrySet()) { @@ -340,6 +351,13 @@ public class ValidLevelGenerator { } else { // plane was not a group, see if it is a master level MasterLevel ml = lf.getMasterLevel(token); + if (ml == null) { + try { + ml = lm.lookupMasterLevel(token, Mapper.DEPRECATED); + } catch (MultipleMappingException e) { + ml = lf.getMasterLevel(e.getArbitraryMapping()); + } + } if (ml != null) { rval = Type.MasterLevel; } else { diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractAliasLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractAliasLevelNode.java index 6ba0fd2526..153634379e 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractAliasLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractAliasLevelNode.java @@ -20,15 +20,15 @@ package com.raytheon.uf.viz.derivparam.tree; import java.util.Arrays; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -50,16 +50,16 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; * @author bsteffen * @version 1.0 */ -public abstract class AbstractAliasLevelNode extends AbstractDerivedLevelNode { +public abstract class AbstractAliasLevelNode extends AbstractDerivedDataNode { - protected AbstractRequestableLevelNode sourceNode; + protected AbstractRequestableNode sourceNode; public AbstractAliasLevelNode(AbstractAliasLevelNode that) { super(that); this.sourceNode = that.sourceNode; } - public AbstractAliasLevelNode(AbstractRequestableLevelNode sourceNode, + public AbstractAliasLevelNode(AbstractRequestableNode sourceNode, DerivParamDesc desc, DerivParamMethod method, String modelName, Level level) { super(sourceNode, desc, method, modelName); @@ -67,32 +67,6 @@ public abstract class AbstractAliasLevelNode extends AbstractDerivedLevelNode { setLevel(level); } - @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - return sourceNode.timeQuery(originalRequest, latestOnly, cache, - latestOnlyCache); - } - - @Override - public boolean isTimeAgnostic() { - return sourceNode.isTimeAgnostic(); - } - - @Override - public Map getRequestConstraintMap() { - // TODO Auto-generated method stub - return sourceNode.getRequestConstraintMap(); - } - - @Override - public boolean hasRequestConstraints() { - return sourceNode.hasRequestConstraints(); - } - @Override public List getDependencies() { return Arrays.asList(new Dependency(sourceNode, 0)); @@ -134,4 +108,19 @@ public abstract class AbstractAliasLevelNode extends AbstractDerivedLevelNode { return true; } + @Override + public Set getAvailability( + Map> availability) + throws VizException { + return availability.get(sourceNode); + } + + @Override + public Map> getDataDependency( + Set times, AvailabilityContainer container) { + Map> result = new HashMap>(); + result.put(sourceNode, times); + return result; + } + } diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractBaseDataNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractBaseDataNode.java new file mode 100644 index 0000000000..38e6a2faa6 --- /dev/null +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractBaseDataNode.java @@ -0,0 +1,131 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.derivparam.tree; + +import java.util.Map; +import java.util.Set; + +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.derivparam.tree.LevelNode; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; + +/** + * TODO Add Description + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 10, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public abstract class AbstractBaseDataNode extends AbstractRequestableNode { + + public AbstractBaseDataNode() { + super(); + } + + public AbstractBaseDataNode(Level level) { + super(level); + } + + public AbstractBaseDataNode(LevelNode that) { + super(that); + } + + /** + * Optional method to provide a request to the AvailabilityContainer so that + * it can bulk all requests to edex to save time. The result of the request + * will be passed to getAvailability. If the return value is null then the + * response passed to getAvailability will be null also. + * + * @param originalConstraints + * the original constraints passed to the data cube container + * + * @return + */ + public abstract DbQueryRequest getAvailabilityRequest( + Map originalConstraints); + + /** + * Optional method to provide a request to the DataContainer so that it can + * bulk all requests to edex to save time. The result of the request will be + * passed to getData. If the return value is null then the response passed + * to getData will be null also. + * + * + * @param originalConstraints + * the original constraints passed to the data cube container + * @param availability + * the TimeAndSpace objects where data is being requested + * @return + */ + public abstract DbQueryRequest getDataRequest( + Map originalConstraints, + Set availability); + + /** + * Determine where and when data is available for this node. + * + * @param originalConstraints + * the original constraints passed to the data cube container + * @param response + * if getAvailabilityRequest() returned a request then this will + * have the response to that request. + * @return the TimeAndSpace when this node has available data. + * @throws VizException + */ + public abstract Set getAvailability( + Map originalConstraints, Object response) + throws VizException; + + /** + * Get data from this node. + * + * @param originalConstraints + * the original constraints passed to the data cube container + * @param availability + * the TimeAndSpace objects where data is being requested + * @param response + * response to the server request returned by getDataRequest. + * @return + */ + public abstract Set getData( + Map orignalConstraints, + Set availability, Object response) + throws VizException; + + @Override + public boolean isConstant() { + return false; + } + +} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractCubeLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractCubeLevelNode.java index fbe71d0063..806711ecb8 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractCubeLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractCubeLevelNode.java @@ -20,26 +20,21 @@ package com.raytheon.uf.viz.derivparam.tree; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.CatalogQuery; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.catalog.ScriptCreator; -import com.raytheon.uf.viz.core.comm.Loader; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.CubeRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpaceMatcher; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpaceMatcher.MatchResult; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -66,9 +61,9 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; * @author bsteffen * @version 1.0 */ -public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { +public abstract class AbstractCubeLevelNode extends AbstractDerivedDataNode { - protected List> levels; + protected List> levels; public AbstractCubeLevelNode(AbstractCubeLevelNode that) { super(that); @@ -77,7 +72,7 @@ public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { } public AbstractCubeLevelNode( - List> levels, + List> levels, String modelName) { this.levels = levels; this.modelName = modelName; @@ -87,7 +82,7 @@ public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { public AbstractCubeLevelNode( Level level, String modelName, - List> levels) { + List> levels) { this.setLevel(level); this.levels = levels; this.modelName = modelName; @@ -99,7 +94,7 @@ public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { DerivParamDesc desc, DerivParamMethod method, String modelName, - List> levels) { + List> levels) { super(level, desc, method, modelName); this.levels = levels; this.setValue("3D"); @@ -111,90 +106,69 @@ public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { } @Override - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + public Map> getDataDependency( + Set availability, + AvailabilityContainer availabilityContainer) throws VizException { + Map> result = new HashMap>(); + for (CubeLevel level : levels) { + result.put(level.getParam(), availability); + result.put(level.getPressure(), availability); + } + return result; + } + + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - List requests = new ArrayList( - levels.size()); - List timeAgnosticRequests = new ArrayList(); - List rawRecords = new ArrayList( - levels.size()); - List timeAgnosticRecords = new ArrayList(); - - for (CubeLevel level : levels) { - AbstractRequestableLevelNode node = level.getParam(); - if (cache.containsKey(node)) { - List cachedRecords = cache.get(node); - if (node.isTimeAgnostic()) { - timeAgnosticRecords.addAll(cachedRecords); - } else { - boolean foundMissingTime = false; - Set selectedTimes = new HashSet( - Arrays.asList(property.getSelectedEntryTime())); - for (AbstractRequestableData cRec : cachedRecords) { - if (!selectedTimes.contains(cRec.getDataTime())) { - foundMissingTime = true; - break; - } - } - if (foundMissingTime) { - requests.add(node); - } else { - rawRecords.addAll(cachedRecords); - } - } - } else { - if (node.isTimeAgnostic()) { - timeAgnosticRequests.add(node); - } else { - requests.add(node); + Map> paramMap = new HashMap>(); + Map> presMap = new HashMap>(); + for (CubeLevel level : levels) { + Set paramRecs = dependencyData.get(level + .getParam()); + for (AbstractRequestableData paramRec : paramRecs) { + TimeAndSpace ast = paramRec.getTimeAndSpace(); + List paramList = paramMap.get(ast); + if (paramList == null) { + paramList = new ArrayList(); + paramMap.put(ast, paramList); } + paramList.add(paramRec); } - } - - retrieveRecords(requests, property, timeOut, cache, rawRecords); - retrieveRecords(timeAgnosticRequests, property, timeOut, cache, - timeAgnosticRecords); - Map bins = new HashMap( - (int) (property.getSelectedEntryTime().length * 1.3)); - processRecords(rawRecords, property, true, false, bins); - processRecords(timeAgnosticRecords, property, true, true, bins); - requests.clear(); - timeAgnosticRequests.clear(); - rawRecords.clear(); - timeAgnosticRecords.clear(); - for (CubeLevel level : levels) { - AbstractRequestableLevelNode node = level.getPressure(); - if (cache.containsKey(node)) { - List cachedRecords = cache.get(node); - if (node.isTimeAgnostic()) { - timeAgnosticRecords.addAll(cachedRecords); - } else { - rawRecords.addAll(cachedRecords); - } - } else { - if (node.isTimeAgnostic()) { - timeAgnosticRequests.add(node); - } else { - requests.add(node); + Set presRecs = dependencyData.get(level + .getPressure()); + for (AbstractRequestableData presRec : presRecs) { + TimeAndSpace ast = presRec.getTimeAndSpace(); + List presList = presMap.get(ast); + if (presList == null) { + presList = new ArrayList(); + presMap.put(ast, presList); } + presList.add(presRec); } - } - retrieveRecords(requests, property, timeOut, cache, rawRecords); - retrieveRecords(timeAgnosticRequests, property, timeOut, cache, - timeAgnosticRecords); - processRecords(rawRecords, property, false, false, bins); - processRecords(timeAgnosticRecords, property, false, true, bins); - List records = new ArrayList( - bins.size()); - for (Entry entry : bins.entrySet()) { - CubeRequestableData record = entry.getValue(); + } + Map matches = new TimeAndSpaceMatcher() + .match(paramMap.keySet(), presMap.keySet()); + Set records = new HashSet(); + for (Entry match : matches.entrySet()) { + List paramList = paramMap.get(match + .getValue().get1()); + CubeRequestableData record = new CubeRequestableData( + paramList.get(0)); + for (AbstractRequestableData paramRec : paramList) { + record.addParam(paramRec); + } + List presList = presMap.get(match + .getValue().get2()); + for (AbstractRequestableData presRec : presList) { + record.addPressure(presRec); + } record.validate(); if (record.size() >= 2) { - record.setDataTime(entry.getKey()); + record.setDataTime(match.getKey().getTime()); + record.setSpace(match.getKey().getSpace()); modifyRequest(record); records.add(record); } @@ -202,183 +176,25 @@ public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { return records; } - private void retrieveRecords( - List requests, - LayerProperty property, - int timeOut, - Map> cache, - List retrievedRecords) throws VizException { - retrievedRecords.addAll(mergedGetData(merge(requests), property, - timeOut)); - for (AbstractRequestableLevelNode request : requests) { - retrievedRecords.addAll(request.getData(property, timeOut, cache)); - } - } + @Override + public Set getAvailability( + Map> availability) + throws VizException { + // things in one are available for one level + Set one = new HashSet(); + // things in two are available for two levels. + Set two = new HashSet(); - private void processRecords(List records, - LayerProperty property, boolean isParam, boolean isTimeAgnostic, - Map bins) { - DataTime[] keys = new DataTime[1]; - if (isTimeAgnostic) { - keys = property.getSelectedEntryTime(); - } - - for (AbstractRequestableData record : records) { - if (!isTimeAgnostic) { - keys[0] = record.getDataTime(); - } - - for (DataTime dt : keys) { - if (dt != null) { - CubeRequestableData bin = bins.get(dt); - if (bin == null) { - bin = new CubeRequestableData(record); - bins.put(dt, bin); - } - if (isParam) { - bin.addParam(record); - } else { - bin.addPressure(record); - } + for (CubeLevel level : levels) { + for (TimeAndSpace time : availability.get(level.getParam())) { + if (one.contains(time)) { + two.add(time); + } else { + one.add(time); } } } - } - - @Override - public boolean isTimeAgnostic() { - boolean timeAgnostic = true; - - for (CubeLevel level : levels) { - if (!level.getPressure().isTimeAgnostic() - || !level.getParam().isTimeAgnostic()) { - timeAgnostic = false; - break; - } - } - return timeAgnostic; - } - - /** - * Perform any filtering on the requestContraintsToFilter based on the - * baseRequestConstraints. - * - * @param baseRequestConstraints - * @param requestContraintsToFilter - */ - protected abstract void filter( - Map baseRequestConstraints, - Map requestContraintsToFilter); - - @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - Set results = new HashSet(); - List requests = new ArrayList( - levels.size() * 2); - - for (CubeLevel level : levels) { - AbstractRequestableLevelNode node = level.getPressure(); - if (cache.containsKey(node)) { - results.addAll(cache.get(node)); - } else if (!node.isTimeAgnostic()) { - requests.add(node); - } - node = level.getParam(); - if (cache.containsKey(node)) { - results.addAll(cache.get(node)); - } else if (!node.isTimeAgnostic()) { - requests.add(node); - } - } - - if (requests.size() == 0 && results.size() == 0) { - return TIME_AGNOSTIC; - } - - results.addAll(mergedTimeQuery(merge(requests), latestOnly)); - for (AbstractRequestableLevelNode request : requests) { - results.addAll(request.timeQuery(originalRequest, latestOnly, - cache, latestOnlyCache)); - } - return results; - } - - /** - * A merged time query performs a single time query from multiple requests - * when possible and removes those requests from the list. - * - * @param requests - * @param latestOnly - * @return - * @throws VizException - */ - protected Set mergedTimeQuery( - List> requests, boolean latestOnly) - throws VizException { - Set results = new HashSet(); - for (Map mergeMap : requests) { - DataTime[] resultsArr = CatalogQuery.performTimeQuery(mergeMap, - latestOnly, null); - - if (resultsArr != null) { - for (int i = 0; i < resultsArr.length; i++) { - results.add(resultsArr[i]); - } - } - } - return results; - } - - protected List mergedGetData( - List> requests, - LayerProperty property, int timeOut) throws VizException { - List results = new ArrayList(); - Map oldQuery = property - .getEntryQueryParameters(false); - int numberOfImages = property.getNumberOfImages(); - if (numberOfImages < 9999) { - property.setNumberOfImages(9999); - } - try { - for (Map mergeMap : requests) { - Map newQuery = new HashMap( - mergeMap); - filter(oldQuery, newQuery); - property.setEntryQueryParameters(newQuery, false); - // TODO: replace - String scriptToExecute = ScriptCreator.createScript(property); - - results.addAll(Loader.loadScripts( - new String[] { scriptToExecute }, timeOut)); - } - } finally { - property.setNumberOfImages(numberOfImages); - property.setEntryQueryParameters(oldQuery, false); - } - - return wrapRawRecord(results); - } - - protected abstract List wrapRawRecord( - List objs) throws VizException; - - protected List> merge( - List requests) { - List> mergeMaps = new ArrayList>( - requests.size()); - Iterator iter = requests.iterator(); - while (iter.hasNext()) { - AbstractRequestableLevelNode request = iter.next(); - if (request.hasRequestConstraints()) { - mergeMaps.add(request.getRequestConstraintMap()); - iter.remove(); - } - } - return mergeConstraints(mergeMaps); + return two; } /* @@ -390,7 +206,7 @@ public abstract class AbstractCubeLevelNode extends AbstractDerivedLevelNode { public List getDependencies() { List dependencies = new ArrayList( levels.size() * 2); - for (CubeLevel level : levels) { + for (CubeLevel level : levels) { dependencies.add(new Dependency(level.getPressure(), 0)); dependencies.add(new Dependency(level.getParam(), 0)); } diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractDerivedLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractDerivedDataNode.java similarity index 66% rename from cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractDerivedLevelNode.java rename to cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractDerivedDataNode.java index 777a6d39a9..2245913150 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractDerivedLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractDerivedDataNode.java @@ -24,15 +24,11 @@ import java.util.Map; import java.util.Set; 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.TimeQueryRequest; -import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; import com.raytheon.uf.common.derivparam.tree.LevelNode; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -55,8 +51,7 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; * @author bsteffen * @version 1.0 */ -public abstract class AbstractDerivedLevelNode extends - AbstractRequestableLevelNode { +public abstract class AbstractDerivedDataNode extends AbstractRequestableNode { protected DerivParamDesc desc; @@ -64,15 +59,15 @@ public abstract class AbstractDerivedLevelNode extends protected String modelName; - public AbstractDerivedLevelNode() { + public AbstractDerivedDataNode() { } - public AbstractDerivedLevelNode(Level level, DerivParamDesc desc, + public AbstractDerivedDataNode(Level level, DerivParamDesc desc, String modelName) { this(level, desc, null, modelName); } - public AbstractDerivedLevelNode(Level level, DerivParamDesc desc, + public AbstractDerivedDataNode(Level level, DerivParamDesc desc, DerivParamMethod method, String modelName) { super(level); this.desc = desc; @@ -80,7 +75,7 @@ public abstract class AbstractDerivedLevelNode extends this.modelName = modelName; } - public AbstractDerivedLevelNode(LevelNode that, DerivParamDesc desc, + public AbstractDerivedDataNode(LevelNode that, DerivParamDesc desc, DerivParamMethod method, String modelName) { super(that); this.desc = desc; @@ -88,7 +83,7 @@ public abstract class AbstractDerivedLevelNode extends this.modelName = modelName; } - public AbstractDerivedLevelNode(AbstractDerivedLevelNode that) { + public AbstractDerivedDataNode(AbstractDerivedDataNode that) { super(that); this.desc = that.desc; this.method = that.method; @@ -133,16 +128,6 @@ public abstract class AbstractDerivedLevelNode extends this.method = method; } - @Override - public Map getRequestConstraintMap() { - return null; - } - - @Override - public boolean hasRequestConstraints() { - return false; - } - /** * Sets the vector, abbreviation, name, unit, and level to match the desc * and level in this node @@ -191,7 +176,7 @@ public abstract class AbstractDerivedLevelNode extends return false; if (getClass() != obj.getClass()) return false; - AbstractDerivedLevelNode other = (AbstractDerivedLevelNode) obj; + AbstractDerivedDataNode other = (AbstractDerivedDataNode) obj; if (desc == null) { if (other.desc != null) return false; @@ -211,43 +196,55 @@ public abstract class AbstractDerivedLevelNode extends } /** - * Should only be called on final nodes, not derived nodes. + * Given the availability of all dependency nodes determine when this node + * is available. + * + * @param availability + * @return + * @throws VizException */ - @Override - protected DbQueryRequest getDataQueryInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - throw new UnsupportedOperationException( - "Derived nodes do not support retrieving data query, call on dependencies"); - } + public abstract Set getAvailability( + Map> availability) + throws VizException; /** - * Should only be called on final nodes, not derived nodes. + * If this node has dependency on other nodes then this method should return + * what data is needed for the dependencies to get data from this node for + * the provided availability. + * + * @param availability + * @return */ - @Override - public void setDataQueryResults( - DbQueryResponse queryResponse, - Map> cache) - throws VizException { - throw new UnsupportedOperationException( - "Derived nodes do not support processing data query, call on dependencies"); - } + public abstract Map> getDataDependency( + Set availability, AvailabilityContainer container) + throws VizException; + + /** + * Get data from this node. + * + * @param availability + * The time and spatial area where data is needed + * @return + */ + public abstract Set getData( + Set availability, + Map> dependencyData) + throws VizException; + + public abstract List getDependencies(); @Override - protected List processDataQueryResults( - DbQueryResponse queryResponse) throws VizException { - throw new UnsupportedOperationException( - "Derived nodes do not support processing data query, call on dependencies"); - } - - @Override - protected TimeQueryRequest getTimeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache) - throws VizException { - throw new UnsupportedOperationException( - "Derived nodes do not support retrieving time query, call on dependencies"); + public boolean isConstant() { + List dependencies = getDependencies(); + if (dependencies.isEmpty()) { + return false; + } + for (Dependency dep : getDependencies()) { + if (!dep.node.isConstant()) { + return false; + } + } + // All dependencies must be constant + return true; } } diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractRequestableLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractRequestableLevelNode.java deleted file mode 100644 index 2a4d8040c9..0000000000 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractRequestableLevelNode.java +++ /dev/null @@ -1,421 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.viz.derivparam.tree; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.raytheon.uf.common.dataplugin.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.TimeQueryRequest; -import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; -import com.raytheon.uf.common.derivparam.tree.LevelNode; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; - -/** - * - * The base level node for Cave, each Level Node should be able to handle time - * queries and metadata requests. This class attempts to handle - * caching(currently very limited) for all subclasses. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Jan 19, 2010            bsteffen     Initial creation
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ -public abstract class AbstractRequestableLevelNode extends LevelNode { - - @SuppressWarnings("unchecked") - public static final Set TIME_AGNOSTIC = Collections.EMPTY_SET; - - public static class Dependency { - - public Dependency(AbstractRequestableLevelNode node, int timeOffset) { - super(); - this.node = node; - this.timeOffset = timeOffset; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((node == null) ? 0 : node.hashCode()); - result = prime * result + timeOffset; - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Dependency other = (Dependency) obj; - if (node == null) { - if (other.node != null) - return false; - } else if (!node.equals(other.node)) - return false; - if (timeOffset != other.timeOffset) - return false; - return true; - } - - public AbstractRequestableLevelNode node; - - public int timeOffset; - } - - public AbstractRequestableLevelNode() { - } - - public AbstractRequestableLevelNode(Level level) { - super(level); - } - - public AbstractRequestableLevelNode(LevelNode that) { - super(that); - } - - public List getData( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - DataTime[] origTimes = property.getSelectedEntryTime(); - List rval = new ArrayList(); - if (cache != null && cache.containsKey(this) && origTimes != null) { - List cachedRecords = cache.get(this); - List selectedTimes = Arrays.asList(origTimes); - List newTimes = new ArrayList(selectedTimes); - for (AbstractRequestableData record : cachedRecords) { - if (selectedTimes.contains(record.getDataTime())) { - rval.add(record); - newTimes.remove(record.getDataTime()); - } - } - property.setSelectedEntryTimes(newTimes.toArray(new DataTime[0])); - } - if (origTimes == null || property.getSelectedEntryTime().length > 0) { - List newRecords = getDataInternal( - property, timeOut, cache); - rval.addAll(newRecords); - List cachedRecords = cache.get(this); - if (cachedRecords == null) { - cache.put(this, new ArrayList( - newRecords)); - } else { - cachedRecords.addAll(newRecords); - } - } - property.setSelectedEntryTimes(origTimes); - return rval; - } - - public DbQueryRequest getDataQuery( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - DataTime[] origTimes = property.getSelectedEntryTime(); - DbQueryRequest rval = null; - if (cache != null && cache.containsKey(this) && origTimes != null) { - List cachedRecords = cache.get(this); - List selectedTimes = Arrays.asList(origTimes); - List newTimes = new ArrayList(selectedTimes); - for (AbstractRequestableData record : cachedRecords) { - if (selectedTimes.contains(record.getDataTime())) { - newTimes.remove(record.getDataTime()); - } - } - property.setSelectedEntryTimes(newTimes - .toArray(new DataTime[newTimes.size()])); - } - if (origTimes == null || property.getSelectedEntryTime().length > 0) { - rval = getDataQueryInternal(property, timeOut, cache); - } - property.setSelectedEntryTimes(origTimes); - return rval; - } - - public void setDataQueryResults( - DbQueryResponse queryResponse, - Map> cache) - throws VizException { - // need transform method - List records = processDataQueryResults(queryResponse); - if (records == null || records.size() > 0) { - List cachedRecords = cache.get(this); - if (cachedRecords == null) { - cache.put(this, records); - } else { - // dups? - cachedRecords.addAll(records); - } - } - } - - protected abstract List processDataQueryResults( - DbQueryResponse queryResponse) throws VizException; - - public Set timeQuery(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - if (cache != null && cache.containsKey(this)) { - return cache.get(this); - } else if (latestOnly && latestOnlyCache.containsKey(this)) { - return latestOnlyCache.get(this); - } - - Set results = timeQueryInternal(originalRequest, latestOnly, - cache, latestOnlyCache); - if (cache != null && !latestOnly) { - cache.put(this, results); - } - return results; - } - - public TimeQueryRequest getTimeQuery(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - if (cache != null && cache.containsKey(this)) { - return null; - } else if (latestOnly && latestOnlyCache.containsKey(this)) { - return null; - } - - return getTimeQueryInternal(originalRequest, latestOnly, cache); - } - - public void setTimeQueryResults(boolean latestOnly, - List queryResponse, - Map> cache, - Map> latestOnlyCache) - throws VizException { - // perform any node specific processing - processTimeQueryResults(latestOnly, queryResponse); - if (latestOnly) { - Set cachedRecords = latestOnlyCache.get(this); - if (cachedRecords == null) { - latestOnlyCache.put(this, new HashSet(queryResponse)); - } else { - cachedRecords.addAll(queryResponse); - } - } else { - Set cachedRecords = cache.get(this); - if (cachedRecords == null) { - cache.put(this, new HashSet(queryResponse)); - } else { - cachedRecords.addAll(queryResponse); - } - } - } - - protected void processTimeQueryResults(boolean latestOnly, - List queryResponse) throws VizException { - // default has no internal processing to add - } - - public abstract List getDependencies(); - - public abstract boolean isTimeAgnostic(); - - public abstract boolean hasRequestConstraints(); - - public abstract Map getRequestConstraintMap(); - - public boolean isConstant() { - List dependencies = getDependencies(); - if (dependencies.isEmpty()) { - return false; - } - for (Dependency dep : getDependencies()) { - if (!dep.node.isConstant()) { - return false; - } - } - // All dependencies must be constant - return true; - } - - /** - * Takes the list of constraintMaps and merges the constraint maps that - * different by only one key into a new list of constraint maps. EX: 5 - * RequestConstraint Maps for GFS40 Temp on 5 MB levels will be consolidated - * into a single RequestConstraint Map using an IN List for the MB levels. - * - * @param constraintMaps - * @return - */ - public List> mergeConstraints( - List> constraintMaps) { - List> rval = new ArrayList>(); - if (constraintMaps != null && constraintMaps.size() > 0) { - List mergeKeyList = new ArrayList(); - - for (Map constraintMap : constraintMaps) { - boolean merged = false; - int index = 0; - - MERGE_MAP_LOOP: for (index = 0; index < rval.size(); index++) { - Map mergeMap = rval.get(index); - - // maps must be of same size - if (mergeMap.size() == constraintMap.size()) { - String mergeKey = mergeKeyList.get(index); - - if (mergeKey != null) { - // determine if it matches map except for uniqueKey - for (String key : mergeMap.keySet()) { - boolean isUniqueKey = mergeKey.equals(key); - boolean constraintEquals = mergeMap.get(key) - .equals(constraintMap.get(key)); - - if (!constraintEquals && !isUniqueKey) { - continue MERGE_MAP_LOOP; - } - } - - // map differs except for key - boolean constraintMerged = mergeMap.get(mergeKey) - .merge(constraintMap.get(mergeKey)); - if (!constraintMerged) { - continue MERGE_MAP_LOOP; - } else { - merged = true; - break MERGE_MAP_LOOP; - } - } else { - // current mergeMap has never been merged with, - // double check that only one key is different - // between maps - for (String key : mergeMap.keySet()) { - if (!mergeMap.get(key).equals( - constraintMap.get(key))) { - if (mergeKey == null) { - // possible merge key, continue checking - // map - mergeKey = key; - } else { - // two merge keys found, go to next - // merge map - continue MERGE_MAP_LOOP; - } - } - } - - merged = true; - - // found mergeKey, add to mergeKeyList. If mergeKey - // still being null is only possible of mergeMap and - // constraintMap contain the exact same constraints, - // consider them merged - if (mergeKey != null) { - mergeKeyList.set(index, mergeKey); - } - - break MERGE_MAP_LOOP; - } - } // maps same size check - } // MERGE_MAP_LOOP - - if (!merged) { - Map mergeMap = new HashMap(); - - // deep copy the map - for (Map.Entry entry : constraintMap - .entrySet()) { - mergeMap.put(entry.getKey(), entry.getValue().clone()); - } - - rval.add(mergeMap); - mergeKeyList.add(null); - } - } - } - - return rval; - } - - protected abstract Set timeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException; - - protected abstract TimeQueryRequest getTimeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache) - throws VizException; - - protected abstract List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException; - - protected abstract DbQueryRequest getDataQueryInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException; - - protected Set timeQuery(TimeQueryRequest originalRequest, - boolean latestOnly) throws VizException { - return timeQuery(originalRequest, latestOnly, - new HashMap>(), - new HashMap>()); - } - -} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractRequestableNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractRequestableNode.java new file mode 100644 index 0000000000..b4049f48b6 --- /dev/null +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AbstractRequestableNode.java @@ -0,0 +1,109 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.derivparam.tree; + +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.derivparam.tree.LevelNode; + +/** + * + * The base level node for Cave, each Level Node should be able to handle time + * queries and metadata requests. This class attempts to handle + * caching(currently very limited) for all subclasses. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jan 19, 2010            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public abstract class AbstractRequestableNode extends LevelNode { + + public static class Dependency { + + public Dependency(AbstractRequestableNode node, int timeOffset) { + super(); + this.node = node; + this.timeOffset = timeOffset; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((node == null) ? 0 : node.hashCode()); + result = prime * result + timeOffset; + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Dependency other = (Dependency) obj; + if (node == null) { + if (other.node != null) + return false; + } else if (!node.equals(other.node)) + return false; + if (timeOffset != other.timeOffset) + return false; + return true; + } + + public AbstractRequestableNode node; + + public int timeOffset; + } + + public AbstractRequestableNode() { + } + + public AbstractRequestableNode(Level level) { + super(level); + } + + public AbstractRequestableNode(LevelNode that) { + super(that); + } + + public abstract boolean isConstant(); + +} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AliasLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AliasLevelNode.java index f69ce2765f..1edc3b3ae9 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AliasLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/AliasLevelNode.java @@ -19,15 +19,15 @@ **/ package com.raytheon.uf.viz.derivparam.tree; -import java.util.ArrayList; -import java.util.List; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.AliasRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -56,20 +56,19 @@ public class AliasLevelNode extends AbstractAliasLevelNode { super(that); } - public AliasLevelNode(AbstractRequestableLevelNode sourceNode, + public AliasLevelNode(AbstractRequestableNode sourceNode, DerivParamDesc desc, DerivParamMethod method, String modelName, Level level) { super(sourceNode, desc, method, modelName, level); } - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - List origs = sourceNode.getData(property, - timeOut, cache); - List results = new ArrayList( + Set origs = dependencyData.get(sourceNode); + Set results = new HashSet( origs.size()); for (AbstractRequestableData orig : origs) { AbstractRequestableData result = new AliasRequestableData(orig); diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/CompositeAverageLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/CompositeAverageLevelNode.java index abc78c6142..11624d8e9d 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/CompositeAverageLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/CompositeAverageLevelNode.java @@ -26,13 +26,11 @@ import java.util.Map; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.AggregateRequestableData; import com.raytheon.uf.viz.derivparam.data.DerivedRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivedParameterRequest; @@ -64,19 +62,19 @@ public class CompositeAverageLevelNode extends UnionLevelNode { } public CompositeAverageLevelNode(Level level, DerivParamDesc desc, - String modelName, List nodes) { + String modelName, List nodes) { super(level, desc, null, modelName, nodes); } - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - List result = new ArrayList(); + Set result = new HashSet(); - for (AbstractRequestableData record : super.getDataInternal(property, - timeOut, cache)) { + for (AbstractRequestableData record : super.getData(availability, + dependencyData)) { AggregateRequestableData aRec = (AggregateRequestableData) record; if (aRec.getSourceRecords().size() == nodes.size()) { DerivedParameterRequest request = new DerivedParameterRequest(); @@ -95,33 +93,22 @@ public class CompositeAverageLevelNode extends UnionLevelNode { return result; } - /* - * (non-Javadoc) - * - * @see - * com.raytheon.uf.viz.derivparam.tree.UnionLevelNode#timeQueryInternal( - * boolean, java.util.Map) - */ @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Set getAvailability( + Map> availability) throws VizException { - // We should only have times if all our nodes have times - Set results = TIME_AGNOSTIC; + Set results = null; - List requests = new ArrayList( + List requests = new ArrayList( nodes); - for (AbstractRequestableLevelNode request : requests) { + for (AbstractRequestableNode request : requests) { // Do not request just latest only because if two nodes have // different latests than this will return no times - Set times = request.timeQuery(originalRequest, false, - cache, latestOnlyCache); - if (times == TIME_AGNOSTIC) { + Set times = availability.get(request); + if (times == null) { continue; - } else if (results == TIME_AGNOSTIC) { - results = new HashSet(times); + } else if (results == null) { + results = new HashSet(times); } else { results.retainAll(times); } diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/DerivedLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/DerivedLevelNode.java index 220f9fa03a..ceea8b34f5 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/DerivedLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/DerivedLevelNode.java @@ -22,6 +22,7 @@ package com.raytheon.uf.viz.derivparam.tree; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; @@ -32,14 +33,15 @@ import java.util.Map.Entry; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.common.time.DataTime.FLAG; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.AliasRequestableData; import com.raytheon.uf.viz.derivparam.data.DerivedRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpaceMatcher; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpaceMatcher.MatchResult; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamField; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -64,21 +66,11 @@ import com.raytheon.uf.viz.derivparam.library.IDerivParamField; * @version 1.0 */ -public class DerivedLevelNode extends AbstractDerivedLevelNode { - - private static final int TIME_QUERY_CACHE_TIME = 30000; +public class DerivedLevelNode extends AbstractDerivedDataNode { private Map fieldStaticData = null; - private Map fields = null; - - /** - * Time cache should be reset every time a time query is performed and then - * it can be used to correlate times when requesting data. - */ - private Map> timeCache = null; - - private long lastTimeQuery = 0; + private Map fields = null; private int dt; @@ -91,7 +83,7 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { public DerivedLevelNode(DerivedLevelNode that) { super(that); if (that.fields != null) { - fields = new HashMap( + fields = new HashMap( that.fields); } if (that.fieldStaticData != null) { @@ -111,7 +103,7 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { /** * @return the fields */ - public Map getFields() { + public Map getFields() { return fields; } @@ -130,10 +122,9 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { this.fieldStaticData.put(field, requestableData); } - public void putField(DerivParamField field, - AbstractRequestableLevelNode object) { + public void putField(DerivParamField field, AbstractRequestableNode object) { if (fields == null) { - fields = new HashMap(); + fields = new HashMap(); } this.fields.put(field, object); } @@ -149,99 +140,70 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { return getFieldsSize() == method.getFields().size(); } - @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - this.lastTimeQuery = System.currentTimeMillis(); - Map> timeCache = new HashMap>(); - // We have a derived parameter for the requested grid - Set availableDataTimes = null; - if (fields == null) { - timeCache.put(null, TIME_AGNOSTIC); - this.timeCache = timeCache; - return TIME_AGNOSTIC; + private TimeAndSpaceMatcher getMatcher() { + TimeAndSpaceMatcher matcher = new TimeAndSpaceMatcher(); + matcher.setIgnoreRange(true); + if (method.isFtime()) { + matcher.setMatchValid(false); + } else { + matcher.setMatchValid(true); } - Collection fieldsKeys = fields.keySet(); - if (method.isDtime()) { - // Attempt to use 0 time shift data first. - List fieldsList = new ArrayList( - fieldsKeys); - for (int i = 1; i < fieldsList.size(); i++) { - if (fieldsList.get(i).getTimeShift() == 0) { - fieldsList.set(i, fieldsList.set(0, fieldsList.get(i))); - } - } - fieldsKeys = fieldsList; - } - for (DerivParamField field : fieldsKeys) { - AbstractRequestableLevelNode node = fields.get(field); - Set queryDataTimes = node.timeQuery(originalRequest, - false, cache, latestOnlyCache); - timeCache.put(field, queryDataTimes); - if (queryDataTimes == TIME_AGNOSTIC) { - if (availableDataTimes == null) { - availableDataTimes = TIME_AGNOSTIC; - } - continue; - } - if (queryDataTimes != null && queryDataTimes.size() > 0) { + return matcher; + } - if (availableDataTimes != null - && availableDataTimes != TIME_AGNOSTIC) { - availableDataTimes.retainAll(timeMatch(availableDataTimes, - queryDataTimes, field).keySet()); + private Map shiftTime(DerivParamField field, + Set dataTimes) { + int timeShift = getDTimeInSeconds(field); + if (timeShift != 0) { + Map result = new HashMap(); + for (TimeAndSpace t : dataTimes) { + if (t.isTimeAgnostic()) { + result.put(t, t); } else { - // populate initial data times - - if (method.isDtime()) { - // if dT required handle now - int dTimeInSeconds = getDTimeInSeconds(field); - - if (dTimeInSeconds == -1) { - return new HashSet(0); - } - - // handle valid time shift - availableDataTimes = new HashSet((64)); - - // generate all possible valid times - for (DataTime dataTime : queryDataTimes) { - if (field.getTimeShift() == 0) { - // Strip any validPeriodInfo - availableDataTimes.add(new DataTime(dataTime - .getRefTime(), dataTime.getFcstTime())); - } else { - availableDataTimes - .addAll(generatePossibleDataTimes( - dataTime, field)); - } - } - } else if (method.isFtime()) { - // handle forecast time shift - availableDataTimes = new HashSet(); - int fcstShift = field.getTimeShift(); - for (DataTime dataTime : queryDataTimes) { - int fcstTime = dataTime.getFcstTime() - fcstShift; - if (fcstTime >= 0) { - availableDataTimes.add(new DataTime(dataTime - .getRefTime(), fcstTime)); - } - } - } else { - availableDataTimes = new HashSet(); - for (DataTime time : queryDataTimes) { - if (time.getUtilityFlags().contains(FLAG.FCST_USED)) - availableDataTimes.add(new DataTime(time - .getRefTime(), time.getFcstTime())); - else - availableDataTimes.add(new DataTime(time - .getRefTime())); - } + DataTime time = t.getTime(); + long rTime = time.getRefTime().getTime(); + int fTime = time.getFcstTime(); + // Shift valid time back rather than having a + // negative forecast time. + fTime -= timeShift; + while (method.isDtime() && fTime < 0) { + rTime -= dt * 1000; + fTime += dt; } + time = new DataTime(new Date(rTime), fTime); + result.put(new TimeAndSpace(time, t.getSpace()), t); } + } + return result; + } + return null; + } + + @Override + public Set getAvailability( + Map> availability) + throws VizException { + TimeAndSpaceMatcher matcher = getMatcher(); + // We have a derived parameter for the requested grid + Set availableDataTimes = null; + if (fields == null) { + availableDataTimes = AvailabilityContainer.AGNOSTIC_SET; + return availableDataTimes; + } + for (DerivParamField field : fields.keySet()) { + AbstractRequestableNode node = fields.get(field); + Set queryDataTimes = availability.get(node); + if (queryDataTimes != null && queryDataTimes.size() > 0) { + Map shiftMap = shiftTime(field, + queryDataTimes); + if (shiftMap != null) { + queryDataTimes = shiftMap.keySet(); + } + if (availableDataTimes == null) { + availableDataTimes = AvailabilityContainer.AGNOSTIC_SET; + } + availableDataTimes = matcher.match(availableDataTimes, + queryDataTimes).keySet(); } else { // no data for this query, clear times and return availableDataTimes = null; @@ -253,72 +215,99 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { } }// FIELD_LOOP - if (availableDataTimes != null) { - timeCache.put(null, availableDataTimes); - this.timeCache = timeCache; - } else { - timeCache = new HashMap>(); - availableDataTimes = new HashSet(0); - timeCache.put(null, availableDataTimes); - this.timeCache = timeCache; + if (availableDataTimes == null) { + availableDataTimes = new HashSet(0); } return availableDataTimes; } @Override - public boolean isTimeAgnostic() { - boolean timeAgnostic = true; - - for (AbstractRequestableLevelNode node : fields.values()) { - if (!node.isTimeAgnostic()) { - timeAgnostic = false; - break; + public Map> getDataDependency( + Set availability, + AvailabilityContainer availabilityContainer) throws VizException { + TimeAndSpaceMatcher matcher = getMatcher(); + availability = matcher.match(availability, + availabilityContainer.getAvailability(this)).keySet(); + if (availability.isEmpty()) { + return Collections.emptyMap(); + } + Map> result = new HashMap>(); + if (fields != null) { + for (Entry field : fields + .entrySet()) { + Set queryTimes = availabilityContainer + .getAvailability(field.getValue()); + Map shiftMap = shiftTime( + field.getKey(), queryTimes); + if (shiftMap != null) { + queryTimes = shiftMap.keySet(); + } + Set fieldResult = TimeAndSpaceMatcher + .getAll2(matcher.match(availability, queryTimes)); + if (shiftMap != null) { + Set newFieldResult = new HashSet(); + for (TimeAndSpace t : fieldResult) { + newFieldResult.add(shiftMap.get(t)); + } + fieldResult = newFieldResult; + } + Set oldSet = result.put(field.getValue(), + fieldResult); + if (oldSet != null) { + fieldResult.addAll(oldSet); + } } } - - return timeAgnostic; + if (fieldStaticData != null) { + for (Entry entry : fieldStaticData + .entrySet()) { + StaticDataLevelNode node = new StaticDataLevelNode(level, desc, + entry.getValue(), modelName); + result.put(node, AvailabilityContainer.AGNOSTIC_SET); + } + } + return result; } - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - if (this.timeCache == null - || this.lastTimeQuery + TIME_QUERY_CACHE_TIME < System - .currentTimeMillis()) { - this.timeQuery(null, false); - } - - // keep a reference for scope of method - Map> myTimeCache = this.timeCache; - Set thisAvailableTimes = myTimeCache.get(null); - if (thisAvailableTimes == TIME_AGNOSTIC) { - thisAvailableTimes = new HashSet(); - thisAvailableTimes.add(null); - } else { - if (property.getSelectedEntryTime() != null) { - thisAvailableTimes = new HashSet(thisAvailableTimes); - thisAvailableTimes.retainAll(Arrays.asList(property - .getSelectedEntryTime())); + Map> availCache = new HashMap>( + (int) (dependencyData.size() / 0.75) + 1, 0.75f); + for (AbstractRequestableNode node : fields.values()) { + Set dataSet = dependencyData.get(node); + Set tas = new HashSet( + (int) (dataSet.size() / 0.75) + 1, 0.75f); + for (AbstractRequestableData data : dataSet) { + tas.add(data.getTimeAndSpace()); } + availCache.put(node, tas); } - Map mapOfRequests = new HashMap( - thisAvailableTimes.size()); + TimeAndSpaceMatcher matcher = getMatcher(); + availability = matcher.match(availability, getAvailability(availCache)) + .keySet(); + if (availability.isEmpty()) { + return Collections.emptySet(); + } + Map mapOfRequests = new HashMap( + availability.size()); List initResponses = new ArrayList( - thisAvailableTimes.size()); + availability.size()); - for (DataTime time : thisAvailableTimes) { + for (TimeAndSpace ast : availability) { DerivedParameterRequest derivRequest = new DerivedParameterRequest(); DerivedRequestableData newRecord = new DerivedRequestableData( derivRequest); - newRecord.setDataTime(time); + newRecord.setDataTime(ast.getTime()); + newRecord.setSpace(ast.getSpace()); derivRequest.setParameterAbbreviation(desc.getAbbreviation()); derivRequest.setMethod(method.getName()); // get data time for this field - derivRequest.setBaseTime(time); + derivRequest.setBaseTime(ast.getTime()); initResponses.add(newRecord); - mapOfRequests.put(time, derivRequest); + mapOfRequests.put(ast, derivRequest); } for (IDerivParamField ifield : method.getFields()) { @@ -326,64 +315,48 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { AbstractRequestableData data = fieldStaticData.get(ifield); if (ifield instanceof DerivParamField) { data = checkFieldUnits((DerivParamField) ifield, - Arrays.asList(data)).get(0); + Arrays.asList(data)).iterator().next(); } for (DerivedParameterRequest request : mapOfRequests.values()) { request.addBaseParam(data); } } else if (fields != null && fields.containsKey(ifield)) { DerivParamField field = (DerivParamField) ifield; - AbstractRequestableLevelNode fieldNode = fields.get(field); - - Collection availableTimes = myTimeCache.get(field); - if (availableTimes == TIME_AGNOSTIC) { - List responses = fieldNode - .getData(property, timeOut, cache); - responses = checkFieldUnits(field, responses); - for (DerivedParameterRequest request : mapOfRequests - .values()) { - for (AbstractRequestableData response : responses) { - if (response.getDataTime() == null - || response.getDataTime().equals( - response.getDataTime())) { - request.addBaseParam(response); - break; - } - } - } - } else { - - DataTime[] oldEntryTimes = property.getSelectedEntryTime(); - Map matchTimes = timeMatch( - mapOfRequests.keySet(), availableTimes, field); - Set newEntryTimes = new HashSet( - matchTimes.values()); - property.setSelectedEntryTimes(newEntryTimes - .toArray(new DataTime[newEntryTimes.size()])); - List responses = fieldNode - .getData(property, timeOut, cache); - property.setSelectedEntryTimes(oldEntryTimes); - responses = checkFieldUnits(field, responses); - Map responseMap = new HashMap(); - for (AbstractRequestableData record : responses) { - responseMap.put(record.getDataTime(), record); - } - Iterator> it = mapOfRequests - .entrySet().iterator(); - while (it.hasNext()) { - Entry entry = it - .next(); - DataTime requestTime = matchTimes.get(entry.getKey()); - AbstractRequestableData data = responseMap - .get(requestTime); - if (data != null) { - entry.getValue().addBaseParam(data); - } else { - it.remove(); - } - } + AbstractRequestableNode fieldNode = fields.get(field); + Set fieldAvailability = availCache.get(fieldNode); + Map shiftMap = shiftTime(field, + fieldAvailability); + if (shiftMap != null) { + fieldAvailability = shiftMap.keySet(); } + Map matchTimes = matcher.match( + availability, fieldAvailability); + Collection responses = dependencyData + .get(fieldNode); + responses = checkFieldUnits(field, responses); + Map responseMap = new HashMap(); + for (AbstractRequestableData record : responses) { + responseMap.put(record.getTimeAndSpace(), record); + } + Iterator> it = mapOfRequests + .entrySet().iterator(); + while (it.hasNext()) { + Entry entry = it + .next(); + TimeAndSpace requestTime = matchTimes.get(entry.getKey()) + .get2(); + if (shiftMap != null) { + requestTime = shiftMap.get(requestTime); + } + AbstractRequestableData data = responseMap.get(requestTime); + if (data != null) { + entry.getValue().addBaseParam(data); + } else { + it.remove(); + } + } + } else { throw new VizException("Error processing Derived parameter:" + desc.getAbbreviation() + ":" + method.getName() + ":" @@ -391,7 +364,7 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { } } - List finalResponses = new ArrayList(); + Set finalResponses = new HashSet(); for (DerivedRequestableData record : initResponses) { if (record.getRequest().getBaseParams().size() == method .getFields().size()) { @@ -403,61 +376,6 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { return finalResponses; } - /** - * Given a set of times to load, and the available times for a field - * generate a map from one to the other, taking into account dTime and fTime - * - * @param timesToLaod - * @param availableTimes - * @param field - * @return - */ - private Map timeMatch(Collection timesToLaod, - Collection availableTimes, DerivParamField field) { - // First step is to sort the available times by valid time - Map> validMap = new HashMap>(); - for (DataTime time : availableTimes) { - Long validTime = time.getMatchValid(); - Set timeSet = validMap.get(validTime); - if (timeSet == null) { - timeSet = new HashSet(); - validMap.put(validTime, timeSet); - } - timeSet.add(time); - } - // For each requested time we find the best available time - Map results = new HashMap(); - int dTimeInSeconds = getDTimeInSeconds(field); - - if (dTimeInSeconds == -1) { - return results; - } - for (DataTime entryTime : timesToLaod) { - Long validTime = entryTime.getMatchValid() + dTimeInSeconds * 1000; - if (!validMap.containsKey(validTime)) { - // This means we have no data for this field at this - // time - continue; - } - DataTime latest = null; - for (DataTime time : validMap.get(validTime)) { - if (time.getMatchRef() == entryTime.getMatchRef()) { - // Prefer a matching ref time - latest = time; - break; - } else if (!method.isFtime() - && (latest == null || latest.getMatchRef() < time - .getMatchRef())) { - latest = time; - } - } - if (latest != null) { - results.put(entryTime, latest); - } - } - return results; - } - private int getDTimeInSeconds(DerivParamField field) { int dTimeInSeconds = 0; @@ -474,9 +392,9 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { return dTimeInSeconds; } - private List checkFieldUnits( - DerivParamField field, List records) { - List newRecs = new ArrayList( + private Collection checkFieldUnits( + DerivParamField field, Collection records) { + Set newRecs = new HashSet( records.size()); for (AbstractRequestableData record : records) { if (record.getUnit() != null @@ -492,44 +410,6 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { return newRecs; } - /** - * Generates the possible data times for a dTime option. - * - * @param dataTime - * The original data time - * @param dTimeInSeconds - * The dTime offset in seconds - * @param dTinSeconds - * The intrinsic time spacing of the current model. - * @return A list of possible data times. - */ - private List generatePossibleDataTimes(DataTime dataTime, - DerivParamField field) { - int dTimeInSeconds = getDTimeInSeconds(field); - int sign = 1; - if (dTimeInSeconds < 0) { - dTimeInSeconds *= -1; - sign = -1; - } - - int fTimeInSeconds = dataTime.getFcstTime(); - long vTimeInMillis = dataTime.getValidTime().getTimeInMillis() - - (dTimeInSeconds * 1000 * sign); - - List rval = new ArrayList( - (dTimeInSeconds * 2 / dt) + 1); - - for (int fInSeconds = fTimeInSeconds - dTimeInSeconds; fInSeconds <= fTimeInSeconds - + dTimeInSeconds; fInSeconds += dt) { - if (fInSeconds >= 0) { - rval.add(new DataTime(new Date(vTimeInMillis - - (fInSeconds * 1000)), fInSeconds)); - } - } - - return rval; - } - /* * (non-Javadoc) * @@ -540,7 +420,7 @@ public class DerivedLevelNode extends AbstractDerivedLevelNode { public List getDependencies() { List dependencies = new ArrayList(); if (fields != null) { - for (Entry entry : fields + for (Entry entry : fields .entrySet()) { dependencies.add(new Dependency(entry.getValue(), getDTimeInSeconds(entry.getKey()))); diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/ModelRunLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/ModelRunLevelNode.java deleted file mode 100644 index bb847c456b..0000000000 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/ModelRunLevelNode.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.viz.derivparam.tree; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; -import com.raytheon.uf.viz.derivparam.data.AggregateRequestableData; -import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; -import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; - -/** - * - * Builds AggregateRecords which contain all forecast times up to the requested - * time. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Feb 8, 2010            bsteffen     Initial creation
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ -public class ModelRunLevelNode extends AbstractAliasLevelNode { - - public ModelRunLevelNode(ModelRunLevelNode that) { - super(that); - } - - public ModelRunLevelNode(AbstractRequestableLevelNode sourceNode, - DerivParamDesc desc, DerivParamMethod method, String modelName, - Level level) { - super(sourceNode, desc, method, modelName, level); - } - - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - Set allTimes = this.timeQuery(null, false); - Set neededTimes = null; - DataTime[] requestedTimes = property.getSelectedEntryTime(); - if (requestedTimes == null) { - neededTimes = allTimes; - } else { - neededTimes = new HashSet(); - for (DataTime time : allTimes) { - for (DataTime rTime : property.getSelectedEntryTime()) { - if (rTime.getRefTime().equals(time.getRefTime()) - && rTime.getFcstTime() >= time.getFcstTime()) { - neededTimes.add(time); - break; - } - } - } - - } - Map> timeBins = new HashMap>(); - if (requestedTimes == null) { - for (DataTime time : allTimes) { - timeBins.put(time, new ArrayList()); - } - } else { - for (DataTime time : requestedTimes) { - timeBins.put(time, new ArrayList()); - } - } - property.setSelectedEntryTimes(neededTimes - .toArray(new DataTime[neededTimes.size()])); - - for (AbstractRequestableData record : sourceNode.getData(property, - timeOut, cache)) { - for (Entry> entry : timeBins - .entrySet()) { - DataTime keyTime = entry.getKey(); - DataTime recordTime = record.getDataTime(); - if (keyTime.getRefTime().getTime() == recordTime.getRefTime() - .getTime() - && keyTime.getFcstTime() >= recordTime.getFcstTime()) { - entry.getValue().add(record); - } - } - } - List records = new ArrayList(); - for (Entry> entry : timeBins - .entrySet()) { - if (!entry.getValue().isEmpty()) { - AggregateRequestableData newRecord = new AggregateRequestableData( - entry.getValue()); - newRecord.setDataTime(entry.getKey()); - modifyRequest(newRecord); - records.add(newRecord); - } - } - return records; - } - - @Override - public ModelRunLevelNode clone() { - return new ModelRunLevelNode(this); - } - -} diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/OrLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/OrLevelNode.java index 370c16b9a0..1e0dffec58 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/OrLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/OrLevelNode.java @@ -20,19 +20,17 @@ package com.raytheon.uf.viz.derivparam.tree; import java.util.ArrayList; -import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -54,20 +52,20 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; * @author bsteffen * @version 1.0 */ -public class OrLevelNode extends AbstractDerivedLevelNode { +public class OrLevelNode extends AbstractDerivedDataNode { - private List nodes; + private List nodes; public OrLevelNode(OrLevelNode that) { super(that); if (that.nodes != null) { - this.nodes = new ArrayList(that.nodes); + this.nodes = new ArrayList(that.nodes); } } public OrLevelNode(Level level, DerivParamDesc desc, DerivParamMethod method, String modelName, - List nodes) { + List nodes) { this(level, desc, method, modelName, nodes, true); } @@ -90,146 +88,50 @@ public class OrLevelNode extends AbstractDerivedLevelNode { */ public OrLevelNode(Level level, DerivParamDesc desc, DerivParamMethod method, String modelName, - List nodes, boolean alias) { + List nodes, boolean alias) { super(level, desc, method, modelName); if (alias) { - this.nodes = new ArrayList( - nodes.size()); - for (AbstractRequestableLevelNode node : nodes) { + this.nodes = new ArrayList(nodes.size()); + for (AbstractRequestableNode node : nodes) { this.nodes.add(new AliasLevelNode(node, desc, method, modelName, level)); } } else { - this.nodes = new ArrayList(nodes); + this.nodes = new ArrayList(nodes); } } - public void addNodeToOrList(AbstractRequestableLevelNode node) { + public void addNodeToOrList(AbstractRequestableNode node) { nodes.add(node); } @Override - protected List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - Set requestedTimes = null; - DataTime[] requestedTimesArr = property.getSelectedEntryTime(); - if (requestedTimesArr == null) { - requestedTimes = this.timeQuery(null, false); - } else { - requestedTimes = new HashSet( - Arrays.asList(requestedTimesArr)); + public Map> getDataDependency( + Set availability, + AvailabilityContainer availabilityContainer) throws VizException { + Map> result = new HashMap>(); + for (AbstractRequestableNode node : nodes) { + result.put(node, availability); } - List records = new ArrayList( - requestedTimes.size()); - for (AbstractRequestableLevelNode node : nodes) { - List newRecords = node.getData(property, - timeOut, cache); - for (AbstractRequestableData record : newRecords) { - if (record.getDataTime() == null) { - requestedTimes.clear(); - } else { - requestedTimes.remove(record.getDataTime()); - } - } - records.addAll(newRecords); - if (requestedTimes.isEmpty()) { - break; - } - property.setSelectedEntryTimes(requestedTimes - .toArray(new DataTime[requestedTimes.size()])); - } - return records; + return result; } @Override - protected Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - Set results = new HashSet(); - for (AbstractRequestableLevelNode node : nodes) { - Set times = node.timeQuery(originalRequest, latestOnly, - cache, latestOnlyCache); - if (times == AbstractRequestableLevelNode.TIME_AGNOSTIC) { - return times; - } else { - for (DataTime time : times) { - boolean good = true; - for (DataTime result : results) { - if (result.getMatchRef() == time.getMatchRef() - && result.getMatchFcst() == time.getMatchFcst()) { - good = false; - break; - } - } - if (good) { - results.add(time); - } + Map dataMap = new HashMap(); + for (AbstractRequestableNode node : nodes) { + Set dataSet = dependencyData.get(node); + for (AbstractRequestableData data : dataSet) { + TimeAndSpace ast = data.getTimeAndSpace(); + if (!dataMap.containsKey(ast)) { + dataMap.put(ast, data); } } } - return results; - } - - @Override - public boolean isTimeAgnostic() { - for (AbstractRequestableLevelNode node : nodes) { - if (node.isTimeAgnostic()) { - return true; - } - } - - return false; - } - - @Override - public Map getRequestConstraintMap() { - Map rval = null; - List> list = new ArrayList>( - nodes.size()); - - for (AbstractRequestableLevelNode node : nodes) { - Map rcMap = node - .getRequestConstraintMap(); - - if (rcMap == null) { - // sub node has no request constraint short circuit and exit now - return null; - } - - list.add(node.getRequestConstraintMap()); - } - - list = mergeConstraints(list); - if (list.size() == 1) { - rval = list.get(0); - } else { - // not directly combinable until this method is updated to - // return a list of rcMaps - rval = null; - } - - return rval; - } - - @Override - public boolean hasRequestConstraints() { - boolean rval = true; - for (AbstractRequestableLevelNode node : nodes) { - if (!node.hasRequestConstraints()) { - rval = false; - break; - } - } - if (rval) { - // handle the maps not being directly combinable - rval = getRequestConstraintMap() != null; - } - return rval; + return new HashSet(dataMap.values()); } /* @@ -240,7 +142,7 @@ public class OrLevelNode extends AbstractDerivedLevelNode { */ public List getDependencies() { List dependencies = new ArrayList(nodes.size()); - for (AbstractRequestableLevelNode node : nodes) { + for (AbstractRequestableNode node : nodes) { dependencies.add(new Dependency(node, 0)); } return dependencies; @@ -286,4 +188,15 @@ public class OrLevelNode extends AbstractDerivedLevelNode { return true; } + @Override + public Set getAvailability( + Map> availability) + throws VizException { + Set myAvailability = new HashSet(); + for (AbstractRequestableNode node : nodes) { + myAvailability.addAll(availability.get(node)); + } + return myAvailability; + } + } diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/StaticDataLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/StaticDataLevelNode.java index 8fd9ff5528..8e4413f31d 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/StaticDataLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/StaticDataLevelNode.java @@ -21,17 +21,16 @@ package com.raytheon.uf.viz.derivparam.tree; import java.util.Arrays; import java.util.Collections; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -57,16 +56,7 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; * @author bsteffen * @version 1.0 */ -public class StaticDataLevelNode extends AbstractDerivedLevelNode { - - @Override - protected DbQueryRequest getDataQueryInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - return null; - } +public class StaticDataLevelNode extends AbstractDerivedDataNode { protected static final String TIME_FIELD = "dataTime"; @@ -90,29 +80,19 @@ public class StaticDataLevelNode extends AbstractDerivedLevelNode { this.source = source; } - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - return Arrays.asList(source); + @Override + public Map> getDataDependency( + Set availability, + AvailabilityContainer availabilityContainer) throws VizException { + return Collections.emptyMap(); } @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - return TIME_AGNOSTIC; - } - - @Override - protected TimeQueryRequest getTimeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache) - throws VizException { - return null; + return new HashSet(Arrays.asList(source)); } @Override @@ -120,11 +100,6 @@ public class StaticDataLevelNode extends AbstractDerivedLevelNode { return true; } - @Override - public boolean isTimeAgnostic() { - return true; - } - /* * (non-Javadoc) * @@ -176,4 +151,13 @@ public class StaticDataLevelNode extends AbstractDerivedLevelNode { return true; } + @Override + public Set getAvailability( + Map> availability) + throws VizException { + Set result = new HashSet(); + result.add(source.getTimeAndSpace()); + return result; + } + } diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/TimeRangeLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/TimeRangeLevelNode.java index 466fd8bee5..e342f25578 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/TimeRangeLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/TimeRangeLevelNode.java @@ -24,16 +24,17 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.AggregateRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpaceMatcher; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpaceMatcher.MatchResult; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -69,56 +70,42 @@ public class TimeRangeLevelNode extends AbstractAliasLevelNode { this.dt = that.dt; } - public TimeRangeLevelNode(AbstractRequestableLevelNode sourceNode, + public TimeRangeLevelNode(AbstractRequestableNode sourceNode, DerivParamDesc desc, DerivParamMethod method, String modelName, - int startTime, int endTime, int dt, Level level) { + Integer startTime, int endTime, int dt, Level level) { super(sourceNode, desc, method, modelName, level); this.startTime = startTime; this.endTime = endTime; this.dt = dt; } - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - Set allTime = sourceNode.timeQuery(null, false); - Map> goodTimes = new HashMap>(); - Set timesToRequest = new HashSet(); - for (DataTime time : allTime) { - List neededTimes = calculateNeededTimes(time); - if (allTime.containsAll(neededTimes)) { - goodTimes.put(time, neededTimes); - timesToRequest.addAll(neededTimes); - } + TimeAndSpaceMatcher matcher = new TimeAndSpaceMatcher(); + matcher.setIgnoreRange(true); + Map dataMap = new HashMap(); + for (AbstractRequestableData data : dependencyData.get(sourceNode)) { + dataMap.put(data.getTimeAndSpace(), data); + } + Set records = new HashSet(); + for (TimeAndSpace ast : availability) { + Set needed = calculateNeededAvailability(ast); + Map matched = matcher.match(needed, + dataMap.keySet()); + if (TimeAndSpaceMatcher.getAll1(matched).containsAll(needed)) { + List dataList = new ArrayList(); + for (TimeAndSpace dataTime : TimeAndSpaceMatcher + .getAll2(matched)) { + dataList.add(dataMap.get(dataTime)); - } - property.setSelectedEntryTimes(timesToRequest - .toArray(new DataTime[timesToRequest.size()])); - Map> timeBins = new HashMap>(); - for (AbstractRequestableData record : sourceNode.getData(property, - timeOut, cache)) { - for (Entry> entry : goodTimes.entrySet()) { - if (entry.getValue().contains(record.getDataTime())) { - List records = timeBins.get(entry - .getKey()); - if (records == null) { - records = new ArrayList(entry - .getValue().size()); - timeBins.put(entry.getKey(), records); - } - records.add(record); } - } - } - List records = new ArrayList(); - for (Entry> entry : timeBins - .entrySet()) { - if (entry.getValue().size() == goodTimes.get(entry.getKey()).size()) { AggregateRequestableData newRecord = new AggregateRequestableData( - entry.getValue()); - newRecord.setDataTime(entry.getKey()); + dataList); + newRecord.setDataTime(ast.getTime()); + newRecord.setSpace(ast.getSpace()); modifyRequest(newRecord); records.add(newRecord); } @@ -127,31 +114,61 @@ public class TimeRangeLevelNode extends AbstractAliasLevelNode { } @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Set getAvailability( + Map> availability) throws VizException { - Set allTime = sourceNode.timeQuery(originalRequest, false, - cache, latestOnlyCache); - Set goodTimes = new HashSet(); - for (DataTime time : allTime) { - if (allTime.containsAll(calculateNeededTimes(time))) { - goodTimes.add(time); + TimeAndSpaceMatcher matcher = new TimeAndSpaceMatcher(); + matcher.setIgnoreRange(true); + Set allAvail = availability.get(sourceNode); + Set goodAvail = new HashSet(); + for (TimeAndSpace ast : allAvail) { + Set needed = calculateNeededAvailability(ast); + Set matchedNeeded = TimeAndSpaceMatcher + .getAll1(matcher.match(needed, allAvail)); + if (matchedNeeded.containsAll(needed)) { + goodAvail.add(ast); } } - return goodTimes; + return goodAvail; } - private List calculateNeededTimes(DataTime time) { - List times = new ArrayList(); - for (int i = time.getFcstTime() + this.startTime; i <= time - .getFcstTime() + this.endTime; i += dt) { - times.add(new DataTime(time.getRefTime(), i)); + @Override + public Map> getDataDependency( + Set availability, + AvailabilityContainer availabilityContainer) { + TimeAndSpaceMatcher matcher = new TimeAndSpaceMatcher(); + matcher.setIgnoreRange(true); + Set sourceAvailability = new HashSet( + availability); + for (TimeAndSpace ast : availability) { + Set needed = calculateNeededAvailability(ast); + Set matchedAvail = TimeAndSpaceMatcher + .getAll1(matcher.match(needed, availability)); + sourceAvailability.addAll(matchedAvail); } - return times; + Map> result = new HashMap>(); + result.put(sourceNode, sourceAvailability); + return result; + } + + @Override + public boolean isConstant() { + return super.isConstant(); + } + + private Set calculateNeededAvailability(TimeAndSpace ast) { + Set result = new HashSet(); + int start = dt; + if (startTime != null) { + start = ast.getTime().getFcstTime() + this.startTime; + } + for (int i = start; i <= ast.getTime().getFcstTime() + this.endTime; i += dt) { + DataTime time = new DataTime(ast.getTime().getRefTime(), i); + result.add(new TimeAndSpace(time, ast.getSpace())); + } + return result; } @Override diff --git a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/UnionLevelNode.java b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/UnionLevelNode.java index 4db0ae9216..fe525d6797 100644 --- a/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/UnionLevelNode.java +++ b/cave/com.raytheon.uf.viz.derivparam/src/com/raytheon/uf/viz/derivparam/tree/UnionLevelNode.java @@ -30,12 +30,11 @@ import java.util.Map.Entry; import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.AggregateRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; @@ -63,7 +62,7 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; * @author bsteffen * @version 1.0 */ -public class UnionLevelNode extends AbstractDerivedLevelNode { +public class UnionLevelNode extends AbstractDerivedDataNode { private static final Comparator requestComp = new Comparator() { @@ -76,21 +75,20 @@ public class UnionLevelNode extends AbstractDerivedLevelNode { }; - protected List nodes; + protected List nodes; public UnionLevelNode(UnionLevelNode that) { super(that); this.nodes = that.nodes; } - public UnionLevelNode(List nodes, - String modelName) { + public UnionLevelNode(List nodes, String modelName) { this.nodes = nodes; this.modelName = modelName; } public UnionLevelNode(Level level, String modelName, - List nodes) { + List nodes) { this.setLevel(level); this.nodes = nodes; this.modelName = modelName; @@ -98,43 +96,55 @@ public class UnionLevelNode extends AbstractDerivedLevelNode { public UnionLevelNode(Level level, DerivParamDesc desc, DerivParamMethod method, String modelName, - List nodes) { + List nodes) { super(level, desc, method, modelName); this.nodes = nodes; } @Override - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + public Map> getDataDependency( + Set availability, + AvailabilityContainer availabilityContainer) throws VizException { + Map> result = new HashMap>(); + for (AbstractRequestableNode node : nodes) { + result.put(node, availability); + } + return result; + } + + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { List rawRecords = new ArrayList(); - List requests = new ArrayList( + List requests = new ArrayList( nodes); - for (AbstractRequestableLevelNode request : requests) { - rawRecords.addAll(request.getData(property, timeOut, cache)); + for (AbstractRequestableNode request : requests) { + rawRecords.addAll(dependencyData.get(request)); } - Map> bins = new HashMap>(); + Map> bins = new HashMap>(); for (AbstractRequestableData record : rawRecords) { - List bin = bins.get(record.getDataTime()); + List bin = bins.get(record + .getTimeAndSpace()); if (bin == null) { bin = new ArrayList(); - bins.put(record.getDataTime(), bin); + bins.put(record.getTimeAndSpace(), bin); } bin.add(record); } - List records = new ArrayList( + Set records = new HashSet( bins.size()); - for (Entry> entry : bins + for (Entry> entry : bins .entrySet()) { if (entry.getValue().size() >= 2) { Collections.sort(entry.getValue(), requestComp); AggregateRequestableData newRecord = new AggregateRequestableData( entry.getValue()); - newRecord.setDataTime(entry.getKey()); + newRecord.setDataTime(entry.getKey().getTime()); + newRecord.setSpace(entry.getKey().getSpace()); modifyRequest(newRecord); records.add(newRecord); } @@ -143,49 +153,28 @@ public class UnionLevelNode extends AbstractDerivedLevelNode { } @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Set getAvailability( + Map> availability) throws VizException { - // Any time in results should have at least 2 nodes with that time - Set results = TIME_AGNOSTIC; - // Any time in single has at least one node available at that time - Set single = new HashSet(); - List requests = new ArrayList( + // things in one are available for one level + Set one = new HashSet(); + // things in two are available for two levels. + Set two = new HashSet(); + + List requests = new ArrayList( nodes); - for (AbstractRequestableLevelNode request : requests) { - Set times = request.timeQuery(originalRequest, - latestOnly, cache, latestOnlyCache); - if (times == TIME_AGNOSTIC) { - continue; - } else if (results == TIME_AGNOSTIC) { - results = new HashSet(); - single.addAll(times); - } else { - // We must have at least two resources with times. The first - // node with times will add only to single, after that any - // time in single will also be added to results - results.addAll(times); - results.retainAll(single); - single.addAll(times); + for (AbstractRequestableNode request : requests) { + // Do not request just latest only because if two nodes have + // different latests than this will return no times + for (TimeAndSpace time : availability.get(request)) { + if (one.contains(time)) { + two.add(time); + } else { + one.add(time); + } } } - return results; - } - - @Override - public boolean isTimeAgnostic() { - boolean timeAgnostic = true; - - for (AbstractRequestableLevelNode node : nodes) { - if (!node.isTimeAgnostic()) { - timeAgnostic = false; - break; - } - } - - return timeAgnostic; + return two; } /* @@ -197,7 +186,7 @@ public class UnionLevelNode extends AbstractDerivedLevelNode { @Override public List getDependencies() { List dependencies = new ArrayList(nodes.size()); - for (AbstractRequestableLevelNode node : nodes) { + for (AbstractRequestableNode node : nodes) { dependencies.add(new Dependency(node, 0)); } return dependencies; diff --git a/cave/com.raytheon.uf.viz.feature.alertviz/feature.xml b/cave/com.raytheon.uf.viz.feature.alertviz/feature.xml index a70d93f27b..93879e98bb 100644 --- a/cave/com.raytheon.uf.viz.feature.alertviz/feature.xml +++ b/cave/com.raytheon.uf.viz.feature.alertviz/feature.xml @@ -192,8 +192,7 @@ id="com.raytheon.uf.common.time" download-size="0" install-size="0" - version="0.0.0" - unpack="false"/> + version="0.0.0"/> + version="0.0.0"/> - + version="0.0.0" + unpack="false"/> + * @@ -64,11 +65,11 @@ import com.raytheon.viz.ui.perspectives.AbstractVizPerspectiveManager; public class LocalizationPerspectiveManager extends AbstractVizPerspectiveManager { - private static final transient IUFStatusHandler statusHandler = UFStatus + private static final IUFStatusHandler statusHandler = UFStatus .getHandler(LocalizationPerspectiveManager.class); /** The edit position restore map */ - private Map restoreMap = new HashMap(); + private final Map restoreMap = new HashMap(); public LocalizationPerspectiveManager() { saveEditors = true; diff --git a/cave/com.raytheon.uf.viz.monitor.fog/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.monitor.fog/META-INF/MANIFEST.MF index 90c7399aca..7df20694e4 100644 --- a/cave/com.raytheon.uf.viz.monitor.fog/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.monitor.fog/META-INF/MANIFEST.MF @@ -20,6 +20,7 @@ Require-Bundle: org.eclipse.ui, Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Import-Package: com.raytheon.uf.common.colormap -Export-Package: com.raytheon.uf.viz.monitor.fog.threshold, +Export-Package: com.raytheon.uf.viz.monitor.fog, + com.raytheon.uf.viz.monitor.fog.threshold, com.raytheon.uf.viz.monitor.fog.ui.resource, com.raytheon.uf.viz.monitor.fog.xml diff --git a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogCommonThreat.java b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogCommonThreat.java new file mode 100644 index 0000000000..2cf2c8a434 --- /dev/null +++ b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogCommonThreat.java @@ -0,0 +1,839 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.monitor.fog; + +import java.awt.Point; +import java.util.ArrayList; +import java.util.Map; + +import org.opengis.referencing.FactoryException; +import org.opengis.referencing.operation.TransformException; + +import com.raytheon.uf.common.dataplugin.fog.FogRecord; +import com.raytheon.uf.common.dataplugin.fog.FogRecord.FOG_THREAT; +import com.raytheon.uf.common.dataplugin.fog.analysis.FogCell; +import com.raytheon.uf.common.dataplugin.fog.analysis.FogDataCorrector; +import com.raytheon.uf.common.dataplugin.fog.analysis.FogMonitorUtils; +import com.raytheon.uf.common.geospatial.ReferencedCoordinate; +import com.raytheon.uf.common.geospatial.ReferencedObject.Type; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.viz.monitor.fog.xml.FogMonitorAlgorithmXML; +import com.vividsolutions.jts.algorithm.locate.SimplePointInAreaLocator; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.GeometryFactory; + +/** + * Common calculations of Fog threats for Fog and SAFESEAS monitors. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 13, 2012            skorolev     Initial creation
+ * 
+ * 
+ * + * @author skorolev + * @version 1.0 + */ + +public abstract class FogCommonThreat { + + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(FogCommonThreat.class); + + // /** list of coordinates for each zone **/ + // private Map> zoneCoordinates = null; + + /** GeometryFactory **/ + protected final GeometryFactory geoFactory = new GeometryFactory(); + + /** Fog record **/ + private FogRecord fog = null; + + /** Fog algorithm XML **/ + protected FogMonitorAlgorithmXML fogAlgXML = null; + + /** Geometry of adjacent areas **/ + protected Geometry geoAdjAreas = null; + + /** Fog threats as the colors **/ + private FOG_THREAT[] threats = null; + + /** Fog cells from satellites **/ + private ArrayList cells = null; + + /** IR thresholds **/ + private float[] ir_diff_thresholds = null; + + /** VIS thresholds **/ + private float[] vis_thresholds = null; + + /** Twilight angle offset **/ + protected int twilight_angle_offset = 0; + + /** boolean isSnowIce switch **/ + protected boolean isSnowIce = true; + + /** boolean isFractalDimension switch **/ + protected boolean isFractalDimension = true; + + /** boolean isSmoothness switch **/ + protected boolean isSmoothness = true; + + /** boolean isAdjacency switch **/ + protected boolean isAdjacency = true; + + /** Geometry of zones **/ + protected Map zoneGeos = null; + + /** + * This method will be called with the switches from the GUI front end + * + * Fog Product [T(10.7) - (T(3.9)] or VIS (normalized count) Maximum cloud + * temperature Daytime Ice/Snow vs Fog Threshold (c) (FogSnowIceFilter) Cool + * Fog vs Warm Surface threshold Daytime Smoothness Algorithm + * (FogSmoothnessFilter) Adjacency Threshold Twilight Angle Threshold + * Fractal Dimension Threshold (FogFractalFilter) + * + * Adds fog threat into Fog record. + * + * @param fog + * record + * @return fog record + */ + public FogRecord getFogThreat(FogRecord fog) { + this.fog = fog; + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.handle(Priority.DEBUG, + "Start analyzing Fog Threat..."); + } + long start = System.currentTimeMillis(); + // this.geoAdjAreas = getMonitor().getGeoAdjAreas(); + // clear threats array, make gray (SK)i=>x j=>y + for (int i = 0; i < fog.getNx(); i++) { + for (int j = 0; j < fog.getNy(); j++) { + getThreats()[fog.getNx() * j + i] = FOG_THREAT.GRAY; + } + } + + // First execute the data corrector, this divides up the FogRecord field + // into Day, Night, and Twilight. + FogDataCorrector fdc = new FogDataCorrector(getFog(), + fogAlgXML.getTwilightAngle()); + fog = fdc.execute(); + + // Second, core processor. Gets you the cells, sets non-filtered values. + executeCoreProcessor(); + + // Third, apply filters + for (FogCell cell : getCells()) { + // *********** APPLY FILTERS ******************* + + // Area Size filter + if (fogAlgXML.isAdjacencyThreshOn() + && cell.getCellThreat() != FOG_THREAT.GREEN + && cell.getCellThreat() != FOG_THREAT.GRAY) { + + if (cell.getArea() < fogAlgXML.getAdjacencyThresh()) { + setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); + } + } + + // Snow & Ice filter + if (fogAlgXML.isIceSnowVsFogOn() + && cell.getImageGroup() == FogRecord.IMAGE_GROUP.VIS_GROUP + && (cell.getCellThreat() != FOG_THREAT.GREEN || cell + .getCellThreat() != FOG_THREAT.GRAY)) { + + float tempMean = calAverageTemp(cell); + + if (tempMean < fogAlgXML.getIceSnowVsFog()) { + downgradeThreat(cell); + } + } + + // Smoothness filter + if (fogAlgXML.isDaytimeSmoothThreshOn() + && cell.getCellThreat() != FOG_THREAT.GREEN + || cell.getCellThreat() != FOG_THREAT.GRAY) { + + float tem_smoothness = calSmoothness(cell); + + if (tem_smoothness < fogAlgXML.getDaytimeSmoothThresh()) { + downgradeThreat(cell); + } + } + + // Fractal filter + if (fogAlgXML.isFractalDimensionOn() + && cell.getCellThreat() != FOG_THREAT.GREEN + && cell.getCellThreat() != FOG_THREAT.GRAY) { + + float temFD = calRegularity(cell); + + if (temFD > fogAlgXML.getFractalDimension() && temFD > 0.0f) { + setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); + } + } + + // We extract the zone threat differently than the GI filter + // Hence it is not needed. + } + + setThreats(); + setMonitorAreaThreats(); + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.handle( + Priority.DEBUG, + "Analyzed Fog Threat...Duration: " + + (System.currentTimeMillis() - start)); + } + return fog; + } + + /** + * Gets the zone threats (ALG) with worst case for zone area + * + * @return Map zoneThreats + */ + protected abstract void setMonitorAreaThreats(); + + /** + * Quick static method to get the float to threat mapping Convert threat + * color to float value + * + * @param threat + * color + * @return float value + */ + public static float getThreatValue(FOG_THREAT threat) { + float value = 0; + + if (threat == FOG_THREAT.BLACK) { + value = 0.0f; + } else if (threat == FOG_THREAT.GRAY) { + value = 15.0f; + } else if (threat == FOG_THREAT.GREEN) { + value = 60.0f; + } else if (threat == FOG_THREAT.YELLOW) { + value = 110.0f; + } else if (threat == FOG_THREAT.RED) { + value = 220.0f; + } + return value; + } + + /** + * Gets the existing threat value at that point + * + * @param i + * => y + * @param j + * => x + * @return threat at point + */ + public FOG_THREAT getThreat(int i, int j) { + return getThreats()[fog.getNx() * j + i]; + } + + /** + * Gets the drawable float array of threats + */ + private void setThreats() { + float[] floats = new float[getThreats().length]; + int i = 0; + for (FOG_THREAT threat : getThreats()) { + floats[i] = getThreatValue(threat); + i++; + } + getFog().setThreats(floats); + } + + // *********************** FILTERS **************************** // + /** + * NAME: CalRegularity(). + * + * TYPE: Private Member function. + * + * Description: Given a cell, calculate its regularity i.e. the fractal + * dimension Input Arguments: cell: The Fog_Cell whose fractal dimension is + * to be measured Output Arguments: Return float: fractal dimension. the + * value is between 1 to 2 smaller means more regular. Here use the + * perimeter and area relation to represent fractal dimension (one of the + * simply ways) History: May 2004 Qin Zeng (GDMB/MDL) -- created Dec 2009 D + * Hladky translated to Java + * + * + * + * @param cell + * @return fractalDimension + */ + private float calRegularity(FogCell cell) { + + int nx = cell.right - cell.left + 1; + int ny = cell.bottom - cell.top + 1; + int i; + boolean[] flag = new boolean[nx * ny]; + + for (i = 0; i < nx * ny; i++) { + flag[i] = false; + } + + int pixels_num = (int) cell.getArea(); + int flagPos; + for (i = 0; i < pixels_num; i++) { + Coordinate coor = cell.getPixelCoordinate(i); + flagPos = (int) ((coor.y - cell.top) * nx + coor.x - cell.left); + if (flagPos >= 0 && flagPos < nx * ny) { + flag[flagPos] = true; + } + } + // From here, perimeter of the fog cell will be calculated; + // |...| 1 |...| + // | 4 | 0 | 2 | + // |...| 3 |...| + // + // If the any of the 0's surrounding pixels(1,2,3,4) is flagged as + // false, + // which means that surrounding pixel(1,2,3,or 4) is not included in + // the cell, pixel 0 then will be at the edge of the cell cluster. + // And the edge connecting to the outside pixel will be counted into the + // perimeter of the cell cluster. + + int pos1, pos2, pos3, pos4; + float perimeter = 0; + for (i = 0; i < pixels_num; i++) { + Coordinate coor = cell.getPixelCoordinate(i); + + pos1 = (int) ((i - cell.top - 1) * nx + coor.y - cell.left); + if (pos1 >= 0 && pos1 < nx * ny && !flag[pos1] + || i - coor.x < cell.top) { + perimeter++; + } + + pos2 = (int) ((coor.y - cell.top) * nx + coor.x + 1 - cell.left); + if (pos2 >= 0 && pos2 < nx * ny && !flag[pos2] + || coor.x + 1 > cell.right) { + perimeter++; + } + + pos3 = (int) ((coor.y - cell.top + 1) * nx + coor.x - cell.left); + if (pos3 >= 0 && pos3 < nx * ny && !flag[pos3] + || coor.y + 1 > cell.bottom) { + perimeter++; + } + + pos4 = (int) ((coor.y - cell.top) * nx + coor.x - 1 - cell.left); + if (pos4 >= 0 && pos4 < nx * ny && !flag[pos4] + || coor.x - 1 < cell.left) { + perimeter++; + } + } + + float fractalDimension = 1.0f; + + if (cell.getArea() != 1) { + fractalDimension = (float) (2 * Math.log(perimeter / 4.0) / Math + .log(cell.getArea())); + } + + // Note : fractalDimension is a data between 1 and 2 and the larger + // fractalDimension is , the more irregular the shape of the cell will + // be. + + return fractalDimension; + } + + /** + * NAME: CalSmoothness(). + * + * TYPE: Private Member function. + * + * Description: Given a cell, calculate the its smoothness Input Arguments: + * cell: The Fog_Cell whose smoothness is to be measured Output Arguments: + * return float: smoothness defined above History: May 2004 Qin Zeng + * (GDMB/MDL) -- created Dec 2009 D Hladky ported to AWIPS II + * + * @param cell + * @return smoothness + **/ + private float calSmoothness(FogCell cell) { + + float mean = 0; // mean grayscale value of pixels in the cell from VIS. + float stdDev = 0; // standard deviation + int pixels_num = (int) cell.getArea(); + + if (pixels_num == 0) { + return 0; + } + + int i; + for (i = 0; i < pixels_num; i++) { + Coordinate pixr = cell.getPixelRelativeCoordinate(i); + mean += getFog().getVisArray()[(int) (getFog().getNx() * pixr.y + pixr.x)]; + } + + mean /= pixels_num; + float tem_float; + + for (i = 0; i < pixels_num; i++) { + Coordinate pixr = cell.getPixelRelativeCoordinate(i); + tem_float = getFog().getVisArray()[(int) (getFog().getNx() * pixr.y + pixr.x)]; + stdDev += (tem_float - mean) * (tem_float - mean); + } + + stdDev /= pixels_num; + stdDev = (float) Math.sqrt(stdDev); + // mean should not be zero, so no need to check mean here. + return (1 - stdDev / mean) * 100; // use percent as unit + } + + /** + * NAME: Cal(). + * + * TYPE: Private Member function. + * + * Description: Calculate the average temperature for a Fog_Cell in channel + * 3.9 um History: May 2004 Qin Zeng (GDMB/MDL) -- created + * + * @param cell + * @return average temperature + */ + private float calAverageTemp(FogCell cell) { + float mean = 0; // mean temperature value of pixels in the cell. + int pixels_num = (int) cell.getArea(); + if (pixels_num == 0) { + return -999.9f; + } + for (int i = 0; i < pixels_num; i++) { + Coordinate pixc = cell.getPixelRelativeCoordinate(i); + mean += temp_at_vis_pixel(new Point((int) pixc.x, (int) pixc.y), + FogRecord.CHANNEL.IR3_9); + } + + mean /= pixels_num; + return mean; + } + + /** + * Get the temp at the pixel + * + * @param pointVis + * @param channel + * @return + */ + private float temp_at_vis_pixel(Point pointVis, FogRecord.CHANNEL channel) { + // The assumption is that Dimensions of IR4 and IR2 are the same. + // IR4 data will be always needed, so attributes for IR4 shall be + // always available. + // **** ATTENTION ***** We have made the vis the same as well for AWIPS + // II + int count_value = 255; + if (channel == FogRecord.CHANNEL.IR3_9) { + count_value = fog.getIR_3_9Array()[fog.getNx() * pointVis.y + + pointVis.x]; + } else if (channel == FogRecord.CHANNEL.IR10_7) { + count_value = fog.getIR_10_7Array()[fog.getNx() * pointVis.y + + pointVis.x]; + } + return FogMonitorUtils.count2temp(count_value, channel); + } + + /** + * NAME: Execute(). + * + * TYPE: Private Member function. + * + * Description: Based on the thresholds of the VIS image data and the IR + * image data, a number of patches of the contiguous suspected fog areas + * will be extracted from the satellite image data. This is an + * implementation of the feature extraction algorithm based on the + * contiguous gray scale values. + * + * Arguments: None History: March 2004 Qin Zeng (GDMB/MDL) -- created Dec + * 2009 D Hladky ported to Java for AWIPS II + * + * + * Calculates cells parameters + */ + private void executeCoreProcessor() { + + cells = new ArrayList(); + ArrayList parent = new ArrayList(); + ArrayList child = new ArrayList(); + ArrayList single_segment = new ArrayList(); + + int x_dim = getFog().getNx(); + int y_dim = getFog().getNy(); + int i; // (SK) x + int j; // (SK) y + // To flag whether a pixel has been visited or not + boolean[][] visited = new boolean[x_dim][y_dim]; + + Point[] surroundPts = new Point[8]; // 8 surrounding points of one + // specific point + for (int z = 0; z < surroundPts.length; z++) { + surroundPts[z] = new Point(); + } + + Point tempoint = new Point(); + getCells().clear(); + + for (i = 0; i < x_dim; i++) { + for (j = 0; j < y_dim; j++) { + visited[i][j] = false; + } + } + for (j = 0; j < y_dim; j++) { + Point firstone = new Point(); + FOG_THREAT threat_level = FOG_THREAT.BLACK; + FogRecord.IMAGE_GROUP imggroup; + for (i = 0; i < x_dim; i++) { + if (visited[i][j]) { + continue; + } + Coordinate cellCoor = this.getCellCoor(i, j); + visited[i][j] = true; + imggroup = getFog().findGroup(i, j); + threat_level = getThreatLevel(i, j, imggroup); + // Sets the initial threat level + setThreat(i, j, threat_level); + firstone.x = i; + firstone.y = j; + parent.clear(); + tempoint.y = j; + tempoint.x = i; + single_segment.add(tempoint); + parent.add(tempoint); + while (parent.size() != 0) { + // the variables(surroundPts[1],surroundPts[2]...) below + // mean surrounding 1,2 + // | 0 | 1 | 2 | + // | 7 | i | 3 | + // | 6 | 5 | 4 | + // iteratively search the 8-connected surrounding pixels + child.clear(); + for (int k = 0; k < parent.size(); k++) { + // y's too small, too big + if (parent.get(k).y == 0) { + surroundPts[0].y = parent.get(k).y; + surroundPts[1].y = parent.get(k).y; + surroundPts[2].y = parent.get(k).y; + } + if (parent.get(k).y == y_dim - 1) { + surroundPts[4].y = parent.get(k).y; + surroundPts[5].y = parent.get(k).y; + surroundPts[6].y = parent.get(k).y; + } + // x's too small, too big + if (parent.get(k).x == 0) { + surroundPts[0].x = parent.get(k).x; + surroundPts[6].x = parent.get(k).x; + surroundPts[7].x = parent.get(k).x; + } + if (parent.get(k).x == x_dim - 1) { + surroundPts[2].x = parent.get(k).x; + surroundPts[3].x = parent.get(k).x; + surroundPts[4].x = parent.get(k).x; + } + // all others + if (parent.get(k).x > 0 && parent.get(k).x < x_dim - 1 + && parent.get(k).y < y_dim - 1 + && parent.get(k).y > 0) { + surroundPts[0].y = parent.get(k).y - 1; + surroundPts[0].x = parent.get(k).x - 1; + surroundPts[1].y = parent.get(k).y - 1; + surroundPts[1].x = parent.get(k).x; + surroundPts[2].y = parent.get(k).y - 1; + surroundPts[2].x = parent.get(k).x + 1; + surroundPts[3].y = parent.get(k).y; + surroundPts[3].x = parent.get(k).x + 1; + surroundPts[4].y = parent.get(k).y + 1; + surroundPts[4].x = parent.get(k).x + 1; + surroundPts[5].y = parent.get(k).y + 1; + surroundPts[5].x = parent.get(k).x; + surroundPts[6].y = parent.get(k).y + 1; + surroundPts[6].x = parent.get(k).x - 1; + surroundPts[7].y = parent.get(k).y; + surroundPts[7].x = parent.get(k).x - 1; + } + FogRecord.IMAGE_GROUP temgroup; + FOG_THREAT temthreat; + + for (int m = 0; m < 8; m++) { + if (surroundPts[m].y >= 0 + && surroundPts[m].y < y_dim + && surroundPts[m].x >= 0 + && surroundPts[m].x < x_dim) { + int ii = surroundPts[m].x; + int jj = surroundPts[m].y; + + if (!visited[ii][jj]) { + temgroup = getFog().findGroup(ii, jj); + temthreat = getThreatLevel(ii, jj, temgroup); + if (temgroup == imggroup + && temthreat == threat_level) { + child.add(surroundPts[m]); + visited[ii][jj] = true; + single_segment.add(surroundPts[m]); + } + }// end of if + }// end of if + }// end of for m + }// end of for k + parent = child; + }// end of while + + int lct = SimplePointInAreaLocator.locate(cellCoor, + this.geoAdjAreas); + if (lct == 2) { + threat_level = FOG_THREAT.BLACK; + setThreat(i, j, threat_level); + } + getCells().add( + new FogCell(single_segment, threat_level, imggroup)); + single_segment.clear(); + } // end of for i + } // end of for j + } + + /** + * Gets geo coordinates of cell + * + * @param i + * => y + * @param j + * => x + * @return crd + */ + private Coordinate getCellCoor(int i, int j) { + ReferencedCoordinate rc = new ReferencedCoordinate( + new Coordinate(i, j), this.getFog().getGridGeometry(), + Type.GRID_CENTER); + Coordinate crd = null; + try { + crd = rc.asLatLon(); + } catch (TransformException e) { + statusHandler.handle(Priority.ERROR, e.getMessage()); + } catch (FactoryException e) { + statusHandler.handle(Priority.ERROR, e.getMessage()); + } + return crd; + } + + /** + * Set fog threat at threat level point + * + * @param i + * => y + * @param j + * => x + * @param threat + */ + private void setThreat(int i, int j, FOG_THREAT threat) { + getThreats()[fog.getNx() * j + i] = threat; + } + + /** + * Remember J is X and I is Y, totally against convention! Gets the threat + * level + * + * @param i + * (SK y) + * @param j + * (SK x) + * @param group + * @return threat level as color + */ + private FOG_THREAT getThreatLevel(int i, int j, FogRecord.IMAGE_GROUP group) { + // (SK) i=>x, j=>y + // default return + FOG_THREAT returnValue = FOG_THREAT.GRAY; + int idx = fog.getNx() * j + i; + switch (group) { + case VIS_GROUP: + float ir4_temp = bTemp(i, j, FogRecord.CHANNEL.IR10_7); + int CLOUD_FREE_BRIGHTNESS = 68; // empirical value + // Too cold + if (ir4_temp < fogAlgXML.getMaxCloudTemp()) { + returnValue = FOG_THREAT.GRAY; + } + // overlapping high/middle cloud + + else if (fog.getVisArray()[idx] <= vis_thresholds[2] + && fog.getVisArray()[idx] >= vis_thresholds[1]) { + + returnValue = FOG_THREAT.RED; + } else if (fog.getVisArray()[idx] < vis_thresholds[1] + && fog.getVisArray()[idx] >= vis_thresholds[0] + || fog.getVisArray()[idx] <= vis_thresholds[3] + && fog.getVisArray()[idx] > vis_thresholds[2]) { + + returnValue = FOG_THREAT.YELLOW; + } + + // This is essentially the Cool Fog vs. Warm surface threshold check + else if (fogAlgXML.isCoolFogVsWarmSurfaceOn() + && ir4_temp >= fogAlgXML.getCoolFogVsWarmSurface()) { + returnValue = FOG_THREAT.GREEN; + } + + else if (fog.getVisArray()[idx] < CLOUD_FREE_BRIGHTNESS) { + returnValue = FOG_THREAT.GREEN; + } + + return returnValue; + + case IR_GROUP: + // for some odd reason j is x and i is y, + // not sure why AWIPS 1 does it this way. + // It is completely against convention. + // Point tempoint = new Point(j, i); + // (SK) here i=>x and j=>y + Point tempoint = new Point(i, j); + float tempIR10_7 = temp_at_vis_pixel(tempoint, + FogRecord.CHANNEL.IR10_7); + if (tempIR10_7 < fogAlgXML.getMaxCloudTemp()) { + // Too cold + returnValue = FOG_THREAT.GRAY; + } + // Overlapping high/middle cloud + float tempIR3_9 = temp_at_vis_pixel(tempoint, + FogRecord.CHANNEL.IR3_9); + float tempDiff = tempIR10_7 - tempIR3_9; + + if (tempDiff <= ir_diff_thresholds[2] + && tempDiff >= ir_diff_thresholds[1]) { + returnValue = FOG_THREAT.RED; + } else if (tempDiff < ir_diff_thresholds[1] + && tempDiff >= ir_diff_thresholds[0] + || tempDiff <= ir_diff_thresholds[3] + && tempDiff > ir_diff_thresholds[2]) { + returnValue = FOG_THREAT.YELLOW; + } else { + returnValue = FOG_THREAT.GREEN; + } + + case TWILIGHT_GROUP: + // do nothing, stays gray + } + return returnValue; + } + + /** + * Precursor call to get temp at pixel + * + * @param i + * => y + * @param j + * => x + * @param imgtype + * @return temperature at the pixel + */ + private float bTemp(int i, int j, FogRecord.CHANNEL imgtype) { + // (SK) here i=>x and j=>y + // for some odd reason j is x and i is y, + // not sure why AWIPS 1 does it this way. + // It is completely against convention. + + Point tempoint = new Point(i, j); + return temp_at_vis_pixel(tempoint, imgtype); + } + + /** + * Downgrade the Fog Threat in the cell + * + * @param cell + */ + private void downgradeThreat(FogCell cell) { + if (cell.getCellThreat() == FOG_THREAT.YELLOW) { + setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); + } else if (cell.getCellThreat() == FOG_THREAT.RED) { + setCellThreats(cell.getPoints(), FOG_THREAT.YELLOW); + } + } + + /** + * Sets the thresholds + */ + protected void setThresholdArrays() { + ir_diff_thresholds = new float[4]; + vis_thresholds = new float[4]; + + ir_diff_thresholds[0] = (float) fogAlgXML.getFogProductYLo(); + ir_diff_thresholds[1] = (float) fogAlgXML.getFogProductYHi(); + ir_diff_thresholds[2] = (float) fogAlgXML.getFogProductRLo(); + ir_diff_thresholds[3] = (float) fogAlgXML.getFogProductRHi(); + + vis_thresholds[0] = (float) fogAlgXML.getVisYLo(); + vis_thresholds[1] = (float) fogAlgXML.getVisYHi(); + vis_thresholds[2] = (float) fogAlgXML.getVisRLo(); + vis_thresholds[3] = (float) fogAlgXML.getVisRHi(); + } + + /** + * Sets all points in the cell to the cell filtered value threat + * + * @param points + * @param threat + */ + private void setCellThreats(ArrayList points, FOG_THREAT threat) { + for (Point point : points) { + getThreats()[fog.getNx() * point.y + point.x] = threat; + } + } + + /** + * Gets the cells of this analysis + * + * @return cells + */ + private ArrayList getCells() { + return cells; + } + + /** + * Gets the fog record + * + * @return + */ + public FogRecord getFog() { + return fog; + } + + /** + * Gets the existing array of threats + * + * @return threats in color + */ + public FOG_THREAT[] getThreats() { + if (threats == null) { + threats = new FOG_THREAT[getFog().getNx() * getFog().getNy()]; + } + return threats; + } + +} diff --git a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogDataGenerator.java b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogDataGenerator.java index be6ab17095..539431bd18 100644 --- a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogDataGenerator.java +++ b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogDataGenerator.java @@ -21,8 +21,10 @@ package com.raytheon.uf.viz.monitor.fog; import java.util.Date; import java.util.HashMap; +import java.util.Map; import com.raytheon.uf.common.dataplugin.fog.FogRecord; +import com.raytheon.uf.common.dataplugin.fog.FogRecord.FOG_THREAT; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.CommonTableConfig; import com.raytheon.uf.common.monitor.data.CommonTableConfig.CellType; @@ -36,156 +38,223 @@ import com.raytheon.uf.viz.monitor.fog.threshold.FogThresholdMgr; import com.raytheon.uf.viz.monitor.util.MonitorConfigConstants; /** -* Generate Data for Fog Dialogs -* -*
-* 
-* SOFTWARE HISTORY
-* 
-* Date         Ticket#     Engineer    Description
-* ------------ ----------  ----------- --------------------------
-* 12/07/09                  dhladky    Initial Creation.
-* 
-* 
-* -* @author dhladky -* -*/ + * Generate Data for Fog Dialogs + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * 12/07/09                  dhladky    Initial Creation.
+ * Oct.29, 2012 1297         skorolev   Changed HashMap to Map
+ * Oct.31, 2012 1297         skorolev   Clean code
+ * 
+ * 
+ * + * @author dhladky + * + */ public class FogDataGenerator { - private CommonTableConfig ctc; - private FogThresholdMgr ftm; - - public FogDataGenerator() - { - ctc = CommonTableConfig.getInstance(); - ftm = FogThresholdMgr.getInstance(); - - } - - /** - * Generates the zone fog data for table - * @param tableData - * @return - */ - public TableData generateZoneData(ObsData obsData, HashMap algThreats, Date date) - { - //TODO: in the future use the data passed to get the nominal time - // closest for display in table and CAVE rendering. - TableData fogTableData = new TableData(CommonConfig.AppName.FOG); - if (obsData != null) { - for (String zone: obsData.getContainer().keySet()) { - addZoneRow(zone, obsData.getArea(zone).getBestAreaReport(date), algThreats.get(zone), fogTableData); - } - } + private CommonTableConfig ctc; - return fogTableData; + private FogThresholdMgr ftm; + + /** + * Generates Fog data + */ + public FogDataGenerator() { + ctc = CommonTableConfig.getInstance(); + ftm = FogThresholdMgr.getInstance(); + } + + /** + * Generates the zone fog data for table + * + * @param obsData + * @param algThreats + * @param date + * @return fogTableData + */ + public TableData generateZoneData(ObsData obsData, + Map algThreats, Date date) { + // TODO: in the future use the data passed to get the nominal time + // closest for display in table and CAVE rendering. + TableData fogTableData = new TableData(CommonConfig.AppName.FOG); + if (obsData != null) { + for (String zone : obsData.getContainer().keySet()) { + addZoneRow(zone, obsData.getArea(zone).getBestAreaReport(date), + algThreats.get(zone), fogTableData); + } } - /** - * Creates a Zone table row - * @param report - * @param td - */ - private void addZoneRow(String zone, ObReport report, FogRecord.FOG_THREAT threat, TableData td) - { - TableRowData trd = new TableRowData(ctc.getTableColumnKeys(CommonConfig.AppName.FOG).length); + return fogTableData; + } - trd.setTableCellData(0, new TableCellData(zone, - zone, CellType.AreaId, false)); - - trd.setTableCellData(1, new TableCellData(new Float(report - .getVisibility()).intValue(),ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_VIS.getXmlKey(), report.getVisibility()), true)); + /** + * Creates a Zone table row + * + * @param zone + * @param report + * @param threat + * @param td + */ + private void addZoneRow(String zone, ObReport report, + FogRecord.FOG_THREAT threat, TableData td) { + TableRowData trd = new TableRowData( + ctc.getTableColumnKeys(CommonConfig.AppName.FOG).length); - trd.setTableCellData(2, new TableCellData(report.getPresentWx(), zone, CellType.NotMonitored, false)); + trd.setTableCellData(0, new TableCellData(zone, zone, CellType.AreaId, + false)); - trd.setTableCellData(3, new TableCellData(new Float(report - .getCeiling()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_CEILING.getXmlKey(), report.getCeiling()), true)); - - trd.setTableCellData(4, new TableCellData(new Float(report - .getWindDir()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_DIR_FROM.getXmlKey(), report - .getWindDir()), true)); - - trd.setTableCellData(5, new TableCellData(new Float(report - .getWindSpeed()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_WIND_SPEED.getXmlKey(), report - .getWindSpeed()), true)); - - trd.setTableCellData(6, new TableCellData(new Float(report - .getMaxWindSpeed()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_PEAK_WIND.getXmlKey(), report - .getMaxWindSpeed()), true)); - - trd.setTableCellData(7, new TableCellData(new Float(report - .getWindGust()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_GUST_SPEED.getXmlKey(), report - .getWindGust()), true)); - - trd.setTableCellData(8, new TableCellData(new Float(report - .getTemperature()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_TEMP.getXmlKey(), report - .getTemperature()), true)); - - trd.setTableCellData(9, new TableCellData(new Float(report - .getDewpoint()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_DEWPT.getXmlKey(), report - .getDewpoint()), true)); - - trd.setTableCellData(10, new TableCellData(new Float(report - .getDewpointDepr()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_T_TD.getXmlKey(), report - .getDewpointDepr()), true)); - - trd.setTableCellData(11, new TableCellData(new Float(report - .getRelativeHumidity()).intValue(), ftm.getThresholdValueCellType(DataUsageKey.DISPLAY, zone, MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_REL_HUMIDITY.getXmlKey(), - report.getRelativeHumidity()), true)); - - trd.setTableCellData(12, new TableCellData("", zone, getAlgorithmCellType(threat), true)); + trd.setTableCellData( + 1, + new TableCellData( + new Float(report.getVisibility()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_VIS + .getXmlKey(), report.getVisibility()), + true)); - td.addReplaceDataRow(trd); + trd.setTableCellData(2, new TableCellData(report.getPresentWx(), zone, + CellType.NotMonitored, false)); + + trd.setTableCellData( + 3, + new TableCellData( + new Float(report.getCeiling()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_CEILING + .getXmlKey(), report.getCeiling()), + true)); + + trd.setTableCellData( + 4, + new TableCellData( + new Float(report.getWindDir()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_DIR_FROM + .getXmlKey(), report.getWindDir()), + true)); + + trd.setTableCellData( + 5, + new TableCellData( + new Float(report.getWindSpeed()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_WIND_SPEED + .getXmlKey(), report.getWindSpeed()), + true)); + + trd.setTableCellData( + 6, + new TableCellData( + new Float(report.getMaxWindSpeed()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_PEAK_WIND + .getXmlKey(), report.getMaxWindSpeed()), + true)); + + trd.setTableCellData( + 7, + new TableCellData( + new Float(report.getWindGust()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_WIND_GUST_SPEED + .getXmlKey(), report.getWindGust()), + true)); + + trd.setTableCellData( + 8, + new TableCellData( + new Float(report.getTemperature()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_TEMP + .getXmlKey(), report.getTemperature()), + true)); + + trd.setTableCellData( + 9, + new TableCellData( + new Float(report.getDewpoint()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_DEWPT + .getXmlKey(), report.getDewpoint()), + true)); + + trd.setTableCellData( + 10, + new TableCellData(new Float(report.getDewpointDepr()) + .intValue(), ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_T_TD + .getXmlKey(), report.getDewpointDepr()), true)); + + trd.setTableCellData( + 11, + new TableCellData( + new Float(report.getRelativeHumidity()).intValue(), + ftm.getThresholdValueCellType( + DataUsageKey.DISPLAY, + zone, + MonitorConfigConstants.FogDisplay.FOG_DISP_METEO_REL_HUMIDITY + .getXmlKey(), report + .getRelativeHumidity()), true)); + + trd.setTableCellData(12, new TableCellData("", zone, + getAlgorithmCellType(threat), true)); + + td.addReplaceDataRow(trd); + } + + /** + * Get threat cells type + * + * @param threat + * @return type + */ + public CellType getAlgorithmCellType(FogRecord.FOG_THREAT threat) { + CellType type = CellType.NotDetermined; + if (threat == FogRecord.FOG_THREAT.GREEN) { + type = CellType.G; + } else if (threat == FogRecord.FOG_THREAT.YELLOW) { + type = CellType.Y; + } else if (threat == FogRecord.FOG_THREAT.RED) { + type = CellType.R; } - - //******************************************************************************************* - //******************************************************************************************* - //******************************************************************************************* - //******************************************************************************************* - //******************************************************************************************* - - public TableData generateObsHistData(CommonConfig.AppName appName, CommonTableConfig.ObsHistType obsType) - { - TableData tData = new TableData(appName); + return type; + } - System.out.println("Creating data for: " + appName.name() + " and " + obsType.name()); - - if (appName == CommonConfig.AppName.SAFESEAS) - { - // Create Safeseas Data - } - - else if (appName == CommonConfig.AppName.FOG) - { - // Create Fog Data - } - - return tData; - } - - - public CellType getAlgorithmCellType(FogRecord.FOG_THREAT threat) { - CellType type = CellType.NotDetermined; - if (threat == FogRecord.FOG_THREAT.GREEN) { - type = CellType.G; - } - else if (threat == FogRecord.FOG_THREAT.YELLOW) { - type = CellType.Y; - } - else if (threat == FogRecord.FOG_THREAT.RED) { - type = CellType.R; - } - return type; - } - - public HashMap getAlgCellTypes(HashMap algThreats) { - HashMap types = new HashMap(); - for (String zone : algThreats.keySet()) { - CellType type = getAlgorithmCellType(algThreats.get(zone)); - types.put(zone, type); - } - return types; + /** + * Get threat types + * + * @param map + * @return types + */ + public Map getAlgCellTypes(Map map) { + Map types = new HashMap(); + for (String zone : map.keySet()) { + CellType type = getAlgorithmCellType(map.get(zone)); + types.put(zone, type); } + return types; + } } diff --git a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogMonitor.java b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogMonitor.java index fd83906249..f5b359411d 100644 --- a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogMonitor.java +++ b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/FogMonitor.java @@ -23,7 +23,8 @@ import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; -import java.util.Set; +import java.util.List; +import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import java.util.regex.Pattern; @@ -40,15 +41,15 @@ import com.raytheon.uf.common.monitor.MonitorAreaUtils; import com.raytheon.uf.common.monitor.config.FogMonitorConfigurationManager; import com.raytheon.uf.common.monitor.data.AdjacentWfoMgr; import com.raytheon.uf.common.monitor.data.CommonConfig; -import com.raytheon.uf.common.monitor.data.ObConst.ChosenAppKey; -import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.viz.core.alerts.AlertMessage; import com.raytheon.uf.viz.core.localization.LocalizationManager; import com.raytheon.uf.viz.core.notification.NotificationMessage; import com.raytheon.uf.viz.monitor.IMonitor; import com.raytheon.uf.viz.monitor.Monitor; import com.raytheon.uf.viz.monitor.ObsMonitor; -import com.raytheon.uf.viz.monitor.data.AreaContainer; import com.raytheon.uf.viz.monitor.data.MonitoringArea; import com.raytheon.uf.viz.monitor.data.ObMultiHrsReports; import com.raytheon.uf.viz.monitor.data.ObReport; @@ -81,6 +82,8 @@ import com.vividsolutions.jts.geom.Geometry; * 11/30/2009 3424 Zhidong/Slav/Wen Adds stationTableData to keep station info. * May 15, 2012 14510 zhao Modified processing at startup * Jun 16, 2012 14386 zhao Auto update County/Zone Table when new fog threat data arrives + * Oct 26, 2012 1280 skorolev Made changes for non-blocking dialog and changed HashMap to Map + * Oct.31 2012 1297 skorolev Clean code * * * @@ -91,6 +94,9 @@ import com.vividsolutions.jts.geom.Geometry; public class FogMonitor extends ObsMonitor implements IFogResourceListener { + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(FogMonitor.class); + /** Singleton instance of this class */ private static FogMonitor monitor = null; @@ -102,59 +108,62 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { private ObMultiHrsReports obData; /** data holder for FOG **/ - public ObsData obsData = null; + private ObsData obsData = null; - public ArrayList resourceTimes = null; + /** data holder for FOG ALG data **/ + private SortedMap> algorithmData = null; - /** data holder for FOG Algo data **/ - //public HashMap> algorithmData = null; - public SortedMap> algorithmData = null; - - public Date dialogTime = null; + private Date dialogTime = null; /** list of coordinates for each zone **/ - public HashMap zoneGeometries = null; + private Map zoneGeometries = null; /** zone table dialog **/ - public FogZoneTableDlg zoneDialog = null; + private FogZoneTableDlg zoneDialog; /** zone table dialog **/ - public MonitoringAreaConfigDlg areaDialog = null; + private MonitoringAreaConfigDlg areaDialog = null; /** area config manager **/ - public FogMonitorConfigurationManager fogConfig = null; - - /** The application key */ - ChosenAppKey chosenAppKey = ChosenAppKey.FOG; + private FogMonitorConfigurationManager fogConfig = null; /** table data for the station table **/ private final TableData stationTableData = new TableData( CommonConfig.AppName.FOG); - /** All FOG's plugs start with this **/ - private static String OBS = "fssobs"; + /** All FOG's datauri start with this **/ + private final String OBS = "fssobs"; - /** Array of fogAlg listeners **/ - private final ArrayList fogResources = new ArrayList(); + /** List of fogAlg listeners **/ + private final List fogResources = new ArrayList(); - /** regex wild card filter */ - protected static String wildCard = "[\\w\\(\\)\\-_:.]+"; + /** regex wild card filter **/ + private final String wildCard = "[\\w\\(\\)\\-_:.]+"; + + /** Geometry of adjacent areas **/ + private Geometry geoAdjAreas = null; + + /** Data URI pattern for fog **/ + private final Pattern fogPattern = Pattern.compile(URIFilter.uriSeperator + + OBS + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator + + wildCard + URIFilter.uriSeperator + cwa + URIFilter.uriSeperator + + wildCard + URIFilter.uriSeperator + wildCard + + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator + + "fog"); - public Geometry geoAdjAreas = null; - /** * Private constructor, singleton */ private FogMonitor() { - pluginPatterns.add(fogPattern); + pluginPatterns.add(fogPattern); readTableConfig(MonitorThresholdConfiguration.FOG_THRESHOLD_CONFIG); - initObserver("fssobs", this); + initObserver(OBS, this); } /** * Static factory * - * @return + * @return fog monitor */ public static synchronized FogMonitor getInstance() { if (monitor == null) { @@ -162,26 +171,26 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { // Pre-populate dialog with an observations from DB monitor.createDataStructures(); monitor.getAdjAreas(); - monitor.processProductAtStartup("fog"); - monitor.fireMonitorEvent(monitor); - } + monitor.processProductAtStartup("fog"); + monitor.fireMonitorEvent(monitor); + } return monitor; } + // TODO: Provide the changes in EDEX URIFilters when area configuration file + // has been changed. /** - * DR#11279: - * When monitor area configuration is changed, - * this module is called to re-initialize monitor - * using new monitor area configuration + * DR#11279: When monitor area configuration is changed, this module is + * called to re-initialize monitor using new monitor area configuration */ public static void reInitialize() { - if ( monitor != null ) { - monitor = null; - monitor = new FogMonitor(); - } + if (monitor != null) { + monitor = null; + monitor = new FogMonitor(); + } } - + /** * Creates the maps */ @@ -191,31 +200,49 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { obData.setThresholdMgr(FogThresholdMgr.getInstance()); obsData = new ObsData(); - algorithmData = new TreeMap>(); + algorithmData = new TreeMap>(); for (String zone : MonitoringArea.getPlatformMap().keySet()) { obsData.addArea(zone, MonitoringArea.getPlatformMap().get(zone)); } } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#filterNotifyMessage(com.raytheon + * .uf.viz.core.notification.NotificationMessage) + */ @Override public boolean filterNotifyMessage(NotificationMessage alertMessage) { - return false; } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processNotifyMessage(com.raytheon + * .uf.viz.core.notification.NotificationMessage) + */ @Override public void processNotifyMessage(NotificationMessage filtered) { - + // Not used } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processProductMessage(com.raytheon + * .uf.viz.core.alerts.AlertMessage) + */ @Override public void processProductMessage(final AlertMessage filtered) { - if (fogPattern.matcher(filtered.dataURI).matches()) { - // System.out.println("Found match: " + fogPattern + " URI: " - // + filtered.dataURI); - processURI(filtered.dataURI, filtered); - } + if (fogPattern.matcher(filtered.dataURI).matches()) { + processURI(filtered.dataURI, filtered); + } } /** @@ -226,8 +253,8 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { * -- the xml configuration filename */ public void readTableConfig(String file) { - // TODO update for Maritime - HashMap> zones = new HashMap>(); + // TODO update for Maritime + Map> zones = new HashMap>(); // create zones and stations list try { FogMonitorConfigurationManager areaConfig = getMonitorAreaConfig(); @@ -247,16 +274,36 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { MonitoringArea.setPlatformMap(zones); } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.Monitor#initObserver(java.lang.String, + * com.raytheon.uf.viz.monitor.Monitor) + */ @Override public void initObserver(String pluginName, Monitor monitor) { ProductAlertObserver.addObserver(pluginName, this); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#thresholdUpdate(com.raytheon.uf + * .viz.monitor.events.IMonitorThresholdEvent) + */ @Override public void thresholdUpdate(IMonitorThresholdEvent me) { fireMonitorEvent(zoneDialog.getClass().getName()); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#configUpdate(com.raytheon.uf.viz + * .monitor.events.IMonitorConfigurationEvent) + */ @Override public void configUpdate(IMonitorConfigurationEvent me) { fireMonitorEvent(zoneDialog.getClass().getName()); @@ -267,89 +314,49 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { */ @Override public void nullifyMonitor() { - // /** - // * Before making the monitor null, remove observers - // */ - // for (String p : pluginName) { - // if (!pluginName.equals("")) { - // stopObserver(p, this); - // } - // } - - // monitor.fogResources.removeAll(getMonitorListeners()); - ProductAlertObserver.removeObserver("fssobs", this); + ProductAlertObserver.removeObserver(OBS, this); monitor = null; } - private Pattern fogPattern = Pattern.compile(URIFilter.uriSeperator + OBS - + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator - + wildCard + URIFilter.uriSeperator + cwa + URIFilter.uriSeperator - + wildCard + URIFilter.uriSeperator + wildCard - + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator - + "fog"); - /** * Finds the zone based on the icao passed into it * * @param icao - * @return + * @return zone */ public String findZone(String icao) { - String rzone = null; for (String zone : MonitoringArea.getPlatformMap().keySet()) { if (MonitoringArea.getPlatformMap().get(zone).contains(icao)) { - rzone = zone; - break; + return zone; } } - return rzone; + return null; } /** * get the main map * - * @return + * @return obsData */ public ObsData getTableData() { return obsData; } - /** - * get your table row data - * - * @param areaID - * @return - */ - public AreaContainer getObs(String areaID) { - AreaContainer ac = null; - if (getTableData().getContainer().containsKey(areaID)) { - ac = getTableData().getArea(areaID); - } - return ac; - } - /** * This method processes the incoming messages * - * @param objectToSend - * @param pluginname + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ObsMonitor#process(com.raytheon.uf.viz.monitor.data.ObReport) */ @Override - protected void process(ObReport result) - throws Exception { - - // ProcessFogReport fog = new ProcessFogReport(result); - // fog.processFogReport(); - - // use ObMultiHrsReports for data archive - // [Jan 21, 2010, zhao] + protected void process(ObReport result) throws Exception { obData.addReport(result); - //fireMonitorEvent(this); String zone = findZone(result.getPlatformId()); getTableData().getArea(zone).addReport(result.getObservationTime(), result); - + fireMonitorEvent(this); } @@ -357,7 +364,7 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { /** * gets the station Table Data * - * @return + * @return stationTableData */ public TableData getStationTableData() { return stationTableData; @@ -366,35 +373,38 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { /** * launch the zone table dialog * - * @param table + * @param type + * @param shell */ public void launchDialog(String type, Shell shell) { if (type.equals("zone")) { - if (zoneDialog == null) { - zoneDialog = new FogZoneTableDlg(shell, obData); + if (zoneDialog == null || zoneDialog.getShell() == null + || zoneDialog.isDisposed()) { + zoneDialog = new FogZoneTableDlg(shell, obData); addMonitorListener(zoneDialog); zoneDialog.addMonitorControlListener(this); + fireMonitorEvent(zoneDialog.getClass().getName()); + zoneDialog.open(); + } else { + zoneDialog.bringToTop(); + } + } else if (type.equals("area")) { + if (areaDialog == null) { + areaDialog = new FogMonitoringAreaConfigDlg(shell, + "Fog Monitor Area Configuration"); + areaDialog.open(); } - - zoneDialog.open(); - fireMonitorEvent(zoneDialog.getClass().getName()); - } - - else if (type.equals("area")) { - areaDialog = new FogMonitoringAreaConfigDlg(shell, - "Fog Monitor Area Configuration"); - areaDialog.open(); } } /** - * Set the algorithm threat by zone, time + * Set the algorithm threat by time and zone * - * @param zone - * @param threat + * @param time + * @param algData */ - public void setAlgorithmData(Date time, HashMap algData) { + public void setAlgorithmData(Date time, Map algData) { if (algorithmData.containsKey(time)) { algorithmData.remove(time); } @@ -403,19 +413,18 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { } /** - * Gets the algorithm threat + * Gets algorithm threat by time * - * @param zone - * @return + * @param time + * @return algData */ - public HashMap getAlgorithmData(Date time) { - - HashMap algData = new HashMap(); + public Map getAlgorithmData(Date time) { + Map algData = new HashMap(); if (algorithmData.containsKey(time)) { algData = algorithmData.get(time); } else { - // default nothing in algo column + // by default is nothing in the ALG column for (String zone : MonitoringArea.getPlatformMap().keySet()) { algData.put(zone, FOG_THREAT.GRAY); } @@ -426,21 +435,22 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { /** * Gets the monitoring geometries * - * @return + * @return zoneGeometries */ - public HashMap getMonitoringAreaGeometries() { + public Map getMonitoringAreaGeometries() { if (zoneGeometries == null) { - ArrayList zones = getMonitorAreaConfig().getAreaList(); + List zones = getMonitorAreaConfig().getAreaList(); zoneGeometries = new HashMap(); for (String zone : zones) { try { - zoneGeometries.put(zone, MonitorAreaUtils - .getZoneGeometry(zone)); + zoneGeometries.put(zone, + MonitorAreaUtils.getZoneGeometry(zone)); } catch (Exception e) { - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, + "Error get Monitoring Area Config", e); } } } @@ -451,7 +461,7 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { /** * Gets the fog configuration manager * - * @return + * @return fogConfig */ public FogMonitorConfigurationManager getMonitorAreaConfig() { if (fogConfig == null) { @@ -464,10 +474,21 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { return fogConfig; } + /** + * Gets observation data + * + * @return + */ public ObMultiHrsReports getObData() { return obData; } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.fog.listeners.IFogResourceListener# + * algorithmUpdate() + */ @Override public void algorithmUpdate() { @@ -507,8 +528,8 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { * @param drawTime */ public void updateDialogTime(Date dialogTime) { - this.dialogTime = dialogTime; - fireMonitorEvent(zoneDialog.getClass().getName()); + this.dialogTime = dialogTime; + fireMonitorEvent(zoneDialog.getClass().getName()); } /** @@ -523,14 +544,20 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { /** * close down the dialog * - * @param type + */ + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.fog.listeners.IFogResourceListener#closeDialog + * () */ public void closeDialog() { if (zoneDialog != null) { monitor.removeMonitorListener(zoneDialog); monitor.nullifyMonitor(); - zoneDialog.shellDisposeDialog(); + zoneDialog.close(); zoneDialog = null; } @@ -546,42 +573,28 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { * @param type * @return */ + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.IMonitor#getTimeOrderedKeys(com.raytheon. + * uf.viz.monitor.IMonitor, java.lang.String) + */ + @Override public ArrayList getTimeOrderedKeys(IMonitor monitor, String type) { return null; } /** - * Get most recent time - * - * @param type - * @return + * Get adjacent areas. */ - public DataTime getMostRecent() { - DataTime time = null; - Set ds = this.algorithmData.keySet(); - DataTime[] times = new DataTime[ds.size()]; - int i = 0; - for (Date d : ds) { - times[i] = new DataTime(d); - i++; - } - java.util.Arrays.sort(times); - if (times.length > 0) { - time = times[times.length - 1]; // most recent - } - - return time; - } - - public FogZoneTableDlg getDialog() { - return zoneDialog; - } - public void getAdjAreas() { this.geoAdjAreas = AdjacentWfoMgr.getAdjacentAreas(cwa); } /** + * Get geometry of adjacent areas. + * * @return the geoAdjAreas */ public Geometry getGeoAdjAreas() { @@ -589,19 +602,39 @@ public class FogMonitor extends ObsMonitor implements IFogResourceListener { } /** + * Sets the geoAdjAreas + * * @param geoAdjAreas - * the geoAdjAreas to set */ public void setGeoAdjAreas(Geometry geoAdjAreas) { this.geoAdjAreas = geoAdjAreas; } - @Override - protected void processAtStartup(ObReport report) { - obData.addReport(report); + /** + * First start + */ + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processAtStartup(com.raytheon. + * uf.viz.monitor.data.ObReport) + */ + @Override + protected void processAtStartup(ObReport report) { + obData.addReport(report); String zone = findZone(report.getPlatformId()); getTableData().getArea(zone).addReport(report.getObservationTime(), report); - } + } + + /** + * Gets Fog zone table dialog + * + * @return zoneDialog + */ + public FogZoneTableDlg getZoneDialog() { + return zoneDialog; + } } diff --git a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/actions/FogMonitorAction.java b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/actions/FogMonitorAction.java index f22e478165..20f743a417 100644 --- a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/actions/FogMonitorAction.java +++ b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/actions/FogMonitorAction.java @@ -47,12 +47,13 @@ public class FogMonitorAction extends AbstractHandler { @Override public Object execute(ExecutionEvent arg0) throws ExecutionException { - + System.out.println("Activating/Action for FOG..."); FogMonitor fog = FogMonitor.getInstance(); - - if (fog.zoneDialog == null || fog.zoneDialog.isDisposed()) { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); + + if (fog.getZoneDialog() == null || fog.getZoneDialog().isDisposed()) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); fog.launchDialog("zone", shell); } return null; diff --git a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/dialogs/FogZoneTableDlg.java b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/dialogs/FogZoneTableDlg.java index 492e9319a9..286c7d7467 100644 --- a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/dialogs/FogZoneTableDlg.java +++ b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/dialogs/FogZoneTableDlg.java @@ -19,9 +19,10 @@ **/ package com.raytheon.uf.viz.monitor.fog.ui.dialogs; +import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.Iterator; +import java.util.Map; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; @@ -31,6 +32,7 @@ import com.raytheon.uf.common.monitor.config.MonitorConfigurationManager; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.CommonTableConfig.CellType; import com.raytheon.uf.common.monitor.data.ObConst.DataUsageKey; +import com.raytheon.uf.common.monitor.data.ObConst.DisplayVarName; import com.raytheon.uf.viz.monitor.IMonitor; import com.raytheon.uf.viz.monitor.data.ObMultiHrsReports; import com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent; @@ -42,15 +44,24 @@ import com.raytheon.uf.viz.monitor.listeners.IMonitorListener; import com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg; /** - * (Where is the history log for this file???) + * Fog Zone Table Dialog * - * Jan 25, 2010 #4281 zhao Modified the notify method - * Jun 16, 2012 14386 zhao Modified the notify method + *
  * 
- * @author
+ * SOFTWARE HISTORY
  * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jan 25, 2010 #4281      zhao Modified the notify method 
+ * Jun 16, 2012 14386      zhao Modified the notify method
+ * Oct 30, 2012            skorolev    Changed HashMap to Map
+ * Nov 11, 2012 1297       skorolev    Added initiateProdArray
+ * 
+ * 
+ * + * @author ? + * @version 1.0 */ - public class FogZoneTableDlg extends ZoneTableDlg { private FogMonDispThreshDlg fogThreshDlg; @@ -62,6 +73,31 @@ public class FogZoneTableDlg extends ZoneTableDlg { super(parent, CommonConfig.AppName.FOG); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#initiateProdArray() + */ + @Override + public void initiateProdArray() { + varName = config.getFogZoneStnTableColVarNames()[colIndex]; + prodArray = new ArrayList(); + String varpref = "VAR_"; + for (DisplayVarName var : DisplayVarName.values()) { + String dispVarName = var.name(); + if (dispVarName.equals(varpref + varName.name())) { + prodArray.add(dispVarName); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#configThreshAction() + */ @Override protected void configThreshAction() { if (fogThreshDlg == null) { @@ -72,6 +108,13 @@ public class FogZoneTableDlg extends ZoneTableDlg { } } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.listeners.IMonitorListener#notify(com.raytheon + * .uf.viz.monitor.events.IMonitorEvent) + */ @Override public void notify(IMonitorEvent me) { @@ -87,23 +130,20 @@ public class FogZoneTableDlg extends ZoneTableDlg { // incorporate both for the obs and // The algorithm output. - if (me.getSource() instanceof FogMonitor) { + if (me.getSource() instanceof FogMonitor) { - FogMonitor fog = (FogMonitor) me.getSource(); - Date date = fog.getDialogDate(); + FogMonitor fog = (FogMonitor) me.getSource(); + Date date = fog.getDialogDate(); if (date != null) { Date nominalTime = date; - ObMultiHrsReports obData = fog.getObData(); -// if (!isLinkedToFrame()) { -// nominalTime = obData.getLatestNominalTime(); -// } - FogDataGenerator fdg = new FogDataGenerator(); - HashMap fogAlgCellType = fdg - .getAlgCellTypes(fog.getAlgorithmData(nominalTime)); - obData.setFogAlgCellType(fogAlgCellType); - this.updateTableDlg(obData.getObHourReports(nominalTime)); + ObMultiHrsReports obData = fog.getObData(); + FogDataGenerator fdg = new FogDataGenerator(); + Map fogAlgCellType = fdg.getAlgCellTypes(fog + .getAlgorithmData(nominalTime)); + obData.setFogAlgCellType(fogAlgCellType); + this.updateTableDlg(obData.getObHourReports(nominalTime)); } - } + } } /** @@ -129,17 +169,36 @@ public class FogZoneTableDlg extends ZoneTableDlg { * date); //} } */ + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * addMonitorControlListener(com.raytheon.uf.viz.monitor.IMonitor) + */ @Override public void addMonitorControlListener(IMonitor monitor) { getMonitorControlListeners().add(monitor); } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireConfigUpdate + * (com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent) + */ @Override public void fireConfigUpdate(IMonitorConfigurationEvent imce) { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireDialogShutdown + * (com.raytheon.uf.viz.monitor.listeners.IMonitorListener) + */ @Override public void fireDialogShutdown(IMonitorListener iml) { Display.getDefault().asyncExec(new Runnable() { @@ -153,6 +212,13 @@ public class FogZoneTableDlg extends ZoneTableDlg { }); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener#fireKillMonitor + * () + */ @Override public void fireKillMonitor() { Display.getDefault().asyncExec(new Runnable() { @@ -166,35 +232,51 @@ public class FogZoneTableDlg extends ZoneTableDlg { }); } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireThresholdUpdate + * (com.raytheon.uf.viz.monitor.events.IMonitorThresholdEvent) + */ @Override public void fireThresholdUpdate(IMonitorThresholdEvent imte) { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * removeMonitorContorlListener(com.raytheon.uf.viz.monitor.IMonitor) + */ @Override public void removeMonitorContorlListener(IMonitor monitor) { getMonitorControlListeners().remove(monitor); } - @Override - protected MonitorConfigurationManager getConfigMgr() { - return FogMonitorConfigurationManager.getInstance(); - } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#getConfigMgr() + */ + @Override + protected MonitorConfigurationManager getConfigMgr() { + return FogMonitorConfigurationManager.getInstance(); + } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#handleLinkToFrame() + */ @Override protected void handleLinkToFrame() { linkedToFrame = linkToFrameChk.getSelection(); FogMonitor.getInstance().fireMonitorEvent(this.getClass().getName()); } - /** - * - */ - protected void unregisterDialogFromMonitor() { - this.fireDialogShutdown(this); - } - /* * (non-Javadoc) * @@ -203,8 +285,29 @@ public class FogZoneTableDlg extends ZoneTableDlg { */ @Override protected void shellDisposeAction() { - // TODO Auto-generated method stub + // Not used + } + @Override + protected void setZoneSortColumnAndDirection() { + if (zoneTblData != null) { + zoneSortColumn = zoneTblData.getSortColumn(); + zoneSortDirection = zoneTblData.getSortDirection(); + } + } + + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg# + * setStnSortColumnAndDirection() + */ + @Override + protected void setStnSortColumnAndDirection() { + if (stnTblData != null) { + stnSortColumn = stnTblData.getSortColumn(); + stnSortDirection = stnTblData.getSortDirection(); + } } } diff --git a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/resource/FogThreat.java b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/resource/FogThreat.java index f763a194a7..50a1103295 100644 --- a/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/resource/FogThreat.java +++ b/cave/com.raytheon.uf.viz.monitor.fog/src/com/raytheon/uf/viz/monitor/fog/ui/resource/FogThreat.java @@ -19,9 +19,8 @@ **/ package com.raytheon.uf.viz.monitor.fog.ui.resource; -import java.awt.Point; -import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; import org.eclipse.swt.widgets.Display; import org.opengis.referencing.FactoryException; @@ -29,51 +28,39 @@ import org.opengis.referencing.operation.TransformException; import com.raytheon.uf.common.dataplugin.fog.FogRecord; import com.raytheon.uf.common.dataplugin.fog.FogRecord.FOG_THREAT; -import com.raytheon.uf.common.dataplugin.fog.analysis.FogCell; -import com.raytheon.uf.common.dataplugin.fog.analysis.FogDataCorrector; -import com.raytheon.uf.common.dataplugin.fog.analysis.FogMonitorUtils; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; import com.raytheon.uf.common.geospatial.ReferencedObject.Type; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.viz.monitor.fog.FogCommonThreat; import com.raytheon.uf.viz.monitor.fog.FogMonitor; import com.raytheon.uf.viz.monitor.fog.xml.FogMonitorAlgorithmXML; -import com.vividsolutions.jts.algorithm.locate.SimplePointInAreaLocator; import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.GeometryFactory; -public class FogThreat { +/** + * Fog monitor threat calculation + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov  1, 2012            skorolev     Changed HashMap to Map and cleaned code.
+ * Nov 13, 2012 1297       skorolev     Made abstract class FogCommonThreat
+ * 
+ * 
+ * + * @author skorolev + * @version 1.0 + */ +public class FogThreat extends FogCommonThreat { + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(FogThreat.class); - /** list of coordinates for each zone **/ - public HashMap> zoneCoordinates = null; - - private final GeometryFactory geoFactory = new GeometryFactory(); - - private FogRecord fog = null; - - private FogMonitorAlgorithmXML fogAlgXML = null; - - private Geometry geoAdjAreas = null; - - public FOG_THREAT[] threats = null; - - public ArrayList cells = null; - - public float[] ir_diff_thresholds = null; - - public float[] vis_thresholds = null; - - public int twilight_angle_offset = 0; - - // boolean filter switches - public boolean isSnowIce = true; - - public boolean isFractalDimension = true; - - public boolean isSmoothness = true; - - public boolean isAdjacency = true; - - private FogMonitor monitor; + /** Fog monitor **/ + private FogMonitor fmonitor = FogMonitor.getInstance(); /** * serialization constructor @@ -84,732 +71,38 @@ public class FogThreat { /** * used constructor + * + * @param fogAlgXML */ public FogThreat(FogMonitorAlgorithmXML fogAlgXML) { this.fogAlgXML = fogAlgXML; setThresholdArrays(); + zoneGeos = fmonitor.getMonitoringAreaGeometries(); + geoAdjAreas = fmonitor.getGeoAdjAreas(); } - /** - * This method will be called with the switches from the GUI front end + /* + * (non-Javadoc) * - * Fog Product [T(10.7) - (T(3.9)] or VIS (normalized count) Maximum cloud - * temperature Daytime Ice/Snow vs Fog Threshold (c) (FogSnowIceFilter) Cool - * Fog vs Warm Surface threshold Daytime Smoothness Algorithm - * (FogSmoothnessFilter) Adjacency Threshold Twilight Angle Threshold - * Fractal Dimension Threshold (FogFractalFilter) + * @see + * com.raytheon.uf.viz.monitor.fog.FogCommonThreat#setMonitorAreaThreats() */ - public FogRecord getFogThreat(FogRecord fog) { - this.fog = fog; - System.out.println("FogThreat: Start analyzing Fog Threat..."); - long start = System.currentTimeMillis(); - this.geoAdjAreas = getFogMonitor().getGeoAdjAreas(); - // clear threats array, make gray (SK)i=>x j=>y - for (int i = 0; i < fog.getNx(); i++) { - for (int j = 0; j < fog.getNy(); j++) { - // (SK) getThreats()[fog.getNy() * i + j] = FOG_THREAT.GRAY; - getThreats()[fog.getNx() * j + i] = FOG_THREAT.GRAY; - } - } - - // First execute the data corrector, this divides up the FogRecord field - // into Day, Night, and Twilight. - FogDataCorrector fdc = new FogDataCorrector(getFog(), - fogAlgXML.getTwilightAngle()); - fog = fdc.execute(); - - // Second, core processor. Gets you the cells, sets non-filtered values. - executeCoreProcessor(); - - // Third, apply filters - for (FogCell cell : getCells()) { - // *********** APPLY FILTERS ******************* - - // Area Size filter - if (fogAlgXML.isAdjacencyThreshOn() - && cell.getCellThreat() != FOG_THREAT.GREEN - && cell.getCellThreat() != FOG_THREAT.GRAY) { - - if (cell.getArea() < fogAlgXML.getAdjacencyThresh()) { - setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); - } - } - - // Snow & Ice filter - if (fogAlgXML.isIceSnowVsFogOn() - && cell.getImageGroup() == FogRecord.IMAGE_GROUP.VIS_GROUP - && (cell.getCellThreat() != FOG_THREAT.GREEN || cell - .getCellThreat() != FOG_THREAT.GRAY)) { - - float tempMean = calAverageTemp(cell); - - if (tempMean < fogAlgXML.getIceSnowVsFog()) { - downgradeThreat(cell); - } - } - - // Smoothness filter - if (fogAlgXML.isDaytimeSmoothThreshOn() - && cell.getCellThreat() != FOG_THREAT.GREEN - || cell.getCellThreat() != FOG_THREAT.GRAY) { - - float tem_smoothness = calSmoothness(cell); - - if (tem_smoothness < fogAlgXML.getDaytimeSmoothThresh()) { - downgradeThreat(cell); - } - } - - // Fractal filter - if (fogAlgXML.isFractalDimensionOn() - && cell.getCellThreat() != FOG_THREAT.GREEN - && cell.getCellThreat() != FOG_THREAT.GRAY) { - - float temFD = calRegularity(cell); - - if (temFD > fogAlgXML.getFractalDimension() && temFD > 0.0f) { - setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); - } - } - - // We extract the zone threat differently than the GI filter - // Hence it is not needed. - } - - setThreats(); - setMonitorAreaThreats(); - System.out.println("FogThreat: Analyzed Fog Threat...Duration: " - + (System.currentTimeMillis() - start)); - return fog; - } - - /** - * Remember J is X and I is Y, totally against convention! Gets the threat - * level - * - * @param i - * (SK y) - * @param j - * (SK x) - * @param group - * @return - */ - private FOG_THREAT getThreatLevel(int i, int j, FogRecord.IMAGE_GROUP group) { - // (SK) i=>x, j=>y - // default return - FOG_THREAT returnValue = FOG_THREAT.GRAY; - // (SK) idx = fog.getNy() * i + j - int idx = fog.getNx() * j + i; - switch (group) { - case VIS_GROUP: - float ir4_temp = bTemp(i, j, FogRecord.CHANNEL.IR10_7); - int CLOUD_FREE_BRIGHTNESS = 68; // empirical value - // Too cold - if (ir4_temp < fogAlgXML.getMaxCloudTemp()) { - returnValue = FOG_THREAT.GRAY; - } - // overlapping high/middle cloud - - else if (fog.getVisArray()[idx] <= vis_thresholds[2] - && fog.getVisArray()[idx] >= vis_thresholds[1]) { - - returnValue = FOG_THREAT.RED; - } else if (fog.getVisArray()[idx] < vis_thresholds[1] - && fog.getVisArray()[idx] >= vis_thresholds[0] - || fog.getVisArray()[idx] <= vis_thresholds[3] - && fog.getVisArray()[idx] > vis_thresholds[2]) { - - returnValue = FOG_THREAT.YELLOW; - } - - // This is essentially the Cool Fog vs. Warm surface threshold check - else if (fogAlgXML.isCoolFogVsWarmSurfaceOn() - && ir4_temp >= fogAlgXML.getCoolFogVsWarmSurface()) { - returnValue = FOG_THREAT.GREEN; - } - - else if (fog.getVisArray()[idx] < CLOUD_FREE_BRIGHTNESS) { - returnValue = FOG_THREAT.GREEN; - } - - return returnValue; - - case IR_GROUP: - // for some odd reason j is x and i is y, - // not sure why AWIPS 1 does it this way. - // It is completely against convention. - // Point tempoint = new Point(j, i); - // (SK) here i=>x and j=>y - Point tempoint = new Point(i, j); - float tempIR10_7 = temp_at_vis_pixel(tempoint, - FogRecord.CHANNEL.IR10_7); - if (tempIR10_7 < fogAlgXML.getMaxCloudTemp()) { - // Too cold - returnValue = FOG_THREAT.GRAY; - } - // Overlapping high/middle cloud - float tempIR3_9 = temp_at_vis_pixel(tempoint, - FogRecord.CHANNEL.IR3_9); - float tempDiff = tempIR10_7 - tempIR3_9; - - if (tempDiff <= ir_diff_thresholds[2] - && tempDiff >= ir_diff_thresholds[1]) { - returnValue = FOG_THREAT.RED; - } else if (tempDiff < ir_diff_thresholds[1] - && tempDiff >= ir_diff_thresholds[0] - || tempDiff <= ir_diff_thresholds[3] - && tempDiff > ir_diff_thresholds[2]) { - returnValue = FOG_THREAT.YELLOW; - } else { - returnValue = FOG_THREAT.GREEN; - } - - case TWILIGHT_GROUP: - // do nothing, stays gray - } - - return returnValue; - } - - /** - * Precursor call to get temp at pixel - * - * @param i - * @param j - * @param imgtype - * @return - */ - private float bTemp(int i, int j, FogRecord.CHANNEL imgtype) { - // (SK) here i=>x and j=>y - // for some odd reason j is x and i is y, - // not sure why AWIPS 1 does it this way. - // It is completely against convention. - - Point tempoint = new Point(i, j); - return temp_at_vis_pixel(tempoint, imgtype); - } - - /** - * Get the temp at the pixel - * - * @param pointVis - * @param channel - * @return - */ - private float temp_at_vis_pixel(Point pointVis, FogRecord.CHANNEL channel) { - // The assumption is that Dimensions of IR4 and IR2 are the same. - // IR4 data will be always needed, so attributes for IR4 shall be - // always available. - // **** ATTENTION ***** We have made the vis the same as well for AWIPS - // II - int count_value = 255; - if (channel == FogRecord.CHANNEL.IR3_9) { - count_value = fog.getIR_3_9Array()[fog.getNx() * pointVis.y - + pointVis.x]; - // (SK) count_value = fog.getIR_3_9Array()[fog.getNy() * pointVis.x - // + pointVis.y]; - } else if (channel == FogRecord.CHANNEL.IR10_7) { - count_value = fog.getIR_10_7Array()[fog.getNx() * pointVis.y - + pointVis.x]; - // (SK) count_value = fog.getIR_10_7Array()[fog.getNy() * pointVis.x - // + pointVis.y]; - } - return FogMonitorUtils.count2temp(count_value, channel); - } - - /** - * Gets the fog - * - * @return - */ - public FogRecord getFog() { - return fog; - } - - /** - * Gets the existing array of threats - * - * @return - */ - public FOG_THREAT[] getThreats() { - if (threats == null) { - threats = new FOG_THREAT[getFog().getNx() * getFog().getNy()]; - } - return threats; - } - - /** - * Gets the cells of this analysis - * - * @return - */ - public ArrayList getCells() { - return cells; - } - - /** - * Gets the existing threat value at that point - * - * @return - */ - public FOG_THREAT getThreat(int i, int j) { - return getThreats()[fog.getNx() * j + i]; - // (SK) return getThreats()[fog.getNy() * i + j]; - } - - /** - * Set fog threat at threat level point - * - * @param i - * @param j - * @param threat - */ - private void setThreat(int i, int j, FOG_THREAT threat) { - // (SK) getThreats()[fog.getNy() * i + j] = threat; - getThreats()[fog.getNx() * j + i] = threat; - } - - /** - * Downgrade the Fog Threat - * - * @param current - * @param i - * @param j - */ - private void downgradeThreat(FogCell cell) { - if (cell.getCellThreat() == FOG_THREAT.YELLOW) { - setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); - } else if (cell.getCellThreat() == FOG_THREAT.RED) { - setCellThreats(cell.getPoints(), FOG_THREAT.YELLOW); - } - } - - // // *********************** FILTERS **************************** ///// - - // -Private-------------------------------------------------------------------- - // NAME: CalRegularity() - // - // TYPE: Private Member function - // - // Descript: - // Given a cell, calculate its regularity i.e. the fractal dimension - // Input Arguments: - // cell: The Fog_Cell whose fractal dimension is to be measured - // Output Arguments: - // Return float: fractal dimension. the value is between 1 to 2 - // smaller means more regular. - // Here use the perimeter and area relation to represent - // fractal dimension (one of the simply ways) - // History: - // May 2004 Qin Zeng (GDMB/MDL) -- created - // Dec 2009 D Hladky translated to Java - // ----------------------------------------------------------------------------- - - private float calRegularity(FogCell cell) { - - int nx = cell.right - cell.left + 1; - int ny = cell.bottom - cell.top + 1; - int i; - boolean[] flag = new boolean[nx * ny]; - - for (i = 0; i < nx * ny; i++) { - flag[i] = false; - } - - int pixels_num = (int) cell.getArea(); - int flagPos; - for (i = 0; i < pixels_num; i++) { - Coordinate coor = cell.getPixelCoordinate(i); - flagPos = (int) ((coor.y - cell.top) * nx + coor.x - cell.left); - if (flagPos >= 0 && flagPos < nx * ny) { - flag[flagPos] = true; - } - } - // From here, perimeter of the fog cell will be calculated; - // |...| 1 |...| - // | 4 | 0 | 2 | - // |...| 3 |...| - // - // If the any of the 0's surrounding pixels(1,2,3,4) is flagged as - // false, - // which means that surrounding pixel(1,2,3,or 4) is not included in - // the cell, pixel 0 then will be at the edge of the cell cluster. - // And the edge connecting to the outside pixel will be counted into the - // perimeter of the cell cluster. - - int pos1, pos2, pos3, pos4; - float perimeter = 0; - for (i = 0; i < pixels_num; i++) { - Coordinate coor = cell.getPixelCoordinate(i); - - pos1 = (int) ((i - cell.top - 1) * nx + coor.y - cell.left); - if (pos1 >= 0 && pos1 < nx * ny && !flag[pos1] - || i - coor.x < cell.top) { - perimeter++; - } - - pos2 = (int) ((coor.y - cell.top) * nx + coor.x + 1 - cell.left); - if (pos2 >= 0 && pos2 < nx * ny && !flag[pos2] - || coor.x + 1 > cell.right) { - perimeter++; - } - - pos3 = (int) ((coor.y - cell.top + 1) * nx + coor.x - cell.left); - if (pos3 >= 0 && pos3 < nx * ny && !flag[pos3] - || coor.y + 1 > cell.bottom) { - perimeter++; - } - - pos4 = (int) ((coor.y - cell.top) * nx + coor.x - 1 - cell.left); - if (pos4 >= 0 && pos4 < nx * ny && !flag[pos4] - || coor.x - 1 < cell.left) { - perimeter++; - } - } - - float fractalDimension = 1.0f; - - if (cell.getArea() != 1) { - fractalDimension = (float) (2 * Math.log(perimeter / 4.0) / Math - .log(cell.getArea())); - } - - // Note : fractalDimension is a data between 1 and 2 and the larger - // fractalDimension is , the more irregular the shape of the cell will - // be. - - return fractalDimension; - } - - // -Private-------------------------------------------------------------------- - // NAME: CalSmoothness() - // - // TYPE: Private Member function - // - // Descript: - // Given a cell, calculate the its smoothness - // Input Arguments: - // cell: The Fog_Cell whose smoothness is to be measured - // Output Arguments: - // return float: smoothness defined above - // History: - // May 2004 Qin Zeng (GDMB/MDL) -- created - // Dec 2009 D Hladky ported to AWIPS II - // ----------------------------------------------------------------------------- - private float calSmoothness(FogCell cell) { - - float mean = 0; // mean grayscale value of pixels in the cell from VIS. - float stdDev = 0; // standard deviation - int pixels_num = (int) cell.getArea(); - - if (pixels_num == 0) { - return 0; - } - - int i; - for (i = 0; i < pixels_num; i++) { - Coordinate pixr = cell.getPixelRelativeCoordinate(i); - // (SK) mean += getFog().getVisArray()[(int) (getFog().getNy() * - // pixr.x + pixr.y)]; - mean += getFog().getVisArray()[(int) (getFog().getNx() * pixr.y + pixr.x)]; - } - - mean /= pixels_num; - float tem_float; - - for (i = 0; i < pixels_num; i++) { - Coordinate pixr = cell.getPixelRelativeCoordinate(i); - // (SK) tem_float = getFog().getVisArray()[(int) (getFog().getNy() * - // pixr.x + pixr.y)]; - tem_float = getFog().getVisArray()[(int) (getFog().getNx() * pixr.y + pixr.x)]; - stdDev += (tem_float - mean) * (tem_float - mean); - } - - stdDev /= pixels_num; - stdDev = (float) Math.sqrt(stdDev); - // mean should not be zero, so no need to check mean here. - return (1 - stdDev / mean) * 100; // use percent as unit - } - - // -Private--------------------------------------------------------------------- - // NAME: Cal() - // - // TYPE: Private Member function - // - // Descript: - // Calculate the average temperature for a Fog_Cell in channel 3.9 um - // History: - // May 2004 Qin Zeng (GDMB/MDL) -- created - // ----------------------------------------------------------------------------- - - private float calAverageTemp(FogCell cell) { - float mean = 0; // mean temperature value of pixels in the cell. - int pixels_num = (int) cell.getArea(); - if (pixels_num == 0) { - return -999.9f; - } - for (int i = 0; i < pixels_num; i++) { - Coordinate pixc = cell.getPixelRelativeCoordinate(i); - mean += temp_at_vis_pixel(new Point((int) pixc.x, (int) pixc.y), - FogRecord.CHANNEL.IR3_9); - } - - mean /= pixels_num; - return mean; - } - - // -Public--------------------------------------------------------------------- - // NAME: Execute() - // - // TYPE: Private Member function - // - // Descript: - // Based on the thresholds of the VIS image data and the IR image data, - // a number of patches of the contiguous suspected fog areas will be - // extracted from the satellite image data. - // This is an implementation of the feature extraction algorithm based - // on the contiguous gray scale values. - // - // Arguments: None - // History: - // March 2004 Qin Zeng (GDMB/MDL) -- created - // Dec 2009 D Hladky ported to Java for AWIPS II - // ----------------------------------------------------------------------------- - private void executeCoreProcessor() { - - cells = new ArrayList(); - ArrayList parent = new ArrayList(); - ArrayList child = new ArrayList(); - ArrayList single_segment = new ArrayList(); - - int x_dim = getFog().getNx(); - int y_dim = getFog().getNy(); - int i; // (SK) x - int j; // (SK) y - // To flag whether a pixel has been visited or not - boolean[][] visited = new boolean[x_dim][y_dim]; - - Point[] s = new Point[8]; // 8 surrounding points of one specific point - for (int z = 0; z < s.length; z++) { - s[z] = new Point(); - } - - Point tempoint = new Point(); - getCells().clear(); - - for (i = 0; i < x_dim; i++) { - for (j = 0; j < y_dim; j++) { - visited[i][j] = false; - } - } - for (j = 0; j < y_dim; j++) { - Point firstone = new Point(); - FOG_THREAT threat_level = FOG_THREAT.BLACK; - FogRecord.IMAGE_GROUP imggroup; - for (i = 0; i < x_dim; i++) { - if (visited[i][j]) { - continue; - } - Coordinate cellCoor = this.getCellCoor(i, j); - visited[i][j] = true; - imggroup = getFog().findGroup(i, j); - threat_level = getThreatLevel(i, j, imggroup); - // Sets the initial threat level - setThreat(i, j, threat_level); - firstone.x = i; - firstone.y = j; - parent.clear(); - tempoint.y = j; - tempoint.x = i; - single_segment.add(tempoint); - parent.add(tempoint); - while (parent.size() != 0) { - // the variables(s[1],s[2]...) below mean surrounding 1,2 - // | 0 | 1 | 2 | - // | 7 | i | 3 | - // | 6 | 5 | 4 | - // iteratively search the 8-connected surrounding pixels - child.clear(); - for (int k = 0; k < parent.size(); k++) { - // y's too small, too big - if (parent.get(k).y == 0) { - s[0].y = parent.get(k).y; - s[1].y = parent.get(k).y; - s[2].y = parent.get(k).y; - } - if (parent.get(k).y == y_dim - 1) { - s[4].y = parent.get(k).y; - s[5].y = parent.get(k).y; - s[6].y = parent.get(k).y; - } - // x's too small, too big - if (parent.get(k).x == 0) { - s[0].x = parent.get(k).x; - s[6].x = parent.get(k).x; - s[7].x = parent.get(k).x; - } - if (parent.get(k).x == x_dim - 1) { - s[2].x = parent.get(k).x; - s[3].x = parent.get(k).x; - s[4].x = parent.get(k).x; - } - // all others - if (parent.get(k).x > 0 && parent.get(k).x < x_dim - 1 - && parent.get(k).y < y_dim - 1 - && parent.get(k).y > 0) { - s[0].y = parent.get(k).y - 1; - s[0].x = parent.get(k).x - 1; - s[1].y = parent.get(k).y - 1; - s[1].x = parent.get(k).x; - s[2].y = parent.get(k).y - 1; - s[2].x = parent.get(k).x + 1; - s[3].y = parent.get(k).y; - s[3].x = parent.get(k).x + 1; - s[4].y = parent.get(k).y + 1; - s[4].x = parent.get(k).x + 1; - s[5].y = parent.get(k).y + 1; - s[5].x = parent.get(k).x; - s[6].y = parent.get(k).y + 1; - s[6].x = parent.get(k).x - 1; - s[7].y = parent.get(k).y; - s[7].x = parent.get(k).x - 1; - } - FogRecord.IMAGE_GROUP temgroup; - FOG_THREAT temthreat; - - for (int m = 0; m < 8; m++) { - if (s[m].y >= 0 && s[m].y < y_dim && s[m].x >= 0 - && s[m].x < x_dim) { - int ii = s[m].x; - int jj = s[m].y; - // (SK) int ii = s[m].y; - // (SK) int jj = s[m].x; - - if (!visited[ii][jj]) { - temgroup = getFog().findGroup(ii, jj); - temthreat = getThreatLevel(ii, jj, temgroup); - if (temgroup == imggroup - && temthreat == threat_level) { - child.add(s[m]); - visited[ii][jj] = true; - single_segment.add(s[m]); - } - }// end of if - }// end of if - }// end of for m - }// end of for k - parent = child; - }// end of while - // if (!this.geoAdjAreas - // .contains(geoFactory.createPoint(cellCoor))) { - int lct = SimplePointInAreaLocator.locate(cellCoor, - this.geoAdjAreas); - if (lct == 2) { - threat_level = FOG_THREAT.BLACK; - setThreat(i, j, threat_level); - } - getCells().add( - new FogCell(single_segment, threat_level, imggroup)); - single_segment.clear(); - } // end of for i - } // end of for j - } - - /** - * Sets all points in the cell to the cell filtered value threat - * - * @param cells - * @param threat - */ - private void setCellThreats(ArrayList points, FOG_THREAT threat) { - for (Point point : points) { - getThreats()[fog.getNx() * point.y + point.x] = threat; - // (SK) getThreats()[fog.getNy() * point.x + point.y] = threat; - } - } - - /** - * Gets the drawable float array of threats - * - * @return - */ - private void setThreats() { - float[] floats = new float[getThreats().length]; - int i = 0; - for (FOG_THREAT threat : getThreats()) { - floats[i] = getThreatValue(threat); - i++; - } - - getFog().setThreats(floats); - } - - /** - * Sets the thresholds - */ - private void setThresholdArrays() { - ir_diff_thresholds = new float[4]; - vis_thresholds = new float[4]; - - ir_diff_thresholds[0] = (float) fogAlgXML.getFogProductYLo(); - ir_diff_thresholds[1] = (float) fogAlgXML.getFogProductYHi(); - ir_diff_thresholds[2] = (float) fogAlgXML.getFogProductRLo(); - ir_diff_thresholds[3] = (float) fogAlgXML.getFogProductRHi(); - - vis_thresholds[0] = (float) fogAlgXML.getVisYLo(); - vis_thresholds[1] = (float) fogAlgXML.getVisYHi(); - vis_thresholds[2] = (float) fogAlgXML.getVisRLo(); - vis_thresholds[3] = (float) fogAlgXML.getVisRHi(); - } - - /** - * Quick static method to get the float to threat mapping - * - * @param threat - * @return - */ - public static float getThreatValue(FOG_THREAT threat) { - float value = 0; - - if (threat == FOG_THREAT.BLACK) { - value = 0.0f; - } else if (threat == FOG_THREAT.GRAY) { - value = 15.0f; - } else if (threat == FOG_THREAT.GREEN) { - value = 60.0f; - } else if (threat == FOG_THREAT.YELLOW) { - value = 110.0f; - } else if (threat == FOG_THREAT.RED) { - value = 220.0f; - } - return value; - } - - /** - * Gets the zone threats (ALG) with worst case for zone area - * - * @return HashMap - */ - public void setMonitorAreaThreats() { - + @Override + protected void setMonitorAreaThreats() { final FogRecord ffogRec = getFog(); - final FogMonitor fmonitor = getFogMonitor(); + // TODO: async or sync ???? + Display.getDefault().asyncExec(new Runnable() { - Display.getDefault().syncExec(new Runnable() { public void run() { - long start = System.currentTimeMillis(); - HashMap zoneGeos = fmonitor - .getMonitoringAreaGeometries(); // set to lowest for default - HashMap zoneThreats = new HashMap(); + Map zoneThreats = new HashMap(); for (String zone : zoneGeos.keySet()) { zoneThreats.put(zone, FOG_THREAT.BLACK); } for (int i = 0; i < ffogRec.getNx(); i++) { for (int j = 0; j < ffogRec.getNy(); j++) { - ReferencedCoordinate rc = new ReferencedCoordinate( new Coordinate(i, j), ffogRec.getGridGeometry(), Type.GRID_CENTER); @@ -817,9 +110,9 @@ public class FogThreat { try { coor = rc.asLatLon(); } catch (TransformException e) { - e.printStackTrace(); + statusHandler.handle(Priority.ERROR, e.getMessage()); } catch (FactoryException e) { - e.printStackTrace(); + statusHandler.handle(Priority.ERROR, e.getMessage()); } for (String zone : zoneGeos.keySet()) { @@ -833,42 +126,25 @@ public class FogThreat { getThreat(i, j)); } } catch (Exception e) { - e.printStackTrace(); + statusHandler.handle(Priority.ERROR, + e.getMessage()); } } } - } - } - } + } // end zone loop + } // end j loop + } // end i loop fmonitor.setAlgorithmData(ffogRec.getRefHour().getTime(), zoneThreats); - System.out.println("FogThreat: Set algorithm zone values..." - + (System.currentTimeMillis() - start)); + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.handle(Priority.DEBUG, + "FogThreat for SS: Set algorithm zone values..." + + (System.currentTimeMillis() - start)); + } + } }); } - private Coordinate getCellCoor(int i, int j) { - ReferencedCoordinate rc = new ReferencedCoordinate( - new Coordinate(i, j), this.getFog().getGridGeometry(), - Type.GRID_CENTER); - Coordinate crd = null; - try { - crd = rc.asLatLon(); - } catch (TransformException e) { - e.printStackTrace(); - } catch (FactoryException e) { - e.printStackTrace(); - } - return crd; - } - - /** Get the Fog monitor **/ - public FogMonitor getFogMonitor() { - if (monitor == null) { - monitor = FogMonitor.getInstance(); - } - return monitor; - } } diff --git a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasAction.java b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasAction.java deleted file mode 100644 index 06824980dd..0000000000 --- a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasAction.java +++ /dev/null @@ -1,61 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.viz.monitor.safeseas; - -import org.eclipse.core.commands.AbstractHandler; -import org.eclipse.core.commands.ExecutionEvent; -import org.eclipse.core.commands.ExecutionException; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; - -/** - * Kick off the SAFESEAS dialog and application backend processes. - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 1/27/09                  dhladky    Initial Creation.
- * 
- * 
- * - * @author dhladky - * - */ -public class SafeSeasAction extends AbstractHandler { - - @Override - public Object execute(ExecutionEvent arg0) throws ExecutionException { - - System.out.println("Activating/Action the SAFESEAS plugin..."); - - SafeSeasMonitor ssm = SafeSeasMonitor.getInstance(); - if (ssm.zoneDialog == null || ssm.zoneDialog.isDisposed()) { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - ssm.launchDialog("zone", shell); - } - - return null; - } - -} diff --git a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasMonitor.java b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasMonitor.java index d50b2eab0a..cad03d29e1 100644 --- a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasMonitor.java +++ b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/SafeSeasMonitor.java @@ -23,7 +23,8 @@ import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Iterator; -import java.util.Set; +import java.util.List; +import java.util.Map; import java.util.regex.Pattern; import org.eclipse.swt.graphics.RGB; @@ -38,8 +39,9 @@ import com.raytheon.uf.common.monitor.config.SSMonitorConfigurationManager; import com.raytheon.uf.common.monitor.data.AdjacentWfoMgr; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.CommonTableConfig.CellType; -import com.raytheon.uf.common.monitor.data.ObConst.ChosenAppKey; -import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.viz.core.alerts.AlertMessage; import com.raytheon.uf.viz.core.localization.LocalizationManager; import com.raytheon.uf.viz.core.notification.NotificationMessage; @@ -78,6 +80,8 @@ import com.vividsolutions.jts.geom.Geometry; * Dec 30, 2009 3424 zhao use ObMultiHrsReports for obs data archive over time * July 20,2010 4891 skorolev Added resource listener * May 15, 2012 14510 zhao Modified processing at startup + * Oct 26, 2012 1280 skorolev Clean code and made changes for non-blocking dialog + * Oct 30, 2012 1297 skorolev Changed HashMap to Map * * * @@ -87,24 +91,27 @@ import com.vividsolutions.jts.geom.Geometry; */ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { + + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(SafeSeasMonitor.class); + /** Singleton instance of this class */ private static SafeSeasMonitor monitor = null; /** zone table dialog **/ - public SSZoneTableDlg zoneDialog = null; + private SSZoneTableDlg zoneDialog; - /** - * monitoring area config dialog - */ - SSMonitoringAreaConfigDlg areaDialog = null; + /** monitoring area config dialog **/ + private SSMonitoringAreaConfigDlg areaDialog = null; + /** configuration manager **/ private SSMonitorConfigurationManager safeseasConfig = null; /** * This object contains all observation data necessary for the table dialogs * and trending plots */ - private ObMultiHrsReports obData; + private ObMultiHrsReports obData; /** table data for the zone table **/ private final TableData zoneTableData = new TableData( @@ -114,116 +121,157 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { private final TableData stationTableData = new TableData( CommonConfig.AppName.SAFESEAS); - /** All SafeSeas plugins start with this */ - private static String OBS = "fssobs"; + /** All SafeSeas datauri start with this */ + private final String OBS = "fssobs"; /** regex wild card filter */ - protected static String wildCard = "[\\w\\(\\)-_:.]+"; + private final String wildCard = "[\\w\\(\\)-_:.]+"; - /** The application key */ - ChosenAppKey chosenAppKey = ChosenAppKey.SAFESEAS; + /** List of SAFESEAS resource listeners **/ + private final List safeSeasResources = new ArrayList(); - private final ArrayList safeSeasResources = new ArrayList(); + /** Time which Zone/County dialog shows. **/ + private Date dialogTime = null; - /** - * Time which Zone/County dialog shows. - */ - public Date dialogTime = null; + /** list of coordinates for each zone **/ + private Map zoneGeometries = null; - /** list of coordinates for each zone **/ - public HashMap zoneGeometries = null; - - /** data holder for FOG data **/ - public HashMap> algorithmData = null; + /** data holder for FOG data **/ + private Map> algorithmData = null; /** Adjacent areas for current cwa **/ private Geometry geoAdjAreas; - /** Array of fogAlg listeners **/ - private final ArrayList fogResources = new ArrayList(); + /** List of fogAlg listeners **/ + private final List fogResources = new ArrayList(); + + /** Pattern for SAFESEAS **/ + private final Pattern ssPattern = Pattern + .compile(URIFilter.uriSeperator + OBS + URIFilter.uriSeperator + + wildCard + URIFilter.uriSeperator + wildCard + + URIFilter.uriSeperator + cwa + URIFilter.uriSeperator + + wildCard + URIFilter.uriSeperator + wildCard + + URIFilter.uriSeperator + wildCard + + URIFilter.uriSeperator + "ss"); /** * Private constructor, singleton */ private SafeSeasMonitor() { - pluginPatterns.add(ssPattern); + pluginPatterns.add(ssPattern); readTableConfig(MonitorThresholdConfiguration.SAFESEAS_THRESHOLD_CONFIG); - initObserver("fssobs", this); + initObserver(OBS, this); } + /** + * @return instance of monitor + */ public static synchronized SafeSeasMonitor getInstance() { if (monitor == null) { monitor = new SafeSeasMonitor(); - // Pre-populate dialog with an observation (METAR) for KOMA - monitor.createDataStructures(); + // Pre-populate dialog with an observation (METAR) for KOMA + monitor.createDataStructures(); monitor.getAdjAreas(); - monitor.processProductAtStartup("ss"); - monitor.fireMonitorEvent(monitor); + monitor.processProductAtStartup("ss"); + monitor.fireMonitorEvent(monitor); } return monitor; } + // TODO: Provide the changes in EDEX URIFilters when area configuration file + // has been changed. /** - * DR#11279: - * When monitor area configuration is changed, - * this module is called to re-initialize monitor - * using new monitor area configuration + * DR#11279: When monitor area configuration is changed, this module is + * called to re-initialize monitor using new monitor area configuration */ public static void reInitialize() { - if ( monitor != null ) { - monitor = null; - monitor = new SafeSeasMonitor(); - } - } - - /** - * Creates the maps - */ - private void createDataStructures() { - // [Jan 21, 2010, zhao] - obData = new ObMultiHrsReports(CommonConfig.AppName.SAFESEAS); - obData.setThresholdMgr(SSThresholdMgr.getInstance()); - - algorithmData = new HashMap>(); - } - - public void launchDialog(String type, Shell shell) { - - if (type.equals("zone")) { - if (zoneDialog == null) { - zoneDialog = new SSZoneTableDlg(shell, obData); - addMonitorListener(zoneDialog); - zoneDialog.addMonitorControlListener(this); - } - zoneDialog.open(); - fireMonitorEvent(zoneDialog.getClass().getName()); - } else if (type.equals("area")) { - areaDialog = new SSMonitoringAreaConfigDlg(shell, - "Safe Seas Monitor Area Configuration"); - areaDialog.open(); + if (monitor != null) { + monitor = null; + monitor = new SafeSeasMonitor(); } } + /** + * Creates the maps + */ + private void createDataStructures() { + obData = new ObMultiHrsReports(CommonConfig.AppName.SAFESEAS); + obData.setThresholdMgr(SSThresholdMgr.getInstance()); + algorithmData = new HashMap>(); + } + + /** + * Launch SAFESEAS Zone Dialog + * + * @param type + * @param shell + */ + public void launchDialog(String type, Shell shell) { + + if (type.equals("zone")) { + if (zoneDialog == null || zoneDialog.getShell() == null + || zoneDialog.isDisposed()) { + zoneDialog = new SSZoneTableDlg(shell, obData); + addMonitorListener(zoneDialog); + zoneDialog.addMonitorControlListener(this); + fireMonitorEvent(zoneDialog.getClass().getName()); + zoneDialog.open(); + } else { + zoneDialog.bringToTop(); + } + } else if (type.equals("area")) { + if (areaDialog == null) { + areaDialog = new SSMonitoringAreaConfigDlg(shell, + "Safe Seas Monitor Area Configuration"); + areaDialog.open(); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#filterNotifyMessage(com.raytheon + * .uf.viz.core.notification.NotificationMessage) + */ @Override public boolean filterNotifyMessage(NotificationMessage alertMessage) { - return false; } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processNotifyMessage(com.raytheon + * .uf.viz.core.notification.NotificationMessage) + */ @Override public void processNotifyMessage(NotificationMessage filtered) { - + // Not used } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processProductMessage(com.raytheon + * .uf.viz.core.alerts.AlertMessage) + */ @Override public void processProductMessage(final AlertMessage filtered) { - if (ssPattern.matcher(filtered.dataURI).matches()) { - // System.out.println("Found match: " + ssPattern + " URI: " - // + filtered.dataURI); - processURI(filtered.dataURI, filtered); - } + if (ssPattern.matcher(filtered.dataURI).matches()) { + processURI(filtered.dataURI, filtered); + } } + /** + * Adds data to station table + * + * @param trd + * @param stationID + */ public void addToStationDataTable(TableRowData trd, String stationID) { int numberCell = trd.getNumberOfCellData(); TableRowData stationRowData = new TableRowData(numberCell + 1); @@ -233,7 +281,6 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { for (int i = 0; i < numberCell; i++) { stationRowData.setTableCellData(i + 1, trd.getTableCellData(i)); } - stationTableData.addReplaceDataRow(stationRowData); } @@ -245,22 +292,28 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { * -- the xml configuration filename */ public void readTableConfig(String file) { - HashMap> zones = new HashMap>(); + Map> zones = new HashMap>(); // create zones and station list try { SSMonitorConfigurationManager areaConfig = getMonitorAreaConfig(); for (String zone : areaConfig.getAreaList()) { - ArrayList stations = areaConfig.getAreaStations(zone); + List stations = areaConfig.getAreaStations(zone); zones.put(zone, stations); } } catch (Exception e) { - System.out.println("SafeSeas failed to load configuration..." - + this.getClass().getName()); + statusHandler.handle(Priority.CRITICAL, + "SafeSeas failed to load configuration..." + + this.getClass().getName(), e); } MonitoringArea.setPlatformMap(zones); } - public SSMonitorConfigurationManager getMonitorAreaConfig() { + /** + * Gets configuration manager + * + * @return safeseasConfig + */ + private SSMonitorConfigurationManager getMonitorAreaConfig() { if (safeseasConfig == null) { LocalizationManager mgr = LocalizationManager.getInstance(); String siteScope = mgr.getCurrentSite(); @@ -271,104 +324,144 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { return safeseasConfig; } - private Pattern ssPattern = Pattern - .compile(URIFilter.uriSeperator + OBS + URIFilter.uriSeperator - + wildCard + URIFilter.uriSeperator + wildCard - + URIFilter.uriSeperator + cwa + URIFilter.uriSeperator - + wildCard + URIFilter.uriSeperator + wildCard - + URIFilter.uriSeperator + wildCard - + URIFilter.uriSeperator + "ss"); - + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.Monitor#initObserver(java.lang.String, + * com.raytheon.uf.viz.monitor.Monitor) + */ @Override public void initObserver(String pluginName, Monitor monitor) { ProductAlertObserver.addObserver(pluginName, this); - } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#thresholdUpdate(com.raytheon.uf + * .viz.monitor.events.IMonitorThresholdEvent) + */ @Override public void thresholdUpdate(IMonitorThresholdEvent me) { fireMonitorEvent(zoneDialog.getClass().getName()); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#configUpdate(com.raytheon.uf.viz + * .monitor.events.IMonitorConfigurationEvent) + */ @Override public void configUpdate(IMonitorConfigurationEvent me) { - + // Not used } /** - * Kill this monitor by nullifying the monitor's private instance variable. + * Kills this monitor by nullifying the monitor's private instance variable. + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ObsMonitor#nullifyMonitor() */ @Override public void nullifyMonitor() { - // /** - // * Before making the monitor null, remove observers - // */ - // for (String p : pluginName) { - // if (!pluginName.equals("")) { - // stopObserver(p, this); - // } - // } monitor.removeMonitorListener(zoneDialog); monitor.fogResources.removeAll(getMonitorListeners()); - stopObserver("fssobs", this); + stopObserver(OBS, this); monitor = null; } + /** + * @return zoneTableData + */ public TableData getZoneTableData() { return zoneTableData; } + /** + * @return stationTableData + */ public TableData getStationTableData() { return stationTableData; } + /** + * Gets data + * + * @return obData + */ public ObMultiHrsReports getObData() { return obData; } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#process(com.raytheon.uf.viz.monitor + * .data.ObReport) + */ @Override - protected void process(ObReport result) - throws Exception { - - // ProcessSafeSeasReport safeSeas = new ProcessSafeSeasReport(result); - // safeSeas.processSafeSeasReport(); - // add data to obData + protected void process(ObReport result) throws Exception { obData.addReport(result); fireMonitorEvent(this); } /** - * SSResource sets the dialogTime + * SSResource updates the dialogTime * * @param dialogTime */ public void updateDialogTime(Date dialogTime) { - this.dialogTime = dialogTime; - fireMonitorEvent(zoneDialog.getClass().getName()); + this.dialogTime = dialogTime; + fireMonitorEvent(zoneDialog.getClass().getName()); } + /** + * @return dialogTime + */ public Date getDialogTime() { return dialogTime; } + /** + * Sets the dialogTime + * + * @param dialogTime + */ public void setDialogTime(Date dialogTime) { this.dialogTime = dialogTime; } + /** + * Add recourse listener + * + * @param issr + */ public void addSSResourceListener(ISSResourceListener issr) { safeSeasResources.add(issr); } + /** + * Remove recourse listener + * + * @param issr + */ public void removeSSResourceListener(ISSResourceListener issr) { safeSeasResources.remove(issr); } + /** + * Close dialog + */ public void closeDialog() { if (zoneDialog != null) { monitor.nullifyMonitor(); zoneDialog.removeMonitorContorlListener(this); - zoneDialog.shellDisposeDialog(); + zoneDialog.close(); zoneDialog = null; } if (areaDialog != null) { @@ -378,124 +471,130 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { } /** - * Order the dates * * @param type * @return + * + * (non-Javadoc) + * @see com.raytheon.uf.viz.monitor.IMonitor#getTimeOrderedKeys(com.raytheon. + * uf.viz.monitor.IMonitor, java.lang.String) */ + @Override public ArrayList getTimeOrderedKeys(IMonitor monitor, String type) { + // Not used return null; } /** - * Get most recent time + * Gets area geometries * - * @param type - * @return + * @return zoneGeometries */ - public DataTime getMostRecent(IMonitor monitor, String type) { - return null; + public Map getMonitoringAreaGeometries() { + if (zoneGeometries == null) { + ArrayList zones = getMonitorAreaConfig().getAreaList(); + zoneGeometries = new HashMap(); + for (String zone : zones) { + try { + zoneGeometries.put(zone, + MonitorAreaUtils.getZoneGeometry(zone)); + } catch (Exception e) { + statusHandler.handle(Priority.PROBLEM, + "Error get Monitoring Area Config", e); + } + } + } + return zoneGeometries; } - public HashMap getMonitoringAreaGeometries() { - if (zoneGeometries == null) { - ArrayList zones = getMonitorAreaConfig().getAreaList(); - zoneGeometries = new HashMap(); - for (String zone : zones) { - try { - zoneGeometries.put(zone, - MonitorAreaUtils.getZoneGeometry(zone)); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return zoneGeometries; - } + /** + * Gets threats + * + * @param refTime + * @param zoneThreats + */ + public void setAlgorithmData(Date refTime, + Map zoneThreats) { + if (algorithmData.containsKey(refTime)) { + algorithmData.remove(refTime); + } + algorithmData.put(refTime, zoneThreats); + } - public void setAlgorithmData(Date refTime, - HashMap zoneThreats) { - if (algorithmData.containsKey(refTime)) { - algorithmData.remove(refTime); - } - algorithmData.put(refTime, zoneThreats); - } + /** + * Gets the algorithm threat by time + * + * @param time + * @return algData + */ + public Map getAlgorithmData(Date time) { - /** - * Gets the algorithm threat - * - * @param zone - * @return - */ - public HashMap getAlgorithmData(Date time) { + Map algData = new HashMap(); - HashMap algData = new HashMap(); + if ((algorithmData != null) && algorithmData.containsKey(time)) { + algData = algorithmData.get(time); + } else { + // by default is nothing in the Fog column + for (String zone : MonitoringArea.getPlatformMap().keySet()) { + algData.put(zone, FOG_THREAT.GRAY); + } + } + return algData; + } - if ((algorithmData != null) && algorithmData.containsKey(time)) { - algData = algorithmData.get(time); - } else { - // default nothing in Fog column - for (String zone : MonitoringArea.getPlatformMap().keySet()) { - algData.put(zone, FOG_THREAT.GRAY); - } - } - return algData; - } + /** + * Gets Fog threat types. + * + * @param fogAlgThreats + * @return types + */ + public Map getAlgCellTypes( + Map fogAlgThreats) { + Map types = new HashMap(); + for (String zone : fogAlgThreats.keySet()) { + CellType type = getAlgorithmCellType(fogAlgThreats.get(zone)); + types.put(zone, type); + } + return types; + } - public HashMap getAlgCellTypes( - HashMap fogAlgThreats) { - HashMap types = new HashMap(); - for (String zone : fogAlgThreats.keySet()) { - CellType type = getAlgorithmCellType(fogAlgThreats.get(zone)); - types.put(zone, type); - } - return types; - } + /** + * Gets cell threat type + * + * @param fog_THREAT + * @return type + */ + private CellType getAlgorithmCellType(FOG_THREAT fog_THREAT) { + CellType type = CellType.NotDetermined; + if (fog_THREAT == FogRecord.FOG_THREAT.GREEN) { + type = CellType.G; + } else if (fog_THREAT == FogRecord.FOG_THREAT.YELLOW) { + type = CellType.Y; + } else if (fog_THREAT == FogRecord.FOG_THREAT.RED) { + type = CellType.R; + } + return type; + } - private CellType getAlgorithmCellType(FOG_THREAT fog_THREAT) { - CellType type = CellType.NotDetermined; - if (fog_THREAT == FogRecord.FOG_THREAT.GREEN) { - type = CellType.G; - } else if (fog_THREAT == FogRecord.FOG_THREAT.YELLOW) { - type = CellType.Y; - } else if (fog_THREAT == FogRecord.FOG_THREAT.RED) { - type = CellType.R; - } - return type; - } - - /** - * Get most recent time - * - * @param type - * @return - */ - public DataTime getMostRecent() { - DataTime time = null; - Set ds = this.algorithmData.keySet(); - DataTime[] times = new DataTime[ds.size()]; - int i = 0; - for (Date d : ds) { - times[i] = new DataTime(d); - i++; - } - java.util.Arrays.sort(times); - if (times.length > 0) { - time = times[times.length - 1]; // most recent - } - - return time; - } - - public ZoneTableDlg getDialog() { - return zoneDialog; - } + /** + * Gets zone dialog + * + * @return zoneDialog + */ + public ZoneTableDlg getDialog() { + return zoneDialog; + } + /** + * Gets adjacent areas + */ public void getAdjAreas() { this.setGeoAdjAreas(AdjacentWfoMgr.getAdjacentAreas(cwa)); } /** + * Sets geometry of adjacent areas + * * @param geoAdjAreas * the geoAdjAreas to set */ @@ -504,6 +603,8 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { } /** + * Gets geometry of adjacent areas + * * @return the geoAdjAreas */ public Geometry getGeoAdjAreas() { @@ -511,6 +612,8 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { } /* + * Updates data of Fog monitor + * * (non-Javadoc) * * @see @@ -531,9 +634,25 @@ public class SafeSeasMonitor extends ObsMonitor implements ISSResourceListener { } - @Override - protected void processAtStartup(ObReport report) { - obData.addReport(report); - } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processAtStartup(com.raytheon. + * uf.viz.monitor.data.ObReport) + */ + @Override + protected void processAtStartup(ObReport report) { + obData.addReport(report); + } + + /** + * Gets SAFESEAS zone table dialog + * + * @return + */ + public SSZoneTableDlg getZoneDialog() { + return zoneDialog; + } } diff --git a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/resources/SSFogThreat.java b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/resources/SSFogThreat.java index 65862cee51..6e29df08b7 100644 --- a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/resources/SSFogThreat.java +++ b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/resources/SSFogThreat.java @@ -19,9 +19,8 @@ **/ package com.raytheon.uf.viz.monitor.safeseas.resources; -import java.awt.Point; -import java.util.ArrayList; import java.util.HashMap; +import java.util.Map; import org.eclipse.swt.widgets.Display; import org.opengis.referencing.FactoryException; @@ -29,17 +28,16 @@ import org.opengis.referencing.operation.TransformException; import com.raytheon.uf.common.dataplugin.fog.FogRecord; import com.raytheon.uf.common.dataplugin.fog.FogRecord.FOG_THREAT; -import com.raytheon.uf.common.dataplugin.fog.analysis.FogCell; -import com.raytheon.uf.common.dataplugin.fog.analysis.FogDataCorrector; -import com.raytheon.uf.common.dataplugin.fog.analysis.FogMonitorUtils; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; import com.raytheon.uf.common.geospatial.ReferencedObject.Type; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.viz.monitor.fog.FogCommonThreat; import com.raytheon.uf.viz.monitor.fog.xml.FogMonitorAlgorithmXML; import com.raytheon.uf.viz.monitor.safeseas.SafeSeasMonitor; -import com.vividsolutions.jts.algorithm.locate.SimplePointInAreaLocator; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.geom.GeometryFactory; /** * FogThreat for SafeSeas monitor @@ -49,47 +47,22 @@ import com.vividsolutions.jts.geom.GeometryFactory; * SOFTWARE HISTORY * * Date Ticket# Engineer Description - * ------------ ---------- ----------- -------------------------- - * Apr 30, 2011 #4981 skorolev Initial creation + * ------------ ---------- ----------- ----------------- + * Apr 30, 2011 #4981 skorolev Initial creation + * Oct.30, 2012 #1297 skorolev Changed HashMap to Map * * * * @author skorolev * @version 1.0 */ -public class SSFogThreat { +public class SSFogThreat extends FogCommonThreat { - /** list of coordinates for each zone **/ - public HashMap> zoneCoordinates = null; + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(SSFogThreat.class); - private final GeometryFactory geoFactory = new GeometryFactory(); - - private FogRecord fog = null; - - private FogMonitorAlgorithmXML fogAlgXML = null; - - private Geometry geoAdjAreas = null; - - public FOG_THREAT[] threats = null; - - public ArrayList cells = null; - - public float[] ir_diff_thresholds = null; - - public float[] vis_thresholds = null; - - public int twilight_angle_offset = 0; - - // boolean filter switches - public boolean isSnowIce = true; - - public boolean isFractalDimension = true; - - public boolean isSmoothness = true; - - public boolean isAdjacency = true; - - private SafeSeasMonitor monitor; + /** SafeSeasMonitor monitor **/ + private SafeSeasMonitor ssmonitor = SafeSeasMonitor.getInstance(); /** * serialization constructor @@ -104,696 +77,27 @@ public class SSFogThreat { public SSFogThreat(FogMonitorAlgorithmXML fogAlgXML) { this.fogAlgXML = fogAlgXML; setThresholdArrays(); - } - - /** - * This method will be called with the switches from the GUI front end - * - * Fog Product [T(10.7) - (T(3.9)] or VIS (normalized count) Maximum cloud temperature Daytime - * Ice/Snow vs Fog Threshold (c) (FogSnowIceFilter) Cool Fog vs Warm Surface threshold Daytime - * Smoothness Algorithm (FogSmoothnessFilter) Adjacency Threshold Twilight Angle Threshold - * Fractal Dimension Threshold (FogFractalFilter) - */ - public FogRecord getFogThreat(FogRecord fog) { - this.fog = fog; - if (fog.getVisArray() == null) - return fog; - System.out.println("FogThreat for SS: Start analyzing Fog Threat..."); - long start = System.currentTimeMillis(); - // String cwa = fog.getCwa(); - geoAdjAreas = getSafeSeasMonitor().getGeoAdjAreas(); - // clear threats array, make gray (SK)i=>x j=>y - for (int i = 0; i < fog.getNx(); i++) { - for (int j = 0; j < fog.getNy(); j++) { - //(SK) getThreats()[fog.getNy() * i + j] = FOG_THREAT.GRAY; - getThreats()[fog.getNx() * j + i] = FOG_THREAT.GRAY; - } - } - - // First execute the data corrector, this divides up the FogRecord field - // into Day, Night, and Twilight. - FogDataCorrector fdc = new FogDataCorrector(getFog(), fogAlgXML.getTwilightAngle()); - fog = fdc.execute(); - - // Second, core processor. Gets you the cells, sets non-filtered values. - executeCoreProcessor(); - - // Third, apply filters - for (FogCell cell : getCells()) { - // *********** APPLY FILTERS ******************* - - // Area Size filter - if (fogAlgXML.isAdjacencyThreshOn() && cell.getCellThreat() != FOG_THREAT.GREEN - && cell.getCellThreat() != FOG_THREAT.GRAY) { - - if (cell.getArea() < fogAlgXML.getAdjacencyThresh()) { - setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); - } - } - - // Snow & Ice filter - if (fogAlgXML.isIceSnowVsFogOn() - && cell.getImageGroup() == FogRecord.IMAGE_GROUP.VIS_GROUP - && (cell.getCellThreat() != FOG_THREAT.GREEN || cell.getCellThreat() != FOG_THREAT.GRAY)) { - - float tempMean = calAverageTemp(cell); - - if (tempMean < fogAlgXML.getIceSnowVsFog()) { - downgradeThreat(cell); - } - } - - // Smoothness filter - if (fogAlgXML.isDaytimeSmoothThreshOn() && cell.getCellThreat() != FOG_THREAT.GREEN - || cell.getCellThreat() != FOG_THREAT.GRAY) { - - float tem_smoothness = calSmoothness(cell); - - if (tem_smoothness < fogAlgXML.getDaytimeSmoothThresh()) { - downgradeThreat(cell); - } - } - - // Fractal filter - if (fogAlgXML.isFractalDimensionOn() && cell.getCellThreat() != FOG_THREAT.GREEN - && cell.getCellThreat() != FOG_THREAT.GRAY) { - - float temFD = calRegularity(cell); - - if (temFD > fogAlgXML.getFractalDimension() && temFD > 0.0f) { - setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); - } - } - - // We extract the zone threat differently than the GI filter - // Hence it is not needed. - } - - setThreats(); - setMonitorAreaThreats(); - System.out - .println("FogThreat for SS: Analyzed Fog Threat...Duration: " - + (System.currentTimeMillis() - start)); - return fog; - } - - /** - * Remember J is X and I is Y, totally against convention! - * Gets the threat level - * @param i (SK y) - * @param j (SK x) - * @param group - * @return - */ - private FOG_THREAT getThreatLevel(int i, int j, FogRecord.IMAGE_GROUP group) { - //(SK) i=>x, j=>y - // default return - FOG_THREAT returnValue = FOG_THREAT.GRAY; - //(SK) idx = fog.getNy() * i + j - int idx = fog.getNx() * j + i; - switch (group) { - case VIS_GROUP: - float ir4_temp = bTemp(i, j, FogRecord.CHANNEL.IR10_7); - int CLOUD_FREE_BRIGHTNESS = 68; // empirical value - // Too cold - if (ir4_temp < fogAlgXML.getMaxCloudTemp()) { - returnValue = FOG_THREAT.GRAY; - } - // overlapping high/middle cloud - - else if (fog.getVisArray()[idx] <= vis_thresholds[2] - && fog.getVisArray()[idx] >= vis_thresholds[1]) { - - returnValue = FOG_THREAT.RED; - } else if (fog.getVisArray()[idx] < vis_thresholds[1] - && fog.getVisArray()[idx] >= vis_thresholds[0] - || fog.getVisArray()[idx] <= vis_thresholds[3] - && fog.getVisArray()[idx] > vis_thresholds[2]) { - - returnValue = FOG_THREAT.YELLOW; - } - - // This is essentially the Cool Fog vs. Warm surface threshold check - else if (fogAlgXML.isCoolFogVsWarmSurfaceOn() - && ir4_temp >= fogAlgXML.getCoolFogVsWarmSurface()) { - returnValue = FOG_THREAT.GREEN; - } - - else if (fog.getVisArray()[idx] < CLOUD_FREE_BRIGHTNESS) { - returnValue = FOG_THREAT.GREEN; - } - - return returnValue; - - case IR_GROUP: - // for some odd reason j is x and i is y, - // not sure why AWIPS 1 does it this way. - // It is completely against convention. - //Point tempoint = new Point(j, i); - //(SK) here i=>x and j=>y - Point tempoint = new Point(i, j); - float tempIR10_7 = temp_at_vis_pixel(tempoint, FogRecord.CHANNEL.IR10_7); - if (tempIR10_7 < fogAlgXML.getMaxCloudTemp()) { - // Too cold - returnValue = FOG_THREAT.GRAY; - } - // Overlapping high/middle cloud - float tempIR3_9 = temp_at_vis_pixel(tempoint, FogRecord.CHANNEL.IR3_9); - float tempDiff = tempIR10_7 - tempIR3_9; - - if (tempDiff <= ir_diff_thresholds[2] && tempDiff >= ir_diff_thresholds[1]) { - returnValue = FOG_THREAT.RED; - } else if (tempDiff < ir_diff_thresholds[1] && tempDiff >= ir_diff_thresholds[0] - || tempDiff <= ir_diff_thresholds[3] && tempDiff > ir_diff_thresholds[2]) { - returnValue = FOG_THREAT.YELLOW; - } else { - returnValue = FOG_THREAT.GREEN; - } - - case TWILIGHT_GROUP: - // do nothing, stays gray - } - - return returnValue; - } - - /** - * Precursor call to get temp at pixel - * - * @param i - * @param j - * @param imgtype - * @return - */ - private float bTemp(int i, int j, FogRecord.CHANNEL imgtype) { - //(SK) here i=>x and j=>y - // for some odd reason j is x and i is y, - // not sure why AWIPS 1 does it this way. - // It is completely against convention. - - Point tempoint = new Point(i, j); - return temp_at_vis_pixel(tempoint, imgtype); - } - - /** - * Get the temp at the pixel - * - * @param pointVis - * @param channel - * @return - */ - private float temp_at_vis_pixel(Point pointVis, FogRecord.CHANNEL channel) { - // The assumption is that Dimensions of IR4 and IR2 are the same. - // IR4 data will be always needed, so attributes for IR4 shall be - // always available. - // **** ATTENTION ***** We have made the vis the same as well for AWIPS - // II - int count_value = 255; - if (channel == FogRecord.CHANNEL.IR3_9) { - count_value = fog.getIR_3_9Array()[fog.getNx() * pointVis.y + pointVis.x]; - //(SK) count_value = fog.getIR_3_9Array()[fog.getNy() * pointVis.x + pointVis.y]; - } else if (channel == FogRecord.CHANNEL.IR10_7) { - count_value = fog.getIR_10_7Array()[fog.getNx() * pointVis.y + pointVis.x]; - //(SK) count_value = fog.getIR_10_7Array()[fog.getNy() * pointVis.x + pointVis.y]; - } - return FogMonitorUtils.count2temp(count_value, channel); - } - - /** - * Gets the fog - * - * @return - */ - public FogRecord getFog() { - return fog; - } - - /** - * Gets the existing array of threats - * - * @return - */ - public FOG_THREAT[] getThreats() { - if (threats == null) { - threats = new FOG_THREAT[getFog().getNx() * getFog().getNy()]; - } - return threats; - } - - /** - * Gets the cells of this analysis - * - * @return - */ - public ArrayList getCells() { - return cells; - } - - /** - * Gets the existing threat value at that point - * - * @return - */ - public FOG_THREAT getThreat(int i, int j) { - return getThreats()[fog.getNx() * j + i]; - //(SK) return getThreats()[fog.getNy() * i + j]; - } - - /** - * Set fog threat at threat level point - * - * @param i - * @param j - * @param threat - */ - private void setThreat(int i, int j, FOG_THREAT threat) { - //(SK) getThreats()[fog.getNy() * i + j] = threat; - getThreats()[fog.getNx() * j + i] = threat; - } - - /** - * Downgrade the Fog Threat - * - * @param current - * @param i - * @param j - */ - private void downgradeThreat(FogCell cell) { - if (cell.getCellThreat() == FOG_THREAT.YELLOW) { - setCellThreats(cell.getPoints(), FOG_THREAT.GREEN); - } else if (cell.getCellThreat() == FOG_THREAT.RED) { - setCellThreats(cell.getPoints(), FOG_THREAT.YELLOW); - } - } - - // // *********************** FILTERS **************************** ///// - - // -Private-------------------------------------------------------------------- - // NAME: CalRegularity() - // - // TYPE: Private Member function - // - // Descript: - // Given a cell, calculate its regularity i.e. the fractal dimension - // Input Arguments: - // cell: The Fog_Cell whose fractal dimension is to be measured - // Output Arguments: - // Return float: fractal dimension. the value is between 1 to 2 - // smaller means more regular. - // Here use the perimeter and area relation to represent - // fractal dimension (one of the simply ways) - // History: - // May 2004 Qin Zeng (GDMB/MDL) -- created - // Dec 2009 D Hladky translated to Java - // ----------------------------------------------------------------------------- - - private float calRegularity(FogCell cell) { - - int nx = cell.right - cell.left + 1; - int ny = cell.bottom - cell.top + 1; - int i; - boolean[] flag = new boolean[nx * ny]; - - for (i = 0; i < nx * ny; i++) { - flag[i] = false; - } - - int pixels_num = (int) cell.getArea(); - int flagPos; - for (i = 0; i < pixels_num; i++) { - Coordinate coor = cell.getPixelCoordinate(i); - flagPos = (int) ((coor.y - cell.top) * nx + coor.x - cell.left); - if (flagPos >= 0 && flagPos < nx * ny) { - flag[flagPos] = true; - } - } - // From here, perimeter of the fog cell will be calculated; - // |...| 1 |...| - // | 4 | 0 | 2 | - // |...| 3 |...| - // - // If the any of the 0's surrounding pixels(1,2,3,4) is flagged as false, - // which means that surrounding pixel(1,2,3,or 4) is not included in - // the cell, pixel 0 then will be at the edge of the cell cluster. - // And the edge connecting to the outside pixel will be counted into the - // perimeter of the cell cluster. - - int pos1, pos2, pos3, pos4; - float perimeter = 0; - for (i = 0; i < pixels_num; i++) { - Coordinate coor = cell.getPixelCoordinate(i); - - pos1 = (int) ((i - cell.top - 1) * nx + coor.y - cell.left); - if (pos1 >= 0 && pos1 < nx * ny && !flag[pos1] || i - coor.x < cell.top) { - perimeter++; - } - - pos2 = (int) ((coor.y - cell.top) * nx + coor.x + 1 - cell.left); - if (pos2 >= 0 && pos2 < nx * ny && !flag[pos2] || coor.x + 1 > cell.right) { - perimeter++; - } - - pos3 = (int) ((coor.y - cell.top + 1) * nx + coor.x - cell.left); - if (pos3 >= 0 && pos3 < nx * ny && !flag[pos3] || coor.y + 1 > cell.bottom) { - perimeter++; - } - - pos4 = (int) ((coor.y - cell.top) * nx + coor.x - 1 - cell.left); - if (pos4 >= 0 && pos4 < nx * ny && !flag[pos4] || coor.x - 1 < cell.left) { - perimeter++; - } - } - - float fractalDimension = 1.0f; - - if (cell.getArea() != 1) { - fractalDimension = (float) (2 * Math.log(perimeter / 4.0) / Math.log(cell.getArea())); - } - - // Note : fractalDimension is a data between 1 and 2 and the larger - // fractalDimension is , the more irregular the shape of the cell will - // be. - - return fractalDimension; - } - - // -Private-------------------------------------------------------------------- - // NAME: CalSmoothness() - // - // TYPE: Private Member function - // - // Descript: - // Given a cell, calculate the its smoothness - // Input Arguments: - // cell: The Fog_Cell whose smoothness is to be measured - // Output Arguments: - // return float: smoothness defined above - // History: - // May 2004 Qin Zeng (GDMB/MDL) -- created - // Dec 2009 D Hladky ported to AWIPS II - // ----------------------------------------------------------------------------- - private float calSmoothness(FogCell cell) { - - float mean = 0; // mean grayscale value of pixels in the cell from VIS. - float stdDev = 0; // standard deviation - int pixels_num = (int) cell.getArea(); - - if (pixels_num == 0) { - return 0; - } - - int i; - for (i = 0; i < pixels_num; i++) { - Coordinate pixr = cell.getPixelRelativeCoordinate(i); - //(SK) mean += getFog().getVisArray()[(int) (getFog().getNy() * pixr.x + pixr.y)]; - mean += getFog().getVisArray()[(int) (getFog().getNx() * pixr.y + pixr.x)]; - } - - mean /= pixels_num; - float tem_float; - - for (i = 0; i < pixels_num; i++) { - Coordinate pixr = cell.getPixelRelativeCoordinate(i); - //(SK) tem_float = getFog().getVisArray()[(int) (getFog().getNy() * pixr.x + pixr.y)]; - tem_float = getFog().getVisArray()[(int) (getFog().getNx() * pixr.y + pixr.x)]; - stdDev += (tem_float - mean) * (tem_float - mean); - } - - stdDev /= pixels_num; - stdDev = (float) Math.sqrt(stdDev); - // mean should not be zero, so no need to check mean here. - return (1 - stdDev / mean) * 100; // use percent as unit - } - - // -Private--------------------------------------------------------------------- - // NAME: Cal() - // - // TYPE: Private Member function - // - // Descript: - // Calculate the average temperature for a Fog_Cell in channel 3.9 um - // History: - // May 2004 Qin Zeng (GDMB/MDL) -- created - // ----------------------------------------------------------------------------- - - private float calAverageTemp(FogCell cell) { - float mean = 0; // mean temperature value of pixels in the cell. - int pixels_num = (int) cell.getArea(); - if (pixels_num == 0) { - return -999.9f; - } - for (int i = 0; i < pixels_num; i++) { - Coordinate pixc = cell.getPixelRelativeCoordinate(i); - mean += temp_at_vis_pixel(new Point((int) pixc.x, (int) pixc.y), - FogRecord.CHANNEL.IR3_9); - } - - mean /= pixels_num; - return mean; - } - - // -Public--------------------------------------------------------------------- - // NAME: Execute() - // - // TYPE: Private Member function - // - // Descript: - // Based on the thresholds of the VIS image data and the IR image data, - // a number of patches of the contiguous suspected fog areas will be - // extracted from the satellite image data. - // This is an implementation of the feature extraction algorithm based - // on the contiguous gray scale values. - // - // Arguments: None - // History: - // March 2004 Qin Zeng (GDMB/MDL) -- created - // Dec 2009 D Hladky ported to Java for AWIPS II - // ----------------------------------------------------------------------------- - private void executeCoreProcessor() { - - cells = new ArrayList(); - ArrayList parent = new ArrayList(); - ArrayList child = new ArrayList(); - ArrayList single_segment = new ArrayList(); - - int x_dim = getFog().getNx(); - int y_dim = getFog().getNy(); - int i; //(SK) x - int j; //(SK) y - // To flag whether a pixel has been visited or not - boolean[][] visited = new boolean[x_dim][y_dim]; - - Point[] s = new Point[8]; // 8 surrounding points of one specific point - for (int z = 0; z < s.length; z++) { - s[z] = new Point(); - } - - Point tempoint = new Point(); - getCells().clear(); - - for (i = 0; i < x_dim; i++) { - for (j = 0; j < y_dim; j++) { - visited[i][j] = false; - } - } - - for (j = 0; j < y_dim; j++) { - Point firstone = new Point(); - FOG_THREAT threat_level = FOG_THREAT.BLACK; - FogRecord.IMAGE_GROUP imggroup; - for (i = 0; i < x_dim; i++) { - if (visited[i][j]) { - continue; - } - Coordinate cellCoor = this.getCellCoor(i, j); - visited[i][j] = true; - imggroup = getFog().findGroup(i, j); - threat_level = getThreatLevel(i, j, imggroup); - // Sets the initial threat level - setThreat(i, j, threat_level); - firstone.x = i; - firstone.y = j; - parent.clear(); - tempoint.y = j; - tempoint.x = i; - single_segment.add(tempoint); - parent.add(tempoint); - while (parent.size() != 0) { - // the variables(s[1],s[2]...) below mean surrounding 1,2 - // | 0 | 1 | 2 | - // | 7 | i | 3 | - // | 6 | 5 | 4 | - // iteratively search the 8-connected surrounding pixels - child.clear(); - for (int k = 0; k < parent.size(); k++) { - // y's too small, too big - if (parent.get(k).y == 0) { - s[0].y = parent.get(k).y; - s[1].y = parent.get(k).y; - s[2].y = parent.get(k).y; - } - if (parent.get(k).y == y_dim - 1) { - s[4].y = parent.get(k).y; - s[5].y = parent.get(k).y; - s[6].y = parent.get(k).y; - } - // x's too small, too big - if (parent.get(k).x == 0) { - s[0].x = parent.get(k).x; - s[6].x = parent.get(k).x; - s[7].x = parent.get(k).x; - } - if (parent.get(k).x == x_dim - 1) { - s[2].x = parent.get(k).x; - s[3].x = parent.get(k).x; - s[4].x = parent.get(k).x; - } - // all others - if (parent.get(k).x > 0 && parent.get(k).x < x_dim - 1 - && parent.get(k).y == y_dim - 1 && parent.get(k).y > 0) { - s[0].y = parent.get(k).y - 1; - s[0].x = parent.get(k).x - 1; - s[1].y = parent.get(k).y - 1; - s[1].x = parent.get(k).x; - s[2].y = parent.get(k).y - 1; - s[2].x = parent.get(k).x + 1; - s[3].y = parent.get(k).y; - s[3].x = parent.get(k).x + 1; - s[4].y = parent.get(k).y + 1; - s[4].x = parent.get(k).x + 1; - s[5].y = parent.get(k).y + 1; - s[5].x = parent.get(k).x; - s[6].y = parent.get(k).y + 1; - s[6].x = parent.get(k).x - 1; - s[7].y = parent.get(k).y; - s[7].x = parent.get(k).x - 1; - } - FogRecord.IMAGE_GROUP temgroup; - FOG_THREAT temthreat; - - for (int m = 0; m < 8; m++) { - if (s[m].y >= 0 && s[m].y < y_dim && s[m].x >= 0 && s[m].x < x_dim) { - int ii = s[m].x; - int jj = s[m].y; - //(SK) int ii = s[m].y; - //(SK) int jj = s[m].x; - - if (!visited[ii][jj]) { - temgroup = getFog().findGroup(ii, jj); - temthreat = getThreatLevel(ii, jj, temgroup); - if (temgroup == imggroup && temthreat == threat_level) { - child.add(s[m]); - visited[ii][jj] = true; - single_segment.add(s[m]); - } - }// end of if - }// end of if - }// end of for m - }// end of for k - parent = child; - }// end of while - // if - // (!this.geoAdjAreas.contains(geoFactory.createPoint(cellCoor))) - // { - int lct = SimplePointInAreaLocator.locate(cellCoor, - this.geoAdjAreas); - if (lct == 2) { - threat_level = FOG_THREAT.BLACK; - setThreat(i, j, threat_level); - } - getCells().add(new FogCell(single_segment, threat_level, imggroup)); - single_segment.clear(); - } // end of for j - } // end of for i - } - - /** - * Sets all points in the cell to the cell filtered value threat - * - * @param cells - * @param threat - */ - private void setCellThreats(ArrayList points, FOG_THREAT threat) { - for (Point point : points) { - getThreats()[fog.getNx() * point.y + point.x] = threat; - //(SK) getThreats()[fog.getNy() * point.x + point.y] = threat; - } - } - - /** - * Gets the drawable float array of threats - * - * @return - */ - private void setThreats() { - float[] floats = new float[getThreats().length]; - int i = 0; - for (FOG_THREAT threat : getThreats()) { - floats[i] = getThreatValue(threat); - i++; - } - - getFog().setThreats(floats); - } - - /** - * Sets the thresholds - */ - private void setThresholdArrays() { - ir_diff_thresholds = new float[4]; - vis_thresholds = new float[4]; - - ir_diff_thresholds[0] = (float) fogAlgXML.getFogProductYLo(); - ir_diff_thresholds[1] = (float) fogAlgXML.getFogProductYHi(); - ir_diff_thresholds[2] = (float) fogAlgXML.getFogProductRLo(); - ir_diff_thresholds[3] = (float) fogAlgXML.getFogProductRHi(); - - vis_thresholds[0] = (float) fogAlgXML.getVisYLo(); - vis_thresholds[1] = (float) fogAlgXML.getVisYHi(); - vis_thresholds[2] = (float) fogAlgXML.getVisRLo(); - vis_thresholds[3] = (float) fogAlgXML.getVisRHi(); - } - - /** - * Quick static method to get the float to threat mapping - * - * @param threat - * @return - */ - public static float getThreatValue(FOG_THREAT threat) { - float value = 0; - - if (threat == FOG_THREAT.BLACK) { - value = 0.0f; - } else if (threat == FOG_THREAT.GRAY) { - value = 15.0f; - } else if (threat == FOG_THREAT.GREEN) { - value = 60.0f; - } else if (threat == FOG_THREAT.YELLOW) { - value = 110.0f; - } else if (threat == FOG_THREAT.RED) { - value = 220.0f; - } - return value; + zoneGeos = ssmonitor.getMonitoringAreaGeometries(); + geoAdjAreas = ssmonitor.getGeoAdjAreas(); } /** * Gets the zone threats (ALG) with worst case for zone area * - * @return HashMap + * @return Map zoneThreats */ public void setMonitorAreaThreats() { final FogRecord ffogRec = getFog(); - final SafeSeasMonitor fmonitor = getSafeSeasMonitor(); // TODO: async or sync ???? Display.getDefault().asyncExec(new Runnable() { - public void run() { + public void run() { long start = System.currentTimeMillis(); - HashMap zoneGeos = fmonitor.getMonitoringAreaGeometries(); + Map zoneGeos = ssmonitor + .getMonitoringAreaGeometries(); // set to lowest for default - HashMap zoneThreats = new HashMap(); + Map zoneThreats = new HashMap(); for (String zone : zoneGeos.keySet()) { zoneThreats.put(zone, FOG_THREAT.BLACK); } @@ -801,75 +105,47 @@ public class SSFogThreat { for (int i = 0; i < ffogRec.getNx(); i++) { for (int j = 0; j < ffogRec.getNy(); j++) { - ReferencedCoordinate rc = new ReferencedCoordinate(new Coordinate(i, j), + ReferencedCoordinate rc = new ReferencedCoordinate( + new Coordinate(i, j), ffogRec.getGridGeometry(), Type.GRID_CENTER); Coordinate coor = null; try { coor = rc.asLatLon(); } catch (TransformException e) { - e.printStackTrace(); + statusHandler.handle(Priority.ERROR, e.getMessage()); } catch (FactoryException e) { - e.printStackTrace(); + statusHandler.handle(Priority.ERROR, e.getMessage()); } - for (String zone : zoneGeos.keySet()) { - if (zoneGeos.get(zone) != null) { - if (zoneGeos.get(zone).contains( - geoFactory.createPoint(coor))) { - try { - if (getThreatValue(getThreat(i, j)) > getThreatValue(zoneThreats - .get(zone))) { - zoneThreats.put(zone, - getThreat(i, j)); - } - } catch (Exception e) { - e.printStackTrace(); + for (String zone : zoneGeos.keySet()) { + if (zoneGeos.get(zone) != null) { + if (zoneGeos.get(zone).contains( + geoFactory.createPoint(coor))) { + try { + if (getThreatValue(getThreat(i, j)) > getThreatValue(zoneThreats + .get(zone))) { + zoneThreats.put(zone, + getThreat(i, j)); + } + } catch (Exception e) { + statusHandler.handle(Priority.ERROR, + e.getMessage()); } } - } - } - } - } + } + } // end zone loop + } // end j loop + } // end i loop - fmonitor.setAlgorithmData(ffogRec.getRefHour().getTime(), + ssmonitor.setAlgorithmData(ffogRec.getRefHour().getTime(), zoneThreats); - System.out - .println("FogThreat for SS: Set algorithm zone values..." - + (System.currentTimeMillis() - start)); + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.handle(Priority.DEBUG, + "FogThreat for SS: Set algorithm zone values..." + + (System.currentTimeMillis() - start)); + } } }); } - private Coordinate getCellCoor(int i, int j) { - ReferencedCoordinate rc = new ReferencedCoordinate(new Coordinate(i, j), this.getFog() - .getGridGeometry(), Type.GRID_CENTER); - Coordinate crd = null; - try { - crd = rc.asLatLon(); - } catch (TransformException e) { - e.printStackTrace(); - } catch (FactoryException e) { - e.printStackTrace(); - } - return crd; - } - - public Geometry getGeoAdjAreas() { - return geoAdjAreas; - } - - public void setGeoAdjAreas(Geometry geoAdjAreas) { - this.geoAdjAreas = geoAdjAreas; - } - - /** - * @return SafeSeasMonitor - */ - private SafeSeasMonitor getSafeSeasMonitor() { - if (monitor == null) { - monitor = SafeSeasMonitor.getInstance(); - } - return monitor; - } - } diff --git a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/actions/SafeSeasAction.java b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/actions/SafeSeasAction.java index 9426d9807b..a1a024e9bd 100644 --- a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/actions/SafeSeasAction.java +++ b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/actions/SafeSeasAction.java @@ -39,6 +39,7 @@ import com.raytheon.uf.viz.monitor.safeseas.SafeSeasMonitor; * Nov 30, 2009 3424 zhao/Slav/wkwock launch safeseas from SafeseasMonitor.getInstance() * Dec 30, 2009 3424 zhao Launch SS monitor and SS zone/station table dialog separately here * Feb 26, 2010 4282 zhao Changed to follow the same dialog launch mechanism as in FOG + * Nov 15, 2012 1297 skorolev Cleaned code * * * @@ -50,13 +51,15 @@ public class SafeSeasAction extends AbstractHandler { @Override public Object execute(ExecutionEvent arg0) throws ExecutionException { - System.out.println("Activating/Action for Safeseas..."); - - SafeSeasMonitor monitor = SafeSeasMonitor.getInstance(); - if ( monitor.zoneDialog == null || monitor.zoneDialog.isDisposed()) { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); - monitor.launchDialog("zone", shell); - } + System.out.println("Activating/Action for Safeseas..."); + + SafeSeasMonitor monitor = SafeSeasMonitor.getInstance(); + if (monitor.getZoneDialog() == null + || monitor.getZoneDialog().isDisposed()) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + monitor.launchDialog("zone", shell); + } return null; } diff --git a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSMonitoringAreaConfigDlg.java b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSMonitoringAreaConfigDlg.java index a4ae88d53d..d0c2db19b1 100644 --- a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSMonitoringAreaConfigDlg.java +++ b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSMonitoringAreaConfigDlg.java @@ -68,11 +68,10 @@ public class SSMonitoringAreaConfigDlg extends MonitoringAreaConfigDlg { configManager.setTimeWindow(timeScale.getSelection()); configManager.setUseAlgorithms(fogChk.getSelection()); configManager.saveConfigData(); - + /** - * DR#11279: - * re-initialize threshold manager and the monitor - * using new monitor area configuration + * DR#11279: re-initialize threshold manager and the monitor using + * new monitor area configuration */ SSThresholdMgr.reInitialize(); SafeSeasMonitor.reInitialize(); @@ -81,7 +80,8 @@ public class SSMonitoringAreaConfigDlg extends MonitoringAreaConfigDlg { "You're updating the SAFESEAS monitoring settings." + "\n\nIf SAFESEAS is running anywhere within " + "the office, please clear it.\n"); - if ( configManager.getAddedZones().size() > 0 || addedZones.size() > 0 ) { + if (configManager.getAddedZones().size() > 0 + || addedZones.size() > 0) { String message2 = "New zones have been added, and their monitoring thresholds " + "have been set to default values; would you like to modify " + "their threshold values now?"; diff --git a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSZoneTableDlg.java b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSZoneTableDlg.java index a1e0ead833..14e702f19e 100644 --- a/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSZoneTableDlg.java +++ b/cave/com.raytheon.uf.viz.monitor.safeseas/src/com/raytheon/uf/viz/monitor/safeseas/ui/dialogs/SSZoneTableDlg.java @@ -21,8 +21,10 @@ package com.raytheon.uf.viz.monitor.safeseas.ui.dialogs; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Shell; import com.raytheon.uf.common.dataplugin.fog.FogRecord.FOG_THREAT; @@ -30,6 +32,7 @@ import com.raytheon.uf.common.monitor.config.MonitorConfigurationManager; import com.raytheon.uf.common.monitor.config.SSMonitorConfigurationManager; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.ObConst.DataUsageKey; +import com.raytheon.uf.common.monitor.data.ObConst.DisplayVarName; import com.raytheon.uf.viz.monitor.IMonitor; import com.raytheon.uf.viz.monitor.data.ObMultiHrsReports; import com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent; @@ -38,16 +41,34 @@ import com.raytheon.uf.viz.monitor.events.IMonitorThresholdEvent; import com.raytheon.uf.viz.monitor.listeners.IMonitorListener; import com.raytheon.uf.viz.monitor.safeseas.SafeSeasMonitor; import com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg; +import com.raytheon.uf.viz.monitor.util.MonitorConfigConstants; /** - * ( where is the "SOFTWARE HISTORY" section of this file? ) + * SAFESEAS Zone Table Dialog * - * Dec 30, 2009 3424 zhao use ObMultiHrsReports for obs data archive + *
  * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Dec 30, 2009 3424       zhao         use ObMultiHrsReports for obs data archive
+ * Oct 30, 2012 1297       skorolev     Changed HashMap to Map
+ * Nov 10, 2012 1297       skorolev     Added initiateProdArray
+ * 
+ * 
+ * + * @author zhao + * @version 1.0 */ public class SSZoneTableDlg extends ZoneTableDlg { + + /** SAFESEAS threshold dialog. **/ private SSDispMonThreshDlg ssThreshDlg; + /** Swell column names in the zone and station table. **/ + private String[] ssSwellCols = { "SSZT_SwellPeriod", "SSZT_Swell2Period" }; + /** * Constructor (Dec 30, 2009, zhao) * @@ -57,10 +78,50 @@ public class SSZoneTableDlg extends ZoneTableDlg { super(parent, obData, CommonConfig.AppName.SAFESEAS); } + /** + * Constructor + * + * @param parent + */ public SSZoneTableDlg(Shell parent) { super(parent, CommonConfig.AppName.SAFESEAS); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#initiateProdArray() + */ + @Override + public void initiateProdArray() { + varName = config.getSafeseasZoneStnTableColVarNames()[colIndex]; + // Fill product arrays + prodArray = new ArrayList(); + String[] varprefs = { "VAR_", "SCA_", "GALE_", "STORM_", "HURRICANE_" }; + for (DisplayVarName var : DisplayVarName.values()) { + String dispVarName = var.name(); + if (colIndex == 1 && dispVarName.startsWith(varprefs[1])) { + prodArray.add(dispVarName); + } else if (colIndex == 2 && dispVarName.startsWith(varprefs[2])) { + prodArray.add(dispVarName); + } else if (colIndex == 3 && dispVarName.startsWith(varprefs[3])) { + prodArray.add(dispVarName); + } else if (colIndex == 4 && dispVarName.startsWith(varprefs[4])) { + prodArray.add(dispVarName); + } else if (dispVarName.startsWith(varprefs[0]) + && dispVarName.equals(varprefs[0] + varName.name())) { + prodArray.add(dispVarName); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#configThreshAction() + */ @Override protected void configThreshAction() { if (ssThreshDlg == null) { @@ -71,70 +132,123 @@ public class SSZoneTableDlg extends ZoneTableDlg { } } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.listeners.IMonitorListener#notify(com.raytheon + * .uf.viz.monitor.events.IMonitorEvent) + */ @Override public void notify(IMonitorEvent me) { if (zoneTable.isDisposed()) { return; } - if (me.getSource() instanceof SafeSeasMonitor) { - SafeSeasMonitor monitor = (SafeSeasMonitor) me.getSource(); - Date date = monitor.getDialogTime(); - if (date != null) { + if (me.getSource() instanceof SafeSeasMonitor) { + SafeSeasMonitor monitor = (SafeSeasMonitor) me.getSource(); + Date date = monitor.getDialogTime(); + if (date != null) { Date nominalTime = date; - ObMultiHrsReports obData = monitor.getObData(); - if (!isLinkedToFrame()) { - nominalTime = obData.getLatestNominalTime(); - } - HashMap fogAlgThreats = monitor + ObMultiHrsReports obData = monitor.getObData(); + if (!isLinkedToFrame()) { + nominalTime = obData.getLatestNominalTime(); + } + Map fogAlgThreats = monitor .getAlgorithmData(nominalTime); - obData.setFogAlgCellType(monitor.getAlgCellTypes(fogAlgThreats)); - this.updateTableDlg(monitor.getObData().getObHourReports(nominalTime)); - } - } + obData.setFogAlgCellType(monitor.getAlgCellTypes(fogAlgThreats)); + this.updateTableDlg(monitor.getObData().getObHourReports( + nominalTime)); + } + } } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * addMonitorControlListener(com.raytheon.uf.viz.monitor.IMonitor) + */ @Override public void addMonitorControlListener(IMonitor monitor) { getMonitorControlListeners().add(monitor); } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireConfigUpdate + * (com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent) + */ @Override public void fireConfigUpdate(IMonitorConfigurationEvent imce) { - // TODO Auto-generated method stub - + // Not used } - - + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener#fireKillMonitor + * () + */ @Override public void fireKillMonitor() { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireThresholdUpdate + * (com.raytheon.uf.viz.monitor.events.IMonitorThresholdEvent) + */ @Override public void fireThresholdUpdate(IMonitorThresholdEvent imte) { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg# + * getMonitorControlListeners() + */ @Override - public ArrayList getMonitorControlListeners() { + public List getMonitorControlListeners() { return controlListeners; } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * removeMonitorContorlListener(com.raytheon.uf.viz.monitor.IMonitor) + */ @Override public void removeMonitorContorlListener(IMonitor monitor) { getMonitorControlListeners().remove(monitor); } - @Override - protected MonitorConfigurationManager getConfigMgr() { - return SSMonitorConfigurationManager.getInstance(); - } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#getConfigMgr() + */ + @Override + protected MonitorConfigurationManager getConfigMgr() { + return SSMonitorConfigurationManager.getInstance(); + } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#handleLinkToFrame() + */ @Override protected void handleLinkToFrame() { linkedToFrame = linkToFrameChk.getSelection(); @@ -150,8 +264,7 @@ public class SSZoneTableDlg extends ZoneTableDlg { */ @Override protected void shellDisposeAction() { - // TODO Auto-generated method stub - + // Not used } /* @@ -163,7 +276,42 @@ public class SSZoneTableDlg extends ZoneTableDlg { */ @Override public void fireDialogShutdown(IMonitorListener iml) { - // TODO Auto-generated method stub + // Not used + } + @Override + protected void setZoneSortColumnAndDirection() { + if (zoneTblData != null) { + zoneSortColumn = zoneTblData.getSortColumn(); + zoneSortDirection = zoneTblData.getSortDirection(); + if (zoneSortColumn == zoneTable.getColumnIndex(appName, + ssSwellCols[0]) + || zoneSortColumn == zoneTable.getColumnIndex(appName, + ssSwellCols[1])) { + if (MonitorConfigConstants.isRankSwellPeriodHigh()) { + zoneSortDirection = SWT.DOWN; + } else { + zoneSortDirection = SWT.UP; + } + } + } + } + + @Override + protected void setStnSortColumnAndDirection() { + if (stnTblData != null) { + stnSortColumn = stnTblData.getSortColumn(); + stnSortDirection = stnTblData.getSortDirection(); + if (stnSortColumn == stationTable.getColumnIndex(appName, + ssSwellCols[0]) + || stnSortColumn == stationTable.getColumnIndex(appName, + ssSwellCols[1])) { + if (MonitorConfigConstants.isRankSwellPeriodHigh()) { + stnSortDirection = SWT.DOWN; + } else { + stnSortDirection = SWT.UP; + } + } + } } } diff --git a/cave/com.raytheon.uf.viz.monitor.scan/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.monitor.scan/META-INF/MANIFEST.MF index ab5e2df390..c061237687 100644 --- a/cave/com.raytheon.uf.viz.monitor.scan/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.monitor.scan/META-INF/MANIFEST.MF @@ -18,7 +18,6 @@ Require-Bundle: org.eclipse.ui, com.raytheon.viz.core.graphing;bundle-version="1.11.5", com.raytheon.edex.meteolib;bundle-version="1.11.5", org.apache.commons.logging;bundle-version="1.0.4", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.17", com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.0.0", com.raytheon.uf.viz.cwat;bundle-version="1.11.17", com.raytheon.uf.common.dataplugin.cwat;bundle-version="1.11.17", diff --git a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/SnowMonitor.java b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/SnowMonitor.java index 450ec979de..9255b4d559 100644 --- a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/SnowMonitor.java +++ b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/SnowMonitor.java @@ -23,6 +23,8 @@ import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.regex.Pattern; import org.eclipse.swt.widgets.Shell; @@ -30,8 +32,9 @@ import org.eclipse.swt.widgets.Shell; import com.raytheon.edex.urifilter.URIFilter; import com.raytheon.uf.common.monitor.config.SnowMonitorConfigurationManager; import com.raytheon.uf.common.monitor.data.CommonConfig; -import com.raytheon.uf.common.monitor.data.ObConst.ChosenAppKey; -import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.viz.core.alerts.AlertMessage; import com.raytheon.uf.viz.core.localization.LocalizationManager; import com.raytheon.uf.viz.core.notification.NotificationMessage; @@ -67,6 +70,8 @@ import com.raytheon.viz.alerts.observers.ProductAlertObserver; * Dec 22, 2009 3424 zhao revised processProductAtStartup method to retrieve all data * July 20,2010 4891 skorolev Added resource listener * May 15, 2012 14510 zhao Modified processing at startup + * Oct 26, 2012 1280 skorolev Clean code and made changes for non-blocking ZoneTableDlg + * Nov. 1, 2012 1297 skorolev Changed HashMap to Map and clean code * * * @@ -77,19 +82,19 @@ import com.raytheon.viz.alerts.observers.ProductAlertObserver; public class SnowMonitor extends ObsMonitor { + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(SnowMonitor.class); + /** Singleton instance of this class */ private static SnowMonitor monitor = null; - /** - * the zone table dialog - */ - public SnowZoneTableDlg zoneDialog = null; + /** Zone table dialog **/ + private SnowZoneTableDlg zoneDialog; - /** - * the monitoring area configure dialog - */ - public SnowMonitoringAreaConfigDlg areaDialog = null; + /** Monitoring area configure dialog **/ + private SnowMonitoringAreaConfigDlg areaDialog = null; + /** SNOW configuration manager **/ private SnowMonitorConfigurationManager snowConfig = null; /** @@ -98,113 +103,138 @@ public class SnowMonitor extends ObsMonitor { */ private final ObMultiHrsReports obData; - /** The application key */ - ChosenAppKey chosenAppKey = ChosenAppKey.SNOW; - - /** All SNOW plugins start with this */ - private static String OBS = "fssobs"; + /** All SNOW datauri start with this */ + private final String OBS = "fssobs"; /** regex wild card filter */ - protected static String wildCard = "[\\w\\(\\)-_:.]+"; + private final String wildCard = "[\\w\\(\\)-_:.]+"; - /** date of the data sent **/ - // private Date dataDate = null; - /** - * Time which Zone/County dialog shows. - */ - public Date dialogTime = null; + /** Time which Zone/County dialog shows. **/ + private Date dialogTime = null; /** Array of snow listeners **/ - private final ArrayList snowResources = new ArrayList(); + private final List snowResources = new ArrayList(); + /** Pattern for SNOW **/ + private final Pattern snowPattern = Pattern.compile(URIFilter.uriSeperator + + OBS + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator + + wildCard + URIFilter.uriSeperator + cwa + URIFilter.uriSeperator + + wildCard + URIFilter.uriSeperator + wildCard + + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator + + "snow"); /** * Private constructor, singleton - */ - /** - * */ private SnowMonitor() { - - pluginPatterns.add(snowPattern); + pluginPatterns.add(snowPattern); readTableConfig(MonitorThresholdConfiguration.SNOW_THRESHOLD_CONFIG); - initObserver("fssobs", this); + initObserver(OBS, this); obData = new ObMultiHrsReports(CommonConfig.AppName.SNOW); obData.setThresholdMgr(SnowThresholdMgr.getInstance()); // Pre-populate dialog with an observation (METAR) for KOMA - } + } + /** + * Gets instance of monitor + * + * @return monitor + */ public static synchronized SnowMonitor getInstance() { if (monitor == null) { monitor = new SnowMonitor(); - monitor.processProductAtStartup("snow"); - monitor.fireMonitorEvent(monitor); + monitor.processProductAtStartup("snow"); + monitor.fireMonitorEvent(monitor); } return monitor; } + // TODO: Provide the changes in EDEX URIFilters when area configuration file + // has been changed. /** - * DR#11279: - * When monitor area configuration is changed, - * this module is called to re-initialize monitor - * using new monitor area configuration + * DR#11279: When monitor area configuration is changed, this module is + * called to re-initialize monitor using new monitor area configuration */ public static void reInitialize() { - if ( monitor != null ) { - monitor = null; - monitor = new SnowMonitor(); - } + if (monitor != null) { + monitor = null; + monitor = new SnowMonitor(); + } } - + /** + * Launches SNOW zone table dialog * + * @param type * @param shell */ public void launchDialog(String type, Shell shell) { if (type.equals("zone")) { - if (zoneDialog == null) { + if (zoneDialog == null || zoneDialog.getShell() == null + || zoneDialog.isDisposed()) { zoneDialog = new SnowZoneTableDlg(shell, obData); addMonitorListener(zoneDialog); zoneDialog.addMonitorControlListener(this); + fireMonitorEvent(zoneDialog.getClass().getName()); + zoneDialog.open(); + } else { + zoneDialog.bringToTop(); } - zoneDialog.open(); - fireMonitorEvent(zoneDialog.getClass().getName()); } else if (type.equals("area")) { - areaDialog = new SnowMonitoringAreaConfigDlg(shell, - "SNOW Monitor Area Configuration"); - areaDialog.open(); + if (areaDialog == null) { + areaDialog = new SnowMonitoringAreaConfigDlg(shell, + "SNOW Monitor Area Configuration"); + areaDialog.open(); + } } } + /** + * Gets data + * + * @return obData + */ public ObMultiHrsReports getObData() { return obData; } - private Pattern snowPattern = Pattern.compile(URIFilter.uriSeperator + OBS - + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator - + wildCard + URIFilter.uriSeperator + cwa + URIFilter.uriSeperator - + wildCard + URIFilter.uriSeperator + wildCard - + URIFilter.uriSeperator + wildCard + URIFilter.uriSeperator - + "snow"); - + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#filterNotifyMessage(com.raytheon + * .uf.viz.core.notification.NotificationMessage) + */ @Override public boolean filterNotifyMessage(NotificationMessage alertMessage) { return false; } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processNotifyMessage(com.raytheon + * .uf.viz.core.notification.NotificationMessage) + */ @Override public void processNotifyMessage(NotificationMessage filtered) { - + // Not used } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processProductMessage(com.raytheon + * .uf.viz.core.alerts.AlertMessage) + */ @Override public void processProductMessage(final AlertMessage filtered) { - if (snowPattern.matcher(filtered.dataURI).matches()) { - // System.out.println("Found match: " + snowPattern + " URI: " - // + filtered.dataURI); - processURI(filtered.dataURI, filtered); - } + if (snowPattern.matcher(filtered.dataURI).matches()) { + processURI(filtered.dataURI, filtered); + } } /** @@ -214,7 +244,6 @@ public class SnowMonitor extends ObsMonitor { * */ public class SortByDate implements Comparator { - @Override public int compare(Date o1, Date o2) { return o1.compareTo(o2); @@ -229,7 +258,7 @@ public class SnowMonitor extends ObsMonitor { * -- the xml configuration filename */ public void readTableConfig(String file) { - HashMap> zones = new HashMap>(); + Map> zones = new HashMap>(); // create zones and station list try { SnowMonitorConfigurationManager areaConfig = getMonitorAreaConfig(); @@ -238,72 +267,103 @@ public class SnowMonitor extends ObsMonitor { zones.put(zone, stations); } } catch (Exception e) { - System.out.println("Snow failed to load configuration..." - + this.getClass().getName()); + statusHandler.handle(Priority.PROBLEM, + "Snow failed to load configuration..." + + this.getClass().getName()); } MonitoringArea.setPlatformMap(zones); } + /** + * Gets configuration manager + * + * @return snowConfig + */ public SnowMonitorConfigurationManager getMonitorAreaConfig() { if (snowConfig == null) { LocalizationManager mgr = LocalizationManager.getInstance(); String siteScope = mgr.getCurrentSite(); - snowConfig = SnowMonitorConfigurationManager.getInstance(); snowConfig.readConfigXml(siteScope); } return snowConfig; } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.Monitor#initObserver(java.lang.String, + * com.raytheon.uf.viz.monitor.Monitor) + */ @Override public void initObserver(String pluginName, Monitor monitor) { ProductAlertObserver.addObserver(pluginName, this); - } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#thresholdUpdate(com.raytheon.uf + * .viz.monitor.events.IMonitorThresholdEvent) + */ @Override public void thresholdUpdate(IMonitorThresholdEvent me) { fireMonitorEvent(zoneDialog.getClass().getName()); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#configUpdate(com.raytheon.uf.viz + * .monitor.events.IMonitorConfigurationEvent) + */ @Override public void configUpdate(IMonitorConfigurationEvent me) { fireMonitorEvent(zoneDialog.getClass().getName()); } /** - * Kill this monitor by nullifying the monitor's private instance variable. + * Kills this monitor by nullifying the monitor's private instance variable. + */ + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ObsMonitor#nullifyMonitor() */ @Override public void nullifyMonitor() { - // /** - // * Before making the monitor null, remove observers - // */ - // for (String p : pluginName) { - // if (!pluginName.equals("")) { - // stopObserver(p, this); - // } - // } monitor.removeMonitorListener(zoneDialog); - stopObserver("fssobs", this); + stopObserver(OBS, this); monitor = null; } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#process(com.raytheon.uf.viz.monitor + * .data.ObReport) + */ @Override - protected void process(ObReport result) - throws Exception { - - //final ProcessSnowReport snow = new ProcessSnowReport(result); - //snow.processSnowReport(); - // add data to obData + protected void process(ObReport result) throws Exception { obData.addReport(result); fireMonitorEvent(this); } + /** + * @return dialogTime + */ public Date getDialogTime() { return dialogTime; } + /** + * Sets dialog time + * + * @param dialogTime + */ public void setDialogTime(Date dialogTime) { this.dialogTime = dialogTime; } @@ -336,12 +396,15 @@ public class SnowMonitor extends ObsMonitor { fireMonitorEvent(this); } + /** + * Close SNOW zone table dialog + */ public void closeDialog() { if (zoneDialog != null) { monitor.nullifyMonitor(); zoneDialog.removeMonitorContorlListener(this); - zoneDialog.shellDisposeDialog(); + zoneDialog.close(); zoneDialog = null; } if (areaDialog != null) { @@ -350,43 +413,47 @@ public class SnowMonitor extends ObsMonitor { } } - /** - * Order the dates + /* + * (non-Javadoc) * - * @param type - * @return + * @see + * com.raytheon.uf.viz.monitor.IMonitor#getTimeOrderedKeys(com.raytheon. + * uf.viz.monitor.IMonitor, java.lang.String) */ + @Override public ArrayList getTimeOrderedKeys(IMonitor monitor, String type) { + // not used return null; } /** - * Get most recent time - * - * @param type - * @return - */ - public DataTime getMostRecent(IMonitor monitor, String type) { - return null; - } - - /** - * @return the zoneDialog + * @return zoneDialog */ public SnowZoneTableDlg getZoneDialog() { return zoneDialog; } /** + * Sets the zoneDialog + * * @param zoneDialog - * the zoneDialog to set */ public void setZoneDialog(SnowZoneTableDlg zoneDialog) { this.zoneDialog = zoneDialog; } - @Override - protected void processAtStartup(ObReport report) { - obData.addReport(report); - } + /** + * First start + */ + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ObsMonitor#processAtStartup(com.raytheon. + * uf.viz.monitor.data.ObReport) + */ + @Override + protected void processAtStartup(ObReport report) { + obData.addReport(report); + } } diff --git a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/actions/SnowAction.java b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/actions/SnowAction.java index 50221d0fa5..48646ee531 100644 --- a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/actions/SnowAction.java +++ b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/actions/SnowAction.java @@ -19,11 +19,9 @@ **/ package com.raytheon.uf.viz.monitor.snow.ui.actions; - import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; @@ -42,22 +40,32 @@ import com.raytheon.uf.viz.monitor.snow.SnowMonitor; * Nov 30, 2009 3424 zhao/wkwock/slav zhao/wkwock/slav Automatically updates snow display. Display station data. * Dec 18, 2009 3424 zhao Launch snow monitor and snow zone/station table dialog separately here * Feb 26, 2010 4282 zhao changed to follow the same launch mechanism in FOG + * Nov.15, 2012 1297 skorolev Cleaned code + * * * * @author grichard * @version 1.0 */ -public class SnowAction extends AbstractHandler { +public class SnowAction extends AbstractHandler { + /* + * (non-Javadoc) + * + * @see + * org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands + * .ExecutionEvent) + */ @Override public Object execute(ExecutionEvent arg0) throws ExecutionException { System.out.println("Activating/Action for SNOW..."); - + SnowMonitor snow = SnowMonitor.getInstance(); - if ( snow.zoneDialog == null || snow.zoneDialog.isDisposed()) { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(); - snow.launchDialog("zone", shell); + if (snow.getZoneDialog() == null || snow.getZoneDialog().isDisposed()) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + snow.launchDialog("zone", shell); } return null; } diff --git a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowMonitoringAreaConfigDlg.java b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowMonitoringAreaConfigDlg.java index 314040e847..c7d17305d7 100644 --- a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowMonitoringAreaConfigDlg.java +++ b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowMonitoringAreaConfigDlg.java @@ -68,9 +68,8 @@ public class SnowMonitoringAreaConfigDlg extends MonitoringAreaConfigDlg { configManager.saveConfigData(); /** - * DR#11279: - * re-initialize threshold manager and the monitor - * using new monitor area configuration + * DR#11279: re-initialize threshold manager and the monitor using + * new monitor area configuration */ SnowThresholdMgr.reInitialize(); SnowMonitor.reInitialize(); @@ -81,7 +80,8 @@ public class SnowMonitoringAreaConfigDlg extends MonitoringAreaConfigDlg { + "\n\nIf SNOW is running anywhere within " + "the office, please clear it.\n"); - if ( configManager.getAddedZones().size() > 0 || addedZones.size() > 0 ) { + if (configManager.getAddedZones().size() > 0 + || addedZones.size() > 0) { String message2 = "New zones have been added, and their monitoring thresholds " + "have been set to default values; would you like to modify " + "their threshold values now?"; diff --git a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowZoneTableDlg.java b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowZoneTableDlg.java index 1a2a13f76d..29f1206706 100644 --- a/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowZoneTableDlg.java +++ b/cave/com.raytheon.uf.viz.monitor.snow/src/com/raytheon/uf/viz/monitor/snow/ui/dialogs/SnowZoneTableDlg.java @@ -21,6 +21,7 @@ package com.raytheon.uf.viz.monitor.snow.ui.dialogs; import java.util.ArrayList; import java.util.Date; +import java.util.List; import org.eclipse.swt.widgets.Shell; @@ -28,6 +29,7 @@ import com.raytheon.uf.common.monitor.config.MonitorConfigurationManager; import com.raytheon.uf.common.monitor.config.SnowMonitorConfigurationManager; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.ObConst.DataUsageKey; +import com.raytheon.uf.common.monitor.data.ObConst.DisplayVarName; import com.raytheon.uf.viz.monitor.IMonitor; import com.raytheon.uf.viz.monitor.data.ObMultiHrsReports; import com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent; @@ -49,6 +51,7 @@ import com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg; * Dec 2, 2009 3424 zhao/wkwock/slav Fix display SNOW 2nd time problem. * Dec 18, 2009 3424 zhao use ObMultiHrsReports for obs data archive * July 20,2010 4891 skorolev added code to fireDialogShutdown + * Nov. 8, 2012 1297 skorolev Added initiateProdArray method * * * @@ -57,14 +60,12 @@ import com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg; */ public class SnowZoneTableDlg extends ZoneTableDlg { - // private ZoneTableComp zoneTableComp; private SnowMonDispThreshDlg snowThreshDlg; /** - * Constructor (Dec 16, 2009, zhao) - * * @param parent + * @param obData */ public SnowZoneTableDlg(Shell parent, ObMultiHrsReports obData) { super(parent, obData, CommonConfig.AppName.SNOW); @@ -79,6 +80,39 @@ public class SnowZoneTableDlg extends ZoneTableDlg { super(parent, CommonConfig.AppName.SNOW); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#initiateProdArray() + */ + @Override + public void initiateProdArray() { + varName = config.getSnowZoneStnTableColVarNames()[colIndex]; + // Fill product array + prodArray = new ArrayList(); + String[] varprefs = { "VAR_", "BLIZ_", "FRZ_", "HSW_" }; + for (DisplayVarName var : DisplayVarName.values()) { + String dispVarName = var.name(); + if (colIndex == 1 && dispVarName.startsWith(varprefs[1])) { + prodArray.add(dispVarName); + } else if (colIndex == 2 && dispVarName.startsWith(varprefs[2])) { + prodArray.add(dispVarName); + } else if (colIndex == 3 && dispVarName.startsWith(varprefs[3])) { + prodArray.add(dispVarName); + } else if (dispVarName.startsWith(varprefs[0]) + && dispVarName.equals(varprefs[0] + varName.name())) { + prodArray.add(dispVarName); + } + } + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#configThreshAction() + */ @Override protected void configThreshAction() { if (snowThreshDlg == null) { @@ -89,6 +123,13 @@ public class SnowZoneTableDlg extends ZoneTableDlg { } } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.listeners.IMonitorListener#notify(com.raytheon + * .uf.viz.monitor.events.IMonitorEvent) + */ @Override public void notify(IMonitorEvent me) { if (zoneTable.isDisposed()) { @@ -97,7 +138,7 @@ public class SnowZoneTableDlg extends ZoneTableDlg { if (me.getSource() instanceof SnowMonitor) { SnowMonitor monitor = (SnowMonitor) me.getSource(); - Date date = monitor.getDialogTime(); + Date date = monitor.getDialogTime(); if (date != null) { if (!isLinkedToFrame()) { date = monitor.getObData().getLatestNominalTime(); @@ -107,64 +148,108 @@ public class SnowZoneTableDlg extends ZoneTableDlg { } } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * addMonitorControlListener(com.raytheon.uf.viz.monitor.IMonitor) + */ @Override public void addMonitorControlListener(IMonitor monitor) { getMonitorControlListeners().add(monitor); } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireConfigUpdate + * (com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent) + */ @Override public void fireConfigUpdate(IMonitorConfigurationEvent imce) { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireDialogShutdown + * (com.raytheon.uf.viz.monitor.listeners.IMonitorListener) + */ @Override public void fireDialogShutdown(IMonitorListener iml) { - // Display.getDefault().asyncExec(new Runnable() { - // public void run() { - // Iterator iter = getMonitorControlListeners() - // .iterator(); - // while (iter.hasNext()) { - // ((SnowMonitor) iter.next()).closeDialog(); - // } - // } - // }); - + // Not used } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener#fireKillMonitor + * () + */ @Override public void fireKillMonitor() { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * fireThresholdUpdate + * (com.raytheon.uf.viz.monitor.events.IMonitorThresholdEvent) + */ @Override public void fireThresholdUpdate(IMonitorThresholdEvent imte) { - // TODO Auto-generated method stub - + // Not used } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg# + * getMonitorControlListeners() + */ @Override - public ArrayList getMonitorControlListeners() { + public List getMonitorControlListeners() { return controlListeners; } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * removeMonitorContorlListener(com.raytheon.uf.viz.monitor.IMonitor) + */ @Override public void removeMonitorContorlListener(IMonitor monitor) { getMonitorControlListeners().remove(monitor); - } - @Override - protected MonitorConfigurationManager getConfigMgr() { - return SnowMonitorConfigurationManager.getInstance(); - } - - @Override - protected void handleLinkToFrame() { + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#getConfigMgr() + */ + @Override + protected MonitorConfigurationManager getConfigMgr() { + return SnowMonitorConfigurationManager.getInstance(); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg#handleLinkToFrame() + */ + @Override + protected void handleLinkToFrame() { linkedToFrame = linkToFrameChk.getSelection(); SnowMonitor.getInstance().fireMonitorEvent(this.getClass().getName()); - } + } /* * (non-Javadoc) @@ -174,20 +259,30 @@ public class SnowZoneTableDlg extends ZoneTableDlg { */ @Override protected void shellDisposeAction() { - // shell.addDisposeListener(new DisposeListener() { - // @Override - // public void widgetDisposed(DisposeEvent e) { - // System.out.println("Fog monitor dialog DISPOSED"); - // unregisterDialogFromMonitor(); - // } - // }); + // Not used } - /** + /* + * (non-Javadoc) * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.ZoneTableDlg# + * setZoneSortColumnAndDirection() */ - protected void unregisterDialogFromMonitor() { - fireDialogShutdown(this); + @Override + protected void setZoneSortColumnAndDirection() { + if (zoneTblData != null) { + zoneSortColumn = zoneTblData.getSortColumn(); + zoneSortDirection = zoneTblData.getSortDirection(); + } + return; + } + + @Override + protected void setStnSortColumnAndDirection() { + if (stnTblData != null) { + stnSortColumn = stnTblData.getSortColumn(); + stnSortDirection = stnTblData.getSortDirection(); + } } } diff --git a/cave/com.raytheon.uf.viz.monitor/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.monitor/META-INF/MANIFEST.MF index a5730f26c9..e28356a7ee 100644 --- a/cave/com.raytheon.uf.viz.monitor/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.monitor/META-INF/MANIFEST.MF @@ -17,7 +17,8 @@ Require-Bundle: org.eclipse.ui, com.raytheon.uf.edex.plugin.mesowest;bundle-version="1.0.0", com.raytheon.uf.edex.decodertools;bundle-version="1.0.0", org.apache.commons.logging;bundle-version="1.0.4", - com.raytheon.uf.common.monitor;bundle-version="1.11.17" + com.raytheon.uf.common.monitor;bundle-version="1.11.17", + org.apache.commons.lang;bundle-version="2.3.0" Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.viz.monitor, com.raytheon.uf.viz.monitor.data, diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/AreaContainer.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/AreaContainer.java index f34434621b..25fa654b5c 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/AreaContainer.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/AreaContainer.java @@ -19,74 +19,92 @@ **/ package com.raytheon.uf.viz.monitor.data; -import java.util.ArrayList; import java.util.Date; +import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** -* Keep Areas with Containers of ObReports by Time in Hash -* Template For Silver Springs -* -*
-* 
-* SOFTWARE HISTORY
-* 
-* Date         Ticket#     Engineer    Description
-* ------------ ----------  ----------- --------------------------
-* 12/07/09                  dhladky    Initial Creation.
-* 
-* 
-* -* @author dhladky -* -*/ - + * Keep Areas with Containers of ObReports by Time in Hash Template For Silver + * Springs + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * 12/07/09                  dhladky    Initial Creation.
+ * Nov. 1, 2012 #1297       skorolev    Changed ArrayList to List
+ * 
+ * 
+ * + * @author dhladky + * + */ public class AreaContainer { - - public ArrayList stations = null; - public String areaId = null; // zone - public ConcurrentHashMap container = null; - - public AreaContainer(ArrayList stations, String areaId) { - this.stations = stations; + + /** List of stations **/ + private List stations = null; + + /** Zone ID **/ + private String areaId = null; + + /** Map zone - stations **/ + private ConcurrentHashMap container = null; + + /** + * Keeps station list for every zone. + * + * @param stations + * @param areaId + */ + public AreaContainer(List stations, String areaId) { + this.setStations(stations); this.areaId = areaId; this.container = new ConcurrentHashMap(); // creates the stations list for this area - for (String stationId: stations) { + for (String stationId : stations) { StationContainer sc = new StationContainer(stationId); container.put(stationId, sc); } } - + + /** + * Gets ObReports for station + * + * @param stationId + * @return StationContainer + */ public StationContainer getStation(String stationId) { StationContainer sc = null; - if (container.containsKey(stationId)) { sc = container.get(stationId); } - return sc; } - + /** * Gets the container + * * @return */ public ConcurrentHashMap getContainer() { return container; } - + /** * Gets the Area ID + * * @return */ public String getAreaId() { return areaId; } - + /** - * If it's ever needed + * Removes zone and it's stations. If it's ever needed + * * @param stationId */ public void removeStation(String stationId) { @@ -94,8 +112,7 @@ public class AreaContainer { container.remove(stationId); } } - - + /** * Get the best obReport (time) * @@ -104,23 +121,20 @@ public class AreaContainer { */ public ObReport getBestAreaReport(Date key) { ObReport report = new ObReport(); - for (String station : container.keySet()) { if (key != null) { report = container.get(station).getMostRecent(key); } } - if (report == null) { report = new ObReport(); } - return report; - } - + /** * Adds a report for this area. + * * @param date * @param report */ @@ -129,4 +143,22 @@ public class AreaContainer { container.get(report.getPlatformId()).addReport(date, report); } } + + /** + * Sets station list + * + * @param stations + */ + public void setStations(List stations) { + this.stations = stations; + } + + /** + * Gets station list + * + * @return stations + */ + public List getStations() { + return stations; + } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/MonitoringArea.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/MonitoringArea.java index be0292f8f1..c72e4317ca 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/MonitoringArea.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/MonitoringArea.java @@ -42,6 +42,7 @@ import com.raytheon.uf.common.monitor.data.ObConst; * Feb 17, 2009 1999 grichard Initial creation. * 3/16/2009 2047 grichard Add zone related routines. * Dec 9, 2009 3424 zhao Added method getZoneId(platformId) + * Nov. 1, 2012 1297 skorolev Changed ArrayList to List. * * * @@ -51,42 +52,73 @@ import com.raytheon.uf.common.monitor.data.ObConst; public final class MonitoringArea { - // Private constructor -- all contents must be public static + /** + * Private constructor -- all contents must be public static + */ private MonitoringArea() { } - // The map that contains the zoneIds for all platform identifiers - private static Map> zoneMap = new HashMap>(); + /** + * The map that contains the zoneIds for all platform identifiers + */ + private static Map> zoneMap = new HashMap>(); - // The map that contains the platformIds for all zone identifiers - private static Map> platformMap = new HashMap>(); + /** + * The map that contains the platformIds for all zone identifiers + */ + private static Map> platformMap = new HashMap>(); - // Get the monitoring area time window + /** + * Get the monitoring area time window + * + * @return + */ public static int getTimeWindow() { return ObConst.THREAT_INTERVAL_HOURS; } - // Getter for zone map - public static Map> getZoneMap() { + /** + * Getter for zone map + * + * @return + */ + public static Map> getZoneMap() { return zoneMap; } - // Setter for zone map - public static void setZoneMap(Map> zoneMap) { + /** + * Setter for zone map + * + * @param zoneMap + */ + public static void setZoneMap(Map> zoneMap) { MonitoringArea.zoneMap = zoneMap; } - // Getter for platform map - public static Map> getPlatformMap() { + /** + * Getter for platform map + * + * @return + */ + public static Map> getPlatformMap() { return platformMap; } - // Setter for platform map - public static void setPlatformMap(Map> platformMap) { + /** + * Setter for platform map + * + * @param platformMap + */ + public static void setPlatformMap(Map> platformMap) { MonitoringArea.platformMap = platformMap; } - // Getter for the List of all zones which associate with the given platform + /** + * Getter for the List of all zones which associate with the given platform + * + * @param platformId + * @return + */ public static List listZonesToPlatform(String platformId) { return getZoneMap().get(platformId); } @@ -112,17 +144,19 @@ public final class MonitoringArea { return theZones; } + /** + * @return list of stations + */ public static String getPlatformIdList() { StringBuilder stList = new StringBuilder(); Set stns = new HashSet(); for (String zone : platformMap.keySet()) { - ArrayList platfrms = platformMap.get(zone); + List platfrms = platformMap.get(zone); stns.addAll(platfrms); } stList.append(stns.toString()); stList.deleteCharAt(0); stList.deleteCharAt(stList.length() - 1); - // System.out.println("============ stList = " + stList.toString()); return stList.toString(); } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObHourReports.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObHourReports.java index 356a359928..b2658e57f6 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObHourReports.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObHourReports.java @@ -22,17 +22,20 @@ package com.raytheon.uf.viz.monitor.data; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; import com.raytheon.uf.common.monitor.data.CommonConfig; import com.raytheon.uf.common.monitor.data.CommonConfig.AppName; import com.raytheon.uf.common.monitor.data.CommonTableConfig.CellType; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.viz.monitor.thresholds.AbstractThresholdMgr; /** - * This class is a container of ObZoneHourReports objects for a - * caller-specified nominal date-time. - * (this class corresponds to the RcHourReports c++ class in AWIPS-1) + * This class is a container of ObZoneHourReports objects for a caller-specified + * nominal date-time. (this class corresponds to the RcHourReports c++ class in + * AWIPS-1) * *
  * 
@@ -40,6 +43,8 @@ import com.raytheon.uf.viz.monitor.thresholds.AbstractThresholdMgr;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Dec. 1, 2009  3424       zhao       Initial creation.
+ * Oct.29, 2012  1297       skorolev   Changed HashMap to Map
+ * Oct.31  2012  1297       skorolev   Clean code
  * 
  * 
* @@ -48,117 +53,160 @@ import com.raytheon.uf.viz.monitor.thresholds.AbstractThresholdMgr; */ public class ObHourReports { - - /** - * the nominal time of this ObHourReports object - */ - private Date nominalTime; + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(ObHourReports.class); - /** - * application name (snow, fog, safeseas, etc) - */ - private CommonConfig.AppName appName; - - /** - * key is zone id, value is ObZoneHourReports object - */ - private HashMap hourReports; - - /** - * constructor - * - * @param appName - */ - public ObHourReports(Date nominalTime, CommonConfig.AppName appName, AbstractThresholdMgr thresholdMgr) { - this.nominalTime = nominalTime; - this.appName = appName; - hourReports = new HashMap(); - Map> zoneStationMap = MonitoringArea.getPlatformMap(); - for ( String zone : zoneStationMap.keySet() ) { - hourReports.put(zone, new ObZoneHourReports(nominalTime, zone, appName, thresholdMgr)); - } - } + /** + * the nominal time of this ObHourReports object + */ + private Date nominalTime; - public void addReport(ObReport report) { - String station = report.getPlatformId(); - ArrayList zones = MonitoringArea.getZoneIds(station); - if ( zones.size() == 0 ) { - System.err.println("Error: station: " + station + " is not associated with any zone in the monitoring area"); - return; - } - boolean hasZone = false; - for ( String zone : zones ) { - if ( hourReports.containsKey(zone) ) { - hasZone = true;; - hourReports.get(zone).addReport(report); - } - } - if ( hasZone == false ) { - System.err.println("Error in addreport() of ObHourReports: unable to add obs report to data archive"); - } - } - - public HashMap getHourReports() { - return hourReports; - } - - public TableData getZoneTableData() { - TableData tblData = new TableData(appName); - for ( String zone : hourReports.keySet() ) { - tblData.addTableRowData(this.getObZoneHourReports(zone).getZoneTableRowData()); - //tblData.addTableRowData(hourReports.get(zone).getZoneTableRowData()); - } - return tblData; - } - - public TableData getFogZoneTableData(HashMap algCellType) { - TableData tblData = new TableData(AppName.FOG); - for ( String zone : hourReports.keySet() ) { - CellType theAlgCellType; - if ( algCellType.containsKey(zone) ) { - theAlgCellType = algCellType.get(zone); - } else { - theAlgCellType = CellType.NotAvailable; - } - tblData.addTableRowData(this.getObZoneHourReports(zone).getFogZoneTableRowData(theAlgCellType)); - } - return tblData; - } - - public TableData getSSZoneTableData(HashMap fogCellType) { - TableData tblData = new TableData(AppName.SAFESEAS); - for (String zone : hourReports.keySet()) { - CellType theFogCellType; - if (fogCellType.containsKey(zone)) { - theFogCellType = fogCellType.get(zone); - } else { - theFogCellType = CellType.NotAvailable; - } - tblData.addTableRowData(this.getObZoneHourReports(zone) - .getSSZoneTableRowData(theFogCellType)); - } - return tblData; - } + /** + * application name (snow, fog, safeseas, etc) + */ + private CommonConfig.AppName appName; - /** - * Returns the ObZoneHourReports object of a caller-specified zone. - * If such object not available, returns null. - * @param zone - * @return - */ - public ObZoneHourReports getObZoneHourReports(String zone) { - if ( !hourReports.containsKey(zone) ) { - return null; - } - return hourReports.get(zone); - } - - public Date getNominalTime() { - return nominalTime; - } - - public CommonConfig.AppName getAppName() { - return appName; - } + /** + * key is zone id, value is ObZoneHourReports object + */ + private Map hourReports; + + /** + * constructor + * + * @param appName + */ + public ObHourReports(Date nominalTime, CommonConfig.AppName appName, + AbstractThresholdMgr thresholdMgr) { + this.nominalTime = nominalTime; + this.appName = appName; + hourReports = new HashMap(); + Map> zoneStationMap = MonitoringArea + .getPlatformMap(); + for (String zone : zoneStationMap.keySet()) { + hourReports.put(zone, new ObZoneHourReports(nominalTime, zone, + appName, thresholdMgr)); + } + } + + /** + * Adds data to hourReports + * + * @param report + */ + public void addReport(ObReport report) { + String station = report.getPlatformId(); + ArrayList zones = MonitoringArea.getZoneIds(station); + if (zones.size() == 0) { + statusHandler + .error("Error: station: " + + station + + " is not associated with any zone in the monitoring area"); + return; + } + boolean hasZone = false; + for (String zone : zones) { + if (hourReports.containsKey(zone)) { + hasZone = true; + ; + hourReports.get(zone).addReport(report); + } + } + if (hasZone == false) { + statusHandler + .error("Error in addreport() of ObHourReports: unable to add obs report to data archive"); + } + } + + /** + * @return hourReports + */ + public Map getHourReports() { + return hourReports; + } + + /** + * Get data for Zone table. + * + * @return tblData + */ + public TableData getZoneTableData() { + TableData tblData = new TableData(appName); + for (String zone : hourReports.keySet()) { + tblData.addTableRowData(this.getObZoneHourReports(zone) + .getZoneTableRowData()); + } + return tblData; + } + + /** + * Get data for Fog Table. + * + * @param algCellType + * @return tblData + */ + public TableData getFogZoneTableData(Map algCellType) { + TableData tblData = new TableData(AppName.FOG); + for (String zone : hourReports.keySet()) { + CellType theAlgCellType; + if (algCellType.containsKey(zone)) { + theAlgCellType = algCellType.get(zone); + } else { + theAlgCellType = CellType.NotAvailable; + } + tblData.addTableRowData(this.getObZoneHourReports(zone) + .getFogZoneTableRowData(theAlgCellType)); + } + return tblData; + } + + /** + * Gets data for SAFESEAS table. + * + * @param fogCellType + * @return tblData + */ + public TableData getSSZoneTableData(Map fogCellType) { + TableData tblData = new TableData(AppName.SAFESEAS); + for (String zone : hourReports.keySet()) { + CellType theFogCellType; + if (fogCellType.containsKey(zone)) { + theFogCellType = fogCellType.get(zone); + } else { + theFogCellType = CellType.NotAvailable; + } + tblData.addTableRowData(this.getObZoneHourReports(zone) + .getSSZoneTableRowData(theFogCellType)); + } + return tblData; + } + + /** + * Returns the ObZoneHourReports object of a caller-specified zone. If such + * object not available, returns null. + * + * @param zone + * @return hour reports + */ + public ObZoneHourReports getObZoneHourReports(String zone) { + if (!hourReports.containsKey(zone)) { + return null; + } + return hourReports.get(zone); + } + + /** + * @return nominalTime + */ + public Date getNominalTime() { + return nominalTime; + } + + /** + * @return appName + */ + public CommonConfig.AppName getAppName() { + return appName; + } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObMultiHrsReports.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObMultiHrsReports.java index 19f5030191..ab888bb68e 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObMultiHrsReports.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObMultiHrsReports.java @@ -24,6 +24,7 @@ import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Iterator; +import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; @@ -49,6 +50,7 @@ import com.raytheon.uf.viz.monitor.thresholds.AbstractThresholdMgr; * Dec. 1, 2009 3424 zhao Initial creation. * Dec 24, 2009 3424 zhao added getTrendDataSet() that returns ObTrendDataSet object * Jan 25, 2010 4281, 3888, 3877 wkwock/zhao added getHistTableData method + * Oct.31, 2012 1297 skorolev Clean code. * * * @@ -66,7 +68,7 @@ public class ObMultiHrsReports { /** * Fog ALG CellType [key is zone, value is cell type] */ - private HashMap fogAlgCellType; + private Map fogAlgCellType; /** * application name (snow, fog, safeseas, etc) @@ -86,6 +88,11 @@ public class ObMultiHrsReports { private int maxFrames = MAX_FRAMES; + /** + * Constructor + * + * @param appName + */ public ObMultiHrsReports(CommonConfig.AppName appName) { this.appName = appName; multiHrsReports = new TreeMap(); @@ -114,9 +121,10 @@ public class ObMultiHrsReports { } /** - * Add an ObReport object to the ObMultiHrsReports object + * Adds an ObReport object to the ObMultiHrsReports object * * @param report + * @return returns multiHrsReports */ public void addReport(ObReport report) { // Date nominalTime = TableUtil @@ -129,14 +137,14 @@ public class ObMultiHrsReports { report.setWindDir(ObConst.MISSING); } /** - * DR#11462: - * set DewpointDepr now, avoid using - * DewpointDepr = worstTemp - worstDewpoint - * for Zone/County Table, which - * causes mismatch between Zone/County table and Station table + * DR#11462: set DewpointDepr now, avoid using DewpointDepr = worstTemp + * - worstDewpoint for Zone/County Table, which causes mismatch between + * Zone/County table and Station table */ - if ( report.getTemperature() != ObConst.MISSING && report.getDewpoint() != ObConst.MISSING ) { - report.setDewpointDepr(report.getTemperature() - report.getDewpoint() ); + if (report.getTemperature() != ObConst.MISSING + && report.getDewpoint() != ObConst.MISSING) { + report.setDewpointDepr(report.getTemperature() + - report.getDewpoint()); } if (multiHrsReports.containsKey(nominalTime)) { multiHrsReports.get(nominalTime).addReport(report); @@ -183,10 +191,10 @@ public class ObMultiHrsReports { return this.getObHourReports(nominalTime).getFogZoneTableData( fogAlgCellType); } - if (appName == AppName.SAFESEAS) { - return this.getObHourReports(nominalTime).getSSZoneTableData( - fogAlgCellType); - } + if (appName == AppName.SAFESEAS) { + return this.getObHourReports(nominalTime).getSSZoneTableData( + fogAlgCellType); + } return this.getObHourReports(nominalTime).getZoneTableData(); // return multiHrsReports.get(nominalTime).getZoneTableData(); @@ -232,6 +240,12 @@ public class ObMultiHrsReports { .getStationTableData(); } + /** + * Gets data for station table + * + * @param zone + * @return station table data + */ public TableData getEmptyStationTableData(String zone) { Date nominalTime = TableUtil.getNominalTime(SimulatedTime .getSystemTime().getTime()); @@ -241,6 +255,7 @@ public class ObMultiHrsReports { } /** + * Gets data for trend plots * * @param zone * @param Station @@ -294,10 +309,6 @@ public class ObMultiHrsReports { } } - // System.out.println("startNominalTime = " + startNominalTime - // + "; latestNominalTime = " + latestNominalTime - // + "; number of nominal times = " + multiHrsReports.size()); - // get data ObTrendDataSet trendData = new ObTrendDataSet(zone, varName, productName, appName, thresholdMgr); @@ -312,9 +323,6 @@ public class ObMultiHrsReports { .getObStnHourReports(station).getObsTimes(); if (obsTimes != null) { for (Date obsTime : obsTimes) { - - // System.out.println("obs time = " + obsTime); - trendData.addDataPoint(obsTime, new Float(this.getObHourReports(nominalTime) .getObZoneHourReports(zone) @@ -423,9 +431,9 @@ public class ObMultiHrsReports { } /** - * Returns a SortedMap object of + * Returns a SortedMap object * - * @return + * @return multiHrsReports */ public SortedMap getMultiHrsReports() { return multiHrsReports; @@ -512,6 +520,7 @@ public class ObMultiHrsReports { } /** + * Gets application name * * @return application name */ @@ -539,27 +548,30 @@ public class ObMultiHrsReports { /** * Set the Fog ALG CellType map * - * @param fogAlgCellType + * @param fogAlgCellType2 */ - public void setFogAlgCellType(HashMap fogAlgCellType) { - this.fogAlgCellType = fogAlgCellType; + public void setFogAlgCellType(Map fogAlgCellType2) { + this.fogAlgCellType = fogAlgCellType2; } /** * * @return fogAlgCellType */ - public HashMap getFogAlgCellType() { + public Map getFogAlgCellType() { return fogAlgCellType; } - private void initFogAlgCellType() { - fogAlgCellType = new HashMap(); - Set zones = MonitoringArea.getPlatformMap().keySet(); - Iterator itr = zones.iterator(); - while (itr.hasNext()) { - fogAlgCellType.put(itr.next(), CellType.NotAvailable); - } - setFogAlgCellType(fogAlgCellType); - } + /** + * Initiates ALG cells for Fog table. Sets all as NotAvailable. + */ + private void initFogAlgCellType() { + fogAlgCellType = new HashMap(); + Set zones = MonitoringArea.getPlatformMap().keySet(); + Iterator itr = zones.iterator(); + while (itr.hasNext()) { + fogAlgCellType.put(itr.next(), CellType.NotAvailable); + } + setFogAlgCellType(fogAlgCellType); + } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObsData.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObsData.java index adfd74f9f9..e9a89ee673 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObsData.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/data/ObsData.java @@ -19,65 +19,69 @@ **/ package com.raytheon.uf.viz.monitor.data; -import java.util.ArrayList; +import java.util.List; import java.util.concurrent.ConcurrentHashMap; /** -* Keeper of the obsData. It is stored in a keyed structure -* Area > Station > Date > ObReport -* -*
-* 
-* SOFTWARE HISTORY
-* 
-* Date         Ticket#     Engineer    Description
-* ------------ ----------  ----------- --------------------------
-* 12/07/09                  dhladky    Initial Creation.
-* 
-* 
-* -* @author dhladky -* -*/ + * Keeper of the obsData. It is stored in a keyed structure Area > Station > + * Date > ObReport + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * 12/07/09                  dhladky    Initial Creation.
+ * Nov 11, 2012 1297        skorolev    Changed ArrayList to List
+ * 
+ * 
+ * + * @author dhladky + * + */ public class ObsData { - + public ConcurrentHashMap tableData = null; - + /** * public construct */ public ObsData() { tableData = new ConcurrentHashMap(); } - + /** * Add an area + * * @param stations * @param areaId */ - public void addArea(String areaId, ArrayList stations) { + public void addArea(String areaId, List stations) { AreaContainer ac = new AreaContainer(stations, areaId); tableData.put(areaId, ac); } - + /** * Gets the Area Container + * * @param areaId * @return */ public AreaContainer getArea(String areaId) { AreaContainer ac = null; - + if (tableData.containsKey(areaId)) { ac = tableData.get(areaId); } - + return ac; } - + /** * remove the area + * * @param areaId */ public void removeArea(String areaId) { @@ -85,9 +89,10 @@ public class ObsData { tableData.remove(areaId); } } - + /** * Gets the container + * * @return */ public ConcurrentHashMap getContainer() { diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/hodograph/HodographDlg.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/hodograph/HodographDlg.java index fe1ad25761..cad6f93a9b 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/hodograph/HodographDlg.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/hodograph/HodographDlg.java @@ -34,322 +34,404 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; +import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.Shell; -public class HodographDlg extends Dialog { +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; - private Shell shell; +/** + * Hodograph dialog + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 26, 2012 1280       skorolev    Changes for non-blocking dialog.
+ * Nov. 1, 2012 1297       skorolev    Cleaned code
+ * 
+ * 
+ * + * @author wkwock + * @version 1.0 + */ +public class HodographDlg extends CaveSWTDialog { - private String elementName = null; - private String siteName = null; - private String dataName = null; + /** direction names **/ + private final String dirName[] = { "N", "NNE", "NE", "ENE", "E", "ESE", + "SE", "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" }; - /* - * direction name - */ - private String dirName[] = { "N", "NNE", "NE", "ENE", "E", "ESE", "SE", - "SSE", "S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW" }; - /* - * red threshold in degree - */ - private float redStartDegree = 0; - private float redDegree = 0; + /** red start threshold in degree **/ + private float redStartDegree = 0; - /* - * yellow threshold in degree - */ - private float yellowStartDegree = 0; - private float yellowDegree = 0; + /** red threshold in degree **/ + private float redDegree = 0; - /* - * green threshold in degree - */ - private float greenStartDegree = 0; - private float greenDegree = 0; + /** yellow start threshold in degree **/ + private float yellowStartDegree = 0; - /* - * Center x and y pixel point - */ - private final int CENTER_X = 285; - private final int CENTER_Y = 280; + /** yellow threshold in degree **/ + private float yellowDegree = 0; - /* - * Radius - */ - private final int RADIUS = 260; - /* - * current time - */ - private Calendar curTime = null; + /** green start threshold in degree **/ + private float greenStartDegree = 0; - /* - * Hodograph data - */ - private SortedMap hodographData; + /** green threshold in degree **/ + private float greenDegree = 0; - /* - * constant milliseconds in a day - */ - private final double milliSecInADay = 24.0 * 60 * 60 * 1000.0; + /** Center x pixel point **/ + private final int CENTER_X = 285; - /* - * display - */ - private Display display; + /** Center y pixel point **/ + private final int CENTER_Y = 280; - /** - * @param args - */ + /** Radius **/ + private final int RADIUS = 260; - public HodographDlg(Shell parent, String elementName, String siteName, - String dataName) { - super(parent, 0); - this.display = parent.getDisplay(); - this.elementName = elementName; - this.siteName = siteName; - this.dataName = dataName; - } + /** current time **/ + private Calendar curTime = null; - /** - * In Hodogrpah, the 0 degree is at North, and increase clockwise, opposite - * in geometry. - * - * @param degree - * @return - */ - private float convertDegree(float degree) { - return (360 + 90 - degree) % 360; - } + /** Hodograph data **/ + private SortedMap hodographData; - public void setGreenThreshold(float greenFromDegree, float greenToDegree) { - if (greenToDegree < greenFromDegree) - this.greenDegree = ((greenFromDegree - greenToDegree) - 360) % 360; - else - this.greenDegree = greenFromDegree - greenToDegree; - this.greenStartDegree = convertDegree(greenFromDegree); - } + /** constant milliseconds in a day **/ + private final double milliSecInADay = 24.0 * 60 * 60 * 1000.0; - public void setYellowThreshold(float yellowFromDegree, float yellowToDegree) { - if (yellowToDegree < yellowFromDegree) - this.yellowDegree = ((yellowFromDegree - yellowToDegree) - 360) % 360; - else - this.yellowDegree = yellowFromDegree - yellowToDegree; - this.yellowStartDegree = convertDegree(yellowFromDegree); - } + /** display **/ + private Display display; - public void setRedThreshold(float redFromDegree, float redToDegree) { - if (redToDegree < redFromDegree) - this.redDegree = ((redFromDegree - redToDegree) - 360) % 360; - else - this.redDegree = redFromDegree - redToDegree; + /** + * Constructor + * + * @param parent + * @param siteName + * @param dataName + * @param title + */ + public HodographDlg(Shell parent, String siteName, String dataName, + String title) { + super(parent, SWT.DIALOG_TRIM | SWT.RESIZE, CAVE.DO_NOT_BLOCK + | CAVE.INDEPENDENT_SHELL); + this.display = parent.getDisplay(); + setText(title); + setReturnValue(this.getText()); + } - this.redStartDegree = convertDegree(redFromDegree); - } + /* + * (non-Javadoc) + * + * @see com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#constructShellLayout() + */ + @Override + protected Layout constructShellLayout() { + // Create the main layout for the shell. + GridLayout mainLayout = new GridLayout(1, false); + mainLayout.marginWidth = 2; + mainLayout.verticalSpacing = 2; + return mainLayout; + } - private int degreeToY(double degree) { - int y = CENTER_Y - (int) Math.round((Math.cos(degree) * RADIUS)); - return y; - } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#initializeComponents(org + * .eclipse.swt.widgets.Shell) + */ + @Override + protected void initializeComponents(Shell shell) { + createHodoGraph(); + addCloseBttn(); + } - private int degreeToX(double degree) { - int x = CENTER_X + (int) Math.round((Math.sin(degree) * RADIUS)); - return x; - } + /** + * In Hodogrpah, the 0 degree is at North, and increase clockwise, opposite + * in geometry. + * + * @param degree + * @return + */ + private float convertDegree(float degree) { + return (360 + 90 - degree) % 360; + } - private void plotTimeLbls(GC gc) { - Calendar currentTime = (Calendar) curTime.clone(); + /** + * Sets Green Threshold + * + * @param greenFromDegree + * @param greenToDegree + */ + public void setGreenThreshold(float greenFromDegree, float greenToDegree) { + if (greenToDegree < greenFromDegree) + this.greenDegree = ((greenFromDegree - greenToDegree) - 360) % 360; + else + this.greenDegree = greenFromDegree - greenToDegree; + this.greenStartDegree = convertDegree(greenFromDegree); + } - for (int i = 13; i > 1; i--) { - String timeLabel = String.format("%tH:30", currentTime); + /** + * Sets Yellow Threshold + * + * @param yellowFromDegree + * @param yellowToDegree + */ + public void setYellowThreshold(float yellowFromDegree, float yellowToDegree) { + if (yellowToDegree < yellowFromDegree) + this.yellowDegree = ((yellowFromDegree - yellowToDegree) - 360) % 360; + else + this.yellowDegree = yellowFromDegree - yellowToDegree; + this.yellowStartDegree = convertDegree(yellowFromDegree); + } - int x = CENTER_X - (gc.textExtent(timeLabel).x / 2) - 2; - int y = CENTER_Y + RADIUS / 13 * i - gc.textExtent(timeLabel).y + 2; - gc.drawText(timeLabel, x, y, true); - currentTime.add(Calendar.HOUR_OF_DAY, -2); - } - gc.setLineWidth(1); - } + /** + * Sets Red Threshold + * + * @param redFromDegree + * @param redToDegree + */ + public void setRedThreshold(float redFromDegree, float redToDegree) { + if (redToDegree < redFromDegree) + this.redDegree = ((redFromDegree - redToDegree) - 360) % 360; + else + this.redDegree = redFromDegree - redToDegree; - private void plotDirNames(GC gc) { - for (int i = 0; i < dirName.length; i++) { - double radian = Math.PI * 2.0 * i / dirName.length; - int x = CENTER_X - + (int) Math.round((Math.sin(radian) * (RADIUS + 10 + gc - .textExtent(dirName[i]).x))); - int y = CENTER_Y - - (int) Math.round((Math.cos(radian) * (RADIUS + 10 + gc - .textExtent(dirName[i]).x))); - gc.drawText(dirName[i], x, y); - } - } + this.redStartDegree = convertDegree(redFromDegree); + } - private void plotElementName(GC gc) { - gc.drawText(elementName, 5, 5); - } + /** + * Converts degrees to plot coordinate Y + * + * @param degree + * @return + */ + private int degreeToY(double degree) { + int y = CENTER_Y - (int) Math.round((Math.cos(degree) * RADIUS)); + return y; + } - private void paintBackground(GC gc) { - gc.setBackground(display.getSystemColor(SWT.COLOR_GRAY)); - gc.fillOval(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, - RADIUS * 2); + /** + * Converts degrees to plot coordinate X + * + * @param degree + * @return + */ + private int degreeToX(double degree) { + int x = CENTER_X + (int) Math.round((Math.sin(degree) * RADIUS)); + return x; + } - gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN)); - gc.fillArc(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, - RADIUS * 2, (int) Math.round(greenStartDegree), (int) Math - .round(greenDegree)); + /** + * Plots time labels + * + * @param gc + */ + private void plotTimeLbls(GC gc) { + Calendar currentTime = (Calendar) curTime.clone(); + String timeLabel = String.format("%tH:30", currentTime); + for (int i = 13; i > 1; i--) { + int x = CENTER_X - (gc.textExtent(timeLabel).x / 2) - 2; + int y = CENTER_Y + RADIUS / 13 * i - gc.textExtent(timeLabel).y + 2; + gc.drawText(timeLabel, x, y, true); + currentTime.add(Calendar.HOUR_OF_DAY, -2); + } + gc.setLineWidth(1); + } - gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW)); - gc.fillArc(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, - RADIUS * 2, (int) Math.round(yellowStartDegree), (int) Math - .round(yellowDegree)); + /** + * Plots direction names. + * + * @param gc + */ + private void plotDirNames(GC gc) { + for (int i = 0; i < dirName.length; i++) { + double radian = Math.PI * 2.0 * i / dirName.length; + int x = CENTER_X + + (int) Math.round((Math.sin(radian) * (RADIUS + 10 + gc + .textExtent(dirName[i]).x))); + int y = CENTER_Y + - (int) Math.round((Math.cos(radian) * (RADIUS + 10 + gc + .textExtent(dirName[i]).x))); + gc.drawText(dirName[i], x, y); + } + } - gc.setBackground(display.getSystemColor(SWT.COLOR_RED)); - gc.fillArc(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, - RADIUS * 2, (int) Math.round(redStartDegree), (int) Math - .round(redDegree)); + /** + * Paint Background + * + * @param gc + */ + private void paintBackground(GC gc) { + gc.setBackground(display.getSystemColor(SWT.COLOR_GRAY)); + gc.fillOval(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, + RADIUS * 2); - // goes back to original background color - gc.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); + gc.setBackground(display.getSystemColor(SWT.COLOR_GREEN)); + gc.fillArc(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, + RADIUS * 2, (int) Math.round(greenStartDegree), + (int) Math.round(greenDegree)); - } + gc.setBackground(display.getSystemColor(SWT.COLOR_YELLOW)); + gc.fillArc(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, + RADIUS * 2, (int) Math.round(yellowStartDegree), + (int) Math.round(yellowDegree)); - private void plotWindDir(GC gc) { - gc.setBackground(display.getSystemColor(SWT.COLOR_DARK_BLUE)); - if (hodographData == null) - return; - long curSec = curTime.getTimeInMillis(); + gc.setBackground(display.getSystemColor(SWT.COLOR_RED)); + gc.fillArc(CENTER_X - RADIUS, CENTER_Y - RADIUS, RADIUS * 2, + RADIUS * 2, (int) Math.round(redStartDegree), + (int) Math.round(redDegree)); - boolean lastOneExist = false; - int lastX = 0; - int lastY = 0; + // goes back to original background color + gc.setBackground(display.getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); - for (Date obsTime : hodographData.keySet()) { - float obsVal = hodographData.get(obsTime); - /* - * When wind speed is zero, wind direction is - * set to be ObConst.MISSING, which is -9999.0f; - */ - if (obsVal < 0.0f) { // wind direction is missing - lastOneExist = false; - continue; // missing value - } - double obsValInRadian = convertDegree(obsVal) * Math.PI * 2.0 - / 360.0; - long thisSec = obsTime.getTime(); - if (thisSec > curSec) { - lastOneExist = false; - continue; // not in the last 24 hour - } - if (thisSec < (curSec - milliSecInADay)) { - lastOneExist = false; - continue; // not in the last 24 hour - } + } - double offsetFromCenter = (milliSecInADay - curSec + thisSec) - / milliSecInADay * RADIUS; + /** + * Plots wind direction + * + * @param gc + */ + private void plotWindDir(GC gc) { + gc.setBackground(display.getSystemColor(SWT.COLOR_DARK_BLUE)); + if (hodographData == null) + return; + long curSec = curTime.getTimeInMillis(); - int x = CENTER_X - + (int) Math.round(offsetFromCenter - * Math.cos(obsValInRadian)); - int y = CENTER_Y - - (int) Math.round(offsetFromCenter - * Math.sin(obsValInRadian)); + boolean lastOneExist = false; + int lastX = 0; + int lastY = 0; - gc.fillOval(x, y, 5, 6); - if (lastOneExist) - gc.drawLine(x, y, lastX, lastY); + for (Date obsTime : hodographData.keySet()) { + float obsVal = hodographData.get(obsTime); + /* + * When wind speed is zero, wind direction is set to be + * ObConst.MISSING, which is -9999.0f; + */ + if (obsVal < 0.0f) { // wind direction is missing + lastOneExist = false; + continue; // missing value + } + double obsValInRadian = convertDegree(obsVal) * Math.PI * 2.0 + / 360.0; + long thisSec = obsTime.getTime(); + if (thisSec > curSec) { + lastOneExist = false; + continue; // not in the last 24 hour + } + if (thisSec < (curSec - milliSecInADay)) { + lastOneExist = false; + continue; // not in the last 24 hour + } - lastX = x; - lastY = y; - lastOneExist = true; - } + double offsetFromCenter = (milliSecInADay - curSec + thisSec) + / milliSecInADay * RADIUS; - } + int x = CENTER_X + + (int) Math.round(offsetFromCenter + * Math.cos(obsValInRadian)); + int y = CENTER_Y + - (int) Math.round(offsetFromCenter + * Math.sin(obsValInRadian)); - public void setHodoGraphData(SortedMap hodographData) { - this.hodographData = hodographData; - } + gc.fillOval(x, y, 5, 6); + if (lastOneExist) + gc.drawLine(x, y, lastX, lastY); - private void drawCanvas(Canvas drawBoard) { - drawBoard.addPaintListener(new PaintListener() { - public void paintControl(PaintEvent e) { - e.gc.setAntialias(SWT.ON); - e.gc.setLineWidth(1); - paintBackground(e.gc); - // draw circles - e.gc.setForeground(display - .getSystemColor(SWT.COLOR_DARK_MAGENTA)); - int numCircle = 13; - for (int i = 1; i <= numCircle; i++) - e.gc.drawOval(CENTER_X - RADIUS / numCircle * i, CENTER_Y - - RADIUS / numCircle * i, RADIUS / numCircle * 2 - * i, RADIUS / numCircle * 2 * i); + lastX = x; + lastY = y; + lastOneExist = true; + } - // draw direction lines - e.gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); - for (int i = 0; i < 16; i++) { - int x2 = degreeToX(i / 16.0 * Math.PI * 2.0); - int y2 = degreeToY(i / 16.0 * Math.PI * 2.0); - e.gc.drawLine(CENTER_X, CENTER_Y, x2, y2); - } + } - plotDirNames(e.gc); - plotTimeLbls(e.gc); - plotElementName(e.gc); - plotWindDir(e.gc); - } - }); - } + /** + * Sets hodograph data + * + * @param hodographData + */ + public void setHodoGraphData(SortedMap hodographData) { + this.hodographData = hodographData; + } - private void addCloseBttn() { - Composite c = new Composite(shell, SWT.NONE); - GridLayout gl = new GridLayout(1, false); - GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); + /** + * Creates canvas + * + * @param drawBoard + */ + private void drawCanvas(Canvas drawBoard) { + drawBoard.addPaintListener(new PaintListener() { + public void paintControl(PaintEvent e) { + e.gc.setAntialias(SWT.ON); + e.gc.setLineWidth(1); + paintBackground(e.gc); + // draw circles + e.gc.setForeground(display + .getSystemColor(SWT.COLOR_DARK_MAGENTA)); + int numCircle = 13; + for (int i = 1; i <= numCircle; i++) + e.gc.drawOval(CENTER_X - RADIUS / numCircle * i, CENTER_Y + - RADIUS / numCircle * i, RADIUS / numCircle * 2 + * i, RADIUS / numCircle * 2 * i); - c.setLayout(gl); - c.setLayoutData(gd); + // draw direction lines + e.gc.setForeground(display.getSystemColor(SWT.COLOR_BLACK)); + for (int i = 0; i < 16; i++) { + int x2 = degreeToX(i / 16.0 * Math.PI * 2.0); + int y2 = degreeToY(i / 16.0 * Math.PI * 2.0); + e.gc.drawLine(CENTER_X, CENTER_Y, x2, y2); + } - gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); - Button closeBtn = new Button(c, SWT.CLOSE); - closeBtn.setText("Close"); - closeBtn.setLayoutData(gd); - final Shell closeShell = shell; - closeBtn.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent event) { - closeShell.dispose(); - } - }); - } + plotDirNames(e.gc); + plotTimeLbls(e.gc); + plotWindDir(e.gc); + } + }); + } - public void open() { - Shell parent = getParent(); - shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE); + /** + * Adds Close button + */ + private void addCloseBttn() { + Composite c = new Composite(getShell(), SWT.NONE); + GridLayout gl = new GridLayout(1, false); + GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); - shell.setText(elementName + " Hodograph for " + siteName + "#" - + dataName); - shell.setLayout(new GridLayout(1, false)); + c.setLayout(gl); + c.setLayoutData(gd); - Composite c = new Composite(shell, SWT.NONE); - GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); - c.setLayoutData(data); + gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); + Button closeBtn = new Button(c, SWT.CLOSE); + closeBtn.setText("Close"); + closeBtn.setLayoutData(gd); + closeBtn.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent event) { + close(); + } + }); + } - Canvas canvas = new Canvas(c, SWT.DIALOG_TRIM); - canvas.setSize(600, 600); - drawCanvas(canvas); + /** + * Plots trend graph + */ + public void createHodoGraph() { - addCloseBttn(); + Composite c = new Composite(this.getShell(), SWT.NONE); + display = c.getDisplay(); + Canvas canvas = new Canvas(c, SWT.DIALOG_TRIM); + GridData data = new GridData(SWT.FILL, SWT.FILL, true, true); + canvas.setSize(600, 600); + c.setLayoutData(data); + drawCanvas(canvas); - shell.pack(); - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - } + } - public void setCurrentTime(Calendar currentTime) { - this.curTime = currentTime; - } + /** + * Sets current time + * + * @param currentTime + */ + public void setCurrentTime(Calendar currentTime) { + this.curTime = currentTime; + } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/listeners/IMonitorControlListener.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/listeners/IMonitorControlListener.java index 491d88be09..96c4414519 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/listeners/IMonitorControlListener.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/listeners/IMonitorControlListener.java @@ -19,7 +19,7 @@ **/ package com.raytheon.uf.viz.monitor.listeners; -import java.util.ArrayList; +import java.util.List; import com.raytheon.uf.viz.monitor.IMonitor; import com.raytheon.uf.viz.monitor.events.IMonitorConfigurationEvent; @@ -27,8 +27,8 @@ import com.raytheon.uf.viz.monitor.events.IMonitorThresholdEvent; /** * - * IMonitorControlListener, Interface that gives some measure of control to dialogs - * over their corresponding monitors. + * IMonitorControlListener, Interface that gives some measure of control to + * dialogs over their corresponding monitors. * *
  * SOFTWARE HISTORY
@@ -42,20 +42,19 @@ import com.raytheon.uf.viz.monitor.events.IMonitorThresholdEvent;
  * 
  */
 public interface IMonitorControlListener {
-    
+
     public void fireConfigUpdate(IMonitorConfigurationEvent imce);
-    
+
     public void fireThresholdUpdate(IMonitorThresholdEvent imte);
-    
+
     public void fireKillMonitor();
-   
+
     public void addMonitorControlListener(IMonitor monitor);
 
-    public void removeMonitorContorlListener(IMonitor monitor); 
-    
-    public ArrayList getMonitorControlListeners();
-    
+    public void removeMonitorContorlListener(IMonitor monitor);
+
+    public List getMonitorControlListeners();
+
     public void fireDialogShutdown(IMonitorListener iml);
- 
 
 }
diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/trendplot/TrendPlotDlg.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/trendplot/TrendPlotDlg.java
index 32d48c00a1..100ad28732 100644
--- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/trendplot/TrendPlotDlg.java
+++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/trendplot/TrendPlotDlg.java
@@ -19,9 +19,9 @@
  **/
 package com.raytheon.uf.viz.monitor.trendplot;
 
-import java.util.ArrayList;
 import java.util.Date;
 import java.util.Iterator;
+import java.util.List;
 
 import org.eclipse.swt.SWT;
 import org.eclipse.swt.events.SelectionAdapter;
@@ -45,9 +45,10 @@ import com.raytheon.viz.ui.dialogs.CaveSWTDialog;
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * 2009-12-02			   vkorolev    Initial creation.
- * 2010-01-21	4268	   vkorolev	   Fixed Trend Plot
- * 2012-10-15   1229       vkorolev    Changes for non-blocking TrendPlotDlg
+ * 2009-12-02			   skorolev    Initial creation.
+ * 2010-01-21	4268	   skorolev	   Fixed Trend Plot
+ * Oct 15,2012  1229       skorolev    Changes for non-blocking TrendPlotDlg
+ * Nov 11,2012  1297       skorolev    Added title parameter and cleaned code
  * 
* * @author vkorolev @@ -58,7 +59,7 @@ public class TrendPlotDlg extends CaveSWTDialog { private String station; - private ArrayList product; + private List product; private String dataName; @@ -66,21 +67,34 @@ public class TrendPlotDlg extends CaveSWTDialog { public Date curdate; - public String var; - + /** + * Constructor + * + * @param parent + * @param selectedZone + * @param station + * @param product + * @param dataName + * @param title + */ public TrendPlotDlg(Shell parent, String selectedZone, String station, - ArrayList product, String dataName) { + List product, String dataName, String title) { super(parent, SWT.DIALOG_TRIM | SWT.RESIZE, CAVE.DO_NOT_BLOCK | CAVE.INDEPENDENT_SHELL); - setText(getTrendPlotName(product) + " Trend Plot for " + station + "#" - + dataName); + setText(title); + setReturnValue(this.getText()); this.selectedZone = selectedZone; this.product = product; this.dataName = dataName; this.station = station; } + /* + * (non-Javadoc) + * + * @see com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#constructShellLayout() + */ @Override protected Layout constructShellLayout() { // Create the main layout for the shell. @@ -91,9 +105,15 @@ public class TrendPlotDlg extends CaveSWTDialog { return mainLayout; } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#initializeComponents(org + * .eclipse.swt.widgets.Shell) + */ @Override protected void initializeComponents(Shell shell) { - setReturnValue(product); // Initialize all layouts Iterator prodVar = product.iterator(); while (prodVar.hasNext()) { @@ -104,6 +124,9 @@ public class TrendPlotDlg extends CaveSWTDialog { addCloseBtn(); } + /** + * Adds Close button. + */ private void addCloseBtn() { Composite c = new Composite(shell, SWT.NONE); GridLayout gl = new GridLayout(1, false); @@ -116,44 +139,24 @@ public class TrendPlotDlg extends CaveSWTDialog { closeBtn.setLayoutData(gd); closeBtn.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { - shell.dispose(); + close(); } }); } + /** + * @return shell + */ public Widget getCurrentShell() { return shell; } + /** + * Sets data for table. + * + * @param obData + */ public void setData(ObMultiHrsReports obData) { this.obData = obData; } - - private String getTrendPlotName(ArrayList prod) { - String varName = null; - String name = (String) prod.get(0); - int stInd = name.indexOf("_"); - if (prod.size() > 1) { - varName = name.substring(0, stInd); - if (varName.equals("SCA")) { - varName = "Small Craft Advisory"; - } else if (varName.equals("GALE")) { - varName = "Gale Warning"; - } else if (varName.equals("STORM")) { - varName = "Storm Warning"; - } else if (varName.equals("HURRICANE")) { - varName = "Hurricane Force Wind Warning"; - } else if (varName.equals("BLIZ")) { - varName = "Blizzard Warning"; - } else if (varName.equals("FRZ")) { - varName = "Frizing Precipitation"; - } else if (varName.equals("HSW")) { - varName = "Heavy Snow Warning"; - } - } else { - varName = name.substring(stInd + 1); - } - - return varName; - } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/StationTableComp.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/StationTableComp.java index f15e3df3ac..53a13ea019 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/StationTableComp.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/StationTableComp.java @@ -254,7 +254,7 @@ public class StationTableComp extends TableComp { * @return Column index. */ @Override - protected int getColumnIndex(AppName appName, String sortCol) { + public int getColumnIndex(AppName appName, String sortCol) { return tableConfig.getTableColumnIndex(appName, sortCol); } @@ -301,7 +301,7 @@ public class StationTableComp extends TableComp { * @param name */ public void setIdLabel(String name) { - idLbl.setText("Zone/County: "+ this.id +" - "+ name); + idLbl.setText("Zone/County: " + this.id + " - " + name); controlComp.layout(); } @@ -355,11 +355,11 @@ public class StationTableComp extends TableComp { } } - @Override - protected void packColumns() { - for (int i = 0; i < table.getColumnCount(); i++) { - table.getColumn(i).pack(); - table.getColumn(i).setWidth(defaultColWidth); - } - } + @Override + protected void packColumns() { + for (int i = 0; i < table.getColumnCount(); i++) { + table.getColumn(i).pack(); + table.getColumn(i).setWidth(defaultColWidth); + } + } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableComp.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableComp.java index 00ca75cad0..8404cc8fed 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableComp.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableComp.java @@ -30,89 +30,89 @@ import org.eclipse.swt.widgets.TableItem; import com.raytheon.uf.common.monitor.data.ColumnAttribData; import com.raytheon.uf.common.monitor.data.CommonConfig; -import com.raytheon.uf.common.monitor.data.CommonTableConfig; import com.raytheon.uf.common.monitor.data.CommonConfig.AppName; +import com.raytheon.uf.common.monitor.data.CommonTableConfig; import com.raytheon.uf.viz.monitor.data.TableData; /** * Zone table composite that contains the table for the zones. * *
- *
+ * 
  * SOFTWARE HISTORY
- *
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Apr 7, 2009            lvenable     Initial creation
- *
+ * 
  * 
- * + * * @author lvenable * @version 1.0 */ -public class ZoneTableComp extends TableComp -{ +public class ZoneTableComp extends TableComp { /** * Callback for the zone table. */ private IZoneTableAction zoneTableCallback; - + /** * Mouse point. */ - private Point mousePt = new Point(0,0); - + private Point mousePt = new Point(0, 0); + /** * Common table config data. */ private CommonTableConfig tableConfig; - + /** * Constructor. - * @param parent Parent composite. - * @param data Table data. - * @param appName Application name. - * @param callback Zone table action callback. + * + * @param parent + * Parent composite. + * @param data + * Table data. + * @param appName + * Application name. + * @param callback + * Zone table action callback. */ - public ZoneTableComp(Composite parent, TableData data, CommonConfig.AppName appName, - IZoneTableAction callback) - { + public ZoneTableComp(Composite parent, TableData data, + CommonConfig.AppName appName, IZoneTableAction callback) { super(parent, data, appName); - + this.zoneTableCallback = callback; - - tableConfig = CommonTableConfig.getInstance(); - + + tableConfig = CommonTableConfig.getInstance(); + init(); } /** * Handle the mouse down action. - * @param event Mouse event. + * + * @param event + * Mouse event. */ @Override - protected void tableMouseDownAction(MouseEvent event) - { + protected void tableMouseDownAction(MouseEvent event) { tableIndex = table.getSelectionIndex(); mousePt.x = event.x; mousePt.y = event.y; TableItem item = table.getItem(mousePt); - - if (item == null) - { + + if (item == null) { return; - } - - for (int i = 0; i < table.getColumnCount(); i++) - { + } + + for (int i = 0; i < table.getColumnCount(); i++) { Rectangle rect = item.getBounds(i); - if (rect.contains(mousePt)) - { + if (rect.contains(mousePt)) { int index = table.indexOf(item); System.out.println("Item " + index + "-" + i); - - if (i == 0) - { + + if (i == 0) { this.zoneTableCallback.zoneTableAction(index); } } @@ -123,42 +123,42 @@ public class ZoneTableComp extends TableComp /** * Handle the table mouse hover action. - * @param event Maouse event. + * + * @param event + * Maouse event. */ @Override - protected void tableMouseHoverAction(MouseEvent event) - { + protected void tableMouseHoverAction(MouseEvent event) { Rectangle rect; mousePt.x = event.x; mousePt.y = event.y; TableItem item = table.getItem(mousePt); - - if (item == null) - { + + if (item == null) { table.setToolTipText(null); return; } - + int index = table.indexOf(item); - - for (int i = 0; i < table.getColumnCount(); i++) - { + + for (int i = 0; i < table.getColumnCount(); i++) { rect = item.getBounds(i); - if (rect.contains(mousePt)) - { - table.setToolTipText(tableData.getTableRows().get(index).getTableCellDataArray()[i].getHoverText()); + if (rect.contains(mousePt)) { + table.setToolTipText(tableData.getTableRows().get(index) + .getTableCellDataArray()[i].getHoverText()); } } } /** * Add controls above the table on the display. - * @param parentComp Parent composite. + * + * @param parentComp + * Parent composite. */ @Override - protected void addTopTableControls(Composite parentComp) - { + protected void addTopTableControls(Composite parentComp) { GridData gd = new GridData(); gd.horizontalIndent = 10; Label zoneLbl = new Label(parentComp, SWT.NONE); @@ -168,61 +168,65 @@ public class ZoneTableComp extends TableComp /** * Get the column index given the application name and sort column. - * @param appName Application name. - * @param columnName Column name. + * + * @param appName + * Application name. + * @param columnName + * Column name. */ @Override - protected int getColumnIndex(AppName appName, String columnName) - { + public int getColumnIndex(AppName appName, String columnName) { return tableConfig.getTableColumnIndex(appName, columnName); } /** * Get the array of column keys. - * @param appName Application name. + * + * @param appName + * Application name. * @return String array of column keys. */ @Override - protected String[] getColumnKeys(AppName appName) - { + protected String[] getColumnKeys(AppName appName) { return tableConfig.getTableColumnKeys(appName); } /** * Get the default column width. - * @param appName Application name. + * + * @param appName + * Application name. * @return The default column width. */ @Override - protected int getDefaultColWidth(AppName appName) - { + protected int getDefaultColWidth(AppName appName) { int colWidth = tableConfig.getTableDefaultColWidth(appName); return colWidth; } /** * Get the column attribute data. - * @param colName Column name. + * + * @param colName + * Column name. * @return The column attribute data. */ @Override - protected ColumnAttribData getColumnAttribteData(String colName) - { + protected ColumnAttribData getColumnAttribteData(String colName) { return tableConfig.getTableColumnAttr(colName); } @Override - protected void tableColRightMouseAction(MouseEvent event) - { + protected void tableColRightMouseAction(MouseEvent event) { // TODO Auto-generated method stub - + } - @Override - protected void packColumns() { - for (int i = 0; i < table.getColumnCount(); i++) { - table.getColumn(i).pack(); - table.getColumn(i).setWidth(defaultColWidth); - } - } + @Override + protected void packColumns() { + for (int i = 0; i < table.getColumnCount(); i++) { + table.getColumn(i).pack(); + table.getColumn(i).setWidth(defaultColWidth); + } + } } diff --git a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableDlg.java b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableDlg.java index 3bb4edfc36..9012b14cc4 100644 --- a/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableDlg.java +++ b/cave/com.raytheon.uf.viz.monitor/src/com/raytheon/uf/viz/monitor/ui/dialogs/ZoneTableDlg.java @@ -22,13 +22,13 @@ package com.raytheon.uf.viz.monitor.ui.dialogs; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; -import java.util.Calendar; import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import java.util.TimeZone; import org.eclipse.swt.SWT; -import org.eclipse.swt.events.DisposeEvent; -import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.ShellAdapter; @@ -37,8 +37,8 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Layout; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; @@ -50,7 +50,6 @@ import com.raytheon.uf.common.monitor.data.CommonTableConfig; import com.raytheon.uf.common.monitor.data.CommonTableConfig.GraphType; import com.raytheon.uf.common.monitor.data.CommonTableConfig.ObsHistType; import com.raytheon.uf.common.monitor.data.ObConst; -import com.raytheon.uf.common.monitor.data.ObConst.DisplayVarName; import com.raytheon.uf.viz.core.IDisplayPane; import com.raytheon.uf.viz.core.IDisplayPaneContainer; import com.raytheon.uf.viz.core.drawables.IDescriptor; @@ -66,9 +65,10 @@ import com.raytheon.uf.viz.monitor.hodograph.HodographDlg; import com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener; import com.raytheon.uf.viz.monitor.listeners.IMonitorListener; import com.raytheon.uf.viz.monitor.trendplot.TrendPlotDlg; -import com.raytheon.uf.viz.monitor.util.MonitorConfigConstants; -import com.raytheon.viz.ui.EditorUtil; import com.raytheon.uf.viz.monitor.util.ObUtil; +import com.raytheon.viz.ui.EditorUtil; +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; +import com.raytheon.viz.ui.dialogs.ICloseCallback; /** * Abstrct Zone table dialog that is the foundation for all Zone dialogs. @@ -83,47 +83,29 @@ import com.raytheon.uf.viz.monitor.util.ObUtil; * Jan 04, 2010 3424 Slav/Wen Adds hodograph and trend plot. * Jan 18, 2010 3424 Slav Change in trend plot * Oct 07, 2010 5105 zhao Disabled the 'X' button of the shell + * Oct 26, 2012 1280 skorolev Changes for non-blocking dialog. + * Nov.11, 2012 1297 skorolev new abstract initiateProdArray() * * * * @author lvenable * @version 1.0 */ -public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, - IMonitorControlListener, IStationTableAction, IZoneTableAction { +public abstract class ZoneTableDlg extends CaveSWTDialog implements + IMonitorListener, IMonitorControlListener, IStationTableAction, + IZoneTableAction { /** Array listening monitors **/ - protected ArrayList controlListeners = new ArrayList(); + protected List controlListeners = new ArrayList(); - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - // private Display display; - - /** - * top controls & labels - */ + /** top controls & labels **/ private Composite controlComp; - /** - * Return value when the shell is disposed. - */ - private final Boolean returnValue = false; - - /** - * Zone table. - */ + /** Zone table. **/ protected ZoneTableComp zoneTable; - /** - * Station table. - */ - private StationTableComp stationTable; + /** Station table. **/ + protected StationTableComp stationTable; /** * This object contains all observation data necessary for table dialogs and @@ -142,14 +124,14 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, * a specific nominal-time (get zoneTblData using obData's getZoneTableData * method) */ - private TableData zoneTblData; + protected TableData zoneTblData; /** * This is the station table data to be displayed in the station table * dialog for a specific nominal-time and a specific zone (get stnTblData * using obData's getStationTableData method) */ - private TableData stnTblData; + protected TableData stnTblData; /** * The zone selected to display its station data in the station table @@ -162,103 +144,97 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, */ private String selectedZoneHoverText = ""; - /** - * Variable name for station column - */ - private ObConst.VarName varName; + /** Variable name for station column **/ + public ObConst.VarName varName; - /** - * Application name. - */ - private final CommonConfig.AppName appName; + /** Application name. **/ + protected final CommonConfig.AppName appName; - /** - * Table configuration file - */ - // private CommonTableConfig config; - - /** - * Table attribute dialog. - */ + /** Table attribute dialog. **/ private TableAttribDlg attrDlg; - /** - * Link to frame check box. - */ + /** Link to frame check box. **/ protected Button linkToFrameChk; + /** Link-to-frame flag. **/ public boolean linkedToFrame = false; - /** - * Vertical check box. - */ + /** Vertical check box. **/ private Button vertChk; - /** - * Nominal time label. - */ + /** Nominal time label. **/ private Label nominalTimeLbl; - /** - * Nominal time label. - */ - // private Date date; - /** - * Table stack composite. - */ + /** Table stack composite. **/ private Composite tableStackComp; - /** - * Table stack layout. - */ - // private StackLayout tableStack; - - /** - * Zone table composite that contains the zone table. - */ + /** Zone table composite that contains the zone table. **/ private Composite zoneTblComp; - /** - * Station table composite that contains the station table. - */ + /** Station table composite that contains the station table. **/ private Composite stationTblComp; - /** simple date in GMT **/ + /** simple date in GMT. **/ private final DateFormat dFormat = new SimpleDateFormat( "E MMM dd HH:mm:ss yyyy"); - private ArrayList prodArray; + /** list of variables to plot. **/ + public List prodArray; - /** - * zone sort column index, initialized to its default value - */ - private int zoneSortColumn = 0; + /** zone sort column index, initialized to its default value. **/ + protected int zoneSortColumn = 0; - /** - * zone sort direction, initialized to its default value - */ - private int zoneSortDirection = SWT.NONE; + /** zone sort direction, initialized to its default value. **/ + protected int zoneSortDirection = SWT.NONE; - /** - * station sort column, initialized to its default value - */ - private int stnSortColumn = 0; + /** station sort column, initialized to its default value. **/ + protected int stnSortColumn = 0; - /** - * station sort direction, initialized to its default value - */ - private int stnSortDirection = SWT.NONE; + /** station sort direction, initialized to its default value. **/ + protected int stnSortDirection = SWT.NONE; + /** Latitude **/ private double lat; + /** Longitude **/ private double lon; - public static float ZONE_ZOOM_LEVEL = 100; + /** Zoom to zone level. **/ + public final float ZONE_ZOOM_LEVEL = 100; - public static float STATION_ZOOM_LEVEL = 50; + /** Zoom to station level. **/ + public final float STATION_ZOOM_LEVEL = 50; + /** Data source. **/ + public String dataSrc = "METAR"; + + /** trend plots. **/ + private TrendPlotDlg tpd, tpdHodo; + + /** Hodograph. **/ + private HodographDlg hodographDlg; + + /** History table. **/ + private ObsHistTableDlg obsHstTblDlg; + + /** dispose action. **/ protected abstract void shellDisposeAction(); + /** List of opened plots. **/ + private Map openedDlgs = new HashMap(); + + /** row index in the station table. **/ + public int rowIndex; + + /** column index in the station table. **/ + public int colIndex; + + /** Common configuration for zone table. **/ + public CommonTableConfig config = CommonTableConfig.getInstance(); + + /** title of plot. **/ + private String dlgTitle; + /** * Constructor * @@ -267,12 +243,13 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, */ public ZoneTableDlg(Shell parent, ObMultiHrsReports obData, CommonConfig.AppName appName) { - super(parent, 0); + super(parent, SWT.DIALOG_TRIM | SWT.RESIZE, CAVE.DO_NOT_BLOCK + | CAVE.INDEPENDENT_SHELL); this.appName = appName; dFormat.setTimeZone(TimeZone.getTimeZone("GMT")); this.obData = obData; - zoneTblData = obData.getZoneTableData(); // the zone table data of the - // latest nominal time + // the zone table data of the latest nominal time: + zoneTblData = obData.getZoneTableData(); zoneTblData.sortData(); nominalTime = obData.getLatestNominalTime(); } @@ -284,17 +261,28 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, * @param appName */ public ZoneTableDlg(Shell parent, CommonConfig.AppName appName) { - super(parent, 0); + super(parent, SWT.DIALOG_TRIM | SWT.RESIZE, CAVE.DO_NOT_BLOCK + | CAVE.INDEPENDENT_SHELL); this.appName = appName; dFormat.setTimeZone(TimeZone.getTimeZone("GMT")); } + /** + * Sets zone table data + * + * @param obData + */ protected void setObData(ObMultiHrsReports obData) { this.obData = obData; - zoneTblData = obData.getZoneTableData(); // the zone table data of the - // latest nominal time + // the zone table data of the latest nominal time: + zoneTblData = obData.getZoneTableData(); } + /** + * Sets nominal time and sorts data + * + * @param date + */ public void setDate(Date date) { this.nominalTime = TableUtil.getNominalTime(date); if (date != null) { @@ -302,69 +290,55 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } } - /** - * Open method to display the dialog. + /* + * (non-Javadoc) * - * @return Boolean return value. + * @see com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#constructShellLayout() */ - public Object open() { - - Shell parent = getParent(); - shell = new Shell(parent.getDisplay(), SWT.DIALOG_TRIM | SWT.RESIZE); - parent.addDisposeListener(new DisposeListener() { - @Override - public void widgetDisposed(DisposeEvent e) { - shell.dispose(); - } - }); - shell.setText(appName.name() + " Threat Level ZONE/COUNTY Table"); - + @Override + protected Layout constructShellLayout() { // Create the main layout for the shell. + setText(appName.name() + " Threat Level ZONE/COUNTY Table"); GridLayout mainLayout = new GridLayout(1, false); mainLayout.marginHeight = 2; mainLayout.marginWidth = 2; mainLayout.verticalSpacing = 2; - shell.setLayout(mainLayout); + return mainLayout; + } - // Initialize all of the controls and layouts + /* + * (non-Javadoc) + * + * @see + * com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#initializeComponents(org + * .eclipse.swt.widgets.Shell) + */ + @Override + protected void initializeComponents(Shell shell) { + setReturnValue(false); initializeComponents(); - - /** - * Disable the close [x] button, prompt the user to use Cave Clear - * button to close application - */ - shell.addShellListener(new ShellAdapter() { + getShell().addShellListener(new ShellAdapter() { @Override public void shellClosed(ShellEvent event) { - MessageBox msgBox = new MessageBox(shell, SWT.OK); + MessageBox msgBox = new MessageBox(getShell(), SWT.OK); msgBox.setMessage("Use the Clear button on D2D to dispose this dialog"); msgBox.open(); event.doit = false; } }); - - shellDisposeAction(); - shell.pack(); - shell.setVisible(true); - - return returnValue; } /** - * Initialize the components on the dialog. + * Initializes the components on the dialog. */ private void initializeComponents() { createTopControls(); // Add a horizontal separator bar to the display. - Label sepLbl = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL); + Label sepLbl = new Label(getShell(), SWT.SEPARATOR | SWT.HORIZONTAL); sepLbl.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); - // tableStackComp = new Composite(shell, SWT.NONE); - // tableStack = new StackLayout(); - // tableStackComp.setLayout(tableStack); - - tableStackComp = new Composite(shell, SWT.NONE); + tableStackComp = new Composite(getShell(), SWT.NONE); tableStackComp.setLayout(new GridLayout(1, false)); tableStackComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); @@ -372,9 +346,6 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, createZoneTable(tableStackComp); createStationTable(tableStackComp); - // tableStack.topControl = zoneTblComp; - // tableStackComp.layout(); - ((GridData) zoneTblComp.getLayoutData()).exclude = false; zoneTblComp.setVisible(true); @@ -385,10 +356,10 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } /** - * Create the controls at the top of the dialog. + * Creates the controls at the top of the dialog. */ private void createTopControls() { - controlComp = new Composite(shell, SWT.NONE); + controlComp = new Composite(getShell(), SWT.NONE); controlComp.setLayout(new GridLayout(6, false)); GridData gd = new GridData(SWT.DEFAULT, SWT.CENTER, false, true); @@ -451,21 +422,24 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } /** - * Create the zone table. + * Creates the zone table. * * @param stackComp * Stack composite. */ private void createZoneTable(Composite stackComp) { // TODO : Need to use a stack layout to show more than on table - zoneTblComp = new Composite(stackComp, SWT.NONE); zoneTblComp.setLayout(new GridLayout(1, false)); zoneTblComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - zoneTable = new ZoneTableComp(zoneTblComp, zoneTblData, appName, this); } + /** + * Updates zone table + * + * @param date + */ public void updateZoneTable(Date date) { /** * before update zoneTblData, set zone sort column and direction to @@ -480,6 +454,11 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, zoneTable.table.redraw(); } + /** + * Updates nominal time label + * + * @param date + */ public void updateNominalTimeLabel(Date date) { nominalTimeLbl.setText(dFormat.format(date)); nominalTimeLbl.redraw(); @@ -501,57 +480,19 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } /** - * set zone table sort column index and sort direction to the current zone + * Sets zone table sort column index and sort direction to the current zone * table sort column index and sort direction */ - private void setZoneSortColumnAndDirection() { - if (zoneTblData != null) { - zoneSortColumn = zoneTblData.getSortColumn(); - zoneSortDirection = zoneTblData.getSortDirection(); - /** - * for safeseas swell period sort direction flip - */ - if ( appName != AppName.SAFESEAS ) { - return; - } - if ( zoneSortColumn == zoneTable.getColumnIndex(appName,"SSZT_SwellPeriod") - || zoneSortColumn == zoneTable.getColumnIndex(appName,"SSZT_Swell2Period") ) { - if ( MonitorConfigConstants.isRankSwellPeriodHigh() ) { - zoneSortDirection = SWT.DOWN; - } else { - zoneSortDirection = SWT.UP; - } - } - } - } + protected abstract void setZoneSortColumnAndDirection(); /** - * set station table sort column index and sort direction to the current + * Sets station table sort column index and sort direction to the current * station table sort column index and sort direction */ - private void setStnSortColumnAndDirection() { - if (stnTblData != null) { - stnSortColumn = stnTblData.getSortColumn(); - stnSortDirection = stnTblData.getSortDirection(); - /** - * for safeseas swell period sort direction flip - */ - if ( appName != AppName.SAFESEAS ) { - return; - } - if ( stnSortColumn == stationTable.getColumnIndex(appName,"SSZT_SwellPeriod") - || stnSortColumn == stationTable.getColumnIndex(appName,"SSZT_Swell2Period") ) { - if ( MonitorConfigConstants.isRankSwellPeriodHigh() ) { - stnSortDirection = SWT.DOWN; - } else { - stnSortDirection = SWT.UP; - } - } - } - } + protected abstract void setStnSortColumnAndDirection(); /** - * Create the station table. + * Creates the station table. * * @param stackComp * Stack composite. @@ -570,17 +511,13 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } /** - * Update the station table (Dec 16, 2009, zhao) + * Updates and sorts the station table * * @param nominalTime - * - * @param zone */ public void updateStationTable(Date nominalTime) { - /** - * before update stnTblData, set station sort column and direction to - * their current values - */ + // before update stnTblData, set station sort column and direction to + // their current values setStnSortColumnAndDirection(); stnTblData = obData.getStationTableData(nominalTime, selectedZone); stnTblData.setSortColumnAndDirection(stnSortColumn, stnSortDirection); @@ -592,11 +529,11 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } /** - * Display the table attributes dialog. + * Displays the table attributes dialog. */ void displayAttributesDialog() { if (attrDlg == null) { - attrDlg = new TableAttribDlg(shell, appName, + attrDlg = new TableAttribDlg(getShell(), appName, zoneTable.getVisibleColumns()); boolean[] visCols = attrDlg.open(); attrDlg = null; @@ -610,50 +547,50 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, /** * Station table action to display the station table. */ + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.IStationTableAction#stationTableAction + * () + */ @Override public void stationTableAction() { - updateZoneTable(nominalTime); - ((GridData) zoneTblComp.getLayoutData()).exclude = false; zoneTblComp.setVisible(true); - ((GridData) stationTblComp.getLayoutData()).exclude = true; stationTblComp.setVisible(false); - tableStackComp.layout(); - - // tableStack.topControl = zoneTblComp; - // tableStackComp.layout(); - - shell.setText(appName.name() + " Threat Level Zone/County Table"); - + getShell().setText(appName.name() + " Threat Level Zone/County Table"); // re-set selectedZone to empty string selectedZone = ""; - updateNominalTimeLabel(nominalTime); } /** * Zone table action to display the zone table. + */ + /* + * (non-Javadoc) * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.IZoneTableAction#zoneTableAction + * (int) */ @Override public void zoneTableAction(int rowNum) { - // set selectedZone to the selected zone selectedZone = zoneTblData.getTableRows().get(rowNum) .getTableCellData(0).getCellText(); selectedZoneHoverText = zoneTblData.getTableRows().get(rowNum) .getTableCellData(0).getHoverText(); - // Zoom and centered bundle to Zone Scale(selectedZone) try { zoomToZone(selectedZone); } catch (Exception e) { e.printStackTrace(); } - updateStationTable(nominalTime); ((GridData) zoneTblComp.getLayoutData()).exclude = true; @@ -664,14 +601,22 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, tableStackComp.layout(); - shell.setText(appName.name() + " Threat Level STATION Table"); + getShell().setText(appName.name() + " Threat Level STATION Table"); updateNominalTimeLabel(nominalTime); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.IStationTableAction#launchTrendPlot + * (int, int) + */ public void launchTrendPlot(int rowIndex, int colIndex) { - // get variable name (linked to the column index of the station table) - CommonTableConfig config = CommonTableConfig.getInstance(); + + setRowIndex(rowIndex); + setColIndex(colIndex); String colKey = config.getTableColumnKeys(appName)[colIndex]; GraphType graphType = config.getTableColumnAttr(colKey).getGraphType(); if (graphType == GraphType.None) { @@ -680,111 +625,90 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, // get station ID (linked to rowIndex of the station table) String station = stnTblData.getTableRows().get(rowIndex) .getTableCellData(0).getCellText(); + // get variable names (linked to the column index of the station table) + initiateProdArray(); + dlgTitle = getTrendPlotName(prodArray) + " Trend Plot for " + station + + "#" + dataSrc; if (graphType == GraphType.Trend) { - prodArray = new ArrayList(); - // choose correct column names - if (appName.equals(AppName.SNOW)) { - varName = config.getSnowZoneStnTableColVarNames()[colIndex]; - // Fill product array - for (DisplayVarName name : DisplayVarName.values()) { - if (colIndex == 1 && name.toString().startsWith("BLIZ_")) { - prodArray.add(name.toString()); - } else if (colIndex == 2 - && name.toString().startsWith("FRZ_")) { - prodArray.add(name.toString()); - } else if (colIndex == 3 - && name.toString().startsWith("HSW_")) { - prodArray.add(name.toString()); - } else if (name.toString().startsWith("VAR_") - && name.toString().equals("VAR_" + varName.name())) { - prodArray.add(name.toString()); + if (mustCreate(tpd) || !openedDlgs.containsKey(dlgTitle)) { + tpd = new TrendPlotDlg(getShell(), selectedZone, station, + prodArray, dataSrc, dlgTitle); + tpd.setCloseCallback(new ICloseCallback() { + @Override + public void dialogClosed(Object returnValue) { + openedDlgs.remove(returnValue); } - } - } - if (appName.equals(AppName.SAFESEAS)) { - varName = config.getSafeseasZoneStnTableColVarNames()[colIndex]; - // Fill product arrays - for (DisplayVarName name : DisplayVarName.values()) { - if (colIndex == 1 && name.toString().startsWith("SCA_")) { - prodArray.add(name.toString()); - } else if (colIndex == 2 - && name.toString().startsWith("GALE_")) { - prodArray.add(name.toString()); - } else if (colIndex == 3 - && name.toString().startsWith("STORM_")) { - prodArray.add(name.toString()); - } else if (colIndex == 4 - && name.toString().startsWith("HURRICANE_")) { - prodArray.add(name.toString()); - } else if (name.toString().startsWith("VAR_") - && name.toString().equals("VAR_" + varName.name())) { - prodArray.add(name.toString()); - } - } - } - if (appName.equals(AppName.FOG)) { - varName = config.getFogZoneStnTableColVarNames()[colIndex]; - for (DisplayVarName name : DisplayVarName.values()) { - if (name.toString().startsWith("VAR_") - && name.toString().equals("VAR_" + varName.name())) { - prodArray.add(name.toString()); - } - } - } - if (varName == ObConst.VarName.UNDEFINED_VARIABLE) { - TrendPlotDlg tpd = new TrendPlotDlg(shell, selectedZone, - station, prodArray, "METAR"); + }); + openedDlgs.put(dlgTitle, tpd); tpd.setData(obData); tpd.open(); } else { - // Handle trend plot for variables of "float" type - TrendPlotDlg tpdNP = new TrendPlotDlg(shell, selectedZone, - station, prodArray, "METAR"); - tpdNP.setData(obData); - tpdNP.open(); + openedDlgs.get(dlgTitle).bringToTop(); } } if (graphType == GraphType.HodoWindDir) { - - if (appName.equals(AppName.SAFESEAS)) { - varName = config.getSafeseasZoneStnTableColVarNames()[colIndex]; - } else { - varName = ObConst.VarName.WIND_DIR; - } // get data for a hodograph trend plot ObTrendDataSet dataset = obData.getTrendDataSet(selectedZone, station, varName, ObConst.ProductName.UNDEFINED_PRODUCT); if (dataset != null && !dataset.isEmpty()) { - float[] thresholds = dataset.getDualValuedThresholds(); - HodographDlg hodographDlg = new HodographDlg(shell, - varName.name(), station, "METAR"); - - hodographDlg.setCurrentTime(ObUtil.getTimeNow()); //Calendar.getInstance()); - if (thresholds[0] == Float.NaN || thresholds[1] == Float.NaN - || thresholds[2] == Float.NaN - || thresholds[3] == Float.NaN) { - hodographDlg.setGreenThreshold(0, 0); + if (mustCreate(hodographDlg) + || !openedDlgs.containsKey(dlgTitle)) { + hodographDlg = new HodographDlg(getShell(), station, + dataSrc, dlgTitle); + hodographDlg.setCloseCallback(new ICloseCallback() { + @Override + public void dialogClosed(Object returnValue) { + openedDlgs.remove(returnValue); + } + }); + openedDlgs.put(dlgTitle, hodographDlg); + hodographDlg.setCurrentTime(ObUtil.getTimeNow()); + if (thresholds[0] == Float.NaN + || thresholds[1] == Float.NaN + || thresholds[2] == Float.NaN + || thresholds[3] == Float.NaN) { + hodographDlg.setGreenThreshold(0, 0); + } else { + hodographDlg.setGreenThreshold(0, 360); + } + hodographDlg.setYellowThreshold(thresholds[2], + thresholds[3]); + hodographDlg.setRedThreshold(thresholds[0], thresholds[1]); + hodographDlg.setHodoGraphData(dataset.getDataSet()); + hodographDlg.open(); } else { - hodographDlg.setGreenThreshold(0, 360); + openedDlgs.get(dlgTitle).bringToTop(); } - hodographDlg.setYellowThreshold(thresholds[2], thresholds[3]); - hodographDlg.setRedThreshold(thresholds[0], thresholds[1]); - - hodographDlg.setHodoGraphData(dataset.getDataSet()); - hodographDlg.open(); } else { prodArray = new ArrayList(); prodArray.add("VAR_" + varName.name()); - TrendPlotDlg tpdHodo = new TrendPlotDlg(shell, selectedZone, - station, prodArray, "METAR"); - tpdHodo.setData(obData); - tpdHodo.open(); + if (mustCreate(tpdHodo) || !openedDlgs.containsKey(dlgTitle)) { + tpdHodo = new TrendPlotDlg(getShell(), selectedZone, + station, prodArray, dataSrc, dlgTitle); + tpdHodo.setCloseCallback(new ICloseCallback() { + @Override + public void dialogClosed(Object returnValue) { + openedDlgs.remove(returnValue); + } + }); + openedDlgs.put(dlgTitle, tpdHodo); + tpdHodo.setData(obData); + tpdHodo.open(); + } else { + openedDlgs.get(dlgTitle).bringToTop(); + } } } } + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.ui.dialogs.IStationTableAction# + * launchObHistoryTable(int) + */ public void launchObHistoryTable(int rowIndex) { String station = stnTblData.getTableRows().get(rowIndex) .getTableCellData(0).getCellText(); @@ -812,11 +736,14 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, if (appName == AppName.SNOW && histType == ObsHistType.Maritime) { return; } - - ObsHistTableDlg obsHstTblDlg = new ObsHistTableDlg(shell, - obData.getHistTableData(selectedZone, station, histType), - station, lat, lon, obData.getAppName(), histType); - obsHstTblDlg.open(); + if (mustCreate(obsHstTblDlg)) { + obsHstTblDlg = new ObsHistTableDlg(getShell(), + obData.getHistTableData(selectedZone, station, histType), + station, lat, lon, obData.getAppName(), histType); + obsHstTblDlg.open(); + } else { + obsHstTblDlg.bringToTop(); + } } protected abstract MonitorConfigurationManager getConfigMgr(); @@ -826,19 +753,23 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, */ protected abstract void configThreshAction(); + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.monitor.listeners.IMonitorControlListener# + * getMonitorControlListeners() + */ @Override - public ArrayList getMonitorControlListeners() { + public List getMonitorControlListeners() { return controlListeners; } - public void shellDisposeDialog() { - shell.dispose(); - } - - public boolean isDisposed() { - return zoneTable.isDisposed(); - } - + /** + * Zooms map to a zone level + * + * @param zone + * @throws Exception + */ private void zoomToZone(String zone) throws Exception { double[] zoneCenter = MonitorAreaUtils.getZoneCenter(zone); if (zoneCenter != null) { @@ -846,6 +777,13 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.monitor.ui.dialogs.IStationTableAction#zoomToStation + * (int) + */ public void zoomToStation(int rowIndex) { String selectedStation = stnTblData.getTableRows().get(rowIndex) .getTableCellData(0).getCellText(); @@ -858,6 +796,12 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } } + /** + * Re-centers and zooms map + * + * @param center + * @param zoom + */ private void zoomAndRecenter(double[] center, float zoom) { IDisplayPaneContainer container = EditorUtil.getActiveVizContainer(); if (container != null) { @@ -880,16 +824,92 @@ public abstract class ZoneTableDlg extends Dialog implements IMonitorListener, } } - public boolean isLinkedToFrame() { - return linkedToFrame; - } + /** + * @return linkedToFrame + */ + public boolean isLinkedToFrame() { + return linkedToFrame; + } - public void setLinkedToFrame(boolean linkedToFrame) { - this.linkedToFrame = linkedToFrame; - } + /** + * Sets linkedToFrame + * + * @param linkedToFrame + */ + public void setLinkedToFrame(boolean linkedToFrame) { + this.linkedToFrame = linkedToFrame; + } + /** + * Handls checkbox "Link to frame" + */ protected void handleLinkToFrame() { linkedToFrame = linkToFrameChk.getSelection(); } + /* + * (non-Javadoc) + * + * @see com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#disposed() + */ + @Override + protected void disposed() { + setReturnValue(true); + } + + /** + * Initiates array of products to plot + * + * @return + */ + protected abstract void initiateProdArray(); + + public int getRowIndex() { + return rowIndex; + } + + public void setRowIndex(int rowIndex) { + this.rowIndex = rowIndex; + } + + public int getColIndex() { + return colIndex; + } + + public void setColIndex(int colIndex) { + this.colIndex = colIndex; + } + + /** + * Gets title of plot. + * + * @param prod + * @return + */ + private String getTrendPlotName(List prod) { + String varName = null; + String name = (String) prod.get(0); + int stInd = name.indexOf("_"); + if (prod.size() > 1) { + varName = name.substring(0, stInd); + if (varName.equals("SCA")) { + varName = "Small Craft Advisory"; + } else if (varName.equals("GALE")) { + varName = "Gale Warning"; + } else if (varName.equals("STORM")) { + varName = "Storm Warning"; + } else if (varName.equals("HURRICANE")) { + varName = "Hurricane Force Wind Warning"; + } else if (varName.equals("BLIZ")) { + varName = "Blizzard Warning"; + } else if (varName.equals("FRZ")) { + varName = "Freezing Precipitation"; + } else if (varName.equals("HSW")) { + varName = "Heavy Snow Warning"; + } + } else { + varName = name.substring(stInd + 1); + } + return varName; + } } diff --git a/cave/com.raytheon.uf.viz.npp.crimss/plugin.xml b/cave/com.raytheon.uf.viz.npp.crimss/plugin.xml index 18716f966b..4c70c64fb0 100644 --- a/cave/com.raytheon.uf.viz.npp.crimss/plugin.xml +++ b/cave/com.raytheon.uf.viz.npp.crimss/plugin.xml @@ -13,7 +13,7 @@ diff --git a/cave/com.raytheon.uf.viz.npp.crimss/src/com/raytheon/uf/viz/npp/crimss/CrimssDataDefinition.java b/cave/com.raytheon.uf.viz.npp.crimss/src/com/raytheon/uf/viz/npp/crimss/CrimssDataDefinition.java index a83c27c8f4..59d1f33848 100644 --- a/cave/com.raytheon.uf.viz.npp.crimss/src/com/raytheon/uf/viz/npp/crimss/CrimssDataDefinition.java +++ b/cave/com.raytheon.uf.viz.npp.crimss/src/com/raytheon/uf/viz/npp/crimss/CrimssDataDefinition.java @@ -83,7 +83,7 @@ public class CrimssDataDefinition public CrimssDataDefinition() { productName = "crimss"; displayName = "CrIMSS"; - order = new String[] { "pluginName", POINT }; + order = new String[] { POINT }; order = getOrder(); loadProperties = new LoadProperties(); loadProperties.setResourceType(getResourceType()); diff --git a/cave/com.raytheon.uf.viz.npp.viirs/plugin.xml b/cave/com.raytheon.uf.viz.npp.viirs/plugin.xml index 75b159da9b..6fcbb48986 100644 --- a/cave/com.raytheon.uf.viz.npp.viirs/plugin.xml +++ b/cave/com.raytheon.uf.viz.npp.viirs/plugin.xml @@ -35,4 +35,12 @@ name="com.raytheon.uf.viz.npp.viirs.viirsProductBrowserDefinition"> + + +
diff --git a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/VIIRSProductBrowserDefinition.java b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/VIIRSProductBrowserDefinition.java index f1604acebf..a26d4ebbe8 100644 --- a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/VIIRSProductBrowserDefinition.java +++ b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/VIIRSProductBrowserDefinition.java @@ -46,8 +46,7 @@ public class VIIRSProductBrowserDefinition extends public VIIRSProductBrowserDefinition() { productName = "viirs"; displayName = "VIIRS"; - order = new String[] { "pluginName", "region", "channelType", - "wavelength" }; + order = new String[] { "region", "channelType", "wavelength" }; order = getOrder(); loadProperties = new LoadProperties(); } diff --git a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataCubeAdapter.java b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataCubeAdapter.java index 8d4197c7b6..fa906e4f67 100644 --- a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataCubeAdapter.java +++ b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataCubeAdapter.java @@ -40,8 +40,9 @@ import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractDataCubeAdapter; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode.Dependency; +import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode.Dependency; import com.raytheon.uf.viz.npp.viirs.Activator; import com.raytheon.uf.viz.npp.viirs.data.VIIRSRequestableData.VIIRSRequest; @@ -173,7 +174,7 @@ public class VIIRSDataCubeAdapter extends AbstractDataCubeAdapter { * evaluateRequestConstraints(java.util.Map) */ @Override - protected List evaluateRequestConstraints( + protected List evaluateRequestConstraints( Map constraints) { return inventory.evaluateRequestConstraints(constraints); } @@ -236,9 +237,9 @@ public class VIIRSDataCubeAdapter extends AbstractDataCubeAdapter { @Override public List> getBaseUpdateConstraints( Map constraints) { - List nodes = evaluateRequestConstraints(constraints); + List nodes = evaluateRequestConstraints(constraints); List> baseConstraints = new ArrayList>(); - for (AbstractRequestableLevelNode node : nodes) { + for (AbstractRequestableNode node : nodes) { getBaseUpdateConstraints(baseConstraints, node); } return baseConstraints; @@ -246,13 +247,22 @@ public class VIIRSDataCubeAdapter extends AbstractDataCubeAdapter { private void getBaseUpdateConstraints( List> baseConstraints, - AbstractRequestableLevelNode node) { - if (node.hasRequestConstraints()) { - baseConstraints.add(node.getRequestConstraintMap()); - } else { - for (Dependency d : node.getDependencies()) { + AbstractRequestableNode node) { + + if (node instanceof VIIRSRequestableLevelNode) { + VIIRSRequestableLevelNode viirsNode = (VIIRSRequestableLevelNode) node; + baseConstraints.add(viirsNode.getRequestConstraintMap()); + } else if (node instanceof AbstractDerivedDataNode) { + AbstractDerivedDataNode derivedNode = (AbstractDerivedDataNode) node; + for (Dependency d : derivedNode.getDependencies()) { getBaseUpdateConstraints(baseConstraints, d.node); } + } else if (!node.isConstant()) { + // If everything is working correctly than this is dead code, but it is here just in case I missed something. + Activator.statusHandler.handle(Priority.WARN, this.getClass() + .getSimpleName() + + " cannot determine base constraints for " + + node.getClass().getSimpleName()); } } diff --git a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataInventory.java b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataInventory.java index 7baec47d3e..9784f2088a 100644 --- a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataInventory.java +++ b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSDataInventory.java @@ -51,8 +51,8 @@ import com.raytheon.uf.viz.derivparam.inv.AbstractInventory; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamField; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; -import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; import com.raytheon.viz.alerts.IAlertObserver; import com.raytheon.viz.alerts.observers.ProductAlertObserver; @@ -243,7 +243,7 @@ public class VIIRSDataInventory extends AbstractInventory implements } } - public List evaluateRequestConstraints( + public List evaluateRequestConstraints( Map constraints) { List sources = new ArrayList(); List parameters = extractParameters(constraints); @@ -274,7 +274,7 @@ public class VIIRSDataInventory extends AbstractInventory implements return walkTree(null, sources, parameters, levels, true, true, null); } catch (InterruptedException e) { } - return new ArrayList(0); + return new ArrayList(0); } /** @@ -407,7 +407,7 @@ public class VIIRSDataInventory extends AbstractInventory implements * com.raytheon.uf.common.dataplugin.level.Level) */ @Override - protected AbstractDerivedLevelNode getImportNode( + protected AbstractDerivedDataNode getImportNode( AbstractRequestableData nodeToImport, SourceNode destSourceNode, DerivParamDesc desc, DerivParamMethod method, Level level) { return null; @@ -425,8 +425,8 @@ public class VIIRSDataInventory extends AbstractInventory implements * com.raytheon.uf.common.dataplugin.level.Level) */ @Override - protected AbstractDerivedLevelNode getImportNode( - AbstractRequestableLevelNode nodeToImport, + protected AbstractDerivedDataNode getImportNode( + AbstractRequestableNode nodeToImport, String nodeToImportSourceName, SourceNode destSourceNode, DerivParamDesc desc, DerivParamMethod method, Level level) { return null; diff --git a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSRequestableLevelNode.java b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSRequestableLevelNode.java index fbcbc93ed7..72a23784ef 100644 --- a/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSRequestableLevelNode.java +++ b/cave/com.raytheon.uf.viz.npp.viirs/src/com/raytheon/uf/viz/npp/viirs/data/VIIRSRequestableLevelNode.java @@ -19,8 +19,6 @@ **/ package com.raytheon.uf.viz.npp.viirs.data; -import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -30,14 +28,12 @@ import java.util.Set; import com.raytheon.uf.common.dataplugin.npp.viirs.VIIRSDataRecord; import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.requests.ThriftClient; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode; /** * VIIRS Requestable level node @@ -56,7 +52,7 @@ import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; * @version 1.0 */ -public class VIIRSRequestableLevelNode extends AbstractRequestableLevelNode { +public class VIIRSRequestableLevelNode extends AbstractBaseDataNode { private Map requestConstraints; @@ -68,152 +64,6 @@ public class VIIRSRequestableLevelNode extends AbstractRequestableLevelNode { this.requestConstraints = requestConstraints; } - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * processDataQueryResults - * (com.raytheon.uf.common.dataquery.responses.DbQueryResponse) - */ - @Override - protected List processDataQueryResults( - DbQueryResponse queryResponse) throws VizException { - List> results = queryResponse.getResults(); - List data = new ArrayList( - results.size()); - for (Map result : results) { - data.add(new VIIRSRequestableData((VIIRSDataRecord) result - .get(null), getLevel())); - } - return data; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getDependencies() - */ - @Override - public List getDependencies() { - return Collections.emptyList(); - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * isTimeAgnostic() - */ - @Override - public boolean isTimeAgnostic() { - return false; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * hasRequestConstraints() - */ - @Override - public boolean hasRequestConstraints() { - return true; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getRequestConstraintMap() - */ - @Override - public Map getRequestConstraintMap() { - return requestConstraints; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * timeQueryInternal(boolean, java.util.Map, java.util.Map) - */ - @Override - protected Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - TimeQueryRequest timeQuery = getTimeQuery(originalRequest, latestOnly, - cache, latestOnlyCache); - @SuppressWarnings("unchecked") - List dataTimes = (List) ThriftClient - .sendRequest(timeQuery); - return new HashSet(dataTimes); - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getTimeQueryInternal(boolean, java.util.Map) - */ - @Override - protected TimeQueryRequest getTimeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache) - throws VizException { - Map constraints = new HashMap( - originalRequest.getQueryTerms()); - constraints.putAll(requestConstraints); - TimeQueryRequest tr = new TimeQueryRequest(); - tr.setQueryTerms(constraints); - tr.setMaxQuery(latestOnly); - tr.setPluginName("viirs"); - return tr; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getDataInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int, - * java.util.Map) - */ - @Override - protected List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - DbQueryRequest dataQuery = getDataQuery(property, timeOut, cache); - return processDataQueryResults((DbQueryResponse) ThriftClient - .sendRequest(dataQuery)); - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getDataQueryInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int, - * java.util.Map) - */ - @Override - protected DbQueryRequest getDataQueryInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - Map constraints = new HashMap( - property.getEntryQueryParameters(true)); - constraints.putAll(requestConstraints); - constraints.put("pluginName", new RequestConstraint("viirs")); - DbQueryRequest request = new DbQueryRequest(); - request.setConstraints(constraints); - request.setEntityClass(VIIRSDataRecord.class); - return request; - } - /* * (non-Javadoc) * @@ -252,4 +102,94 @@ public class VIIRSRequestableLevelNode extends AbstractRequestableLevelNode { return true; } + public Map getRequestConstraintMap() { + return requestConstraints; + } + + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode# + * getAvailabilityRequest() + */ + @Override + public DbQueryRequest getAvailabilityRequest( + Map originalConstraints) { + Map constraints = new HashMap( + originalConstraints); + constraints.putAll(requestConstraints); + constraints.put("pluginName", new RequestConstraint("viirs")); + DbQueryRequest request = new DbQueryRequest(); + request.setEntityClass(VIIRSDataRecord.class.getName()); + request.addRequestField("dataTime"); + request.setDistinct(true); + request.setConstraints(constraints); + return request; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode#getDataRequest + * (java.util.Map, java.util.Set) + */ + @Override + public DbQueryRequest getDataRequest( + Map originalConstraints, + Set availability) { + Map constraints = new HashMap( + originalConstraints); + constraints.putAll(requestConstraints); + constraints.put("pluginName", new RequestConstraint("viirs")); + DbQueryRequest request = new DbQueryRequest(); + request.setConstraints(constraints); + request.setEntityClass(VIIRSDataRecord.class); + return request; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode#getAvailability + * (java.lang.Object) + */ + @Override + public Set getAvailability( + Map originalConstraints, Object response) + throws VizException { + Set result = new HashSet(); + DbQueryResponse dbresponse = (DbQueryResponse) response; + for (Map map : dbresponse.getResults()) { + DataTime time = (DataTime) map.get("dataTime"); + + result.add(new TimeAndSpace(time)); + } + return result; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode#getData(java + * .util.Map, java.util.Set, java.lang.Object) + */ + @Override + public Set getData( + Map orignalConstraints, + Set availability, Object response) + throws VizException { + DbQueryResponse queryResponse = (DbQueryResponse) response; + List> results = queryResponse.getResults(); + Set data = new HashSet( + results.size()); + for (Map result : results) { + data.add(new VIIRSRequestableData((VIIRSDataRecord) result + .get(null), getLevel())); + } + return data; + } + } diff --git a/cave/com.raytheon.uf.viz.objectiveanalysis/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.objectiveanalysis/META-INF/MANIFEST.MF index 5f8f57f3fd..3cf4e5f9b3 100644 --- a/cave/com.raytheon.uf.viz.objectiveanalysis/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.objectiveanalysis/META-INF/MANIFEST.MF @@ -28,9 +28,9 @@ Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.viz.objectiveanalysis.rsc Import-Package: com.raytheon.uf.common.comm, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.dataplugin.radar, + com.raytheon.uf.common.gridcoverage, com.raytheon.uf.viz.derivparam.library, com.raytheon.uf.viz.derivparam.tree, com.raytheon.viz.ui, diff --git a/cave/com.raytheon.uf.viz.plugin.nwsauth/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.plugin.nwsauth/META-INF/MANIFEST.MF index 556964ae8b..4eea9f3427 100644 --- a/cave/com.raytheon.uf.viz.plugin.nwsauth/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.plugin.nwsauth/META-INF/MANIFEST.MF @@ -11,3 +11,4 @@ Require-Bundle: org.eclipse.core.runtime, com.raytheon.uf.viz.core Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy +Export-Package: com.raytheon.uf.viz.plugin.nwsauth diff --git a/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/FileManager.java b/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/FileManager.java new file mode 100644 index 0000000000..7934ecd493 --- /dev/null +++ b/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/FileManager.java @@ -0,0 +1,382 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.plugin.nwsauth; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.Unmarshaller; + +import com.raytheon.uf.common.auth.user.IPermission; +import com.raytheon.uf.common.auth.user.IRole; +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException; +import com.raytheon.uf.common.plugin.nwsauth.NwsPermission; +import com.raytheon.uf.common.plugin.nwsauth.NwsRole; +import com.raytheon.uf.common.plugin.nwsauth.xml.NwsRoleData; +import com.raytheon.uf.common.plugin.nwsauth.xml.PermissionXML; +import com.raytheon.uf.common.plugin.nwsauth.xml.RoleXML; +import com.raytheon.uf.common.plugin.nwsauth.xml.UserXML; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; + +/** + * Uses localization data to determine role/permissions. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 30, 2012            mpduff     Initial creation
+ * Nov 06, 2012 1302       djohnson   Move to nwsauth plugin.
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class FileManager { + /** Status handler */ + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(FileManager.class); + + private static final FileManager instance = new FileManager(); + + private final String ROLE_DIR = "roles"; + + /** JAXB context */ + private JAXBContext jax; + + /** Marshaller object */ + private Marshaller marshaller; + + /** Unmarshaller object */ + private Unmarshaller unmarshaller; + + private final Map roleDataMap = new HashMap(); + + /** + * Application name -> LocalizationFile map. + */ + private final Map roleFileMap = new HashMap(); + + private FileManager() { + createContext(); + readXML(); + } + + /** + * Get an instance. + * + * @return an instance + */ + public static FileManager getInstance() { + return instance; + } + + private void createContext() { + @SuppressWarnings("rawtypes") + Class[] classes = new Class[] { NwsRoleData.class, PermissionXML.class, + RoleXML.class, UserXML.class }; + + try { + jax = JAXBContext.newInstance(classes); + this.unmarshaller = jax.createUnmarshaller(); + this.marshaller = jax.createMarshaller(); + + // format the output xml file + this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + + } catch (JAXBException e) { + e.printStackTrace(); + } + } + + /** + * Get the NwsRoleData object. + * + * @param application + * The application + * + * @return The NwsRoleData object + */ + public NwsRoleData getRoleData(String application) { + return this.roleDataMap.get(application); + } + + /** + * Get a list of user ids for the application. + * + * @param application + * the application + * @return String[] of user ids + */ + public String[] getUserIdList(String application) { + ArrayList userNameList = new ArrayList(); + for (UserXML ux : this.roleDataMap.get(application).getUserList()) { + userNameList.add(ux.getUserId()); + } + + return userNameList.toArray(new String[userNameList.size()]); + } + + /** + * Get an array of user roles. + * + * @param userId + * The user id + * @param application + * The application + * @return the array of roles + */ + public String[] getUserRoles(String userId, String application) { + ArrayList userRoles = new ArrayList(); + + for (UserXML userXml : this.roleDataMap.get(application).getUserList()) { + if (userXml.getUserId().equals(userId)) { + for (String role : userXml.getRoleList()) { + userRoles.add(role); + } + break; + } + } + + return userRoles.toArray(new String[userRoles.size()]); + } + + /** + * Get a list of user permissions. + * + * @param userId + * The user id + * @param application + * The application + * @return The array of user permissions + */ + public String[] getUserPermissions(String userId, String application) { + ArrayList userPermissions = new ArrayList(); + + for (UserXML userXml : this.roleDataMap.get(application).getUserList()) { + if (userXml.getUserId().equals(userId)) { + for (String permission : userXml.getPermissionList()) { + userPermissions.add(permission); + } + break; + } + } + + return userPermissions.toArray(new String[userPermissions.size()]); + } + + public String[] getRolePermissions(String roleId, String application) { + ArrayList rolePerms = new ArrayList(); + + for (RoleXML roleXml : roleDataMap.get(application).getRoleList()) { + if (roleXml.getRoleId().equals(roleId)) { + for (String perm : roleXml.getPermissionList()) { + rolePerms.add(perm); + } + } + } + + return rolePerms.toArray(new String[rolePerms.size()]); + } + + /** + * @param application + * @return + */ + public List getPermissions(String application) { + List permissions = new ArrayList(); + NwsRoleData roleData = roleDataMap.get(application); + + for (PermissionXML xml : roleData.getPermissionList()) { + String id = xml.getId(); + String description = xml.getDescription(); + permissions.add(new NwsPermission(id, description)); + } + return permissions; + } + + /** + * @return + */ + public List getRoles(String application) { + List roles = new ArrayList(); + for (NwsRoleData roleData : roleDataMap.values()) { + for (RoleXML xml : roleData.getRoleList()) { + String id = xml.getRoleId(); + String description = xml.getRoleDescription(); + roles.add(new NwsRole(id, + getPermissionsForRole(id, application), description)); + } + } + return roles; + } + + private List getPermissionsForRole(String roleId, + String application) { + List rolePerms = new ArrayList(); + List permissionIds = Arrays.asList(getRolePermissions(roleId, + application)); + + for (PermissionXML roleXml : roleDataMap.get(application) + .getPermissionList()) { + if (permissionIds.contains(roleXml.getId())) { + rolePerms.add(new NwsPermission(roleXml.getId(), roleXml + .getDescription())); + } + } + + return rolePerms; + } + + /** + * Return a list of applications that have roles/permissions defined. + * + * @return String[] of application names + */ + public String[] getApplications() { + return roleDataMap.keySet().toArray(new String[roleDataMap.size()]); + } + + public void addUser(String user, String application) { + if (user != null && user.length() > 0) { + UserXML userXml = new UserXML(); + userXml.setUserId(user); + this.roleDataMap.get(application).getUserList().add(userXml); + } + } + + public void addRole(String role, String description, String application) { + if (role != null && description != null && role.length() > 0 + && description.length() > 0) { + RoleXML roleXml = new RoleXML(); + roleXml.setRoleDescription(description); + roleXml.setRoleId(role); + this.roleDataMap.get(application).getRoleList().add(roleXml); + } + } + + public void deleteUser(String user, String application) { + if (user != null && user.length() > 0) { + int idx = -1; + for (UserXML u : roleDataMap.get(application).getUserList()) { + idx++; + if (u.getUserId().equalsIgnoreCase(user)) { + roleDataMap.get(application).getUserList().remove(idx); + break; + } + } + } + } + + public void deleteRole(String role, String application) { + if (role != null && role.length() > 0) { + int idx = -1; + for (RoleXML r : roleDataMap.get(application).getRoleList()) { + idx++; + if (r.getRoleId().equalsIgnoreCase(role)) { + roleDataMap.get(application).getRoleList().remove(idx); + break; + } + } + } + } + + /** + * Save the NwsRoleData object. + * + * @param application + */ + public void save(String application) { + NwsRoleData roleData = roleDataMap.get(application); + LocalizationFile lf = roleFileMap.get(application); + + IPathManager pm = PathManagerFactory.getPathManager(); + LocalizationContext context = pm.getContext( + LocalizationType.COMMON_STATIC, LocalizationLevel.SITE); + LocalizationFile locFile = pm + .getLocalizationFile(context, lf.getName()); + ; + + try { + marshaller.marshal(roleData, locFile.getFile()); + locFile.save(); + } catch (JAXBException e) { + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); + } catch (LocalizationOpFailedException e) { + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); + } + + } + + private void readXML() { + try { + IPathManager pm = PathManagerFactory.getPathManager(); + LocalizationContext[] contexts = new LocalizationContext[2]; + contexts[0] = pm.getContext(LocalizationType.COMMON_STATIC, + LocalizationLevel.BASE); + contexts[1] = pm.getContext(LocalizationType.COMMON_STATIC, + LocalizationLevel.SITE); + LocalizationFile[] roleFiles = pm.listFiles(contexts, ROLE_DIR, + null, false, true); + + for (LocalizationFile lf : roleFiles) { + File f = lf.getFile(true); + if (f != null && f.exists()) { + System.out.println(f.getAbsolutePath()); + NwsRoleData roleData = (NwsRoleData) unmarshaller + .unmarshal(f); + this.roleDataMap.put(roleData.getApplication(), roleData); + this.roleFileMap.put(roleData.getApplication(), lf); + } + } + } catch (JAXBException e1) { + statusHandler + .handle(Priority.PROBLEM, e1.getLocalizedMessage(), e1); + } catch (Exception e) { + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); + } + } + + /** + * Reload theXML files from disk. + */ + public void reloadXML() { + readXML(); + } +} diff --git a/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/NwsUserManager.java b/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/NwsUserManager.java index 044efd46fd..b3d527f677 100644 --- a/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/NwsUserManager.java +++ b/cave/com.raytheon.uf.viz.plugin.nwsauth/src/com/raytheon/uf/viz/plugin/nwsauth/NwsUserManager.java @@ -19,7 +19,11 @@ **/ package com.raytheon.uf.viz.plugin.nwsauth; +import java.util.List; + import com.raytheon.uf.common.auth.user.IAuthenticationData; +import com.raytheon.uf.common.auth.user.IPermission; +import com.raytheon.uf.common.auth.user.IRole; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.plugin.nwsauth.user.User; import com.raytheon.uf.viz.core.auth.IUserManager; @@ -43,7 +47,7 @@ import com.raytheon.uf.viz.core.requests.INotAuthHandler; public class NwsUserManager implements IUserManager { - private NwsNotAuthHandler notAuthHandler = new NwsNotAuthHandler(); + private final NwsNotAuthHandler notAuthHandler = new NwsNotAuthHandler(); /* * (non-Javadoc) @@ -78,4 +82,21 @@ public class NwsUserManager implements IUserManager { public void updateUserObject(IUser user, IAuthenticationData authData) { } + /** + * {@inheritDoc} + */ + @Override + public List getPermissions(String application) { + // TODO: Should this pass through to EDEX to get this stuff? + return FileManager.getInstance().getPermissions(application); + } + + /** + * {@inheritDoc} + */ + @Override + public List getRoles(String application) { + // TODO: Should this pass through to EDEX to get this stuff? + return FileManager.getInstance().getRoles(application); + } } diff --git a/cave/com.raytheon.uf.viz.points/src/com/raytheon/uf/viz/points/PointsDataManager.java b/cave/com.raytheon.uf.viz.points/src/com/raytheon/uf/viz/points/PointsDataManager.java index e254caa7a1..db6d844c89 100644 --- a/cave/com.raytheon.uf.viz.points/src/com/raytheon/uf/viz/points/PointsDataManager.java +++ b/cave/com.raytheon.uf.viz.points/src/com/raytheon/uf/viz/points/PointsDataManager.java @@ -1756,10 +1756,15 @@ public class PointsDataManager implements ILocalizationFileObserver { */ private Point unmarshalPointFromXmlFile(LocalizationFile lFile) throws LocalizationException, IOException { - InputStream stream = lFile.openInputStream(); - Point point = JAXB.unmarshal(stream, Point.class); - stream.close(); - return point; + InputStream stream = null; + try { + stream = lFile.openInputStream(); + return JAXB.unmarshal(stream, Point.class); + } finally { + if (stream != null) { + stream.close(); + } + } } /** diff --git a/cave/com.raytheon.uf.viz.preciprate/src/com/raytheon/uf/viz/preciprate/PrecipRateDataDefinition.java b/cave/com.raytheon.uf.viz.preciprate/src/com/raytheon/uf/viz/preciprate/PrecipRateDataDefinition.java index bafc58d0bb..06ab5b1c29 100644 --- a/cave/com.raytheon.uf.viz.preciprate/src/com/raytheon/uf/viz/preciprate/PrecipRateDataDefinition.java +++ b/cave/com.raytheon.uf.viz.preciprate/src/com/raytheon/uf/viz/preciprate/PrecipRateDataDefinition.java @@ -51,7 +51,7 @@ public class PrecipRateDataDefinition extends public PrecipRateDataDefinition() { productName = "preciprate"; displayName = "Precipitation Rate"; - order = new String[] { "pluginName", "icao" }; + order = new String[] { "icao" }; order = getOrder(); loadProperties = new LoadProperties(); loadProperties.setResourceType(getResourceType()); diff --git a/cave/com.raytheon.uf.viz.product.alertviz/alertviz.product b/cave/com.raytheon.uf.viz.product.alertviz/alertviz.product index d86760b293..aeb66f6041 100644 --- a/cave/com.raytheon.uf.viz.product.alertviz/alertviz.product +++ b/cave/com.raytheon.uf.viz.product.alertviz/alertviz.product @@ -51,7 +51,7 @@ Developed on the Raytheon Visualization Environment (viz) - + diff --git a/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/AbstractRequestableProductBrowserDataDefinition.java b/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/AbstractRequestableProductBrowserDataDefinition.java index 2839125fb5..d89159bf80 100644 --- a/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/AbstractRequestableProductBrowserDataDefinition.java +++ b/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/AbstractRequestableProductBrowserDataDefinition.java @@ -79,6 +79,9 @@ public abstract class AbstractRequestableProductBrowserDataDefinition parameters = null; - if (order.length > 1) { + if (order.length >= 1) { try { DbQuery query = new DbQuery(productName); query.setMaxResults(1); @@ -135,10 +138,10 @@ public abstract class AbstractRequestableProductBrowserDataDefinition parameters = null; boolean product = false; - String param = order[selection.length]; + String param = order[selection.length - 1]; HashMap queryList = getProductParameters( selection, order); - product = (selection.length + 1) == order.length; + product = selection.length == order.length; String[] temp = queryData(param, queryList); if (temp != null) { @@ -154,6 +157,7 @@ public abstract class AbstractRequestableProductBrowserDataDefinition queryList = new HashMap(); RequestConstraint contstraint = new RequestConstraint(productName); - queryList.put(order[0], contstraint); - for (int i = 1; i < order.length; i++) { + queryList.put(PLUGIN_NAME, contstraint); + for (int i = 0; i < order.length; i++) { try { String[] items = CatalogQuery.performQuery(order[i], queryList); List labels = formatData(order[i], items); @@ -254,13 +258,29 @@ public abstract class AbstractRequestableProductBrowserDataDefinition getProductParameters( String[] selection, String[] order) { HashMap queryList = new HashMap(); - queryList.put(order[0], new RequestConstraint(productName)); - for (int i = 1; i < selection.length; i++) { - queryList.put(order[i], new RequestConstraint(selection[i])); + queryList.put(PLUGIN_NAME, new RequestConstraint(productName)); + + String[] usedSelection = realignSelection(selection); + for (int i = 0; i < usedSelection.length; i++) { + queryList.put(order[i], new RequestConstraint(usedSelection[i])); } return queryList; } + /** + * Reorder the selection so that it lines up with the order + * + * @param selection + * @return + */ + protected final String[] realignSelection(String[] selection) { + String[] usedSelection = new String[selection.length - 1]; + for (int i = 1; i < selection.length; i++) { + usedSelection[i - 1] = selection[i]; + } + return usedSelection; + } + public ResourceType getResourceType() { return ResourceType.PLAN_VIEW; } diff --git a/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/ProductBrowserView.java b/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/ProductBrowserView.java index 6fa668e966..e8e585102f 100644 --- a/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/ProductBrowserView.java +++ b/cave/com.raytheon.uf.viz.productbrowser/src/com/raytheon/uf/viz/productbrowser/ProductBrowserView.java @@ -24,6 +24,7 @@ import java.io.File; import java.util.ArrayList; import java.util.HashSet; import java.util.List; +import java.util.Map; import java.util.Set; import org.eclipse.core.runtime.CoreException; @@ -483,15 +484,15 @@ public class ProductBrowserView extends ViewPart { // if not a product, do not give opportunity to load things if ((Boolean) productTree.getTree().getSelection()[0] .getData("product")) { - if (prod.getDisplayTypes() != null - && !prod.getDisplayTypes().isEmpty()) { + Map> displayTypes = prod + .getDisplayTypes(); + if (displayTypes != null && displayTypes.isEmpty() == false) { MenuManager menuMgr = new MenuManager("Load As...", ProductBrowserUtils.getImageDescriptor("run.gif"), ""); - for (ResourceType type : prod.getDisplayTypes().keySet()) { - if (prod.getDisplayTypes().keySet().size() <= 1) { - for (DisplayType types : prod.getDisplayTypes() - .get(type)) { + for (ResourceType type : displayTypes.keySet()) { + if (displayTypes.keySet().size() <= 1) { + for (DisplayType types : displayTypes.get(type)) { menuMgr.add(getDisplayTypeAction(types)); } } @@ -500,9 +501,6 @@ public class ProductBrowserView extends ViewPart { } else { mgr.add(loadProductAction); } - if (prod instanceof AbstractRequestableProductBrowserDataDefinition) { - // mgr.add(bookmarkProductsAction); - } } mgr.add(productInfoAction); } @@ -576,7 +574,7 @@ public class ProductBrowserView extends ViewPart { ti.setData(((AbstractRequestableProductBrowserDataDefinition) prod).productName); ti.setData( "product", - ((AbstractRequestableProductBrowserDataDefinition) prod).order.length == 1 ? true + ((AbstractRequestableProductBrowserDataDefinition) prod).order.length == 0 ? true : false); } else { ti.setData(prod.displayName); diff --git a/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFProductBrowserDataDefinition.java b/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFProductBrowserDataDefinition.java index fb1eb87724..f269e78d67 100644 --- a/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFProductBrowserDataDefinition.java +++ b/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFProductBrowserDataDefinition.java @@ -56,7 +56,7 @@ public class QPFProductBrowserDataDefinition extends public QPFProductBrowserDataDefinition() { productName = "qpf"; displayName = "QPF"; - order = new String[] { "pluginName", "icao", "fieldName" }; + order = new String[] { "icao", "fieldName" }; order = getOrder(); loadProperties = new LoadProperties(); loadProperties.setResourceType(getResourceType()); @@ -76,7 +76,8 @@ public class QPFProductBrowserDataDefinition extends if ("fieldName".equals(param)) { for (int i = 0; i < parameters.length; i++) { labels.add(new ProductBrowserLabel(DATA_TYPE.valueOf( - parameters[i]).getFieldName(), parameters[i])); + parameters[i]).getFieldName() + + " (" + parameters[i] + ")", parameters[i])); } Collections.sort(labels); } else { @@ -95,7 +96,6 @@ public class QPFProductBrowserDataDefinition extends */ @Override public Map> getDisplayTypes() { - // TODO Auto-generated method stub Map> type = new HashMap>(); List types = new ArrayList(); types.add(DisplayType.CONTOUR); diff --git a/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFResource.java b/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFResource.java index 9b60d07690..a3e55c30ef 100644 --- a/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFResource.java +++ b/cave/com.raytheon.uf.viz.qpf/src/com/raytheon/uf/viz/qpf/QPFResource.java @@ -19,32 +19,29 @@ **/ package com.raytheon.uf.viz.qpf; +import java.nio.FloatBuffer; +import java.text.ParsePosition; import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; import javax.measure.unit.Unit; - -import org.geotools.coverage.grid.GeneralGridGeometry; -import org.geotools.coverage.grid.GridGeometry2D; +import javax.measure.unit.UnitFormat; import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.dataplugin.qpf.QPFRecord; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.viz.core.IGraphicsTarget; +import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.map.MapDescriptor; -import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData; -import com.raytheon.uf.viz.core.rsc.AbstractVizResource; -import com.raytheon.uf.viz.core.rsc.IResourceDataChanged; import com.raytheon.uf.viz.core.rsc.LoadProperties; +import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability; import com.raytheon.uf.viz.core.style.ParamLevelMatchCriteria; -import com.raytheon.uf.viz.core.style.StyleManager; -import com.raytheon.uf.viz.core.style.StyleRule; -import com.raytheon.viz.core.style.contour.ContourPreferences; -import com.raytheon.viz.grid.rsc.AbstractMapVectorResource; -import com.raytheon.viz.grid.rsc.GridLoadProperties; +import com.raytheon.viz.grid.rsc.general.AbstractGridResource; +import com.raytheon.viz.grid.rsc.general.GeneralGridData; /** * QPFVectorResource @@ -65,56 +62,54 @@ import com.raytheon.viz.grid.rsc.GridLoadProperties; * @version 1 */ -public class QPFResource extends AbstractMapVectorResource implements - IResourceDataChanged { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(QPFResource.class); - - protected String icao; - - protected String fieldName; - - protected String fieldUnitString; +public class QPFResource extends AbstractGridResource { public QPFResource(QPFResourceData data, LoadProperties props) { super(data, props); + this.getCapability(DisplayTypeCapability.class) + .setAlternativeDisplayTypes(null); + } - data.addChangeListener(this); - for (QPFRecord rec : data.getRecords()) { - try { - this.addRecord(rec); - } catch (VizException ve) { - ve.printStackTrace(); + @Override + protected void initInternal(IGraphicsTarget target) throws VizException { + for (QPFRecord rec : resourceData.getRecords()) { + this.addDataObject(rec); + } + super.initInternal(target); + } + + @Override + public ParamLevelMatchCriteria getMatchCriteria() { + ParamLevelMatchCriteria match = new ParamLevelMatchCriteria(); + ArrayList paramList = new ArrayList(); + paramList.add("qpf"); + match.setParameterName(paramList); + for (DataTime time : getDataTimes()) { + List pdos = getPluginDataObjects(time); + if (pdos != null && !pdos.isEmpty()) { + paramList.clear(); + paramList.add(((QPFRecord) pdos.get(0)).getParameterName()); + break; } } + return match; } - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.AbstractMapContourResource#getQPFGeometry - * (com.raytheon.edex.db.objects.PluginDataObject) - */ @Override - protected GeneralGridGeometry getGridGeometry(PluginDataObject obj) { - QPFRecord qpfRecord = (QPFRecord) obj; - - GridGeometry2D qpfGeometry2D = qpfRecord.getGridGeometry(); - - return qpfGeometry2D; - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.AbstractMapContourResource#validateRecord - * (com.raytheon.edex.db.objects.PluginDataObject) - */ - @Override - protected boolean validateRecord(PluginDataObject obj) { - return (obj instanceof QPFRecord); + public List getData(DataTime time, + List pdos) throws VizException { + if (pdos.isEmpty()) { + return Collections.emptyList(); + } + QPFRecord rec = (QPFRecord) pdos.get(0); + IDataRecord[] dataRecs = DataCubeContainer.getDataRecord(rec); + FloatDataRecord fdr = (FloatDataRecord) dataRecs[0]; + FloatBuffer data = FloatBuffer.wrap(fdr.getFloatData()); + Unit unit = UnitFormat.getInstance().parseObject( + rec.getParameterUnit(), new ParsePosition(0)); + GeneralGridData ggd = GeneralGridData.createScalarData( + rec.getGridGeometry(), data, unit); + return Arrays.asList(ggd); } /* @@ -125,9 +120,9 @@ public class QPFResource extends AbstractMapVectorResource implements @Override public String getName() { PluginDataObject pdo = null; - for (PluginDataObject obj : getDataObjectMap().values()) { - pdo = obj; - break; + List pdos = getCurrentPluginDataObjects(); + if (pdos != null && !pdos.isEmpty()) { + pdo = pdos.get(0); } if (pdo == null) { return "No Data Available"; @@ -145,83 +140,4 @@ public class QPFResource extends AbstractMapVectorResource implements return prefix.toString(); } - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.rsc.AbstractMapContourResource#getStyleRule - * (com.raytheon.edex.db.objects.PluginDataObject) - */ - @Override - public StyleRule getStyleRule(PluginDataObject obj) throws VizException { - QPFRecord record = (QPFRecord) obj; - - ParamLevelMatchCriteria match = getMatchCriteria(record); - ArrayList paramList = new ArrayList(); - paramList.add(record.getParameterName()); - match.setParameterName(paramList); - StyleRule sr = StyleManager.getInstance().getStyleRule( - StyleManager.StyleType.CONTOUR, match); - if (sr != null - && ((ContourPreferences) sr.getPreferences()).getDisplayUnits() != null) { - this.fieldUnitString = ((ContourPreferences) sr.getPreferences()) - .getDisplayUnits().toString(); - } - return sr; - } - - /** - * Get and load the style rule - * - * @return - */ - public ParamLevelMatchCriteria getMatchCriteria(QPFRecord record) { - ParamLevelMatchCriteria match = new ParamLevelMatchCriteria(); - ArrayList paramList = new ArrayList(); - paramList.add(record.getPluginName()); - match.setParameterName(paramList); - return match; - } - - @SuppressWarnings("unchecked") - @Override - public AbstractVizResource getImageryResource() - throws VizException { - Collection pdo = this.getDataObjectMap().values(); - QPFRecord[] recs = new QPFRecord[pdo.size()]; - Iterator pdoIter = pdo.iterator(); - int i = 0; - while (pdoIter.hasNext()) { - recs[i] = (QPFRecord) pdoIter.next(); - i++; - } - - return (AbstractVizResource) this.resourceData - .construct(new GridLoadProperties( - com.raytheon.uf.viz.core.rsc.DisplayType.IMAGE), - descriptor); - } - - @Override - public void resourceChanged(ChangeType type, Object object) { - if (type.equals(ChangeType.DATA_UPDATE)) { - PluginDataObject[] pdos = (PluginDataObject[]) object; - for (PluginDataObject pdo : pdos) { - try { - addRecord(pdo); - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error updating QPF resource", e); - } - } - } - issueRefresh(); - } - - @Override - protected Unit getDataUnits(PluginDataObject obj) { - // TODO Auto-generated method stub - return null; - } - } diff --git a/cave/com.raytheon.uf.viz.sounding/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.sounding/META-INF/MANIFEST.MF index 0c26a854dd..b3c689cabb 100644 --- a/cave/com.raytheon.uf.viz.sounding/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.uf.viz.sounding/META-INF/MANIFEST.MF @@ -7,43 +7,30 @@ Bundle-Activator: com.raytheon.uf.viz.sounding.Activator Bundle-Vendor: RAYTHEON Require-Bundle: org.eclipse.core.runtime, javax.measure;bundle-version="1.0.0", - org.geotools;bundle-version="2.5.2", com.raytheon.edex.common;bundle-version="1.11.17", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.17", - com.raytheon.uf.common.sounding;bundle-version="1.0.0" + com.raytheon.uf.common.sounding;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0", + com.raytheon.uf.common.topo;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin.level;bundle-version="1.12.1174", + com.raytheon.uf.common.parameter;bundle-version="1.0.0" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.viz.sounding, com.raytheon.uf.viz.sounding.adapters Import-Package: com.raytheon.edex.meteoLib, com.raytheon.edex.plugin.modelsounding.common, - com.raytheon.edex.scriptfactory, - com.raytheon.edex.util, com.raytheon.uf.common.dataplugin, - com.raytheon.uf.common.dataplugin.acarssounding, - com.raytheon.uf.common.dataplugin.bufrua, com.raytheon.uf.common.dataplugin.goessounding, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.dataplugin.poessounding, com.raytheon.uf.common.dataplugin.profiler, com.raytheon.uf.common.geospatial, - com.raytheon.uf.common.menus, - com.raytheon.uf.common.menus.xml, com.raytheon.uf.common.pointdata, com.raytheon.uf.common.pointdata.spatial, - com.raytheon.uf.common.serialization, com.raytheon.uf.common.status, com.raytheon.uf.common.time, - com.raytheon.uf.common.topo, - com.raytheon.uf.viz.acarssounding, - com.raytheon.uf.viz.core.catalog, com.raytheon.uf.viz.core.datastructure, com.raytheon.uf.viz.core.exception, com.raytheon.uf.viz.core.status, com.raytheon.uf.viz.core.topo, - com.raytheon.uf.viz.ui.menus, com.raytheon.viz.core.map, - com.raytheon.viz.core.slice, - com.raytheon.viz.core.slice.request, com.raytheon.viz.pointdata diff --git a/cave/com.raytheon.uf.viz.sounding/src/com/raytheon/uf/viz/sounding/adapters/GribSoundingAdapter.java b/cave/com.raytheon.uf.viz.sounding/src/com/raytheon/uf/viz/sounding/adapters/GridSoundingAdapter.java similarity index 84% rename from cave/com.raytheon.uf.viz.sounding/src/com/raytheon/uf/viz/sounding/adapters/GribSoundingAdapter.java rename to cave/com.raytheon.uf.viz.sounding/src/com/raytheon/uf/viz/sounding/adapters/GridSoundingAdapter.java index ad89a11087..55531c8a71 100644 --- a/cave/com.raytheon.uf.viz.sounding/src/com/raytheon/uf/viz/sounding/adapters/GribSoundingAdapter.java +++ b/cave/com.raytheon.uf.viz.sounding/src/com/raytheon/uf/viz/sounding/adapters/GridSoundingAdapter.java @@ -27,7 +27,7 @@ import java.util.List; import java.util.Map; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.common.geospatial.ISpatialObject; @@ -49,7 +49,7 @@ import com.raytheon.viz.core.map.GeoUtil; import com.vividsolutions.jts.geom.GeometryFactory; /** - * Sounding adapter for grib data, used for both skewt and cloud height sampling + * Sounding adapter for grid data, used for cloud height sampling * *
  * 
@@ -64,9 +64,9 @@ import com.vividsolutions.jts.geom.GeometryFactory;
  * @version 1.0
  */
 
-public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
+public class GridSoundingAdapter extends AbstractVerticalSoundingAdapter {
     private static final transient IUFStatusHandler statusHandler = UFStatus
-            .getHandler(GribSoundingAdapter.class);
+            .getHandler(GridSoundingAdapter.class);
 
     /** Interface for getting point information */
     private IPointSounding pointSounding;
@@ -84,7 +84,7 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
      *            Object which will provide information on point location and
      *            name
      */
-    public GribSoundingAdapter(IPointSounding pointSounding) {
+    public GridSoundingAdapter(IPointSounding pointSounding) {
         this.pointSounding = pointSounding;
         soundingMap = new HashMap>();
     }
@@ -101,7 +101,7 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
         long t0 = System.currentTimeMillis();
         List soundings = new ArrayList();
         try {
-            GribRecord sampleRecord = (GribRecord) objects[0];
+            GridRecord sampleRecord = (GridRecord) objects[0];
             ISpatialObject spatial = sampleRecord.getSpatialObject();
             Point point = PointUtil.determineIndex(
                     pointSounding.getCoordinate(), spatial.getCrs(),
@@ -113,10 +113,9 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
                                 "Point is outside bounds of grid"));
                 return new VerticalSounding[0];
             }
-            String name = String.format("%s pt%s %s", sampleRecord
-                    .getModelInfo().getModelTitle(), pointSounding
-                    .getPointName(), GeoUtil.formatCoordinate(pointSounding
-                    .getCoordinate()));
+            String name = String.format("%s pt%s %s",
+                    sampleRecord.getDatasetId(), pointSounding.getPointName(),
+                    GeoUtil.formatCoordinate(pointSounding.getCoordinate()));
             location = new SurfaceObsLocation(name);
             location.setGeometry(new GeometryFactory()
                     .createPoint(pointSounding.getCoordinate()));
@@ -134,18 +133,9 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
                 if (rec != null && rec.length > 0) {
                     float[] data = (float[]) rec[0].getDataObject();
                     float val = data[0];
-                    addToSoundingMap((GribRecord) pdo, val);
+                    addToSoundingMap((GridRecord) pdo, val);
                 }
             }
-            double rotation = 0;
-            if ((sampleRecord.getResCompFlags() == null)
-                    || (sampleRecord.getResCompFlags() & 8) != 0) {
-                rotation = 180 - MapUtil.rotation(
-                        pointSounding.getCoordinate(),
-                        sampleRecord.getSpatialObject());
-            }
-            float sinRot = (float) Math.sin(Math.toRadians(rotation));
-            float cosRot = (float) Math.cos(Math.toRadians(rotation));
             for (DataTime time : soundingMap.keySet()) {
                 VerticalSounding sounding = new VerticalSounding();
                 sounding.setDataTime(time);
@@ -156,12 +146,6 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
                 sounding.setStationId(location.getStationId());
                 Map layerMap = soundingMap.get(time);
                 for (SoundingLayer layer : layerMap.values()) {
-                    float u = layer.getWindU();
-                    float v = layer.getWindV();
-                    float vTemp = (u * sinRot) + (v * cosRot);
-                    u = (u * cosRot) - (v * sinRot);
-                    layer.setWindU(u);
-                    layer.setWindV(vTemp);
                     sounding.addLayer(layer);
                 }
 
@@ -213,7 +197,7 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
      * @param dataVal
      * @throws VizException
      */
-    private void addToSoundingMap(GribRecord record, float dataVal)
+    private void addToSoundingMap(GridRecord record, float dataVal)
             throws VizException {
         DataTime dt = record.getDataTime();
         Map layerMap = soundingMap.get(dt);
@@ -222,14 +206,14 @@ public class GribSoundingAdapter extends AbstractVerticalSoundingAdapter {
             soundingMap.put(dt, layerMap);
         }
 
-        Double l1val = record.getModelInfo().getLevelOneValue();
+        Double l1val = record.getLevel().getLevelonevalue();
         SoundingLayer layer = layerMap.get(l1val);
         if (layer == null) {
             layer = new SoundingLayer();
             layer.setPressure(l1val.floatValue());
             layerMap.put(l1val, layer);
         }
-        String param = record.getModelInfo().getParameterAbbreviation();
+        String param = record.getParameter().getAbbreviation();
 
         if ("T".equals(param)) {
             layer.setTemperature(dataVal);
diff --git a/cave/com.raytheon.uf.viz.spring.dm/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.spring.dm/META-INF/MANIFEST.MF
index a212dcc512..e16b79390b 100644
--- a/cave/com.raytheon.uf.viz.spring.dm/META-INF/MANIFEST.MF
+++ b/cave/com.raytheon.uf.viz.spring.dm/META-INF/MANIFEST.MF
@@ -7,7 +7,6 @@ Bundle-Activator: com.raytheon.uf.viz.spring.dm.Activator
 Bundle-Vendor: RAYTHEON
 Require-Bundle: org.eclipse.core.runtime,
  org.springframework;bundle-version="2.5.6",
- org.apache.commons.logging;bundle-version="1.1.1",
- org.springframework.dm;bundle-version="1.2.1"
+ org.apache.commons.logging;bundle-version="1.1.1"
 Bundle-RequiredExecutionEnvironment: JavaSE-1.6
 Bundle-ActivationPolicy: lazy
diff --git a/cave/com.raytheon.uf.viz.spring.dm/META-INF/p2.inf b/cave/com.raytheon.uf.viz.spring.dm/META-INF/p2.inf
index 307c9954de..f5c5e0fd6f 100644
--- a/cave/com.raytheon.uf.viz.spring.dm/META-INF/p2.inf
+++ b/cave/com.raytheon.uf.viz.spring.dm/META-INF/p2.inf
@@ -1,3 +1,3 @@
 instructions.configure = \
-       setStartLevel(startLevel:5);\
+       setStartLevel(startLevel:0);\
        markStarted(started: true);
\ No newline at end of file
diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/Activator.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/Activator.java
index 4469c34590..0c120fc982 100644
--- a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/Activator.java
+++ b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/Activator.java
@@ -1,48 +1,21 @@
 package com.raytheon.uf.viz.spring.dm;
 
+import java.io.IOException;
+import java.net.URL;
 import java.util.ArrayList;
-import java.util.Collections;
+import java.util.Enumeration;
+import java.util.HashMap;
 import java.util.HashSet;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Timer;
+import java.util.Set;
 
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
+import org.eclipse.core.runtime.FileLocator;
+import org.eclipse.core.runtime.IPath;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleActivator;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.SynchronousBundleListener;
-import org.osgi.framework.Version;
-import org.springframework.beans.factory.DisposableBean;
-import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
-import org.springframework.core.CollectionFactory;
-import org.springframework.core.task.SyncTaskExecutor;
-import org.springframework.core.task.TaskExecutor;
-import org.springframework.osgi.context.ConfigurableOsgiBundleApplicationContext;
-import org.springframework.osgi.context.DelegatedExecutionOsgiBundleApplicationContext;
-import org.springframework.osgi.context.event.OsgiBundleApplicationContextEventMulticaster;
-import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener;
-import org.springframework.osgi.extender.OsgiApplicationContextCreator;
-import org.springframework.osgi.extender.internal.activator.ContextLoaderListener;
-import org.springframework.osgi.extender.internal.dependencies.shutdown.BundleDependencyComparator;
-import org.springframework.osgi.extender.internal.dependencies.shutdown.ComparatorServiceDependencySorter;
-import org.springframework.osgi.extender.internal.dependencies.shutdown.ServiceDependencySorter;
-import org.springframework.osgi.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor;
-import org.springframework.osgi.extender.internal.support.NamespaceManager;
-import org.springframework.osgi.extender.internal.support.OsgiBeanFactoryPostProcessorAdapter;
-import org.springframework.osgi.extender.internal.util.concurrent.Counter;
-import org.springframework.osgi.extender.internal.util.concurrent.RunnableTimedExecution;
-import org.springframework.osgi.extender.support.ApplicationContextConfiguration;
-import org.springframework.osgi.extender.support.internal.ConfigUtils;
-import org.springframework.osgi.service.importer.support.Cardinality;
-import org.springframework.osgi.service.importer.support.CollectionType;
-import org.springframework.osgi.service.importer.support.OsgiServiceCollectionProxyFactoryBean;
-import org.springframework.osgi.util.OsgiBundleUtils;
-import org.springframework.osgi.util.OsgiStringUtils;
+import org.osgi.framework.Constants;
 
 /**
  * 
@@ -65,749 +38,133 @@ import org.springframework.osgi.util.OsgiStringUtils;
  */
 public class Activator implements BundleActivator {
 
-    /**
-     * Common base class for {@link ContextLoaderListener} listeners.
-     * 
-     * @author Costin Leau
-     */
-    private abstract class BaseListener implements SynchronousBundleListener {
+    // The plug-in ID
+    public static final String PLUGIN_ID = "com.raytheon.uf.viz.spring.dm";
 
-        /**
-         * A bundle has been started, stopped, resolved, or unresolved. This
-         * method is a synchronous callback, do not do any long-running work in
-         * this thread.
-         * 
-         * @see org.osgi.framework.SynchronousBundleListener#bundleChanged
-         */
-        public void bundleChanged(BundleEvent event) {
+    private static final String SPRING_PATH = "res" + IPath.SEPARATOR
+            + "spring";
 
-            boolean trace = log.isTraceEnabled();
+    private static final String SPRING_FILE_EXT = "*.xml";
 
-            // check if the listener is still alive
-            synchronized (monitor) {
-                if (isClosed) {
-                    if (trace)
-                        log.trace("Listener is closed; events are being ignored");
-                    return;
-                }
-            }
-            if (trace) {
-                log.debug("Processing bundle event ["
-                        + OsgiStringUtils.nullSafeToString(event)
-                        + "] for bundle ["
-                        + OsgiStringUtils.nullSafeSymbolicName(event
-                                .getBundle()) + "]");
-            }
-            try {
-                handleEvent(event);
-            } catch (Exception ex) {
-                /* log exceptions before swallowing */
-                log.warn("Got exception while handling event " + event, ex);
-            }
-        }
-
-        protected abstract void handleEvent(BundleEvent event);
-    }
+    // The shared instance
+    private static Activator plugin;
 
     /**
-     * Bundle listener used for detecting namespace handler/resolvers. Exists as
-     * a separate listener so that it can be registered early to avoid race
-     * conditions with bundles in INSTALLING state but still to avoid premature
-     * context creation before the Spring {@link ContextLoaderListener} is not
-     * fully initialized.
-     * 
-     * @author Costin Leau
+     * The constructor
      */
-    private class NamespaceBundleLister extends BaseListener {
-
-        protected void handleEvent(BundleEvent event) {
-
-            Bundle bundle = event.getBundle();
-
-            switch (event.getType()) {
-            case BundleEvent.STARTED: {
-                maybeAddNamespaceHandlerFor(bundle);
-                break;
-            }
-            case BundleEvent.STOPPED: {
-                maybeRemoveNameSpaceHandlerFor(bundle);
-                break;
-            }
-            default:
-                break;
-            }
-        }
-    }
-
-    /**
-     * Bundle listener used for context creation/destruction.
-     */
-    private class ContextBundleListener extends BaseListener {
-
-        protected void handleEvent(BundleEvent event) {
-
-            Bundle bundle = event.getBundle();
-
-            // ignore current bundle for context creation
-            if (bundle.getBundleId() == bundleId) {
-                return;
-            }
-
-            switch (event.getType()) {
-            case BundleEvent.STARTED: {
-                maybeCreateApplicationContextFor(bundle);
-                break;
-            }
-            case BundleEvent.STOPPING: {
-                if (OsgiBundleUtils.isSystemBundle(bundle)) {
-                    if (log.isDebugEnabled()) {
-                        log.debug("System bundle stopping");
-                    }
-                    // System bundle is shutting down; Special handling for
-                    // framework shutdown
-                    shutdown();
-                } else {
-                    maybeCloseApplicationContextFor(bundle);
-                }
-                break;
-            }
-            default:
-                break;
-            }
-        }
-    }
-
-    private static final Log log = LogFactory
-            .getLog(ContextLoaderListener.class);
-
-    // "Spring Application Context Creation Timer"
-    private Timer timer = new Timer(true);
-
-    /** extender bundle id */
-    private long bundleId;
-
-    /** extender configuration */
-    private ExtenderConfiguration extenderConfiguration;
-
-    /**
-     * The contexts we are currently managing. Keys are bundle ids, values are
-     * ServiceDependentOsgiApplicationContexts for the application context
-     */
-    private final Map managedContexts;
-
-    /** Task executor used for bootstraping the Spring contexts in async mode */
-    private TaskExecutor taskExecutor;
-
-    /** ApplicationContext Creator */
-    private OsgiApplicationContextCreator contextCreator;
-
-    /** BFPP list */
-    private List postProcessors;
-
-    /**
-     * Task executor which uses the same thread for running tasks. Used when
-     * doing a synchronous wait-for-dependencies.
-     */
-    private TaskExecutor sameThreadTaskExecutor = new SyncTaskExecutor();
-
-    /** listener counter - used to properly synchronize shutdown */
-    private Counter contextsStarted = new Counter("contextsStarted");
-
-    /** Spring namespace/resolver manager */
-    private NamespaceManager nsManager;
-
-    /** The bundle's context */
-    private BundleContext bundleContext;
-
-    /** Bundle listener interested in context creation */
-    private SynchronousBundleListener contextListener;
-
-    /** Bundle listener interested in namespace resolvers/parsers discovery */
-    private SynchronousBundleListener nsListener;
-
-    /** Service-based dependency sorter for shutdown */
-    private ServiceDependencySorter shutdownDependencySorter = new ComparatorServiceDependencySorter();
-
-    /**
-     * Monitor used for dealing with the bundle activator and synchronous bundle
-     * threads
-     */
-    private transient final Object monitor = new Object();
-
-    /**
-     * flag indicating whether the context is down or not - useful during
-     * shutdown
-     */
-    private boolean isClosed = false;
-
-    /** This extender version */
-    private Version extenderVersion;
-
-    private OsgiBundleApplicationContextEventMulticaster multicaster;
-
-    /** listeners interested in monitoring managed OSGi appCtxs */
-    private List applicationListeners;
-
-    /** dynamicList clean up hook */
-    private DisposableBean applicationListenersCleaner;
-
-    /** shutdown task executor */
-    private TaskExecutor shutdownTaskExecutor;
-
-    /** Required by the BundleActivator contract */
     public Activator() {
-        this.managedContexts = CollectionFactory.createConcurrentMap(16);
     }
 
-    /**
-     * 

- * Called by OSGi when this bundle is started. Finds all previously resolved - * bundles and adds namespace handlers for them if necessary. - *

- *

- * Creates application contexts for bundles started before the extender was - * started. - *

- *

- * Registers a namespace/entity resolving service for use by web app - * contexts. - *

+ /* + * (non-Javadoc) * - * @see org.osgi.framework.BundleActivator#start + * @see + * org.eclipse.core.runtime.Plugins#start(org.osgi.framework.BundleContext) */ public void start(BundleContext context) throws Exception { + plugin = this; - this.bundleContext = context; - this.bundleId = context.getBundle().getBundleId(); + Map contextMap = new HashMap(); + Set processing = new HashSet(); + Bundle[] bundles = context.getBundles(); + Map bundleMap = new HashMap(); + for (Bundle b : bundles) { + bundleMap.put(b.getSymbolicName(), b); + } + for (Bundle b : bundles) { + createContext(bundleMap, contextMap, b, processing); + } + } - this.extenderVersion = OsgiBundleUtils.getBundleVersion(context - .getBundle()); - log.info("Starting [" + bundleContext.getBundle().getSymbolicName() - + "] bundle v.[" + extenderVersion + "]"); - - // Step 1 : discover existing namespaces (in case there are fragments - // with custom XML definitions) - nsManager = new NamespaceManager(context); - - // register listener first to make sure any bundles in INSTALLED state - // are not lost - nsListener = new NamespaceBundleLister(); - context.addBundleListener(nsListener); - - Bundle[] previousBundles = context.getBundles(); - - for (int i = 0; i < previousBundles.length; i++) { - Bundle bundle = previousBundles[i]; - if (OsgiBundleUtils.isBundleResolved(bundle)) { - maybeAddNamespaceHandlerFor(bundle); + private OSGIXmlApplicationContext createContext( + Map bundles, + Map contextMap, Bundle bundle, + Set processing) { + String bundleName = bundle.getSymbolicName(); + OSGIXmlApplicationContext appCtx = contextMap.get(bundleName); + if (contextMap.containsKey(bundleName) == false + && bundleName.contains(".edex.") == false) { + if (processing.contains(bundleName)) { + throw new RuntimeException( + "Found recursive spring dependency while processing plugins: " + + bundleName); } - } + processing.add(bundleName); - // discovery finished, publish the resolvers/parsers in the OSGi space - nsManager.afterPropertiesSet(); - - // Step 2: initialize the extender configuration - try { - extenderConfiguration = new ExtenderConfiguration(context); - } catch (Exception ex) { - log.error("Unable to process extender configuration", ex); - throw ex; - } - - // initialize the configuration once namespace handlers have been - // detected - this.taskExecutor = extenderConfiguration.getTaskExecutor(); - this.shutdownTaskExecutor = extenderConfiguration - .getShutdownTaskExecutor(); - - this.contextCreator = extenderConfiguration.getContextCreator(); - this.postProcessors = extenderConfiguration.getPostProcessors(); - - // init the OSGi event dispatch/listening system - initListenerService(); - - // Step 3: discover the bundles that are started - // and require context creation - - // register the context creation listener - contextListener = new ContextBundleListener(); - // listen to any changes in bundles - context.addBundleListener(contextListener); - // get the bundles again to get an updated view - previousBundles = context.getBundles(); - - // Instantiate all previously resolved bundles which are Spring - // powered - for (int i = 0; i < previousBundles.length; i++) { - if (OsgiBundleUtils.isBundleActive(previousBundles[i])) { - try { - maybeCreateApplicationContextFor(previousBundles[i]); - } catch (Throwable e) { - log.warn( - "Cannot start bundle " - + OsgiStringUtils - .nullSafeSymbolicName(previousBundles[i]) - + " due to", e); + // No context created yet and not edex project, check for files + Enumeration entries = bundle.findEntries(SPRING_PATH, + SPRING_FILE_EXT, true); + if (entries != null) { + List files = new ArrayList(); + while (entries.hasMoreElements()) { + URL url = (URL) entries.nextElement(); + try { + url = FileLocator.toFileURL(url); + files.add(url.toString()); + } catch (IOException e) { + throw new RuntimeException( + "Error resolving spring file: " + url, e); + } } - } - } - - } - - /** - * Called by OSGi when this bundled is stopped. Unregister the - * namespace/entity resolving service and clear all state. No further - * management of application contexts created by this extender prior to - * stopping the bundle occurs after this point (even if the extender bundle - * is subsequently restarted). - * - * @see org.osgi.framework.BundleActivator#stop - */ - public void stop(BundleContext context) throws Exception { - shutdown(); - } - - /** - * Shutdown the extender and all bundled managed by it. Shutdown of contexts - * is in the topological order of the dependency graph formed by the service - * references. - */ - protected void shutdown() { - synchronized (monitor) { - // if already closed, bail out - if (isClosed) - return; - else - isClosed = true; - } - log.info("Stopping [" + bundleContext.getBundle().getSymbolicName() - + "] bundle v.[" + extenderVersion + "]"); - - // first stop the watchdog - stopTimer(); - - // remove the bundle listeners (we are closing down) - if (contextListener != null) { - bundleContext.removeBundleListener(contextListener); - contextListener = null; - } - - if (nsListener != null) { - bundleContext.removeBundleListener(nsListener); - nsListener = null; - } - - // destroy bundles - Bundle[] bundles = new Bundle[managedContexts.size()]; - - int i = 0; - for (Iterator it = managedContexts.values().iterator(); it.hasNext();) { - ConfigurableOsgiBundleApplicationContext context = (ConfigurableOsgiBundleApplicationContext) it - .next(); - bundles[i++] = context.getBundle(); - } - - bundles = shutdownDependencySorter - .computeServiceDependencyGraph(bundles); - - boolean debug = log.isDebugEnabled(); - - StringBuffer buffer = new StringBuffer(); - - if (debug) { - buffer.append("Shutdown order is: {"); - for (i = 0; i < bundles.length; i++) { - buffer.append("\nBundle [" + bundles[i].getSymbolicName() + "]"); - ServiceReference[] services = bundles[i].getServicesInUse(); - HashSet usedBundles = new HashSet(); - if (services != null) { - for (int j = 0; j < services.length; j++) { - if (BundleDependencyComparator - .isSpringManagedService(services[j])) { - Bundle used = services[j].getBundle(); - if (!used.equals(bundleContext.getBundle()) - && !usedBundles.contains(used)) { - usedBundles.add(used); - buffer.append("\n Using [" - + used.getSymbolicName() + "]"); + if (files.size() > 0) { + // Files found, check for dependencies + String requiredBundlesHeader = (String) bundle.getHeaders() + .get(Constants.REQUIRE_BUNDLE); + // Split comma separated string from MANIFEST + String[] requiredBundles = requiredBundlesHeader + .split("[,]"); + List parentContexts = new ArrayList(); + for (String requiredBndl : requiredBundles) { + // Extract bundle name which is first item in + // semicolon + // split list + String[] bndlParts = requiredBndl.split("[;]"); + Bundle reqBndl = bundles.get(bndlParts[0]); + if (reqBndl != null) { + // Found bundle, process context for bundle + OSGIXmlApplicationContext parent = createContext( + bundles, contextMap, reqBndl, processing); + if (parent != null) { + // Context found, add to list + parentContexts.add(parent); } } + } + if (parentContexts.size() > 0) { + // Context with parent context + appCtx = new OSGIXmlApplicationContext( + new OSGIGroupApplicationContext(parentContexts), + files.toArray(new String[0]), bundle); + } else { + // No parent context required + appCtx = new OSGIXmlApplicationContext( + files.toArray(new String[0]), bundle); } } } - buffer.append("\n}"); - log.debug(buffer); + contextMap.put(bundleName, appCtx); } + processing.remove(bundleName); + return appCtx; + } - final List taskList = new ArrayList(managedContexts.size()); - final List closedContexts = Collections - .synchronizedList(new ArrayList()); - final Object[] contextClosingDown = new Object[1]; - - for (i = 0; i < bundles.length; i++) { - Long id = new Long(bundles[i].getBundleId()); - final ConfigurableOsgiBundleApplicationContext context = (ConfigurableOsgiBundleApplicationContext) managedContexts - .get(id); - if (context != null) { - closedContexts.add(context); - // add a new runnable - taskList.add(new Runnable() { - - private final String toString = "Closing runnable for context " - + context.getDisplayName(); - - public void run() { - contextClosingDown[0] = context; - // eliminate context - closedContexts.remove(context); - if (log.isDebugEnabled()) - log.debug("Closing appCtx " - + context.getDisplayName()); - context.close(); - } - - public String toString() { - return toString; - } - }); - } - } - - // tasks - final Runnable[] tasks = (Runnable[]) taskList - .toArray(new Runnable[taskList.size()]); - - // start the ripper >:) - for (int j = 0; j < tasks.length; j++) { - if (RunnableTimedExecution.execute(tasks[j], - extenderConfiguration.getShutdownWaitTime(), - shutdownTaskExecutor)) { - if (debug) { - log.debug(contextClosingDown[0] - + " context did not close successfully; forcing shutdown..."); - } - } - } - - this.managedContexts.clear(); - // clear the namespace registry - nsManager.destroy(); - - // release listeners - if (applicationListeners != null) { - applicationListeners = null; - try { - applicationListenersCleaner.destroy(); - } catch (Exception ex) { - log.warn( - "exception thrown while releasing OSGi event listeners", - ex); - } - } - - // release multicaster - if (multicaster != null) { - multicaster.removeAllListeners(); - multicaster = null; - } - - // before bailing out; wait for the threads that might be left by - // the task executor - stopTaskExecutor(); - - extenderConfiguration.destroy(); + /* + * (non-Javadoc) + * + * @see + * org.eclipse.core.runtime.Plugin#stop(org.osgi.framework.BundleContext) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; } /** - * Cancel any tasks scheduled for the timer. - */ - private void stopTimer() { - if (timer != null) { - if (log.isDebugEnabled()) - log.debug("Canceling timer tasks"); - timer.cancel(); - } - timer = null; - } - - /** - * Do some additional waiting so the service dependency listeners detect the - * shutdown. - */ - private void stopTaskExecutor() { - boolean debug = log.isDebugEnabled(); - - if (debug) - log.debug("Waiting for " + contextsStarted - + " service dependency listener(s) to stop..."); - - contextsStarted - .waitForZero(extenderConfiguration.getShutdownWaitTime()); - - if (!contextsStarted.isZero()) { - if (debug) - log.debug(contextsStarted.getValue() - + " service dependency listener(s) did not responded in time; forcing them to shutdown..."); - extenderConfiguration.setForceThreadShutdown(true); - } - - else - log.debug("All listeners closed"); - } - - /** - * Utility method that does extender range versioning and approapriate - * logging. + * Returns the shared instance * - * @param bundle + * @return the shared instance */ - private boolean handlerBundleMatchesExtenderVersion(Bundle bundle) { - if (!ConfigUtils.matchExtenderVersionRange(bundle, extenderVersion)) { - if (log.isDebugEnabled()) - log.debug("Bundle [" - + OsgiStringUtils.nullSafeNameAndSymName(bundle) - + "] expects an extender w/ version[" - + OsgiBundleUtils.getHeaderAsVersion(bundle, - ConfigUtils.EXTENDER_VERSION) - + "] which does not match current extender w/ version[" - + extenderVersion - + "]; skipping bundle from handler detection"); - return false; - } - return true; - } - - private void maybeAddNamespaceHandlerFor(Bundle bundle) { - if (handlerBundleMatchesExtenderVersion(bundle)) - nsManager.maybeAddNamespaceHandlerFor(bundle); - } - - private void maybeRemoveNameSpaceHandlerFor(Bundle bundle) { - if (handlerBundleMatchesExtenderVersion(bundle)) - nsManager.maybeRemoveNameSpaceHandlerFor(bundle); - } - - /** - * Context creation is a potentially long-running activity (certainly more - * than we want to do on the synchronous event callback). - * - *

- * Based on our configuration, the context can be started on the same thread - * or on a different one. - * - *

- * Kick off a background activity to create an application context for the - * given bundle if needed. - * - * Note: Make sure to do the fastest filtering first to avoid - * slowdowns on platforms with a big number of plugins and wiring (i.e. - * Eclipse platform). - * - * @param bundle - */ - protected void maybeCreateApplicationContextFor(Bundle bundle) { - - boolean debug = log.isDebugEnabled(); - String bundleString = "[" - + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]"; - - final Long bundleId = new Long(bundle.getBundleId()); - - if (managedContexts.containsKey(bundleId)) { - if (debug) { - log.debug("Bundle " + bundleString - + " is already managed; ignoring..."); - } - return; - } - - if (!ConfigUtils.matchExtenderVersionRange(bundle, extenderVersion)) { - if (debug) - log.debug("Bundle " - + bundleString - + " expects an extender w/ version[" - + OsgiBundleUtils.getHeaderAsVersion(bundle, - ConfigUtils.EXTENDER_VERSION) - + "] which does not match current extender w/ version[" - + extenderVersion - + "]; skipping bundle from context creation"); - return; - } - - BundleContext localBundleContext = OsgiBundleUtils - .getBundleContext(bundle); - - if (debug) - log.debug("Scanning bundle " + bundleString - + " for configurations..."); - - // initialize context - final DelegatedExecutionOsgiBundleApplicationContext localApplicationContext; - - if (debug) - log.debug("Creating an application context for bundle " - + bundleString); - - try { - localApplicationContext = contextCreator - .createApplicationContext(localBundleContext); - } catch (Exception ex) { - log.error("Cannot create application context for bundle " - + bundleString, ex); - return; - } - - if (localApplicationContext == null) { - log.debug("No application context created for bundle " - + bundleString); - return; - } - - // create a dedicated hook for this application context - BeanFactoryPostProcessor processingHook = new OsgiBeanFactoryPostProcessorAdapter( - localBundleContext, postProcessors); - - // add in the post processors - localApplicationContext.addBeanFactoryPostProcessor(processingHook); - - // add the context to the tracker - managedContexts.put(bundleId, localApplicationContext); - - localApplicationContext.setDelegatedEventMulticaster(multicaster); - - // create refresh runnable - Runnable contextRefresh = new Runnable() { - - public void run() { - localApplicationContext.refresh(); - } - }; - - // executor used for creating the appCtx - // chosen based on the sync/async configuration - TaskExecutor executor = null; - - ApplicationContextConfiguration config = new ApplicationContextConfiguration( - bundle); - - String creationType; - - // synch/asynch context creation - if (config.isCreateAsynchronously()) { - // for the async stuff use the executor - executor = taskExecutor; - creationType = "Asynchronous"; - } else { - // for the sync stuff, use this thread - executor = sameThreadTaskExecutor; - creationType = "Synchronous"; - } - - if (debug) { - log.debug(creationType + " context creation for bundle " - + bundleString); - } - - // wait/no wait for dependencies behaviour - if (config.isWaitForDependencies()) { - DependencyWaiterApplicationContextExecutor appCtxExecutor = new DependencyWaiterApplicationContextExecutor( - localApplicationContext, !config.isCreateAsynchronously(), - extenderConfiguration.getDependencyFactories()); - - long timeout; - // check whether a timeout has been defined - - if (ConfigUtils.isDirectiveDefined(bundle.getHeaders(), - ConfigUtils.DIRECTIVE_TIMEOUT)) { - timeout = config.getTimeout(); - if (debug) - log.debug("Setting bundle-defined, wait-for-dependencies timeout value=" - + timeout + " ms, for bundle " + bundleString); - - } else { - timeout = extenderConfiguration.getDependencyWaitTime(); - if (debug) - log.debug("Setting globally defined wait-for-dependencies timeout value=" - + timeout + " ms, for bundle " + bundleString); - } - - appCtxExecutor.setTimeout(config.getTimeout()); - - appCtxExecutor.setWatchdog(timer); - appCtxExecutor.setTaskExecutor(executor); - appCtxExecutor.setMonitoringCounter(contextsStarted); - // set events publisher - appCtxExecutor.setDelegatedMulticaster(this.multicaster); - - contextsStarted.increment(); - } else { - // do nothing; by default contexts do not wait for services. - } - - executor.execute(contextRefresh); - } - - /** - * Closing an application context is a potentially long-running activity, - * however, we *have* to do it synchronously during the event process as the - * BundleContext object is not valid once we return from this method. - * - * @param bundle - */ - protected void maybeCloseApplicationContextFor(Bundle bundle) { - final ConfigurableOsgiBundleApplicationContext context = (ConfigurableOsgiBundleApplicationContext) managedContexts - .remove(new Long(bundle.getBundleId())); - if (context == null) { - return; - } - - RunnableTimedExecution.execute(new Runnable() { - - private final String toString = "Closing runnable for context " - + context.getDisplayName(); - - public void run() { - if (context.isActive()) { - context.close(); - } - } - - public String toString() { - return toString; - } - - }, extenderConfiguration.getShutdownWaitTime(), shutdownTaskExecutor); - } - - private void initListenerService() { - multicaster = extenderConfiguration.getEventMulticaster(); - - createListenersList(); - // register the listener that does the dispatching - multicaster.addApplicationListener(new ListListenerAdapter( - applicationListeners)); - multicaster.addApplicationListener(extenderConfiguration - .getContextEventListener()); - - if (log.isDebugEnabled()) - log.debug("Initialization of OSGi listeners service completed..."); - } - - /** - * Creates a dynamic OSGi list of OSGi services interested in receiving - * events for OSGi application contexts. - */ - private void createListenersList() { - OsgiServiceCollectionProxyFactoryBean fb = new OsgiServiceCollectionProxyFactoryBean(); - fb.setBundleContext(bundleContext); - fb.setCardinality(Cardinality.C_0__N); - fb.setCollectionType(CollectionType.LIST); - fb.setInterfaces(new Class[] { OsgiBundleApplicationContextListener.class }); - fb.setBeanClassLoader(extenderConfiguration.getClassLoader()); - fb.afterPropertiesSet(); - - applicationListenersCleaner = fb; - applicationListeners = (List) fb.getObject(); + public static Activator getDefault() { + return plugin; } } diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/CustomOsgiApplicationContextCreator.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/CustomOsgiApplicationContextCreator.java deleted file mode 100644 index c8a4fa2a35..0000000000 --- a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/CustomOsgiApplicationContextCreator.java +++ /dev/null @@ -1,88 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.viz.spring.dm; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.springframework.osgi.context.DelegatedExecutionOsgiBundleApplicationContext; -import org.springframework.osgi.extender.support.ApplicationContextConfiguration; -import org.springframework.osgi.extender.support.DefaultOsgiApplicationContextCreator; -import org.springframework.osgi.extender.support.scanning.ConfigurationScanner; -import org.springframework.osgi.extender.support.scanning.DefaultConfigurationScanner; -import org.springframework.osgi.util.OsgiStringUtils; -import org.springframework.util.ObjectUtils; - -/** - * Custom DefaultOsgiApplicationContextCreator used to turn off xml validation - * - * - *

- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Oct 12, 2010            mschenke     Initial creation
- * 
- * 
- * - * @author mschenke - * @version 1.0 - */ - -public class CustomOsgiApplicationContextCreator extends - DefaultOsgiApplicationContextCreator { - - /** logger */ - private static final Log log = LogFactory - .getLog(CustomOsgiApplicationContextCreator.class); - - private ConfigurationScanner configurationScanner = new DefaultConfigurationScanner(); - - public DelegatedExecutionOsgiBundleApplicationContext createApplicationContext( - BundleContext bundleContext) throws Exception { - Bundle bundle = bundleContext.getBundle(); - ApplicationContextConfiguration config = new ApplicationContextConfiguration( - bundle, configurationScanner); - if (log.isTraceEnabled()) - log.trace("Created configuration " + config + " for bundle " - + OsgiStringUtils.nullSafeNameAndSymName(bundle)); - - // it's not a spring bundle, ignore it - if (!config.isSpringPoweredBundle()) { - return null; - } - - log.info("Discovered configurations " - + ObjectUtils.nullSafeToString(config - .getConfigurationLocations()) + " in bundle [" - + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]"); - - DelegatedExecutionOsgiBundleApplicationContext sdoac = new CustomOsgiBundleXmlApplicationContext( - config.getConfigurationLocations()); - sdoac.setBundleContext(bundleContext); - sdoac.setPublishContextAsService(config.isPublishContextAsService()); - - return sdoac; - } - -} diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/ExtenderConfiguration.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/ExtenderConfiguration.java deleted file mode 100644 index b4dba761e4..0000000000 --- a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/ExtenderConfiguration.java +++ /dev/null @@ -1,577 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.viz.spring.dm; - -import java.io.UnsupportedEncodingException; -import java.net.URL; -import java.net.URLDecoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.osgi.framework.Bundle; -import org.osgi.framework.BundleContext; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.context.event.SimpleApplicationEventMulticaster; -import org.springframework.core.JdkVersion; -import org.springframework.core.task.SimpleAsyncTaskExecutor; -import org.springframework.core.task.TaskExecutor; -import org.springframework.osgi.context.ConfigurableOsgiBundleApplicationContext; -import org.springframework.osgi.context.event.OsgiBundleApplicationContextEventMulticaster; -import org.springframework.osgi.context.event.OsgiBundleApplicationContextEventMulticasterAdapter; -import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener; -import org.springframework.osgi.extender.OsgiApplicationContextCreator; -import org.springframework.osgi.extender.OsgiBeanFactoryPostProcessor; -import org.springframework.osgi.extender.OsgiServiceDependencyFactory; -import org.springframework.osgi.extender.internal.dependencies.startup.MandatoryImporterDependencyFactory; -import org.springframework.osgi.extender.internal.support.DefaultOsgiBundleApplicationContextListener; -import org.springframework.osgi.extender.internal.support.OsgiAnnotationPostProcessor; -import org.springframework.osgi.extender.support.internal.ConfigUtils; -import org.springframework.osgi.util.BundleDelegatingClassLoader; -import org.springframework.scheduling.timer.TimerTaskExecutor; -import org.springframework.util.Assert; -import org.springframework.util.ObjectUtils; - -/** - * TODO Add Description - * - *
- * 
- * Custom version of spring osgi ExtenderConfiguration to turn off xml validation
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Oct 12, 2010            mschenke     Initial creation
- * 
- * 
- * - * @author mschenke - * @version 1.0 - */ - -public class ExtenderConfiguration implements DisposableBean { - - /** logger */ - private static final Log log = LogFactory - .getLog(ExtenderConfiguration.class); - - private static final String TASK_EXECUTOR_NAME = "taskExecutor"; - - private static final String SHUTDOWN_TASK_EXECUTOR_NAME = "shutdownTaskExecutor"; - - private static final String CONTEXT_CREATOR_NAME = "applicationContextCreator"; - - private static final String APPLICATION_EVENT_MULTICASTER_BEAN_NAME = "osgiApplicationEventMulticaster"; - - private static final String CONTEXT_LISTENER_NAME = "osgiApplicationContextListener"; - - private static final String PROPERTIES_NAME = "extenderProperties"; - - private static final String SHUTDOWN_WAIT_KEY = "shutdown.wait.time"; - - private static final String PROCESS_ANNOTATIONS_KEY = "process.annotations"; - - private static final String WAIT_FOR_DEPS_TIMEOUT_KEY = "dependencies.wait.time"; - - private static final String EXTENDER_CFG_LOCATION = "META-INF/spring/extender"; - - private static final String XML_PATTERN = "*.xml"; - - private static final String ANNOTATION_DEPENDENCY_FACTORY = "org.springframework.osgi.extensions.annotation.ServiceReferenceDependencyBeanFactoryPostProcessor"; - - /** annotation processing system property (kept for backwards compatibility) */ - private static final String AUTO_ANNOTATION_PROCESSING = "org.springframework.osgi.extender.annotation.auto.processing"; - - // - // defaults - // - - // default dependency wait time (in milliseconds) - private static final long DEFAULT_DEP_WAIT = ConfigUtils.DIRECTIVE_TIMEOUT_DEFAULT * 1000; - - private static final long DEFAULT_SHUTDOWN_WAIT = 10 * 1000; - - private static final boolean DEFAULT_PROCESS_ANNOTATION = false; - - private ConfigurableOsgiBundleApplicationContext extenderConfiguration; - - private TaskExecutor taskExecutor, shutdownTaskExecutor; - - private boolean isTaskExecutorManagedInternally; - - private boolean isShutdownTaskExecutorManagedInternally; - - private boolean isMulticasterManagedInternally; - - private long shutdownWaitTime, dependencyWaitTime; - - private boolean processAnnotation; - - private OsgiBundleApplicationContextEventMulticaster eventMulticaster; - - private OsgiBundleApplicationContextListener contextEventListener; - - private boolean forceThreadShutdown; - - private OsgiApplicationContextCreator contextCreator; - - /** bundle wrapped class loader */ - private final ClassLoader classLoader; - - /** List of context post processors */ - private final List postProcessors = Collections - .synchronizedList(new ArrayList(0)); - - /** List of service dependency factories */ - private final List dependencyFactories = Collections - .synchronizedList(new ArrayList(0)); - - // fields reading/writing lock - private Object lock = new Object(); - - /** - * Constructs a new ExtenderConfiguration instance. Locates the - * extender configuration, creates an application context which will - * returned the extender items. - * - * @param bundleContext - * extender OSGi bundle context - */ - public ExtenderConfiguration(BundleContext bundleContext) { - Bundle bundle = bundleContext.getBundle(); - Properties properties = new Properties(createDefaultProperties()); - - Enumeration enm = bundle.findEntries(EXTENDER_CFG_LOCATION, - XML_PATTERN, false); - - if (enm == null) { - log.info("No custom extender configuration detected; using defaults..."); - - synchronized (lock) { - taskExecutor = createDefaultTaskExecutor(); - shutdownTaskExecutor = createDefaultShutdownTaskExecutor(); - eventMulticaster = createDefaultEventMulticaster(); - contextCreator = createDefaultApplicationContextCreator(); - contextEventListener = createDefaultApplicationContextListener(); - - } - classLoader = BundleDelegatingClassLoader - .createBundleClassLoaderFor(bundle); - } else { - String[] configs = copyEnumerationToList(enm); - - log.info("Detected extender custom configurations at " - + ObjectUtils.nullSafeToString(configs)); - // create OSGi specific XML context - ConfigurableOsgiBundleApplicationContext extenderAppCtx = new CustomOsgiBundleXmlApplicationContext( - configs); - extenderAppCtx.setBundleContext(bundleContext); - extenderAppCtx.refresh(); - - synchronized (lock) { - extenderConfiguration = extenderAppCtx; - // initialize beans - taskExecutor = extenderConfiguration - .containsBean(TASK_EXECUTOR_NAME) ? (TaskExecutor) extenderConfiguration - .getBean(TASK_EXECUTOR_NAME, TaskExecutor.class) - : createDefaultTaskExecutor(); - - shutdownTaskExecutor = extenderConfiguration - .containsBean(SHUTDOWN_TASK_EXECUTOR_NAME) ? (TaskExecutor) extenderConfiguration - .getBean(SHUTDOWN_TASK_EXECUTOR_NAME, - TaskExecutor.class) - : createDefaultShutdownTaskExecutor(); - - eventMulticaster = extenderConfiguration - .containsBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME) ? (OsgiBundleApplicationContextEventMulticaster) extenderConfiguration - .getBean( - APPLICATION_EVENT_MULTICASTER_BEAN_NAME, - OsgiBundleApplicationContextEventMulticaster.class) - : createDefaultEventMulticaster(); - - contextCreator = extenderConfiguration - .containsBean(CONTEXT_CREATOR_NAME) ? (OsgiApplicationContextCreator) extenderConfiguration - .getBean(CONTEXT_CREATOR_NAME, - OsgiApplicationContextCreator.class) - : createDefaultApplicationContextCreator(); - - contextEventListener = extenderConfiguration - .containsBean(CONTEXT_LISTENER_NAME) ? (OsgiBundleApplicationContextListener) extenderConfiguration - .getBean(CONTEXT_LISTENER_NAME, - OsgiBundleApplicationContextListener.class) - : createDefaultApplicationContextListener(); - } - - // get post processors - postProcessors.addAll(extenderConfiguration.getBeansOfType( - OsgiBeanFactoryPostProcessor.class).values()); - - // get dependency factories - dependencyFactories.addAll(extenderConfiguration.getBeansOfType( - OsgiServiceDependencyFactory.class).values()); - - classLoader = extenderConfiguration.getClassLoader(); - // extender properties using the defaults as backup - if (extenderConfiguration.containsBean(PROPERTIES_NAME)) { - Properties customProperties = (Properties) extenderConfiguration - .getBean(PROPERTIES_NAME, Properties.class); - Enumeration propertyKey = customProperties.propertyNames(); - while (propertyKey.hasMoreElements()) { - String property = (String) propertyKey.nextElement(); - properties.setProperty(property, - customProperties.getProperty(property)); - } - } - } - - synchronized (lock) { - shutdownWaitTime = getShutdownWaitTime(properties); - dependencyWaitTime = getDependencyWaitTime(properties); - processAnnotation = getProcessAnnotations(properties); - } - - // load default dependency factories - addDefaultDependencyFactories(); - } - - /** - * {@inheritDoc} - * - * Cleanup the configuration items. - */ - public void destroy() { - - synchronized (lock) { - if (isMulticasterManagedInternally) { - eventMulticaster.removeAllListeners(); - eventMulticaster = null; - } - - if (extenderConfiguration != null) { - extenderConfiguration.close(); - extenderConfiguration = null; - } - - // postpone the task executor shutdown - if (forceThreadShutdown) { - - if (isTaskExecutorManagedInternally) { - log.warn("Forcing the (internally created) taskExecutor to stop..."); - ThreadGroup th = ((SimpleAsyncTaskExecutor) taskExecutor) - .getThreadGroup(); - if (!th.isDestroyed()) { - // ask the threads nicely to stop - th.interrupt(); - } - } - taskExecutor = null; - } - - if (isShutdownTaskExecutorManagedInternally) { - try { - ((DisposableBean) shutdownTaskExecutor).destroy(); - } catch (Exception ex) { - log.debug( - "Received exception while shutting down shutdown task executor", - ex); - } - shutdownTaskExecutor = null; - } - } - } - - /** - * Copies the URLs returned by the given enumeration and returns them as an - * array of Strings for consumption by the application context. - * - * @param enm - * @return - */ - private String[] copyEnumerationToList(Enumeration enm) { - List urls = new ArrayList(4); - while (enm != null && enm.hasMoreElements()) { - URL configURL = (URL) enm.nextElement(); - if (configURL != null) { - String configURLAsString = configURL.toExternalForm(); - try { - urls.add(URLDecoder.decode(configURLAsString, "UTF8")); - } catch (UnsupportedEncodingException uee) { - log.warn("UTF8 encoding not supported, using the platform default"); - urls.add(URLDecoder.decode(configURLAsString)); - } - } - } - - return (String[]) urls.toArray(new String[urls.size()]); - } - - private Properties createDefaultProperties() { - Properties properties = new Properties(); - properties.setProperty(SHUTDOWN_WAIT_KEY, "" + DEFAULT_SHUTDOWN_WAIT); - properties.setProperty(PROCESS_ANNOTATIONS_KEY, "" - + DEFAULT_PROCESS_ANNOTATION); - properties - .setProperty(WAIT_FOR_DEPS_TIMEOUT_KEY, "" + DEFAULT_DEP_WAIT); - - return properties; - } - - private void addDefaultDependencyFactories() { - boolean debug = log.isDebugEnabled(); - - // default JDK 1.4 processor - dependencyFactories.add(0, new MandatoryImporterDependencyFactory()); - - // load through reflection the dependency and injection processors if - // running on JDK 1.5 and annotation processing is enabled - if (processAnnotation) { - if (JdkVersion.isAtLeastJava15()) { - // dependency processor - Class annotationProcessor = null; - try { - annotationProcessor = Class.forName( - ANNOTATION_DEPENDENCY_FACTORY, false, - ExtenderConfiguration.class.getClassLoader()); - } catch (ClassNotFoundException cnfe) { - log.warn( - "Spring DM annotation package not found, annotation processing disabled.", - cnfe); - return; - } - Object processor = BeanUtils - .instantiateClass(annotationProcessor); - Assert.isInstanceOf(OsgiServiceDependencyFactory.class, - processor); - dependencyFactories.add(1, - (OsgiServiceDependencyFactory) processor); - - if (debug) - log.debug("Succesfully loaded annotation dependency processor [" - + ANNOTATION_DEPENDENCY_FACTORY + "]"); - - // add injection processor (first in line) - postProcessors.add(0, new OsgiAnnotationPostProcessor()); - log.info("Spring-DM annotation processing enabled"); - } else { - if (debug) - log.debug("JDK 5 not available [" - + ANNOTATION_DEPENDENCY_FACTORY + "] not loaded"); - log.warn("Spring-DM annotation processing enabled but JDK 5 is n/a; disabling annotation processing..."); - } - } else { - if (debug) { - log.debug("Spring-DM annotation processing disabled; [" - + ANNOTATION_DEPENDENCY_FACTORY + "] not loaded"); - } - } - - } - - private TaskExecutor createDefaultTaskExecutor() { - // create thread-pool for starting contexts - ThreadGroup threadGroup = new ThreadGroup("spring-osgi-extender[" - + ObjectUtils.getIdentityHexString(this) + "]-threads"); - threadGroup.setDaemon(false); - - SimpleAsyncTaskExecutor taskExecutor = new SimpleAsyncTaskExecutor(); - taskExecutor.setThreadGroup(threadGroup); - taskExecutor.setThreadNamePrefix("SpringOsgiExtenderThread-"); - - isTaskExecutorManagedInternally = true; - - return taskExecutor; - } - - private TaskExecutor createDefaultShutdownTaskExecutor() { - TimerTaskExecutor taskExecutor = new TimerTaskExecutor(); - taskExecutor.afterPropertiesSet(); - isShutdownTaskExecutorManagedInternally = true; - return taskExecutor; - } - - private OsgiBundleApplicationContextEventMulticaster createDefaultEventMulticaster() { - isMulticasterManagedInternally = true; - return new OsgiBundleApplicationContextEventMulticasterAdapter( - new SimpleApplicationEventMulticaster()); - } - - private OsgiApplicationContextCreator createDefaultApplicationContextCreator() { - return new CustomOsgiApplicationContextCreator(); - } - - private OsgiBundleApplicationContextListener createDefaultApplicationContextListener() { - return new DefaultOsgiBundleApplicationContextListener(); - } - - private long getShutdownWaitTime(Properties properties) { - return Long.parseLong(properties.getProperty(SHUTDOWN_WAIT_KEY)); - } - - private long getDependencyWaitTime(Properties properties) { - return Long - .parseLong(properties.getProperty(WAIT_FOR_DEPS_TIMEOUT_KEY)); - } - - private boolean getProcessAnnotations(Properties properties) { - return Boolean.valueOf(properties.getProperty(PROCESS_ANNOTATIONS_KEY)) - .booleanValue() - || Boolean.getBoolean(AUTO_ANNOTATION_PROCESSING); - } - - /** - * Returns the taskExecutor. - * - * @return Returns the taskExecutor - */ - public TaskExecutor getTaskExecutor() { - synchronized (lock) { - return taskExecutor; - } - } - - /** - * Returns the shutdown task executor. - * - * @return Returns the shutdown task executor - */ - public TaskExecutor getShutdownTaskExecutor() { - synchronized (lock) { - return shutdownTaskExecutor; - } - } - - /** - * Returns the contextEventListener. - * - * @return Returns the contextEventListener - */ - public OsgiBundleApplicationContextListener getContextEventListener() { - synchronized (lock) { - return contextEventListener; - } - } - - /** - * Returns the shutdownWaitTime. - * - * @return Returns the shutdownWaitTime - */ - public long getShutdownWaitTime() { - synchronized (lock) { - return shutdownWaitTime; - } - } - - /** - * Indicates if the process annotation is enabled or not. - * - * @return Returns true if the annotation should be processed or not - * otherwise. - */ - public boolean shouldProcessAnnotation() { - synchronized (lock) { - return processAnnotation; - } - } - - /** - * Returns the dependencyWaitTime. - * - * @return Returns the dependencyWaitTime - */ - public long getDependencyWaitTime() { - synchronized (lock) { - return dependencyWaitTime; - } - } - - /** - * Returns the eventMulticaster. - * - * @return Returns the eventMulticaster - */ - public OsgiBundleApplicationContextEventMulticaster getEventMulticaster() { - synchronized (lock) { - return eventMulticaster; - } - } - - /** - * Sets the flag to force the taskExtender to close up in case of runaway - * threads - this applies *only* if the taskExecutor has been created - * internally. - * - *

- * The flag will cause a best attempt to shutdown the threads. - * - * @param forceThreadShutdown - * The forceThreadShutdown to set. - */ - public void setForceThreadShutdown(boolean forceThreadShutdown) { - synchronized (lock) { - this.forceThreadShutdown = forceThreadShutdown; - } - } - - /** - * Returns the contextCreator. - * - * @return Returns the contextCreator - */ - public OsgiApplicationContextCreator getContextCreator() { - synchronized (lock) { - return contextCreator; - } - } - - /** - * Returns the postProcessors. - * - * @return Returns the postProcessors - */ - public List getPostProcessors() { - return postProcessors; - } - - /** - * Returns the class loader wrapped around the extender bundle. - * - * @return extender bundle class loader - */ - public ClassLoader getClassLoader() { - return classLoader; - } - - /** - * Returns the dependencies factories declared by the extender - * configuration. The list automatically contains the default listeners - * (such as the annotation one). - * - * @return list of dependency factories - */ - public List getDependencyFactories() { - return dependencyFactories; - } -} diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/ListListenerAdapter.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/ListListenerAdapter.java deleted file mode 100644 index d51400b57a..0000000000 --- a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/ListListenerAdapter.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.viz.spring.dm; - -import java.util.Iterator; -import java.util.List; - -import org.springframework.osgi.context.event.OsgiBundleApplicationContextEvent; -import org.springframework.osgi.context.event.OsgiBundleApplicationContextListener; -import org.springframework.util.Assert; - -/** - * Direct copy of - * org.springframework.osgi.extender.internal.activator.ListListenerAdapter. - * Needed for copy of ContextLoaderListener (Activator) since spring class is - * package level visibility only - * - *

- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Oct 12, 2010            mschenke     Initial creation
- * 
- * 
- * - * @author mschenke - * @version 1.0 - */ - -class ListListenerAdapter implements OsgiBundleApplicationContextListener { - - private final List listeners; - - /** - * Constructs a new ListListenerAdapter instance. - * - * @param listeners - */ - public ListListenerAdapter(List listeners) { - Assert.notNull(listeners); - this.listeners = listeners; - } - - public void onOsgiApplicationEvent(OsgiBundleApplicationContextEvent event) { - for (Iterator iterator = listeners.iterator(); iterator.hasNext();) { - OsgiBundleApplicationContextListener osgiListener = (OsgiBundleApplicationContextListener) iterator - .next(); - osgiListener.onOsgiApplicationEvent(event); - } - } -} diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIGroupApplicationContext.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIGroupApplicationContext.java new file mode 100644 index 0000000000..0396b29a7c --- /dev/null +++ b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIGroupApplicationContext.java @@ -0,0 +1,62 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.spring.dm; + +import java.util.List; + +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.context.support.GenericApplicationContext; + +/** + * OSGI Group application context, constructs an {@link OSGIGroupBeanFactory} + * from the context group's factories + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 1, 2012            mschenke     Initial creation
+ * 
+ * 
+ * + * @author mschenke + * @version 1.0 + */ + +public class OSGIGroupApplicationContext extends GenericApplicationContext { + + public OSGIGroupApplicationContext( + List contextGroup) { + refresh(); // refresh first to avoid recreating bean definitions + DefaultListableBeanFactory factory = getDefaultListableBeanFactory(); + // Register all bean definitions from other contexts into our factory + for (OSGIXmlApplicationContext ctx : contextGroup) { + ConfigurableListableBeanFactory ctxFactory = ctx.getBeanFactory(); + for (String beanName : ctxFactory.getBeanDefinitionNames()) { + factory.registerBeanDefinition(beanName, + ctxFactory.getBeanDefinition(beanName)); + } + } + } + +} diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIXmlApplicationContext.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIXmlApplicationContext.java new file mode 100644 index 0000000000..7ccfb4c6a2 --- /dev/null +++ b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIXmlApplicationContext.java @@ -0,0 +1,73 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.spring.dm; + +import org.osgi.framework.Bundle; +import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.AbstractXmlApplicationContext; + +/** + * XML Application context for OSGI Bundle. Creates a class loader which uses + * the bundle to resolve classes + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 30, 2012            mschenke     Initial creation
+ * 
+ * 
+ * + * @author mschenke + * @version 1.0 + */ + +public class OSGIXmlApplicationContext extends AbstractXmlApplicationContext { + + public OSGIXmlApplicationContext(String[] configLocations, Bundle bundle) { + this(null, configLocations, bundle); + } + + public OSGIXmlApplicationContext(ApplicationContext parent, + String[] configLocations, Bundle bundle) { + super(parent); + setClassLoader(new OSGIXmlClassLoader(bundle, getClassLoader())); + setConfigLocations(configLocations); + refresh(); + } + + /* + * (non-Javadoc) + * + * @see org.springframework.context.support.AbstractXmlApplicationContext# + * initBeanDefinitionReader + * (org.springframework.beans.factory.xml.XmlBeanDefinitionReader) + */ + @Override + protected void initBeanDefinitionReader( + XmlBeanDefinitionReader beanDefinitionReader) { + super.initBeanDefinitionReader(beanDefinitionReader); + beanDefinitionReader.setBeanClassLoader(getClassLoader()); + } + +} diff --git a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/CustomOsgiBundleXmlApplicationContext.java b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIXmlClassLoader.java similarity index 55% rename from cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/CustomOsgiBundleXmlApplicationContext.java rename to cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIXmlClassLoader.java index 7d944907ca..a7997b74b8 100644 --- a/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/CustomOsgiBundleXmlApplicationContext.java +++ b/cave/com.raytheon.uf.viz.spring.dm/src/com/raytheon/uf/viz/spring/dm/OSGIXmlClassLoader.java @@ -19,11 +19,11 @@ **/ package com.raytheon.uf.viz.spring.dm; -import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; -import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; +import org.osgi.framework.Bundle; /** - * Custom OsgiBundleXmlApplicationContext used to turn off xml validation + * + * Class loader for spring bundle context * *
  * 
@@ -31,7 +31,7 @@ import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext;
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Oct 12, 2010            mschenke     Initial creation
+ * Nov 6, 2012            mschenke     Initial creation
  * 
  * 
* @@ -39,23 +39,30 @@ import org.springframework.osgi.context.support.OsgiBundleXmlApplicationContext; * @version 1.0 */ -public class CustomOsgiBundleXmlApplicationContext extends - OsgiBundleXmlApplicationContext { +public class OSGIXmlClassLoader extends ClassLoader { - /** - * @param configs - */ - public CustomOsgiBundleXmlApplicationContext(String[] configs) { - super(configs); + private Bundle bundle; + + public OSGIXmlClassLoader(Bundle bundle, ClassLoader parent) { + super(parent); + this.bundle = bundle; } @Override - protected void initBeanDefinitionReader( - XmlBeanDefinitionReader beanDefinitionReader) { - super.initBeanDefinitionReader(beanDefinitionReader); - beanDefinitionReader - .setValidationMode(XmlBeanDefinitionReader.VALIDATION_NONE); - beanDefinitionReader.setNamespaceAware(true); + protected synchronized Class loadClass(String name, boolean resolve) + throws ClassNotFoundException { + Class clazz = null; + try { + clazz = super.loadClass(name, resolve); + } catch (ClassNotFoundException e) { + // Ignore here + } + + if (clazz == null) { + clazz = bundle.loadClass(name); + } + + return clazz; } } diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/.classpath b/cave/com.raytheon.uf.viz.stats/.classpath similarity index 100% rename from cave/com.raytheon.uf.viz.datastorage.remote/.classpath rename to cave/com.raytheon.uf.viz.stats/.classpath diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/.project b/cave/com.raytheon.uf.viz.stats/.project similarity index 92% rename from cave/com.raytheon.uf.viz.datastorage.remote/.project rename to cave/com.raytheon.uf.viz.stats/.project index c14cea0d16..9efc849520 100644 --- a/cave/com.raytheon.uf.viz.datastorage.remote/.project +++ b/cave/com.raytheon.uf.viz.stats/.project @@ -1,6 +1,6 @@ - com.raytheon.uf.viz.datastorage.remote + com.raytheon.uf.viz.stats diff --git a/cots/org.springframework.dm/.settings/org.eclipse.jdt.core.prefs b/cave/com.raytheon.uf.viz.stats/.settings/org.eclipse.jdt.core.prefs similarity index 92% rename from cots/org.springframework.dm/.settings/org.eclipse.jdt.core.prefs rename to cave/com.raytheon.uf.viz.stats/.settings/org.eclipse.jdt.core.prefs index 05ddb3ae5c..bb7cad9231 100644 --- a/cots/org.springframework.dm/.settings/org.eclipse.jdt.core.prefs +++ b/cave/com.raytheon.uf.viz.stats/.settings/org.eclipse.jdt.core.prefs @@ -1,4 +1,4 @@ -#Wed Oct 13 11:24:37 CDT 2010 +#Mon Nov 05 11:14:57 CST 2012 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 diff --git a/cave/com.raytheon.uf.viz.stats/META-INF/MANIFEST.MF b/cave/com.raytheon.uf.viz.stats/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..bbc9e9368e --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/META-INF/MANIFEST.MF @@ -0,0 +1,19 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Stats +Bundle-SymbolicName: com.raytheon.uf.viz.stats;singleton:=true +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: com.raytheon.uf.viz.stats.Activator +Bundle-Vendor: RAYTHEON +Require-Bundle: org.eclipse.ui, + org.eclipse.core.runtime, + com.raytheon.uf.viz.core;bundle-version="1.12.1174", + com.raytheon.viz.ui;bundle-version="1.12.1174", + com.raytheon.uf.common.stats;bundle-version="1.0.0", + com.raytheon.uf.common.time;bundle-version="1.12.1174", + com.raytheon.uf.common.util;bundle-version="1.12.1174", + com.google.guava;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-ActivationPolicy: lazy +Export-Package: com.raytheon.uf.viz.stats, + com.raytheon.uf.viz.stats.ui diff --git a/cave/com.raytheon.uf.viz.stats/build.properties b/cave/com.raytheon.uf.viz.stats/build.properties new file mode 100644 index 0000000000..b5c529a3c3 --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + plugin.xml,\ + build.properties diff --git a/cave/com.raytheon.uf.viz.stats/plugin.xml b/cave/com.raytheon.uf.viz.stats/plugin.xml new file mode 100644 index 0000000000..0c3c85699f --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/plugin.xml @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + diff --git a/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/Activator.java b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/Activator.java new file mode 100644 index 0000000000..5ef0faed54 --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/Activator.java @@ -0,0 +1,50 @@ +package com.raytheon.uf.viz.stats; + +import org.eclipse.ui.plugin.AbstractUIPlugin; +import org.osgi.framework.BundleContext; + +/** + * The activator class controls the plug-in life cycle + */ +public class Activator extends AbstractUIPlugin { + + // The plug-in ID + public static final String PLUGIN_ID = "com.raytheon.uf.viz.stats"; //$NON-NLS-1$ + + // The shared instance + private static Activator plugin; + + /** + * The constructor + */ + public Activator() { + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + plugin = this; + } + + /* + * (non-Javadoc) + * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } + +} diff --git a/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/action/StatsAction.java b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/action/StatsAction.java new file mode 100644 index 0000000000..55e91bb15a --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/action/StatsAction.java @@ -0,0 +1,99 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.stats.action; + +import org.eclipse.core.commands.AbstractHandler; +import org.eclipse.core.commands.ExecutionEvent; +import org.eclipse.core.commands.ExecutionException; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; + +import com.raytheon.uf.common.stats.GraphDataRequest; +import com.raytheon.uf.common.stats.GraphDataResponse; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.core.requests.ThriftClient; +import com.raytheon.uf.viz.stats.ui.StatsControlDlg; + +/** + * Stats Action Handler. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 11, 2012    728     mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class StatsAction extends AbstractHandler { + private final IUFStatusHandler statusHandler = UFStatus + .getHandler(StatsAction.class); + + /** Dialog instance */ + private StatsControlDlg statsControlDlg = null; + + @Override + public Object execute(ExecutionEvent event) throws ExecutionException { + if ((statsControlDlg == null) || (statsControlDlg.isDisposed() == true)) { + GraphDataRequest request = new GraphDataRequest(); + request.setMetaDataRequest(true); + + GraphDataResponse response = sendRequest(request); + + if (response != null) { + Shell shell = PlatformUI.getWorkbench() + .getActiveWorkbenchWindow().getShell(); + statsControlDlg = new StatsControlDlg(shell); + statsControlDlg.setConfigList(response.getConfigList()); + statsControlDlg.open(); + } + } else { + statsControlDlg.bringToTop(); + } + + return null; + } + + /** + * Send GraphDataRequest. + * + * @param req + * The request to send + * @return The GraphDataResponse + */ + private GraphDataResponse sendRequest(GraphDataRequest req) { + try { + return (GraphDataResponse) ThriftClient.sendRequest(req); + } catch (VizException e) { + statusHandler.handle(Priority.ERROR, "Error Requesting Data", e); + } + + return null; + } +} diff --git a/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/display/ScaleManager.java b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/display/ScaleManager.java new file mode 100644 index 0000000000..cda6e8e74a --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/display/ScaleManager.java @@ -0,0 +1,190 @@ +package com.raytheon.uf.viz.stats.display; + + +public class ScaleManager { + /** + * Max number of major ticks, including first and last + */ + private final int MAX_MAJOR_TICK = 6; + + private final double ZOOMED_FACTOR = 0.01; + + private final double UNZOOMED_FACTOR = 5.0; + + private double[] niceMajorIncrementArray = { 0.01, 0.02, 0.05, 0.1, 0.2, + 0.5, 1.0, 2.0, 5.0 }; + + private double baseFactorStartingPoint = .01; + + private double minDataValue; + + private double maxDataValue; + + private double minScaleValue; + + private double maxScaleValue; + + private int majorTickCount; + + private double majorTickIncrement; + + private boolean zoomFlag; + + public ScaleManager(double minDataValue, double maxDataValue) { + this.minDataValue = minDataValue; + this.maxDataValue = maxDataValue; + + rescale(); + } + + private synchronized void rescale() { + int multipleCount = 0; + + // if zooming, use the ZOOMED_FACTOR value + if (zoomFlag) { + multipleCount = (int) Math.floor(minDataValue / ZOOMED_FACTOR); + minScaleValue = multipleCount * ZOOMED_FACTOR; + } + // if NOT zooming, use the UNZOOMED_FACTOR value + else { + multipleCount = (int) Math.floor(minDataValue / UNZOOMED_FACTOR); + minScaleValue = multipleCount * UNZOOMED_FACTOR; + + if ((maxDataValue - minDataValue < 10) && (minDataValue > .5)) { + minScaleValue = minDataValue - .5; + } + } + + double baseFactor = baseFactorStartingPoint; + + boolean done = false; + int i = 0; + + // set the range the values fit into + double range = maxDataValue - minScaleValue; + if (range < 1 && !zoomFlag) { + range = 1; + } + + while (!done) { + double testIncrement = niceMajorIncrementArray[i] * (baseFactor); + + int testTickCount = (int) Math.ceil(range / testIncrement + 1); + + // if there are a reasonable number of tickCounts, then stop + if (testTickCount <= MAX_MAJOR_TICK) { + + majorTickCount = testTickCount; + + majorTickIncrement = testIncrement; + + // first tick counts as a tick, so subtract 1 + maxScaleValue = minScaleValue + + ((majorTickCount - 1) * majorTickIncrement); + + return; + } + + i++; + + if (i >= niceMajorIncrementArray.length) { + i = 0; + baseFactor *= 10.0; + } + + } // end while !done + + return; + } + + public void setMaxDataValue(double maxDataValue) { + this.maxDataValue = maxDataValue; + + rescale(); + } + + public double getMaxDataValue() { + return maxDataValue; + + } + + public void setMinDataValue(double minDataValue) { + this.minDataValue = minDataValue; + rescale(); + } + + public double getMinDataValue() { + return minDataValue; + } + + public int getMajorTickCount() { + return majorTickCount; + } + + public double getMajorTickIncrement() { + return majorTickIncrement; + } + + public double getMaxScaleValue() { + return maxScaleValue; + } + + public double getMinScaleValue() { + return minScaleValue; + } + + public void setNiceMajorIncrementArray(double[] niceMajorIncrementArray) { + this.niceMajorIncrementArray = niceMajorIncrementArray; + rescale(); + } + + public double[] getNiceMajorIncrementArray() { + return niceMajorIncrementArray; + } + + public boolean isZoomFlag() { + return zoomFlag; + } + + public void setZoomFlag(boolean zoomFlag) { + this.zoomFlag = zoomFlag; + rescale(); + + } + + /** + * @param baseFactorStartingPoint + * The baseFactorStartingPoint to set. + */ + public void setBaseFactorStartingPoint(double baseFactorStartingPoint) { + this.baseFactorStartingPoint = baseFactorStartingPoint; + } + + /** + * @return Returns the baseFactorStartingPoint. + */ + public double getBaseFactorStartingPoint() { + return baseFactorStartingPoint; + } + + @Override + public String toString() { + String outString = " minDataValue = " + getMinDataValue() + + " maxDataValue = " + getMaxDataValue() + "\n" + + " minScaleValue = " + getMinScaleValue() + + " maxScaleValue = " + getMaxScaleValue() + "\n" + + " majorTickCount = " + getMajorTickCount() + + " majorTickIncrement = " + getMajorTickIncrement(); + + return outString; + } + + // For testing + public static void main(String[] argArray) { + double minValue = 5.1; + double maxValue = 5.3; + ScaleManager scaler = new ScaleManager(minValue, maxValue); + + System.out.println(scaler.toString()); + } +} diff --git a/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/ui/ColorManager.java b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/ui/ColorManager.java new file mode 100644 index 0000000000..68b55924a1 --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/ui/ColorManager.java @@ -0,0 +1,142 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.stats.ui; + +/** + * Color Manager + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 16, 2012            mpduff      Initial creation.
+ *
+ * 
+ * + * @version 1.0 + */ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.eclipse.swt.graphics.RGB; + +public class ColorManager { + + /** Color list */ + private List colorRGBs; + + /** + * Constructor. + */ + public ColorManager() { + setupColors(); + } + + /** + * Initialize the colors + */ + private void setupColors() { + List tempColorRGBs = new ArrayList(); + + tempColorRGBs.add(new RGB(255, 0, 0)); // RED + tempColorRGBs.add(new RGB(255, 165, 0)); // ORANGE + tempColorRGBs.add(new RGB(0, 255, 0)); // GREEN + tempColorRGBs.add(new RGB(255, 255, 0)); // YELLOW + tempColorRGBs.add(new RGB(165, 42, 42)); // BROWN + tempColorRGBs.add(new RGB(0, 255, 255)); // CYAN + tempColorRGBs.add(new RGB(255, 0, 255)); // MAGENTA + tempColorRGBs.add(new RGB(0, 0, 255)); // BLUE + tempColorRGBs.add(new RGB(138, 43, 226)); // BLUEVIOLET + tempColorRGBs.add(new RGB(238, 130, 238)); // VIOLET + tempColorRGBs.add(new RGB(102, 205, 170)); // AQUAMARINE3 + tempColorRGBs.add(new RGB(139, 125, 107)); // BISQUE4 + tempColorRGBs.add(new RGB(238, 197, 145)); // BURLYWOOD2 + tempColorRGBs.add(new RGB(205, 205, 0)); // YELLOW3 + tempColorRGBs.add(new RGB(69, 139, 0)); // CHARTREUSE4 + tempColorRGBs.add(new RGB(255, 127, 80)); // CORAL + tempColorRGBs.add(new RGB(100, 149, 237)); // CORNFLOWERBLUE + tempColorRGBs.add(new RGB(0, 139, 139)); // CYAN4 + tempColorRGBs.add(new RGB(169, 169, 169)); // DARKGRAY + tempColorRGBs.add(new RGB(139, 0, 139)); // DARKMAGENTA + tempColorRGBs.add(new RGB(238, 118, 0)); // DARKORANGE2 + tempColorRGBs.add(new RGB(139, 0, 0)); // DARKRED + tempColorRGBs.add(new RGB(233, 150, 122)); // DARKSALMON + tempColorRGBs.add(new RGB(255, 20, 147)); // DEEPPINK + tempColorRGBs.add(new RGB(0, 191, 255)); // DEEPSKYBLUE + tempColorRGBs.add(new RGB(255, 255, 255)); // WHITE + tempColorRGBs.add(new RGB(193, 205, 193)); // HONEYDEW3 + tempColorRGBs.add(new RGB(139, 58, 98)); // HOTPINK4 + tempColorRGBs.add(new RGB(144, 238, 144)); // LIGHTGREEN + tempColorRGBs.add(new RGB(255, 182, 193)); // LIGHTPINK + tempColorRGBs.add(new RGB(176, 196, 222)); // LIGHTSTEELBLUE + tempColorRGBs.add(new RGB(205, 133, 0)); // ORANGE3 + tempColorRGBs.add(new RGB(139, 105, 105)); // ROSYBROWN4 + tempColorRGBs.add(new RGB(210, 180, 140)); // TAN + tempColorRGBs.add(new RGB(0, 0, 0)); // BLACK + + colorRGBs = Collections.unmodifiableList(tempColorRGBs); + + } + + /** + * Get the list of colors. + * + * @return the list of colors + */ + public List getColorRGBs() { + return colorRGBs; + } + + /** + * Get the color at the provided index. + * + * @param index + * The index + * @return the color for the index + */ + public RGB getColorAtIndex(int index) { + int indexRV = index % colorRGBs.size(); + + RGB returnColor = colorRGBs.get(indexRV); + + if (returnColor == null) { + return new RGB(0, 0, 0); + } + + return returnColor; + } + + // for testing + public static void main(String[] args) { + ColorManager cm = new ColorManager(); + + List colorRGBArray = cm.getColorRGBs(); + + for (RGB rgb : colorRGBArray) { + // String s = RGBColors.getColorName(rgb); + // System.out.println(String.format("%20S", s) + "\t" + + // rgb.toString()); + System.out.println(rgb.toString()); + } + } +} diff --git a/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/ui/ColorManagerDlg.java b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/ui/ColorManagerDlg.java new file mode 100644 index 0000000000..f26367d842 --- /dev/null +++ b/cave/com.raytheon.uf.viz.stats/src/com/raytheon/uf/viz/stats/ui/ColorManagerDlg.java @@ -0,0 +1,356 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.viz.stats.ui; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.ScrolledComposite; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.ColorDialog; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Layout; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Tree; + +import com.raytheon.uf.common.stats.data.GraphData; +import com.raytheon.viz.ui.dialogs.CaveSWTDialogBase; + +/** + * TODO Add Description + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 18, 2012            mpduff     Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class ColorManagerDlg extends CaveSWTDialogBase { + private Composite mainComp; + + private final IColorSelection callback; + + private Button individualRdo; + + private Tree selectionTree; + + private final GraphData graphData; + + private final List
* @@ -63,7 +63,7 @@ import com.raytheon.viz.aviation.monitor.AvnPyUtil; */ public class PythonCacheGuidanceJob extends AbstractQueueJob { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final IUFStatusHandler statusHandler = UFStatus .getHandler(PythonCacheGuidanceJob.class); /** @@ -116,16 +116,27 @@ public class PythonCacheGuidanceJob extends * * @return pythonCacheJob */ - public static PythonCacheGuidanceJob getInstance() { + public static synchronized PythonCacheGuidanceJob getInstance() { if (instance == null) { instance = new PythonCacheGuidanceJob( "AvnFPS Cache Python Guidance"); instance.setSystem(true); instance.schedule(); } + return instance; } + /** + * Shutdown and remove instance of this class. + */ + public static synchronized void dispose() { + if (instance != null) { + instance.shutdown(); + instance = null; + } + } + /** * A private constructor to force singleton. * @@ -138,7 +149,6 @@ public class PythonCacheGuidanceJob extends suspendMonitor = new Object(); suspendJob = false; waitList = new ArrayList(); - setupDispose(); } /** @@ -164,7 +174,6 @@ public class PythonCacheGuidanceJob extends private void shutdown() { shutdown = true; restart(); - instance = null; } /** @@ -186,21 +195,6 @@ public class PythonCacheGuidanceJob extends } } - /** - * Setup listener to clean up the instance of this class and any threads it - * is running. - */ - private void setupDispose() { - PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell() - .addDisposeListener(new DisposeListener() { - - @Override - public void widgetDisposed(DisposeEvent e) { - shutdown(); - } - }); - } - /** * A request some thread is waiting for the results to be cached. * diff --git a/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDataManager.java b/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDataManager.java index 593e58363b..593607f89d 100644 --- a/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDataManager.java +++ b/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDataManager.java @@ -40,6 +40,9 @@ import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.python.PyUtil; import com.raytheon.uf.common.python.PythonScript; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.viz.core.catalog.CatalogQuery; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.viz.aviation.cachedata.CacheGuidanceRequest; @@ -65,6 +68,8 @@ import com.raytheon.viz.aviation.xml.WxPlotCfg; * only retrieves selected data. * 28 FEB 2011 8188 rferrel Fixed getNam * Apr 28, 2011 8065 rferrel Use cache data + * Nov 26, 2012 1298 rferrel Non-blocking dialog cleanup now use + * IUFStatusHandler for error messages. * * * @@ -73,16 +78,18 @@ import com.raytheon.viz.aviation.xml.WxPlotCfg; */ public class WeatherPlotDataManager { + private final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(WeatherPlotDataManager.class); /** * The types used for each model. */ private final static Map modelTypes = new HashMap(); static { - modelTypes.put("etamos", "ETA");// + modelTypes.put("etamos", "ETA"); modelTypes.put("etabuf", "ETA"); - modelTypes.put("gfsmos", "GFS");// - modelTypes.put("gfslamp", "LAMP");// + modelTypes.put("gfsmos", "GFS"); + modelTypes.put("gfslamp", "LAMP"); } private static WeatherPlotDataManager instance; @@ -158,7 +165,8 @@ public class WeatherPlotDataManager { wxPlotCfg = JAXB.unmarshal(path, WxPlotCfg.class); } catch (Exception e) { - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, + "Unable to read WxPlotCfg.xml", e); } } @@ -380,10 +388,10 @@ public class WeatherPlotDataManager { TafRecord[] tafs = TafUtil.getLatestTafs(siteId, 99); long keyTime = 0; - List tlist = Arrays.asList(tafs); - Collections.reverse(tlist); - tlist.toArray(tafs); if (tafs != null) { + List tlist = Arrays.asList(tafs); + Collections.reverse(tlist); + tlist.toArray(tafs); for (TafRecord taf : tafs) { Map args = new HashMap(); args.put("taf", TafUtil.safeFormatTaf(taf, false)); @@ -455,8 +463,7 @@ public class WeatherPlotDataManager { } } } catch (JepException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); } finally { if (python != null) { python.dispose(); @@ -543,8 +550,7 @@ public class WeatherPlotDataManager { } } } catch (JepException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); } finally { if (python != null) { python.dispose(); @@ -703,7 +709,7 @@ public class WeatherPlotDataManager { } } } catch (JepException e) { - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); } finally { if (python != null) { python.dispose(); @@ -805,7 +811,7 @@ public class WeatherPlotDataManager { } } } catch (JepException e) { - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); } finally { if (python != null) { python.dispose(); @@ -1009,10 +1015,7 @@ public class WeatherPlotDataManager { result = CatalogQuery.performQuery(fieldName, queryTerms); Arrays.sort(result, Collections.reverseOrder()); } catch (VizException e) { - // TODO Auto-generated catch block. Please revise as appropriate. - // statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), - // e); - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); } return result; diff --git a/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDialog.java b/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDialog.java index 9942a9a0bc..d3b971e343 100755 --- a/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDialog.java +++ b/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/climatology/WeatherPlotDialog.java @@ -88,6 +88,8 @@ import com.raytheon.viz.ui.dialogs.ICloseCallback; * 10/02/2012 1229 rferrel Made dialog non-blocking. * 10/10/2012 1229 rferrel Changes for non-blocking TimeSelectorDlg. * 10/15/2012 1229 rferrel Changes for non-blocking HelpUsageDlg. + * 11/26/2012 1298 rferrel Non-blocking dialog code cleanup. + * * * * @@ -221,6 +223,8 @@ public class WeatherPlotDialog extends CaveSWTDialog { private HelpUsageDlg usageDlg; + private WeatherPlotDataManager dataMgr; + /** * Constructor. * @@ -238,6 +242,7 @@ public class WeatherPlotDialog extends CaveSWTDialog { this.msgType = msgType; this.icaos = stationList; + this.dataMgr = WeatherPlotDataManager.getInstance(); } @Override @@ -287,9 +292,8 @@ public class WeatherPlotDialog extends CaveSWTDialog { } private void initData() { - WeatherPlotDataManager mgr = WeatherPlotDataManager.getInstance(); - mgr.getNewConfig(); - wxPlotCfg = mgr.getWxPlotCfg(); + dataMgr.getNewConfig(); + wxPlotCfg = dataMgr.getWxPlotCfg(); } /** @@ -418,8 +422,7 @@ public class WeatherPlotDialog extends CaveSWTDialog { timesBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - if (timeDlg == null || timeDlg.getShell() == null - || timeDlg.isDisposed()) { + if (timeDlg == null) { timeDlg = new TimeSelectorDialog(shell, wxPlotCfg); timeDlg.setCloseCallback(new ICloseCallback() { @@ -431,13 +434,11 @@ public class WeatherPlotDialog extends CaveSWTDialog { displayData(); } } - + timeDlg = null; } }); - timeDlg.open(); - } else { - timeDlg.bringToTop(); } + timeDlg.open(); } }); @@ -470,14 +471,12 @@ public class WeatherPlotDialog extends CaveSWTDialog { helpBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - if (mustCreate(usageDlg)) { + if (usageDlg == null) { String description = "Help"; String helpText = "This dialog is used to display TAFs, METARs and guidance forecasts.\n\nMenus:\n Site ID - pulldown menu displaying list of all TAF sites.\n Selection of a site from the list redraws the window.\n zoom - zoom factor (time scale). \n\nButtons:\n Display - Redraws the window.\n Times - Displays forecast time selection window\n Print - Dumps an image of the window to a command specified in\n the configration file etc/wxplot.cfg.\n Close - Closes this dialog.\n Help - Displays this help.\n\nData Sources - selection of available data sources. "; usageDlg = new HelpUsageDlg(shell, description, helpText); - usageDlg.open(); - } else { - usageDlg.bringToTop(); } + usageDlg.open(); } }); } @@ -727,15 +726,11 @@ public class WeatherPlotDialog extends CaveSWTDialog { Thread thread = new Thread(new Runnable() { @Override public void run() { - WeatherPlotDataManager dataMgr = WeatherPlotDataManager - .getInstance(); dataMgr.loadCacheData(siteId); if (isDisposed() == false) { VizApp.runAsync(new Runnable() { @Override public void run() { - WeatherPlotDataManager dataMgr = WeatherPlotDataManager - .getInstance(); if (dataMgr.loadData(siteId, currentTime)) { updateSiteTimeLabel(); displayData(); @@ -753,13 +748,12 @@ public class WeatherPlotDialog extends CaveSWTDialog { } private void displayData() { - WeatherPlotDataManager dataMgr = WeatherPlotDataManager.getInstance(); if (dataMgr.havePendingCache()) { setCursorBusy(true); Thread thread = new Thread(new Runnable() { @Override public void run() { - WeatherPlotDataManager.getInstance().waitForCacheRequests(); + dataMgr.waitForCacheRequests(); if (isDisposed() == false) { VizApp.runAsync(new Runnable() { @Override diff --git a/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/observer/TafMonitorDlg.java b/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/observer/TafMonitorDlg.java index 51b21c90c5..cb1eb40bdf 100644 --- a/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/observer/TafMonitorDlg.java +++ b/cave/com.raytheon.viz.aviation/src/com/raytheon/viz/aviation/observer/TafMonitorDlg.java @@ -53,7 +53,7 @@ import org.eclipse.ui.actions.ActionFactory; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.viz.alerts.observers.ProductAlertObserver; -// import com.raytheon.viz.aviation.cachedata.PythonCacheGuidanceJob; +import com.raytheon.viz.aviation.cachedata.PythonCacheGuidanceJob; import com.raytheon.viz.aviation.climatology.ClimateMenuDlg; import com.raytheon.viz.aviation.climatology.WeatherPlotDialog; import com.raytheon.viz.aviation.editor.ITafSettable; @@ -141,6 +141,7 @@ import com.raytheon.viz.ui.dialogs.ICloseCallback; * 10/11/2012 1229 jkorman Changes for BackupDialog to support non-blocking. * 10/11/2012 1229 rferrel Changes for non-blocking TafViewerEditorDlg. * 10/15/2012 1229 rferrel Changes for non-blocking HelpUsageDlg. + * 11/26/2012 1298 rferrel Non-blocking dialog cleanup. * 11/28/2012 1363 rferrel Dispose of PythonGuidanceJob when closing. * * @@ -895,7 +896,7 @@ public class TafMonitorDlg extends CaveSWTDialog { } tveDlg.disposeDialog(); - // PythonCacheGuidanceJob.dispose(); + PythonCacheGuidanceJob.dispose(); PythonGuidanceJob.dispose(); return close(); } diff --git a/cave/com.raytheon.viz.avnconfig/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.avnconfig/META-INF/MANIFEST.MF index 00158a5e0e..b8dc665c46 100644 --- a/cave/com.raytheon.viz.avnconfig/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.viz.avnconfig/META-INF/MANIFEST.MF @@ -9,7 +9,8 @@ Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, com.raytheon.uf.viz.core, com.raytheon.viz.ui;bundle-version="1.11.9", - org.geotools + org.geotools, + org.apache.commons.lang;bundle-version="2.3.0" Bundle-ActivationPolicy: lazy Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Import-Package: com.raytheon.uf.common.dataplugin.persist, diff --git a/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/ChooseByIdDialog.java b/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/ChooseByIdDialog.java index 4038b73ef1..5ee0293fa1 100644 --- a/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/ChooseByIdDialog.java +++ b/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/ChooseByIdDialog.java @@ -29,6 +29,7 @@ import org.apache.commons.lang.ArrayUtils; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.ErrorDialog; import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.ScrolledComposite; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.events.KeyEvent; @@ -39,6 +40,8 @@ import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; @@ -61,6 +64,7 @@ import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.HDF5Util; +import com.raytheon.uf.viz.core.VizApp; import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.catalog.ScriptCreator; import com.raytheon.uf.viz.core.comm.Loader; @@ -70,6 +74,7 @@ import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.AbstractVizResource; import com.raytheon.uf.viz.core.rsc.IResourceDataChanged; import com.raytheon.uf.viz.core.rsc.ResourceType; +import com.raytheon.uf.viz.points.IPointChangedListener; import com.raytheon.uf.viz.points.PointsDataManager; import com.raytheon.uf.viz.points.ui.layer.PointsToolLayer; import com.raytheon.viz.awipstools.ToolsDataManager; @@ -92,6 +97,7 @@ import com.vividsolutions.jts.geom.GeometryFactory; * a point to the location of a * "mesocyclone". * 31Jul2012 #875 rferrel Let preopen initialize components. + * 05Nov2012 #1304 rferrel Added Point Change Listener. * * * @@ -99,14 +105,15 @@ import com.vividsolutions.jts.geom.GeometryFactory; * @version 1.0 */ -public class ChooseByIdDialog extends CaveSWTDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus +public class ChooseByIdDialog extends CaveSWTDialog implements + IPointChangedListener { + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(ChooseByIdDialog.class); - private static final String HOME_POINT = "Home"; - public static final String DIALOG_TITLE = "Choose By Id"; + private final String HOME_POINT = "Home"; + private Button pointsRdo, baselinesRdo, homeRdo; private HomeToolLayer homeToolLayer; @@ -117,12 +124,24 @@ public class ChooseByIdDialog extends CaveSWTDialog { private final List changeListeners = new ArrayList(); - private final ArrayList pointStationIdTextFields; + private final List pointStationIdTextFields; - private final ArrayList baselineStationIdTextFields; + private final List baselineStationIdTextFields; private IDescriptor descriptor; + private final PointsDataManager pointsDataManager = PointsDataManager + .getInstance(); + + private final ToolsDataManager toolsDataManager = ToolsDataManager + .getInstance(); + + private ScrolledComposite pointsScroll; + + private final int NAME_INDEX = 0; + + private final int POINT_TEXT_INDEX = 1; + private class ChooseByIdSelectionListener implements SelectionListener { private final List texts; @@ -188,13 +207,11 @@ public class ChooseByIdDialog extends CaveSWTDialog { } private boolean isBaseline() { - return (isBaseline && ToolsDataManager.getInstance().getBaseline( - idName) != null); + return (isBaseline && toolsDataManager.getBaseline(idName) != null); } private boolean isPoint() { - return (!isBaseline && PointsDataManager.getInstance().getCoordinate( - idName) != null); + return (!isBaseline && pointsDataManager.getCoordinate(idName) != null); } /** @@ -307,21 +324,18 @@ public class ChooseByIdDialog extends CaveSWTDialog { private void updatePosition(List stationCoordinates) { if (isPoint()) { - PointsDataManager.getInstance().setCoordinate(idName, + pointsDataManager.setCoordinate(idName, stationCoordinates.get(0)); refreshToolLayer(pointsToolLayer); } else if (isBaseline()) { - ToolsDataManager.getInstance().setBaseline( - idName, - (new GeometryFactory()) - .createLineString(stationCoordinates - .toArray(new Coordinate[] {}))); + toolsDataManager.setBaseline(idName, (new GeometryFactory()) + .createLineString(stationCoordinates + .toArray(new Coordinate[] {}))); refreshToolLayer(baselinesToolLayer); } else if (isHome()) { - PointsDataManager.getInstance().setHome( - stationCoordinates.get(0)); + pointsDataManager.setHome(stationCoordinates.get(0)); refreshToolLayer(homeToolLayer); } } @@ -465,7 +479,6 @@ public class ChooseByIdDialog extends CaveSWTDialog { query.put("databasename", new RequestConstraint("metadata")); query.put("classname", new RequestConstraint(ObStation.class.getCanonicalName())); - // query.put("icao", new RequestConstraint(stationID)); String gid = ObStation .createGID(ObStation.CAT_TYPE_ICAO, stationID); query.put("gid", new RequestConstraint(gid)); @@ -512,21 +525,20 @@ public class ChooseByIdDialog extends CaveSWTDialog { } if (isHome()) { - Coordinate homeCoordinate = PointsDataManager.getInstance() - .getHome(); + Coordinate homeCoordinate = pointsDataManager.getHome(); stationLocationHasChanged = (!homeCoordinate .equals(stationCoordinates.get(0))); } else if (isPoint()) { - Coordinate pointCoordinate = PointsDataManager.getInstance() + Coordinate pointCoordinate = pointsDataManager .getCoordinate(idName); stationLocationHasChanged = (!pointCoordinate .equals(stationCoordinates.get(0))); } else if (isBaseline()) { - Coordinate[] baselineCoordinates = ToolsDataManager - .getInstance().getBaseline(idName).getCoordinates(); + Coordinate[] baselineCoordinates = toolsDataManager + .getBaseline(idName).getCoordinates(); for (Coordinate baselineCoordinate : baselineCoordinates) { if (!stationCoordinates.contains(baselineCoordinate)) { @@ -615,52 +627,152 @@ public class ChooseByIdDialog extends CaveSWTDialog { */ private void initializeComponents() { createTopBar(); + pointsScroll = new ScrolledComposite(shell, SWT.V_SCROLL); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + pointsScroll.setLayoutData(gd); createIdBoxes(); createBottomBar(); } private void createIdBoxes() { + Composite pointsComposite = (Composite) pointsScroll.getContent(); + boolean doPack = false; - String[] pointNames = PointsDataManager.getInstance().getPointNames() - .toArray(new String[] {}); - Arrays.sort(pointNames); - for (String point : pointNames) { - Group g = new Group(shell, SWT.NONE); + // Assume base lines do not change. + if (pointsComposite == null) { + String[] names = toolsDataManager.getBaselineNames().toArray( + new String[0]); + Arrays.sort(names); - GridData gridData = new GridData(); - gridData.horizontalAlignment = GridData.FILL; - gridData.grabExcessHorizontalSpace = true; - g.setLayoutData(gridData); - g.setLayout(new GridLayout(4, false)); - - Label label = new Label(g, SWT.NONE); - String s = point; - label.setText(s); - Text text1 = new Text(g, SWT.BORDER); - text1.setText(""); - text1.addKeyListener(new ChooseByIdKeyListener(point)); - - pointStationIdTextFields.add(text1); - - GridData data = new GridData(); - data.horizontalSpan = 2; - Text text2 = new Text(g, SWT.BORDER); - text2.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL - | GridData.HORIZONTAL_ALIGN_FILL)); - ChooseByIdKeyListener chooseByIdKeyListener = new ChooseByIdKeyListener( - point); - chooseByIdKeyListener.setBaseline(true); - text2.addKeyListener(chooseByIdKeyListener); - - baselineStationIdTextFields.add(text2); + pointsComposite = new Composite(pointsScroll, SWT.NONE); + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + pointsComposite.setLayout(new GridLayout(1, false)); + pointsComposite.setLayoutData(gd); + pointsScroll.setContent(pointsComposite); + for (String name : names) { + createGroup(pointsComposite, name, true); + } } + + String[] pointNames = pointsDataManager.getPointNames().toArray( + new String[] {}); + Arrays.sort(pointNames); + Control[] oldGroups = pointsComposite.getChildren(); + int index = 0; + for (String point : pointNames) { + boolean doMoveAbove = false; + boolean createGroup = true; + Control moveAbove = null; + while (index < oldGroups.length) { + Group group = (Group) oldGroups[index]; + String oldPoint = ((Label) group.getChildren()[NAME_INDEX]) + .getText(); + boolean isBaseline = (Boolean) group.getData(); + Text pointText = (Text) group.getChildren()[POINT_TEXT_INDEX]; + int cmp = point.compareTo(oldPoint); + if (cmp == 0) { + createGroup = false; + if (pointText.isEnabled() == false) { + pointStationIdTextFields.add(pointText); + pointText.setEnabled(true); + } + ++index; + break; + } else if (cmp > 0) { + pointStationIdTextFields.remove(pointText); + + if (isBaseline) { + pointText.setEnabled(false); + pointText.setText(""); + } else { + group.dispose(); + doPack = true; + } + ++index; + } else { + moveAbove = group; + doMoveAbove = true; + break; + } + } + + if (createGroup) { + doPack = true; + Group group = createGroup(pointsComposite, point, false); + if (doMoveAbove) { + group.moveAbove(moveAbove); + } + } + } + + while (index < oldGroups.length) { + Group group = (Group) oldGroups[index]; + boolean isBaseline = (Boolean) group.getData(); + Text pointText = (Text) group.getChildren()[POINT_TEXT_INDEX]; + pointStationIdTextFields.remove(pointText); + if (isBaseline) { + pointText.setEnabled(false); + } else { + oldGroups[index].dispose(); + doPack = true; + } + ++index; + } + + pointsScroll.setMinSize(pointsComposite.computeSize(SWT.DEFAULT, + SWT.DEFAULT)); + pointsScroll.setExpandHorizontal(true); + pointsScroll.setExpandVertical(true); + if (doPack) { + pointsComposite.pack(); + } + } + + private Group createGroup(Composite pointsComposite, String name, + boolean isBaseLine) { + Group group = new Group(pointsComposite, SWT.NONE); + group.setData(isBaseLine); + + GridData gridData = new GridData(); + gridData.horizontalAlignment = GridData.FILL; + gridData.grabExcessHorizontalSpace = true; + group.setLayoutData(gridData); + group.setLayout(new GridLayout(3, false)); + + Label label = new Label(group, SWT.NONE); + label.setText(name); + Text pointText = new Text(group, SWT.BORDER); + pointText.setText(""); + pointText.addKeyListener(new ChooseByIdKeyListener(name)); + + if (isBaseLine) { + pointText.setEnabled(false); + } else { + pointStationIdTextFields.add(pointText); + } + + Text baselineText = new Text(group, SWT.BORDER); + baselineText.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL + | GridData.HORIZONTAL_ALIGN_FILL)); + + ChooseByIdKeyListener chooseByIdKeyListener = new ChooseByIdKeyListener( + name); + chooseByIdKeyListener.setBaseline(true); + baselineText.addKeyListener(chooseByIdKeyListener); + + if (isBaseLine) { + baselineStationIdTextFields.add(baselineText); + } else { + baselineText.setEnabled(false); + } + return group; } @Override protected void preOpened() { super.preOpened(); initializeComponents(); - shell.pack(); + pointsDataManager.addPointsChangedListener(this); } private void createBottomBar() { @@ -670,7 +782,7 @@ public class ChooseByIdDialog extends CaveSWTDialog { gridData.horizontalAlignment = GridData.CENTER; gridData.grabExcessHorizontalSpace = true; g.setLayoutData(gridData); - g.setLayout(new GridLayout(4, false)); + g.setLayout(new GridLayout(3, false)); Label label = new Label(g, SWT.NONE); label.setText(HOME_POINT); @@ -679,8 +791,6 @@ public class ChooseByIdDialog extends CaveSWTDialog { text1.addKeyListener(new ChooseByIdKeyListener(HOME_POINT)); - GridData data = new GridData(); - data.horizontalSpan = 2; homeRdo = new Button(g, SWT.CHECK); homeRdo.setLayoutData(new GridData(GridData.GRAB_HORIZONTAL | GridData.HORIZONTAL_ALIGN_FILL)); @@ -754,4 +864,19 @@ public class ChooseByIdDialog extends CaveSWTDialog { this.descriptor = descriptor; } + @Override + protected void disposed() { + pointsDataManager.removePointsChangedListener(this); + } + + @Override + public void pointChanged() { + VizApp.runAsync(new Runnable() { + @Override + public void run() { + createIdBoxes(); + } + }); + } + } diff --git a/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/RangeRingDialog.java b/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/RangeRingDialog.java index 166b216f21..f64b864401 100644 --- a/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/RangeRingDialog.java +++ b/cave/com.raytheon.viz.awipstools/src/com/raytheon/viz/awipstools/ui/dialog/RangeRingDialog.java @@ -46,10 +46,12 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.Widget; +import com.raytheon.uf.viz.core.VizApp; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.AbstractResourceData; import com.raytheon.uf.viz.core.rsc.IResourceDataChanged; import com.raytheon.uf.viz.core.rsc.capabilities.EditableCapability; +import com.raytheon.uf.viz.points.IPointChangedListener; import com.raytheon.uf.viz.points.PointsDataManager; import com.raytheon.uf.viz.points.data.IPointNode; import com.raytheon.viz.awipstools.ToolsDataManager; @@ -70,6 +72,8 @@ import com.vividsolutions.jts.geom.Coordinate; * 07-11-12 #875 rferrel Bug fix for check box on * unapplied points. * 07-31-12 #875 rferrel Use MenuButton to show points in groups. + * 11-05-12 #1304 rferrel Added Point Change Listener. + * 11-29-12 #1365 rferrel Properly close dialog when not on UI thread. * * * @@ -77,15 +81,14 @@ import com.vividsolutions.jts.geom.Coordinate; * @version 1.0 */ public class RangeRingDialog extends CaveJFACEDialog implements - IResourceDataChanged { + IResourceDataChanged, IPointChangedListener { - private static final String FIXED_LABELS[] = { "None", "1", "2", "3", "12", - "13", "23", "123", "C", "C1", "C2", "C3", "C12", "C13", "C23", - "C123" }; + private final String FIXED_LABELS[] = { "None", "1", "2", "3", "12", "13", + "23", "123", "C", "C1", "C2", "C3", "C12", "C13", "C23", "C123" }; - private static final String MOVABLE_LABELS[] = { "None", "1", "C", "C1" }; + private final String MOVABLE_LABELS[] = { "None", "1", "C", "C1" }; - private static final String LATLON = "Lat/Lon"; + private final String LATLON = "Lat/Lon"; private class FixedRingRow { @@ -151,6 +154,8 @@ public class RangeRingDialog extends CaveJFACEDialog implements private int rowIdWidth = SWT.DEFAULT; + private MenuButton pointsMenuButton; + public Widget lastActiveWidget; private FocusListener lastActiveListener = new FocusListener() { @@ -172,8 +177,6 @@ public class RangeRingDialog extends CaveJFACEDialog implements super(parShell); this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE); this.resourceData = abstractResourceData; - // resourceData.fireChangeListeners(ChangeType.DATA_UPDATE, false); - // resourceData.fireChangeListeners(ChangeType.DATA_UPDATE, true); resourceData.addChangeListener(this); } @@ -250,8 +253,33 @@ public class RangeRingDialog extends CaveJFACEDialog implements true, true, 1, 1)); new Label(createComposite, SWT.NONE).setText("New at: "); - MenuButton menuButton = new MenuButton(createComposite); - Menu menu = new Menu(menuButton); + pointsMenuButton = new MenuButton(createComposite); + populatePointsMenuButton(); + + pointsDataManager.addPointsChangedListener(this); + + pointsMenuButton.addSelectionListener(new SelectionAdapter() { + + @Override + public void widgetSelected(SelectionEvent e) { + MenuButton menuButton = (MenuButton) e.widget; + MenuItem mi = menuButton.getSelectedItem(); + addMovableRing(mi.getText()); + menuButton.setSelectedItem("Select One"); + } + }); + + Button delete = new Button(createComposite, SWT.PUSH); + delete.setText("Delete"); + delete.addListener(SWT.Selection, new Listener() { + public void handleEvent(Event event) { + deleteMovableRing(); + } + }); + } + + private void populatePointsMenuButton() { + Menu menu = new Menu(pointsMenuButton); MenuItem mi0 = new MenuItem(menu, SWT.PUSH); mi0.setText("Select One"); @@ -275,14 +303,14 @@ public class RangeRingDialog extends CaveJFACEDialog implements mi = new MenuItem(menu, SWT.SEPARATOR); // Now add in the points organized in groups. - menuButton.setMinimumSize(SWT.DEFAULT, SWT.DEFAULT); + pointsMenuButton.setMinimumSize(SWT.DEFAULT, SWT.DEFAULT); populatePoints(menu, null); - menuButton.setMenu(menu); - menuButton.setSelectedItem(mi0); + pointsMenuButton.setMenu(menu); + pointsMenuButton.setSelectedItem(mi0); // Determine the maximum row.id's width - rowIdWidth = menuButton.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; + rowIdWidth = pointsMenuButton.computeSize(SWT.DEFAULT, SWT.DEFAULT).x; for (RangeRing ring : rangeRings) { if (ring.getType() != RangeRingType.FIXED) { @@ -290,25 +318,6 @@ public class RangeRingDialog extends CaveJFACEDialog implements fillMovableRow(row, ring); } } - - menuButton.addSelectionListener(new SelectionAdapter() { - - @Override - public void widgetSelected(SelectionEvent e) { - MenuButton menuButton = (MenuButton) e.widget; - MenuItem mi = menuButton.getSelectedItem(); - addMovableRing(mi.getText()); - menuButton.setSelectedItem("Select One"); - } - }); - - Button delete = new Button(createComposite, SWT.PUSH); - delete.setText("Delete"); - delete.addListener(SWT.Selection, new Listener() { - public void handleEvent(Event event) { - deleteMovableRing(); - } - }); } private void populatePoints(Menu menu, IPointNode root) { @@ -606,13 +615,21 @@ public class RangeRingDialog extends CaveJFACEDialog implements }); } + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.viz.core.rsc.IResourceDataChanged#resourceChanged(com + * .raytheon.uf.viz.core.rsc.IResourceDataChanged.ChangeType, + * java.lang.Object) + */ @Override public void resourceChanged(ChangeType type, Object object) { if (object instanceof Boolean) { boolean b = (Boolean) object; if (b == false) { this.resourceData.removeChangeListener(this); - close(); + performClose(); } return; } else if (object instanceof RangeRing[]) { @@ -633,23 +650,45 @@ public class RangeRingDialog extends CaveJFACEDialog implements } else if (object instanceof EditableCapability) { if (!((EditableCapability) object).isEditable()) { this.resourceData.removeChangeListener(this); - close(); + performClose(); } } - - /* - * VizApp.runAsync(new Runnable() { - * - * @Override public void run() { load(); } - * - * }); - */ } + /** + * Close dialog when not on the UI thread. + */ + private void performClose() { + VizApp.runAsync(new Runnable() { + + @Override + public void run() { + close(); + } + }); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.dialogs.Dialog#close() + */ @Override public boolean close() { // passing true tells the resource that editable should be turned off this.resourceData.fireChangeListeners(ChangeType.DATA_UPDATE, true); + pointsDataManager.removePointsChangedListener(this); return super.close(); } + + /* (non-Javadoc) + * @see com.raytheon.uf.viz.points.IPointChangedListener#pointChanged() + */ + @Override + public void pointChanged() { + VizApp.runAsync(new Runnable() { + @Override + public void run() { + populatePointsMenuButton(); + } + }); + } } diff --git a/cave/com.raytheon.viz.core.contours/src/com/raytheon/viz/core/contours/ContourSupport.java b/cave/com.raytheon.viz.core.contours/src/com/raytheon/viz/core/contours/ContourSupport.java index 2d503e9b04..e08be2ea5f 100644 --- a/cave/com.raytheon.viz.core.contours/src/com/raytheon/viz/core/contours/ContourSupport.java +++ b/cave/com.raytheon.viz.core.contours/src/com/raytheon/viz/core/contours/ContourSupport.java @@ -31,8 +31,12 @@ import org.apache.commons.collections.map.LRUMap; import org.eclipse.swt.graphics.RGB; import org.geotools.coverage.grid.GeneralGridEnvelope; import org.geotools.coverage.grid.GeneralGridGeometry; +import org.geotools.coverage.grid.GridEnvelope2D; import org.geotools.coverage.grid.GridGeometry2D; +import org.geotools.geometry.DirectPosition2D; +import org.geotools.geometry.Envelope2D; import org.geotools.geometry.GeneralEnvelope; +import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.referencing.operation.DefaultMathTransformFactory; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.datum.PixelInCell; @@ -46,6 +50,7 @@ import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.common.geospatial.CRSCache; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.geospatial.TransformFactory; import com.raytheon.uf.common.geospatial.util.WorldWrapChecker; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; @@ -68,6 +73,7 @@ import com.raytheon.viz.core.contours.util.FortConBuf; import com.raytheon.viz.core.contours.util.FortConConfig; import com.raytheon.viz.core.interval.XFormFunctions; import com.raytheon.viz.core.style.contour.ContourPreferences; +import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; /** @@ -632,49 +638,153 @@ public class ContourSupport { public static GeneralEnvelope calculateSubGrid(IExtent workingExtent, GeneralGridGeometry mapGridGeometry, GeneralGridGeometry imageGridGeometry) throws VizException { - GeneralEnvelope env = null; + GeneralEnvelope env = new GeneralEnvelope(2); try { - // transform screen extent to map crs - double[] screen = new double[] { workingExtent.getMinX(), - workingExtent.getMinY(), workingExtent.getMaxX(), - workingExtent.getMaxY() }; - double[] map = new double[4]; + GridGeometry2D mapGeometry2D = GridGeometry2D.wrap(mapGridGeometry); + GridGeometry2D imageGeometry2D = GridGeometry2D + .wrap(imageGridGeometry); + // Start with a grid envelope in screen space0 + GridEnvelope2D screenGridEnvelope = new GridEnvelope2D( + (int) Math.floor(workingExtent.getMinX()), + (int) Math.floor(workingExtent.getMinY()), + (int) Math.ceil(workingExtent.getWidth()), + (int) Math.ceil(workingExtent.getHeight())); + // intersect with mapGeometry so we only have points on the actual + // display + screenGridEnvelope = new GridEnvelope2D( + screenGridEnvelope.intersection(mapGeometry2D + .getGridRange2D())); + // convert from screen grid space to screen crs space. + Envelope2D screenCRSEnvelope = mapGeometry2D + .gridToWorld(screenGridEnvelope); + // Use referenced envelope to go from screen crs into image crs. + ReferencedEnvelope screenRefEnvelope = new ReferencedEnvelope( + screenCRSEnvelope); + try { + screenRefEnvelope = screenRefEnvelope.transform( + imageGridGeometry.getCoordinateReferenceSystem(), true, + 200); + } catch (TransformException e) { + // If the corners of the screen envelope are invalid in the + // source crs then the referenced envelope fails so this is the + // backup plan. This is known to hit when displaying North Polar + // Stereographic data on a Equidistant cyclindrical projection + // that extends to the south pole. - long t0 = System.currentTimeMillis(); - mapGridGeometry.getGridToCRS(PixelInCell.CELL_CORNER).transform( - screen, 0, map, 0, 2); - long t1 = System.currentTimeMillis(); - System.out.println("subgrid transform grid to CRS time: " - + (t1 - t0)); - - // TODO: Construct screen Grid Geometry - GeneralGridEnvelope gge = new GeneralGridEnvelope(new int[] { - (int) Math.floor(screen[0]), (int) Math.floor(screen[1]) }, - new int[] { (int) Math.ceil(screen[2]), - (int) Math.ceil(screen[3]) }, false); - GridGeometry2D screenGeometry = new GridGeometry2D(gge, - mapGridGeometry.getGridToCRS(), - mapGridGeometry.getCoordinateReferenceSystem()); - GridGeometry2D imageGeometry = new GridGeometry2D(imageGridGeometry); - - t0 = System.currentTimeMillis(); - org.opengis.geometry.Envelope[] envs = MapUtil.computeEnvelopes( - screenGeometry, imageGeometry); - t1 = System.currentTimeMillis(); - System.out.println("subgrid compute envelopes time: " + (t1 - t0)); - - double[] grid = new double[4]; - grid[0] = envs[0].getMinimum(0); - grid[1] = envs[0].getMinimum(1); - grid[2] = envs[0].getMaximum(0); - grid[3] = envs[0].getMaximum(1); - env = new GeneralEnvelope(2); - env.setRange(0, Math.min(grid[0], grid[2]), - Math.max(grid[0], grid[2])); - env.setRange(1, Math.min(grid[1], grid[3]), - Math.max(grid[1], grid[3])); + // Start with the full image envelope + ReferencedEnvelope imageRefEnvelope = new ReferencedEnvelope( + imageGeometry2D.getEnvelope2D()); + // transform to screen space. + imageRefEnvelope = imageRefEnvelope.transform( + screenRefEnvelope.getCoordinateReferenceSystem(), true, + 200); + // intersect the transformed envelope with the visible portion + // of screen. Hopefully this intersection will eliminate the + // invalid points in the original screen envelope. + Envelope intersectingEnv = screenRefEnvelope + .intersection(imageRefEnvelope); + screenRefEnvelope = new ReferencedEnvelope(intersectingEnv, + screenRefEnvelope.getCoordinateReferenceSystem()); + // transform the intersection back to image space, now it is + // hopefully a subgrid. + screenRefEnvelope = screenRefEnvelope.transform( + imageGridGeometry.getCoordinateReferenceSystem(), true, + 200); + } + // Convert from image crs to image grid space. + GridEnvelope2D screenImageGridEnvelope = imageGeometry2D + .worldToGrid(new Envelope2D(screenRefEnvelope)); + // intersection to limit to grid cells within the image. + screenImageGridEnvelope = new GridEnvelope2D( + screenImageGridEnvelope.intersection(imageGeometry2D + .getGridRange2D())); + // Referenced envelope does an almost perfect transformation. + // Unfortunately, it has been observed that when the screen is polar + // stereographic and the image is equidistant cylindrical that the + // referenced envelope algorithm can miss several rows of data near + // the pole. An envelope expansion has been added here to + // check every edge of the subgrid to see if the next image cell is + // on the screen, if it is then additional rows or columns are + // added. + MathTransform transform = TransformFactory.gridCellToGridCell( + imageGridGeometry, PixelInCell.CELL_CENTER, + mapGridGeometry, PixelInCell.CELL_CENTER); + DirectPosition2D center = new DirectPosition2D( + screenImageGridEnvelope.getCenterX(), + screenImageGridEnvelope.getCenterY()); + // this loop checks first in the x direction then in the y direction + for (int ordinate : new int[] { 0, 1 }) { + // loop over every row or column on the top or left and check + // the center point, if it can be transformed to screen space + // and is on the screen then add the whole row or column and try + // the next one. Choosing just the center point is arbitrary, + // but it catches all known cases. + for (int i = screenImageGridEnvelope.getLow(ordinate); i > imageGeometry2D + .getGridRange2D().getLow(ordinate); i -= 1) { + DirectPosition2D imageCell = center.clone(); + imageCell.setOrdinate(ordinate, i); + DirectPosition2D screenCell = new DirectPosition2D(); + try { + transform.transform(imageCell, screenCell); + } catch (TransformException e) { + // exception probably means we are outside valid range. + break; + } + if (workingExtent.contains(screenCell.getCoordinate())) { + screenImageGridEnvelope.add(imageCell); + } else { + break; + } + } + // same thing only this time on the bottom and right. + for (int i = screenImageGridEnvelope.getHigh(ordinate); i > imageGeometry2D + .getGridRange2D().getHigh(ordinate); i -= 1) { + DirectPosition2D imageCell = center.clone(); + imageCell.setOrdinate(ordinate, i); + DirectPosition2D screenCell = new DirectPosition2D(); + try { + transform.transform(imageCell, screenCell); + } catch (TransformException e) { + // exception probably means we are outside valid range. + break; + } + if (workingExtent.contains(screenCell.getCoordinate())) { + screenImageGridEnvelope.add(imageCell); + } else { + break; + } + } + } + // Add a 1 pixel border since worldToGrid is only guaranteed to + // include a cell if the cell center is in the envelope but we want + // to include the data in the subgrid if even a tiny bit of the edge + // overlaps. + screenImageGridEnvelope.grow(1, 1); + // intersection to limit to grid cells within the image. + screenImageGridEnvelope = new GridEnvelope2D( + screenImageGridEnvelope.intersection(imageGeometry2D + .getGridRange2D())); + if (!screenImageGridEnvelope.isEmpty()) { + // Convert GridEnvelope to general envelope. + env.setRange(0, screenImageGridEnvelope.getLow(0), + screenImageGridEnvelope.getHigh(0)); + env.setRange(1, screenImageGridEnvelope.getLow(1), + screenImageGridEnvelope.getHigh(1)); + } } catch (Exception e) { - throw new VizException("Error transforming extent", e); + statusHandler.handle(Priority.WARN, + "Cannot compute subgrid, contouring may be slow.", e); + // Don't use a subgrid, just contour the complete image. + // This may result in doing way to much contouring which can be + // slow, but it is better than no contouring at all. It's also worth + // noting that it gets slower as you zoom in and more contours are + // generated, but as you zoom in it also becomes more likely you + // will be successful in your transformation since the smaller area + // is less likely to contain invalid points. + env.setRange(0, imageGridGeometry.getGridRange().getLow(0), + imageGridGeometry.getGridRange().getHigh(0)); + env.setRange(1, imageGridGeometry.getGridRange().getLow(1), + imageGridGeometry.getGridRange().getHigh(1)); } System.out.println("*** Subgrid: " + env); return env; @@ -1128,9 +1238,10 @@ public class ContourSupport { double gridPixelSize = offCenter[0] - center[0]; double gridPixelMax = 2000.; - // If gridPixelSize is large, arrows on streamline will be too small, so adjust here - if(gridPixelSize > gridPixelMax) { - gridPixelSize = gridPixelSize/5; + // If gridPixelSize is large, arrows on streamline will be too small, so + // adjust here + if (gridPixelSize > gridPixelMax) { + gridPixelSize = gridPixelSize / 5; } float arrowSize = (float) (currentMagnification * 5 / zoom / gridPixelSize); diff --git a/cave/com.raytheon.viz.core.gl/localization/glsl/include/indexing.glsl b/cave/com.raytheon.viz.core.gl/localization/glsl/include/indexing.glsl index 151107d561..c1fdfeae96 100644 --- a/cave/com.raytheon.viz.core.gl/localization/glsl/include/indexing.glsl +++ b/cave/com.raytheon.viz.core.gl/localization/glsl/include/indexing.glsl @@ -18,7 +18,7 @@ float capIndex(float index) { * 65504.0 is treated as NaN for half floats and -1 is returned as special case */ float findFloatIndex(float rawValue, float cmapMin, float cmapMax) { - if ( rawValue == HALF_FLOAT_NaN ) { + if ( rawValue == HALF_FLOAT_NaN || rawValue != rawValue) { return -1.0; } float index = ((rawValue - cmapMin) / abs(cmapMax-cmapMin)); diff --git a/cave/com.raytheon.viz.core.gl/src/com/raytheon/viz/core/gl/dataformat/GLColorMapDataFormatFactory.java b/cave/com.raytheon.viz.core.gl/src/com/raytheon/viz/core/gl/dataformat/GLColorMapDataFormatFactory.java index 28ab76f9d2..c3c1336a97 100644 --- a/cave/com.raytheon.viz.core.gl/src/com/raytheon/viz/core/gl/dataformat/GLColorMapDataFormatFactory.java +++ b/cave/com.raytheon.viz.core.gl/src/com/raytheon/viz/core/gl/dataformat/GLColorMapDataFormatFactory.java @@ -66,8 +66,7 @@ public class GLColorMapDataFormatFactory { break; } case FLOAT: { - // dataFormat = new GLFloatDataFormat(); - dataFormat = new GLHalfFloatDataFormat(); + dataFormat = new GLFloatDataFormat(); } } return dataFormat; diff --git a/cave/com.raytheon.viz.core/src/com/raytheon/viz/core/rsc/VizGroupResource.java b/cave/com.raytheon.viz.core/src/com/raytheon/viz/core/rsc/VizGroupResource.java index 74434727e8..badbd29f3c 100644 --- a/cave/com.raytheon.viz.core/src/com/raytheon/viz/core/rsc/VizGroupResource.java +++ b/cave/com.raytheon.viz.core/src/com/raytheon/viz/core/rsc/VizGroupResource.java @@ -97,7 +97,8 @@ public class VizGroupResource extends PaintProperties paintProps) throws VizException { for (ResourcePair rp : this.resourceData.resourceList) { if (rp.getResource() != null) { - paintProps.setDataTime(descriptor.getTimeForResource(rp.getResource())); + paintProps.setDataTime(descriptor.getTimeForResource(rp + .getResource())); rp.getResource().paint(target, paintProps); } } @@ -116,9 +117,9 @@ public class VizGroupResource extends String value = "No Data"; for (ResourcePair pair : rl) { if (pair.getResource() != null) { - AbstractVizResource rsc = pair.getResource(); + AbstractVizResource rsc = pair.getResource(); value = rsc.inspect(coord); - if (value.equals(NO_DATA) == false) { + if (NO_DATA.equalsIgnoreCase(value) == false) { return value; } } @@ -156,16 +157,17 @@ public class VizGroupResource extends resource.registerListener(this); } } -// this.dataTimes = new ArrayList(resourceData.getMap().keySet()); + // this.dataTimes = new + // ArrayList(resourceData.getMap().keySet()); // If child resources have capabilities that this does not, steal them for (AbstractVizResource rcs : getResourceData().getRscs()) { for (AbstractCapability capability : rcs.getCapabilities() .getCapabilityClassCollection()) { -// if (!hasCapability(capability.getClass())) { + // if (!hasCapability(capability.getClass())) { this.getCapabilities().addCapability(capability); capability.setResourceData(resourceData); -// } + // } } } // Spread my master capability set to all my children diff --git a/cave/com.raytheon.viz.feature.awips.developer/feature.xml b/cave/com.raytheon.viz.feature.awips.developer/feature.xml index ff7e3c0570..d4ef19206a 100644 --- a/cave/com.raytheon.viz.feature.awips.developer/feature.xml +++ b/cave/com.raytheon.viz.feature.awips.developer/feature.xml @@ -146,6 +146,14 @@ id="com.raytheon.uf.viz.thinclient.feature" version="0.0.0"/> + + + + @@ -154,6 +162,10 @@ id="com.raytheon.uf.viz.kml.export.feature" version="0.0.0"/> + + diff --git a/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMaps.py b/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMaps.py index a3bec056ad..b82af5fd2a 100644 --- a/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMaps.py +++ b/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMaps.py @@ -1,19 +1,19 @@ ## # 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 +# 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 -# +# 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. ## diff --git a/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapsAdd.py b/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapsAdd.py index 976646edb3..18ae5b7e52 100644 --- a/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapsAdd.py +++ b/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapsAdd.py @@ -1,19 +1,19 @@ ## # 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 +# 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 -# +# 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. ## diff --git a/cave/com.raytheon.viz.gfe/help/GFEStartup.html b/cave/com.raytheon.viz.gfe/help/GFEStartup.html index a6c0052491..4924da4858 100644 --- a/cave/com.raytheon.viz.gfe/help/GFEStartup.html +++ b/cave/com.raytheon.viz.gfe/help/GFEStartup.html @@ -23,7 +23,7 @@ Table of Contents


cave.sh [-server hostname:port/services] [-mode TEST|PRACTICE|OPERATIONAL] [-site xxx] [-u user] [-component componentName] [-perspective perspecitiveName] [-noredirect] -[-consoleLog]
+[-consoleLog] [-nc TRUE]

@@ -77,6 +77,15 @@ Table of Contents
+ + + + +
Causes the CAVE log to be output to the console for monitoring/debugging.
-ncYESThis option is only used by Service backup. It is used to indicate that the site is + a national center, consequently a non-primary site gets special permission to export + site configuration to the central server via the Service Backup GUI. This option should + be set to 'true', i.e., -nc true. +

diff --git a/cave/com.raytheon.viz.gfe/plugin.xml b/cave/com.raytheon.viz.gfe/plugin.xml index 4c0ae88305..9ba667331d 100644 --- a/cave/com.raytheon.viz.gfe/plugin.xml +++ b/cave/com.raytheon.viz.gfe/plugin.xml @@ -1880,7 +1880,7 @@ point="com.raytheon.uf.viz.localization.localizationpath"> + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Initial creation + * Oct 30, 2012 1298 rferrel Must be a blocking dialog. + * + * + * + * @author unknown + * @version 1.0 */ public class Activator extends AbstractUIPlugin implements BundleActivator { private static final transient IUFStatusHandler statusHandler = UFStatus @@ -101,17 +115,22 @@ public class Activator extends AbstractUIPlugin implements BundleActivator { public PythonPreferenceStore getPreferenceStore() { synchronized (this) { if (pythonPrefs == null) { - if (cfgDlg == null) { + if (cfgDlg == null || cfgDlg.getShell() == null + || cfgDlg.isDisposed()) { cfgDlg = new GFEConfigDialog( new Shell(Display.getDefault())); + // Must keep as a blocking dialog for eclipse plugins to + // work properly. + cfgDlg.setBlockOnOpen(true); + cfgDlg.open(); + } else { + cfgDlg.bringToTop(); } - cfgDlg.setBlockOnOpen(true); - cfgDlg.open(); - String config = cfgDlg.getConfig(); // this is necessary because we sometimes get in here // recursively and only want to do this once if (pythonPrefs == null) { + String config = cfgDlg.getConfig(); pythonPrefs = new PythonPreferenceStore(config); statusHandler.handle(Priority.EVENTA, "GFE started with configuration: " + config); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/GridManagerView.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/GridManagerView.java index 558661d71c..eadc85eb1e 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/GridManagerView.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/GridManagerView.java @@ -54,6 +54,7 @@ import com.raytheon.viz.ui.color.IBackgroundColorChangedListener.BGColorMode; * 06/11/2009 #1947 rjpeter Updated to add saving of parms on close, * adding cancel capability and if error on * save then the close is cancelled. + * 10/30/2012 #1298 rferrel Must keep blocking dialogs to work with eclipse plugins. * * * @author dfitch @@ -129,6 +130,11 @@ public class GridManagerView extends ViewPart implements ISaveablePart2 { return view; } + /* + * (non-Javadoc) + * + * @see org.eclipse.ui.ISaveablePart2#promptToSaveOnClose() + */ @Override public int promptToSaveOnClose() { // Check for any running/queued jobs. @@ -137,6 +143,8 @@ public class GridManagerView extends ViewPart implements ISaveablePart2 { .getShell(); KillJobsOnExitDialog dialog = new KillJobsOnExitDialog(shell); + // Must keep modal and blocking in order to work with eclipse + // plugins. dialog.setBlockOnOpen(true); int returnCode = dialog.open(); if (returnCode == IDialogConstants.CANCEL_ID) { @@ -154,7 +162,8 @@ public class GridManagerView extends ViewPart implements ISaveablePart2 { SaveParameterDialog dialog = new SaveParameterDialog(shell, dataManager); - + // Must keep modal and blocking in order to work with eclipse + // plugins. dialog.setBlockOnOpen(true); int returnCode = dialog.open(); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ChangeBrightnessAction.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ChangeBrightnessAction.java index 836e71aee2..9822395110 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ChangeBrightnessAction.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ChangeBrightnessAction.java @@ -27,7 +27,7 @@ import com.raytheon.viz.gfe.dialogs.BrightnessDialog; import com.raytheon.viz.ui.cmenu.AbstractRightClickAction; /** - * TODO Add Description + * Action class for dispalying the Change Brightness dialog. * *
  * 
@@ -35,6 +35,7 @@ import com.raytheon.viz.ui.cmenu.AbstractRightClickAction;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Aug 18, 2010            wldougher     Initial creation
+ * Oct 30, 2012 1298       rferrel     Changes for non-blocking BrightnessDialog.
  * 
  * 
* @@ -43,6 +44,7 @@ import com.raytheon.viz.ui.cmenu.AbstractRightClickAction; */ public class ChangeBrightnessAction extends AbstractRightClickAction { + private BrightnessDialog dialog; protected Parm parm; @@ -53,10 +55,15 @@ public class ChangeBrightnessAction extends AbstractRightClickAction { @Override public void run() { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - BrightnessDialog dialog = new BrightnessDialog(shell, parm); - dialog.open(); + if (dialog == null || dialog.getShell() == null || dialog.isDisposed()) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + dialog = new BrightnessDialog(shell, parm); + dialog.setBlockOnOpen(false); + dialog.open(); + } else { + dialog.bringToTop(); + } } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/RunProcedureAction.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/RunProcedureAction.java index 87763d2899..1f0bd1b4e7 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/RunProcedureAction.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/RunProcedureAction.java @@ -48,6 +48,7 @@ import com.raytheon.viz.gfe.ui.runtimeui.SelectionDlg; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Nov 4, 2008 njensen Initial creation + * Nov 15, 2012 1298 rferrel Changes for non-blocking ProcedureSelectionDlg. * * * @author njensen @@ -55,7 +56,7 @@ import com.raytheon.viz.gfe.ui.runtimeui.SelectionDlg; */ public class RunProcedureAction extends AbstractHandler { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(RunProcedureAction.class); /* @@ -84,10 +85,15 @@ public class RunProcedureAction extends AbstractHandler { } } } else { + // The ProcedureSelectionDlg changes based on the procedure. + // Since it is non-modal several dialogs may be displayed. This + // mimics the AWIPS 1 behavior. + // make the gui, let it handle running the procedure SelectionDlg sd = new ProcedureSelectionDlg(PlatformUI .getWorkbench().getActiveWorkbenchWindow().getShell(), procedureName, dm, varList); + sd.setBlockOnOpen(false); sd.open(); } } catch (JepException e) { diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/SetContourValues.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/SetContourValues.java index e2e68b292a..2335e8da27 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/SetContourValues.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/SetContourValues.java @@ -33,7 +33,7 @@ import com.raytheon.viz.gfe.rsc.GFEResource; import com.raytheon.viz.ui.cmenu.AbstractRightClickAction; /** - * TODO Add Description + * Right click action to bring up the Contour dialog. * *
  * 
@@ -41,6 +41,7 @@ import com.raytheon.viz.ui.cmenu.AbstractRightClickAction;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Jun 5, 2009            randerso     Initial creation
+ * Oct 30, 2012 1298       rferrel     Changes for non-blocking SetContourValues.
  * 
  * 
* @@ -49,6 +50,7 @@ import com.raytheon.viz.ui.cmenu.AbstractRightClickAction; */ public class SetContourValues extends AbstractRightClickAction { + private ContourDialog dialog; /** * Constructor @@ -64,11 +66,15 @@ public class SetContourValues extends AbstractRightClickAction { */ @Override public void run() { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - ContourDialog contourDialog = new ContourDialog(shell, - ((GFEResource) getSelectedRsc()).getParm()); - contourDialog.open(); + if (dialog == null || dialog.getShell() == null || dialog.isDisposed()) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + dialog = new ContourDialog(shell, + ((GFEResource) getSelectedRsc()).getParm()); + dialog.open(); + } else { + dialog.bringToTop(); + } } /* diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowTimeShiftDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowTimeShiftDialog.java index bdd34fc7eb..e3053fa36d 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowTimeShiftDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowTimeShiftDialog.java @@ -38,6 +38,7 @@ import com.raytheon.viz.gfe.dialogs.TimeShiftDialog; * Feb 27, 2008 Eric Babin Initial Creation * 05Aug2008 1383 ebabin Fix for time shift not working. * Apr 9, 2009 1288 rjpeter Removed explicit refresh of SpatialDisplayManager. + * Oct 30, 2012 1298 rferrel Changes for non-blocking TimeShiftDialog. * * * @@ -46,6 +47,7 @@ import com.raytheon.viz.gfe.dialogs.TimeShiftDialog; */ public class ShowTimeShiftDialog extends AbstractHandler { + private TimeShiftDialog dialog; /* * (non-Javadoc) @@ -57,14 +59,20 @@ public class ShowTimeShiftDialog extends AbstractHandler { @Override public Object execute(ExecutionEvent arg0) throws ExecutionException { DataManager dm = DataManager.getCurrentInstance(); - if (dm != null) { + if (dm == null) { + return null; + } + + if (dialog == null || dialog.getShell() == null || dialog.isDisposed()) { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(); - TimeShiftDialog dialog = new TimeShiftDialog(shell, dm); - dialog.setBlockOnOpen(true); + dialog = new TimeShiftDialog(shell, dm); + dialog.setBlockOnOpen(false); dialog.open(); + } else { + dialog.bringToTop(); } return null; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowWeatherElementBrowserDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowWeatherElementBrowserDialog.java index 4d2bcb779d..cc0b91d99d 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowWeatherElementBrowserDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/actions/ShowWeatherElementBrowserDialog.java @@ -38,6 +38,7 @@ import com.raytheon.viz.gfe.dialogs.WeatherElementBrowserDialog; * 02/22/2008 Eric Babin Initial Creation * 04/09/2009 1288 rjpeter Removed explicit refresh of SpatialDisplayManager. * 04/30/2009 2282 rjpeter Moved dialog handling to the dialog. + * 10/30/2012 1229 rferrel Changed for non-blocking WeatherElementBrowserDialog. * * * @author ebabin @@ -45,6 +46,7 @@ import com.raytheon.viz.gfe.dialogs.WeatherElementBrowserDialog; */ public class ShowWeatherElementBrowserDialog extends AbstractHandler { + private WeatherElementBrowserDialog dialog; /* * (non-Javadoc) @@ -56,13 +58,18 @@ public class ShowWeatherElementBrowserDialog extends AbstractHandler { @Override public Object execute(ExecutionEvent arg0) throws ExecutionException { DataManager dm = DataManager.getCurrentInstance(); - if (dm != null) { + if (dm == null) { + return null; + } + + if (dialog == null || dialog.getShell() == null || dialog.isDisposed()) { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(); - WeatherElementBrowserDialog dialog = new WeatherElementBrowserDialog( - shell, dm); - dialog.setBlockOnOpen(true); + dialog = new WeatherElementBrowserDialog(shell, dm); + dialog.setBlockOnOpen(false); dialog.open(); + } else { + dialog.bringToTop(); } return null; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/AbstractSaveParameterDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/AbstractSaveParameterDialog.java index 857d4da0af..7a6660917c 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/AbstractSaveParameterDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/AbstractSaveParameterDialog.java @@ -59,6 +59,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Oct 26, 2011 randerso Initial creation + * Oct 30, 2012 1298 rferrel Code clean for non-blocking dialog. * * * @@ -68,10 +69,10 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; public abstract class AbstractSaveParameterDialog extends CaveJFACEDialog implements DisposeListener { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(AbstractSaveParameterDialog.class); - protected static final int MAX_CONCURRENT_SAVES = 5; + private final int MAX_CONCURRENT_SAVES = 5; protected DataManager dataManager; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/BrightnessDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/BrightnessDialog.java index 0c91a62bc4..fbf540f09b 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/BrightnessDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/BrightnessDialog.java @@ -54,6 +54,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 18, 2010 wldougher Initial creation + * Oct 30, 2012 1298 rferrel Code cleanup for non-blocking dialog. * * * @@ -64,38 +65,38 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; public class BrightnessDialog extends CaveJFACEDialog { // A width hint that keeps part of the title from being cut off - private static final int WIDTH_HINT = 235; + private final int WIDTH_HINT = 235; /** * A label for displaying the scale's value, that moves with the scale thumb */ - protected Label driftingLabel; + private Label driftingLabel; /** * A scale for adjusting brightness. */ - protected Scale scale; + private Scale scale; /** * A text field; an alternate way of changing the brightness. */ - protected Text field; + private Text field; /** * The brightness for the weather element (0-1). */ - protected float brightness; + private float brightness; /** * The brightness value when the dialog is first opened. Used by field * validation code. */ - protected float originalBrightness; + private float originalBrightness; /** * The composite for the main dialog area. */ - protected Composite comp; + private Composite comp; private Parm parm; @@ -104,7 +105,7 @@ public class BrightnessDialog extends CaveJFACEDialog { /** * Multiplier to keep driftingLabel from very ends of the dialog. */ - protected static final float FUDGE_FACTOR = 0.8f; + private final float FUDGE_FACTOR = 0.8f; /** * Constructor. diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ButtonEntryDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ButtonEntryDialog.java deleted file mode 100644 index d29188fb71..0000000000 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ButtonEntryDialog.java +++ /dev/null @@ -1,195 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.gfe.dialogs; - -import java.util.HashMap; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.layout.RowLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Group; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Shell; - -/** - * TODO Add Description - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * May 16, 2012            jdynina     Initial creation
- * 
- * 
- * - * @author jdynina - * @version 1.0 - */ -public class ButtonEntryDialog extends Dialog { - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - private Display display; - - private String dialogTitle; - - private HashMap inputMap; - - private String inputText = ""; - - private String[] selections; - - public ButtonEntryDialog(Shell parentShell, String title, HashMap map) { - super(parentShell, 0); - - this.dialogTitle = title; - this.inputMap = map; - } - - public String open() { - Shell parent = getParent(); - display = parent.getDisplay(); - shell = new Shell(parent, SWT.DIALOG_TRIM); - - if (dialogTitle != null) { - shell.setText(dialogTitle); - } - - // Create the main layout for the shell. - GridLayout mainLayout = new GridLayout(1, false); - shell.setLayout(mainLayout); - - // Initialize data and all of the controls and layouts - initializeComponents(); - - shell.pack(); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - return inputText; - } - - private void initializeComponents() { - createInputControls(); - createBottomButtons(); - } - - private void createInputControls() { - Composite controlComp = new Composite(shell, SWT.NONE); - GridLayout gl = new GridLayout(inputMap.size(), false); - controlComp.setLayout(gl); - GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, true); - controlComp.setLayoutData(gd); - - selections = new String[inputMap.size()]; - - Listener listener = new Listener () { - public void handleEvent(Event event) { - Button button = (Button)event.widget; - if (!button.getSelection()) return; - - int i = 0; - for (String s : inputMap.keySet()) { - for (String value : inputMap.get(s)) { - if ((value == button.getText()) && - (selections[i] != button.getText())) - selections[i] = button.getText(); - } - i++; - } - } - }; - - - int i = 0; - for (String s : inputMap.keySet()) { - int j = 0; - - Group group = new Group(controlComp, SWT.SHADOW_IN); - group.setText(s); - group.setLayout(new RowLayout(SWT.VERTICAL)); - - for (String value : inputMap.get(s)) { - Button button = new Button(group, SWT.RADIO); - button.setText(value); - if (j == 0) button.setSelection(true); - if (j == 0) selections[i] = value; - button.addListener(SWT.Selection, listener); - j++; - } - i++; - } - } - - private void createBottomButtons() { - Composite buttonComp = new Composite(shell, SWT.NONE); - GridLayout gl = new GridLayout(2, false); - buttonComp.setLayout(gl); - GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); - buttonComp.setLayoutData(gd); - - gd = new GridData(SWT.RIGHT, SWT.DEFAULT, true, false); - gd.widthHint = 80; - Button okBtn = new Button(buttonComp, SWT.PUSH); - okBtn.setText("OK"); - okBtn.setLayoutData(gd); - okBtn.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - for (String selection : selections) { - inputText = (inputText + selection + " "); - } - shell.dispose(); - } - }); - - gd = new GridData(SWT.LEFT, SWT.DEFAULT, true, false); - gd.widthHint = 80; - Button cancelBtn = new Button(buttonComp, SWT.PUSH); - cancelBtn.setText("Cancel"); - cancelBtn.setLayoutData(gd); - cancelBtn.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - inputText = null; - shell.dispose(); - } - }); - } -} diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ContourDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ContourDialog.java index 160f167ba6..a027757c7c 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ContourDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ContourDialog.java @@ -34,13 +34,11 @@ import org.eclipse.swt.widgets.Text; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.viz.gfe.Activator; -import com.raytheon.viz.gfe.constants.StatusConstants; import com.raytheon.viz.gfe.core.parm.Parm; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; /** - * TODO Add Description + * Dialog for getting contour intervals. * *
  * 
@@ -48,6 +46,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Jun 5, 2009            randerso     Initial creation
+ * Oct 30, 2012 1298       rferrel     Code cleanup for non-blocking dialog.
  * 
  * 
* @@ -56,9 +55,10 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; */ public class ContourDialog extends CaveJFACEDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(ContourDialog.class); + private final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(ContourDialog.class); - private static final int RESET_ID = IDialogConstants.CLIENT_ID; + private final int RESET_ID = IDialogConstants.CLIENT_ID; private Parm parm; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/DefineRefSetDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/DefineRefSetDialog.java index fe939c7d8e..8cdee68369 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/DefineRefSetDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/DefineRefSetDialog.java @@ -77,6 +77,7 @@ import com.raytheon.viz.gfe.core.wxvalue.WxValue; import com.raytheon.viz.gfe.query.QueryFactory; import com.raytheon.viz.gfe.query.QueryScript; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; +import com.raytheon.viz.ui.dialogs.ICloseCallback; import com.raytheon.viz.ui.widgets.ToggleSelectList; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.MultiPolygon; @@ -93,6 +94,9 @@ import com.vividsolutions.jts.geom.MultiPolygon; * Oct 24, 2012 1287 rferrel Code clean up for non-blocking dialog. * Oct 24, 2012 1287 rferrel Changes for non-blocking SaveDeleteRefDialog. * Oct 24, 2012 1287 rferrel Changes for non-blocking SaveDeleteEditAreaGroupDialog. + * Oct 31, 2012 1298 rferrel Changes for non-blocking MaskDialog. + * Changes for non-blocking WeatherDialog. + * Changes for non-blocking DiscreteDialog. * * * @@ -165,10 +169,10 @@ public class DefineRefSetDialog extends CaveJFACEDialog implements private String[] initialGroups; - private SaveDeleteRefDialog deleteDlg; - - private SaveDeleteRefDialog saveDlg; - + /** + * Modal dialog from the menu so only one can be open at a time. + */ + private CaveJFACEDialog menuModalDlg; private SaveDeleteEditAreaGroupDialog deleteGroupDlg; private SaveDeleteEditAreaGroupDialog saveGroupDlg; @@ -577,11 +581,27 @@ public class DefineRefSetDialog extends CaveJFACEDialog implements } protected void maskCB(Parm parm) { - MaskDialog mask = new MaskDialog(this.getShell(), parm); - mask.setBlockOnOpen(true); - int status = mask.open(); - if (status != IDialogConstants.CANCEL_ID) { - addToQueryField(mask.mask()); + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new MaskDialog(this.getShell(), parm); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof Integer) { + int status = (Integer) returnValue; + if (status != IDialogConstants.CANCEL_ID) { + MaskDialog mask = (MaskDialog) menuModalDlg; + addToQueryField(mask.mask()); + } + } + menuModalDlg = null; + } + }); + menuModalDlg.open(); + } else { + menuModalDlg.bringToTop(); } } @@ -615,20 +635,54 @@ public class DefineRefSetDialog extends CaveJFACEDialog implements protected void wxCB(Parm parm) { if (parm.getGridInfo().getGridType().equals(GridType.WEATHER)) { - WeatherDialog d = new WeatherDialog(this.getShell(), parm); - d.setBlockOnOpen(true); - int status = d.open(); - if (status != IDialogConstants.CANCEL_ID) { - addToQueryField('"' + ((WeatherWxValue) d.getWxValue()) - .getWeatherKey().toString() + '"'); + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new WeatherDialog(this.getShell(), parm); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof Integer) { + int status = (Integer) returnValue; + if (status != IDialogConstants.CANCEL_ID) { + WeatherDialog d = (WeatherDialog) menuModalDlg; + addToQueryField('"' + ((WeatherWxValue) d + .getWxValue()).getWeatherKey() + .toString() + '"'); + } + } + menuModalDlg = null; + } + }); + menuModalDlg.open(); + } else { + menuModalDlg.bringToTop(); } } else { - DiscreteDialog d = new DiscreteDialog(this.getShell(), parm); - d.setBlockOnOpen(true); - int status = d.open(); - if (status != IDialogConstants.CANCEL_ID) { - addToQueryField('"' + ((DiscreteWxValue) d.getDiscreteValue()) - .getDiscreteKey().toString() + '"'); + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new DiscreteDialog(this.getShell(), parm); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof Integer) { + int status = (Integer) returnValue; + if (status != IDialogConstants.CANCEL_ID) { + DiscreteDialog d = (DiscreteDialog) menuModalDlg; + addToQueryField('"' + ((DiscreteWxValue) d + .getDiscreteValue()).getDiscreteKey() + .toString() + '"'); + } + } + menuModalDlg = null; + } + }); + menuModalDlg.open(); + } else { + menuModalDlg.bringToTop(); } } } @@ -1009,52 +1063,52 @@ public class DefineRefSetDialog extends CaveJFACEDialog implements private void saveAreaCB() { - if (saveDlg == null || saveDlg.getShell() == null - || saveDlg.isDisposed()) { - saveDlg = new SaveDeleteRefDialog(getShell(), this.refSetMgr, + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new SaveDeleteRefDialog(getShell(), this.refSetMgr, "Save"); - saveDlg.setBlockOnOpen(false); - saveDlg.open(); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.open(); } else { - saveDlg.bringToTop(); + menuModalDlg.bringToTop(); } } private void deleteAreaCB() { - if (deleteDlg == null || deleteDlg.getShell() == null - || deleteDlg.isDisposed()) { - deleteDlg = new SaveDeleteRefDialog(this.getShell(), refSetMgr, + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new SaveDeleteRefDialog(this.getShell(), refSetMgr, "Delete"); - deleteDlg.setBlockOnOpen(false); - deleteDlg.open(); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.open(); } else { - deleteDlg.bringToTop(); + menuModalDlg.bringToTop(); } } private void saveGroupCB() { - if (deleteGroupDlg == null || deleteGroupDlg.getShell() == null - || deleteGroupDlg.isDisposed()) { - deleteGroupDlg = new SaveDeleteEditAreaGroupDialog(getShell(), + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new SaveDeleteEditAreaGroupDialog(getShell(), this.refSetMgr, "Save"); - deleteGroupDlg.setBlockOnOpen(false); - deleteGroupDlg.open(); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.open(); } else { - deleteGroupDlg.bringToTop(); + menuModalDlg.bringToTop(); } } private void deleteGroupCB() { - if (saveGroupDlg == null || saveGroupDlg.getShell() == null - || saveGroupDlg.isDisposed()) { - saveGroupDlg = new SaveDeleteEditAreaGroupDialog(getShell(), + if (menuModalDlg == null || menuModalDlg.getShell() == null + || menuModalDlg.isDisposed()) { + menuModalDlg = new SaveDeleteEditAreaGroupDialog(getShell(), this.refSetMgr, "Delete"); - saveGroupDlg.setBlockOnOpen(false); - saveGroupDlg.open(); + menuModalDlg.setBlockOnOpen(false); + menuModalDlg.open(); } else { - saveGroupDlg.bringToTop(); + menuModalDlg.bringToTop(); } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EditActionsDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EditActionsDialog.java index 57d87ac4c5..2dea7eb792 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EditActionsDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EditActionsDialog.java @@ -59,6 +59,8 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Feb 18, 2007 njensen Initial creation. * 05Aug2008 #1407 ebabin Dim delta button for wx/discrete types. * Oct 25, 2012 #1287 rferrel Code clean up part of non-blocking dialog. + * Oct 13, 2012 #1298 rferrel Changes for non-blocking SetDeltaDialog. + * Changes for non-blocking SetValueDialog. * * * @author njensen @@ -94,8 +96,6 @@ public class EditActionsDialog extends CaveJFACEDialog implements private IActivatedParmChangedListener parmChanged; - private SetDeltaDialog deltaDialog; - private DataManager dataManager; private Parm parm; @@ -104,8 +104,6 @@ public class EditActionsDialog extends CaveJFACEDialog implements private Button deltaButton; - // private LocalizationFile baseLF; - /** * Constructor * @@ -114,7 +112,7 @@ public class EditActionsDialog extends CaveJFACEDialog implements public EditActionsDialog(Shell parentShell) { super(parentShell); title = "Edit Actions"; - setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE | SWT.RESIZE); + setShellStyle(SWT.DIALOG_TRIM | SWT.MODELESS | SWT.RESIZE); dataManager = DataManager.getCurrentInstance(); parm = dataManager.getSpatialDisplayManager().getActivatedParm(); @@ -327,24 +325,11 @@ public class EditActionsDialog extends CaveJFACEDialog implements } private void showDeltaDialog() { - Shell shell = getParentShell(); - - if (deltaDialog == null) { - deltaDialog = new SetDeltaDialog(shell, dataManager); - deltaDialog.setBlockOnOpen(true); - deltaDialog.open(); - deltaDialog = null; - } - + SetDeltaDialog.openDialog(); } private void showPickupDialog() { - Shell shell = getParentShell(); - - SetValueDialog svd = new SetValueDialog(shell, dataManager); - svd.setBlockOnOpen(false); - svd.open(); - + SetValueDialog.openDialog(); } /* diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EmptyEditAreaWarningDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EmptyEditAreaWarningDialog.java index 736f1d70f3..347e45b74a 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EmptyEditAreaWarningDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/EmptyEditAreaWarningDialog.java @@ -40,6 +40,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Apr 3, 2008 njensen Initial creation + * Nov 7, 2012 1298 rferrel Part of non-blocking made dialog modal. * * * @@ -64,7 +65,7 @@ public class EmptyEditAreaWarningDialog extends CaveJFACEDialog { public EmptyEditAreaWarningDialog(Shell parentShell) { super(parentShell); this.title = "Empty Edit Area Warning"; - this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); } /* diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FormatterLauncherDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FormatterLauncherDialog.java index c9f0f3f5ff..e1850449a5 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FormatterLauncherDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FormatterLauncherDialog.java @@ -73,6 +73,7 @@ import com.raytheon.viz.gfe.dialogs.formatterlauncher.IssuanceSiteIdDlg; import com.raytheon.viz.gfe.dialogs.formatterlauncher.ProductAreaComp; import com.raytheon.viz.gfe.textformatter.TextProductManager; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; +import com.raytheon.viz.ui.dialogs.ICloseCallback; /** * The formatter launcher dialog. @@ -90,6 +91,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Nov 22, 2011 8781 mli remove Processor menu * Jul 26, 2012 15165 ryu Set default db source when formatter has no db defined. * Oct 23, 2012 1287 rferrel Changes for non-blocking dialogs and code clean up. + * Nov 08, 2012 1298 rferrel Changes for non-blocking IssuanceSiteIdDlg. * * * @@ -102,6 +104,8 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(FormatterLauncherDialog.class); + private IssuanceSiteIdDlg issuedByDlg; + private final String BASELINE = "Baseline"; private final String CIVIL_EMERGENCY = "CivilEmergency"; @@ -410,12 +414,24 @@ public class FormatterLauncherDialog extends CaveJFACEDialog implements issuanceSiteMI.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - IssuanceSiteIdDlg issuedByDlg = new IssuanceSiteIdDlg( - FormatterLauncherDialog.this.getShell()); - String issuedBy = textProductMgr.getIssuedBy(); - issuedBy = (String) issuedByDlg.open(issuedBy); - if (issuedBy != null) { - textProductMgr.setIssuedBy(issuedBy.toUpperCase()); + if (issuedByDlg == null || issuedByDlg.getShell() == null + || issuedByDlg.isDisposed()) { + String issuedBy = textProductMgr.getIssuedBy(); + issuedByDlg = new IssuanceSiteIdDlg( + FormatterLauncherDialog.this.getShell(), issuedBy); + issuedByDlg.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof String) { + textProductMgr.setIssuedBy(returnValue + .toString()); + } + } + }); + issuedByDlg.open(); + } else { + issuedByDlg.bringToTop(); } } }); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FuzzValueDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FuzzValueDialog.java index b47048674e..ab03b0c361 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FuzzValueDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/FuzzValueDialog.java @@ -32,6 +32,7 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.core.msgs.IActivatedParmChangedListener; @@ -60,6 +61,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Mar 10, 2008 Eric Babin Initial Creation + * Nov 10, 2012 1298 rferrel Changes for non-blocking dialog. * * * @@ -70,10 +72,6 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; public class FuzzValueDialog extends CaveJFACEDialog implements IDisplayedParmListChangedListener, IActivatedParmChangedListener { - /** - * @param args - */ - private Scale fuzzSlider; private Composite top; @@ -94,9 +92,25 @@ public class FuzzValueDialog extends CaveJFACEDialog implements private DataManager dataManager; - public FuzzValueDialog(Shell parent, DataManager dataManager) { + private static FuzzValueDialog dialog; + + public static void openDialog(DataManager dataManager) { + if (dialog == null || dialog.getShell() == null || dialog.isDisposed()) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + + dialog = new FuzzValueDialog(shell, dataManager); + + dialog.setBlockOnOpen(false); + dialog.open(); + } else { + dialog.bringToTop(); + } + } + + private FuzzValueDialog(Shell parent, DataManager dataManager) { super(parent); - this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.MODELESS); this.dataManager = dataManager; this.parm = dataManager.getSpatialDisplayManager().getActivatedParm(); this.minimum = parm.getGridInfo().getMinValue(); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GFEConfigDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GFEConfigDialog.java index a3d1c885f6..885b065b5e 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GFEConfigDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GFEConfigDialog.java @@ -83,6 +83,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket// Engineer Description * ------------ ---------- ----------- -------------------------- * Apr 30, 2009 randerso Initial creation + * Oct 30, 2012 1298 rferrel Code cleanup for non-blocking dialog. * * * @@ -91,34 +92,33 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; */ public class GFEConfigDialog extends CaveJFACEDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(GFEConfigDialog.class); - private static final String DEFAULT_CONFIG = "gfeConfig"; + private final String DEFAULT_CONFIG = "gfeConfig"; - private static final String LAST_CONFIG = FileUtil.join("gfe", - "lastConfig.txt"); + private final String LAST_CONFIG = FileUtil.join("gfe", "lastConfig.txt"); // Number of votes for Extra Photos - private static final int[][] splashVotes = new int[][] { { 14, 10 }, - { 15, 8 }, { 16, 7 }, { 17, 5 }, { 18, 5 }, { 19, 8 }, { 20, 5 }, - { 21, 7 }, { 22, 7 }, { 23, 5 }, { 24, 6 }, { 25, 9 }, { 26, 6 }, - { 27, 9 }, { 28, 8 } }; + private final int[][] splashVotes = new int[][] { { 14, 10 }, { 15, 8 }, + { 16, 7 }, { 17, 5 }, { 18, 5 }, { 19, 8 }, { 20, 5 }, { 21, 7 }, + { 22, 7 }, { 23, 5 }, { 24, 6 }, { 25, 9 }, { 26, 6 }, { 27, 9 }, + { 28, 8 } }; - private static final int[][] splashDist = new int[splashVotes.length][2]; + private final int[][] splashDist = new int[splashVotes.length][2]; // Percentage of time to show a winner - private static final double winnerThreshold = .65; + private final double winnerThreshold = .65; // Percentage of time to show an extra photo - private static final double extrasThreshold = .30; + private final double extrasThreshold = .30; // The remainder will be developer's choice photos - private static final int totalPics = 45; + private final int totalPics = 45; - private static final int totalVotes; + private final int totalVotes; - static { + { int val = 0; for (int i = 0; i < splashVotes.length; i++) { val += splashVotes[i][1]; @@ -128,7 +128,7 @@ public class GFEConfigDialog extends CaveJFACEDialog { totalVotes = val; } - private static Set usedImages = new HashSet(totalPics); + private Set usedImages = new HashSet(totalPics); private Image image; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GridInfoDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GridInfoDialog.java index c6753c230a..b6c28cce76 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GridInfoDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/GridInfoDialog.java @@ -71,6 +71,7 @@ import com.vividsolutions.jts.geom.Coordinate; * Mar 25, 2008 ebabin Initial creation * Jun 20, 2008 #875 bphillip Implemented Dialog functionality * Sep 20, 2012 #1190 dgilling Use new WsId.getHostName() method. + * Nov 12, 2012 #1298 rferrel Code cleanup for non-blocking dialog. * * * @@ -92,7 +93,7 @@ public class GridInfoDialog extends CaveJFACEDialog implements private Composite top; - private String[] gridInfoElements = { "Grid Info", "Grid History", + private final String[] gridInfoElements = { "Grid Info", "Grid History", "ISC History", "Weather Element Info", "Weather Element State", "Locks", "Data Distribution" }; @@ -102,7 +103,7 @@ public class GridInfoDialog extends CaveJFACEDialog implements public GridInfoDialog(Shell parent, Parm parm, Date clickTime) { super(parent); - this.setShellStyle(SWT.TITLE | SWT.CLOSE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.MODELESS); this.parm = parm; gridData = parm.overlappingGrid(clickTime); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewTextProductDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewTextProductDialog.java index b6e56b4694..fc484e6f12 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewTextProductDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewTextProductDialog.java @@ -45,13 +45,14 @@ import com.raytheon.viz.gfe.textproduct.TextProductUtil; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; /** - * Dialog for the define new text products + * Dialog for the define new text products. * *
  * SOFTWARE HISTORY
  * Date          Ticket#    Engineer    Description
  * ------------  ---------- ----------- --------------------------
  * Sept 25, 2008 1562       askripsky   Initial creation.
+ * Nov 12, 2012  1298       rferrel     Changes for non-blocking dialog.
  * 
* * @author askripsky @@ -62,9 +63,9 @@ public class NewTextProductDialog extends CaveJFACEDialog { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(NewTextProductDialog.class); - public static final int CANCEL_ID = 1; + private final int CANCEL_ID = 1; - public static final int OK_ID = 2; + private final int OK_ID = 2; private String title; @@ -99,7 +100,7 @@ public class NewTextProductDialog extends CaveJFACEDialog { super(parentShell); this.title = title; - this.setShellStyle(SWT.DIALOG_TRIM); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); this.validator = validator; } @@ -289,7 +290,6 @@ public class NewTextProductDialog extends CaveJFACEDialog { private void initNameSelectionEntry() { nameSelectionText = new Text(comp, SWT.BORDER); - // nameSelectionText.setTextLimit(50); nameSelectionText.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, true)); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewToolDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewToolDialog.java index 1cb826164c..bdbb693174 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewToolDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/NewToolDialog.java @@ -41,18 +41,18 @@ import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID; import com.raytheon.uf.common.localization.LocalizationFile; import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.core.parm.Parm; -import com.raytheon.viz.gfe.core.script.NewInputValidator; import com.raytheon.viz.gfe.smarttool.SmartToolEdit; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; /** - * Dialog for creating new smart tools + * Dialog for creating new smart tools. * *
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Feb 20, 2008            njensen     Initial creation
+ * Nov 12, 2012 1298       rferrel     Changes for non-blocking dialog.
  * 
  * 
* @@ -74,6 +74,7 @@ public class NewToolDialog extends CaveJFACEDialog { super(aShell); title = aTitle; this.validator = validator; + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); } /* @@ -133,13 +134,9 @@ public class NewToolDialog extends CaveJFACEDialog { @Override protected void createButtonsForButtonBar(Composite parent) { - // okButton = createButton(parent, IDialogConstants.OK_ID, - // IDialogConstants.OK_LABEL, true); createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL, true); - // cancelButton = createButton(parent, IDialogConstants.CANCEL_ID, - // IDialogConstants.CANCEL_LABEL, false); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @@ -164,8 +161,6 @@ public class NewToolDialog extends CaveJFACEDialog { top.setLayoutData(new GridData(SWT.FILL, SWT.NONE, true, false)); Label label = new Label(top, SWT.NONE); - // label.setLayoutData(new GridData(SWT.BEGINNING, SWT.CENTER, false, - // false)); label.setText("Name"); text = new Text(top, SWT.BORDER); @@ -193,22 +188,6 @@ public class NewToolDialog extends CaveJFACEDialog { parms.setSelection(0); } - // Group typeGroup = new Group(comp, SWT.BORDER); - // typeGroup.setText("Tool Type:"); - // - // Button numericButton = new Button(typeGroup, SWT.RADIO); - // numericButton.setText("numeric"); - // numericButton.setLayoutData(new GridData(SWT.BEGINNING, - // SWT.BEGINNING, - // false, false)); - // numericButton.setBounds(10, 20, 120, 30); - // - // Button pointButton = new Button(typeGroup, SWT.RADIO); - // pointButton.setText("point-based"); - // pointButton.setBounds(10, 50, 120, 30); - // - // typeGroup.pack(); - applyDialogFont(composite); return composite; } @@ -237,12 +216,4 @@ public class NewToolDialog extends CaveJFACEDialog { private boolean isInputValid() { return (validator.isValid(text.getText()) == null); } - - public static void main(String[] args) { - Shell shell = new Shell(SWT.DIALOG_TRIM); - NewToolDialog d = new NewToolDialog(shell, "MyTool", - new NewInputValidator()); - d.open(); - } - } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ProductScriptsDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ProductScriptsDialog.java index 1470da1644..9b7d4e0fb7 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ProductScriptsDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/ProductScriptsDialog.java @@ -65,6 +65,7 @@ import com.raytheon.viz.ui.widgets.ToggleSelectList; * Mar 7, 2008 Eric Babin Initial Creation * Oct 27, 2012 1287 rferrel Code cleanup for non-blocking dialog. * Oct 25, 2012 1287 rferrel Code changes for non-blocking PublishDialog. + * Nov 13, 2012 1298 rferrel Code changes for non-blocking UserEntryDialog. * * * @@ -318,16 +319,22 @@ public class ProductScriptsDialog extends CaveJFACEDialog { String[] entry = cmd.substring(entryIdx + 1, endEntryIdx) .split(":"); String configFile = entry[2]; + // The dialog being opened is modal to the parent dialog. + // This will prevent the launching of another dialog until + // the modal dialog is closed. + + // Keep this a blocking dialog so the loop will only display + // one dialog at a time. UserEntryDialog entryDlg = new UserEntryDialog( this.getShell(), entry[1] + " Entry", entry[1] + ":", entry[2]); - String returnMsg = entryDlg.open(); + Object returnMsg = entryDlg.open(); if (returnMsg == null) { // cancel pressed run = false; continue; } - configFile = returnMsg; + configFile = returnMsg.toString(); cmd = cmd.substring(0, entryIdx) + configFile + cmd.substring(endEntryIdx + 1); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetDeltaDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetDeltaDialog.java index fce8c1d718..fb6f886341 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetDeltaDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetDeltaDialog.java @@ -31,6 +31,7 @@ import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Scale; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; +import org.eclipse.ui.PlatformUI; import com.raytheon.viz.gfe.Activator; import com.raytheon.viz.gfe.core.DataManager; @@ -42,7 +43,7 @@ import com.raytheon.viz.gfe.smarttool.SmartUtil; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; /** - * TODO Add Description + * Dialog to adjust a grid's delta value. * *
  * 
@@ -51,6 +52,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Sep 16, 2011            dgilling     Initial creation
+ * Nov 13, 2012 1298       rferrel     Code clean up for non-blocking dialog.
  * 
  * 
* @@ -61,9 +63,11 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; public class SetDeltaDialog extends CaveJFACEDialog implements IDisplayedParmListChangedListener, IActivatedParmChangedListener { - private final static int ADJUST_DOWN = 97; + private static SetDeltaDialog dialog; - private final static int ADJUST_UP = 98; + private final int ADJUST_DOWN = 97; + + private final int ADJUST_UP = 98; private DataManager dataManager; @@ -79,8 +83,6 @@ public class SetDeltaDialog extends CaveJFACEDialog implements private Text entryField; - private int returnCode = IDialogConstants.CANCEL_ID; - private float origValue; private float res; @@ -117,7 +119,27 @@ public class SetDeltaDialog extends CaveJFACEDialog implements } }; - public SetDeltaDialog(Shell parent, DataManager dataManager) { + /** + * Allow only one instance of the dialog to exist at any given time. + */ + public static void openDialog() { + if (dialog == null) { + Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + DataManager dataManager = DataManager.getCurrentInstance(); + dialog = new SetDeltaDialog(parent, dataManager); + dialog.setBlockOnOpen(false); + } + dialog.open(); + } + + /** + * Private use the static method openDialog. + * + * @param parent + * @param dataManager + */ + private SetDeltaDialog(Shell parent, DataManager dataManager) { super(parent); this.setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE); this.dataManager = dataManager; @@ -142,7 +164,7 @@ public class SetDeltaDialog extends CaveJFACEDialog implements */ @Override protected void buttonPressed(int buttonId) { - returnCode = buttonId; + setReturnCode(buttonId); if (buttonId == ADJUST_UP) { setNewDelta(); SmartUtil.runTool(SmartToolConstants.ADJUST_UP); @@ -154,16 +176,6 @@ public class SetDeltaDialog extends CaveJFACEDialog implements } } - /* - * (non-Javadoc) - * - * @see org.eclipse.jface.window.Window#getReturnCode() - */ - @Override - public int getReturnCode() { - return returnCode; - } - /* * (non-Javadoc) * @@ -268,6 +280,7 @@ public class SetDeltaDialog extends CaveJFACEDialog implements this); dataManager.getSpatialDisplayManager() .removeActivatedParmChangedListener(this); + SetDeltaDialog.dialog = null; return super.close(); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetValueDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetValueDialog.java index 2a681d9e5e..bcaa129ea4 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetValueDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/SetValueDialog.java @@ -33,6 +33,7 @@ import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Monitor; import org.eclipse.swt.widgets.Shell; +import org.eclipse.ui.PlatformUI; import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord.GridType; import com.raytheon.viz.gfe.core.DataManager; @@ -52,6 +53,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jun 18, 2009 #1318 randerso Ported AWIPS I pickup value dialogs + * Nov 13, 2012 #1298 rferrel Changes for non-blocking dialog. * * * @@ -62,9 +64,11 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; public class SetValueDialog extends CaveJFACEDialog implements IDisplayedParmListChangedListener, IActivatedParmChangedListener { - private static final int DISMISS_ID = IDialogConstants.CLIENT_ID + 1; + private static SetValueDialog dialog; - private static final int ASSIGN_ID = IDialogConstants.CLIENT_ID + 0; + private final int DISMISS_ID = IDialogConstants.CLIENT_ID + 1; + + private final int ASSIGN_ID = IDialogConstants.CLIENT_ID + 0; private DataManager dataManager; @@ -78,15 +82,26 @@ public class SetValueDialog extends CaveJFACEDialog implements private Composite valueFrame; + public static void openDialog() { + if (dialog == null) { + Shell parent = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + DataManager dataManager = DataManager.getCurrentInstance(); + dialog = new SetValueDialog(parent, dataManager); + dialog.setBlockOnOpen(false); + } + dialog.open(); + } + /** - * Constructor + * Constructor is private use openDialog * * @param parentShell * parent shell * @param dataManager * DataManager for the associated window */ - public SetValueDialog(Shell parentShell, DataManager dataManager) { + private SetValueDialog(Shell parentShell, DataManager dataManager) { super(parentShell); this.dataManager = dataManager; @@ -191,6 +206,8 @@ public class SetValueDialog extends CaveJFACEDialog implements setValue = null; } + SetValueDialog.dialog = null; + return super.close(); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeRangeWarningDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeRangeWarningDialog.java index 8d02bb6dde..6b6c765335 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeRangeWarningDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeRangeWarningDialog.java @@ -40,6 +40,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Dec 1, 2009 1426 ryu Initial creation + * Nov 7, 2012 1298 rferrel Part of non-blocking made dialog modal. * * * @@ -63,7 +64,7 @@ public class TimeRangeWarningDialog extends CaveJFACEDialog { public TimeRangeWarningDialog(Shell parentShell) { super(parentShell); this.title = "Time Range Warning"; - this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); } /* diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeShiftDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeShiftDialog.java index 7c208db479..46d9f1cffa 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeShiftDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/TimeShiftDialog.java @@ -29,9 +29,13 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Group; +import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import com.raytheon.edex.util.MathUtil; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.core.parm.Parm; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; @@ -45,6 +49,7 @@ import com.raytheon.viz.ui.widgets.LabeledScale; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Feb 26, 2008 Eric Babin Initial Creation + * Oct 30, 2012 1298 rferrel Code clean up for non-blocking dialog. * * * @@ -53,7 +58,10 @@ import com.raytheon.viz.ui.widgets.LabeledScale; */ public class TimeShiftDialog extends CaveJFACEDialog { - private static final int SECONDS_PER_HOUR = 3600; + private final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(TimeShiftDialog.class); + + private final int SECONDS_PER_HOUR = 3600; private Composite top; @@ -69,15 +77,22 @@ public class TimeShiftDialog extends CaveJFACEDialog { public TimeShiftDialog(Shell parent, DataManager dataManager) { super(parent); - this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.MODELESS); this.dataManager = dataManager; } @Override protected Control createDialogArea(Composite parent) { top = (Composite) super.createDialogArea(parent); - - initializeComponents(); + Parm[] parms = this.dataManager.getParmManager().getSelectedParms(); + if (parms == null || parms.length == 0) { + Label label = new Label(top, SWT.CENTER); + GridData gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); + label.setLayoutData(gd); + label.setText("No Grids selected."); + } else { + initializeComponents(); + } return top; } @@ -167,14 +182,18 @@ public class TimeShiftDialog extends CaveJFACEDialog { */ @Override protected void okPressed() { - // Tell the dataManager about the time shift - // LogStream.logUse("Time Shift", selection, self.__secondsToShift) - int secondsToShift = (int) formatter.getScaledValue(intervalScale - .getSelection()) - * SECONDS_PER_HOUR; - this.dataManager.getParmOp().timeShift(secondsToShift, - copyButton.getSelection()); - + if (formatter != null) { + // Tell the dataManager about the time shift + int secondsToShift = (int) formatter.getScaledValue(intervalScale + .getSelection()) * SECONDS_PER_HOUR; + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.handle(Priority.DEBUG, + "Time Shift " + copyButton.getSelection() + " " + + secondsToShift); + } + this.dataManager.getParmOp().timeShift(secondsToShift, + copyButton.getSelection()); + } super.okPressed(); } @@ -201,13 +220,6 @@ public class TimeShiftDialog extends CaveJFACEDialog { return (number + offset) * scale; } - /** - * @return the offset - */ - public int getOffset() { - return offset; - } - /** * @param offset * the offset to set @@ -216,13 +228,6 @@ public class TimeShiftDialog extends CaveJFACEDialog { this.offset = offset; } - /** - * @return the scale - */ - public int getScale() { - return scale; - } - /** * @param scale * the scale to set diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/UserEntryDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/UserEntryDialog.java index d615b1128d..2f39d93013 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/UserEntryDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/UserEntryDialog.java @@ -26,14 +26,14 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; + /** - * TODO Add Description + * Dialog to get user text. * *
  * 
@@ -41,24 +41,14 @@ import org.eclipse.swt.widgets.Text;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Mar 16, 2010            lvenable     Initial creation
+ * Nov 14, 2012 1298       rferrel     Convert to CaveSWTDialog for non-blocking.
  * 
  * 
* * @author lvenable * @version 1.0 */ -public class UserEntryDialog extends Dialog { - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - private Display display; - - private String dialogTitle; +public class UserEntryDialog extends CaveSWTDialog { private String message; @@ -68,21 +58,18 @@ public class UserEntryDialog extends Dialog { public UserEntryDialog(Shell parentShell, String title, String message, String defaultText) { - super(parentShell, 0); + super(parentShell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL, CAVE.NONE); + + if (title != null) { + setText(title); + } - this.dialogTitle = title; this.message = message; this.inputText = defaultText; } - public String open() { - Shell parent = getParent(); - display = parent.getDisplay(); - shell = new Shell(parent, SWT.DIALOG_TRIM); - - if (dialogTitle != null) { - shell.setText(dialogTitle); - } + @Override + protected void initializeComponents(Shell shell) { // Create the main layout for the shell. GridLayout mainLayout = new GridLayout(1, false); @@ -90,17 +77,6 @@ public class UserEntryDialog extends Dialog { // Initialize data and all of the controls and layouts initializeComponents(); - - shell.pack(); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - return inputText; } private void initializeComponents() { @@ -127,7 +103,7 @@ public class UserEntryDialog extends Dialog { inputTF = new Text(controlComp, SWT.BORDER); inputTF.setLayoutData(gd); - if (this.inputText != null) { + if (inputText != null) { inputTF.setText(inputText); } } @@ -147,8 +123,9 @@ public class UserEntryDialog extends Dialog { okBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - inputText = inputTF.getText().trim(); - shell.dispose(); + String inputText = inputTF.getText().trim(); + setReturnValue(inputText); + close(); } }); @@ -160,8 +137,8 @@ public class UserEntryDialog extends Dialog { cancelBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - inputText = null; - shell.dispose(); + setReturnValue(null); + close(); } }); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementBrowserDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementBrowserDialog.java index ecf249623b..c94f0522c4 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementBrowserDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementBrowserDialog.java @@ -54,6 +54,7 @@ import com.raytheon.viz.core.mode.CAVEMode; import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.core.parm.Parm; import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; +import com.raytheon.viz.ui.dialogs.ICloseCallback; import com.raytheon.viz.ui.widgets.ToggleSelectList; /** @@ -72,6 +73,8 @@ import com.raytheon.viz.ui.widgets.ToggleSelectList; * 09/12/2012 #1117 dgilling Revert previous changes, retrieve * database list from ParmManager * not EDEX. + * 10/30/2012 1298 rferrel Code clean up non-blocking dialog. + * Changes for non-blocking WeatherElementGroupDialog. * * * @author ebabin @@ -109,9 +112,9 @@ public class WeatherElementBrowserDialog extends CaveJFACEDialog { private ParmID[] currentDisplayedParms; - private static final Point size = new Point(603, 778); + private final Point size = new Point(603, 778); - private static final String IFP = "IFP"; + private final String IFP = "IFP"; /** * Constructor @@ -197,33 +200,49 @@ public class WeatherElementBrowserDialog extends CaveJFACEDialog { /** * Show the save weather element dialog. */ - private void showSaveWeatherElementGroup(Menu loadWeatherElementGroupMenu) { - - WeatherElementGroupDialog dialog = new WeatherElementGroupDialog( + private void showSaveWeatherElementGroup( + final Menu loadWeatherElementGroupMenu) { + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. + final WeatherElementGroupDialog dialog = new WeatherElementGroupDialog( getShell(), dataManager, true); - dialog.setBlockOnOpen(true); + dialog.setBlockOnOpen(false); + dialog.setCloseCallback(new ICloseCallback() { + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof Integer) { + int returnCode = (Integer) returnValue; + if (returnCode == Window.OK) { + String groupName = dialog.getSelectedItem(); + doSaveWeatherElementGroup(loadWeatherElementGroupMenu, + groupName); + } + } + } + }); dialog.open(); - if (dialog.getReturnCode() == Window.OK) { - String groupName = dialog.getSelectedItem(); - if (groupName != null) { - ParmID[] selectedParmIds = getSelectedParmIDS(); - if ((selectedParmIds != null) && (selectedParmIds.length > 0)) { - ParmID[] availIds = selectedType.getPossibleParmIDs(); - if ((availIds != null) && (availIds.length != 0)) { - dataManager.getWEGroupManager().save(groupName, - selectedParmIds, availIds); - boolean alreadyListed = false; - for (MenuItem item : loadWeatherElementGroupMenu - .getItems()) { - if (item.getText().equals(groupName)) { - alreadyListed = true; - } - } - if (!alreadyListed) { - addWEGroup(loadWeatherElementGroupMenu, groupName); + } + + private void doSaveWeatherElementGroup(Menu loadWeatherElementGroupMenu, + String groupName) { + if (groupName != null) { + ParmID[] selectedParmIds = getSelectedParmIDS(); + if ((selectedParmIds != null) && (selectedParmIds.length > 0)) { + ParmID[] availIds = selectedType.getPossibleParmIDs(); + if ((availIds != null) && (availIds.length != 0)) { + dataManager.getWEGroupManager().save(groupName, + selectedParmIds, availIds); + boolean alreadyListed = false; + for (MenuItem item : loadWeatherElementGroupMenu.getItems()) { + if (item.getText().equals(groupName)) { + alreadyListed = true; } } + if (!alreadyListed) { + addWEGroup(loadWeatherElementGroupMenu, groupName); + } } } } @@ -232,22 +251,36 @@ public class WeatherElementBrowserDialog extends CaveJFACEDialog { /** * Show delete weather element dialog. */ - private void showDeleteWeatherElementGroup(Menu loadWeatherElementGroupMenu) { + private void showDeleteWeatherElementGroup( + final Menu loadWeatherElementGroupMenu) { + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. final WeatherElementGroupDialog dialog = new WeatherElementGroupDialog( getShell(), this.dataManager, false); - dialog.setBlockOnOpen(true); - dialog.open(); - if ((dialog.getReturnCode() == Window.OK) - && (dialog.getSelectedItem() != null)) { - String groupName = dialog.getSelectedItem(); - // we may have just overridden a site or base level group, need to - // verify menu item can be deleted - if (dataManager.getWEGroupManager().remove(groupName) - && !dataManager.getWEGroupManager().getInventory() - .contains(groupName)) { - removeWEGroup(loadWeatherElementGroupMenu, groupName); + dialog.setBlockOnOpen(false); + dialog.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof Integer) { + int returnCode = (Integer) returnValue; + if (returnCode == Window.OK + && dialog.getSelectedItem() != null) { + String groupName = dialog.getSelectedItem(); + // we may have just overridden a site or base level + // group, need to verify menu item can be deleted + if (dataManager.getWEGroupManager().remove(groupName) + && !dataManager.getWEGroupManager() + .getInventory().contains(groupName)) { + removeWEGroup(loadWeatherElementGroupMenu, + groupName); + } + } + } } - } + }); + dialog.open(); } /** diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementGroupDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementGroupDialog.java index 65514e0af0..20e4ac8abd 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementGroupDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/WeatherElementGroupDialog.java @@ -20,6 +20,7 @@ package com.raytheon.viz.gfe.dialogs; import java.util.ArrayList; +import java.util.Arrays; import org.eclipse.jface.dialogs.IDialogConstants; import org.eclipse.swt.SWT; @@ -29,8 +30,10 @@ import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; @@ -53,8 +56,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * ------------ ---------- ----------- -------------------------- * 02/22/2008 Eric Babin Initial Creation * 04/17/2009 #2282 rjpeter Added confirmation message on delete. - * 11/20/2012 DR 15532 jzeng Added popup dialog to make sure group saved with - * valid characters + * 11/14/2012 #1298 rferrel Changes for non-blocking dialog. * * * @author ebabin @@ -62,7 +64,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; */ public class WeatherElementGroupDialog extends CaveJFACEDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(WeatherElementGroupDialog.class); private Composite top; @@ -77,6 +79,8 @@ public class WeatherElementGroupDialog extends CaveJFACEDialog { private Text groupField; + private Button okButton; + private String selectedItem; private DataManager dataManager; @@ -86,9 +90,11 @@ public class WeatherElementGroupDialog extends CaveJFACEDialog { public WeatherElementGroupDialog(Shell parent, DataManager dataManager, boolean saveType) { super(parent); + setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); this.dataManager = dataManager; this.wegManager = this.dataManager.getWEGroupManager(); this.saveType = saveType; + this.selectedItem = ""; this.names = new ArrayList(); this.protectedNames = new ArrayList(); @@ -121,6 +127,12 @@ public class WeatherElementGroupDialog extends CaveJFACEDialog { private void initializeComponents() { + if (names.size() == 0 && !saveType) { + Label label = new Label(top, SWT.CENTER); + label.setText("No groups available for deletion."); + return; + } + GridData data = new GridData(GridData.FILL_BOTH); groupList = new List(top, SWT.BORDER | SWT.SINGLE); @@ -137,16 +149,21 @@ public class WeatherElementGroupDialog extends CaveJFACEDialog { } } }); - groupList.setItems(names.toArray(new String[names.size()])); + + String[] items = names.toArray(new String[names.size()]); + Arrays.sort(items); + groupList.setItems(items); groupList.setSelection(0); groupList.deselectAll(); groupList.setLayoutData(data); groupField = new Text(top, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); groupField.setLayoutData(data); + groupField.setEnabled(saveType); groupField.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent arg0) { - selectedItem = groupField.getText(); + selectedItem = groupField.getText().trim(); + okButton.setEnabled(selectedItem.length() > 0); } }); @@ -179,7 +196,8 @@ public class WeatherElementGroupDialog extends CaveJFACEDialog { } else { label = "Delete"; } - createButton(parent, IDialogConstants.OK_ID, label, true); + okButton = createButton(parent, IDialogConstants.OK_ID, label, true); + okButton.setEnabled(false); createButton(parent, IDialogConstants.CANCEL_ID, IDialogConstants.CANCEL_LABEL, false); } @@ -196,49 +214,28 @@ public class WeatherElementGroupDialog extends CaveJFACEDialog { protected void okPressed() { boolean ok = true; String groupName = getSelectedItem(); - - if (!saveType) { - if (!FileUtil.isValidFilename(groupName)) { - MessageBox mb = new MessageBox(super.getShell(), SWT.ICON_ERROR - | SWT.OK); - mb.setText("Invalid Group Name"); - mb.setMessage("Group name may only contain the following characters: " - + FileUtil.VALID_FILENAME_CHARS); - ok = false; - } else if (!protectedNames.contains(groupName) - && names.contains(groupName)) { - MessageBox mb = new MessageBox(super.getShell(), - SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL); - mb.setText("Item Delete"); - mb.setMessage(getSelectedItem() + " will be Deleted."); - if (mb.open() == SWT.CANCEL) { - ok = false; - } - } else { - statusHandler.handle(Priority.SIGNIFICANT, - "Weather Element Group " + groupName - + " is protected or an invalid name."); + if (!FileUtil.isValidFilename(groupName)) { + MessageBox mb = new MessageBox(super.getShell(), SWT.ICON_ERROR + | SWT.OK); + mb.setText("Invalid Group Name"); + mb.setMessage("Group name may only contain the following characters: " + + FileUtil.VALID_FILENAME_CHARS); + mb.open(); + ok = false; + } else if (protectedNames.contains(groupName)) { + statusHandler.handle(Priority.SIGNIFICANT, "Weather Element Group " + + getSelectedItem() + " is protected or an invalid name."); + ok = false; + } else if (!saveType) { + MessageBox mb = new MessageBox(super.getShell(), SWT.ICON_QUESTION + | SWT.OK | SWT.CANCEL); + mb.setText("Item Delete"); + mb.setMessage(getSelectedItem() + " will be Deleted."); + + if (mb.open() == SWT.CANCEL) { ok = false; } - } else { - if (protectedNames.contains(getSelectedItem())) { - statusHandler.handle(Priority.SIGNIFICANT, - "Weather Element Group " + getSelectedItem() - + " is protected or an invalid name."); - ok = false; - } - - if (!FileUtil.isValidFilename(groupName)) { - MessageBox mb = new MessageBox(super.getShell(), SWT.ICON_ERROR - | SWT.OK); - mb.setText("Invalid Group Name"); - mb.setMessage("Group name may only contain the following characters: " - + FileUtil.VALID_FILENAME_CHARS); - mb.open(); - ok = false; - } - } if (ok) { diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/CallToActionsDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/CallToActionsDlg.java index c157190992..41f729df1a 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/CallToActionsDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/CallToActionsDlg.java @@ -36,7 +36,6 @@ import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Shell; -import com.raytheon.uf.common.dataplugin.gfe.StatusConstants; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -52,6 +51,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 12 JAN 2010 DR3463 RT Initial creation + * 07 Nov 2012 1298 rferrel Changes for non-blocking dialog. * * * @@ -60,9 +60,10 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * */ public class CallToActionsDlg extends CaveJFACEDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(CallToActionsDlg.class); + private final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(CallToActionsDlg.class); - private static String psplitRE = "\n\\s*?(?:\n\\s*?)+"; + private final String psplitRE = "\n\\s*?(?:\n\\s*?)+"; /** * Composite containing the Product Editor controls. @@ -86,7 +87,7 @@ public class CallToActionsDlg extends CaveJFACEDialog { String[] CtaText, ProductEditorComp productEditorComp) { super(parent); - this.setShellStyle(SWT.RESIZE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.RESIZE | SWT.APPLICATION_MODAL); this.callToActionType = callToActionType; this.txt = CtaText; this.productEditorComp = productEditorComp; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/FindReplaceDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/FindReplaceDlg.java index 029193ca88..0824869d72 100755 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/FindReplaceDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/FindReplaceDlg.java @@ -36,8 +36,6 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; @@ -46,6 +44,7 @@ import org.eclipse.swt.widgets.Text; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; /** * Display the Find and/or Replace dialog. @@ -66,25 +65,10 @@ import com.raytheon.uf.common.status.UFStatus.Priority; * @version 1.0 * */ -public class FindReplaceDlg extends Dialog { - private static final transient IUFStatusHandler statusHandler = UFStatus +public class FindReplaceDlg extends CaveSWTDialog { + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(FindReplaceDlg.class); - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - private Display display; - - /** - * Return object when the shell is disposed. - */ - private String returnObj = null; - /** * Flag indicating if the dialog should display the replace controls. */ @@ -194,7 +178,8 @@ public class FindReplaceDlg extends Dialog { */ public FindReplaceDlg(Shell parent, boolean findAndReplace, StyledTextComp editorComp) { - super(parent, 0); + super(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL, + CAVE.DO_NOT_BLOCK); this.findAndReplace = findAndReplace; this.editorComp = editorComp; @@ -202,15 +187,8 @@ public class FindReplaceDlg extends Dialog { this.searchOptions = EnumSet.noneOf(FindReplaceOptions.class); } - /** - * Setup and open the dialog. - * - * @return Return object. - */ - public Object open() { - Shell parent = getParent(); - display = parent.getDisplay(); - shell = new Shell(parent, SWT.DIALOG_TRIM); + @Override + protected void initializeComponents(Shell shell) { if (findAndReplace == true) { shell.setText("Find & Replace"); @@ -227,17 +205,6 @@ public class FindReplaceDlg extends Dialog { // Initialize all of the controls and layouts initializeComponents(); - - shell.pack(); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - return returnObj; } /** @@ -253,8 +220,7 @@ public class FindReplaceDlg extends Dialog { */ private void createMainControls() { Composite mainComp = new Composite(shell, SWT.NONE); - mainComp - .setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); + mainComp.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); mainComp.setLayout(new GridLayout(1, false)); createFindTextControl(mainComp); @@ -277,8 +243,7 @@ public class FindReplaceDlg extends Dialog { */ private void createFindTextControl(Composite mainComp) { Composite findComp = new Composite(mainComp, SWT.NONE); - findComp - .setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); + findComp.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); findComp.setLayout(new GridLayout(2, false)); Label findLbl = new Label(findComp, SWT.NONE); @@ -304,8 +269,7 @@ public class FindReplaceDlg extends Dialog { */ private void createDirectionControls(Composite mainComp) { Group dirGroup = new Group(mainComp, SWT.NONE); - dirGroup - .setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); + dirGroup.setLayoutData(new GridData(SWT.FILL, SWT.DEFAULT, true, false)); dirGroup.setLayout(new GridLayout(2, false)); dirGroup.setText(" Search Direction: "); @@ -550,8 +514,8 @@ public class FindReplaceDlg extends Dialog { cancelBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - returnObj = null; - shell.dispose(); + setReturnValue(null); + close(); } }); } @@ -638,8 +602,8 @@ public class FindReplaceDlg extends Dialog { .getSelectionRange())) { String replaceString = replaceTF.getText(); - editorST.replaceTextRange(selectionToBeReplaced.x, searchString - .length(), replaceString); + editorST.replaceTextRange(selectionToBeReplaced.x, + searchString.length(), replaceString); int[] replaceMatch = findString(replaceString, selectionToBeReplaced.x); @@ -689,7 +653,7 @@ public class FindReplaceDlg extends Dialog { readyToReplace = findAndSelectString(findTF.getText()); selectionToBeReplaced = editorST.getSelectionRange(); - + } /** diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/IssuanceSiteIdDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/IssuanceSiteIdDlg.java index 54d355d5ba..4e17c62745 100755 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/IssuanceSiteIdDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/IssuanceSiteIdDlg.java @@ -24,16 +24,18 @@ import org.eclipse.swt.events.KeyAdapter; import org.eclipse.swt.events.KeyEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.events.VerifyEvent; +import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; + /** * Display the Issuance Site ID dialog. * @@ -43,6 +45,7 @@ import org.eclipse.swt.widgets.Text; * ------------ ---------- ----------- -------------------------- * 18 APR 2008 ### lvenable Initial creation * Jan 18 2010 3395 ryu Fix "issued by" functionality + * Nov 08 2012 1298 rferrel Changes for non-blocking dialog. * * * @@ -50,21 +53,7 @@ import org.eclipse.swt.widgets.Text; * @version 1.0 * */ -public class IssuanceSiteIdDlg extends Dialog { - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - private Display display; - - /** - * Return object when the shell is disposed. - */ - private String returnObj = null; +public class IssuanceSiteIdDlg extends CaveSWTDialog { /** * Site ID text control. @@ -76,28 +65,21 @@ public class IssuanceSiteIdDlg extends Dialog { */ private Button okBtn; + private String issuedBy; + /** * Constructor. * * @param parent * Parent Shell. */ - public IssuanceSiteIdDlg(Shell parent) { - super(parent, 0); + public IssuanceSiteIdDlg(Shell parent, String issuedBy) { + super(parent, SWT.DIALOG_TRIM, CAVE.DO_NOT_BLOCK); + this.issuedBy = issuedBy; } - /** - * Setup and open the dialog. - * - * @param issuedBy - * Initial value for text field. - * @return Return object. - */ - public Object open(String issuedBy) { - Shell parent = getParent(); - display = parent.getDisplay(); - shell = new Shell(parent, SWT.DIALOG_TRIM); - shell.setText("Issuance Site ID"); + @Override + protected void initializeComponents(Shell shell) { // Create the main layout for the shell. GridLayout mainLayout = new GridLayout(1, false); @@ -108,22 +90,19 @@ public class IssuanceSiteIdDlg extends Dialog { // Initialize all of the controls and layouts initializeComponents(); - + + } + + @Override + protected void preOpened() { + super.preOpened(); + shell.setText("Issuance Site ID"); siteIdTF.insert(issuedBy); if (issuedBy.length() == 0 || issuedBy.length() == 3) { okBtn.setEnabled(true); } - - shell.pack(); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - return returnObj; + siteIdTF.forceFocus(); + siteIdTF.selectAll(); } /** @@ -150,20 +129,23 @@ public class IssuanceSiteIdDlg extends Dialog { siteIdTF.setTextLimit(3); siteIdTF.setLayoutData(gd); siteIdTF.addKeyListener(new KeyAdapter() { - @Override - public void keyPressed(KeyEvent ke) { - } - @Override public void keyReleased(KeyEvent ke) { - if (siteIdTF.getText().length() > 0 && - siteIdTF.getText().length() < 3) { + if (siteIdTF.getText().length() > 0 + && siteIdTF.getText().length() < 3) { okBtn.setEnabled(false); } else { okBtn.setEnabled(true); } } }); + siteIdTF.addVerifyListener(new VerifyListener() { + + @Override + public void verifyText(VerifyEvent e) { + e.text = e.text.trim().toUpperCase(); + } + }); } /** @@ -188,8 +170,8 @@ public class IssuanceSiteIdDlg extends Dialog { okBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - returnObj = siteIdTF.getText(); - shell.dispose(); + setReturnValue(siteIdTF.getText()); + close(); } }); @@ -200,8 +182,8 @@ public class IssuanceSiteIdDlg extends Dialog { cancelBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - returnObj = null; - shell.dispose(); + setReturnValue(null); + close(); } }); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ProductEditorComp.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ProductEditorComp.java index 84cc8ae5ac..53665be285 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ProductEditorComp.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ProductEditorComp.java @@ -116,6 +116,7 @@ import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.dialogs.formatterlauncher.ConfigData.productStateEnum; import com.raytheon.viz.gfe.product.ProductFileUtil; import com.raytheon.viz.gfe.product.TextDBUtil; +import com.raytheon.viz.ui.dialogs.ICloseCallback; /** * Composite containing the product editor controls. @@ -137,7 +138,11 @@ import com.raytheon.viz.gfe.product.TextDBUtil; * 21 SEP 2010 5817 jnjanga Fix attribution phrase append from issuance to issuance. * 27 OCT 2010 5817 jnjanga Fix N.P.E caused when call getVTECActionCodes on non VTEC products. * 31 AUG 2012 15178 mli Add autoWrite and autoStore capability - * 31 AUG 2012 15037 mli Handle bad characters in text formatter definition + * 31 AUG 2012 15037 mli Handle bad characters in text formatter definition + * 07 Nov 2012 1298 rferrel Changes for non-blocking CallToActionsDlg. + * Changes for non-blocking FindReplaceDlg. + * Changes for non-blocking StoreTransmitDlg. + * Changes for non-blocking WrapLengthDialog. * * * @@ -147,10 +152,10 @@ import com.raytheon.viz.gfe.product.TextDBUtil; */ public class ProductEditorComp extends Composite implements INotificationObserver { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(ProductEditorComp.class); - private static final String EMPTY = ""; + private final String EMPTY = ""; /** * Parent composite. @@ -296,27 +301,27 @@ public class ProductEditorComp extends Composite implements private String autoSendAddress; - private String longLocalFmtStr = "hmm a z EEE MMM d yyyy"; + private final String longLocalFmtStr = "hmm a z EEE MMM d yyyy"; - private TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT"); + private final TimeZone gmtTimeZone = TimeZone.getTimeZone("GMT"); - private int initialYear = year(SimulatedTime.getSystemTime().getTime()); + private final int initialYear = year(SimulatedTime.getSystemTime() + .getTime()); // for CTA dialogs private String phenSig = null; private boolean HazardCTA = false; - private boolean ProductCTA = false; - - private boolean GenericCTA = false; + private CallToActionsDlg ctaDialog; private ProductDataStruct prodDataStruct; private TimeZone localTimeZone; - + private enum Action { - STORE, TRANSMIT, AUTOSTORE }; + STORE, TRANSMIT, AUTOSTORE + }; /** * Product transmission callback to report the state of transmitting a @@ -324,17 +329,17 @@ public class ProductEditorComp extends Composite implements */ private ITransmissionState transmissionCB; - private SimpleDateFormat purgeTimeFmt = new SimpleDateFormat("ddHHmm"); + private final SimpleDateFormat purgeTimeFmt = new SimpleDateFormat("ddHHmm"); - private SimpleDateFormat vtecTimeFmt = new SimpleDateFormat( + private final SimpleDateFormat vtecTimeFmt = new SimpleDateFormat( "yyMMdd'T'HHmm'Z'"); - private Pattern vtecRE = Pattern + private final Pattern vtecRE = Pattern .compile("/[OTEX]\\.([A-Z]{3})\\.([A-Z]{4})\\.([A-Z]{2})\\." + "([WAYSOFN])\\.([0-9]{4})\\.([0-9]{6})T([0-9]{4})Z-" + "([0-9]{6})T([0-9]{4})Z/"); - private Map> newYearETNs = new HashMap>(); + private final Map> newYearETNs = new HashMap>(); /** * Job to update times in product @@ -356,14 +361,14 @@ public class ProductEditorComp extends Composite implements REG, PE, COR; } - private static final String[] REG_PTypes = { "rou", "AAA", "AAB", "AAC", - "AAD", "AAE", "RRA", "RRB", "RRC" }; + private final String[] REG_PTypes = { "rou", "AAA", "AAB", "AAC", "AAD", + "AAE", "RRA", "RRB", "RRC" }; - private static final String[] PE_PTypes = { "res", "RRA", "RRB", "RRC" }; + private final String[] PE_PTypes = { "res", "RRA", "RRB", "RRC" }; - private static final String[] COR_PTypes = { "CCA", "CCB", "CCC" }; + private final String[] COR_PTypes = { "CCA", "CCB", "CCC" }; - private static final String ZERO_VTEC = "000000T0000Z"; + private final String ZERO_VTEC = "000000T0000Z"; private List activeVtecRecords = null; @@ -654,7 +659,7 @@ public class ProductEditorComp extends Composite implements transmitMI.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - storeTransmit(Action.TRANSMIT); + storeTransmit(Action.TRANSMIT); } }); menuItems.add(transmitMI); @@ -862,14 +867,27 @@ public class ProductEditorComp extends Composite implements wrapLengthMI.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { - WrapLengthDialog wrapLengthDialog = new WrapLengthDialog( + // The dialog being opened is modal to the parent dialog. This + // will prevent the launching of another dialog until the modal + // dialog is closed. + final WrapLengthDialog wrapLengthDialog = new WrapLengthDialog( getShell()); wrapLengthDialog.setWrapLength(wrapColumn); - int result = wrapLengthDialog.open(); - if (result == Window.OK) { - wrapColumn = wrapLengthDialog.getWrapLength(); - textComp.setWrapColumn(wrapColumn); - } + wrapLengthDialog.setBlockOnOpen(false); + wrapLengthDialog.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof Integer) { + int result = (Integer) returnValue; + if (result == Window.OK) { + wrapColumn = wrapLengthDialog.getWrapLength(); + textComp.setWrapColumn(wrapColumn); + } + } + } + }); + wrapLengthDialog.open(); } }); } @@ -1038,9 +1056,8 @@ public class ProductEditorComp extends Composite implements * Store or Transmit text product. * * @param action - * STORE: show the Store dialog - * TRANSMITT: shows the Transmit dialog. - * AUTOSTORE: implement autoStore + * STORE: show the Store dialog TRANSMITT: shows the Transmit + * dialog. AUTOSTORE: implement autoStore */ private void storeTransmit(Action action) { @@ -1067,22 +1084,21 @@ public class ProductEditorComp extends Composite implements } if (fixText()) { - + // autoStore if (action == Action.AUTOSTORE) { if (testVTEC) { devStore(textdbPil.substring(3)); } else { - TextDBUtil.storeProduct(textdbPil, getProductText(), testVTEC); + TextDBUtil.storeProduct(textdbPil, getProductText(), + testVTEC); } return; } - - // Store/transmit... + + // Store/transmit... boolean showStore = (action == Action.STORE) ? true : false; - StoreTransmitDlg storeDlg = new StoreTransmitDlg(parent.getShell(), - showStore, this, transmissionCB); String pid; if (showStore) { pid = guessTDBPil(); @@ -1093,10 +1109,16 @@ public class ProductEditorComp extends Composite implements pid = "kkkknnnxxx"; } } - storeDlg.open(pid); + + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. + StoreTransmitDlg storeDlg = new StoreTransmitDlg(parent.getShell(), + showStore, this, transmissionCB, pid); + storeDlg.open(); } } - + private boolean fixText() { textComp.startUpdate(); // mmaron #7285: make sure there is \n in the end - to allow @@ -2248,47 +2270,47 @@ public class ProductEditorComp extends Composite implements } } } - + /* - * handle autoWrite, autoStore + * handle autoWrite, autoStore */ public void doAutoStuff() { int autoWrite = 0; Object autoWrite_obj = productDefinition.get("autoWrite"); if (autoWrite_obj != null) - autoWrite = (Integer)autoWrite_obj; - + autoWrite = (Integer) autoWrite_obj; + int autoStore = 0; Object autoStore_obj = productDefinition.get("autoStore"); if (autoStore_obj != null) - autoStore = (Integer)autoStore_obj; + autoStore = (Integer) autoStore_obj; - if (autoWrite == 1) { + if (autoWrite == 1) { autoWrite(); - } - - if (autoStore == 1) { + } + + if (autoStore == 1) { storeTransmit(Action.AUTOSTORE); - } + } } - + /* * autoWrite */ private void autoWrite() { - String fname = null; + String fname = null; if (productDefinition.get("outputFile") != null) { fname = getDefString("outputFile"); - if (fname.equals(EMPTY)) return; + if (fname.equals(EMPTY)) + return; } else { return; } - + fname = fixfname(fname); try { - ProductFileUtil.writeFile(getProductText(), new File( - fname)); + ProductFileUtil.writeFile(getProductText(), new File(fname)); } catch (IOException e) { MessageBox mb = new MessageBox(parent.getShell(), SWT.OK | SWT.ICON_WARNING); @@ -2296,21 +2318,20 @@ public class ProductEditorComp extends Composite implements mb.open(); } } - + /* * Replace {prddir} with siteConfig.GFESUITE_PRDDIR if applicable. */ private String fixfname(String fname) { if (fname.contains("{prddir}")) fname = fname.replace("{prddir}", prdDir); - + return fname; } private String guessFilename() { if (productDefinition.get("outputFile") != null) { - String basename = new File( - getDefString("outputFile")).getName(); + String basename = new File(getDefString("outputFile")).getName(); return basename; } else { return guessTDBPil(); @@ -2422,40 +2443,33 @@ public class ProductEditorComp extends Composite implements } private void displayCallToActionsDialog(int callToActionType) { + // Allow only one of the 3 types of dialogs to be displayed. + if (ctaDialog != null && ctaDialog.getShell() != null + && !ctaDialog.isDisposed()) { + ctaDialog.bringToTop(); + return; + } if (callToActionType == 1) { - - if (!ProductCTA && !GenericCTA && !HazardCTA) { - HazardCTA = true; - CTAHazCB(callToActionType); - HazardCTA = false; - } + CTAHazCB(callToActionType); } if (callToActionType == 2) { - - if (!HazardCTA && !GenericCTA && !ProductCTA) { - String[] Sig = new String[1]; - String pil = getDefString("pil"); - if (pil != null) { - Sig[0] = pil.substring(0, 3); - ProductCTA = true; - CallToActionsDlg productCTAsDlg = new CallToActionsDlg( - parent.getShell(), callToActionType, Sig, this); - productCTAsDlg.open(); - ProductCTA = false; - } + String[] Sig = new String[1]; + String pil = getDefString("pil"); + if (pil != null) { + Sig[0] = pil.substring(0, 3); + ctaDialog = new CallToActionsDlg(parent.getShell(), + callToActionType, Sig, this); + ctaDialog.setBlockOnOpen(false); + ctaDialog.open(); } } if (callToActionType == 3) { - - if (!ProductCTA && !HazardCTA && !GenericCTA) { - GenericCTA = true; - String[] Sig = new String[1]; - CallToActionsDlg genericCTAsDlg = new CallToActionsDlg( - parent.getShell(), callToActionType, Sig, this); - genericCTAsDlg.open(); - GenericCTA = false; - } + String[] Sig = new String[1]; + ctaDialog = new CallToActionsDlg(parent.getShell(), + callToActionType, Sig, this); + ctaDialog.setBlockOnOpen(false); + ctaDialog.open(); } } @@ -2467,6 +2481,9 @@ public class ProductEditorComp extends Composite implements * dialog. */ private void displayFindReplaceDialog(boolean findAndReplace) { + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. FindReplaceDlg findAndReplaceDlg = new FindReplaceDlg( parent.getShell(), findAndReplace, textComp); findAndReplaceDlg.open(); @@ -2560,9 +2577,22 @@ public class ProductEditorComp extends Composite implements } } }// loop - CallToActionsDlg hazardCTAsDlg = new CallToActionsDlg( - parent.getShell(), callToActionType, Sig, this); - hazardCTAsDlg.open(); + + HazardCTA = true; + ctaDialog = new CallToActionsDlg(parent.getShell(), + callToActionType, Sig, this); + ctaDialog.setBlockOnOpen(false); + ctaDialog.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + HazardCTA = false; + ctaDialog = null; + } + }); + ctaDialog.open(); + // Found segment the cursor is in no need to check more segments. + break; }// loop } @@ -2571,8 +2601,6 @@ public class ProductEditorComp extends Composite implements textEditorST = getTextEditorST(); prodDataStruct = textComp.getProductDataStruct(); - String product = getProductText(); - int offset = textEditorST.getCaretOffset(); if (offset >= (textEditorST.getCharCount() - 1)) { return; @@ -2952,21 +2980,21 @@ public class ProductEditorComp extends Composite implements } } - + /* * Handle bad characters in text formatter definition. */ private String getDefString(String key) { String str = null; - + Object obj = productDefinition.get(key); - if (obj != null && obj instanceof Collection ) { + if (obj != null && obj instanceof Collection) { Collection collection = (Collection) obj; - str = (String)(collection.toArray())[0]; + str = (String) (collection.toArray())[0]; } else { str = (String) productDefinition.get(key); } - + return str; } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/SaveDeleteComboDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/SaveDeleteComboDlg.java index b224fa800d..8db66557c7 100755 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/SaveDeleteComboDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/SaveDeleteComboDlg.java @@ -51,6 +51,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 25 MAR 2008 N/A lvenable Initial creation + * 08 NOV 2012 1298 rferrel Code cleanup for non-blocking dialog. * * * @@ -59,7 +60,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * */ public class SaveDeleteComboDlg extends CaveJFACEDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(SaveDeleteComboDlg.class); private Map comboDict; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/StoreTransmitDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/StoreTransmitDlg.java index 379abf9d87..98174d46bc 100755 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/StoreTransmitDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/StoreTransmitDlg.java @@ -29,7 +29,6 @@ import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.ProgressBar; @@ -52,6 +51,7 @@ import com.raytheon.uf.viz.core.requests.ThriftClient; import com.raytheon.viz.core.mode.CAVEMode; import com.raytheon.viz.gfe.core.DataManager; import com.raytheon.viz.gfe.product.TextDBUtil; +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; /** * Display the Store/Transmit dialog. @@ -64,33 +64,20 @@ import com.raytheon.viz.gfe.product.TextDBUtil; * 19 FEB 2010 4132 ryu Product correction. * 28May2010 2187 cjeanbap Added StdTextProductFactory * functionality. + * 09 NOV 2012 1298 rferrel Changes for non-blocking dialog. * * * @author lvenable * @version 1.0 * */ -public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { +public class StoreTransmitDlg extends CaveSWTDialog implements + IStoreTransmitProduct { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(StoreTransmitDlg.class); private static int SEQ_NUMBER = 0; - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - private Display display; - - /** - * Return object when the shell is disposed. - */ - private String returnObj = null; - /** * PRoduct ID text control. */ @@ -138,6 +125,8 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { */ private ITransmissionState transmissionCB; + private String pid; + /** * Constructor. * @@ -147,25 +136,20 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { * Store flag. True is store, false is transmit. */ public StoreTransmitDlg(Shell parent, boolean storeDialog, - ProductEditorComp editor, ITransmissionState transmissionCB) { - super(parent, 0); + ProductEditorComp editor, ITransmissionState transmissionCB, + String pid) { + super(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL, + CAVE.DO_NOT_BLOCK); this.transmissionCB = transmissionCB; isStoreDialog = storeDialog; parentEditor = editor; this.productText = editor.getProductText(); + this.pid = pid; } - /** - * Setup and open the dialog. - * - * @return Return object. - */ - public Object open(String initialPid) { - Shell parent = getParent(); - display = parent.getDisplay(); - shell = new Shell(parent, SWT.DIALOG_TRIM); - + @Override + protected void initializeComponents(Shell shell) { String title = null; CAVEMode opMode = DataManager.getCurrentInstance().getOpMode(); if (opMode.equals(CAVEMode.OPERATIONAL)) { @@ -199,18 +183,12 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { // Initialize all of the controls and layouts initializeComponents(); - productIdTF.insert(initialPid); + } - shell.pack(); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - return returnObj; + @Override + protected void preOpened() { + super.preOpened(); + productIdTF.insert(pid); } /** @@ -226,6 +204,8 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { createMainControls(); createBottomButtons(); + Display display = shell.getParent().getDisplay(); + countdownThread = new StoreTransmitCountdownThread(display, progBar, progressLbl, countdownText, this, isStoreDialog); } @@ -327,6 +307,7 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { if (countdownThread.isDone() == false) { countdownThread.cancelThread(); progressLbl.setText(countdownText); + Display display = shell.getParent().getDisplay(); progressLbl.setBackground(display .getSystemColor(SWT.COLOR_WIDGET_BACKGROUND)); progressLbl.setForeground(display @@ -334,8 +315,8 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { } } - returnObj = null; - shell.dispose(); + setReturnValue(null); + close(); } }); } @@ -374,9 +355,11 @@ public class StoreTransmitDlg extends Dialog implements IStoreTransmitProduct { // The asyncExec call is used to dispose of the shell since it is // called outside the GUI thread (count down thread). - display.asyncExec(new Runnable() { + VizApp.runAsync(new Runnable() { + + @Override public void run() { - shell.dispose(); + close(); } }); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/WrapLengthDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/WrapLengthDialog.java index f5760050f6..19e64dfc02 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/WrapLengthDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/WrapLengthDialog.java @@ -41,6 +41,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jul 27, 2010 wldougher Initial creation + * Nov 09, 2012 1298 rferrel Code clean up for non-blocking dialog. * * * @@ -49,11 +50,11 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; */ public class WrapLengthDialog extends CaveJFACEDialog { - private static final int MAX_COLUMNS = 255; + private final int MAX_COLUMNS = 255; - private static final int MIN_COLUMNS = 15; + private final int MIN_COLUMNS = 15; - private static final String MESSAGE = "Current Wrap Length: %d\n" + private final String MESSAGE = "Current Wrap Length: %d\n" + "Enter new Wrap Length"; protected Label notice; @@ -66,10 +67,6 @@ public class WrapLengthDialog extends CaveJFACEDialog { super(parentShell); } - protected WrapLengthDialog(Shell parentShell, boolean perspectiveSpecific) { - super(parentShell, perspectiveSpecific); - } - /** * @see org.eclipse.jface.dialogs.Dialog#createDialogArea(org.eclipse.swt.widgets * .Composite) diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneColorEditorDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneColorEditorDlg.java index b1fd62ec56..5676196f69 100755 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneColorEditorDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneColorEditorDlg.java @@ -39,10 +39,9 @@ import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Canvas; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Dialog; -import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; +import com.raytheon.viz.ui.dialogs.CaveSWTDialog; import com.raytheon.viz.ui.dialogs.colordialog.ColorWheelComp; /** @@ -53,6 +52,7 @@ import com.raytheon.viz.ui.dialogs.colordialog.ColorWheelComp; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 21 APR 2008 ### lvenable Initial creation + * 08 NOV 2012 1298 rferrel Changes for non-blocking dialog. * * * @@ -60,22 +60,8 @@ import com.raytheon.viz.ui.dialogs.colordialog.ColorWheelComp; * @version 1.0 * */ -public class ZoneColorEditorDlg extends Dialog implements MouseListener, +public class ZoneColorEditorDlg extends CaveSWTDialog implements MouseListener, MouseMoveListener { - /** - * Dialog shell. - */ - private Shell shell; - - /** - * The display control. - */ - private Display display; - - /** - * Return object when the shell is disposed. - */ - private String returnObj = null; /** * Color wheel composite used to select colors. @@ -182,7 +168,8 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, * Array of RGB colors. */ public ZoneColorEditorDlg(Shell parent, List colorArray) { - super(parent, 0); + super(parent, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL, + CAVE.DO_NOT_BLOCK); this.rgbArray = colorArray; @@ -191,15 +178,8 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, cellWidth = COLOR_BAR_WIDTH / (double) colorArray.size(); } - /** - * Setup and open the dialog. - * - * @return Return object. - */ - public Object open() { - Shell parent = getParent(); - display = parent.getDisplay(); - shell = new Shell(parent, SWT.DIALOG_TRIM); + @Override + protected void initializeComponents(Shell shell) { shell.setText("Zone Color Table Editor"); @@ -212,17 +192,6 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, // Initialize all of the controls and layouts initializeComponents(); - - shell.pack(); - - shell.open(); - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - return returnObj; } /** @@ -311,7 +280,7 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, @Override public void widgetSelected(SelectionEvent event) { originalRgbArray = rgbArray; - shell.dispose(); + close(); } }); @@ -322,10 +291,10 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, dismissBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - returnObj = null; + setReturnValue(null); rgbArray.clear(); rgbArray.addAll(originalRgbArray); - shell.dispose(); + close(); } }); } @@ -337,10 +306,10 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, * Graphics context. */ private void drawCanvas(GC gc) { - gc.setBackground(display.getSystemColor(SWT.COLOR_BLACK)); + gc.setBackground(getDisplay().getSystemColor(SWT.COLOR_BLACK)); gc.fillRectangle(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); - gc.setForeground(display.getSystemColor(SWT.COLOR_WHITE)); + gc.setForeground(getDisplay().getSystemColor(SWT.COLOR_WHITE)); gc.drawString("Zone Group Colors", 10, 5, true); // ------------------------------------------------- @@ -372,8 +341,7 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, if (currentColor != null) { currentColor.dispose(); } - - currentColor = new Color(display, rgbArray.get(i)); + currentColor = new Color(getDisplay(), rgbArray.get(i)); gc.setBackground(currentColor); gc.fillRectangle(cellXCoord, COLOR_BAR_Y_COORD, @@ -474,4 +442,16 @@ public class ZoneColorEditorDlg extends Dialog implements MouseListener, */ public void mouseUp(MouseEvent e) { } + + /* + * (non-Javadoc) + * + * @see com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#disposed() + */ + @Override + protected void disposed() { + if (currentColor != null) { + currentColor.dispose(); + } + } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneCombinerComp.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneCombinerComp.java index cd4bddf3e5..e9e9614d0f 100755 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneCombinerComp.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/formatterlauncher/ZoneCombinerComp.java @@ -95,6 +95,10 @@ import com.raytheon.viz.gfe.ui.zoneselector.ZoneSelector; * ------------ ---------- ----------- -------------------------- * 21 APR 2008 ### lvenable Initial creation * 07 JUL 2011 9293 rferrel Hook to allow checking of includeAllZones + * 07 Nov 2012 1298 rferrel Changes for non-blocking ClearZoneGroupsDialog. + * Changes for non-blocking SaveDeleteComboDlg. + * Changes for non-blocking ShuffleZoneGroupsDialog. + * Changes for non-blocking ZoneColorEditorDlg. * * * @@ -104,7 +108,7 @@ import com.raytheon.viz.gfe.ui.zoneselector.ZoneSelector; */ public class ZoneCombinerComp extends Composite implements ILocalizationFileObserver, IZoneCombiner { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(ZoneCombinerComp.class); /** @@ -192,8 +196,8 @@ public class ZoneCombinerComp extends Composite implements private List colorMap = new ArrayList(); - private static final String COLOR_MAP_FILE = FileUtil.join("gfe", - "combinations", "Combinations_ColorMap"); + private final String COLOR_MAP_FILE = FileUtil.join("gfe", "combinations", + "Combinations_ColorMap"); Matcher matcher; @@ -390,11 +394,15 @@ public class ZoneCombinerComp extends Composite implements saveComboMI.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { + // The dialog being opened is modal to the parent dialog. This + // will + // prevent the launching of another dialog until the modal + // dialog is + // closed. SaveDeleteComboDlg saveCombDlg = new SaveDeleteComboDlg(parent .getShell(), mapNames, "Save", zoneSelector.getCombos()); - saveCombDlg.setBlockOnOpen(true); + saveCombDlg.setBlockOnOpen(false); saveCombDlg.open(); - } }); @@ -421,9 +429,14 @@ public class ZoneCombinerComp extends Composite implements deleteComboMI.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { + // The dialog being opened is modal to the parent dialog. This + // will + // prevent the launching of another dialog until the modal + // dialog is + // closed. SaveDeleteComboDlg deleteCombDlg = new SaveDeleteComboDlg( parent.getShell(), mapNames, "Delete", null); - deleteCombDlg.setBlockOnOpen(true); + deleteCombDlg.setBlockOnOpen(false); deleteCombDlg.open(); } }); @@ -487,15 +500,22 @@ public class ZoneCombinerComp extends Composite implements } private void openClearDialog() { + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. ClearZoneGroupsDialog examClearDlg = new ClearZoneGroupsDialog( parent.getShell(), zoneSelector, getCombinationsFileName()); + examClearDlg.setBlockOnOpen(false); examClearDlg.open(); - } private void openShuffleDialog() { + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. ShuffleZoneGroupsDialog shuffleDlg = new ShuffleZoneGroupsDialog( parent.getShell(), this.zoneSelector, getCombinationsFileName()); + shuffleDlg.setBlockOnOpen(false); shuffleDlg.open(); } @@ -736,7 +756,9 @@ public class ZoneCombinerComp extends Composite implements * Display the Color Editor dialog. */ private void displayColorEditorDialog() { - + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. ZoneColorEditorDlg zoneColorDlg = new ZoneColorEditorDlg( parent.getShell(), colorMap); zoneColorDlg.open(); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/isc/ShowISCInfoDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/isc/ShowISCInfoDlg.java deleted file mode 100644 index 6707ea84f1..0000000000 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/isc/ShowISCInfoDlg.java +++ /dev/null @@ -1,190 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.viz.gfe.dialogs.isc; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.SelectionAdapter; -import org.eclipse.swt.events.SelectionEvent; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.graphics.Font; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Shell; - -import com.raytheon.viz.ui.dialogs.CaveSWTDialog; - -/** - * Dialog containing the results of the Show_ISC_Info smart tool - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 08/28/09      1995       bphillip    Initial creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class ShowISCInfoDlg extends CaveSWTDialog { - - /** Text used for color coding */ - private static final String OK_TXT = "OK"; - - /** Text used for color coding */ - private static final String IGNORED_TXT = "IGNORED"; - - /** Text used for color coding */ - private static final String FAILED_TXT = "FAILED"; - - /** The resulting text from the Show_ISC_Info smart tool */ - private String text; - - /** The font used for displaying the text */ - private Font textFont; - - /** Custom color for coloring the IGNORED items */ - private Color darkOrange; - - /** Text box containing the text */ - private StyledText textBox; - - /** - * Creates a new dialog - * - * @param parentShell - * The shell - * @param text - * The text from Show_ISC_Info smart tool - */ - public ShowISCInfoDlg(Shell parentShell, String text) { - super(parentShell, SWT.DIALOG_TRIM | SWT.RESIZE); - setText("ISC Discrepancy Info"); - - if (text == null) { - this.text = ""; - } else { - this.text = text; - } - - } - - @Override - protected void disposed() { - textFont.dispose(); - darkOrange.dispose(); - } - - @Override - protected void initializeComponents(Shell shell) { - textFont = new Font(getDisplay(), "Monospace", 8, SWT.NORMAL); - darkOrange = new Color(getDisplay(), 255, 102, 0); - - // Initialize all of the controls and layouts - createTextArea(); - createBottomButton(); - colorText(); - } - - /** - * Creates the text area and populates the text - */ - private void createTextArea() { - Composite listComp = new Composite(shell, SWT.NONE); - GridLayout gl = new GridLayout(1, false); - listComp.setLayout(gl); - listComp.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); - - GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); - gd.widthHint = 500; - gd.heightHint = 200; - - textBox = new StyledText(listComp, SWT.BORDER | SWT.V_SCROLL); - textBox.setEditable(false); - textBox.setText(text); - textBox.setFont(textFont); - textBox.setLayoutData(gd); - } - - /** - * Creates the close button - */ - private void createBottomButton() { - GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); - Composite buttonComp = new Composite(shell, SWT.NONE); - buttonComp.setLayout(new GridLayout(1, false)); - buttonComp.setLayoutData(gd); - - int buttonWidth = 120; - - gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); - gd.widthHint = buttonWidth; - Button closeBtn = new Button(buttonComp, SWT.PUSH); - closeBtn.setText("Close"); - closeBtn.setLayoutData(gd); - closeBtn.setForeground(getDisplay().getSystemColor(SWT.COLOR_RED)); - - closeBtn.addSelectionListener(new SelectionAdapter() { - @Override - public void widgetSelected(SelectionEvent e) { - shell.dispose(); - } - }); - - } - - /** - * Colors the text according to rules - */ - private void colorText() { - int startLineIndex = 0; - int numLines = textBox.getLineCount(); - String tmpStr = null; - - for (int i = 0; i < numLines; i++) { - startLineIndex = textBox.getOffsetAtLine(i); - tmpStr = textBox.getLine(i); - if (tmpStr.endsWith(OK_TXT)) { - StyleRange sr = new StyleRange(startLineIndex - + tmpStr.lastIndexOf(OK_TXT), OK_TXT.length(), - getDisplay().getSystemColor(SWT.COLOR_DARK_GREEN), null); - textBox.setStyleRange(sr); - } else if (tmpStr.endsWith(IGNORED_TXT)) { - StyleRange sr = new StyleRange(startLineIndex - + tmpStr.lastIndexOf(IGNORED_TXT), - IGNORED_TXT.length(), darkOrange, null); - textBox.setStyleRange(sr); - } else if (tmpStr.endsWith(FAILED_TXT)) { - StyleRange sr = new StyleRange(startLineIndex - + tmpStr.lastIndexOf(FAILED_TXT), FAILED_TXT.length(), - getDisplay().getSystemColor(SWT.COLOR_RED), null); - textBox.setStyleRange(sr); - } - } - } -} diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/CheckPermissions.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/CheckPermissions.java index db64d96b80..0a326b07f4 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/CheckPermissions.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/CheckPermissions.java @@ -21,7 +21,6 @@ package com.raytheon.viz.gfe.dialogs.sbu; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.dataplugin.gfe.request.CheckPermissionsRequest; -import com.raytheon.uf.common.dataplugin.gfe.request.NcCheckRequest; import com.raytheon.uf.common.dataplugin.gfe.server.message.ServerResponse; import com.raytheon.uf.common.site.requests.GetPrimarySiteRequest; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -41,7 +40,6 @@ import com.raytheon.uf.viz.core.requests.ThriftClient; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 11, 2011 bphillip Initial creation - * Nov 14, 2012 jdynina Added check for national center * * * @@ -58,7 +56,8 @@ public class CheckPermissions { public static boolean getAuthorization() { boolean authorized = false; IUser user = UserController.getUserObject(); - CheckPermissionsRequest request = new CheckPermissionsRequest(user); + CheckPermissionsRequest request = new CheckPermissionsRequest(); + request.setUser(user); try { ServerResponse obj = (ServerResponse) ThriftClient .sendRequest(request); @@ -68,30 +67,11 @@ public class CheckPermissions { authorized = false; } } catch (VizException e) { - statusHandler.error("Error checking permissions for: " + user); + statusHandler.error("Error checking permissions for: " + user, e); authorized = false; } return authorized; } - - @SuppressWarnings("unchecked") - public static boolean isNationalCenter() { - boolean isNationalCenter = false; - NcCheckRequest request = new NcCheckRequest(); - try { - ServerResponse obj = (ServerResponse) ThriftClient - .sendRequest(request); - if (obj.isOkay()) { - isNationalCenter = true; - } else { - isNationalCenter = false; - } - } catch (VizException e) { - statusHandler.error("Error checking site type!", e); - isNationalCenter = false; - } - return isNationalCenter; - } public static boolean runningAsPrimary() { boolean isPrimary = false; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/ServiceBackupDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/ServiceBackupDlg.java index 4f03ab588e..3b02517223 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/ServiceBackupDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/ServiceBackupDlg.java @@ -88,9 +88,8 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 4, 2011 randerso Initial creation - * Sep 19,2011 10955 rferrel Use RunProcess + * Sep 19, 2011 10955 rferrel Use RunProcess * Oct 25, 2012 1287 rferrel Code clean up for non-blocking dialog. - * Nov 15,2012 15614 jdynina Added check for national center * * * @@ -156,8 +155,6 @@ public class ServiceBackupDlg extends CaveJFACEDialog { private Job updateJob; private boolean authorized; - - private boolean nationalCenter; private SVCBU_OP currentOperation = SVCBU_OP.no_backup; @@ -168,7 +165,6 @@ public class ServiceBackupDlg extends CaveJFACEDialog { super(parentShell); authorized = CheckPermissions.getAuthorization(); this.site = LocalizationManager.getInstance().getCurrentSite(); - this.nationalCenter = CheckPermissions.isNationalCenter(); this.runningAsPrimary = CheckPermissions.runningAsPrimary(); if (!ServiceBackupJobManager.getInstance().isRunning()) { ServiceBackupJobManager.getInstance().start(); @@ -1203,7 +1199,8 @@ public class ServiceBackupDlg extends CaveJFACEDialog { + UserController.getUserObject().uniqueId()); } - if ((!runningAsPrimary) & (!nationalCenter)) { + if ((!runningAsPrimary) + && (!LocalizationManager.getInstance().isNationalCenter())) { doExCon.setEnabled(false); } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/SiteActivationDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/SiteActivationDlg.java index 832c052879..1de07839d5 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/SiteActivationDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/dialogs/sbu/SiteActivationDlg.java @@ -243,38 +243,45 @@ public class SiteActivationDlg extends CaveJFACEDialog implements private void doValidate() { String siteID = this.siteId.getText(); - ValidateConfigRequest request = new ValidateConfigRequest(siteID, "gfe"); - try { - String result = (String) ThriftClient.sendRequest(request); - appendToLog(result); - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error processing site activation request", e); - + if (!siteID.isEmpty()) { + ValidateConfigRequest request = new ValidateConfigRequest(siteID, + "gfe"); + try { + String result = (String) ThriftClient.sendRequest(request); + appendToLog(result); + } catch (VizException e) { + statusHandler.handle(Priority.PROBLEM, + "Error processing site activation request", e); + } } } private void doActivate() { String siteID = this.siteId.getText(); - ActivateSiteRequest request = new ActivateSiteRequest(siteID, "gfe"); - try { - ThriftClient.sendRequest(request); - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error processing site activation request", e); + if (!siteID.isEmpty()) { + ActivateSiteRequest request = new ActivateSiteRequest(siteID, "gfe"); + try { + ThriftClient.sendRequest(request); + } catch (VizException e) { + statusHandler.handle(Priority.PROBLEM, + "Error processing site activation request", e); + } } } private void doDeactivate() { String siteID = this.siteId.getText(); - DeactivateSiteRequest request = new DeactivateSiteRequest(siteID, "gfe"); - try { - ThriftClient.sendRequest(request); - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error processing site deactivation request", e); + if (!siteID.isEmpty()) { + DeactivateSiteRequest request = new DeactivateSiteRequest(siteID, + "gfe"); + try { + ThriftClient.sendRequest(request); + } catch (VizException e) { + statusHandler.handle(Priority.PROBLEM, + "Error processing site deactivation request", e); + } } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/gridmanager/action/DisplayInfoAction.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/gridmanager/action/DisplayInfoAction.java index 12cce79aec..07e38482fe 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/gridmanager/action/DisplayInfoAction.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/gridmanager/action/DisplayInfoAction.java @@ -35,6 +35,7 @@ import com.raytheon.viz.gfe.dialogs.GridInfoDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 03/04/2008 dfitch Initial creation. + * 11/12/2012 1298 rferrel Changes for non-blocking GridInfoDialog. * * * @@ -60,8 +61,10 @@ public class DisplayInfoAction extends AbstractGridManagerAction { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(); + // Allow multiple instance of this dialog. + // Mimics A1 and allows user to display information on multiple grids. GridInfoDialog dialog = new GridInfoDialog(shell, parm, clickTime); - dialog.setBlockOnOpen(true); + dialog.setBlockOnOpen(false); dialog.open(); } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/GFEResource.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/GFEResource.java index e557fcebab..2dd9895521 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/GFEResource.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/GFEResource.java @@ -44,8 +44,6 @@ import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.swt.custom.BusyIndicator; import org.eclipse.swt.graphics.RGB; import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; import org.geotools.coverage.grid.GridGeometry2D; import org.opengis.metadata.spatial.PixelOrientation; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -160,6 +158,7 @@ import com.vividsolutions.jts.geom.Envelope; * Aug 20, 2008 dglazesk Update for the ColorMap interface change * Nov 23, 2011 mli set vector lineStyle * May 11, 2012 njensen Allow rsc to be recycled + * Nov 08, 2012 1298 rferrel Changes for non-blocking FuzzValueDialog. * * * @@ -171,28 +170,28 @@ import com.vividsolutions.jts.geom.Envelope; public class GFEResource extends AbstractVizResource implements IResourceDataChanged, IContextMenuContributor, IMessageClient { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(GFEResource.class); /** maximum label size in pixels */ - private static final int maxLabelLength = 100; + private final int maxLabelLength = 100; /** maximum label height in pixels */ @SuppressWarnings("unused") - private static final int maxLabelHeight = 40; + private final int maxLabelHeight = 40; /** distance between labels */ - private static final int pixelDistance = 125; + private final int pixelDistance = 125; - private static final Set OUTLINE_TYPES = EnumSet.of( + private final Set OUTLINE_TYPES = EnumSet.of( VisualizationType.CONTOUR, VisualizationType.WIND_ARROW, VisualizationType.WIND_BARB, VisualizationType.BOUNDED_AREA); - private static final Set DENSITY_TYPES = EnumSet.of( + private final Set DENSITY_TYPES = EnumSet.of( VisualizationType.CONTOUR, VisualizationType.WIND_ARROW, VisualizationType.WIND_BARB); - private static final Set MAG_TYPES = EnumSet.of( + private final Set MAG_TYPES = EnumSet.of( VisualizationType.CONTOUR, VisualizationType.WIND_ARROW, VisualizationType.WIND_BARB, VisualizationType.BOUNDED_AREA); @@ -274,7 +273,7 @@ public class GFEResource extends } }; - + /** * Construct a resource that is capable of displaying a particular parm * @@ -1202,7 +1201,6 @@ public class GFEResource extends } private class FuzzValueAction extends AbstractRightClickAction { - public FuzzValueAction() { super("Set Fuzz Value..."); @@ -1210,13 +1208,7 @@ public class GFEResource extends @Override public void run() { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - - FuzzValueDialog fuzz = new FuzzValueDialog(shell, dataManager); - - fuzz.setBlockOnOpen(true); - fuzz.open(); + FuzzValueDialog.openDialog(dataManager); } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/colorbar/GFEColorbarResource.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/colorbar/GFEColorbarResource.java index 4631e55de5..9e5888fdf6 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/colorbar/GFEColorbarResource.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/rsc/colorbar/GFEColorbarResource.java @@ -98,6 +98,8 @@ import com.raytheon.viz.ui.input.InputAdapter; * 05Aug2008 #1405 ebabin Fix fo delta not displaying after first use. * 06/03/2011 #8919 rferrel No longer display color bar when * VisMode is GRAPHIC + * 11/13/20112 #1298 rferrel Changes for non-blocking SetDeltaDialog. + * Changes for non-blocking SetValueDialog. * * * @@ -109,8 +111,8 @@ public class GFEColorbarResource extends IContextMenuProvider, IPickupValueChangedListener, IDisplayModeChangedListener, IMessageClient, IDisplayedParmListChangedListener { - - public static final double HEIGHT = 25.0; + + public static final double HEIGHT = 25.0; private class GFEColorbarInputHandler extends InputAdapter { @@ -388,7 +390,7 @@ public class GFEColorbarResource extends // Construct a bar that is HEIGHT pixels high double height = HEIGHT * screenExtent.getHeight() - / paintProps.getCanvasBounds().height; + / paintProps.getCanvasBounds().height; PixelExtent pe = new PixelExtent(screenExtent.getMinX(), screenExtent.getMaxX(), screenExtent.getMinY(), @@ -403,7 +405,7 @@ public class GFEColorbarResource extends // erase the whole colorbar to a black background target.drawShadedRect(pe, ColorUtil.BLACK, 1.0, null); target.drawRect(pe, GFEColorbarResource.COLORBAR_GRAY, 2.0f, 1.0f); - + if (currentParm == null) { return; } @@ -530,21 +532,11 @@ public class GFEColorbarResource extends } private void showDeltaDialog() { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - - SetDeltaDialog deltaDialog = new SetDeltaDialog(shell, dManager); - deltaDialog.setBlockOnOpen(true); - deltaDialog.open(); + SetDeltaDialog.openDialog(); } private void showPickupDialog() { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - - SetValueDialog svd = new SetValueDialog(shell, dManager); - svd.setBlockOnOpen(false); - svd.open(); + SetValueDialog.openDialog(); } private class SetPickupAction extends AbstractRightClickAction { diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/EditActionProcessor.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/EditActionProcessor.java index 42139649d0..1eaa15dbc8 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/EditActionProcessor.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/EditActionProcessor.java @@ -33,7 +33,6 @@ import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.PlatformUI; -import com.raytheon.uf.common.dataplugin.gfe.StatusConstants; import com.raytheon.uf.common.dataplugin.gfe.reference.ReferenceData; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; @@ -61,6 +60,8 @@ import com.raytheon.viz.gfe.dialogs.TimeRangeWarningDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * May 3, 2010 njensen Initial creation + * Nov 7, 2012 1298 rferrel Keep EmptyEditAreaWarningDialog blocking. + * Keep TimeRangeWarningdialog blocking. * * * @@ -69,7 +70,8 @@ import com.raytheon.viz.gfe.dialogs.TimeRangeWarningDialog; */ public class EditActionProcessor { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(EditActionProcessor.class); + private final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(EditActionProcessor.class); private DataManager dataMgr; @@ -454,9 +456,11 @@ public class EditActionProcessor { VizApp.runSync(new Runnable() { @Override public void run() { + // Simple warning keep as a blocking dialog. TimeRangeWarningDialog prompt = new TimeRangeWarningDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); + prompt.setBlockOnOpen(true); returnCode = prompt.open(); } }); @@ -471,9 +475,11 @@ public class EditActionProcessor { VizApp.runSync(new Runnable() { @Override public void run() { + // Simple warning keep as a blocking dialog. EmptyEditAreaWarningDialog prompt = new EmptyEditAreaWarningDialog( PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell()); + prompt.setBlockOnOpen(true); returnCode = prompt.open(); } }); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/SmartUtil.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/SmartUtil.java index 64c0b9f65b..b44dda7594 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/SmartUtil.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/SmartUtil.java @@ -50,6 +50,7 @@ import com.raytheon.viz.gfe.ui.runtimeui.SelectionDlg; * ------------ ---------- ----------- -------------------------- * Feb 21, 2008 njensen Initial creation * Dec 1, 2009 1426 ryu Add time range warning + * Nov 15, 2012 1298 rferrel Changes for non-blocking prcedures. * * * @@ -91,16 +92,21 @@ public class SmartUtil { try { varList = dm.getSmartToolInterface().getVarDictWidgets(toolName); } catch (JepException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + statusHandler.handle(Priority.PROBLEM, + "Error getting VariableList for procedure: " + toolName, e); } if (varList == null || varList.size() == 0) { runToolNoVarDict(dm, toolName); } else { + // The SmartToolSelectionDlg changes based on the procedure. + // Since it is non-modal several dialogs may be displayed. This + // mimics the AWIPS 1 behavior. + // make the gui, let it handle running the tool SelectionDlg sd = new SmartToolSelectionDlg(PlatformUI .getWorkbench().getActiveWorkbenchWindow().getShell(), toolName, dm, varList); + sd.setBlockOnOpen(false); sd.open(); } } @@ -150,11 +156,20 @@ public class SmartUtil { .getSmartToolInterface().getVarDictWidgets( toolName); if (varList != null && varList.size() > 0) { + // The SmartToolBlockingSelectionDlg changes based + // on the procedure. Since it is non-modal several + // dialogs may be displayed. This mimics the AWIPS 1 + // behavior. + // make the gui, let it handle running the procedure SmartToolBlockingSelectionDlg sd = new SmartToolBlockingSelectionDlg( PlatformUI.getWorkbench() .getActiveWorkbenchWindow() .getShell(), toolName, dm, varList); + + // must block because this method needs the results + // to determine what to return. + sd.setBlockOnOpen(true); sd.open(); Map resultMap = sd .getVarDictResult(); @@ -170,7 +185,8 @@ public class SmartUtil { } } catch (JepException e) { statusHandler.handle(Priority.PROBLEM, - "Error getting VariableList", e); + "Error getting VariableList for procedure: " + + toolName, e); } } }); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/action/NewAction.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/action/NewAction.java index 53bef7f9e4..9437309c00 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/action/NewAction.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/smarttool/action/NewAction.java @@ -33,6 +33,7 @@ import com.raytheon.viz.gfe.dialogs.NewToolDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Feb 21, 2008 njensen Initial creation + * Nov 12, 2012 1298 rferrel Changes for non-blocking NewToolDialog. * * * @@ -51,8 +52,12 @@ public class NewAction extends AbstractSmartToolAction { if (!utility) { Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(); + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. NewToolDialog d = new NewToolDialog(shell, "MyTool", new NewInputValidator()); + d.setBlockOnOpen(false); d.open(); } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/TemporalEditor.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/TemporalEditor.java index 1b5607f455..0c670d497a 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/TemporalEditor.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/TemporalEditor.java @@ -37,11 +37,9 @@ import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Shell; -import org.eclipse.ui.PlatformUI; -import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID; import com.raytheon.uf.common.dataplugin.gfe.db.objects.GFERecord.GridType; +import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID; import com.raytheon.uf.viz.core.VizApp; import com.raytheon.viz.gfe.GFEPreference; import com.raytheon.viz.gfe.PreferenceConstants; @@ -53,12 +51,11 @@ import com.raytheon.viz.gfe.core.msgs.IDisplayedParmListChangedListener; import com.raytheon.viz.gfe.core.msgs.IGridVisibilityChangedListener; import com.raytheon.viz.gfe.core.msgs.IParmIDChangedListener; import com.raytheon.viz.gfe.core.msgs.Message; +import com.raytheon.viz.gfe.core.msgs.Message.IMessageClient; import com.raytheon.viz.gfe.core.msgs.TEOverlayModeChangedMsg; import com.raytheon.viz.gfe.core.msgs.TEweModeChangedMsg; -import com.raytheon.viz.gfe.core.msgs.Message.IMessageClient; import com.raytheon.viz.gfe.core.parm.Parm; import com.raytheon.viz.gfe.gridmanager.GridManager; -import com.raytheon.viz.gfe.temporaleditor.dialogs.MoveWeatherElementDialog; /** * TemporalEditor widget containing a TemporalEditorBar for each displayed @@ -70,6 +67,7 @@ import com.raytheon.viz.gfe.temporaleditor.dialogs.MoveWeatherElementDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Apr 30, 2009 2159 rjpeter Initial creation + * Nov 14, 2012 1298 rferrel Remove no longer used reference to MoveWeatherElementDialog. * * * @author rjpeter @@ -439,21 +437,6 @@ public class TemporalEditor extends Composite implements IMessageClient { return barList; } - /** - * - * @param parm - * @param sourceBar - */ - public void createMoveParmDialog(Parm parm, - AbstractTemporalEditorBar sourceBar) { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - MoveWeatherElementDialog dialog = new MoveWeatherElementDialog(shell, - this, parm, sourceBar, getCombinableBars(parm, sourceBar)); - dialog.setBlockOnOpen(true); - dialog.open(); - } - public StatisticsMode getMode() { return statMode; } @@ -530,8 +513,8 @@ public class TemporalEditor extends Composite implements IMessageClient { break; } - final ArrayList parmsToRemove = new ArrayList(parmToTEBar - .keySet()); + final ArrayList parmsToRemove = new ArrayList( + parmToTEBar.keySet()); parmsToRemove.removeAll(parmsToAdd); VizApp.runAsync(new Runnable() { @@ -651,8 +634,8 @@ public class TemporalEditor extends Composite implements IMessageClient { break; case ALL_NOISC: for (Parm parmAdd : additions) { - if (!parmAdd.getParmID().getDbId().getModelName().equals( - "ISC")) { + if (!parmAdd.getParmID().getDbId().getModelName() + .equals("ISC")) { addParm(parmAdd); } } @@ -680,8 +663,7 @@ public class TemporalEditor extends Composite implements IMessageClient { @Override public void propertyChange(PropertyChangeEvent event) { String id = event.getProperty(); - if (id - .equals(PreferenceConstants.GFE_TEMPORAL_EDITOR_STATISTICS_MODE)) { + if (id.equals(PreferenceConstants.GFE_TEMPORAL_EDITOR_STATISTICS_MODE)) { statMode = StatisticsMode .valueOf(GFEPreference .getPreference(PreferenceConstants.GFE_TEMPORAL_EDITOR_STATISTICS_MODE)); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/actions/SetDiscreteAction.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/actions/SetDiscreteAction.java index 8850f0a577..17eb8e7dfc 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/actions/SetDiscreteAction.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/actions/SetDiscreteAction.java @@ -36,6 +36,7 @@ import com.raytheon.viz.gfe.temporaleditor.dialogs.TEDiscreteSetValueDialog; * Date Ticket# Engineer Description * ------------ ---------- ------------- -------------------------- * May 28, 2009 #2159 Richard Peter Initial Creation. + * Nov 13, 2012 #1298 rferrel Changes for non-blocking TEDiscreteSetValueDialog. * * * @author rjpeter @@ -54,9 +55,12 @@ public class SetDiscreteAction extends Action { @Override public void run() { + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. TEDiscreteSetValueDialog discretePickupValueDialog = new TEDiscreteSetValueDialog( Display.getCurrent().getActiveShell(), parm, date); - discretePickupValueDialog.setBlockOnOpen(true); + discretePickupValueDialog.setBlockOnOpen(false); discretePickupValueDialog.open(); } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/MoveWeatherElementDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/MoveWeatherElementDialog.java index 6f71e3acd3..8c4237f334 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/MoveWeatherElementDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/MoveWeatherElementDialog.java @@ -47,6 +47,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 05/19/09 #2159 rjpeter Initial creation. + * 11/14/2012 #1298 rferrel Changes for non-blocking dialog. * * * @author rjpeter @@ -70,7 +71,7 @@ public class MoveWeatherElementDialog extends CaveJFACEDialog { AbstractTemporalEditorBar sourceBar, List destBars) { super(parent); - this.setShellStyle(SWT.TITLE | SWT.MODELESS | SWT.CLOSE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL); this.temporalEditor = temporalEditor; this.parm = parm; this.sourceBar = sourceBar; diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/TEDiscreteSetValueDialog.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/TEDiscreteSetValueDialog.java index 00c816aaa3..550e1c5f58 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/TEDiscreteSetValueDialog.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/dialogs/TEDiscreteSetValueDialog.java @@ -37,9 +37,7 @@ import com.raytheon.uf.common.dataplugin.gfe.grid.Grid2DBit; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.viz.gfe.Activator; import com.raytheon.viz.gfe.GFEOperationFailedException; -import com.raytheon.viz.gfe.constants.StatusConstants; import com.raytheon.viz.gfe.core.griddata.IGridData; import com.raytheon.viz.gfe.core.parm.Parm; import com.raytheon.viz.gfe.core.wxvalue.WxValue; @@ -55,6 +53,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jun 24, 2009 #1318 randerso Initial creation + * Nov 14, 2012 #1298 rferrel Changes for non-blocking dialog. * * * @@ -63,7 +62,8 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; */ public class TEDiscreteSetValueDialog extends CaveJFACEDialog { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(TEDiscreteSetValueDialog.class); + private final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(TEDiscreteSetValueDialog.class); private Parm parm; @@ -144,9 +144,6 @@ public class TEDiscreteSetValueDialog extends CaveJFACEDialog { layout.marginWidth = 0; GridData layoutData = new GridData(SWT.FILL, SWT.DEFAULT, true, false); - // pnLabel = new Label(topFrame, SWT.CENTER); - // pnLabel.setText("No active weather element"); - // pnLabel.setLayoutData(layoutData); Composite valueFrame = new Composite(topFrame, SWT.NONE); layout = new GridLayout(1, false); @@ -200,8 +197,7 @@ public class TEDiscreteSetValueDialog extends CaveJFACEDialog { } parm.endParmEdit(); } catch (GFEOperationFailedException exc) { - statusHandler.handle(Priority.PROBLEM, - "Grid edit failed", exc); + statusHandler.handle(Priority.PROBLEM, "Grid edit failed", exc); } super.okPressed(); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/mousehandler/TitleBarMouseHandler.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/mousehandler/TitleBarMouseHandler.java index 9c4c032148..df07c3a40a 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/mousehandler/TitleBarMouseHandler.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/temporaleditor/mousehandler/TitleBarMouseHandler.java @@ -38,6 +38,7 @@ import com.raytheon.viz.gfe.temporaleditor.AbstractTemporalEditorBar; import com.raytheon.viz.gfe.temporaleditor.TemporalEditorUtil; import com.raytheon.viz.gfe.temporaleditor.dialogs.DisplayAttributesDialog; import com.raytheon.viz.gfe.temporaleditor.dialogs.MoveWeatherElementDialog; +import com.raytheon.viz.ui.dialogs.ICloseCallback; /** * MouseHandler to resize temporal editor bars. @@ -47,6 +48,8 @@ import com.raytheon.viz.gfe.temporaleditor.dialogs.MoveWeatherElementDialog; * Date Ticket# Engineer Description * ------------ ---------- ------------- -------------------------- * May 28, 2009 #2159 Richard Peter Initial Creation. + * Nov 14, 2012 #1298 rferrel Changes for non-blocking DisplayAttributesDialog. + * Changes for non-blocking MoveWeatherElementDialog. * * * @author rjpeter @@ -122,11 +125,20 @@ public class TitleBarMouseHandler extends MouseHandler { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); + // The dialog being opened is modal to the parent + // dialog. This will prevent the launching of another + // dialog until the modal dialog is closed. DisplayAttributesDialog dialog = new DisplayAttributesDialog( shell, teBar, parm); - dialog.setBlockOnOpen(true); + dialog.setBlockOnOpen(false); + dialog.setCloseCallback(new ICloseCallback() { + + @Override + public void dialogClosed(Object returnValue) { + teBar.redraw(); + } + }); dialog.open(); - teBar.redraw(); } }); } @@ -140,10 +152,13 @@ public class TitleBarMouseHandler extends MouseHandler { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); + // The dialog being opened is modal to the parent + // dialog. This will prevent the launching of another + // dialog until the modal dialog is closed. MoveWeatherElementDialog dialog = new MoveWeatherElementDialog( shell, teBar.getTemporalEditor(), parm, teBar, barList); - dialog.setBlockOnOpen(true); + dialog.setBlockOnOpen(false); dialog.open(); } }); diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/textproduct/action/NewAction.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/textproduct/action/NewAction.java index d8a7b8c159..878531c951 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/textproduct/action/NewAction.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/textproduct/action/NewAction.java @@ -34,6 +34,7 @@ import com.raytheon.viz.gfe.dialogs.NewTextProductDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Sep 30, 2008 1562 askripsky Initial creation + * Nov 12, 2012 1298 rferrel Changes for non-blocking NewTextProductDialog. * * * @@ -58,8 +59,12 @@ public class NewAction extends Action { // Do this... Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getShell(); + // The dialog being opened is modal to the parent dialog. This will + // prevent the launching of another dialog until the modal dialog is + // closed. NewTextProductDialog dlg = new NewTextProductDialog(shell, "New Text Product", new NewInputValidator()); + dlg.setBlockOnOpen(false); dlg.open(); } } diff --git a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/ui/runtimeui/SelectionDlg.java b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/ui/runtimeui/SelectionDlg.java index 6f2f87c716..73b2189d6c 100644 --- a/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/ui/runtimeui/SelectionDlg.java +++ b/cave/com.raytheon.viz.gfe/src/com/raytheon/viz/gfe/ui/runtimeui/SelectionDlg.java @@ -46,6 +46,7 @@ import com.raytheon.viz.ui.dialogs.CaveJFACEDialog; * ------------ ---------- ----------- -------------------------- * Feb 9, 2010 3353 njensen Initial creation * Jul 13,2011 9291 rferrel Convert to subclass of CaveJFACEDialog. + * Nov 15,2012 1298 rferrel Code cleanup for non-blocking dialogs. * * * @@ -90,7 +91,7 @@ public abstract class SelectionDlg extends CaveJFACEDialog { this.name = title; this.dataMgr = dataMgr; this.fieldDefs = fieldDefs; - this.setShellStyle(SWT.MODELESS | SWT.TITLE | SWT.RESIZE); + this.setShellStyle(SWT.DIALOG_TRIM | SWT.MODELESS | SWT.RESIZE); } /* diff --git a/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/GhgMonitorAction.java b/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/GhgMonitorAction.java index cb4a908f32..70eecca0f1 100644 --- a/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/GhgMonitorAction.java +++ b/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/GhgMonitorAction.java @@ -35,6 +35,7 @@ import com.raytheon.viz.ghg.monitor.GhgMonitorDlg; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Mar 26, 2008 1033 lvenable Initial creation + * Nov 15, 2012 1298 rferrel Changes for non-blocking GhgMonitorDlg. * * * @@ -43,12 +44,15 @@ import com.raytheon.viz.ghg.monitor.GhgMonitorDlg; */ public class GhgMonitorAction extends AbstractHandler { + private GhgMonitorDlg monitorDlg; @Override public Object execute(ExecutionEvent arg0) throws ExecutionException { - Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() - .getShell(); - GhgMonitorDlg monitorDlg = new GhgMonitorDlg(shell); + if (monitorDlg == null) { + Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow() + .getShell(); + monitorDlg = new GhgMonitorDlg(shell); + } monitorDlg.open(); return null; diff --git a/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgAlertDlg.java b/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgAlertDlg.java index 7439b23936..40cb924411 100644 --- a/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgAlertDlg.java +++ b/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgAlertDlg.java @@ -47,6 +47,7 @@ import com.raytheon.viz.ui.dialogs.CaveSWTDialog; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 25 MAR 2008 N/A lvenable Initial creation + * 15 NOV 2012 1298 rferrel Changes for non-blocking dialog. * * * @@ -104,10 +105,15 @@ public class GhgAlertDlg extends CaveSWTDialog { * Parent Shell. */ public GhgAlertDlg(Shell parent) { - super(parent); + super(parent, SWT.DIALOG_TRIM, CAVE.DO_NOT_BLOCK); setText("GHG Monitor Alert Dialog"); } + /* + * (non-Javadoc) + * + * @see com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#constructShellLayout() + */ @Override protected Layout constructShellLayout() { // Create the main layout for the shell. @@ -118,11 +124,13 @@ public class GhgAlertDlg extends CaveSWTDialog { return mainLayout; } - @Override - protected void disposed() { - setReturnValue(alerts); - } - + /* + * (non-Javadoc) + * + * @see + * com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#initializeComponents(org + * .eclipse.swt.widgets.Shell) + */ @Override protected void initializeComponents(Shell shell) { // Initialize all of the controls and layouts @@ -264,7 +272,8 @@ public class GhgAlertDlg extends CaveSWTDialog { @Override public void widgetSelected(SelectionEvent event) { updateAlertingValues(); - shell.dispose(); + setReturnValue(alerts); + close(); } }); @@ -275,8 +284,8 @@ public class GhgAlertDlg extends CaveSWTDialog { cancelBtn.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent event) { - alerts = null; - shell.dispose(); + setReturnValue(null); + close(); } }); } diff --git a/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgMonitorDlg.java b/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgMonitorDlg.java index f03c47aae6..d32264bb5f 100644 --- a/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgMonitorDlg.java +++ b/cave/com.raytheon.viz.ghg/src/com/raytheon/viz/ghg/monitor/GhgMonitorDlg.java @@ -90,6 +90,7 @@ import com.raytheon.viz.ghg.monitor.filter.GhgFilterEngine; import com.raytheon.viz.ghg.monitor.listener.GhgMonitorFilterChangeListener; import com.raytheon.viz.ghg.monitor.listener.GhgMonitorZoneSelectionListener; import com.raytheon.viz.ui.dialogs.CaveSWTDialog; +import com.raytheon.viz.ui.dialogs.ICloseCallback; import com.raytheon.viz.ui.statusline.EdgeLayout; import com.raytheon.viz.ui.statusline.EdgeLayout.EdgeLayoutData; import com.raytheon.viz.ui.statusline.EdgeLayout.EdgeLayoutData.EdgeAffinity; @@ -108,6 +109,8 @@ import com.raytheon.viz.ui.statusline.StatusStore; * ------------ ---------- ----------- -------------------------- * 25 MAR 2008 N/A lvenable Initial creation * 17Jun2008 1157 MW Fegan Pass configuration to sub-dialogs. + * 15 Nov 2012 1298 rferrel Changes for non-blocking dialog. + * Changes for non-blocking GhgAlertDlg. * * * @@ -118,30 +121,32 @@ import com.raytheon.viz.ui.statusline.StatusStore; public class GhgMonitorDlg extends CaveSWTDialog implements GhgMonitorFilterChangeListener, GhgMonitorZoneSelectionListener, INotificationObserver { - private static final transient IUFStatusHandler statusHandler = UFStatus + private final transient IUFStatusHandler statusHandler = UFStatus .getHandler(GhgMonitorDlg.class); private static final Map labelToEnumMap; + private GhgAlertDlg alertDlg; + /** * Active group one string. */ - private static final String ACT_GROUP_ONE_STRING = " CON EXA EXB EXT NEW "; + private final String ACT_GROUP_ONE_STRING = " CON EXA EXB EXT NEW "; /** * Active group two string. */ - private static final String ACT_GROUP_TWO_STRING = " CAN EXP UPG "; + private final String ACT_GROUP_TWO_STRING = " CAN EXP UPG "; /** * Default timeout value. */ - private static final long DEFAULT_TIMEOUT = 30000; + private final long DEFAULT_TIMEOUT = 30000; /** * Status bar definition key. */ - private static final String STATUS_KEY = com.raytheon.viz.ghg.constants.StatusConstants.CATEGORY_GHG; + private final String STATUS_KEY = com.raytheon.viz.ghg.constants.StatusConstants.CATEGORY_GHG; /** * The currently selected font data (is null until font is selected) @@ -229,7 +234,8 @@ public class GhgMonitorDlg extends CaveSWTDialog implements * Parent Shell. */ public GhgMonitorDlg(Shell parent) { - super(parent, SWT.RESIZE, CAVE.INDEPENDENT_SHELL); + super(parent, SWT.DIALOG_TRIM | SWT.RESIZE, CAVE.INDEPENDENT_SHELL + | CAVE.DO_NOT_BLOCK); // Register as a listener to the display manager and VTECActiveTable GhgDisplayManager.getInstance().addGhgMonitorFilterChangeListener(this); @@ -1080,15 +1086,25 @@ public class GhgMonitorDlg extends CaveSWTDialog implements * Display the Define Alerts dialog. */ private void showDefineAlertsDialog() { - GhgConfigData configuration = GhgConfigData.getInstance(); - GhgAlertDlg alertDlg = new GhgAlertDlg(getShell()); - alertDlg.setAlerts(configuration.getAlerts()); - GhgAlertsConfigData rtnAlerts = (GhgAlertsConfigData) alertDlg.open(); + if (alertDlg == null) { + GhgConfigData configuration = GhgConfigData.getInstance(); + alertDlg = new GhgAlertDlg(getShell()); + alertDlg.setAlerts(configuration.getAlerts()); + alertDlg.setCloseCallback(new ICloseCallback() { - // null is returned if the dialog is canceled - if (rtnAlerts != null) { - configuration.setAlerts(rtnAlerts); + @Override + public void dialogClosed(Object returnValue) { + if (returnValue instanceof GhgAlertsConfigData) { + GhgAlertsConfigData rtnAlerts = (GhgAlertsConfigData) returnValue; + GhgConfigData configuration = GhgConfigData + .getInstance(); + configuration.setAlerts(rtnAlerts); + } + alertDlg = null; + } + }); } + alertDlg.open(); } /** diff --git a/cave/com.raytheon.viz.grib.feature/feature.xml b/cave/com.raytheon.viz.grib.feature/feature.xml index 4c9687e9fa..a2d20aaebc 100644 --- a/cave/com.raytheon.viz.grib.feature/feature.xml +++ b/cave/com.raytheon.viz.grib.feature/feature.xml @@ -32,11 +32,4 @@ install-size="0" version="0.0.0"/> - - diff --git a/cave/com.raytheon.viz.grid/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.grid/META-INF/MANIFEST.MF index e58e81f75f..949ac37275 100644 --- a/cave/com.raytheon.viz.grid/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.viz.grid/META-INF/MANIFEST.MF @@ -5,7 +5,7 @@ Bundle-SymbolicName: com.raytheon.viz.grid;singleton:=true Bundle-Version: 1.12.1174.qualifier Bundle-Activator: com.raytheon.viz.grid.Activator Bundle-Vendor: Raytheon -Eclipse-RegisterBuddy: com.raytheon.viz.core, com.raytheon.uf.viz.core +Eclipse-RegisterBuddy: com.raytheon.viz.core, com.raytheon.uf.viz.core, com.raytheon.uf.common.dataplugin.grid.coverage Eclipse-BuddyPolicy: ext, global Require-Bundle: org.eclipse.ui, org.eclipse.core.runtime, @@ -22,10 +22,12 @@ Require-Bundle: org.eclipse.ui, com.raytheon.uf.common.serialization.comm, com.raytheon.uf.viz.productbrowser;bundle-version="1.11.31", com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", - com.raytheon.uf.viz.points;bundle-version="1.0.0" + com.raytheon.uf.viz.points;bundle-version="1.0.0", + com.raytheon.uf.common.gridcoverage, + org.apache.commons.beanutils;bundle-version="1.8.3", + com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0" Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.viz.grid, - com.raytheon.viz.grid.gridcache, com.raytheon.viz.grid.inv, com.raytheon.viz.grid.rsc, com.raytheon.viz.grid.rsc.general, @@ -34,17 +36,12 @@ Export-Package: com.raytheon.viz.grid, Import-Package: com.raytheon.edex.scriptfactory, com.raytheon.uf.common.colormap, com.raytheon.uf.common.comm, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.exception, - com.raytheon.uf.common.dataplugin.grib.request, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.grib.subgrid, - com.raytheon.uf.common.dataplugin.grib.util, com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.derivparam.tree, com.raytheon.uf.common.localization, com.raytheon.uf.common.message, com.raytheon.uf.common.message.response, + com.raytheon.uf.common.parameter, com.raytheon.uf.common.pointdata, com.raytheon.uf.common.serialization, com.raytheon.uf.common.time, diff --git a/cave/com.raytheon.viz.grid/META-INF/services/com.raytheon.uf.viz.core.datastructure.IDataCubeAdapter b/cave/com.raytheon.viz.grid/META-INF/services/com.raytheon.uf.viz.core.datastructure.IDataCubeAdapter index 948e8f2d98..9df436d24f 100644 --- a/cave/com.raytheon.viz.grid/META-INF/services/com.raytheon.uf.viz.core.datastructure.IDataCubeAdapter +++ b/cave/com.raytheon.viz.grid/META-INF/services/com.raytheon.uf.viz.core.datastructure.IDataCubeAdapter @@ -1 +1 @@ -com.raytheon.viz.grid.util.GribDataCubeAdapter \ No newline at end of file +com.raytheon.viz.grid.util.GridDataCubeAdapter \ No newline at end of file diff --git a/cave/com.raytheon.viz.grid/localization/bundles/grib/gribImageBundle.xml b/cave/com.raytheon.viz.grid/localization/bundles/grib/gribImageBundle.xml index 0c4526d4bc..ed71894444 100644 --- a/cave/com.raytheon.viz.grid/localization/bundles/grib/gribImageBundle.xml +++ b/cave/com.raytheon.viz.grid/localization/bundles/grib/gribImageBundle.xml @@ -40,16 +40,16 @@ - + - + - + - + diff --git a/cave/com.raytheon.viz.grid/localization/bundles/grib/gribVectorBundle.xml b/cave/com.raytheon.viz.grid/localization/bundles/grib/gribVectorBundle.xml index 087c05d846..392f60475a 100644 --- a/cave/com.raytheon.viz.grid/localization/bundles/grib/gribVectorBundle.xml +++ b/cave/com.raytheon.viz.grid/localization/bundles/grib/gribVectorBundle.xml @@ -35,16 +35,16 @@ - + - + - + - + diff --git a/cave/com.raytheon.viz.grid/localization/styleRules/gridImageryStyleRules.xml b/cave/com.raytheon.viz.grid/localization/styleRules/gridImageryStyleRules.xml index da570400d3..3a65243be8 100644 --- a/cave/com.raytheon.viz.grid/localization/styleRules/gridImageryStyleRules.xml +++ b/cave/com.raytheon.viz.grid/localization/styleRules/gridImageryStyleRules.xml @@ -2422,12 +2422,12 @@ % - -1 + 5 105 Grid/warm to cold - 20 40 60 80 100 + 20 diff --git a/cave/com.raytheon.viz.grid/plugin.xml b/cave/com.raytheon.viz.grid/plugin.xml index bb3df147fa..ab42369f93 100644 --- a/cave/com.raytheon.viz.grid/plugin.xml +++ b/cave/com.raytheon.viz.grid/plugin.xml @@ -22,21 +22,10 @@ - - diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/Activator.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/Activator.java index bf1a4ce77b..b90d13076b 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/Activator.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/Activator.java @@ -27,43 +27,49 @@ import org.osgi.framework.BundleContext; */ public class Activator extends AbstractUIPlugin { - // The plug-in ID - public static final String PLUGIN_ID = "com.raytheon.viz.grid"; + // The plug-in ID + public static final String PLUGIN_ID = "com.raytheon.viz.grid"; - // The shared instance - private static Activator plugin; - - /** - * The constructor - */ - public Activator() { - plugin = this; - } + // The shared instance + private static Activator plugin; - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext) - */ - public void start(BundleContext context) throws Exception { - super.start(context); - } + /** + * The constructor + */ + public Activator() { + plugin = this; + } - /* - * (non-Javadoc) - * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext) - */ - public void stop(BundleContext context) throws Exception { - plugin = null; - super.stop(context); - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext + * ) + */ + public void start(BundleContext context) throws Exception { + super.start(context); + } - /** - * Returns the shared instance - * - * @return the shared instance - */ - public static Activator getDefault() { - return plugin; - } + /* + * (non-Javadoc) + * + * @see + * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext + * ) + */ + public void stop(BundleContext context) throws Exception { + plugin = null; + super.stop(context); + } + + /** + * Returns the shared instance + * + * @return the shared instance + */ + public static Activator getDefault() { + return plugin; + } } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridDataCubeFactory.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridDataCubeFactory.java deleted file mode 100644 index 5e13d95110..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridDataCubeFactory.java +++ /dev/null @@ -1,112 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid; - -import javax.measure.unit.Unit; - -import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.datastorage.records.IDataRecord; -import com.raytheon.uf.common.geospatial.ISpatialObject; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.datastructure.AbstractDataCubeFactory; -import com.raytheon.uf.viz.core.datastructure.CubeUtil; -import com.raytheon.uf.viz.core.datastructure.DataCube; -import com.raytheon.uf.viz.core.datastructure.VizDataCubeException; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.style.level.SingleLevel; - -/** - * Factory for creating data cubes from GribRecords - * - *
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 28, 2007            njensen     Initial creation
- * 
- * 
- * - * @author njensen - * @version 1.0 - */ - -public class GridDataCubeFactory extends AbstractDataCubeFactory { - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.datastructure.AbstractDataCubeFactory#construct - * (com.raytheon.edex.db.objects.PluginDataObject[]) - */ - @Override - public DataCube construct(PluginDataObject[] pdos, DataCube.Mode mode) - throws VizDataCubeException { - GribRecord[] grids = new GribRecord[pdos.length]; - String parameter = null; - ISpatialObject spatial = null; - Unit units = null; - for (int i = 0; i < grids.length; i++) { - grids[i] = (GribRecord) pdos[i]; - if (i == 0) { - parameter = grids[i].getModelInfo().getParameterName(); - spatial = (grids[i].getSpatialObject()); - units = grids[i].getModelInfo().getParameterUnitObject(); - } else { - if (!grids[i].getModelInfo().getParameterName().equals( - parameter)) { - throw new VizDataCubeException( - "Only one parameter allowed per data cube."); - } - } - } - - DataCube cube = new DataCube("grib", mode); - cube.setSpatialArea(spatial); - cube.setParameter(parameter); - cube.setUnits(units); - - for (GribRecord rec : grids) { - SingleLevel level = GridLevelTranslator.construct(rec - .getModelInfo().getLevelName()); - level.setValue(rec.getModelInfo().getLevelOneValue()); - DataTime time = rec.getDataTime(); - if (mode == DataCube.Mode.ON_DEMAND) { - cube.addData(time, level, rec); - } else if (mode == DataCube.Mode.EAGER) { - IDataRecord dr = null; - try { - dr = CubeUtil.retrieveData(rec, "grib"); - } catch (VizException e) { - throw new VizDataCubeException( - "Error retrieving data to form cube.", e); - } - if (dr != null) { - float[] data = (float[]) dr.getDataObject(); - rec.setMessageData(data); - cube.addData(time, level, rec); - } - } - } - cube.initGeometry(); - return cube; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridLevelTranslator.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridLevelTranslator.java index 5046f37b56..36945cc64a 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridLevelTranslator.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridLevelTranslator.java @@ -24,7 +24,7 @@ import javax.measure.unit.NonSI; import javax.measure.unit.SI; import javax.measure.unit.Unit; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.viz.core.style.level.Level; import com.raytheon.uf.viz.core.style.level.SingleLevel; @@ -91,23 +91,8 @@ public class GridLevelTranslator { } - public static SingleLevel construct(GribRecord record) { - Unit levelUnits = record.getModelInfo().getLevelUnitObject(); - - UnitConverter levelConverter = UnitConverter.IDENTITY; - if (levelUnits.isCompatible(SI.MILLI(NonSI.BAR))) { - levelConverter = levelUnits.getConverterTo(SI.MILLI(NonSI.BAR)); - } - - float convertedLevel = (float) levelConverter.convert(record - .getModelInfo().getLevelOneValue()); - SingleLevel level = construct(record.getModelInfo().getLevelName()); - level.setValue(convertedLevel); - return level; - } - - public static SingleLevel constructMatching(GribRecord record) { - return constructMatching(record.getModelInfo().getLevel()); + public static SingleLevel constructMatching(GridRecord record) { + return constructMatching(record.getLevel()); } public static SingleLevel constructMatching( diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridProductBrowserDataDefinition.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridProductBrowserDataDefinition.java index ee963d6d51..d9c2e02481 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridProductBrowserDataDefinition.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/GridProductBrowserDataDefinition.java @@ -27,15 +27,18 @@ import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import com.raytheon.uf.common.comm.CommunicationException; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.dataplugin.level.MasterLevel; @@ -44,6 +47,8 @@ import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; +import com.raytheon.uf.viz.core.exception.VizCommunicationException; +import com.raytheon.uf.viz.core.level.LevelMappingFactory; import com.raytheon.uf.viz.core.rsc.DisplayType; import com.raytheon.uf.viz.core.rsc.LoadProperties; import com.raytheon.uf.viz.core.rsc.ResourceType; @@ -77,8 +82,6 @@ public class GridProductBrowserDataDefinition extends private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(GridProductBrowserDataDefinition.class); - private static final String SHOW_UNKNOWN_MODELS = "Show Unknown Models"; - private static final String SHOW_DERIVED_PARAMS = "Show Derived Parameters"; private static final Comparator levelComparator = new Comparator() { @@ -104,11 +107,11 @@ public class GridProductBrowserDataDefinition extends }; public GridProductBrowserDataDefinition() { - productName = "grib"; + productName = GridInventory.PLUGIN_NAME; displayName = "Grid"; - order = new String[] { GridInventory.PLUGIN_NAME_QUERY, - GridInventory.MODEL_NAME_QUERY, GridInventory.PARAMETER_QUERY, - GridInventory.MASTER_LEVEL_QUERY, "modelInfo.level.id" }; + order = new String[] { GridInventory.MODEL_NAME_QUERY, + GridInventory.PARAMETER_QUERY, + GridInventory.MASTER_LEVEL_QUERY, GridInventory.LEVEL_ID_QUERY }; order = getOrder(); loadProperties = new LoadProperties(); loadProperties.setResourceType(getResourceType()); @@ -127,79 +130,119 @@ public class GridProductBrowserDataDefinition extends } @Override - public List populateData(String[] selection) { - // inventory and cannot label each level of product browser - if (getInventory() == null) { - return super.populateData(selection); - } - Collection sources = null; - Collection params = null; - Collection levels = null; - BlockingQueue returnQueue = new LinkedBlockingQueue(); - if (selection.length > 1) { - sources = Arrays.asList(selection[1]); - } else { - try { - getInventory().checkSources(sources, params, levels, - returnQueue); - } catch (InterruptedException e) { - e.printStackTrace(); - } - List results = formatData( - GridInventory.MODEL_NAME_QUERY, - returnQueue.toArray(new String[returnQueue.size()])); - Collections.sort(results); - return results; - } - if (selection.length > 2) { - params = Arrays.asList(selection[2]); - } else { - try { - getInventory().checkParameters(sources, params, levels, false, - returnQueue); - } catch (InterruptedException e) { - e.printStackTrace(); - } - List results = formatData( - GridInventory.PARAMETER_QUERY, - returnQueue.toArray(new String[returnQueue.size()])); - Collections.sort(results); - return results; - } + protected String[] queryData(String param, + HashMap queryList) { try { - getInventory().checkLevels(sources, params, levels, returnQueue); - } catch (InterruptedException e) { - e.printStackTrace(); - } - LevelFactory lf = LevelFactory.getInstance(); - try { - if (selection.length > 3) { - List availLevels = new ArrayList(); - for (String levelid : returnQueue) { - Level level = lf.getLevel(levelid); - if (level.getMasterLevel().getName().equals(selection[3])) { - availLevels.add(levelid); + if (getInventory() == null) { + return super.queryData(param, queryList); + } else { + Collection sources = null; + Collection params = null; + Collection levels = null; + BlockingQueue returnQueue = new LinkedBlockingQueue(); + for (Entry queryParam : queryList + .entrySet()) { + String key = queryParam.getKey(); + String value = queryParam.getValue().getConstraintValue(); + if (key.equals(GridInventory.MODEL_NAME_QUERY)) { + sources = Arrays.asList(value); + } else if (key.equals(GridInventory.PARAMETER_QUERY)) { + params = Arrays.asList(value); + } else if (key.equals(GridInventory.MASTER_LEVEL_QUERY)) { + if (levels == null) { + levels = new ArrayList(LevelMappingFactory + .getInstance().getAllLevels()); + } + Iterator iter = levels.iterator(); + while (iter.hasNext()) { + if (!iter.next().getMasterLevel().getName() + .equals(value)) { + iter.remove(); + } + } + + } else if (key.equals(GridInventory.LEVEL_ONE_QUERY)) { + double doubleValue = Double.parseDouble(value); + if (levels == null) { + levels = new ArrayList(LevelMappingFactory + .getInstance().getAllLevels()); + } + Iterator iter = levels.iterator(); + while (iter.hasNext()) { + if (iter.next().getLevelonevalue() != doubleValue) { + iter.remove(); + } + } + } else if (key.equals(GridInventory.LEVEL_TWO_QUERY)) { + double doubleValue = Double.parseDouble(value); + if (levels == null) { + levels = new ArrayList(LevelMappingFactory + .getInstance().getAllLevels()); + } + Iterator iter = levels.iterator(); + while (iter.hasNext()) { + if (iter.next().getLeveltwovalue() != doubleValue) { + iter.remove(); + } + } + } else if (key.equals(GridInventory.LEVEL_ID_QUERY)) { + levels = Arrays.asList(LevelFactory.getInstance() + .getLevel(value)); } } - return formatData(GridInventory.LEVEL_ID_QUERY, - availLevels.toArray(new String[availLevels.size()])); - } else { - Set masterLevels = new HashSet(); - for (String levelid : returnQueue) { - Level level = lf.getLevel(levelid); - masterLevels.add(level.getMasterLevel().getName()); - } - List results = formatData( - GridInventory.MASTER_LEVEL_QUERY, - masterLevels.toArray(new String[masterLevels.size()])); - Collections.sort(results); - return results; - } - } catch (CommunicationException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); - return super.populateData(selection); - } + if (param.equals(GridInventory.MODEL_NAME_QUERY)) { + try { + getInventory().checkSources(sources, params, levels, + returnQueue); + } catch (InterruptedException e) { + statusHandler.handle(Priority.PROBLEM, + e.getLocalizedMessage(), e); + } + return returnQueue.toArray(new String[0]); + } else if (param.equals(GridInventory.PARAMETER_QUERY)) { + try { + getInventory().checkParameters(sources, params, levels, + false, returnQueue); + } catch (InterruptedException e) { + statusHandler.handle(Priority.PROBLEM, + e.getLocalizedMessage(), e); + } + return returnQueue.toArray(new String[0]); + } else if (param.equals(GridInventory.MASTER_LEVEL_QUERY)) { + try { + getInventory().checkLevels(sources, params, levels, + returnQueue); + } catch (InterruptedException e) { + statusHandler.handle(Priority.PROBLEM, + e.getLocalizedMessage(), e); + } + Set masterlevels = new HashSet(); + LevelFactory lf = LevelFactory.getInstance(); + for (String levelid : returnQueue) { + Level level = lf.getLevel(levelid); + masterlevels.add(level.getMasterLevel().getName()); + } + return masterlevels.toArray(new String[0]); + } else if (param.equals(GridInventory.LEVEL_ID_QUERY)) { + try { + getInventory().checkLevels(sources, params, levels, + returnQueue); + } catch (InterruptedException e) { + statusHandler.handle(Priority.PROBLEM, + e.getLocalizedMessage(), e); + } + return returnQueue.toArray(new String[0]); + } + } + } catch (VizCommunicationException e) { + statusHandler.handle(Priority.ERROR, "Unable to query data for " + + productName, e); + } catch (CommunicationException e) { + statusHandler.handle(Priority.ERROR, "Unable to query data for " + + productName, e); + } + return new String[0]; } /* @@ -213,83 +256,69 @@ public class GridProductBrowserDataDefinition extends public List formatData(String param, String[] parameters) { List labels = new ArrayList(); - if (!(Boolean) getPreference(FORMAT_DATA).getValue()) { - boolean isProduct = false; - if (GridInventory.LEVEL_ID_QUERY.equals(param)) { - isProduct = true; - } - for (String string : parameters) { - ProductBrowserLabel label = new ProductBrowserLabel(string, - string); - label.setProduct(isProduct); - labels.add(label); - } - return labels; - } - if (GridInventory.MODEL_NAME_QUERY.equals(param)) { - GribModelLookup lookup = GribModelLookup.getInstance(); - for (int i = 0; i < parameters.length; i++) { - GridModel model = lookup.getModelByName(parameters[i]); - if (model == null) { - if (!(Boolean) getPreference(SHOW_UNKNOWN_MODELS) - .getValue()) { - continue; + try { + if (GridInventory.MODEL_NAME_QUERY.equals(param)) { + DatasetInfoLookup lookup = DatasetInfoLookup.getInstance(); + for (int i = 0; i < parameters.length; i++) { + DatasetInfo info = lookup.getInfo(parameters[i]); + if (info == null) { + labels.add(new ProductBrowserLabel(parameters[i], + parameters[i])); + } else { + labels.add(new ProductBrowserLabel(info.getTitle() + + " (" + " (" + parameters[i] + ")", + parameters[i])); } - labels.add(new ProductBrowserLabel(parameters[i], - parameters[i])); - } else { - labels.add(new ProductBrowserLabel(model.getTitle() + " (" - + parameters[i] + ")", parameters[i])); } - } - return labels; - } else if (GridInventory.PARAMETER_QUERY.equals(param)) { - Map library = DerivedParameterGenerator - .getDerParLibrary(); - for (int i = 0; i < parameters.length; i++) { - DerivParamDesc desc = library.get(parameters[i]); - if (desc == null || desc.getName().isEmpty()) { - labels.add(new ProductBrowserLabel(parameters[i], - parameters[i])); - } else { - labels.add(new ProductBrowserLabel(desc.getName(), - parameters[i])); + Collections.sort(labels); + return labels; + } else if (GridInventory.PARAMETER_QUERY.equals(param)) { + Map library = DerivedParameterGenerator + .getDerParLibrary(); + for (int i = 0; i < parameters.length; i++) { + DerivParamDesc desc = library.get(parameters[i]); + if (desc == null || desc.getName().isEmpty()) { + labels.add(new ProductBrowserLabel(parameters[i], + parameters[i])); + } else { + labels.add(new ProductBrowserLabel(desc.getName() + + " (" + parameters[i] + ")", parameters[i])); + } } - } - return labels; - } else if (GridInventory.LEVEL_ID_QUERY.equals(param)) { - Level[] levels = new Level[parameters.length]; - LevelFactory lf = LevelFactory.getInstance(); - try { + Collections.sort(labels); + return labels; + } else if (GridInventory.LEVEL_ID_QUERY.equals(param)) { + Level[] levels = new Level[parameters.length]; + LevelFactory lf = LevelFactory.getInstance(); for (int i = 0; i < levels.length; i++) { levels[i] = lf.getLevel(parameters[i]); } - } catch (CommunicationException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), - e); - } - Arrays.sort(levels, levelComparator); - for (int i = 0; i < parameters.length; i++) { - String levelName = levels[i].toString().replace("_", "-"); - levelName = levelName.replace(levels[i].getMasterLevel() - .getName(), " " + levels[i].getMasterLevel().getName()); - labels.add(new ProductBrowserLabel(levelName, Long - .toString(levels[i].getId()))); - labels.get(i).setProduct(true); - } - return labels; - } else if (GridInventory.MASTER_LEVEL_QUERY.equals(param)) { - LevelFactory lf = LevelFactory.getInstance(); - try { + Arrays.sort(levels, levelComparator); + for (int i = 0; i < parameters.length; i++) { + String levelName = levels[i].toString().replace("_", "-"); + levelName = levelName.replace(levels[i].getMasterLevel() + .getName(), " " + + levels[i].getMasterLevel().getName()); + labels.add(new ProductBrowserLabel(levelName, Long + .toString(levels[i].getId()))); + } + return labels; + } else if (GridInventory.MASTER_LEVEL_QUERY.equals(param)) { + LevelFactory lf = LevelFactory.getInstance(); for (int i = 0; i < parameters.length; i++) { MasterLevel masterLevel = lf.getMasterLevel(parameters[i]); labels.add(new ProductBrowserLabel(masterLevel - .getDescription(), masterLevel.getName())); + .getDescription() + + " (" + + masterLevel.getName() + + ")", masterLevel.getName())); } - } catch (CommunicationException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), - e); + Collections.sort(labels); + return labels; } + } catch (CommunicationException e) { + statusHandler.handle(Priority.ERROR, "Unable to format data for " + + productName, e); } return super.formatData(param, parameters); } @@ -302,24 +331,38 @@ public class GridProductBrowserDataDefinition extends } HashMap queryList = super .getProductParameters(selection, order); - try { + if (queryList.containsKey(GridInventory.LEVEL_ID_QUERY)) { + RequestConstraint levelRC = queryList + .remove(GridInventory.LEVEL_ID_QUERY); // Convert Level id to level one and level two values. - Level level = LevelFactory.getInstance().getLevel(selection[4]); - queryList.put(GridInventory.LEVEL_ONE_QUERY, new RequestConstraint( - level.getLevelOneValueAsString())); - queryList.put(GridInventory.LEVEL_TWO_QUERY, new RequestConstraint( - level.getLevelTwoValueAsString())); - queryList.remove(order[4]); - } catch (CommunicationException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); - + try { + Level level = LevelFactory.getInstance().getLevel( + levelRC.getConstraintValue()); + queryList + .put(GridInventory.LEVEL_ONE_QUERY, + new RequestConstraint(level + .getLevelOneValueAsString())); + queryList + .put(GridInventory.LEVEL_TWO_QUERY, + new RequestConstraint(level + .getLevelTwoValueAsString())); + queryList + .put(GridInventory.MASTER_LEVEL_QUERY, + new RequestConstraint(level.getMasterLevel() + .getName())); + } catch (CommunicationException e) { + statusHandler.handle(Priority.ERROR, + "Unable to get product parameters for " + productName, + e); + } } return queryList; } private GridInventory getInventory() { if ((Boolean) getPreference(SHOW_DERIVED_PARAMS).getValue()) { - return (GridInventory) DataCubeContainer.getInventory("grib"); + return (GridInventory) DataCubeContainer + .getInventory(GridConstants.GRID); } else { return null; } @@ -358,13 +401,6 @@ public class GridProductBrowserDataDefinition extends .setTooltip("Show derived parameters in the Product Browser"); derivedParameterPref.setValue(true); widgets.add(derivedParameterPref); - ProductBrowserPreference unknownPreference = new ProductBrowserPreference(); - unknownPreference.setLabel(SHOW_UNKNOWN_MODELS); - unknownPreference.setPreferenceType(PreferenceType.BOOLEAN); - unknownPreference - .setTooltip("Show unknown models in the Product Browser"); - unknownPreference.setValue(true); - widgets.add(unknownPreference); return widgets; } } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GribRequestableData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GridRequestableData.java similarity index 85% rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GribRequestableData.java rename to cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GridRequestableData.java index a815a1cc4b..1af247ccbb 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GribRequestableData.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GridRequestableData.java @@ -24,7 +24,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; @@ -34,7 +34,7 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator; /** - * TODO Add Description + * A requestable data object for which wraps a GridRecord. * *
  * 
@@ -49,7 +49,7 @@ import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator;
  * @version 1.0
  */
 
-public class GribRequestableData extends AbstractRequestableData {
+public class GridRequestableData extends AbstractRequestableData {
 
     protected Map> cache = Collections
             .synchronizedMap(new HashMap>());
@@ -57,41 +57,38 @@ public class GribRequestableData extends AbstractRequestableData {
     protected Map timeRequested = Collections
             .synchronizedMap(new HashMap());
 
-    protected GribRecord gribSource;
+    protected GridRecord gridSource;
 
-    protected GribRequestableData() {
+    protected GridRequestableData() {
     }
 
-    protected GribRequestableData(GribRecord source) {
-        this.gribSource = source;
-        this.source = source.getModelInfo().getModelName();
+    protected GridRequestableData(GridRecord source) {
+        this.gridSource = source;
+        this.source = source.getDatasetId();
         this.dataTime = source.getDataTime();
-        this.level = source.getModelInfo().getLevel();
-        this.parameter = source.getModelInfo().getParameterAbbreviation();
-        this.unit = source.getModelInfo().getParameterUnitObject();
+        this.space = source.getLocation();
+        this.level = source.getLevel();
+        this.parameter = source.getParameter().getAbbreviation();
+        this.unit = source.getParameter().getUnit();
         if (DerivedParameterGenerator.getDerParLibrary().containsKey(
                 this.parameter)) {
             DerivParamDesc derivParamDesc = DerivedParameterGenerator
                     .getDerParLibrary().get(this.parameter);
             this.parameterName = derivParamDesc.getName();
         } else {
-            this.parameterName = source.getModelInfo().getParameterName();
+            this.parameterName = source.getParameter().getName();
         }
     }
 
     /**
      * @return the source
      */
-    public GribRecord getGribSource() {
-        return gribSource;
+    public GridRecord getGridSource() {
+        return gridSource;
     }
 
-    /**
-     * @param source
-     *            the source to set
-     */
-    public void setGribSource(GribRecord source) {
-        this.gribSource = source;
+    public void setGridSource(GridRecord gridSource) {
+        this.gridSource = gridSource;
     }
 
     public boolean needsRequest(Request request) {
@@ -167,7 +164,7 @@ public class GribRequestableData extends AbstractRequestableData {
                 // + (time - timeLastRequest) + " ms ago");
                 // }
 
-                result = DataCubeContainer.getDataRecord(gribSource,
+                result = DataCubeContainer.getDataRecord(gridSource,
                         (Request) arg, null);
 
                 cache.put(request, new SoftReference(result));
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GribRequestableDataFactory.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GridRequestableDataFactory.java
similarity index 69%
rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GribRequestableDataFactory.java
rename to cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GridRequestableDataFactory.java
index 23ad64a817..335e4020cf 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GribRequestableDataFactory.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/GridRequestableDataFactory.java
@@ -23,13 +23,16 @@ import java.util.Collection;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
 
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.viz.core.alerts.AlertMessage;
 import com.raytheon.viz.alerts.IAlertObserver;
 import com.raytheon.viz.alerts.observers.ProductAlertObserver;
 
 /**
- * TODO Add Description
+ * Provides a cache of GridRequestableDataObjcts, since these objects have the a
+ * SoftReference to the raw data loading a cached object might be able to
+ * provide faster data loading.
  * 
  * 
  * 
@@ -45,29 +48,29 @@ import com.raytheon.viz.alerts.observers.ProductAlertObserver;
  * @version 1.0
  */
 
-public class GribRequestableDataFactory implements IAlertObserver {
-    private static GribRequestableDataFactory instance = new GribRequestableDataFactory();
+public class GridRequestableDataFactory implements IAlertObserver {
+    private static GridRequestableDataFactory instance = new GridRequestableDataFactory();
 
-    public static GribRequestableDataFactory getInstance() {
+    public static GridRequestableDataFactory getInstance() {
         return instance;
     }
 
-    private Map requestableDataMap = new ConcurrentHashMap();
+    private Map requestableDataMap = new ConcurrentHashMap();
 
-    public GribRequestableDataFactory() {
-        ProductAlertObserver.addObserver("grib", this);
+    public GridRequestableDataFactory() {
+        ProductAlertObserver.addObserver(GridConstants.GRID, this);
     }
 
-    public GribRequestableData getGribRequestableData(GribRecord record) {
+    public GridRequestableData getGridRequestableData(GridRecord record) {
         String uri = record.getDataURI();
-        GribRequestableData rval = requestableDataMap.get(uri);
+        GridRequestableData rval = requestableDataMap.get(uri);
 
         if (rval == null) {
             synchronized (this) {
                 // double check value still null
                 rval = requestableDataMap.get(uri);
                 if (rval == null) {
-                    rval = new GribRequestableData(record);
+                    rval = new GridRequestableData(record);
                     requestableDataMap.put(uri, rval);
                 }
             }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/ImportRequestableData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/ImportRequestableData.java
index 8aeb18df05..cdbb1669f1 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/ImportRequestableData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/ImportRequestableData.java
@@ -24,10 +24,10 @@ import java.util.List;
 
 import javax.media.jai.Interpolation;
 
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
 import com.raytheon.uf.common.datastorage.Request;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
 import com.raytheon.uf.common.datastorage.records.IDataRecord;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
 import com.raytheon.uf.common.time.DataTime;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
@@ -115,8 +115,8 @@ public class ImportRequestableData extends AliasRequestableData {
         }
 
         CoverageUtils covUtil = CoverageUtils.getInstance();
-        GridCoverage sourceGrid = covUtil.getCoverage(sourceRecord.getSource());
-        GridCoverage destGrid = covUtil.getCoverage(this.getSource());
+        GridCoverage sourceGrid = (GridCoverage) sourceRecord.getSpace();
+        GridCoverage destGrid = (GridCoverage) getSpace();
         Interpolation interpolation = Interpolation
                 .getInstance(Interpolation.INTERP_BICUBIC);
         if (rval instanceof FloatDataRecord) {
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/RadarRequestableData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/RadarRequestableData.java
index df22c50f35..02902f109e 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/RadarRequestableData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/RadarRequestableData.java
@@ -26,9 +26,8 @@ import javax.measure.converter.UnitConverter;
 import javax.measure.unit.Unit;
 
 import com.raytheon.uf.common.comm.CommunicationException;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.dataplugin.level.LevelFactory;
 import com.raytheon.uf.common.dataplugin.radar.RadarRecord;
 import com.raytheon.uf.common.dataplugin.radar.util.RadarDataRetriever;
@@ -38,6 +37,8 @@ import com.raytheon.uf.common.datastorage.IDataStore;
 import com.raytheon.uf.common.datastorage.Request;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
 import com.raytheon.uf.common.datastorage.records.IDataRecord;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
+import com.raytheon.uf.common.parameter.Parameter;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
@@ -49,7 +50,8 @@ import com.raytheon.viz.grid.util.SliceUtil;
 import com.raytheon.viz.radar.util.DataUtilities;
 
 /**
- * TODO Add Description
+ * A requestable data record which wraps a RadarRecord and can convert radar
+ * radial data into the expected radar projection and units.
  * 
  * 
  * 
@@ -64,7 +66,7 @@ import com.raytheon.viz.radar.util.DataUtilities;
  * @version 1.0
  */
 
-public class RadarRequestableData extends GribRequestableData {
+public class RadarRequestableData extends GridRequestableData {
     private static final transient IUFStatusHandler statusHandler = UFStatus
             .getHandler(RadarRequestableData.class);
 
@@ -86,6 +88,7 @@ public class RadarRequestableData extends GribRequestableData {
                 RadarAdapter.getGridSpacing());
         this.source = "radar";
         this.dataTime = source.getDataTime();
+        this.space = RadarAdapter.getInstance().getCoverage();
         try {
             this.level = LevelFactory.getInstance().getLevel("TILT",
                     source.getPrimaryElevationAngle());
@@ -98,19 +101,17 @@ public class RadarRequestableData extends GribRequestableData {
         this.unit = unit;
 
         try {
-            GribRecord record = new GribRecord();
-            GribModel modelInfo = new GribModel();
-            modelInfo.setModelName(this.source);
-            modelInfo.setLocation(RadarAdapter.getInstance().getCoverage());
-            modelInfo.setLevel(this.level);
-            modelInfo.setParameterAbbreviation(parameterAbbrev);
-            modelInfo.setParameterUnit(unit.toString());
-            modelInfo.setParameterName(this.parameterName);
-            record.setModelInfo(modelInfo);
-            record.setPluginName("grib");
+            GridRecord record = new GridRecord();
+            record.setDatasetId(this.source);
+            record.setLocation(RadarAdapter.getInstance().getCoverage());
+            record.setLevel(this.level);
+            Parameter parameter = new Parameter(parameterAbbrev,
+                    this.parameterName, unit);
+            record.setParameter(parameter);
+            record.setPluginName(GridConstants.GRID);
             record.setDataTime(source.getDataTime());
             record.constructDataURI();
-            setGribSource(record);
+            setGridSource(record);
         } catch (Exception e) {
             throw new VizException(e);
         }
@@ -142,7 +143,7 @@ public class RadarRequestableData extends GribRequestableData {
              * tiler.setDataToImageConverter(dataToImage);
              */
             Unit unit = cMapParams.getDisplayUnit();
-            getGribSource().getModelInfo().setParameterUnit(unit.toString());
+            getGridSource().getParameter().setUnit(unit);
             setUnit(unit);
             UnitConverter converter = cMapParams.getDataToDisplayConverter();
             tiler.setDataConverter(converter);
@@ -152,7 +153,7 @@ public class RadarRequestableData extends GribRequestableData {
             float[] data = tiler.createImage();
             fdr = new FloatDataRecord();
             fdr.setFloatData(data);
-            GridCoverage coverage = gribSource.getModelInfo().getLocation();
+            GridCoverage coverage = gridSource.getLocation();
             fdr.setSizes(new long[] { coverage.getNx(), coverage.getNy() });
             fdr.setDimension(2);
             cache = new WeakReference(fdr);
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/StaticGridRequestableData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/StaticGridRequestableData.java
index a5a72b9e01..f720da3454 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/StaticGridRequestableData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/StaticGridRequestableData.java
@@ -22,24 +22,25 @@ package com.raytheon.viz.grid.data;
 import javax.measure.unit.SI;
 
 import com.raytheon.uf.common.comm.CommunicationException;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup;
-import com.raytheon.uf.common.dataplugin.grib.util.GridModel;
-import com.raytheon.uf.common.dataplugin.grib.util.StaticGridData;
-import com.raytheon.uf.common.dataplugin.grib.util.StaticGridDataType;
+import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo;
+import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup;
+import com.raytheon.uf.common.dataplugin.grid.util.StaticGridData;
+import com.raytheon.uf.common.dataplugin.grid.util.StaticGridDataType;
 import com.raytheon.uf.common.dataplugin.level.LevelFactory;
 import com.raytheon.uf.common.datastorage.Request;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
-import com.raytheon.viz.grid.util.CoverageUtils;
+import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace;
 import com.raytheon.viz.grid.util.SliceUtil;
 
 /**
- * TODO Add Description
+ * Requestable data object that returns static data for a GridCoverage dx,dy, or
+ * coriolis.
  * 
  * 
  * 
@@ -60,11 +61,14 @@ public class StaticGridRequestableData extends AbstractRequestableData {
 
     private StaticGridDataType dataType;
 
-    public StaticGridRequestableData(StaticGridDataType dataType, String source) {
+    public StaticGridRequestableData(StaticGridDataType dataType,
+            String source, GridCoverage coverage) {
         this.dataType = dataType;
         this.source = source;
         this.parameter = dataType.toString();
         this.parameterName = dataType.toString();
+        this.space = coverage;
+        this.dataTime = TimeAndSpace.TIME_AGNOSTIC;
         if (StaticGridDataType._dt.equals(dataType)) {
             this.unit = SI.SECOND;
         } else {
@@ -88,11 +92,10 @@ public class StaticGridRequestableData extends AbstractRequestableData {
 
         if (StaticGridDataType._dt.equals(dataType)) {
             int dTinSeconds = 0;
-            GridModel model = GribModelLookup.getInstance().getModelByName(
-                    source);
+            DatasetInfo info = DatasetInfoLookup.getInstance().getInfo(source);
 
-            if (model != null) {
-                dTinSeconds = model.getDt();
+            if (info != null) {
+                dTinSeconds = info.getDt();
 
                 // dT <= 24 is in hours, need to convert to seconds
                 if (Math.abs(dTinSeconds) <= 24) {
@@ -102,21 +105,25 @@ public class StaticGridRequestableData extends AbstractRequestableData {
 
             return new Float(dTinSeconds);
         } else {
-            GridCoverage coverage = CoverageUtils.getInstance().getCoverage(
-                    source);
-            StaticGridData data = StaticGridData.getInstance(coverage);
-
-            switch (dataType) {
-            case coriolis:
-                rval = data.getCoriolis();
-                break;
-            case dx:
-                rval = data.getDx();
-                break;
-            case dy:
-                rval = data.getDy();
-                break;
+            if (this.space instanceof GridCoverage) {
+                StaticGridData data = StaticGridData
+                        .getInstance((GridCoverage) this.space);
+                switch (dataType) {
+                case coriolis:
+                    rval = data.getCoriolis();
+                    break;
+                case dx:
+                    rval = data.getDx();
+                    break;
+                case dy:
+                    rval = data.getDy();
+                    break;
+                }
+            } else {
+                throw new IllegalStateException("Cannot get static topo for: "
+                        + this.space);
             }
+
         }
         if (arg instanceof Request) {
             return SliceUtil.slice(rval, (Request) arg);
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TiltRequestableData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TiltRequestableData.java
index 4dc0bc688d..3504c9c3d0 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TiltRequestableData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TiltRequestableData.java
@@ -21,19 +21,18 @@ package com.raytheon.viz.grid.data;
 
 import javax.measure.unit.SI;
 
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
 import com.raytheon.uf.common.dataplugin.level.Level;
 import com.raytheon.uf.common.datastorage.Request;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
-import com.raytheon.viz.grid.util.CoverageUtils;
 import com.raytheon.viz.grid.util.SliceUtil;
 import com.raytheon.viz.grid.util.TiltUtils;
 import com.vividsolutions.jts.geom.Coordinate;
 
 /**
- * TODO Add Description
+ * Requestable Data that generated tilt elevation.
  * 
  * 
  * 
@@ -59,18 +58,20 @@ public class TiltRequestableData extends AbstractRequestableData {
 
     }
 
-    public TiltRequestableData(String modelName, Level tiltAngle) {
+    public TiltRequestableData(String modelName, Level tiltAngle,
+            GridCoverage coverage) {
         this.source = modelName;
         this.unit = SI.METER;
         this.parameter = "TILT";
         this.parameterName = "TILT";
         this.level = tiltAngle;
+        this.space = coverage;
     }
 
     @Override
     public FloatDataRecord getDataValue(Object arg) throws VizException {
 
-        GridCoverage coverage = CoverageUtils.getInstance().getCoverage(source);
+        GridCoverage coverage = (GridCoverage) getSpace();
         FloatDataRecord fdr = null;
         if (arg instanceof TiltCenterPoint) {
             Coordinate tiltLoc = ((TiltCenterPoint) arg).latLon;
@@ -80,7 +81,7 @@ public class TiltRequestableData extends AbstractRequestableData {
             fdr = TiltUtils.getInstance().getHeightGrid(coverage,
                     level.getLevelonevalue());
         }
-        if (arg instanceof Request) {
+        if (fdr != null && arg instanceof Request) {
             return SliceUtil.slice(fdr, (Request) arg);
         } else {
             return fdr;
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TopoRequestableData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TopoRequestableData.java
index 8bf10dbf3d..88491c082e 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TopoRequestableData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/data/TopoRequestableData.java
@@ -27,21 +27,21 @@ import javax.measure.unit.SI;
 import org.geotools.coverage.grid.GridGeometry2D;
 
 import com.raytheon.uf.common.comm.CommunicationException;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
 import com.raytheon.uf.common.dataplugin.level.LevelFactory;
 import com.raytheon.uf.common.datastorage.Request;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.core.topo.TopoQuery;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
-import com.raytheon.viz.grid.util.CoverageUtils;
 import com.raytheon.viz.grid.util.SliceUtil;
 
 /**
- * TODO Add Description
+ * requestable data that queries the topo datastore and transforms the data into
+ * the correct coverage.
  * 
  * 
  * 
@@ -82,7 +82,7 @@ public class TopoRequestableData extends AbstractRequestableData {
      */
     @Override
     public FloatDataRecord getDataValue(Object arg) throws VizException {
-        GridCoverage coverage = CoverageUtils.getInstance().getCoverage(source);
+        GridCoverage coverage = (GridCoverage) this.getSpace();
         FloatDataRecord rval = topoCache.get(coverage);
 
         if (rval == null) {
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCache.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCache.java
deleted file mode 100644
index 9013ec96bc..0000000000
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCache.java
+++ /dev/null
@@ -1,541 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.viz.grid.gridcache;
-
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.HashMap;
-import java.util.List;
-import java.util.TimeZone;
-import java.util.Timer;
-import java.util.TimerTask;
-
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
-import com.raytheon.uf.viz.core.catalog.LayerProperty;
-import com.raytheon.uf.viz.core.catalog.ScriptCreator;
-import com.raytheon.uf.viz.core.comm.Loader;
-import com.raytheon.uf.viz.core.exception.VizException;
-
-/**
- * This is the 3 dimensional data cube cache for D2D.
- * 
- * 
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 11, 2009 3579       mpduff      Initial creation
- * 
- * 
- * - * @author mpduff - * @version 1.0 - */ - -public class DataCache { - /** The only instance of this cache. */ - private static DataCache instance = null; - - private static final int SECONDS_PER_MINUTE = 60; - - private static final int MILLIS_PER_SECOND = 1000; - - private static SimpleDateFormat sdf = null; - - static { - sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - sdf.setTimeZone(TimeZone.getTimeZone("GMT")); - } - - /** Date Format yyyy-MM-dd HH:mm:ss */ - public static final SimpleDateFormat DATE_FORMAT = sdf; - - /** - * List of Model Nodes. - */ - private List modelNodeList = new ArrayList(); - - /** - * How long (in millis) to keep the data cubes around. - */ - private int retentionTime = 10 * SECONDS_PER_MINUTE * MILLIS_PER_SECOND; - - /** - * The timer delay, how long to wait to run. - */ - private int delay = 10 * SECONDS_PER_MINUTE * MILLIS_PER_SECOND; - - /** - * How often to repeat. - */ - private int period = 10 * SECONDS_PER_MINUTE * MILLIS_PER_SECOND; - - /** - * Cache Purge Timer. - */ - private Timer timer = new Timer(); - - /** - * Private, invisible constructor. - */ - private DataCache() { - // Set the purge timer to run - timer.scheduleAtFixedRate(new TimerTask() { - @Override - public void run() { - purge(); - } - }, delay, period); - - } - - /** - * Get an instance of the DataCache. - * - * This class should not be used directly. Use the DataCacheManager to - * interface with this class. - * - * @return An instance of this DataCache - */ - public static synchronized DataCache getInstance() { - if (instance == null) { - instance = new DataCache(); - } - - return instance; - } - - /** - * Add a cube to the cache. - * - * @param cube - * The DataCacheCube to add - * @param replace - * true = replace an existing cube, false = do not replace - */ - public synchronized void addData(DataCacheCube cube, boolean replace) { - boolean modelMatch = false; - boolean parameterMatch = false; - boolean levelMatch = false; - boolean refTimeMatch = false; - for (ModelNode mnode : modelNodeList) { - if ((mnode.getModelName() != null) && mnode.getModelName().equals(cube.getMetadata().getModelName())) { - modelMatch = true; - - /* Check if this parameter is in the list */ - if (mnode.getParameterNodeList().size() > 0) { - for (ParameterNode pnode : mnode.getParameterNodeList()) { - if (pnode.getParameter().equalsIgnoreCase( - cube.getMetadata().getParameter())) { - parameterMatch = true; - - /* Check if this level type is in the list */ - if (pnode.getLevelTypeList().size() > 0) { - for (LevelNode lnode : pnode.getLevelTypeList()) { - if (lnode.getLevelType().equals( - cube.getMetadata().getLevelType())) { - levelMatch = true; - - /* - * Check if the reference time is in the - * list - */ - if (lnode.getReferenceTimeList().size() > 0) { - for (TimeNode tnode : lnode - .getReferenceTimeList()) { - if (tnode.getReferenceTime() == cube - .getMetadata() - .getRefTime()) { - refTimeMatch = true; - tnode.addDataCube(cube); - } - } - if (refTimeMatch == false) { - // Found a new reference time - addNewTimeNode(cube, lnode); - } - } else { - // Found a new reference time - addNewTimeNode(cube, lnode); - } - } - } - if (levelMatch == false) { - // Found a new level type - addNewLevelTypeNode(cube, pnode); - } - } else { - // Found a new level type - addNewLevelTypeNode(cube, pnode); - } - } - } - if (parameterMatch == false) { - // Found a new parameter - addNewParameterNode(cube, mnode); - } - } else { - // Found a new parameter - addNewParameterNode(cube, mnode); - } - } - } - if (modelMatch == false) { - // Found a new model - addNewModelNode(cube); - } - } - - /** - * Add a new Model Node. - * - * @param cube - * The cube of data - */ - private void addNewModelNode(DataCacheCube cube) { - ModelNode mnode = new ModelNode(); - mnode.setModelName(cube.getMetadata().getModelName()); - - addNewParameterNode(cube, mnode); - - modelNodeList.add(mnode); - } - - /** - * Add a new parameter node. - * - * @param cube - * The cube of data - * @param mnode - * The model node that holds this node - */ - private void addNewParameterNode(DataCacheCube cube, ModelNode mnode) { - ParameterNode pnode = new ParameterNode(); - pnode.setModelName(cube.getMetadata().getModelName()); - pnode.setParameter(cube.getMetadata().getParameter()); - - mnode.addParameterNode(pnode); - - /* Add new level type node */ - addNewLevelTypeNode(cube, pnode); - } - - /** - * Add a level type node. - * - * @param cube - * The cube of data - * @param pnode - * The parameter node that holds this node - */ - private void addNewLevelTypeNode(DataCacheCube cube, ParameterNode pnode) { - LevelNode lnode = new LevelNode(); - lnode.setModelName(cube.getMetadata().getModelName()); - lnode.setLevelType(cube.getMetadata().getLevelType()); - - pnode.addLevelNode(lnode); - - /* Add new reference time node */ - addNewTimeNode(cube, lnode); - } - - /** - * Add a Time Node. - * - * @param cube - * The cube of data - * @param lnode - * The level node that holds this node - */ - private void addNewTimeNode(DataCacheCube cube, LevelNode lnode) { - TimeNode tnode = new TimeNode(); - tnode.setModelName(cube.getMetadata().getModelName()); - tnode.setReferenceTime(cube.getMetadata().getRefTime()); - - tnode.addDataCube(cube); - lnode.addTimeNode(tnode); - } - - /** - * If the cache has the cube return it, otherwise build it, put it in the - * cache, then return it. - * - * @param lProp - * The layer properties - * @return The data cube - * @throws VizException - */ - public DataCacheCube getCube(LayerProperty lProp) throws VizException { - DataCubeMetadata metadata = new DataCubeMetadata(); - DataCacheCube cube = null; - String tableScript = ScriptCreator.createScript(lProp); - List rs = Loader.loadData(tableScript, 10000); - - if (rs.size() > 0) { - - /* Build the metadata */ - if (rs.get(0) instanceof GribRecord) { - GribRecord record = (GribRecord) rs.get(0); - metadata.setModelName(record.getModelInfo().getModelName()); - metadata.setLevelType(record.getModelInfo().getLevel() - .getMasterLevel().getName()); - metadata.setParameter(record.getModelInfo() - .getParameterAbbreviation()); - Calendar cal = Calendar - .getInstance(TimeZone.getTimeZone("GMT")); - cal - .setTimeInMillis(record.getDataTime().getRefTime() - .getTime()); - metadata.setRefTime(cal.getTimeInMillis()); - metadata.setFcstHr(record.getDataTime().getFcstTime()); - - // Look for the cube - for (ModelNode mnode : modelNodeList) { - for (ParameterNode pnode : mnode.getParameterNodeList()) { - for (LevelNode lnode : pnode.getLevelTypeList()) { - for (TimeNode tnode : lnode.getReferenceTimeList()) { - for (int fcstTime : tnode.getFcstTimes()) { - if (tnode.getCube(fcstTime).getMetadata() - .equals(metadata)) { - return tnode.getCube(fcstTime); - } - } - } - } - } - } - } - } - - // Cube not in the cache, create one - DataCubeFactory factory = new DataCubeFactory(); - cube = factory.createCube(lProp); - addData(cube, true); - - return cube; - } - - /** - * Get a DataCacheCube from the cache. Check the GribRecord for layer data. - * If layerOneValue and layerTwoValue are both null, request the entire - * cube, otherwise just get the data for the layer. - * - * @param rec - * The GribRecord - * @return - * The DataCacheCube - */ - public DataCacheCube getCube(GribRecord record) { - String levelType = record.getModelInfo().getLevel().getMasterLevel() - .getName(); - - DataCacheCube cube = null; - DataCubeMetadata metadata = new DataCubeMetadata(); - - metadata.setModelName(record.getModelInfo().getModelName()); - metadata.setLevelType(record.getModelInfo().getLevel() - .getMasterLevel().getName()); - metadata.setParameter(record.getModelInfo().getParameterAbbreviation()); - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.setTimeInMillis(record.getDataTime().getRefTime().getTime()); - metadata.setRefTime(cal.getTimeInMillis()); - metadata.setFcstHr(record.getDataTime().getFcstTime()); - - // Look for the cube - for (ModelNode mnode : modelNodeList) { - for (ParameterNode pnode : mnode.getParameterNodeList()) { - for (LevelNode lnode : pnode.getLevelTypeList()) { - for (TimeNode tnode : lnode.getReferenceTimeList()) { - for (int fcstTime : tnode.getFcstTimes()) { - if (tnode.getCube(fcstTime).getMetadata() - .equals(metadata)) { - return tnode.getCube(fcstTime); - } - } - } - } - } - } - - // Build the query. - DataCubeFactory factory = new DataCubeFactory(); - HashMap query = new HashMap(); - query.put("pluginName", new RequestConstraint("grib")); - - // Model parameter - query.put("modelInfo.parameterAbbreviation", new RequestConstraint(record - .getModelInfo().getParameterAbbreviation())); - - // Level type - query.put("modelInfo.level.masterLevel.name", - new RequestConstraint(levelType)); - - // model name - query.put("modelInfo.modelName", new RequestConstraint(record - .getModelInfo().getModelName())); - - query.put("dataTime.refTime", new RequestConstraint(DATE_FORMAT - .format(record.getDataTime().getRefTime()))); - - query.put("dataTime.fcstTime", new RequestConstraint(String.valueOf(record - .getDataTime().getFcstTime()))); - - // No data cube available in cache, Check for layer data - if ((record.getModelInfo().getLevelOneValue() == null) - && (record.getModelInfo().getLevelTwoValue() == null)) { - - LayerProperty lp = new LayerProperty(); - - // The number of records to return - lp.setNumberOfImages(9999); - - try { - lp.setEntryQueryParameters(query, false); - cube = factory.createCube(lp); - DataCache.getInstance().addData(cube, true); - - return cube; - } catch (VizException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - return cube; - } - - /** - * Clear the cache. - */ - public void clearCache() { - modelNodeList.clear(); - } - - private void purge() { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - - // Find and remove the cubes and nodes - for (int i = 0; i < modelNodeList.size(); i++) { - ModelNode mnode = modelNodeList.get(i); - if (mnode.getModelName() == null) { - modelNodeList.remove(i); - } - for (int j = 0; j < mnode.getParameterNodeList().size(); j++) { - ParameterNode pnode = mnode.getParameterNodeList().get(j); - - for (int k = 0; k < pnode.getLevelTypeList().size(); k++) { - LevelNode lnode = pnode.getLevelTypeList().get(k); - - for (int ii = 0; ii < lnode.getReferenceTimeList().size(); ii++) { - TimeNode tnode = lnode.getReferenceTimeList().get(ii); - - for (int fcstTime : tnode.getFcstTimes()) { - DataCacheCube cube = tnode.getCube(fcstTime); - long creationTime = cube.getCreationTime(); - if (cal.getTimeInMillis() - creationTime > retentionTime) { - // Delete the cube. - if (tnode.getFcstTimes().length > 0) { - tnode.removeCube(cube.getMetadata() - .getFcstHr()); - } - } - } - if (tnode.getFcstTimes().length == 0) { - lnode.getReferenceTimeList().remove(ii); - } - } - if (lnode.getReferenceTimeList().size() == 0) { - pnode.getLevelTypeList().remove(k); - } - } - if (pnode.getLevelTypeList().size() == 0) { - mnode.getParameterNodeList().remove(j); - } - } - if (mnode.getParameterNodeList().size() == 0) { - modelNodeList.remove(i); - } - } - } - - /** - * @return the retentionTime in milliseconds - */ - public int getRetentionTime() { - return retentionTime; - } - - /** - * @param retentionTime - * the retentionTime to set in milliseconds - */ - public void setRetentionTime(int retentionTime) { - this.retentionTime = retentionTime; - } - - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - - for (ModelNode mnode : modelNodeList) { - buf.append("******************\n"); - buf.append("* " + mnode.getModelName() + "\n"); - - List parameterNodeList = mnode - .getParameterNodeList(); - for (ParameterNode pnode : parameterNodeList) { - buf.append("*-------------------\n"); - buf.append("* " + pnode.getParameter() + "\n"); - - List levelList = pnode.getLevelTypeList(); - for (LevelNode lnode : levelList) { - buf.append("* " + lnode.getLevelType() + "\n"); - - List timeList = lnode.getReferenceTimeList(); - for (TimeNode tnode : timeList) { - Calendar c = Calendar.getInstance(TimeZone - .getTimeZone("GMT")); - c.setTimeInMillis(tnode.getReferenceTime()); - buf.append("* " + (c.get(Calendar.MONTH) + 1) + "/" - + c.get(Calendar.DAY_OF_MONTH) + " " - + c.get(Calendar.HOUR_OF_DAY) + "Z\n"); - - int[] fcstTimes = tnode.getFcstTimes(); - - buf.append("* " + fcstTimes.length + " datacubes\n"); - buf.append("* Fcst Hrs: "); - for (int i = 0; i < fcstTimes.length; i++) { - if (i > 0) { - buf.append(", "); - } - buf.append(fcstTimes[i] / 60 / 60); - } - buf.append("\n"); - } - } - } - buf.append("******************\n"); - } - - return buf.toString(); - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCacheCube.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCacheCube.java deleted file mode 100644 index 70b53a4292..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCacheCube.java +++ /dev/null @@ -1,246 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.gridcache; - -import java.util.ArrayList; -import java.util.Calendar; -import java.util.TimeZone; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.datastorage.records.FloatDataRecord; - -/** - * TODO Add Description - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 11, 2009            mpduff     Initial creation
- * 
- * 
- * - * @author mpduff - * @version 1.0 - */ - -public class DataCacheCube implements Comparable { - /** - * Data cube metadata. - */ - private DataCubeMetadata metadata = new DataCubeMetadata(); - - /** - * FloatDataRecord list in stack order. - */ - private ArrayList fdrStackData = new ArrayList(); - - /** - * GribRecord list in stack order. - */ - private ArrayList gribRecordStack = new ArrayList(); - - /** - * The creation time of this data cube. - */ - private long creationTime; - - /** - * Constructor - */ - public DataCacheCube() { - - } - - /** - * Concatenate the layer arrays into one and return it. - * - * @return float[] of data - */ - public float[] getRawData() { - // Concatenate all the arrays into one - int size = 0; - for (FloatDataRecord fdr : fdrStackData) { - size += fdr.getFloatData().length; - } - - float[] floatArray = new float[size]; - int offset = 0; - for (FloatDataRecord fdr : fdrStackData) { - float[] tmp = fdr.getFloatData(); - System.arraycopy(tmp, 0, floatArray, offset, tmp.length); - offset += tmp.length; - } - - return floatArray; - } - - public float[] getLevelData() { - float[] levels = new float[gribRecordStack.size()]; - for (int i = 0; i < gribRecordStack.size(); i++) { - levels[i] = gribRecordStack.get(i).getModelInfo() - .getLevelOneValue().floatValue(); - } - return levels; - } - - /** - * Get the stack of FloatDataRecord objects. - * - * @return the fdrStackData - */ - public ArrayList getFdrStackData() { - return fdrStackData; - } - - /** - * Set the stack of FloatDataRecord objects. - * - * @param fdrStackData - * the fdrStackData to set - */ - public void setFdrStackData(ArrayList fdrStackData) { - this.fdrStackData = fdrStackData; - } - - /** - * Get the stack of GribRecord Objects. - * - * @return the gribRecordStack - */ - public ArrayList getGribRecordStack() { - return gribRecordStack; - } - - /** - * Set the stack of GribRecord Objects. - * - * @param gribRecordStack - * the gribRecordStack to set - */ - public void setGribRecordStack(ArrayList gribRecordStack) { - this.gribRecordStack = gribRecordStack; - } - - /** - * @return the metadata - */ - public DataCubeMetadata getMetadata() { - return metadata; - } - - /** - * @param metadata - * the metadata to set - */ - public void setMetadata(DataCubeMetadata metadata) { - this.metadata = metadata; - } - - /** - * @return the creationTime - */ - public long getCreationTime() { - return creationTime; - } - - /** - * @param creationTime - * the creationTime to set - */ - public void setCreationTime(long creationTime) { - this.creationTime = creationTime; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if ((obj == null) || (obj.getClass() != this.getClass())) { - return false; - } - - DataCacheCube cube = (DataCacheCube) obj; - if (!metadata.equals(cube.getMetadata())) { - return false; - } - - return true; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return metadata.getFcstHr() + metadata.getModelName().hashCode() - + metadata.getParameter().hashCode() - + metadata.getLevelType().hashCode(); - } - - /** - * Compare this DataCacheCube to another DataCacheCube. This method compares - * the Forecast hour attribute. - */ - @Override - public int compareTo(DataCacheCube o) { - DataCacheCube cube = o; - if (metadata.getFcstHr() > cube.getMetadata().getFcstHr()) { - return 1; - } else if (metadata.getFcstHr() < cube.getMetadata().getFcstHr()) { - return -1; - } - - return 0; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("Model Name: " + metadata.getModelName() + "\n"); - sb.append("Parameter: " + metadata.getParameter() + "\n"); - sb.append("Level Type: " + metadata.getLevelType() + "\n"); - Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - c.setTimeInMillis(metadata.getRefTime()); - sb.append("Ref Time: " + c.get(Calendar.YEAR) + "/" - + c.get(Calendar.MONTH) + "/" + c.get(Calendar.DAY_OF_MONTH)); - sb.append(" " + c.get(Calendar.HOUR_OF_DAY) + ":" - + c.get(Calendar.MINUTE) + "\n"); - sb.append("Fcst Hour: " + metadata.getFcstHr() / 60 / 60 + "\n"); - sb.append("Grid Size: " + metadata.getNx() + " x " + metadata.getNy()); - - return sb.toString(); - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCacheManager.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCacheManager.java deleted file mode 100644 index e06213200e..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCacheManager.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.gridcache; - -import java.util.ArrayList; -import java.util.HashMap; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.exception.VizException; - -/** - * Interface layer to the DataCache. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 10, 2009 3579       mpduff      Initial creation
- * 
- * 
- * - * @author mpduff - * @version 1.0 - */ - -public class DataCacheManager { - /** - * The only instance of this class. - */ - private static DataCacheManager instance = null; - - /** - * Private constructor. - */ - private DataCacheManager() { - } - - /** - * Get an instance of this class. - * - * @return Instance of this class - */ - public static synchronized DataCacheManager getInstance() { - if (instance == null) { - instance = new DataCacheManager(); - } - - return instance; - } - - /** - * Get the raw 3D float[]. - * - * @param lProp - * The LayerProperties - * @return - * The float[] - * @throws VizException - */ - public float[] getDataCube(LayerProperty lProp) throws VizException { - DataCache cache = DataCache.getInstance(); - - DataCacheCube cube = cache.getCube(lProp); - - return cube.getRawData(); - } - - /** - * Get the raw layer float[] - * - * @param lProp - * The LayerProperties - * @return - * The float[] - * @throws VizException - */ - public float[] getDataLayer(LayerProperty lProp) throws VizException { - DataCache cache = DataCache.getInstance(); - float[] data = null; - DataCacheCube cube = cache.getCube(lProp); - - // Get the layer of interest value - HashMap requestMap = lProp.getEntryQueryParameters(false); - double requestedLevel = -999; - if (requestMap.containsKey("modelInfo.level.levelonevalue")) { - requestedLevel = Double.parseDouble(requestMap.get("modelInfo.level.levelonevalue").getConstraintValue()); - } - - // Find the layer of interest - ArrayList grStack = cube.getGribRecordStack(); - for (int i = 0; i < grStack.size(); i++) { - GribRecord gr = grStack.get(i); - - double level = gr.getModelInfo().getLevel().getLevelonevalue(); - if ((requestedLevel != -999) && (level == requestedLevel)) { - data = cube.getFdrStackData().get(i).getFloatData(); - } - } - - return data; - } - - /** - * Get the raw float array. It returns a layer if a layer - * is specified in the GribRecord, otherwise returns the - * whole cube. - * - * @param rec - * The GribRecord object - * @return - * float[] of raw data values - */ - public float[] getData(GribRecord rec) { - DataCache cache = DataCache.getInstance(); - DataCacheCube cube = cache.getCube(rec); - float[] fa = null; - - /* If a level is set, return data for that level */ - if (rec.getModelInfo().getLevelOneValue() != null) { - - double level1 = rec.getModelInfo().getLevelOneValue(); - - // Find the layer of interest - ArrayList grStack = cube.getGribRecordStack(); - for (int i = 0; i < grStack.size(); i++) { - GribRecord gr = grStack.get(i); - - double level = gr.getModelInfo().getLevel().getLevelonevalue(); - if ((level1 != -999) && (level == level1)) { - fa = cube.getFdrStackData().get(i).getFloatData(); - } - } - - return fa; - } - - // no level set, return the whole cube - - return cube.getRawData(); - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCubeFactory.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCubeFactory.java deleted file mode 100644 index efc8f765c2..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCubeFactory.java +++ /dev/null @@ -1,169 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.gridcache; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.List; -import java.util.TimeZone; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.datastorage.DataStoreFactory; -import com.raytheon.uf.common.datastorage.IDataStore; -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.viz.core.HDF5Util; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.catalog.ScriptCreator; -import com.raytheon.uf.viz.core.comm.Loader; -import com.raytheon.uf.viz.core.exception.VizException; - -/** - * Generates the 3-D data cubes for the 3-D cache. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 11, 2009 3579       mpduff      Initial creation
- * 
- * 
- * - * @author mpduff - * @version 1.0 - */ - -public class DataCubeFactory { - /** - * The cube to build. - */ - private DataCacheCube cube = new DataCacheCube(); - - /** - * List of GribRecord objects for the cube. - */ - private ArrayList recList = new ArrayList(); - - /** - * List of FloatDataRecord objects for the cube - */ - private ArrayList fdrList = new ArrayList(); - - /** - * Constructor. - */ - public DataCubeFactory() { - } - - /** - * Create a DataCacheCube from a LayerProperty object. - * - * @param lProp - * The LayerProperty object - * @return - * The DataCacheCube - * @throws VizException - */ - public DataCacheCube createCube(LayerProperty lProp) throws VizException { - String tableScript = null; - - tableScript = ScriptCreator.createScript(lProp); - List rs = Loader.loadData(tableScript, 10000); - for (int i = 0; i < rs.size(); i++) { - if (rs.get(i) instanceof GribRecord) { - GribRecord record = (GribRecord) rs.get(i); - if (i == 0) { - // Set the metadata the first time through the loop - cube.getMetadata().setModelName(record.getModelInfo().getModelName()); - cube.getMetadata().setLevelType(record.getModelInfo().getLevel() - .getMasterLevel().getName()); - cube.getMetadata().setParameter(record.getModelInfo() - .getParameterAbbreviation()); - Calendar cal = Calendar.getInstance(TimeZone - .getTimeZone("GMT")); - // Set the creation time to the current time - cube.setCreationTime(cal.getTimeInMillis()); - - // Set the reference time - cal.setTimeInMillis(record.getDataTime().getRefTime() - .getTime()); - cube.getMetadata().setRefTime(cal.getTimeInMillis()); - cube.getMetadata().setFcstHr(record.getDataTime().getFcstTime()); - cube.getMetadata().setNx(record.getModelInfo().getLocation().getNx()); - cube.getMetadata().setNy(record.getModelInfo().getLocation().getNy()); - } - - if (record.getModelInfo().getLevelTwoValue() == null) { - recList.add(record); - } - } - } - - // Sort the stack by level - java.util.Collections.sort(recList, new LevelComparator()); - - cube.setGribRecordStack(recList); - - createStack(); - - return cube; - } - - /** - * Create a stack of grids. - * - * @param record - * A GribRecord - */ - private void createStack() { - for (GribRecord record : recList) { - try { - File loc = HDF5Util.findHDF5Location(record); - IDataStore dataStore = DataStoreFactory.getDataStore(loc); - IDataRecord[] dataRec; - dataRec = dataStore.retrieve(record.getDataURI()); - if (dataRec.length > 0) { - if (dataRec[0] instanceof FloatDataRecord) { - fdrList.add((FloatDataRecord) dataRec[0]); - } else { - // Log message - System.err.println("Grib data not of type float: " - + record.getModelInfo().getModelName() + ": " - + record.getModelInfo().getParameterName()); - } - } - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } catch (StorageException e) { - // TODO Auto-generated catch block - // e.printStackTrace(); - System.err.println("Storage Error: " + e.getMessage()); - System.err.println(" Caused by: " + e.getCause()); - } - } - - cube.setFdrStackData(fdrList); - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCubeMetadata.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCubeMetadata.java deleted file mode 100644 index 6c25cc4a41..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/DataCubeMetadata.java +++ /dev/null @@ -1,216 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.gridcache; - -/** - * DataCacheCube Metadata. - * - *
- *
- * SOFTWARE HISTORY
- *
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 15, 2009 3579       mpduff      Initial creation
- *
- * 
- * - * @author mpduff - * @version 1.0 - */ - -public class DataCubeMetadata { - /** - * The model name. - */ - private String modelName = null; - - /** - * The parameter. - */ - private String parameter = null; - - /** - * The level type. - */ - private String levelType = null; - - /** - * The reference time. - */ - private long refTime; - - /** - * The forecast hour. - */ - private int fcstHr; - - /** - * Number of values in the x direction. - */ - private int nx; - - /** - * Number of values in the y direction. - */ - private int ny; - - /** - * @return the modelName - */ - public String getModelName() { - return modelName; - } - - /** - * @param modelName - * the modelName to set - */ - public void setModelName(String modelName) { - this.modelName = modelName; - } - - /** - * @return the parameter - */ - public String getParameter() { - return parameter; - } - - /** - * @param parameter - * the parameter to set - */ - public void setParameter(String parameter) { - this.parameter = parameter; - } - - /** - * @return the levelType - */ - public String getLevelType() { - return levelType; - } - - /** - * @param levelType - * the levelType to set - */ - public void setLevelType(String levelType) { - this.levelType = levelType; - } - - /** - * @return the refTime - */ - public long getRefTime() { - return refTime; - } - - /** - * @param refTime - * the refTime to set - */ - public void setRefTime(long refTime) { - this.refTime = refTime; - } - - /** - * @return the fcstHr - */ - public int getFcstHr() { - return fcstHr; - } - - /** - * @param fcstHr - * the fcstHr to set - */ - public void setFcstHr(int fcstHr) { - this.fcstHr = fcstHr; - } - - /** - * @return the nx - */ - public int getNx() { - return nx; - } - - /** - * @param nx the nx to set - */ - public void setNx(int nx) { - this.nx = nx; - } - - /** - * @return the ny - */ - public int getNy() { - return ny; - } - - /** - * @param ny the ny to set - */ - public void setNy(int ny) { - this.ny = ny; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - - if ((obj == null) || (obj.getClass() != this.getClass())) { - return false; - } - - DataCubeMetadata cube = (DataCubeMetadata) obj; - if (!getModelName().equals(cube.getModelName())) { - return false; - } - - if (!getParameter().equals(cube.getParameter())) { - return false; - } - - if (!getLevelType().equals(cube.getLevelType())) { - return false; - } - - if (getRefTime() != cube.getRefTime()) { - return false; - } - - if (getFcstHr() != cube.getFcstHr()) { - return false; - } - - return true; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/TestDriver.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/TestDriver.java deleted file mode 100644 index 32c0825970..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/TestDriver.java +++ /dev/null @@ -1,227 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.gridcache; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.exception.VizException; - -/** - * Used to testing the Data cube cache functionality. Can be removed from the - * baseline - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 17, 2009            mpduff     Initial creation
- * 
- * 
- * - * @author mpduff - * @version 1.0 - */ -public class TestDriver { - public void printcache() { - System.out.println(DataCache.getInstance().toString()); - } - - public void createCache() { - // DataCache.getInstance().clearCache(); - DataCache cache = DataCache.getInstance(); - DataCacheManager dman = DataCacheManager.getInstance(); - - ArrayList paramList = new ArrayList(); - paramList.add("T"); - paramList.add("RH"); - paramList.add("GH"); - LayerProperty lpParm = new LayerProperty(); - - // String modelName = "NAM12"; - String modelName = "NAM212"; - String levelType = "MB"; - - for (int i = 0; i < paramList.size(); i++) { - DataCubeFactory factory = new DataCubeFactory(); - HashMap query = new HashMap(); - query.put("pluginName", new RequestConstraint("grib")); - - // Model parameter - query.put("modelInfo.parameterAbbreviation", new RequestConstraint( - paramList.get(i))); - - // model name - query.put("modelInfo.modelName", new RequestConstraint(modelName)); - - // level type - query.put("modelInfo.level.masterLevel.name", - new RequestConstraint(levelType)); - - query.put("dataTime.refTime", new RequestConstraint( - "2009-11-17 06:00:00")); - - query.put("dataTime.fcstTime", new RequestConstraint("0")); - // query.put("dataTime.fcstTime", new RequestConstraint("10800")); - // query.put("dataTime.fcstTime", new RequestConstraint("21600")); - - // model identifying data - // query.put("modelInfo.gridid", new RequestConstraint("211")); - // query.put("modelInfo.genprocess", new RequestConstraint("84")); - // query.put("modelInfo.centerid", new RequestConstraint("7")); - // query.put("modelInfo.subcenterid", new RequestConstraint("0")); - - // The number of records to return - lpParm.setNumberOfImages(9999); - - try { - Date d1 = new Date(); - lpParm.setEntryQueryParameters(query, false); - DataCacheCube cube = factory.createCube(lpParm); - cache.addData(cube, true); - - Date d2 = new Date(); - System.out.println("Cube generation time: " - + (d2.getTime() - d1.getTime())); - - // ArrayList gribRecList = - // cube.getGribRecordStack(); - - // GribRecord rec = gribRecList.get(0); - // float[] fa = dman.getData(rec); - // System.out.println(fa.length + " elements in the array"); - } catch (VizException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } - - public void getData() { - DataCacheManager dman = DataCacheManager.getInstance(); - - HashMap query = new HashMap(); - query.put("pluginName", new RequestConstraint("grib")); - - // Model parameter - query - .put("modelInfo.parameterAbbreviation", new RequestConstraint( - "T")); - - // model name - query.put("modelInfo.modelName", new RequestConstraint("NAM212")); - - // level type - query.put("modelInfo.level.masterLevel.name", new RequestConstraint( - "MB")); - - query.put("dataTime.refTime", new RequestConstraint( - "2009-11-17 06:00:00")); - - query.put("dataTime.fcstTime", new RequestConstraint("0")); - // query.put("dataTime.fcstTime", new RequestConstraint("10800")); - // query.put("dataTime.fcstTime", new RequestConstraint("21600")); - - // model identifying data - // query.put("modelInfo.gridid", new RequestConstraint("211")); - // query.put("modelInfo.genprocess", new RequestConstraint("84")); - // query.put("modelInfo.centerid", new RequestConstraint("7")); - // query.put("modelInfo.subcenterid", new RequestConstraint("0")); - - // query.put("modelInfo.level.id", new - // RequestConstraint("-796167917")); - - LayerProperty lpParm = new LayerProperty(); - // The number of records to return - lpParm.setNumberOfImages(9999); - - try { - Date d1 = new Date(); - lpParm.setEntryQueryParameters(query, false); - - float[] fa = dman.getDataCube(lpParm); - Date d2 = new Date(); - - System.out.println(fa.length + " elements in the array"); - System.out.println(d2.getTime() - d1.getTime() - + " millis for the query"); - - DataCubeFactory factory = new DataCubeFactory(); - DataCacheCube cube = factory.createCube(lpParm); - - ArrayList gribRecList = cube.getGribRecordStack(); - - GribRecord rec = gribRecList.get(0); - Date d3 = new Date(); - fa = dman.getData(rec); - Date d4 = new Date(); - System.out.println(fa.length + " elements in the array"); - System.out.println(d4.getTime() - d3.getTime() - + " millis for the query 2"); - } catch (VizException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - - public void getLayerData() { - DataCacheManager dman = DataCacheManager.getInstance(); - HashMap query = new HashMap(); - query.put("pluginName", new RequestConstraint("grib")); - - // Model parameter - query - .put("modelInfo.parameterAbbreviation", new RequestConstraint( - "T")); - - // model name - query.put("modelInfo.modelName", new RequestConstraint("NAM218")); - - // level type - query - .put("modelInfo.level.levelonevalue", new RequestConstraint( - "500")); - - query.put("dataTime.refTime", new RequestConstraint( - "2009-11-17 06:00:00")); - - query.put("dataTime.fcstTime", new RequestConstraint("0")); - // query.put("dataTime.fcstTime", new RequestConstraint("10800")); - // query.put("dataTime.fcstTime", new RequestConstraint("21600")); - - LayerProperty lpParm = new LayerProperty(); - lpParm.setNumberOfImages(9999); - - try { - lpParm.setEntryQueryParameters(query, false); - float[] layer = dman.getDataLayer(lpParm); - System.out.println(layer.length + " elements in the layer array"); - } catch (VizException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/TimeNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/TimeNode.java deleted file mode 100644 index 747c5c7a75..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/TimeNode.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.gridcache; - -import java.util.Arrays; -import java.util.Calendar; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Set; -import java.util.TimeZone; - -/** - * Time node of the cache tree. - * - *
- *
- * SOFTWARE HISTORY
- *
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Nov 13, 2009 3579       mpduff      Initial creation
- *
- * 
- * - * @author mpduff - * @version 1.0 - */ - -public class TimeNode extends CacheNode { - private long referenceTime; - - private Map dataCubeMap = new HashMap(); - - /** - * @return the referenceTime - */ - public long getReferenceTime() { - return referenceTime; - } - - /** - * @param referenceTime the referenceTime to set - */ - public void setReferenceTime(long referenceTime) { - this.referenceTime = referenceTime; - } - - /** - * Add data cube to the time node. - * @param cube - */ - public void addDataCube(DataCacheCube cube) { - referenceTime = cube.getMetadata().getRefTime(); - dataCubeMap.put(cube.getMetadata().getFcstHr(), cube); - } - - /** - * Get the forecast times for each cube. - * @return - */ - public int[] getFcstTimes() { - Set rtimes = dataCubeMap.keySet(); - int[] timeList = new int[rtimes.size()]; - - // create a list to sort the times - Iterator iter = rtimes.iterator(); - - int index = 0; - while (iter.hasNext()) { - timeList[index] = iter.next(); - index++; - } - - Arrays.sort(timeList); - - return timeList; - } - - /** - * Get a data cube. - * - * @param fcstTime - * The forecast time of the cube - * @return - * The cube - */ - public DataCacheCube getCube(int fcstTime) { - return dataCubeMap.get(fcstTime); - } - - /** - * Remove a data cube. - * - * @param fcstTime - * Forecast time of the cube to remove - */ - public void removeCube(int fcstTime) { - dataCubeMap.remove(fcstTime); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - StringBuilder buf = new StringBuilder(); - - Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - c.setTimeInMillis(getReferenceTime()); - - buf.append("**************"); - buf.append("TimeNode\n"); - buf.append("Ref time = " + c.get((Calendar.MONTH) + 1) + "/" + c.get(Calendar.DAY_OF_MONTH) + " "); - buf.append(c.get(Calendar.HOUR_OF_DAY) + "\n"); - buf.append("Fcst times = "); - int[] ft = getFcstTimes(); - for (long l: ft) { - buf.append(l + " "); - } - buf.append("\n"); - - return buf.toString(); - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/CubeLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/CubeLevelNode.java index 45f8a443ec..45c68508dc 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/CubeLevelNode.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/CubeLevelNode.java @@ -19,19 +19,11 @@ **/ package com.raytheon.viz.grid.inv; -import java.util.ArrayList; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.tree.AbstractCubeLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; import com.raytheon.uf.viz.derivparam.tree.CubeLevel; -import com.raytheon.viz.grid.data.GribRequestableDataFactory; /** * @@ -63,35 +55,9 @@ public class CubeLevelNode extends AbstractCubeLevelNode { } public CubeLevelNode( - List> levels, + List> levels, String modelName) { super(levels, modelName); } - protected List wrapRawRecord(List objs) - throws VizException { - List gribResults = new ArrayList( - objs.size()); - GribRequestableDataFactory factory = GribRequestableDataFactory - .getInstance(); - for (Object obj : objs) { - AbstractRequestableData record = factory - .getGribRequestableData((GribRecord) obj); - gribResults.add(record); - } - - return gribResults; - } - - @Override - protected void filter( - Map baseRequestConstraints, - Map requestContraintsToFilter) { - for (Entry e : baseRequestConstraints - .entrySet()) { - if (!requestContraintsToFilter.containsKey(e.getKey())) { - requestContraintsToFilter.put(e.getKey(), e.getValue()); - } - } - } } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GatherLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GatherLevelNode.java index 8a93c4327b..e89e0602c3 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GatherLevelNode.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GatherLevelNode.java @@ -21,20 +21,20 @@ package com.raytheon.viz.grid.inv; import java.util.ArrayList; import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Set; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.data.AggregateRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; import com.raytheon.uf.viz.derivparam.tree.AbstractAliasLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; /** * @@ -58,41 +58,29 @@ public class GatherLevelNode extends AbstractAliasLevelNode { super(that); } - public GatherLevelNode(AbstractRequestableLevelNode sourceNode, + public GatherLevelNode(AbstractRequestableNode sourceNode, DerivParamDesc desc, DerivParamMethod method, String modelName, Level level) { super(sourceNode, desc, method, modelName, level); } - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + @Override + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - Map> recordMap = new HashMap>(); - HashMap rcMap = property - .getEntryQueryParameters(false); - for (Integer pert : GridInventory.getPerts(sourceNode)) { - rcMap.put(GridInventory.PERT_QUERY, new RequestConstraint(pert - .toString())); - property.setEntryQueryParameters(rcMap, false); - cache.clear(); - for (AbstractRequestableData record : sourceNode.getData(property, - timeOut, cache)) { - List records = recordMap.get(record - .getDataTime()); - if (records == null) { - records = new ArrayList(); - recordMap.put(record.getDataTime(), records); - } - records.add(record); + Map> availMap = new HashMap>(); + for (AbstractRequestableData data : dependencyData.get(sourceNode)) { + TimeAndSpace ast = data.getTimeAndSpace(); + List avail = availMap.get(ast); + if (avail == null) { + avail = new ArrayList(); + availMap.put(ast, avail); } + avail.add(data); } - rcMap.remove(GridInventory.PERT_QUERY); - property.setEntryQueryParameters(rcMap, false); - List result = new ArrayList( - recordMap.size()); - for (List records : recordMap.values()) { + Set result = new HashSet(); + for (List records : availMap.values()) { AggregateRequestableData record = new AggregateRequestableData( records); modifyRequest(record); diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribDataCubeAlertMessageParser.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribDataCubeAlertMessageParser.java index 188969bd41..907de1fe8b 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribDataCubeAlertMessageParser.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribDataCubeAlertMessageParser.java @@ -62,8 +62,8 @@ public class GribDataCubeAlertMessageParser extends DataCubeAlertMessageParser { message.decodedAlert); // remove cache'd entry from grib time cache - GribMapKey mapKey = new GribMapKey(attribs); - GribTimeCache.getInstance().clearTimes(mapKey); + GridMapKey mapKey = new GridMapKey(attribs); + GridTimeCache.getInstance().clearTimes(mapKey); return super.parseAlertMessage(message, reqResourceData); } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribRequestableLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribRequestableLevelNode.java deleted file mode 100644 index d3017cd74d..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribRequestableLevelNode.java +++ /dev/null @@ -1,307 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.inv; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -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.requests.TimeQueryRequest; -import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; -import com.raytheon.uf.common.derivparam.tree.LevelNode; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.CatalogQuery; -import com.raytheon.uf.viz.core.catalog.LayerProperty; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.requests.ThriftClient; -import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; -import com.raytheon.viz.grid.data.GribRequestableDataFactory; - -/** - * - * A basic node which fulfills time and data requests by going to edex. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Jan 19, 2010            bsteffen     Initial creation
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ -public class GribRequestableLevelNode extends AbstractRequestableLevelNode { - - protected static final String TIME_FIELD = "dataTime"; - - protected Map rcMap; - - private List perts; - - /** - * Copy constructor - * - * @param that - */ - public GribRequestableLevelNode(GribRequestableLevelNode that) { - super(that); - this.rcMap = that.rcMap; - } - - /** - * Create a new requestable Level Node that is LevelNode clone of that and - * uses rcMap for all Requests - * - * @param that - * @param rcMap - */ - public GribRequestableLevelNode(LevelNode that, - Map rcMap) { - super(that); - this.rcMap = rcMap; - } - - /** - * @param rcMap - * the rcMap to set - */ - public void setRequestConstraintMap(Map rcMap) { - this.rcMap = rcMap; - } - - @Override - public boolean isTimeAgnostic() { - return false; - } - - @Override - public Map getRequestConstraintMap() { - return rcMap; - } - - @Override - public boolean hasRequestConstraints() { - return true; - } - - @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) - throws VizException { - Set resultsSet = GribTimeCache.getInstance().getTimes(this); - if (resultsSet != null) { - return resultsSet; - } - - DataTime[] results = CatalogQuery.performTimeQuery(rcMap, latestOnly, - null); - if (results != null) { - resultsSet = new HashSet(Arrays.asList(results)); - if (!latestOnly) { - GribTimeCache.getInstance().setTimes(this, resultsSet); - } - return resultsSet; - } else { - return null; - } - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getTimeQueryInternal(boolean, java.util.Map) - */ - @Override - protected TimeQueryRequest getTimeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache) - throws VizException { - Set resultsSet = GribTimeCache.getInstance().getTimes(this); - if (resultsSet != null) { - return null; - } - return CatalogQuery.getTimeQuery(rcMap, latestOnly, null); - } - - @Override - protected void processTimeQueryResults(boolean latestOnly, - List queryResponse) throws VizException { - if (!latestOnly) { - Set resultsSet = new HashSet(queryResponse); - GribTimeCache.getInstance().setTimes(this, resultsSet); - } - } - - @Override - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - DbQueryRequest dbRequest = getDataQueryInternal(property, timeOut, - cache); - DbQueryResponse response = (DbQueryResponse) ThriftClient - .sendRequest(dbRequest); - return processDataQueryResults(response); - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getDataQueryInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int) - */ - @Override - protected DbQueryRequest getDataQueryInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - Map oldQuery = property - .getEntryQueryParameters(false); - - Map newQuery = new HashMap( - rcMap); - for (Entry e : oldQuery.entrySet()) { - if (!newQuery.containsKey(e.getKey())) { - newQuery.put(e.getKey(), e.getValue()); - } - } - - DbQueryRequest dbRequest = new DbQueryRequest(); - DataTime[] times = property.getSelectedEntryTime(); - if (times != null && times.length > 0) { - RequestConstraint dtRC = new RequestConstraint(); - dtRC.setConstraintType(ConstraintType.IN); - for (DataTime t : times) { - dtRC.addToConstraintValueList(t.toString()); - } - newQuery.put("dataTime", dtRC); - } - newQuery.put("pluginName", new RequestConstraint("grib")); - dbRequest.setConstraints(newQuery); - return dbRequest; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * processQueryResults - * (com.raytheon.uf.common.dataquery.responses.DbQueryResponse) - */ - @Override - protected List processDataQueryResults( - DbQueryResponse response) throws VizException { - List> rows = response.getResults(); - List rval = new ArrayList( - rows.size()); - GribRequestableDataFactory factory = GribRequestableDataFactory - .getInstance(); - for (Map objMap : rows) { - rval.add(factory.getGribRequestableData((GribRecord) objMap - .get(null))); - } - return rval; - } - - /* - * (non-Javadoc) - * - * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getDependencies() - */ - @Override - public List getDependencies() { - return Collections.emptyList(); - } - - @Override - public GribRequestableLevelNode clone() { - return new GribRequestableLevelNode(this); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - final int prime = 31; - int result = super.hashCode(); - result = prime * result + ((rcMap == null) ? 0 : rcMap.hashCode()); - return result; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (!super.equals(obj)) - return false; - if (getClass() != obj.getClass()) - return false; - GribRequestableLevelNode other = (GribRequestableLevelNode) obj; - if (rcMap == null) { - if (other.rcMap != null) - return false; - } else if (!rcMap.equals(other.rcMap)) - return false; - return true; - } - - /** - * @return the perts - */ - public List getPerts() { - return perts; - } - - /** - * @param perts - * the perts to set - */ - public void setPerts(List perts) { - this.perts = perts; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribTimeCache.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribTimeCache.java deleted file mode 100644 index ebeb272537..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribTimeCache.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.inv; - -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import com.raytheon.uf.common.time.DataTime; - -/** - * TODO Add Description - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Jun 10, 2010            bsteffen     Initial creation
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ - -public class GribTimeCache { - - protected static final int CACHE_SIZE = 500; - - protected static final int CACHE_TIME = 300000; - - private static GribTimeCache instance; - - public static GribTimeCache getInstance() { - if (instance == null) { - instance = new GribTimeCache(); - } - return instance; - } - - private GribTimeCache() { - - } - - private class CacheEntry { - - public CacheEntry(Set times) { - this.insertTime = System.currentTimeMillis(); - this.times = times; - } - - public long insertTime; - - public Set times; - - } - - private Map cache = new LinkedHashMap( - 135, .75f, true) { - - private static final long serialVersionUID = 2022670836957170184L; - - /* - * (non-Javadoc) - * - * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) - */ - @Override - protected boolean removeEldestEntry(Entry eldest) { - return this.size() > CACHE_SIZE; - } - }; - - public synchronized void setTimes(GribRequestableLevelNode gNode, - Set times) { - cache.put(new GribMapKey(gNode.getRequestConstraintMap()), - new CacheEntry(times)); - } - - public synchronized Set getTimes(GribRequestableLevelNode gNode) { - GribMapKey key = new GribMapKey(gNode.getRequestConstraintMap()); - CacheEntry entry = cache.get(key); - if (entry == null) { - return null; - } - if (entry.insertTime + CACHE_TIME < System.currentTimeMillis()) { - cache.remove(key); - return null; - } - return entry.times; - } - - public synchronized void clearTimes(GribMapKey key) { - cache.remove(key); - } - - public synchronized void flush() { - cache.clear(); - } - -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridInventory.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridInventory.java index 1f868c64aa..9ffb16bda6 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridInventory.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridInventory.java @@ -21,6 +21,7 @@ package com.raytheon.viz.grid.inv; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; @@ -32,11 +33,13 @@ import java.util.Map.Entry; import java.util.NavigableSet; import java.util.Set; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; -import com.raytheon.uf.common.dataplugin.grib.util.StaticGridDataType; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridInfoConstants; +import com.raytheon.uf.common.dataplugin.grid.GridInfoRecord; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; +import com.raytheon.uf.common.dataplugin.grid.request.GetGridTreeRequest; +import com.raytheon.uf.common.dataplugin.grid.util.StaticGridDataType; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; @@ -46,13 +49,13 @@ import com.raytheon.uf.common.derivparam.tree.DataTree; import com.raytheon.uf.common.derivparam.tree.LevelNode; import com.raytheon.uf.common.derivparam.tree.ParameterNode; import com.raytheon.uf.common.derivparam.tree.SourceNode; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.catalog.CatalogQuery; import com.raytheon.uf.viz.core.catalog.DbQuery; -import com.raytheon.uf.viz.core.comm.Connector; import com.raytheon.uf.viz.core.exception.VizCommunicationException; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.level.LevelUtilities; @@ -63,21 +66,20 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamField; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod.MethodType; -import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode.Dependency; +import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode.Dependency; import com.raytheon.uf.viz.derivparam.tree.CubeLevel; import com.raytheon.uf.viz.derivparam.tree.StaticDataLevelNode; import com.raytheon.uf.viz.points.IPointChangedListener; import com.raytheon.uf.viz.points.PointsDataManager; import com.raytheon.viz.grid.data.ImportRequestableData; -import com.raytheon.viz.grid.data.StaticGridRequestableData; -import com.raytheon.viz.grid.data.TiltRequestableData; import com.raytheon.viz.grid.util.CoverageUtils; import com.raytheon.viz.grid.util.RadarAdapter; /** - * TODO Add Description + * Inventory object for calculating and managing the available grid data, + * including any data that can be derived. * *
  * 
@@ -98,32 +100,26 @@ public class GridInventory extends AbstractInventory implements
     private static final transient IUFStatusHandler statusHandler = UFStatus
             .getHandler(GridInventory.class);
 
-    public static String MODEL_NAME = "modelName";
+    public static final String PLUGIN_NAME_QUERY = GridConstants.PLUGIN_NAME;
 
-    public static String PERT_NUMBER = "perturbationNumber";
+    public static final String MODEL_NAME_QUERY = GridConstants.DATASET_ID;
 
-    public static String PARAMETER = "parameterAbbreviation";
+    public static final String PARAMETER_QUERY = GridConstants.PARAMETER_ABBREVIATION;
 
-    public static String LEVEL_ID = "level.id";
+    public static final String LEVEL_ID_QUERY = GridConstants.LEVEL_ID;
 
-    public static final String PLUGIN_NAME_QUERY = "pluginName";
+    public static final String MASTER_LEVEL_QUERY = GridConstants.MASTER_LEVEL_NAME;
 
-    public static final String MODEL_NAME_QUERY = "modelInfo." + MODEL_NAME;
+    public static final String LEVEL_ONE_QUERY = GridConstants.LEVEL_ONE;
 
-    public static final String PARAMETER_QUERY = "modelInfo." + PARAMETER;
+    public static final String LEVEL_TWO_QUERY = GridConstants.LEVEL_TWO;
 
-    public static final String LEVEL_ID_QUERY = "modelInfo." + LEVEL_ID;
-
-    public static final String MASTER_LEVEL_QUERY = "modelInfo.level.masterLevel.name";
-
-    public static final String LEVEL_ONE_QUERY = "modelInfo.level.levelonevalue";
-
-    public static final String LEVEL_TWO_QUERY = "modelInfo.level.leveltwovalue";
-
-    public static final String PERT_QUERY = "modelInfo." + PERT_NUMBER;
+    public static final String ENSEMBLE_QUERY = GridConstants.ENSEMBLE_ID;
 
     public static final String CUBE_MASTER_LEVEL_NAME = "MB";
 
+    public static final String PLUGIN_NAME = GridConstants.GRID;
+
     private GridUpdater updater;
 
     private List modelsWithPerts = new ArrayList();
@@ -163,17 +159,19 @@ public class GridInventory extends AbstractInventory implements
         }
     }
 
-    private DataTree getTreeFromEdex() throws VizException {
-        String request = "from com.raytheon.edex.uengine.tasks.grib import GridCatalog\n"
-                + "from com.raytheon.uf.common.message.response import ResponseMessageGeneric\n"
-                + "test = GridCatalog()\n"
-                + "return ResponseMessageGeneric(test.execute())";
-        Object[] tree = null;
-        tree = Connector.getInstance().connect(request, null, 60000);
-        if (tree != null) {
-            return (DataTree) tree[0];
+    private DataTree getTreeFromEdex() {
+        GetGridTreeRequest request = new GetGridTreeRequest();
+        Object tree = null;
+        try {
+            tree = ThriftClient.sendRequest(request);
+        } catch (VizCommunicationException e) {
+            statusHandler.handle(Priority.PROBLEM,
+                    "Error communicating with server.", e);
+        } catch (VizException e) {
+            statusHandler.handle(Priority.PROBLEM,
+                    "Error occurred while retrieving grid tree.", e);
         }
-        return null;
+        return (DataTree) tree;
     }
 
     private void initGatherModels(DataTree tree) {
@@ -184,36 +182,40 @@ public class GridInventory extends AbstractInventory implements
         // perturbationNumber >= 0
         DbQueryRequest request = new DbQueryRequest();
         request.setDistinct(true);
-        request.addRequestField(MODEL_NAME);
-        request.addRequestField(PARAMETER);
-        request.addRequestField(LEVEL_ID);
-        request.addRequestField(PERT_NUMBER);
-        request.addConstraint(PERT_NUMBER, new RequestConstraint("0",
-                ConstraintType.GREATER_THAN_EQUALS));
-        request.setEntityClass(GribModel.class.getName());
+        request.addRequestField(GridInfoConstants.DATASET_ID);
+        request.addRequestField(GridInfoConstants.PARAMETER_ABBREVIATION);
+        request.addRequestField(GridInfoConstants.LEVEL_ID);
+        request.addRequestField(GridInfoConstants.ENSEMBLE_ID);
+        request.addConstraint(GridInfoConstants.ENSEMBLE_ID,
+                new RequestConstraint("", ConstraintType.NOT_EQUALS));
+        request.setEntityClass(GridInfoRecord.class.getName());
 
         // Send request and process response
         try {
             DbQueryResponse response = (DbQueryResponse) ThriftClient
                     .sendRequest(request);
             for (Map objMap : response.getResults()) {
-                String model = String.valueOf(objMap.get(MODEL_NAME));
-                String parameter = String.valueOf(objMap.get(PARAMETER));
-                String levelId = String.valueOf(objMap.get(LEVEL_ID));
-                Integer pert = ((Number) objMap.get(PERT_NUMBER)).intValue();
+                String model = String.valueOf(objMap
+                        .get(GridInfoConstants.DATASET_ID));
+                String parameter = String.valueOf(objMap
+                        .get(GridInfoConstants.PARAMETER_ABBREVIATION));
+                String levelId = String.valueOf(objMap
+                        .get(GridInfoConstants.LEVEL_ID));
+                String ensemble = (String) objMap
+                        .get(GridInfoConstants.ENSEMBLE_ID);
                 LevelNode node = tree.getLevelNode(model, parameter,
                         levelId.toString());
-                if (node instanceof GribRequestableLevelNode) {
-                    GribRequestableLevelNode gribNode = (GribRequestableLevelNode) node;
-                    List perts = gribNode.getPerts();
-                    if (perts == null) {
-                        perts = new ArrayList(1);
-                        perts.add(pert);
-                    } else if (!perts.contains(pert)) {
-                        perts = new ArrayList(perts);
-                        perts.add(pert);
+                if (node instanceof GridRequestableNode) {
+                    GridRequestableNode gribNode = (GridRequestableNode) node;
+                    List ensembles = gribNode.getEnsembles();
+                    if (ensembles == null) {
+                        ensembles = new ArrayList(1);
+                        ensembles.add(ensemble);
+                    } else if (!ensembles.contains(ensemble)) {
+                        ensembles = new ArrayList(ensembles);
+                        ensembles.add(ensemble);
                     }
-                    gribNode.setPerts(perts);
+                    gribNode.setEnsembles(ensembles);
                 }
                 if (!modelsWithPerts.contains(model)) {
                     modelsWithPerts.add(model);
@@ -222,7 +224,7 @@ public class GridInventory extends AbstractInventory implements
         } catch (VizException e) {
             statusHandler
                     .handle(Priority.PROBLEM,
-                            "Error determining perterbations, Gather function may be broken",
+                            "Error determining ensemble information, Gather function may be broken",
                             e);
         }
         long endTime = System.currentTimeMillis();
@@ -240,15 +242,15 @@ public class GridInventory extends AbstractInventory implements
      */
     public LevelNode getNode(String source, String parameter, Level level) {
         try {
-            List nodes = walkTree(null,
+            List nodes = walkTree(null,
                     Arrays.asList(source), Arrays.asList(parameter),
                     Arrays.asList(level), true, true, null);
             if (nodes == null || nodes.isEmpty()) {
                 return null;
             }
-            if (nodes.get(0) instanceof AbstractDerivedLevelNode) {
+            if (nodes.get(0) instanceof AbstractDerivedDataNode) {
                 try {
-                    updater.addNode((AbstractDerivedLevelNode) nodes.get(0));
+                    updater.addNode((AbstractDerivedDataNode) nodes.get(0));
                 } catch (VizException e) {
                     statusHandler
                             .handle(Priority.PROBLEM,
@@ -278,7 +280,8 @@ public class GridInventory extends AbstractInventory implements
                     LevelNode lNode = new LevelNode();
                     lNode.setLevel(lEntry.getValue().getLevel());
                     Map rcMap = new HashMap();
-                    rcMap.put(PLUGIN_NAME_QUERY, new RequestConstraint("grib"));
+                    rcMap.put(PLUGIN_NAME_QUERY, new RequestConstraint(
+                            PLUGIN_NAME));
                     rcMap.put(MODEL_NAME_QUERY,
                             new RequestConstraint(sNode.getValue()));
                     rcMap.put(PARAMETER_QUERY,
@@ -293,7 +296,7 @@ public class GridInventory extends AbstractInventory implements
                             LEVEL_TWO_QUERY,
                             new RequestConstraint(Double.toString(lNode
                                     .getLevel().getLeveltwovalue())));
-                    lNode = new GribRequestableLevelNode(lNode, rcMap);
+                    lNode = new GridRequestableNode(lNode, rcMap);
                     pNode.getChildNodes().put(lEntry.getKey(), lNode);
                 }
                 sNode.addChildNode(pNode);
@@ -350,17 +353,14 @@ public class GridInventory extends AbstractInventory implements
      * @param newGridTree
      */
     private void initAliasModels(DataTree newGridTree) {
-        Set allAliasModels = new HashSet();
         sourceAliases.clear();
-        GribModelLookup lookup = GribModelLookup.getInstance();
+        DatasetInfoLookup lookup = DatasetInfoLookup.getInstance();
         for (String modelName : newGridTree.getSources()) {
-            GridModel model = lookup.getModelByName(modelName);
-            if (model != null && model.getAlias() != null) {
+            DatasetInfo info = lookup.getInfo(modelName);
+            if (info != null && info.getAlias() != null) {
                 SourceNode source = newGridTree.getSourceNode(modelName);
-                SourceNode dest = newGridTree.getSourceNode(model.getAlias());
+                SourceNode dest = newGridTree.getSourceNode(info.getAlias());
                 if (source != null && dest != null) {
-                    allAliasModels.add(source.getValue());
-                    allAliasModels.add(dest.getValue());
                     List aliases = sourceAliases.get(dest.getValue());
                     if (aliases == null) {
                         aliases = new ArrayList();
@@ -371,36 +371,52 @@ public class GridInventory extends AbstractInventory implements
                 }
             }
         }
-        // Requesting coverages all at once is more efficient
-        try {
-            final Map coverages = CoverageUtils
-                    .getInstance().getCoverages(allAliasModels);
+        for (Entry> aliases : sourceAliases.entrySet()) {
+            Collections.sort(aliases.getValue(), new Comparator() {
 
-            for (Entry> aliases : sourceAliases.entrySet()) {
-                Collections.sort(aliases.getValue(), new Comparator() {
-
-                    @Override
-                    public int compare(String model1, String model2) {
-                        GridCoverage coverage1 = coverages.get(model1);
-                        Integer res1 = coverage1.getNx() * coverage1.getNy();
-                        GridCoverage coverage2 = coverages.get(model2);
-                        Integer res2 = coverage2.getNx() * coverage2.getNy();
-                        return res2.compareTo(res1);
+                @Override
+                public int compare(String model1, String model2) {
+                    try {
+                        // attempt to figure out which model is the highest
+                        // resolution.
+                        Collection coverages1 = CoverageUtils
+                                .getInstance().getCoverages(model1);
+                        Collection coverages2 = CoverageUtils
+                                .getInstance().getCoverages(model2);
+                        if (coverages1.isEmpty()) {
+                            return 1;
+                        } else if (coverages2.isEmpty()) {
+                            return -1;
+                        }
+                        double total1 = 0;
+                        double total2 = 0;
+                        for (GridCoverage coverage : coverages1) {
+                            total1 += coverage.getDx();
+                            total1 += coverage.getDy();
+                        }
+                        for (GridCoverage coverage : coverages2) {
+                            total2 += coverage.getDx();
+                            total2 += coverage.getDy();
+                        }
+                        Double res1 = total1 / coverages1.size();
+                        Double res2 = total2 / coverages2.size();
+                        return res1.compareTo(res2);
+                    } catch (VizException e) {
+                        statusHandler.handle(Priority.PROBLEM,
+                                "Unable to create model aliases, problems with "
+                                        + model1 + " and " + model2, e);
+                        return 0;
                     }
+                }
 
-                });
-            }
-        } catch (VizException e) {
-            statusHandler.handle(Priority.PROBLEM,
-                    "Unable to create model aliases", e);
-            return;
+            });
         }
     }
 
     public Set getAvailableLevels(Map query) {
         Set levels = new HashSet();
-        List nodes = evaluateRequestConstraints(query);
-        for (AbstractRequestableLevelNode node : nodes) {
+        List nodes = evaluateRequestConstraints(query);
+        for (AbstractRequestableNode node : nodes) {
             levels.add(node.getLevel());
         }
         return levels;
@@ -413,7 +429,7 @@ public class GridInventory extends AbstractInventory implements
      * @param query
      * @return
      */
-    public List evaluateRequestConstraints(
+    public List evaluateRequestConstraints(
             Map query) {
         List sourcesToProcess = getSourcesToProcess(query);
         List paramsToProcess = getParametersToProcess(query);
@@ -421,14 +437,14 @@ public class GridInventory extends AbstractInventory implements
         if (!levelsToProcess.isEmpty() && !sourcesToProcess.isEmpty()
                 && !paramsToProcess.isEmpty()) {
             try {
-                List nodes = walkTree(null,
+                List nodes = walkTree(null,
                         sourcesToProcess, paramsToProcess, levelsToProcess,
                         true, true, null);
                 try {
 
-                    for (AbstractRequestableLevelNode node : nodes) {
-                        if (node instanceof AbstractDerivedLevelNode) {
-                            updater.addNode((AbstractDerivedLevelNode) node);
+                    for (AbstractRequestableNode node : nodes) {
+                        if (node instanceof AbstractDerivedDataNode) {
+                            updater.addNode((AbstractDerivedDataNode) node);
                         }
                     }
                 } catch (VizException e) {
@@ -449,10 +465,10 @@ public class GridInventory extends AbstractInventory implements
             }
         }
 
-        return new ArrayList(0);
+        return new ArrayList(0);
     }
 
-    public List getPerts(Map query)
+    public List getEnsembles(Map query)
             throws VizException {
         RequestConstraint nameRC = query.get(MODEL_NAME_QUERY);
         if (nameRC == null) {
@@ -476,44 +492,47 @@ public class GridInventory extends AbstractInventory implements
                 return Collections.emptyList();
             }
         }
-        Set perts = new HashSet();
-        for (AbstractRequestableLevelNode node : evaluateRequestConstraints(query)) {
-            perts.addAll(getPerts(node));
+        Set ensembles = new HashSet();
+        for (AbstractRequestableNode node : evaluateRequestConstraints(query)) {
+            ensembles.addAll(getEnsembles(node));
         }
-        return new ArrayList(perts);
+        return new ArrayList(ensembles);
 
     }
 
-    protected static List getPerts(AbstractRequestableLevelNode node)
+    protected static List getEnsembles(AbstractRequestableNode node)
             throws VizException {
-        if (node instanceof GribRequestableLevelNode) {
-            GribRequestableLevelNode gNode = (GribRequestableLevelNode) node;
-            if (gNode.getPerts() != null) {
-                return gNode.getPerts();
+
+        if (node instanceof GridRequestableNode) {
+            GridRequestableNode gNode = (GridRequestableNode) node;
+            if (gNode.getEnsembles() != null) {
+                return gNode.getEnsembles();
             }
             Map rcMap = gNode
                     .getRequestConstraintMap();
-            DbQuery dbQuery = new DbQuery("grib");
-            dbQuery.setDistinctField(PERT_QUERY);
+            DbQuery dbQuery = new DbQuery(PLUGIN_NAME);
+            dbQuery.setDistinctField(ENSEMBLE_QUERY);
             for (Entry entry : rcMap.entrySet()) {
                 dbQuery.addConstraint(entry.getKey(), entry.getValue());
             }
-            List perts = new ArrayList();
-            for (Object[] pert : dbQuery.performQuery()) {
-                perts.add((Integer) pert[0]);
+            List ensembles = new ArrayList();
+            for (Object[] ensemble : dbQuery.performQuery()) {
+                ensembles.add((String) ensemble[0]);
             }
-            gNode.setPerts(perts);
-            return perts;
+            gNode.setEnsembles(ensembles);
+            return ensembles;
         } else if (node instanceof GatherLevelNode) {
             return Collections.emptyList();
-        } else {
-            Set perts = new HashSet();
+        } else if (node instanceof AbstractDerivedDataNode) {
+            AbstractDerivedDataNode dataNode = (AbstractDerivedDataNode) node;
+            Set ensembles = new HashSet();
 
-            for (Dependency dep : node.getDependencies()) {
-                perts.addAll(getPerts(dep.node));
+            for (Dependency dep : dataNode.getDependencies()) {
+                ensembles.addAll(getEnsembles(dep.node));
             }
-            return new ArrayList(perts);
+            return new ArrayList(ensembles);
         }
+        return Collections.emptyList();
     }
 
     /**
@@ -607,7 +626,7 @@ public class GridInventory extends AbstractInventory implements
     }
 
     @Override
-    protected AbstractDerivedLevelNode getImportNode(
+    protected AbstractDerivedDataNode getImportNode(
             AbstractRequestableData nodeToImport, SourceNode destSourceNode,
             DerivParamDesc desc, DerivParamMethod method, Level level) {
         AbstractRequestableData data = new ImportRequestableData(nodeToImport,
@@ -622,8 +641,8 @@ public class GridInventory extends AbstractInventory implements
     }
 
     @Override
-    protected AbstractDerivedLevelNode getImportNode(
-            AbstractRequestableLevelNode nodeToImport,
+    protected AbstractDerivedDataNode getImportNode(
+            AbstractRequestableNode nodeToImport,
             String nodeToImportSourceName, SourceNode destSourceNode,
             DerivParamDesc desc, DerivParamMethod method, Level level) {
         return new ImportLevelNode(nodeToImport, nodeToImportSourceName, desc,
@@ -655,26 +674,20 @@ public class GridInventory extends AbstractInventory implements
         String masterLevelName = get3DMasterLevel(sNode.getValue());
         boolean isRadar = sNode.getValue().equals(RadarAdapter.RADAR_SOURCE);
 
-        NavigableSet levels = null;
-        try {
-            levels = LevelUtilities
-                    .getOrderedSetOfStandardLevels(masterLevelName);
-        } catch (VizCommunicationException e) {
-            statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e);
-            return null;
-        }
-        List> cubeLevels = new ArrayList>(
+        NavigableSet levels = LevelUtilities
+                .getOrderedSetOfStandardLevels(masterLevelName);
+        List> cubeLevels = new ArrayList>(
                 levels.size());
 
         for (Level fieldLevel : levels) {
-            AbstractRequestableLevelNode pressure = resolveNode(sNode, "P",
+            AbstractRequestableNode pressure = resolveNode(sNode, "P",
                     fieldLevel, stack, nodata);
             if (pressure != null) {
-                AbstractRequestableLevelNode param = resolveNode(sNode,
+                AbstractRequestableNode param = resolveNode(sNode,
                         field.getParam(), fieldLevel, stack, nodata);
 
                 if (param != null) {
-                    CubeLevel cl = new CubeLevel(
+                    CubeLevel cl = new CubeLevel(
                             pressure, param);
                     cubeLevels.add(cl);
                 }
@@ -703,32 +716,31 @@ public class GridInventory extends AbstractInventory implements
             DerivParamField field, Level level) {
         String fieldParamAbbrev = field.getParam();
         if (StaticGridDataType.getStringValues().contains(fieldParamAbbrev)) {
-            StaticGridDataType staticGridDataType = StaticGridDataType
-                    .valueOf(fieldParamAbbrev);
-            return new StaticGridRequestableData(staticGridDataType,
-                    sNode.getValue());
+            return new StaticGridDataLevelNode(sNode.getValue(),
+                    fieldParamAbbrev);
         }
         // Check to see if we can set the field from the
         // masterlevel name
         if (level.getMasterLevel().getName().equals(fieldParamAbbrev)) {
             if ("TILT".equals(fieldParamAbbrev)) {
-                return new TiltRequestableData(sNode.getValue(), level);
+                return new StaticGridDataLevelNode(sNode.getValue(),
+                        fieldParamAbbrev, level);
             }
         }
         return null;
     }
 
-    protected AbstractDerivedLevelNode createDerivedNode(DerivParamDesc desc,
+    protected AbstractDerivedDataNode createDerivedNode(DerivParamDesc desc,
             DerivParamMethod method, Level level, List fields,
             SourceNode source) {
         if (method.getMethodType() == MethodType.OTHER
                 && method.getName().equalsIgnoreCase("Gather")) {
-            AbstractRequestableLevelNode lNode = (AbstractRequestableLevelNode) fields
+            AbstractRequestableNode lNode = (AbstractRequestableNode) fields
                     .get(0);
 
             try {
                 if (modelsWithPerts.contains(source.getValue())
-                        && getPerts(lNode).size() > 1) {
+                        && getEnsembles(lNode).size() > 1) {
                     return new GatherLevelNode(lNode, desc, method,
                             source.getValue(), level);
                 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribMapKey.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridMapKey.java
similarity index 91%
rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribMapKey.java
rename to cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridMapKey.java
index 20d881637a..357569aadf 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GribMapKey.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridMapKey.java
@@ -24,7 +24,24 @@ import java.util.Map;
 import com.raytheon.uf.common.dataplugin.level.Level;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
 
-public class GribMapKey {
+/**
+ * 
+ * Unique key for grid metadata, useful in caches.
+ * 
+ * 
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 20, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class GridMapKey { public final String modelName; @@ -36,11 +53,11 @@ public class GribMapKey { public final double leveltwo; - public GribMapKey(GribRequestableLevelNode node) { + public GridMapKey(GridRequestableNode node) { this(node.getRequestConstraintMap()); } - public GribMapKey(Map map) { + public GridMapKey(Map map) { Object obj; obj = map.get(GridInventory.MODEL_NAME_QUERY); if (obj != null && obj instanceof RequestConstraint) { @@ -130,7 +147,7 @@ public class GribMapKey { return false; if (getClass() != obj.getClass()) return false; - GribMapKey other = (GribMapKey) obj; + GridMapKey other = (GridMapKey) obj; if (Double.doubleToLongBits(levelone) != Double .doubleToLongBits(other.levelone)) return false; diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridMetadataContainer.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridMetadataContainer.java new file mode 100644 index 0000000000..0c08b804af --- /dev/null +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridMetadataContainer.java @@ -0,0 +1,244 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.grid.inv; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; +import com.raytheon.uf.common.dataquery.requests.DbQueryRequestSet; +import com.raytheon.uf.common.dataquery.requests.RequestConstraint; +import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; +import com.raytheon.uf.common.dataquery.responses.DbQueryResponseSet; +import com.raytheon.uf.viz.core.RecordFactory; +import com.raytheon.uf.viz.core.datastructure.DecisionTree; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.core.requests.ThriftClient; +import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.MetadataContainer; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; +import com.raytheon.viz.grid.data.GridRequestableData; +import com.raytheon.viz.grid.data.GridRequestableDataFactory; + +/** + * TODO Add Description + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 10, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridMetadataContainer extends MetadataContainer { + + /** + * @param originalConstraints + */ + public GridMetadataContainer( + Map originalConstraints, + AvailabilityContainer availabilityContainer) { + super(originalConstraints, availabilityContainer); + } + + @Override + protected void processRequests() throws VizException { + DecisionTree tree = new DecisionTree(); + List> constraintMaps = new ArrayList>(); + for (AbstractRequestableNode node : availCache.keySet()) { + if (dataCache.containsKey(node)) { + continue; + } + if (node instanceof GridRequestableNode) { + GridRequestableNode dataNode = (GridRequestableNode) node; + DbQueryRequest request = dataNode.getDataRequest( + originalConstraints, availCache.get(node)); + Map constraints = request + .getConstraints(); + tree.insertCriteria(constraints, dataNode, false); + constraintMaps.add(constraints); + } + } + if (constraintMaps.isEmpty()) { + super.processRequests(); + return; + } else if (constraintMaps.size() == 1) { + super.processRequests(); + return; + } + List requests = new ArrayList(); + constraintMaps = mergeConstraints(constraintMaps); + for (Map constraintMap : constraintMaps) { + DbQueryRequest dbRequest = new DbQueryRequest(); + dbRequest.setEntityClass(GridRecord.class.getName()); + dbRequest.setConstraints(constraintMap); + requests.add(dbRequest); + } + DbQueryRequestSet requestSet = new DbQueryRequestSet(); + requestSet.setQueries(requests.toArray(new DbQueryRequest[0])); + DbQueryResponseSet responseSet = (DbQueryResponseSet) ThriftClient + .sendRequest(requestSet); + + Map> dataCache = new HashMap>(); + GridRequestableDataFactory grdf = GridRequestableDataFactory + .getInstance(); + tree.rebuildTree(); + for (DbQueryResponse response : responseSet.getResults()) { + for (Map result : response.getResults()) { + GridRecord record = (GridRecord) result.get(null); + Map recordMap = RecordFactory.getInstance() + .loadMapFromUri(record.getDataURI()); + GridRequestableData data = grdf.getGridRequestableData(record); + for (GridRequestableNode node : tree.searchTree(recordMap)) { + Set set = dataCache.get(node); + if (set == null) { + set = new HashSet(); + dataCache.put(node, set); + } + set.add(data); + } + } + } + this.dataCache.putAll(dataCache); + super.processRequests(); + + } + + /** + * Takes the list of constraintMaps and merges the constraint maps that + * different by only one key into a new list of constraint maps. EX: 5 + * RequestConstraint Maps for GFS40 Temp on 5 MB levels will be consolidated + * into a single RequestConstraint Map using an IN List for the MB levels. + * + * @param constraintMaps + * @return + */ + public static List> mergeConstraints( + List> constraintMaps) { + List> rval = new ArrayList>(); + if (constraintMaps != null && constraintMaps.size() > 0) { + List mergeKeyList = new ArrayList(); + + for (Map constraintMap : constraintMaps) { + boolean merged = false; + int index = 0; + + MERGE_MAP_LOOP: for (index = 0; index < rval.size(); index++) { + Map mergeMap = rval.get(index); + + // maps must be of same size + if (mergeMap.size() == constraintMap.size()) { + String mergeKey = mergeKeyList.get(index); + + if (mergeKey != null) { + // determine if it matches map except for uniqueKey + for (String key : mergeMap.keySet()) { + boolean isUniqueKey = mergeKey.equals(key); + boolean constraintEquals = mergeMap.get(key) + .equals(constraintMap.get(key)); + + if (!constraintEquals && !isUniqueKey) { + continue MERGE_MAP_LOOP; + } + } + + // map differs except for key + boolean constraintMerged = mergeMap.get(mergeKey) + .merge(constraintMap.get(mergeKey)); + if (!constraintMerged) { + continue MERGE_MAP_LOOP; + } else { + merged = true; + break MERGE_MAP_LOOP; + } + } else { + // current mergeMap has never been merged with, + // double check that only one key is different + // between maps + for (String key : mergeMap.keySet()) { + if (!mergeMap.get(key).equals( + constraintMap.get(key))) { + if (mergeKey == null) { + // possible merge key, continue checking + // map + mergeKey = key; + } else { + // two merge keys found, go to next + // merge map + continue MERGE_MAP_LOOP; + } + } + } + + // found mergeKey, add to mergeKeyList. If mergeKey + // still being null is only possible of mergeMap and + // constraintMap contain the exact same constraints, + // consider them merged + if (mergeKey == null) { + merged = true; + break MERGE_MAP_LOOP; + } + + boolean constraintMerged = mergeMap.get(mergeKey) + .merge(constraintMap.get(mergeKey)); + if (!constraintMerged) { + continue MERGE_MAP_LOOP; + } else { + merged = true; + mergeKeyList.set(index, mergeKey); + break MERGE_MAP_LOOP; + } + + } + } // maps same size check + } // MERGE_MAP_LOOP + + if (!merged) { + Map mergeMap = new HashMap(); + + // deep copy the map + for (Map.Entry entry : constraintMap + .entrySet()) { + mergeMap.put(entry.getKey(), entry.getValue().clone()); + } + + rval.add(mergeMap); + mergeKeyList.add(null); + } + } + } + + return rval; + } + +} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridRequestableNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridRequestableNode.java new file mode 100644 index 0000000000..2eff0b93f0 --- /dev/null +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridRequestableNode.java @@ -0,0 +1,289 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.grid.inv; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +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.derivparam.tree.LevelNode; +import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.core.requests.ThriftClient; +import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode; +import com.raytheon.viz.grid.data.GridRequestableDataFactory; +import com.raytheon.viz.grid.util.CoverageUtils; + +/** + * + * A basic node which fulfills time and data requests by going to edex. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jan 19, 2010            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class GridRequestableNode extends AbstractBaseDataNode { + + protected static final String TIME_FIELD = "dataTime"; + + protected Map rcMap; + + private List ensembles; + + /** + * Copy constructor + * + * @param that + */ + public GridRequestableNode(GridRequestableNode that) { + super(that); + this.rcMap = that.rcMap; + } + + /** + * Create a new requestable Level Node that is LevelNode clone of that and + * uses rcMap for all Requests + * + * @param that + * @param rcMap + */ + public GridRequestableNode(LevelNode that, + Map rcMap) { + super(that); + this.rcMap = rcMap; + } + + /** + * @param rcMap + * the rcMap to set + */ + public void setRequestConstraintMap(Map rcMap) { + this.rcMap = rcMap; + } + + public Map getRequestConstraintMap() { + return rcMap; + } + + @Override + public Set getData( + Map orignalConstraints, + Set availability, Object response) + throws VizException { + DbQueryResponse dbresponse = (DbQueryResponse) response; + GridRequestableDataFactory grdf = GridRequestableDataFactory + .getInstance(); + Set ards = new HashSet(); + for (Map result : dbresponse.getResults()) { + GridRecord record = (GridRecord) result.get(null); + ards.add(grdf.getGridRequestableData(record)); + } + return ards; + } + + @Override + public DbQueryRequest getDataRequest( + Map orignalConstraints, + Set availability) { + boolean timeAgnostic = false; + boolean spaceAgnostic = false; + Set times = new HashSet(); + Set spaces = new HashSet(); + for (TimeAndSpace ast : availability) { + if (ast.isTimeAgnostic()) { + timeAgnostic = true; + } else { + times.add(ast.getTime()); + } + if (ast.isSpaceAgnostic()) { + spaceAgnostic = true; + } else { + spaces.add(ast.getSpace()); + } + } + DbQueryRequest dbRequest = new DbQueryRequest(); + dbRequest.setEntityClass(GridRecord.class.getName()); + dbRequest.setConstraints(new HashMap(rcMap)); + for (Entry e : orignalConstraints.entrySet()) { + if (!rcMap.containsKey(e.getKey())) { + dbRequest.addConstraint(e.getKey(), e.getValue()); + } + } + if (!timeAgnostic) { + RequestConstraint timeRc = new RequestConstraint(); + timeRc.setConstraintType(ConstraintType.IN); + for (DataTime time : times) { + timeRc.addToConstraintValueList(time.toString()); + } + dbRequest.addConstraint(TIME_FIELD, timeRc); + } + if (!spaceAgnostic) { + RequestConstraint spaceRc = new RequestConstraint(); + spaceRc.setConstraintType(ConstraintType.IN); + for (ISpatialObject space : spaces) { + if (space instanceof GridCoverage) { + spaceRc.addToConstraintValueList(Integer + .toString(((GridCoverage) space).getId())); + } else { + // TODO figure out the intersection of my spatial object + // with this spatial object. + } + } + dbRequest.addConstraint(GridConstants.LOCATION_ID, spaceRc); + } + return dbRequest; + } + + @Override + public GridRequestableNode clone() { + return new GridRequestableNode(this); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((rcMap == null) ? 0 : rcMap.hashCode()); + return result; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + GridRequestableNode other = (GridRequestableNode) obj; + if (rcMap == null) { + if (other.rcMap != null) + return false; + } else if (!rcMap.equals(other.rcMap)) + return false; + return true; + } + + public List getEnsembles() { + return ensembles; + } + + public void setEnsembles(List ensembles) { + this.ensembles = ensembles; + } + + private String getSource() { + return rcMap.get(GridConstants.DATASET_ID).getConstraintValue(); + } + + @Override + public DbQueryRequest getAvailabilityRequest( + Map originalConstraints) { + if (GridTimeCache.getInstance().getTimes(this) != null) { + return null; + } + DbQueryRequest request = new DbQueryRequest(); + request.setEntityClass(GridRecord.class.getName()); + request.addRequestField(TIME_FIELD); + try { + if (CoverageUtils.getInstance().getCoverages(getSource()).size() > 1) { + request.addRequestField(GridConstants.LOCATION_ID); + } + } catch (VizException e) { + // not really a problem, just request the location from db. + UFStatus.getHandler().handle(Priority.VERBOSE, + e.getLocalizedMessage(), e); + request.addRequestField(GridConstants.LOCATION_ID); + } + request.setDistinct(true); + request.setConstraints(rcMap); + return request; + } + + @Override + public Set getAvailability( + Map originalConstraints, Object response) + throws VizException { + Set result = new HashSet(); + if (response == null) { + result = GridTimeCache.getInstance().getTimes(this); + if (result == null) { + // Oh No! the cache has been cleared since we made our request. + response = ThriftClient + .sendRequest(getAvailabilityRequest(originalConstraints)); + return getAvailability(originalConstraints, response); + } + GridTimeCache.getInstance().setTimes(this, result); + } else if (response instanceof DbQueryResponse) { + DbQueryResponse dbresponse = (DbQueryResponse) response; + for (Map map : dbresponse.getResults()) { + DataTime time = (DataTime) map.get(TIME_FIELD); + GridCoverage coverage = null; + if (map.containsKey(GridConstants.LOCATION_ID)) { + Number locationId = (Number) map + .get(GridConstants.LOCATION_ID); + coverage = GridCoverageLookup.getInstance().getCoverage( + locationId.intValue()); + } else { + coverage = CoverageUtils.getInstance() + .getCoverages(getSource()).iterator().next(); + } + result.add(new TimeAndSpace(time, coverage)); + } + GridTimeCache.getInstance().setTimes(this, result); + } + return result; + } + +} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridTimeCache.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridTimeCache.java new file mode 100644 index 0000000000..f60d5235d6 --- /dev/null +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridTimeCache.java @@ -0,0 +1,150 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.grid.inv; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; + +/** + * Cache times for GridRequestableNode's to avoid multiple trips to edex for the + * same data. The hit rate tends to be low when requesting individual products + * but can get very high when requesting complex derived parameters or model + * families since often many of the derived parameters can have dependencies on + * the same base parameters. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jun 10, 2010            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridTimeCache { + + protected static final int CACHE_SIZE = 500; + + protected static final int CACHE_TIME = 300000; + + private static GridTimeCache instance; + + public static GridTimeCache getInstance() { + if (instance == null) { + instance = new GridTimeCache(); + } + return instance; + } + + private GridTimeCache() { + + } + + private class CacheEntry { + + public CacheEntry(Set times) { + this.insertTime = System.currentTimeMillis(); + this.times = times; + } + + public long insertTime; + + public Set times; + + } + + private Map cache = new LinkedHashMap( + 135, .75f, true) { + + private static final long serialVersionUID = 2022670836957170184L; + + // used to make sure we don't spam the logs + private long lastLogTime; + + // Tracks the shortest amount of time that something has remained in the + // cache recently. + private long minTimeInCache = CACHE_TIME; + + /* + * (non-Javadoc) + * + * @see java.util.LinkedHashMap#removeEldestEntry(java.util.Map.Entry) + */ + @Override + protected boolean removeEldestEntry(Entry eldest) { + if (this.size() > CACHE_SIZE) { + // It is normal for stale entries to stay in the map until this + // purges them, but we want some logging for non stale entries. + long curTime = System.currentTimeMillis(); + long timeInCache = curTime - eldest.getValue().insertTime; + // only print if the entry is within its valid time, + if (timeInCache < CACHE_TIME + // Don't print more than once a minute (60000ms) unless this + // entry has been purged faster(was in the cache for less time) + // than the last output message. + && (curTime - lastLogTime > 60000 || timeInCache < minTimeInCache)) { + System.out.println(GridTimeCache.class.getSimpleName() + + " is purging after only " + timeInCache + "ms"); + lastLogTime = curTime; + // this is now the shortest time in cache. + minTimeInCache = timeInCache; + } + return true; + } + return false; + } + }; + + public synchronized void setTimes(GridRequestableNode gNode, + Set times) { + cache.put(new GridMapKey(gNode.getRequestConstraintMap()), + new CacheEntry(times)); + } + + public synchronized Set getTimes(GridRequestableNode gNode) { + GridMapKey key = new GridMapKey(gNode.getRequestConstraintMap()); + CacheEntry entry = cache.get(key); + if (entry == null) { + return null; + } + if (entry.insertTime + CACHE_TIME < System.currentTimeMillis()) { + cache.remove(key); + return null; + } + return entry.times; + } + + public synchronized void clearTimes(GridMapKey key) { + cache.remove(key); + } + + public synchronized void flush() { + cache.clear(); + } + +} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridUpdater.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridUpdater.java index c0d2e4ca24..227c654343 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridUpdater.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/GridUpdater.java @@ -27,14 +27,15 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.raytheon.edex.util.Util; import com.raytheon.uf.common.comm.CommunicationException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.derivparam.tree.LevelNode; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -42,8 +43,8 @@ import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.alerts.AlertMessage; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; -import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode.Dependency; +import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode.Dependency; import com.raytheon.uf.viz.derivparam.tree.OrLevelNode; import com.raytheon.viz.alerts.IAlertObserver; import com.raytheon.viz.alerts.observers.ProductAlertObserver; @@ -71,9 +72,9 @@ public class GridUpdater implements IAlertObserver { private class UpdateValue { public int timeOffset; - public AbstractDerivedLevelNode node; + public AbstractDerivedDataNode node; - public UpdateValue(Integer timeOffset, AbstractDerivedLevelNode node) { + public UpdateValue(Integer timeOffset, AbstractDerivedDataNode node) { this.timeOffset = timeOffset == null ? 0 : timeOffset; this.node = node; } @@ -129,23 +130,21 @@ public class GridUpdater implements IAlertObserver { private GridInventory inventory; - private Map> updateMap = new HashMap>(); + private Map> updateMap = new HashMap>(); public GridUpdater(GridInventory inventory) { - // TODO remove following line once Util removes static block - Util.getCurrentMemory(); this.inventory = inventory; } public void startObserving() { - ProductAlertObserver.addObserver("grib", this); + ProductAlertObserver.addObserver(GridInventory.PLUGIN_NAME, this); } public void stopObserving() { - ProductAlertObserver.removeObserver("grib", this); + ProductAlertObserver.removeObserver(GridInventory.PLUGIN_NAME, this); } - public synchronized void addNode(AbstractDerivedLevelNode node) + public synchronized void addNode(AbstractDerivedDataNode node) throws VizException { List dependencies = node.getDependencies(); if (dependencies == null || dependencies.isEmpty()) { @@ -155,9 +154,9 @@ public class GridUpdater implements IAlertObserver { for (int i = 0; i < dep.size(); i++) { Dependency dependency = dep.get(i); - if (dependency.node instanceof GribRequestableLevelNode) { - GribRequestableLevelNode gNode = (GribRequestableLevelNode) dependency.node; - GribMapKey updateKey = new GribMapKey( + if (dependency.node instanceof GridRequestableNode) { + GridRequestableNode gNode = (GridRequestableNode) dependency.node; + GridMapKey updateKey = new GridMapKey( gNode.getRequestConstraintMap()); Set set = updateMap.get(updateKey); if (set == null) { @@ -180,15 +179,16 @@ public class GridUpdater implements IAlertObserver { gribMap.put(GridInventory.LEVEL_TWO_QUERY, level.getLeveltwovalue()); - GribMapKey updateKey = new GribMapKey(gribMap); + GridMapKey updateKey = new GridMapKey(gribMap); Set set = updateMap.get(updateKey); if (set == null) { set = new HashSet(); updateMap.put(updateKey, set); } set.add(new UpdateValue(dependency.timeOffset, node)); - } else { - for (Dependency d : dependency.node.getDependencies()) { + } else if (dependency.node instanceof AbstractDerivedDataNode) { + AbstractDerivedDataNode dataNode = (AbstractDerivedDataNode) dependency.node; + for (Dependency d : dataNode.getDependencies()) { d.timeOffset += dependency.timeOffset; if (!dep.contains(d)) { dep.add(d); @@ -210,13 +210,12 @@ public class GridUpdater implements IAlertObserver { Set datauris = new HashSet(); for (AlertMessage alert : alertMessages) { if (myUpdates.remove(alert.dataURI)) { - // This updater triggered this alert, if it processes it now - // we + // This updater triggered this alert, if it processes it now we // could do this forever continue; } - GribMapKey updateKey = new GribMapKey(alert.decodedAlert); - GribTimeCache.getInstance().clearTimes(updateKey); + GridMapKey updateKey = new GridMapKey(alert.decodedAlert); + GridTimeCache.getInstance().clearTimes(updateKey); LevelNode lNode = null; try { Level level = LevelFactory.getInstance().getLevel( @@ -233,7 +232,7 @@ public class GridUpdater implements IAlertObserver { inventory.reinitTree(); // System.out.println(alert.dataURI); // System.out.println("LevelId=" + level.getId()); - } else if (!(lNode instanceof GribRequestableLevelNode)) { + } else if (!(lNode instanceof GridRequestableNode)) { if (lNode instanceof OrLevelNode) { DerivParamMethod method = ((OrLevelNode) lNode).getMethod(); // Null means it is an alias model and supplement means @@ -242,8 +241,7 @@ public class GridUpdater implements IAlertObserver { if (method == null || !method.getName().equals("Supplement")) { inventory.reinitTree(); - // System.out.println(((AbstractDerivedLevelNode) - // lNode) + // System.out.println(((AbstractDerivedLevelNode) lNode) // .getModelName()); } } else { @@ -257,8 +255,8 @@ public class GridUpdater implements IAlertObserver { continue; } for (UpdateValue value : set) { - GribRecord fakeRec = new GribRecord(); - fakeRec.setPluginName("grib"); + GridRecord fakeRec = new GridRecord(); + fakeRec.setPluginName(GridInventory.PLUGIN_NAME); Object obj = alert.decodedAlert.get("dataTime"); if (!(obj instanceof DataTime)) { throw new IllegalArgumentException( @@ -270,21 +268,23 @@ public class GridUpdater implements IAlertObserver { DataTime time = (DataTime) obj; fakeRec.setDataTime(new DataTime(time.getRefTime(), time .getFcstTime() - value.timeOffset)); - GribModel modelInfo = new GribModel(); - modelInfo.setModelName(value.node.getModelName()); - modelInfo.setParameterAbbreviation(value.node.getDesc() - .getAbbreviation()); - modelInfo.setLevel(value.node.getLevel()); + fakeRec.setDatasetId(value.node.getModelName()); + + Parameter param = new Parameter(value.node.getDesc() + .getAbbreviation(), value.node.getDesc().getName(), + value.node.getDesc().getUnit()); + fakeRec.setParameter(param); + fakeRec.setLevel(value.node.getLevel()); if (value.node instanceof GatherLevelNode) { - modelInfo.setPerturbationNumber(null); + fakeRec.setEnsembleId(null); } else { - modelInfo - .setPerturbationNumber((Integer) alert.decodedAlert - .get(GridInventory.PERT_QUERY)); + fakeRec.setEnsembleId((String) alert.decodedAlert + .get(GridInventory.ENSEMBLE_QUERY)); } - // do I need to set this? - modelInfo.setTypeEnsemble(null); - fakeRec.setModelInfo(modelInfo); + fakeRec.setSecondaryId((String) alert.decodedAlert + .get(GridConstants.SECONDARY_ID)); + fakeRec.setLocation((GridCoverage) alert.decodedAlert + .get(GridConstants.LOCATION)); try { fakeRec.constructDataURI(); datauris.add(fakeRec.getDataURI()); @@ -294,6 +294,7 @@ public class GridUpdater implements IAlertObserver { "Unable to generate updates for derived product", e); } + } } myUpdates.addAll(datauris); @@ -304,15 +305,15 @@ public class GridUpdater implements IAlertObserver { * */ public synchronized void refreshNodes() { - GribTimeCache.getInstance().flush(); - Set oldNodes = new HashSet(); + GridTimeCache.getInstance().flush(); + Set oldNodes = new HashSet(); for (Set values : updateMap.values()) { for (UpdateValue value : values) { oldNodes.add(value.node); } } updateMap.clear(); - for (AbstractDerivedLevelNode node : oldNodes) { + for (AbstractDerivedDataNode node : oldNodes) { // Get Node will automatically add this to the updater. inventory.getNode(node.getModelName(), node.getDesc() .getAbbreviation(), node.getLevel()); diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/ImportLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/ImportLevelNode.java index 14bc0db057..f66a7c06ec 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/ImportLevelNode.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/ImportLevelNode.java @@ -19,28 +19,28 @@ **/ package com.raytheon.viz.grid.inv; -import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; -import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.Set; import java.util.TreeSet; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.dataplugin.level.Level; -import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; import com.raytheon.uf.viz.derivparam.tree.AbstractAliasLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; import com.raytheon.viz.grid.data.ImportRequestableData; +import com.raytheon.viz.grid.util.CoverageUtils; import com.raytheon.viz.grid.util.RadarAdapter; /** @@ -71,7 +71,7 @@ public class ImportLevelNode extends AbstractAliasLevelNode { this.sourceNodeModelName = that.sourceNodeModelName; } - public ImportLevelNode(AbstractRequestableLevelNode sourceNode, + public ImportLevelNode(AbstractRequestableNode sourceNode, String sourceNodeModelName, DerivParamDesc desc, DerivParamMethod method, String modelName, Level level) { super(sourceNode, desc, method, modelName, level); @@ -79,94 +79,91 @@ public class ImportLevelNode extends AbstractAliasLevelNode { } @Override - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) + public Set getData( + Set availability, + Map> dependencyData) throws VizException { - // change out the time queries - DataTime[] selectedTimes = property.getSelectedEntryTime(); - int numberOfImages = property.getNumberOfImages(); - try { - Set newSelectedTimes = new HashSet( - (int) (selectedTimes.length * 2.5)); - for (DataTime time : selectedTimes) { - DataTime[] timesToAdd = boundingSourceTimes.get(time); + Set origs = dependencyData.get(sourceNode); + Set results = new HashSet( + origs.size()); + Map timeMap = new HashMap( + (int) (origs.size() * 1.25) + 1); + for (AbstractRequestableData orig : origs) { + timeMap.put(orig.getDataTime(), orig); + } - // sanity check - if (timesToAdd != null) { - for (DataTime t : timesToAdd) { - newSelectedTimes.add(t); - } + // need to build ImportRequestableData by bounding nodes + for (TimeAndSpace time : availability) { + DataTime[] timesToAdd = boundingSourceTimes.get(time.getTime()); + if (timesToAdd != null) { + AbstractRequestableData beforeData = timeMap.get(timesToAdd[0]); + AbstractRequestableData afterData = null; + + if (beforeData == null) { + continue; } - } - - property.setSelectedEntryTimes(newSelectedTimes - .toArray(new DataTime[0])); - property.setNumberOfImages(Math.max(newSelectedTimes.size(), - numberOfImages)); - - List origs = sourceNode.getData(property, - timeOut, cache); - List results = new ArrayList( - origs.size()); - Map timeMap = new HashMap( - (int) (origs.size() * 1.25) + 1); - for (AbstractRequestableData orig : origs) { - timeMap.put(orig.getDataTime(), orig); - } - - // need to build ImportRequestableData by bounding nodes - for (DataTime time : selectedTimes) { - DataTime[] timesToAdd = boundingSourceTimes.get(time); - if (timesToAdd != null) { - AbstractRequestableData beforeData = timeMap - .get(timesToAdd[0]); - AbstractRequestableData afterData = null; - - if (beforeData == null) { + if (timesToAdd.length == 2) { + afterData = timeMap.get(timesToAdd[1]); + if (afterData == null) { continue; } - if (timesToAdd.length == 2) { - afterData = timeMap.get(timesToAdd[1]); - if (afterData == null) { - continue; - } - } - - AbstractRequestableData result = new ImportRequestableData( - beforeData, afterData, time); - modifyRequest(result); - results.add(result); } + + AbstractRequestableData result = new ImportRequestableData( + beforeData, afterData, time.getTime()); + result.setSpace(time.getSpace()); + modifyRequest(result); + results.add(result); } - return results; - } finally { - // make sure to return the selectedEntryTimes to proper value - property.setSelectedEntryTimes(selectedTimes); - property.setNumberOfImages(numberOfImages); } + return results; } @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Map> getDataDependency( + Set times, AvailabilityContainer availabilityContainer) { + Map> result = new HashMap>(); + result.put(sourceNode, getSourceAvailability(times)); + return result; + } + + private Set getSourceAvailability(Set times) { + Set neededTimes = new HashSet(); + for (TimeAndSpace time : times) { + if (time.isTimeAgnostic()) { + for (DataTime[] dtarr : boundingSourceTimes.values()) { + for (DataTime dt : dtarr) { + neededTimes.add(new TimeAndSpace(dt)); + } + } + break; + } else { + for (DataTime dt : boundingSourceTimes.get(time.getTime())) { + neededTimes.add(new TimeAndSpace(dt)); + } + } + } + return neededTimes; + } + + @Override + public Set getAvailability( + Map> availability) throws VizException { boundingSourceTimes.clear(); // grab this source and discover all available times ala time agnostic, // then see what is available in the imported source, use time // interpolation to verify what data can be achieved - NavigableSet sourceDataTimes = new TreeSet( - sourceNode.timeQuery(originalRequest, latestOnly, cache, - latestOnlyCache)); - GridModel sourceModel = GribModelLookup.getInstance().getModelByName( + NavigableSet sourceDataTimes = new TreeSet(); + for (TimeAndSpace ast : availability.get(sourceNode)) { + sourceDataTimes.add(ast.getTime()); + } + DatasetInfo sourceInfo = DatasetInfoLookup.getInstance().getInfo( sourceNodeModelName); long sourceDt = 0; - if (sourceModel != null) { - sourceDt = sourceModel.getDt(); + if (sourceInfo != null) { + sourceDt = sourceInfo.getDt(); } if (sourceDt <= 24) { @@ -197,8 +194,14 @@ public class ImportLevelNode extends AbstractAliasLevelNode { boundingSourceTimes.put(time, new DataTime[] { time }); } } - - return boundingSourceTimes.keySet(); + Set result = new HashSet(); + for (DataTime time : boundingSourceTimes.keySet()) { + for (GridCoverage coverage : CoverageUtils.getInstance() + .getCoverages(modelName)) { + result.add(new TimeAndSpace(time, coverage)); + } + } + return result; } @Override diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarCubeLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarCubeLevelNode.java index 8022969938..0120c8f162 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarCubeLevelNode.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarCubeLevelNode.java @@ -19,26 +19,12 @@ **/ package com.raytheon.viz.grid.inv; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; import java.util.List; -import java.util.Map; -import java.util.Set; -import com.raytheon.uf.common.dataplugin.radar.RadarRecord; -import com.raytheon.uf.common.dataquery.requests.DbQueryRequest; -import com.raytheon.uf.common.dataquery.requests.RequestConstraint; -import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.requests.ThriftClient; -import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; import com.raytheon.uf.viz.derivparam.library.DerivParamField; import com.raytheon.uf.viz.derivparam.tree.AbstractCubeLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; import com.raytheon.uf.viz.derivparam.tree.CubeLevel; -import com.raytheon.viz.grid.data.RadarRequestableData; /** * @@ -65,78 +51,14 @@ import com.raytheon.viz.grid.data.RadarRequestableData; * @version 1.0 */ public class RadarCubeLevelNode extends AbstractCubeLevelNode { - private String paramAbbrev = null; public RadarCubeLevelNode(AbstractCubeLevelNode that) { super(that); } public RadarCubeLevelNode( - List> levels, + List> levels, String modelName, DerivParamField field) { super(levels, modelName); - paramAbbrev = field.getParam(); - } - - protected List wrapRawRecord(List objs) - throws VizException { - List gribResults = new ArrayList( - objs.size()); - for (Object obj : objs) { - AbstractRequestableData record = new RadarRequestableData( - (RadarRecord) obj, paramAbbrev); - gribResults.add(record); - } - return gribResults; - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.uf.viz.derivparam.tree.AbstractCubeLevelNode#mergedTimeQuery - * (java.util.List, boolean) - */ - @Override - protected Set mergedTimeQuery( - List> requests, boolean latestOnly) - throws VizException { - // Make sure we have data on at least two levels - Map single = new HashMap(); - Set results = new HashSet(); - for (Map mergeMap : requests) { - DbQueryRequest request = new DbQueryRequest(); - request.setConstraints(mergeMap); - String field = "dataTime"; - String levelField = "primaryElevationAngle"; - request.addFields(new String[] { field, levelField }); - - DbQueryResponse response = (DbQueryResponse) ThriftClient - .sendRequest(request); - if (response.getResults() == null) { - continue; - } - for (Map map : response.getResults()) { - DataTime time = (DataTime) map.get(field); - Double level = (Double) map.get(levelField); - if (results.contains(time)) { - continue; - } - if (!single.containsKey(time)) { - single.put(time, level); - } else if (!level.equals(single.get(time))) { - single.remove(time); - results.add(time); - } - } - } - return results; - } - - @Override - protected void filter( - Map baseRequestConstraints, - Map requestContraintsToFilter) { - // do nothing, no filtering necessary for radar } } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarRequestableLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarRequestableLevelNode.java index 371fc5cc46..a444771af0 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarRequestableLevelNode.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarRequestableLevelNode.java @@ -19,8 +19,6 @@ **/ package com.raytheon.viz.grid.inv; -import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -31,17 +29,16 @@ import com.raytheon.uf.common.dataplugin.radar.RadarRecord; 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.requests.TimeQueryRequest; import com.raytheon.uf.common.dataquery.responses.DbQueryResponse; import com.raytheon.uf.common.derivparam.tree.LevelNode; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.catalog.CatalogQuery; -import com.raytheon.uf.viz.core.catalog.LayerProperty; import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.requests.ThriftClient; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode; import com.raytheon.viz.grid.data.RadarRequestableData; +import com.raytheon.viz.grid.util.RadarAdapter; /** * @@ -59,7 +56,7 @@ import com.raytheon.viz.grid.data.RadarRequestableData; * @author bsteffen * @version 1.0 */ -public class RadarRequestableLevelNode extends AbstractRequestableLevelNode { +public class RadarRequestableLevelNode extends AbstractBaseDataNode { protected static final String TIME_FIELD = "dataTime"; @@ -105,42 +102,34 @@ public class RadarRequestableLevelNode extends AbstractRequestableLevelNode { this.rcMap = rcMap; } - @Override - public boolean isTimeAgnostic() { - return false; - } - - @Override public Map getRequestConstraintMap() { return rcMap; } @Override - public boolean hasRequestConstraints() { - return true; + public DbQueryRequest getAvailabilityRequest( + Map originalConstraints) { + return null; } @Override - public Set timeQueryInternal(TimeQueryRequest originalRequest, - boolean latestOnly, - Map> cache, - Map> latestOnlyCache) + public Set getAvailability( + Map originalConstraints, Object response) throws VizException { - Set resultsSet = RadarUpdater.getInstance().getTimes(this); + Set resultsSet = RadarUpdater.getInstance() + .getTimes(this); if (resultsSet != null) { return resultsSet; } - DataTime[] results = CatalogQuery.performTimeQuery(rcMap, latestOnly, - null); + DataTime[] results = CatalogQuery.performTimeQuery(rcMap, false, null); if (results != null) { - resultsSet = new HashSet(results.length); + resultsSet = new HashSet(results.length); for (int i = 0; i < results.length; i++) { - resultsSet.add(results[i]); - } - if (!latestOnly) { - RadarUpdater.getInstance().setTimes(this, resultsSet); + resultsSet.add(new TimeAndSpace(results[i], RadarAdapter + .getInstance().getCoverage())); } + RadarUpdater.getInstance().setTimes(this, resultsSet); return resultsSet; } else { return null; @@ -148,69 +137,31 @@ public class RadarRequestableLevelNode extends AbstractRequestableLevelNode { } @Override - protected TimeQueryRequest getTimeQueryInternal( - TimeQueryRequest originalRequest, boolean latestOnly, - Map> cache) - throws VizException { - // TODO Auto-generated method stub - return null; - } - - @Override - public List getDataInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { - DbQueryRequest dbRequest = getDataQueryInternal(property, timeOut, - cache); - DbQueryResponse response = (DbQueryResponse) ThriftClient - .sendRequest(dbRequest); - return processDataQueryResults(response); - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * getDataQueryInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int, - * java.util.Map) - */ - @Override - protected DbQueryRequest getDataQueryInternal( - LayerProperty property, - int timeOut, - Map> cache) - throws VizException { + public DbQueryRequest getDataRequest( + Map orignalConstraints, + Set availability) { Map newQuery = new HashMap( rcMap); DbQueryRequest dbRequest = new DbQueryRequest(); - DataTime[] times = property.getSelectedEntryTime(); - if (times != null && times.length > 0) { - RequestConstraint dtRC = new RequestConstraint(); - dtRC.setConstraintType(ConstraintType.IN); - for (DataTime t : times) { - dtRC.addToConstraintValueList(t.toString()); - } - newQuery.put("dataTime", dtRC); + RequestConstraint dtRC = new RequestConstraint(); + dtRC.setConstraintType(ConstraintType.IN); + for (TimeAndSpace ast : availability) { + dtRC.addToConstraintValueList(ast.getTime().toString()); } + newQuery.put("dataTime", dtRC); newQuery.put("pluginName", new RequestConstraint("radar")); dbRequest.setConstraints(newQuery); return dbRequest; } - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode# - * processQueryResults - * (com.raytheon.uf.common.dataquery.responses.DbQueryResponse) - */ @Override - protected List processDataQueryResults( - DbQueryResponse response) throws VizException { - List> rows = response.getResults(); - List rval = new ArrayList( + public Set getData( + Map orignalConstraints, + Set availability, Object response) + throws VizException { + List> rows = ((DbQueryResponse) response) + .getResults(); + Set rval = new HashSet( rows.size()); // switch to GribRequestableData and build a grib record from the radar // record... won't work because of the get data call, can't be a @@ -222,11 +173,6 @@ public class RadarRequestableLevelNode extends AbstractRequestableLevelNode { return rval; } - @Override - public List getDependencies() { - return Collections.emptyList(); - } - public String getParamAbbrev() { return paramAbbrev; } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarUpdater.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarUpdater.java index 2544f574d4..81c04a55b4 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarUpdater.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/RadarUpdater.java @@ -9,23 +9,42 @@ import java.util.Set; import com.raytheon.uf.common.comm.CommunicationException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.dataplugin.radar.RadarStation; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.alerts.AlertMessage; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; import com.raytheon.viz.alerts.IAlertObserver; import com.raytheon.viz.alerts.observers.ProductAlertObserver; import com.raytheon.viz.grid.util.RadarAdapter; import com.raytheon.viz.grid.util.RadarProductCodeMapping; +/** + * + * Listens for updates to radatr products and transforms them into grid updates + * so that radar data being used in grid derived parameters will update. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 20, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ public class RadarUpdater implements IAlertObserver { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(RadarUpdater.class); @@ -92,14 +111,14 @@ public class RadarUpdater implements IAlertObserver { private class CacheEntry { - public CacheEntry(Set times) { + public CacheEntry(Set times) { this.insertTime = System.currentTimeMillis(); this.times = times; } public long insertTime; - public Set times; + public Set times; } @@ -114,7 +133,9 @@ public class RadarUpdater implements IAlertObserver { } }; - private CacheEntry globalTimes; + private Set globalTimes; + + private long globalInsertTime; private RadarUpdater() { ProductAlertObserver.addObserver("radar", this); @@ -166,15 +187,14 @@ public class RadarUpdater implements IAlertObserver { statusHandler.handle(Priority.PROBLEM, e1.getLocalizedMessage(), e1); } - GribRecord fakeRec = new GribRecord(); - fakeRec.setPluginName("grib"); + GridRecord fakeRec = new GridRecord(); + fakeRec.setPluginName(GridInventory.PLUGIN_NAME); + fakeRec.setDataTime(time); - GribModel modelInfo = new GribModel(); - modelInfo.setModelName(RadarAdapter.RADAR_SOURCE); - modelInfo.setParameterAbbreviation(paramAbbrev); - modelInfo.setLevel(level); - modelInfo.setTypeEnsemble(null); - fakeRec.setModelInfo(modelInfo); + fakeRec.setDatasetId(RadarAdapter.RADAR_SOURCE); + Parameter param = new Parameter(paramAbbrev); + fakeRec.setParameter(param); + fakeRec.setLevel(level); try { fakeRec.constructDataURI(); datauris.add(fakeRec.getDataURI()); @@ -201,11 +221,12 @@ public class RadarUpdater implements IAlertObserver { return new CacheKey(productCode, elevationAngle); } - public void setTimes(RadarRequestableLevelNode rNode, Set times) { + public void setTimes(RadarRequestableLevelNode rNode, + Set times) { cache.put(getCacheKey(rNode), new CacheEntry(times)); } - public Set getTimes(RadarRequestableLevelNode rNode) { + public Set getTimes(RadarRequestableLevelNode rNode) { CacheKey cacheKey = getCacheKey(rNode); CacheEntry entry = cache.get(cacheKey); if (entry == null) { @@ -219,18 +240,19 @@ public class RadarUpdater implements IAlertObserver { } public void setGlobalTimes(Set times) { - globalTimes = new CacheEntry(times); + globalTimes = times; + globalInsertTime = System.currentTimeMillis(); } public Set getGlobalTimes() { if (globalTimes == null) { return null; } - if (globalTimes.insertTime + CACHE_TIME < System.currentTimeMillis()) { + if (globalInsertTime + CACHE_TIME < System.currentTimeMillis()) { globalTimes = null; return null; } - return globalTimes.times; + return globalTimes; } public void clearCache() { diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/StaticGridDataLevelNode.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/StaticGridDataLevelNode.java new file mode 100644 index 0000000000..ea902e0428 --- /dev/null +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/inv/StaticGridDataLevelNode.java @@ -0,0 +1,171 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.grid.inv; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import com.raytheon.uf.common.dataplugin.grid.util.StaticGridDataType; +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.gridcoverage.GridCoverage; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; +import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode; +import com.raytheon.viz.grid.data.StaticGridRequestableData; +import com.raytheon.viz.grid.data.TiltRequestableData; +import com.raytheon.viz.grid.util.CoverageUtils; + +/** + * A LevelNode for static grid data that is either constant or can be calculated + * based off the coverage. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Apr 13, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class StaticGridDataLevelNode extends AbstractBaseDataNode { + + private String dataType; + + private String source; + + public StaticGridDataLevelNode(String source, String dataType) { + this.source = source; + this.dataType = dataType; + } + + public StaticGridDataLevelNode(String source, String dataType, Level level) { + this(source, dataType); + setLevel(level); + } + + @Override + public DbQueryRequest getAvailabilityRequest( + Map originalConstraints) { + return null; + } + + @Override + public Set getAvailability( + Map originalConstraints, Object response) + throws VizException { + Set result = new HashSet(); + for (GridCoverage coverage : CoverageUtils.getInstance().getCoverages( + source)) { + result.add(new TimeAndSpace(coverage)); + } + return result; + } + + @Override + public DbQueryRequest getDataRequest( + Map orignalConstraints, + Set availability) { + return null; + } + + @Override + public Set getData( + Map orignalConstraints, + Set availability, Object response) + throws VizException { + Set results = new HashSet(); + for (TimeAndSpace ast : availability) { + if (ast.getSpace() instanceof GridCoverage) { + GridCoverage coverage = (GridCoverage) ast.getSpace(); + AbstractRequestableData data = createRequestableData(coverage); + data.setDataTime(ast.getTime()); + results.add(data); + } else { + for (GridCoverage coverage : CoverageUtils.getInstance() + .getCoverages(source)) { + AbstractRequestableData data = createRequestableData(coverage); + data.setDataTime(ast.getTime()); + results.add(data); + } + } + } + return results; + } + + private AbstractRequestableData createRequestableData(GridCoverage coverage) { + if (StaticGridDataType.getStringValues().contains(dataType)) { + StaticGridDataType staticGridDataType = StaticGridDataType + .valueOf(dataType); + return new StaticGridRequestableData(staticGridDataType, source, + coverage); + } else if ("TILT".equals(dataType)) { + return new TiltRequestableData(source, level, coverage); + } + return null; + } + + @Override + public boolean isConstant() { + return true; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + + ((dataType == null) ? 0 : dataType.hashCode()); + result = prime * result + ((source == null) ? 0 : source.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + StaticGridDataLevelNode other = (StaticGridDataLevelNode) obj; + if (dataType == null) { + if (other.dataType != null) + return false; + } else if (!dataType.equals(other.dataType)) + return false; + if (source == null) { + if (other.source != null) + return false; + } else if (!source.equals(other.source)) + return false; + return true; + } + +} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/record/RequestableDataRecord.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/record/RequestableDataRecord.java index 497bc7e3f0..e064b79af2 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/record/RequestableDataRecord.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/record/RequestableDataRecord.java @@ -23,25 +23,23 @@ import java.util.ArrayList; import java.util.Collection; import java.util.List; -import javax.measure.unit.Unit; -import javax.measure.unit.UnitFormat; - import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; -import com.raytheon.viz.grid.data.GribRequestableData; +import com.raytheon.viz.grid.data.GridRequestableData; import com.raytheon.viz.grid.data.TiltRequestableData.TiltCenterPoint; -import com.raytheon.viz.grid.util.CoverageUtils; import com.raytheon.viz.grid.util.TiltRequest; /** - * The RequestableDataRecord Class + * A PDO that extends GridRecord and wraps a AbstractRequestableData to allow + * derived parameters to be used anywhere GridRecords can be used. * *
  *
@@ -57,7 +55,7 @@ import com.raytheon.viz.grid.util.TiltRequest;
  * @version 1.0
  */
 
-public class RequestableDataRecord extends GribRecord {
+public class RequestableDataRecord extends GridRecord {
 
     private static final long serialVersionUID = 1L;
 
@@ -66,30 +64,22 @@ public class RequestableDataRecord extends GribRecord {
     public RequestableDataRecord(AbstractRequestableData requester)
             throws VizException {
         this.requester = requester;
-        GridCoverage coverage = CoverageUtils.getInstance().getCoverage(
-                requester.getSource());
-        if (coverage == null && requester instanceof GribRequestableData) {
-            coverage = ((GribRequestableData) requester).getGribSource()
-                    .getModelInfo().getLocation();
-            CoverageUtils.getInstance().setCoverage(requester.getSource(),
-                    coverage);
+        GridCoverage coverage = null;
+        if (requester.getSpace() instanceof GridCoverage) {
+            coverage = (GridCoverage) requester.getSpace();
+        if (requester instanceof GridRequestableData) {
+            setSecondaryId(((GridRequestableData) requester).getGridSource().getSecondaryId());
         }
-        GribModel modelInfo = new GribModel();
-        if (requester instanceof GribRequestableData) {
-            setGridVersion(((GribRequestableData) requester).getGribSource().getGridVersion());
         }
-        modelInfo.setModelName(requester.getSource());
-        modelInfo.setLocation(coverage);
-        modelInfo.setLevel(requester.getLevel());
-        modelInfo.setParameterAbbreviation(requester.getParameter());
-        modelInfo.setParameterName(requester.getParameterName());
-        if (requester.getUnit() != Unit.ONE) {
-            modelInfo.setParameterUnit(UnitFormat.getUCUMInstance().format(
-                    requester.getUnit()));
-        }
-        setPluginName("grib");
+        setDatasetId(requester.getSource());
+        setLocation(coverage);
+        setLevel(requester.getLevel());
+        Parameter parameter = new Parameter(requester.getParameter(),
+                requester.getParameterName(), requester.getUnit());
+
+        setParameter(parameter);
+        setPluginName(GridConstants.GRID);
         setDataTime(requester.getDataTime());
-        setModelInfo(modelInfo);
         try {
             constructDataURI();
         } catch (PluginException e) {
@@ -97,9 +87,9 @@ public class RequestableDataRecord extends GribRecord {
         }
     }
 
-    public RequestableDataRecord(GribRequestableData requester)
+    public RequestableDataRecord(GridRequestableData requester)
             throws VizException {
-        super(requester.getGribSource());
+        super(requester.getGridSource());
         this.requester = requester;
     }
 
@@ -125,8 +115,8 @@ public class RequestableDataRecord extends GribRecord {
         } else if (obj instanceof IDataRecord) {
             return new IDataRecord[] { (IDataRecord) obj };
         } else if (obj instanceof Number) {
-            Integer nx = this.getModelInfo().getLocation().getNx();
-            Integer ny = this.getModelInfo().getLocation().getNy();
+            Integer nx = 0;
+            Integer ny = 0;
             if (request != null) {
                 switch (request.getType()) {
                 case POINT:
@@ -146,15 +136,18 @@ public class RequestableDataRecord extends GribRecord {
                     ny = request.getIndices().length;
                     nx = 1;
                     break;
+                default:
+                    nx = this.getLocation().getNx();
+                    ny = this.getLocation().getNy();
                 }
             }
             float[] data = new float[nx * ny];
             for (int i = 0; i < nx * ny; i++) {
                 data[i] = ((Number) obj).floatValue();
             }
-            FloatDataRecord rec = new FloatDataRecord(this.getModelInfo()
-                    .getParameterName(), this.getPluginName(), data, 2,
-                    new long[] { nx, ny });
+            FloatDataRecord rec = new FloatDataRecord(this.getParameter()
+                    .getName(), this.getPluginName(), data, 2, new long[] { nx,
+                    ny });
             return new IDataRecord[] { rec };
         }
         return null;
@@ -163,15 +156,15 @@ public class RequestableDataRecord extends GribRecord {
     /**
      * @return
      */
-    public Collection getGribRequests() {
-        List results = new ArrayList();
+    public Collection getGribRequests() {
+        List results = new ArrayList();
         List list = new ArrayList();
         list.add(requester);
         AbstractRequestableData current = null;
         for (int i = 0; i < list.size(); i++) {
             current = list.get(i);
-            if (current.getClass().equals(GribRequestableData.class)) {
-                results.add((GribRequestableData) current);
+            if (current.getClass().equals(GridRequestableData.class)) {
+                results.add((GridRequestableData) current);
             } else {
                 for (AbstractRequestableData data : current.getDependencies()) {
                     if (data != null) {
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/AbstractMapVectorResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/AbstractMapVectorResource.java
deleted file mode 100644
index 796c51a53d..0000000000
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/AbstractMapVectorResource.java
+++ /dev/null
@@ -1,1098 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.viz.grid.rsc;
-
-import java.io.FileNotFoundException;
-import java.nio.FloatBuffer;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.measure.converter.UnitConverter;
-import javax.measure.unit.Unit;
-import javax.media.jai.Interpolation;
-
-import org.apache.commons.lang.Validate;
-import org.eclipse.swt.graphics.RGB;
-import org.geotools.coverage.grid.GeneralGridGeometry;
-import org.geotools.coverage.grid.GridGeometry2D;
-import org.geotools.coverage.grid.InvalidGridGeometryException;
-import org.geotools.referencing.CRS;
-import org.geotools.referencing.crs.DefaultGeographicCRS;
-import org.opengis.referencing.FactoryException;
-import org.opengis.referencing.crs.CoordinateReferenceSystem;
-import org.opengis.referencing.datum.PixelInCell;
-import org.opengis.referencing.operation.MathTransform;
-import org.opengis.referencing.operation.TransformException;
-
-import com.raytheon.edex.util.Util;
-import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.CombinedGribRecord;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LambertConformalGridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.MercatorGridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.PolarStereoGridCoverage;
-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.MapUtil;
-import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation;
-import com.raytheon.uf.common.geospatial.interpolation.GridReprojection;
-import com.raytheon.uf.common.geospatial.interpolation.data.FloatArrayWrapper;
-import com.raytheon.uf.common.status.IUFStatusHandler;
-import com.raytheon.uf.common.status.UFStatus;
-import com.raytheon.uf.common.status.UFStatus.Priority;
-import com.raytheon.uf.common.time.DataTime;
-import com.raytheon.uf.viz.core.IGraphicsTarget;
-import com.raytheon.uf.viz.core.IGraphicsTarget.LineStyle;
-import com.raytheon.uf.viz.core.datastructure.DataCubeContainer;
-import com.raytheon.uf.viz.core.drawables.PaintProperties;
-import com.raytheon.uf.viz.core.drawables.PaintStatus;
-import com.raytheon.uf.viz.core.exception.VizException;
-import com.raytheon.uf.viz.core.map.IMapDescriptor;
-import com.raytheon.uf.viz.core.map.MapDescriptor;
-import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData;
-import com.raytheon.uf.viz.core.rsc.AbstractVizResource;
-import com.raytheon.uf.viz.core.rsc.IResourceDataChanged;
-import com.raytheon.uf.viz.core.rsc.LoadProperties;
-import com.raytheon.uf.viz.core.rsc.capabilities.AbstractCapability;
-import com.raytheon.uf.viz.core.rsc.capabilities.ColorableCapability;
-import com.raytheon.uf.viz.core.rsc.capabilities.DensityCapability;
-import com.raytheon.uf.viz.core.rsc.capabilities.MagnificationCapability;
-import com.raytheon.uf.viz.core.rsc.capabilities.OutlineCapability;
-import com.raytheon.uf.viz.core.style.StyleRule;
-import com.raytheon.viz.core.contours.ContourRenderable;
-import com.raytheon.viz.core.contours.rsc.displays.AbstractGriddedDisplay;
-import com.raytheon.viz.core.contours.rsc.displays.GriddedVectorDisplay;
-import com.raytheon.viz.core.rsc.ICombinedResourceData;
-import com.raytheon.viz.core.rsc.ICombinedResourceData.CombineOperation;
-import com.raytheon.viz.core.style.arrow.ArrowPreferences;
-import com.raytheon.viz.core.style.contour.ContourPreferences;
-import com.raytheon.viz.pointdata.PointWindDisplay.DisplayType;
-
-/**
- * AbstractMapContourResource
- * 
- * An abstract class that provides contouring support for map-based resources
- * 
- * 
- * 
- *    SOFTWARE HISTORY
- *   
- *    Date         Ticket#     Engineer    Description
- *    ------------ ----------  ----------- --------------------------
- *    Oct 22, 2007             chammack    Initial Creation.
- *    02/16/09                 njensen     Refactored to new rsc architecture
- *    06/25/10     #1691       bkowal      The data will now be retrieved for
- *                                         every frame initially instead of
- *                                         only retrieving data frame-by-frame
- *                                         as the user switches frames.
- * 
- * 
- * - * @author chammack - * @version 1 - */ -public abstract class AbstractMapVectorResource extends - AbstractVizResource { - protected static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(AbstractMapVectorResource.class); - - protected DisplayType displayType; - - private DataTime displayedDataTime; - - protected IGraphicsTarget lastTarget; - - protected boolean retrievedAllData = false; - - protected Map dataObjectMap; - - protected String uuid; - - protected StyleRule styleRule; - - protected CombineOperation combineOperation; - - protected VectorContourRenderableManagerJob vcrManagerJob = null; - - protected GriddedDisplayManagerJob gdManagerJob = null; - - public class VectorContourRenderable extends ContourRenderable { - - private IDataRecord[] cache; - - private boolean dataRequested = false; - - private Exception exception = null; - - private final PluginDataObject pdo; - - private final StyleRule styleRule; - - public VectorContourRenderable(IMapDescriptor descriptor, - PluginDataObject pdo, StyleRule styleRule) { - super(descriptor); - this.pdo = pdo; - this.styleRule = styleRule; - } - - @Override - public IDataRecord[] getData() throws VizException { - try { - if (exception != null) { - throw exception; - } - if (cache == null && !dataRequested) { - dataRequested = true; - if (pdo instanceof CombinedGribRecord) { - cache = getCombinedDataRecord( - ((CombinedGribRecord) pdo), styleRule); - } else { - cache = getDataRecord(pdo, styleRule); - } - issueRefresh(); - } - - return cache; - - } catch (Throwable e) { - throw new VizException("Error retrieving data for contouring", - e); - } - } - - @Override - public GeneralGridGeometry getGridGeometry() throws VizException { - return AbstractMapVectorResource.this.getGridGeometry(pdo); - } - - @Override - public ContourPreferences getPreferences() throws VizException { - if (styleRule == null) { - return null; - } - - return (ContourPreferences) styleRule.getPreferences(); - } - - public boolean hasData() { - return (cache != null); - } - } - - public class GriddedDisplayRequest { - private FloatBuffer mag; - - private FloatBuffer dir; - - private final PluginDataObject pdo; - - private final StyleRule styleRule; - - public GriddedDisplayRequest(PluginDataObject pdo, StyleRule styleRule) { - this.pdo = pdo; - this.styleRule = styleRule; - } - - public AbstractGriddedDisplay getData() throws VizException { - if (mag == null || dir == null) { - try { - IDataRecord[] recs; - - if (pdo instanceof CombinedGribRecord) { - recs = getCombinedDataRecord((CombinedGribRecord) pdo, - styleRule); - } else { - recs = getDataRecord(pdo, getStyleRule()); - } - mag = FloatBuffer.wrap(((FloatDataRecord) recs[0]) - .getFloatData()); - dir = FloatBuffer.wrap(((FloatDataRecord) recs[1]) - .getFloatData()); - issueRefresh(); - } catch (Throwable e) { - throw new VizException("Error retrieving data for vector", - e); - } - } - - AbstractGriddedDisplay display = null; - if (AbstractMapVectorResource.this.displayType == DisplayType.ARROW - || AbstractMapVectorResource.this.displayType == DisplayType.BARB - || AbstractMapVectorResource.this.displayType == DisplayType.DUALARROW) { - com.raytheon.uf.viz.core.rsc.DisplayType displayType = null; - switch (AbstractMapVectorResource.this.displayType) { - case ARROW: - displayType = com.raytheon.uf.viz.core.rsc.DisplayType.ARROW; - break; - case BARB: - displayType = com.raytheon.uf.viz.core.rsc.DisplayType.BARB; - break; - case DUALARROW: - displayType = com.raytheon.uf.viz.core.rsc.DisplayType.DUALARROW; - break; - } - GriddedVectorDisplay arrowDisplay = new GriddedVectorDisplay( - mag, dir, descriptor, getGridGeometry(pdo), 64, - displayType); - - display = arrowDisplay; - if (styleRule != null - && styleRule.getPreferences() instanceof ArrowPreferences) { - arrowDisplay.setScale(((ArrowPreferences) styleRule - .getPreferences()).getScale()); - } - arrowDisplay - .setLineStyle(getCapability(OutlineCapability.class) - .getLineStyle()); - arrowDisplay - .setLineWidth(getCapability(OutlineCapability.class) - .getOutlineWidth()); - } else { - GriddedVectorDisplay vectorDisplay = new GriddedVectorDisplay( - mag, dir, descriptor, - AbstractMapVectorResource.this.getGridGeometry(pdo), - 64, com.raytheon.uf.viz.core.rsc.DisplayType.STREAMLINE); - - display = vectorDisplay; - if (styleRule != null - && styleRule.getPreferences() instanceof ArrowPreferences) { - vectorDisplay.setScale(((ArrowPreferences) styleRule - .getPreferences()).getScale()); - } - vectorDisplay.setLineWidth(getCapability( - OutlineCapability.class).getOutlineWidth()); - } - if (styleRule != null - && styleRule.getPreferences() instanceof ArrowPreferences) { - if (display instanceof GriddedVectorDisplay) { - ((GriddedVectorDisplay) display) - .setScale(((ArrowPreferences) styleRule - .getPreferences()).getScale()); - } else if (display instanceof GriddedVectorDisplay) { - ((GriddedVectorDisplay) display) - .setScale(((ArrowPreferences) styleRule - .getPreferences()).getScale()); - } - } - display.setColor(getCapability(ColorableCapability.class) - .getColor()); - display.setDensity(getCapability(DensityCapability.class) - .getDensity()); - display.setMagnification(getCapability( - MagnificationCapability.class).getMagnification()); - return display; - } - - public boolean hasData() { - return (mag != null && dir != null); - } - } - - /** - * Constructor - */ - public AbstractMapVectorResource(AbstractRequestableResourceData data, - LoadProperties props) { - super(data, props); - - try { - ICombinedResourceData combinedResourceData = (ICombinedResourceData) getResourceData(); - this.combineOperation = combinedResourceData.getCombineOperation(); - } catch (ClassCastException e) { - // do nothing - } - - this.vcrManagerJob = new VectorContourRenderableManagerJob(); - this.gdManagerJob = new GriddedDisplayManagerJob(); - - dataObjectMap = new HashMap(); - uuid = UUID.randomUUID().toString(); - resourceData.addChangeListener(new IResourceDataChanged() { - @Override - public void resourceChanged(ChangeType type, Object object) { - if (type == ChangeType.CAPABILITY) { - if (!hasCapability(((AbstractCapability) object).getClass()) - || getCapability(((AbstractCapability) object) - .getClass()) != object) { - return; - } - if (object instanceof MagnificationCapability) { - Double mag = ((MagnificationCapability) object) - .getMagnification(); - - for (ContourRenderable display : vcrManagerJob - .getRequestMapAsCollection()) { - display.setMagnification(mag); - } - for (ContourRenderable display : vcrManagerJob - .getResponseMapAsCollection()) { - display.setMagnification(mag); - } - for (AbstractGriddedDisplay display : gdManagerJob - .getResponseMapAsCollection()) { - display.setMagnification(mag); - } - } else if (object instanceof DensityCapability) { - Double density = ((DensityCapability) object) - .getDensity(); - - for (ContourRenderable display : vcrManagerJob - .getRequestMapAsCollection()) { - display.setDensity(density); - } - for (ContourRenderable display : vcrManagerJob - .getResponseMapAsCollection()) { - display.setDensity(density); - } - for (AbstractGriddedDisplay display : gdManagerJob - .getResponseMapAsCollection()) { - display.setDensity(density); - } - } else if (object instanceof ColorableCapability) { - RGB color = ((ColorableCapability) object).getColor(); - - for (ContourRenderable display : vcrManagerJob - .getRequestMapAsCollection()) { - display.setColor(color); - } - for (ContourRenderable display : vcrManagerJob - .getResponseMapAsCollection()) { - display.setColor(color); - } - for (AbstractGriddedDisplay display : gdManagerJob - .getResponseMapAsCollection()) { - display.setColor(color); - } - } else if (object instanceof OutlineCapability) { - int lineWidth = ((OutlineCapability) object) - .getOutlineWidth(); - LineStyle lineStyle = ((OutlineCapability) object) - .getLineStyle(); - for (ContourRenderable display : vcrManagerJob - .getRequestMapAsCollection()) { - display.setOutlineWidth(lineWidth); - display.setLineStyle(lineStyle); - } - for (ContourRenderable display : vcrManagerJob - .getResponseMapAsCollection()) { - display.setOutlineWidth(lineWidth); - display.setLineStyle(lineStyle); - } - for (AbstractGriddedDisplay display : gdManagerJob - .getResponseMapAsCollection()) { - if (display instanceof GriddedVectorDisplay) { - ((GriddedVectorDisplay) display) - .setLineWidth(lineWidth); - ((GriddedVectorDisplay) display) - .setLineStyle(lineStyle); - } - } - - } - } - - } - - }); - } - - protected abstract StyleRule getStyleRule(PluginDataObject obj) - throws VizException; - - /** - * Validate the record - * - * @param obj - * the record to validate - * @return - */ - protected abstract boolean validateRecord(PluginDataObject obj); - - /** - * Get the grid geometry - * - * @param obj - * @return - */ - protected abstract GeneralGridGeometry getGridGeometry(PluginDataObject obj); - - /** - * Return the units of the data - * - * @param obj - * the object - * @return the unit - */ - protected abstract Unit getDataUnits(PluginDataObject obj); - - /** - * Return the imagery resource - */ - public abstract AbstractVizResource getImageryResource() - throws VizException; - - /** - * Retrieve the data record - * - * @param obj - * @param styleRule - * @return - * @throws FileNotFoundException - * @throws StorageException - * @throws VizException - */ - protected synchronized IDataRecord[] getCombinedDataRecord( - CombinedGribRecord pdo, StyleRule styleRule1) - throws FileNotFoundException, StorageException, VizException { - if (combineOperation == null - || CombineOperation.NONE.equals(combineOperation)) { - return getDataRecord(pdo.getPrimaryGribRecord(), styleRule1); - } - IDataRecord rec1 = null; - IDataRecord rec2 = null; - IDataRecord[] records1 = DataCubeContainer.getDataRecord(pdo - .getPrimaryGribRecord()); - IDataRecord[] records2 = DataCubeContainer.getDataRecord(pdo - .getSecondaryGribRecord()); - - if (records1 != null && records1.length > 0) { - rec1 = records1[0].clone(); - } - if (records2 != null && records2.length > 0) { - rec2 = records2[0].clone(); - } - if (rec1 != null && rec1.getSizes().length != 2) { - throw new VizException("Two dimensional space required to contour"); - } - if (rec2 != null && rec2.getSizes().length != 2) { - throw new VizException("Two dimensional space required to contour"); - } - for (int i = 0; i < records1.length; i++) { - records1[i] = getCombinedData((FloatDataRecord) records1[i], - (FloatDataRecord) records2[i], (CombinedGribRecord) pdo); - } - rec1 = records1[0]; - - if (styleRule != null) { - convertDataRecord(pdo, styleRule, rec1); - } - - if ((this.displayType == DisplayType.STREAMLINE - || this.displayType == DisplayType.ARROW - || this.displayType == DisplayType.BARB || this.displayType == DisplayType.DUALARROW) - && pdo instanceof GribRecord) { - if (records1.length == 4) { - if (this.displayType == DisplayType.STREAMLINE) { - return new IDataRecord[] { records1[2], records1[3] }; - } else { - float[] floatData = ((FloatDataRecord) records1[1]) - .getFloatData(); - // Need to ensure diff'd directions still in the 0-360 range - for (int i = 0; i < floatData.length; i++) { - if (floatData[i] < 0) { - floatData[i] = floatData[i] + 360; - } - } - return new IDataRecord[] { records1[0], records1[1] }; - } - - } - } - - return new IDataRecord[] { rec1 }; - } - - /** - * Retrieve the data record - * - * @param obj - * @param styleRule - * @return - * @throws FileNotFoundException - * @throws StorageException - * @throws VizException - */ - protected IDataRecord[] getDataRecord(PluginDataObject pdo, - StyleRule styleRule) throws FileNotFoundException, - StorageException, VizException { - - IDataRecord rec = null; - IDataRecord[] records = null; - if (pdo instanceof GribRecord) { - records = GridResourceData.getDataRecordsForTilt((GribRecord) pdo, - descriptor); - } - if (records == null) { - records = DataCubeContainer.getDataRecord(pdo); - } - if (records != null && records.length > 0) { - rec = records[0].clone(); - } - if (rec != null && rec.getSizes().length != 2) { - throw new VizException("Two dimensional space required to contour"); - } - if (styleRule != null) { - convertDataRecord(pdo, styleRule, rec); - } - - if ((this.displayType == DisplayType.STREAMLINE - || this.displayType == DisplayType.ARROW - || this.displayType == DisplayType.BARB || this.displayType == DisplayType.DUALARROW) - && pdo instanceof GribRecord) { - if (records.length == 4) { - if (this.displayType == DisplayType.STREAMLINE) { - return new IDataRecord[] { records[2], records[3] }; - } else { - return new IDataRecord[] { rec, records[1] }; - } - - } - } - - return new IDataRecord[] { rec }; - } - - private void convertDataRecord(PluginDataObject pdo, StyleRule styleRule, - IDataRecord rec) { - Unit desiredUnit = styleRule.getPreferences().getDisplayUnits(); - if (desiredUnit != null) { - Unit dataUnit = getDataUnits(pdo); - if (dataUnit != null && !dataUnit.equals(Unit.ONE)) { - if (!dataUnit.isCompatible(desiredUnit)) { - String message = "Data unit: " + dataUnit - + " cannot be converted to desired unit: " - + desiredUnit - + " Data displayed will be displayed with unit: " - + dataUnit; - statusHandler.handle(Priority.VERBOSE, message); - } else { - UnitConverter converter = dataUnit - .getConverterTo(desiredUnit); - if (converter != null) { - - if (rec instanceof FloatDataRecord) { - float[] fd = ((FloatDataRecord) rec).getFloatData(); - for (int i = 0; i < fd.length; i++) { - if (fd[i] != Util.GRID_FILL_VALUE) { - fd[i] = (float) converter.convert(fd[i]); - } - } - } - } - } - } - } - } - - /** - * @param pdo - * @param rec - * @return - * @throws VizException - * @throws StorageException - * @throws FileNotFoundException - */ - private synchronized IDataRecord getCombinedData( - FloatDataRecord sourceDataRecord, FloatDataRecord targetDataRecord, - CombinedGribRecord pdo) throws FileNotFoundException, - StorageException, VizException { - GribRecord pdo1 = pdo.getPrimaryGribRecord(); - GribRecord pdo2 = pdo.getSecondaryGribRecord(); - - GribRecord record1 = (GribRecord) pdo1; - GribRecord record2 = (GribRecord) pdo2; - GridCoverage sourceCoverage = record1.getModelInfo().getLocation(); - GridCoverage targetCoverage = record2.getModelInfo().getLocation(); - Unit primaryDataUnits = getDataUnits(pdo1); - Unit secondaryDataUnits = getDataUnits(pdo2); - - if (sourceCoverage.equals(targetCoverage)) { - return diffData(sourceDataRecord, targetDataRecord, - primaryDataUnits, secondaryDataUnits); - } - try { - GridGeometry2D newTarget = targetCoverage.getGridGeometry(); - double sourcePixeWidth = getPixelWidth( - sourceCoverage.getGridGeometry(), descriptor); - double targetPixeWidth = getPixelWidth( - targetCoverage.getGridGeometry(), descriptor); - if (sourcePixeWidth >= targetPixeWidth) { - double sizeMultiplier = sourcePixeWidth / targetPixeWidth; - sizeMultiplier = sizeMultiplier > 4 ? 2 : 4; - long[] newSizes = { - (long) (targetDataRecord.getSizes()[0] * sizeMultiplier), - (long) (targetDataRecord.getSizes()[1] * sizeMultiplier) }; - newTarget = MapUtil.createFineIntersectingGeometry( - sourceCoverage.getGridGeometry().getEnvelope(), - targetCoverage.getGridGeometry().getEnvelope(), - newSizes); - } else { - double sizeMultiplier = targetPixeWidth / sourcePixeWidth; - sizeMultiplier = sizeMultiplier > 4 ? 2 : 4; - long[] newSizes = { - (long) (sourceDataRecord.getSizes()[0] * sizeMultiplier), - (long) (sourceDataRecord.getSizes()[1] * sizeMultiplier) }; - newTarget = MapUtil.createFineIntersectingGeometry( - targetCoverage.getGridGeometry().getEnvelope(), - sourceCoverage.getGridGeometry().getEnvelope(), - newSizes); - } - - targetDataRecord = remapGrid(targetDataRecord, newTarget, - targetCoverage.getGridGeometry()); - sourceDataRecord = remapGrid(sourceDataRecord, newTarget, - sourceCoverage.getGridGeometry()); - GridCoverage coverage = null; - if (sourceCoverage instanceof LambertConformalGridCoverage) { - coverage = new LambertConformalGridCoverage( - (LambertConformalGridCoverage) sourceCoverage); - } else if (sourceCoverage instanceof LatLonGridCoverage) { - coverage = new LatLonGridCoverage( - (LatLonGridCoverage) sourceCoverage); - } else if (sourceCoverage instanceof MercatorGridCoverage) { - coverage = new MercatorGridCoverage( - (MercatorGridCoverage) sourceCoverage); - } else if (sourceCoverage instanceof PolarStereoGridCoverage) { - coverage = new PolarStereoGridCoverage( - (PolarStereoGridCoverage) sourceCoverage); - } - coverage.setGridGeometry(newTarget); - GribModel modelInfo = new GribModel(pdo.getModelInfo()); - modelInfo.setLocation(coverage); - pdo.setModelInfo(modelInfo); - - diffData(sourceDataRecord, targetDataRecord, primaryDataUnits, - secondaryDataUnits); - } catch (Exception e) { - throw new VizException(e); - } - - return sourceDataRecord; - } - - private FloatDataRecord remapGrid(FloatDataRecord targetDataRecord, - GridGeometry2D newTarget, GeneralGridGeometry gridGeometry) - throws FactoryException, TransformException { - GridGeometry2D remappedImageGeometry = newTarget; - GridReprojection reproj = new GridReprojection(gridGeometry, - remappedImageGeometry); - FloatArrayWrapper source = new FloatArrayWrapper( - targetDataRecord.getFloatData(), gridGeometry); - source.setValidRange(-9998, Float.POSITIVE_INFINITY); - FloatArrayWrapper dest = new FloatArrayWrapper(remappedImageGeometry); - dest.setFillValue(-999999); - float[] data = reproj.reprojectedGrid(new BilinearInterpolation(), - source, dest).getArray(); - FloatDataRecord remapGrid = (FloatDataRecord) targetDataRecord.clone(); - remapGrid.setIntSizes(new int[] { - remappedImageGeometry.getGridRange2D().width, - remappedImageGeometry.getGridRange2D().height }); - remapGrid.setFloatData(data); - return remapGrid; - } - - public double getPixelWidth(GridGeometry2D gridGeometry, - IMapDescriptor descriptor) throws VizException { - double pixelWidth = 0; - try { - double xCenter = gridGeometry.getGridRange().getSpan(0) / 2.0; - double yCenter = gridGeometry.getGridRange().getSpan(1) / 2.0; - - double[] input = new double[] { xCenter, yCenter, xCenter + 1, - yCenter }; - double[] output = new double[input.length]; - - MathTransform mathTransform = gridGeometry - .getGridToCRS(PixelInCell.CELL_CORNER); - // convert the point s to lat/lon - mathTransform.transform(input, 0, output, 0, input.length / 2); - MathTransform localProjToLL = CRS.findMathTransform( - gridGeometry.getCoordinateReferenceSystem(), - DefaultGeographicCRS.WGS84); - localProjToLL.transform(output, 0, output, 0, 2); - - double[] p1 = descriptor.worldToPixel(new double[] { output[0], - output[1] }); - double[] p2 = descriptor.worldToPixel(new double[] { output[2], - output[3] }); - - // compute the number of map pixels per tile pixel - pixelWidth = Math.abs(p2[0] - p1[0]); - } - - catch (org.opengis.referencing.operation.NoninvertibleTransformException e) { - throw new VizException(e); - - } catch (TransformException e) { - throw new VizException(e); - - } catch (InvalidGridGeometryException e) { - throw new VizException(e); - - } catch (FactoryException e) { - throw new VizException(e); - } - return pixelWidth; - } - - private synchronized FloatDataRecord diffData( - FloatDataRecord primaryDataRecord, - FloatDataRecord secondaryDataRecord, Unit primaryDataUnits, - Unit secondaryDataUnits) { - if (this.getStyleRule() != null) { - UnitConverter primaryUnitConverter = primaryDataUnits - .getConverterTo(this.getStyleRule().getPreferences() - .getDisplayUnits()); - UnitConverter secondaryUnitConverter = secondaryDataUnits - .getConverterTo(this.getStyleRule().getPreferences() - .getDisplayUnits()); - - for (int i = 0; i < secondaryDataRecord.getFloatData().length; i++) { - - float n1 = (float) primaryUnitConverter - .convert(primaryDataRecord.getFloatData()[i] == -999999 ? Float.NaN - : primaryDataRecord.getFloatData()[i]); - // convert secondary data to primary - float n2 = (float) secondaryUnitConverter - .convert(secondaryDataRecord.getFloatData()[i] == -999999 ? Float.NaN - : secondaryDataRecord.getFloatData()[i]); - primaryDataRecord.getFloatData()[i] = (float) primaryUnitConverter - .inverse().convert(n1 - n2); - if (Float.compare(primaryDataRecord.getFloatData()[i], - Float.NaN) == 0) { - primaryDataRecord.getFloatData()[i] = -999999; - } - - } - } else { - for (int i = 0; i < secondaryDataRecord.getFloatData().length; i++) { - - float n1 = (float) primaryDataRecord.getFloatData()[i] == -999999 ? Float.NaN - : primaryDataRecord.getFloatData()[i]; - // convert secondary data to primary - float n2 = (float) secondaryDataRecord.getFloatData()[i] == -999999 ? Float.NaN - : secondaryDataRecord.getFloatData()[i]; - primaryDataRecord.getFloatData()[i] = (n1 - n2); - if (Float.compare(primaryDataRecord.getFloatData()[i], - Float.NaN) == 0) { - primaryDataRecord.getFloatData()[i] = -999999; - } - - } - } - return primaryDataRecord; - } - - /** - * Remap the data in dataRecord from location to location2 - * - * This method is meant to be overriden by child classes, by default the - * dataRecord will simply be returned without being re-mapped. - * - * @param location - * @param location2 - * @param dataRecord - * @return a remapped dataRecord - */ - protected FloatDataRecord remapGrid(GridCoverage location, - GridCoverage location2, FloatDataRecord dataRecord, - Interpolation interpolation) { - return dataRecord; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.viz.core.rsc.IVizResource#dispose() - */ - @Override - protected void disposeInternal() { - if (this.vcrManagerJob != null) { - this.vcrManagerJob.shutdown(); - this.vcrManagerJob.disposeInternal(); - } - - if (this.gdManagerJob != null) { - this.gdManagerJob.shutdown(); - this.gdManagerJob.disposeInternal(); - } - synchronized (dataObjectMap) { - dataObjectMap.clear(); - } - retrievedAllData = false; - } - - /* - * (non-Javadoc) - * - * @seecom.raytheon.viz.core.rsc.IVizResource#init(com.raytheon.viz.core. - * IGraphicsTarget) - */ - @Override - protected void initInternal(IGraphicsTarget target) throws VizException { - // Initialize capabilities for resources that aresn't painting - getCapability(DensityCapability.class); - getCapability(MagnificationCapability.class); - getCapability(OutlineCapability.class); - - this.lastTarget = target; - } - - /** - * This method will retrieve all of the data for a set of contours for every - * frame. This will ensure that CAVE will not display any empty frames for - * one or a few iterations if the user begins looping through the frames. - * - * @throws VizException - */ - protected void getAllData() throws VizException { - System.out.println("Retrieving All Data"); - - this.vcrManagerJob.reset(); - this.gdManagerJob.reset(); - DataTime dataTime = null; - Set keySet = this.getDataObjectMap().keySet(); - Iterator keySetItr = keySet.iterator(); - - while (keySetItr.hasNext()) { - dataTime = keySetItr.next(); - - this.addJobRequest(dataTime); - } - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.drawables.IRenderable#paint(com.raytheon.viz.core - * .IGraphicsTarget, com.raytheon.viz.core.drawables.PaintProperties) - */ - @Override - protected void paintInternal(IGraphicsTarget target, - PaintProperties paintProps) throws VizException { - boolean useVCR = this.displayType != DisplayType.ARROW - && this.displayType != DisplayType.BARB - && this.displayType != DisplayType.DUALARROW; - - if (!this.retrievedAllData) { - this.getAllData(); - this.retrievedAllData = true; - } else { - if (useVCR) { - this.vcrManagerJob.makeHighestPriority(this.displayedDataTime); - } else { - this.gdManagerJob.makeHighestPriority(this.displayedDataTime); - } - } - - synchronized (this) { - this.setDisplayedDataTime(paintProps.getDataTime()); - - // Pull the record out - PluginDataObject pdo = this.getDataObjectMap().get( - this.getDisplayedDataTime()); - - if (pdo == null) { - // Don't have data for this frame - return; - } - - if (this.getStyleRule() == null) { - this.setStyleRule(this.getStyleRule(pdo)); - } - - if (useVCR) { - ContourRenderable contourGroup = this.vcrManagerJob - .request(this.getDisplayedDataTime()); - - if (contourGroup != null) { - if (combineOperation != CombineOperation.NONE) { - contourGroup.paint(target, paintProps); - } - } else { - updatePaintStatus(PaintStatus.INCOMPLETE); - } - } else { - AbstractGriddedDisplay display = this.gdManagerJob - .request(this.getDisplayedDataTime()); - - if (display != null) { - if (combineOperation != CombineOperation.NONE) { - display.paint(target, paintProps); - } - } - } - } - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.rsc.capabilities.IProjectableResource#project(org - * .opengis.referencing.crs.CoordinateReferenceSystem) - */ - @Override - public void project(CoordinateReferenceSystem mapData) throws VizException { - if (gdManagerJob != null) { - for (AbstractGriddedDisplay display : gdManagerJob - .getResponseMapAsCollection()) { - if (display != null) { - display.reproject(); - } - } - } - initInternal(this.lastTarget); - this.retrievedAllData = false; - if (vcrManagerJob != null) { - vcrManagerJob.shutdown(); - vcrManagerJob.clearResponseMap(); - } - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.uf.viz.core.rsc.AbstractVizResource#remove(com.raytheon. - * uf.common.time.DataTime) - */ - @Override - public void remove(DataTime dataTime) { - synchronized (dataObjectMap) { - dataObjectMap.remove(dataTime); - } - this.vcrManagerJob.removeDataTime(dataTime); - this.gdManagerJob.removeDataTime(dataTime); - recreateDataTimes(); - } - - /** - * Recreate all the datatimes from the objects - */ - protected void recreateDataTimes() { - this.dataTimes = new ArrayList(this.getDataObjectMap() - .keySet()); - } - - public void addRecord(PluginDataObject record) throws VizException { - Validate.notNull(record); - boolean good = validateRecord(record); - if (!good) { - throw new IllegalArgumentException( - "Wrong type of data provided to " - + this.getClass().getName() + " :: " - + record.getClass().getName()); - } - DataTime dt = record.getDataTime(); - synchronized (dataObjectMap) { - dataObjectMap.put(dt, record); - } - - if (this.retrievedAllData) { - this.addJobRequest(dt); - } - - recreateDataTimes(); - if (this.getDisplayedDataTime() == null) { - this.setDisplayedDataTime(dt); - } - } - - public void addJobRequest(DataTime dt) throws VizException { - PluginDataObject pdo = this.getDataObjectMap().get(dt); - if (pdo == null) { - return; - } - - StyleRule sr = getStyleRule(); - if (sr == null) { - sr = getStyleRule(pdo); - if (sr != null) { - this.setStyleRule(sr); - } - } - - if (displayType == DisplayType.ARROW || displayType == DisplayType.BARB - || displayType == DisplayType.DUALARROW) { - GriddedDisplayRequest req = new GriddedDisplayRequest(pdo, sr); - this.gdManagerJob.addRequest(dt, req); - } else { - VectorContourRenderable cr = new VectorContourRenderable( - this.descriptor, pdo, sr); - cr.setColor(this.getCapability(ColorableCapability.class) - .getColor()); - cr.setLineStyle(this.getCapability(OutlineCapability.class) - .getLineStyle()); - cr.setOutlineWidth(this.getCapability(OutlineCapability.class) - .getOutlineWidth()); - cr.setDensity(getCapability(DensityCapability.class).getDensity()); - cr.setMagnification(getCapability(MagnificationCapability.class) - .getMagnification()); - this.vcrManagerJob.addRequest(dt, cr); - } - } - - public synchronized StyleRule getStyleRule() { - return styleRule; - } - - public synchronized void setStyleRule(StyleRule styleRule) { - this.styleRule = styleRule; - } - - /** - * Get a copy of dataObjectMap, this copy is safe to use without - * synchronizing, if you need to modify the dataObjectMap, use the field - * directly and synchronize on it. - * - * @return - */ - protected Map getDataObjectMap() { - if (dataObjectMap == null) { - return Collections.emptyMap(); - } - synchronized (dataObjectMap) { - return new HashMap(dataObjectMap); - } - } - - public synchronized DataTime getDisplayedDataTime() { - return displayedDataTime; - } - - /** - * @param displayedDataTime - * the displayedDataTime to set - */ - protected synchronized void setDisplayedDataTime(DataTime displayedDataTime) { - this.displayedDataTime = displayedDataTime; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResource.java index 8bab4af36e..ac2d9186b4 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResource.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResource.java @@ -21,24 +21,19 @@ package com.raytheon.viz.grid.rsc; import java.util.Map; -import javax.measure.converter.UnitConverter; - -import org.geotools.coverage.grid.GridGeometry2D; -import org.opengis.referencing.datum.PixelInCell; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.datastorage.StorageException; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; import com.raytheon.uf.viz.core.drawables.ColorMapParameters; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.LoadProperties; import com.raytheon.uf.viz.core.rsc.capabilities.ColorMapCapability; import com.raytheon.uf.viz.core.style.DataMappingPreferences.DataMappingEntry; -import com.raytheon.viz.core.rsc.hdf5.AbstractTileSet; -import com.vividsolutions.jts.geom.Coordinate; +import com.raytheon.viz.grid.rsc.general.D2DGridResource; +import com.raytheon.viz.grid.rsc.general.GeneralGridData; /** - * TODO Add Description + * Grid Resource that does not do simple mapping from data to colors but has an + * overly complex mapping, usually for something where pixel values are actually + * enums. * *
  * 
@@ -54,76 +49,12 @@ import com.vividsolutions.jts.geom.Coordinate;
  * @version 1.0
  */
 
-public class DataMappedGridResource extends GridResource {
-
-    private class NcwfMemoryBasedTileSet extends GridMemoryBasedTileSet {
-
-        public NcwfMemoryBasedTileSet(String group, String dataset,
-                AbstractTileSet sharedGeometryTileset, UnitConverter converter,
-                GribRecord pdo) throws VizException {
-            super(group, dataset, sharedGeometryTileset, converter, pdo);
-        }
-
-        public NcwfMemoryBasedTileSet(String dataURI, String string,
-                int numLevels, int i, GridGeometry2D gridGeometry2D,
-                GridResource gridResource, UnitConverter conversion,
-                PixelInCell cellCorner, GribRecord record, String viewType)
-                throws VizException {
-            super(dataURI, string, numLevels, i, gridGeometry2D, gridResource,
-                    conversion, cellCorner, record, viewType);
-        }
-
-        @Override
-        protected void preloadDataObject(int level) throws StorageException {
-            super.preloadDataObject(level);
-            float[] data = new float[((float[]) loadedData[0]).length];
-            for (int i = 0; i < data.length; i++) {
-                data[i] = ((float[]) loadedData[0])[i];
-                if (Float.isNaN(data[i])) {
-                    data[i] = Float.NaN;
-                }
-            }
-
-            loadedData[0] = data; // transformNCWFData(data);
-        }
-    }
+public class DataMappedGridResource extends D2DGridResource {
 
     public DataMappedGridResource(GridResourceData data, LoadProperties props) {
         super(data, props);
     }
 
-    private float[] transformNCWFData(float[] data) {
-        ColorMapParameters params = getCapability(ColorMapCapability.class)
-                .getColorMapParameters();
-        if (params == null || params.getImageToDisplayConverter() == null) {
-            return data;
-        }
-        UnitConverter converter = params.getDataToImageConverter();
-        if (converter == null) {
-            return data;
-        }
-        float[] newData = new float[data.length];
-        for (int i = 0; i < newData.length; i++) {
-            newData[i] = (float) converter.convert(data[i]);
-        }
-        return newData;
-    }
-
-    @Override
-    public NcwfMemoryBasedTileSet createTile(GribRecord record,
-            GridMemoryBasedTileSet commonTile) throws VizException {
-        if (commonTile != null) {
-            return new NcwfMemoryBasedTileSet(record.getDataURI(), "Data",
-                    commonTile, conversion, record);
-        }
-
-        GridGeometry2D gridGeometry2D = record.getModelInfo().getLocation()
-                .getGridGeometry();
-        return new NcwfMemoryBasedTileSet(record.getDataURI(), "Data",
-                numLevels, 256, gridGeometry2D, this, conversion,
-                PixelInCell.CELL_CORNER, record, viewType);
-    }
-
     @Override
     public String getName() {
         String name = this.resourceData.getCustomLegend();
@@ -136,31 +67,11 @@ public class DataMappedGridResource extends GridResource {
     @Override
     public String inspect(ReferencedCoordinate coord) throws VizException {
 
-        Map map = tileSet.get(descriptor
-                .getFramesInfo().getTimeForResource(this));
+        Map map = interrogate(coord);
         if (map == null) {
-            return "No Data";
+            return "NO DATA";
         }
-
-        GridMemoryBasedTileSet tile = map.get(displayedLevel);
-        if (tile == null) {
-            tile = map.values().iterator().next();
-        }
-
-        if (tile == null) {
-            return "No Data";
-        }
-
-        Coordinate latLon;
-        try {
-            latLon = coord.asLatLon();
-        } catch (Exception e) {
-            throw new VizException("Error transforming coordinate to lat/lon",
-                    e);
-        }
-
-        // get raw image pixels (0-255)
-        Double val = tile.interrogate(latLon, true);
+        Double val = ((Float) map.get(INTERROGATE_VALUE)).doubleValue();
         if (val.isNaN() || val <= -9999) {
             return "No Data";
         }
@@ -168,6 +79,8 @@ public class DataMappedGridResource extends GridResource {
         ColorMapParameters params = getCapability(ColorMapCapability.class)
                 .getColorMapParameters();
 
+        val = params.getDisplayToImageConverter().convert(val);
+
         for (DataMappingEntry entry : params.getDataMapping().getEntries()) {
             double pixelValue = entry.getPixelValue();
             double relError = Math.abs((pixelValue - val) / val);
@@ -182,14 +95,13 @@ public class DataMappedGridResource extends GridResource {
         }
 
         return ((DataMappedGridResourceData) this.getResourceData())
-                .getSampleFormat().format(val) + this.units;
+                .getSampleFormat().format(val) + map.get(INTERROGATE_UNIT);
     }
 
     @Override
-    protected ColorMapParameters initColorMapParameters(GribRecord record)
+    protected ColorMapParameters createColorMapParameters(GeneralGridData data)
             throws VizException {
-        ColorMapParameters params = super.initColorMapParameters(record);
-        // Always have min/max of 0-255 for data mapped
+        ColorMapParameters params = super.createColorMapParameters(data);
         params.setColorMapMin(0.0f);
         params.setColorMapMax(255.0f);
         return params;
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResourceData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResourceData.java
index 3f6d2dcac3..081d7f24e2 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResourceData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/DataMappedGridResourceData.java
@@ -26,12 +26,12 @@ import javax.xml.bind.annotation.XmlAccessorType;
 import javax.xml.bind.annotation.XmlAttribute;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.viz.core.rsc.AbstractVizResource;
 import com.raytheon.uf.viz.core.rsc.LoadProperties;
 
 /**
- * TODO Add Description
+ * Resource data used for grid data that needs complex mapping to colors.
  * 
  * 
  * 
@@ -63,9 +63,9 @@ public class DataMappedGridResourceData extends GridResourceData {
     @Override
     protected AbstractVizResource constructResource(
             LoadProperties loadProperties, PluginDataObject[] objects) {
-        records = new GribRecord[objects.length];
+        records = new GridRecord[objects.length];
         for (int i = 0; i < objects.length; i++) {
-            records[i] = (GribRecord) objects[i];
+            records[i] = (GridRecord) objects[i];
         }
         return new DataMappedGridResource(this, loadProperties);
     }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/FFGVizGroupResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/FFGVizGroupResource.java
index e8a58a889e..4c3a774cbe 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/FFGVizGroupResource.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/FFGVizGroupResource.java
@@ -18,6 +18,7 @@
  * further licensing information.
  **/
 package com.raytheon.viz.grid.rsc;
+
 import java.util.ArrayList;
 import java.util.Map;
 
@@ -38,19 +39,19 @@ import com.raytheon.viz.core.rsc.VizGroupResourceData;
 
 /**
  * FFG Group Resource class.
- *
+ * 
  * Based off VizGroupResource.java
- *
+ * 
  * 
- *
+ * 
  * SOFTWARE HISTORY
- *
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Sep 19, 2012  1162      mpduff      Initial creation.
- *
+ * 
  * 
- * + * * @author mpduff * @version 1.0 */ @@ -63,7 +64,7 @@ public class FFGVizGroupResource extends /** * Constructor. - * + * * @param resourceData * @param loadProperties */ @@ -75,7 +76,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see com.raytheon.uf.viz.core.rsc.AbstractVizResource#disposeInternal() */ @Override @@ -89,7 +90,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see * com.raytheon.uf.viz.core.rsc.AbstractVizResource#paintInternal(com.raytheon * .uf.viz.core.IGraphicsTarget, @@ -107,7 +108,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see * com.raytheon.uf.viz.core.rsc.AbstractVizResource#inspect(com.raytheon * .uf.common.geospatial.ReferencedCoordinate) @@ -116,11 +117,14 @@ public class FFGVizGroupResource extends public String inspect(ReferencedCoordinate coord) throws VizException { ResourceList rl = resourceData.getResourceList(); String value = "No Data"; + Map, DataTime[]> timeMap = descriptor + .getTimeMatchingMap(); for (ResourcePair pair : rl) { if (pair.getResource() != null) { - AbstractVizResource rsc = pair.getResource(); + AbstractVizResource rsc = pair.getResource(); + timeMap.put(rsc, timeMap.get(this)); value = rsc.inspect(coord); - if (!value.equals(NO_DATA)) { + if (!NO_DATA.equalsIgnoreCase(value)) { return value; } } @@ -131,7 +135,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see * com.raytheon.uf.viz.core.rsc.AbstractVizResource#interrogate(com.raytheon * .uf.common.geospatial.ReferencedCoordinate) @@ -145,7 +149,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see * com.raytheon.uf.viz.core.rsc.AbstractVizResource#initInternal(com.raytheon * .uf.viz.core.IGraphicsTarget) @@ -179,7 +183,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see com.raytheon.uf.viz.core.rsc.IRefreshListener#refresh() */ @Override @@ -190,7 +194,7 @@ public class FFGVizGroupResource extends /* * (non-Javadoc) - * + * * @see * com.raytheon.uf.viz.core.rsc.IResourceDataChanged#resourceChanged(com * .raytheon.uf.viz.core.rsc.IResourceDataChanged.ChangeType, diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridIconResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridIconResource.java deleted file mode 100644 index ebd3f12199..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridIconResource.java +++ /dev/null @@ -1,200 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.rsc; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.swt.graphics.RGB; -import org.opengis.referencing.crs.CoordinateReferenceSystem; - -import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.datastorage.records.IDataRecord; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.IGraphicsTarget; -import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; -import com.raytheon.uf.viz.core.drawables.PaintProperties; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.map.MapDescriptor; -import com.raytheon.uf.viz.core.rsc.AbstractVizResource; -import com.raytheon.uf.viz.core.rsc.IResourceDataChanged; -import com.raytheon.uf.viz.core.rsc.LoadProperties; -import com.raytheon.uf.viz.core.rsc.capabilities.ColorableCapability; -import com.raytheon.uf.viz.core.rsc.capabilities.DensityCapability; -import com.raytheon.uf.viz.core.rsc.capabilities.MagnificationCapability; -import com.raytheon.viz.grid.rsc.GridNameGenerator.IGridNameResource; -import com.raytheon.viz.grid.rsc.GridNameGenerator.LegendParameters; - -/** - * - * TODO Add Description - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Jan 26, 2010            bsteffen     Initial creation
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ -public class GridIconResource extends - AbstractVizResource implements - IResourceDataChanged, IGridNameResource { - - private static final int imageSize = 80; - - private Map displays = new HashMap(); - - private Map records = new HashMap(); - - private DataTime currTime; - - public GridIconResource(GridResourceData resourceData, - LoadProperties loadProperties) { - super(resourceData, loadProperties); - this.dataTimes = new ArrayList(); - for (GribRecord record : resourceData.getRecords()) { - addRecord(record); - } - if (resourceData.getNameGenerator() == null) { - resourceData.setNameGenerator(new GridNameGenerator()); - } - resourceData.addChangeListener(this); - } - - @Override - protected void disposeInternal() { - for (GriddedIconDisplay display : displays.values()) { - display.dispose(); - } - displays.clear(); - } - - @Override - protected void initInternal(IGraphicsTarget target) throws VizException { - - } - - @Override - protected void paintInternal(IGraphicsTarget target, - PaintProperties paintProps) throws VizException { - currTime = paintProps.getDataTime(); - GriddedIconDisplay display = displays.get(currTime); - if (display == null) { - GribRecord record = records.get(paintProps.getDataTime()); - if (record == null) { - return; - } - if (!(record.getMessageData() instanceof float[])) { - IDataRecord[] dataRecord = DataCubeContainer - .getDataRecord(record); - record.setMessageData(dataRecord[0].getDataObject()); - } - float[] values = (float[]) record.getMessageData(); - display = new GriddedIconDisplay(values, descriptor, record - .getModelInfo().getLocation().getGridGeometry(), imageSize); - display.setColor(getCapability(ColorableCapability.class) - .getColor()); - display.setDensity(getCapability(DensityCapability.class) - .getDensity()); - display.setMagnification(getCapability( - MagnificationCapability.class).getMagnification()); - displays.put(currTime, display); - } - - display.paint(target, paintProps); - } - - public LegendParameters getLegendParameters() { - GribRecord record = records.get(currTime); - if (record == null) { - record = resourceData.getRecords()[0]; - } - LegendParameters legendParams = new LegendParameters(); - legendParams.model = resourceData.getModelInfo(); - legendParams.unit = resourceData.getModelInfo().getParameterUnit(); - legendParams.dataTime = record.getDataTime(); - legendParams.type = "Icons"; - return legendParams; - } - - @Override - public void resourceChanged(ChangeType type, Object object) { - if (type.equals(ChangeType.DATA_UPDATE)) { - PluginDataObject[] pdos = (PluginDataObject[]) object; - for (PluginDataObject pdo : pdos) { - addRecord(pdo); - } - } else if (type == ChangeType.CAPABILITY) { - if (object instanceof DensityCapability) { - Double density = ((DensityCapability) object).getDensity(); - for (GriddedIconDisplay display : displays.values()) { - display.setDensity(density); - } - } else if (object instanceof ColorableCapability) { - RGB color = ((ColorableCapability) object).getColor(); - for (GriddedIconDisplay display : displays.values()) { - display.setColor(color); - } - } else if (object instanceof MagnificationCapability) { - double mag = ((MagnificationCapability) object) - .getMagnification(); - for (GriddedIconDisplay display : displays.values()) { - display.setMagnification(mag); - } - } - } - issueRefresh(); - } - - private void addRecord(PluginDataObject pdo) { - if (pdo instanceof GribRecord) { - records.put(pdo.getDataTime(), (GribRecord) pdo); - if (!this.dataTimes.contains(pdo.getDataTime())) { - this.dataTimes.add(pdo.getDataTime()); - } - } - } - - @Override - public void project(CoordinateReferenceSystem crs) throws VizException { - for (GriddedIconDisplay display : displays.values()) { - display.reproject(); - } - super.project(crs); - } - - @Override - public void remove(DataTime dataTime) { - records.remove(dataTime); - GriddedIconDisplay display = displays.remove(dataTime); - if (display != null) { - display.dispose(); - } - dataTimes.remove(dataTime); - } - -} \ No newline at end of file diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridNameGenerator.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridNameGenerator.java index 325d21bc54..809059318b 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridNameGenerator.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridNameGenerator.java @@ -19,7 +19,6 @@ **/ package com.raytheon.viz.grid.rsc; -import com.raytheon.uf.common.dataplugin.grib.GribModel; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.exception.VizCommunicationException; @@ -28,6 +27,24 @@ import com.raytheon.uf.viz.core.level.LevelMappingFactory; import com.raytheon.uf.viz.core.rsc.AbstractNameGenerator; import com.raytheon.uf.viz.core.rsc.AbstractVizResource; +/** + * + * Name generator that creates names for grids based off a standards set of + * LegendParameters. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 20, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ public class GridNameGenerator extends AbstractNameGenerator { public interface IGridNameResource { @@ -35,7 +52,12 @@ public class GridNameGenerator extends AbstractNameGenerator { } public static class LegendParameters { - public GribModel model = null; + + public String model = ""; + + public String parameter = ""; + + public Level level; public String type = ""; @@ -43,6 +65,8 @@ public class GridNameGenerator extends AbstractNameGenerator { public DataTime dataTime; + public String ensembleId; + public boolean isPlaneLabelDisplayed = true; } @@ -92,16 +116,16 @@ public class GridNameGenerator extends AbstractNameGenerator { } private String getLegendName(LegendParameters legendParams) { - String plane = this.planeLabelString == null ? lookupPlane(legendParams.model - .getLevel()) : this.planeLabelString; + String plane = this.planeLabelString == null ? lookupPlane(legendParams.level) + : this.planeLabelString; String pert = ""; - if (legendParams.model.getPerturbationNumber() != null) { - pert = "Perturbation " + legendParams.model.getPerturbationNumber(); + if (legendParams.ensembleId != null) { + pert = "Perturbation " + legendParams.ensembleId; } if (legendParams.unit == null) { legendParams.unit = ""; } - String modelTitle = legendParams.model.getModelTitle(); + String modelTitle = legendParams.model; // Camel case single word lower case titles, like radar if (modelTitle.matches("[a-z]*")) { modelTitle = modelTitle.substring(0, 1).toUpperCase() @@ -109,11 +133,11 @@ public class GridNameGenerator extends AbstractNameGenerator { } if (legendParams.isPlaneLabelDisplayed) { return String.format("%s %s %s %s (%s) %s ", modelTitle, plane, - legendParams.model.getParameterName(), legendParams.type, + legendParams.parameter, legendParams.type, legendParams.unit, pert); } else { return String.format("%s %s %s (%s) %s ", modelTitle, - legendParams.model.getParameterName(), legendParams.type, + legendParams.parameter, legendParams.type, legendParams.unit, pert); } } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResource.java deleted file mode 100644 index 4288fe7a07..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResource.java +++ /dev/null @@ -1,1809 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.rsc; - -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.concurrent.ConcurrentLinkedQueue; - -import javax.measure.converter.UnitConverter; -import javax.measure.unit.NonSI; -import javax.measure.unit.SI; -import javax.measure.unit.Unit; -import javax.media.jai.Interpolation; - -import org.apache.commons.collections.keyvalue.MultiKey; -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.geotools.coverage.grid.GeneralGridGeometry; -import org.geotools.coverage.grid.GridGeometry2D; -import org.geotools.coverage.grid.InvalidGridGeometryException; -import org.geotools.geometry.Envelope2D; -import org.geotools.geometry.jts.JTS; -import org.geotools.referencing.CRS; -import org.geotools.referencing.crs.DefaultGeographicCRS; -import org.opengis.referencing.FactoryException; -import org.opengis.referencing.crs.CoordinateReferenceSystem; -import org.opengis.referencing.datum.PixelInCell; -import org.opengis.referencing.operation.MathTransform; -import org.opengis.referencing.operation.TransformException; - -import com.raytheon.edex.meteoLib.Controller; -import com.raytheon.uf.common.colormap.IColorMap; -import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.CombinedGribRecord; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage; -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.MapUtil; -import com.raytheon.uf.common.geospatial.ReferencedCoordinate; -import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation; -import com.raytheon.uf.common.geospatial.interpolation.GridReprojection; -import com.raytheon.uf.common.geospatial.interpolation.GridSampler; -import com.raytheon.uf.common.geospatial.interpolation.NearestNeighborInterpolation; -import com.raytheon.uf.common.geospatial.interpolation.data.FloatArrayWrapper; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.IGraphicsTarget; -import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; -import com.raytheon.uf.viz.core.drawables.ColorMapLoader; -import com.raytheon.uf.viz.core.drawables.ColorMapParameters; -import com.raytheon.uf.viz.core.drawables.ColorMapParameters.PersistedParameters; -import com.raytheon.uf.viz.core.drawables.IColormappedImage; -import com.raytheon.uf.viz.core.drawables.IImage; -import com.raytheon.uf.viz.core.drawables.PaintProperties; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.map.IMapDescriptor; -import com.raytheon.uf.viz.core.map.MapDescriptor; -import com.raytheon.uf.viz.core.rsc.AbstractVizResource; -import com.raytheon.uf.viz.core.rsc.IResourceDataChanged; -import com.raytheon.uf.viz.core.rsc.LoadProperties; -import com.raytheon.uf.viz.core.rsc.capabilities.ColorMapCapability; -import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability; -import com.raytheon.uf.viz.core.rsc.capabilities.ImagingCapability; -import com.raytheon.uf.viz.core.rsc.hdf5.ImageTile; -import com.raytheon.uf.viz.core.style.DataMappingPreferences; -import com.raytheon.uf.viz.core.style.ParamLevelMatchCriteria; -import com.raytheon.uf.viz.core.style.StyleManager; -import com.raytheon.uf.viz.core.style.StyleManager.StyleType; -import com.raytheon.uf.viz.core.style.StyleRule; -import com.raytheon.uf.viz.core.style.level.Level; -import com.raytheon.uf.viz.core.style.level.SingleLevel; -import com.raytheon.viz.core.drawables.ColorMapParameterFactory; -import com.raytheon.viz.core.rsc.ICombinedResourceData; -import com.raytheon.viz.core.rsc.ICombinedResourceData.CombineOperation; -import com.raytheon.viz.core.rsc.ICombinedResourceData.CombineUtil; -import com.raytheon.viz.core.rsc.hdf5.AbstractTileSet; -import com.raytheon.viz.core.rsc.hdf5.MemoryBasedTileSet; -import com.raytheon.viz.core.style.image.ImagePreferences; -import com.raytheon.viz.grid.GridLevelTranslator; -import com.raytheon.viz.grid.record.RequestableDataRecord; -import com.raytheon.viz.grid.rsc.GridNameGenerator.IGridNameResource; -import com.raytheon.viz.grid.rsc.GridNameGenerator.LegendParameters; -import com.raytheon.viz.grid.xml.FieldDisplayTypesFactory; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.Geometry; -import com.vividsolutions.jts.io.WKTReader; - -/** - * Grid Resource - * - * Accepts grib data records from different time and levels. Data record array - * should represent a single parameter. - * - *
- *
- *    SOFTWARE HISTORY
- *
- *    Date         Ticket#     Engineer    Description
- *    ------------ ----------  ----------- --------------------------
- *    Feb 28, 2007             chammack    Initial Creation.
- *    02/12/09                 njensen     Refactored to new rsc architecture
- *    04/03/2012   14774/14775 D. Friedman Fixed tiling and lockup problem
- *    05/08/2012   14828       D. Friedman Use nearest-neighbor interpolation for
- *                                         reprojected grids.
- *    06/19/2012   14988       D. Friedman Choose interpolation method based on
- *                                         ImagingCapability.isInterpolationState().
- *                                         Oversample reprojected grids.
- *    09/20/2012    15394      mpduff      Condense the PDOs based on grid version.
- *                                         Get DataTime from paintProps.
- * 
- * - * @author chammack - * @version 1 - */ -public class GridResource extends - AbstractVizResource implements - IResourceDataChanged, IGridNameResource { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(GridResource.class); - - private static final String NO_DATA = "No Data"; - - protected static final DecimalFormat sampleFormat = new DecimalFormat( - "0.00"); - - protected Map> tileSet; - - protected WKTReader reader; - - protected SingleLevel[] levels; - - protected float displayedLevel; - - protected String parameter; - - protected String parameterAbbrev; - - protected Map baseTiles = new HashMap(); - - protected boolean ready = false; - - protected String units; - - protected Geometry baseTileCoverage; - - protected IGraphicsTarget target; - - protected SingleLevel level; - - protected String levelUnits; - - protected UnitConverter conversion; - - protected int numLevels; - - private UnitConverter levelConverter; - - protected String viewType; - - private final List pdosToParse = new ArrayList(); - - private CombineOperation combineOperation; - - private GridCoverage gridCoverage; - - private StyleRule styleRule; - - /** - * The great protector of all things related to dataTimes, do not modify or - * iterate over pdosToParse, dataTimes, or tileSet unless you sync on this - * or else... - * - */ - protected Object timeLock = new Object(); - - /** - * Extends the MemoryBasedTileSet class so that we can have direct access to - * the loadedData - */ - protected class GridMemoryBasedTileSet extends MemoryBasedTileSet { - - private boolean combined = false; - - public boolean isCombined() { - return combined; - } - - public void setCombined(boolean combined) { - this.combined = combined; - } - - public int[][] getDims() { - return dims; - } - - public String getGroup() { - return group; - } - - /** - * @param group - * @param dataset - * @param sharedGeometryTileset - * @param converter - * @param record - * @throws VizException - */ - public GridMemoryBasedTileSet(String group, String dataset, - AbstractTileSet sharedGeometryTileset, UnitConverter converter, - GribRecord record) throws VizException { - super(null, group, dataset, sharedGeometryTileset, converter, - record); - } - - /** - * @param dataURI - * @param string - * @param numLevels - * @param i - * @param gridGeometry2D - * @param gridResource - * @param conversion - * @param cellCorner - * @param record - * @param viewType - * @throws VizException - */ - public GridMemoryBasedTileSet(String dataURI, String string, - int numLevels, int i, GridGeometry2D gridGeometry2D, - GridResource gridResource, UnitConverter conversion, - PixelInCell cellCorner, GribRecord record, String viewType) - throws VizException { - super(null, dataURI, string, numLevels, i, gridGeometry2D, - gridResource, conversion, cellCorner, record, viewType); - } - - @Override - protected IDataRecord getDataRecord() throws StorageException { - GribRecord gribRecord = (GribRecord) pdo; - IDataRecord record = null; - try { - IDataRecord[] records = GridResourceData.getDataRecordsForTilt( - gribRecord, descriptor); - if (records != null && records.length > 0) { - record = records[0]; - } - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), - e); - } - - if (record == null) { - record = super.getDataRecord(); - } - Unit realDataUnit = gribRecord.getModelInfo() - .getParameterUnitObject(); - Unit expectedDataUnit = getCapability(ColorMapCapability.class) - .getColorMapParameters().getDataUnit(); - if (!realDataUnit.equals(expectedDataUnit) - && realDataUnit.isCompatible(expectedDataUnit)) { - if (record instanceof FloatDataRecord) { - UnitConverter converter = realDataUnit - .getConverterTo(expectedDataUnit); - record = record.clone(); - float[] data = ((FloatDataRecord) record).getFloatData(); - for (int i = 0; i < data.length; i++) { - if (data[i] > -9999) { - data[i] = (float) converter.convert(data[i]); - } - } - } - } - GridGeometry2D realGridGeometry = gribRecord.getModelInfo() - .getLocation().getGridGeometry(); - GridGeometry2D expectedGridGeometry = this.gridGeometry[0]; - if (!realGridGeometry.equals(expectedGridGeometry)) { - GridReprojection reproj = new GridReprojection( - realGridGeometry, expectedGridGeometry); - com.raytheon.uf.common.geospatial.interpolation.Interpolation interp; - - if (getCapability(ImagingCapability.class) - .isInterpolationState()) { - BilinearInterpolation blInterp = new BilinearInterpolation(); - blInterp.setMissingThreshold(1.0f); - interp = blInterp; - } else { - interp = new NearestNeighborInterpolation(); - } - - if (record instanceof FloatDataRecord) { - float[] data = ((FloatDataRecord) record).getFloatData(); - record = record.clone(); - FloatArrayWrapper source = new FloatArrayWrapper(data, - realGridGeometry); - source.setValidRange(-9998, Double.POSITIVE_INFINITY); - FloatArrayWrapper dest = new FloatArrayWrapper( - expectedGridGeometry); - dest.setFillValue(-999999); - try { - data = reproj.reprojectedGrid(interp, source, dest) - .getArray(); - } catch (Exception e) { - statusHandler.handle(Priority.PROBLEM, - e.getLocalizedMessage(), e); - } - record = record.clone(); - record.setIntSizes(new int[] { - expectedGridGeometry.getGridRange2D().width, - expectedGridGeometry.getGridRange2D().height }); - ((FloatDataRecord) record).setFloatData(data); - } - } - - // convert based on data mapping - DataMappingPreferences dataMapping = getCapability( - ColorMapCapability.class).getColorMapParameters() - .getDataMapping(); - - if (dataMapping != null - && expectedDataUnit.isCompatible(dataMapping - .getImageUnit(expectedDataUnit))) { - UnitConverter conv = expectedDataUnit - .getConverterTo(dataMapping - .getImageUnit(expectedDataUnit)); - record = record.clone(); - float[] data = ((FloatDataRecord) record).getFloatData(); - for (int i = 0; i < data.length; i++) { - if (data[i] > -9999) { - data[i] = (float) conv.convert(data[i]); - } - } - } - return record; - } - - public float[] getLoadedData() { - return (float[]) (loadedData != null ? loadedData[0] : null); - } - - public void setLoadedData(float[] loadedData) { - if (this.loadedData != null) { - this.loadedData[0] = loadedData; - } - } - - public void setLoadedData(float[][] loadedData) { - this.loadedData = loadedData; - } - - public void preloadDataObject() { - try { - preloadDataObject(lastPaintedLevel); - } catch (StorageException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), - e); - } - } - - public DataTime getDataTime() { - return pdo.getDataTime(); - } - - public void getImageCoordinates(Coordinate coord, - double[] envelopeCoordinates, double[] imageCoordinates) - throws VizException { - try { - if (llToLocalProj != null) { - double[] in = new double[2]; - - in[0] = coord.x; - in[1] = coord.y; - - llToLocalProj.transform(in, 0, envelopeCoordinates, 0, 1); - - } else { - envelopeCoordinates[0] = coord.x; - envelopeCoordinates[1] = coord.y; - } - this.inverseMathTransform[this.lastPaintedLevel].transform( - envelopeCoordinates, 0, imageCoordinates, 0, 1); - } catch (TransformException e) { - throw new VizException("Error interrogating ", e); - } - } - - public double getTileCoordinateValue(boolean getRaw, - double[] envelopeCoordinates, double[] imageCoordinates) - throws VizException { - ImageTile[][] tiles = this.tileSet - .getTileGrid(this.lastPaintedLevel); - - if (tiles == null) { - - return Double.NaN; - } - - try { - if (!this.hasDataPreloaded(this.lastPaintedLevel)) { - this.preloadDataObject(this.lastPaintedLevel); - } - } catch (StorageException e1) { - throw new VizException("Unable to load data to interrogate", e1); - } - - for (int i = 0; i < tiles.length; i++) { - for (int j = 0; j < tiles[0].length; j++) { - ImageTile tile = tiles[i][j]; - if (tile != null - && tile.contains(envelopeCoordinates[0], - envelopeCoordinates[1])) { - int coordX = (int) (imageCoordinates[0]); - int coordY = (int) (imageCoordinates[1]); - - // Since createTile is asynchronous, wait to see - // if tile image is available - IImage image = imageMap.get(tile); - if (image == null && this.lastPaintedTarget != null) { - int retries = 20; - - MultiKey key = new MultiKey(this.lastPaintedLevel, - i, j); - if (jobMap.containsKey(key)) { - while (image == null && retries > 0) { - image = imageMap.get(tile); - try { - Thread.sleep(10); - } catch (InterruptedException e) { - // ignore - } - retries--; - } - } else { - image = createTile(this.lastPaintedTarget, - this.lastPaintedLevel, i, j); - imageMap.put(tile, image); - } - - } - - if (image != null) { - if (getRaw - || (rsc.getCapability( - ColorMapCapability.class) - .getColorMapParameters() - .getDataToDisplayConverter() == null)) { - if (image instanceof IColormappedImage) { - return ((IColormappedImage) image) - .getValue(coordX % this.tileSize, - coordY % this.tileSize); - } else { - return 0; - } - } else { - if (image instanceof IColormappedImage) { - double value = ((IColormappedImage) image) - .getValue(coordX % this.tileSize, - coordY % this.tileSize); - if (value > -9999) { - return rsc - .getCapability( - ColorMapCapability.class) - .getColorMapParameters() - .getDataToDisplayConverter() - .convert(value); - } - } - } - } - - } - } - } - - return Double.NaN; - } - - public boolean hasDataPreloaded() { - return super.hasDataPreloaded(lastPaintedLevel); - } - - public PluginDataObject getPluginDataObject() { - return pdo; - } - - public GridGeometry2D getGridGeometry() { - return gridGeometry[0]; - } - - public double[] getPixelWidth() { - return pixelWidth; - } - - public void setDataRecord(FloatDataRecord rec, int level) { - if (loadedData == null) { - loadedData = new Object[levels]; - dims = new int[levels][]; - } - - if (rec != null) { - loadedData[level] = rec.getDataObject(); - long[] d = rec.getSizes(); - dims[level] = new int[] { (int) d[0], (int) d[1] }; - - } - isLoaded[level] = true; - } - } - - private class DataRetrievalJob extends Job { - private final ConcurrentLinkedQueue tilesToRetrieve = new ConcurrentLinkedQueue(); - - public DataRetrievalJob() { - super("Retrieving Gridded Data"); - } - - @Override - protected IStatus run(IProgressMonitor monitor) { - while (!tilesToRetrieve.isEmpty()) { - GridMemoryBasedTileSet tile = tilesToRetrieve.poll(); - if (tile != null) { - tile.preloadDataObject(); - } - } - - return Status.OK_STATUS; - } - - public void retrieve(GridMemoryBasedTileSet mbts) { - tilesToRetrieve.add(mbts); - if (this.getState() != Job.RUNNING) { - this.schedule(); - } - } - } - - private final DataRetrievalJob dataRetriever = new DataRetrievalJob(); - - /** - * Constructor - */ - public GridResource(GridResourceData data, LoadProperties props) { - super(data, props); - data.addChangeListener(this); - numLevels = 1; - tileSet = new HashMap>(); - reader = new WKTReader(); - dataTimes = new ArrayList(); - - ICombinedResourceData combinedResourceData = null; - - try { - combinedResourceData = getResourceData(); - } catch (ClassCastException e) { - // do nothing - } - - if (combinedResourceData != null) { - this.combineOperation = combinedResourceData.getCombineOperation(); - } - - GribRecord[] records = resourceData.getRecords(); - GribRecord emptyRecord = new GribRecord(); - synchronized (timeLock) { - for (int i = 0; i < records.length; i++) { - if (emptyRecord.equals(records[i])) { - // Don't add empty records - continue; - } - pdosToParse.add(records[i]); - } - } - - if (resourceData.getNameGenerator() == null) { - resourceData.setNameGenerator(new GridNameGenerator()); - if (resourceData.secondaryResourceData != null - && resourceData.secondaryResourceData.getNameGenerator() == null) { - resourceData.secondaryResourceData - .setNameGenerator(new GridNameGenerator()); - } - } - // Add in imaging Capability now - if (!this.hasCapability(ImagingCapability.class)) { - this.getCapability(ImagingCapability.class).setInterpolationState( - true); - this.getCapability(ImagingCapability.class).setBrightness(0.5f); - } - } - - protected GridMemoryBasedTileSet addRecord(GribRecord record) - throws VizException { - - Geometry curGeom; - GridMemoryBasedTileSet mbts = null; - - ISpatialObject spatialObj = record.getSpatialObject(); - curGeom = spatialObj.getGeometry(); - - Set lvlSet = new HashSet(); - if (levels != null) { - for (SingleLevel f : levels) { - lvlSet.add(f); - } - } - - if (baseTileCoverage == null) { - baseTileCoverage = curGeom; - - parameter = record.getModelInfo().getParameterName(); - parameterAbbrev = record.getModelInfo().getParameterAbbreviation(); - units = record.getModelInfo().getParameterUnit(); - - this.getCapability(DisplayTypeCapability.class) - .setAlternativeDisplayTypes( - FieldDisplayTypesFactory.getInstance() - .getDisplayTypes(parameterAbbrev)); - - levelUnits = record.getModelInfo().getLevelUnit(); - - gridCoverage = record.getModelInfo().getLocation(); - - Unit levelUnits = Unit.valueOf(this.levelUnits); - levelConverter = UnitConverter.IDENTITY; - if (levelUnits.isCompatible(SI.MILLI(NonSI.BAR))) { - this.levelUnits = "MB"; - levelConverter = levelUnits.getConverterTo(SI.MILLI(NonSI.BAR)); - } - - level = GridLevelTranslator.constructMatching(record); - if (level == null) { - throw new VizException("Unhandled layer type: " - + record.getModelInfo().getLevelName()); - } - - this.getCapability(ColorMapCapability.class).setColorMapParameters( - initColorMapParameters(record)); - } - - mbts = createTileSet(record, lvlSet, levelConverter); - mbts.setMapDescriptor(descriptor); - synchronized (timeLock) { - Set dateSet = tileSet.keySet(); - dataTimes.clear(); - Iterator dateIterator = dateSet.iterator(); - while (dateIterator.hasNext()) { - dataTimes.add(dateIterator.next()); - } - - Collections.sort(dataTimes); - } - - levels = new SingleLevel[lvlSet.size()]; - Iterator lvlIterator = lvlSet.iterator(); - for (int i = 0; i < levels.length; i++) { - levels[i] = lvlIterator.next(); - } - - Arrays.sort(levels); - - return mbts; - - } - - private GridMemoryBasedTileSet createTileSet(GribRecord record, - Set lvlSet, UnitConverter levelConverter) - throws VizException { - DataTime dataTime = record.getDataTime(); - Map tilemap = null; - synchronized (timeLock) { - tilemap = tileSet.get(dataTime); - if (tilemap == null) { - tilemap = new HashMap(); - tileSet.put(dataTime, tilemap); - } - } - float convertedLevel = (float) levelConverter.convert(record - .getModelInfo().getLevelOneValue()); - - SingleLevel l = GridLevelTranslator.constructMatching(record); - GridMemoryBasedTileSet mts = null; - if (tilemap.containsKey(convertedLevel)) { - mts = tilemap.remove(convertedLevel); - mts.dispose(); - } - Integer baseTilesKey = record.getModelInfo().getLocation().getId(); - GridMemoryBasedTileSet commonTile = baseTiles.get(baseTilesKey); - mts = createTile(record, commonTile); - - if (commonTile == null) { - baseTiles.put(baseTilesKey, mts); - } - - lvlSet.add(l); - if (levelUnits.equals("MB")) { - mts.setElevation(Controller.ptozsa(convertedLevel)); - l.setType(Level.LevelType.PRESSURE); - } else { - mts.setElevation(convertedLevel); - } - tilemap.put(convertedLevel, mts); - - return mts; - } - - public GridMemoryBasedTileSet createTile(GribRecord record, - GridMemoryBasedTileSet commonTile) throws VizException { - - if (commonTile != null) { - return new GridMemoryBasedTileSet(record.getDataURI(), "Data", - commonTile, conversion, record); - } - - boolean reproject = false; - GridGeometry2D gridGeometry2D = record.getModelInfo().getLocation() - .getGridGeometry(); - GridCoverage location = record.getModelInfo().getLocation(); - if (location != null && location.getSpacingUnit().equals("degree")) { - double dx = location.getDx(); - Integer nx = location.getNx(); - if (dx * nx >= 360) { - reproject = true; - } - } - if (reproject == true) { - try { - gridGeometry2D = GridGeometry2D.wrap(MapUtil.reprojectGeometry( - gridGeometry2D, descriptor.getGridGeometry() - .getEnvelope(), false, 2)); - } catch (Exception e) { - statusHandler.handle(Priority.PROBLEM, - "Unable to reproject image:" + e.getLocalizedMessage(), - e); - } - } - GridMemoryBasedTileSet mbts = new GridMemoryBasedTileSet( - record.getDataURI(), "Data", numLevels, 512, gridGeometry2D, - this, conversion, PixelInCell.CELL_CORNER, record, viewType); - return mbts; - } - - @Override - public LegendParameters getLegendParameters() { - LegendParameters legendParams = new LegendParameters(); - legendParams.model = resourceData.getModelInfo(); - legendParams.unit = units; - legendParams.type = "Img"; - - legendParams.dataTime = descriptor.getFramesInfo().getTimeForResource( - this); - - return legendParams; - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.core.rsc.AbstractVizResource#disposeInternal() - */ - @Override - protected void disposeInternal() { - synchronized (timeLock) { - for (Map.Entry> set : tileSet - .entrySet()) { - for (Map.Entry tile : set - .getValue().entrySet()) { - tile.getValue().dispose(); - } - } - } - } - - @Override - protected void initInternal(IGraphicsTarget target) throws VizException { - synchronized (timeLock) { - this.target = target; - - if (pdosToParse.size() > 0) { - condensePDOs(); - for (PluginDataObject pdo : pdosToParse) { - createTile(pdo); - } - pdosToParse.clear(); - } - - boolean combineResources = combineOperation != CombineOperation.NONE; - - viewType = target.getViewType(); - Map> combinedSet = new HashMap>(); - for (Map.Entry baseTileEntry : baseTiles - .entrySet()) { - GridMemoryBasedTileSet baseTile = baseTileEntry.getValue(); - baseTile.setMapDescriptor(descriptor); - baseTile.init(target); - if (combineResources && !baseTile.isCombined()) { - Entry tileSetRef = null; - // Need to find the reference in order to update the object - // when - // it comes back as a new combined object - for (Map.Entry> set : tileSet - .entrySet()) { - for (Map.Entry tile : set - .getValue().entrySet()) { - if (tile.getValue().getDataTime() - .equals(baseTile.getDataTime())) { - tileSetRef = tile; - break; - } - } - if (tileSetRef != null) { - break; - } - } - - GridMemoryBasedTileSet combinedResourceData = combineResourceData(baseTile); - if (tileSetRef != null) { - tileSetRef.setValue(combinedResourceData); - } - - baseTileEntry.setValue(combinedResourceData); - } - } - DataTime[] primaryDataTimes = tileSet.keySet().toArray( - new DataTime[0]); - for (DataTime primaryDataTime : primaryDataTimes) { - Map map = tileSet - .get(primaryDataTime); - if (map != null) { - for (Map.Entry tile : map - .entrySet()) { - if (baseTiles.values().contains(tile.getValue())) { - if (combineResources) { - Map map2 = new HashMap(); - map2.put(tile.getKey(), tile.getValue()); - combinedSet.put(primaryDataTime, map2); - } - continue; - } - - tile.getValue().init(target); - - if (!tile.getValue().isCombined()) { - GridMemoryBasedTileSet combinedResourceData = combineResourceData(tile - .getValue()); - Map map2 = new HashMap(); - map2.put(tile.getKey(), combinedResourceData); - combinedSet.put(primaryDataTime, map2); - } - } - } - } - if (!combinedSet.isEmpty()) { - tileSet = combinedSet; - List newDataTimes = new ArrayList(); - - for (Entry> entry : combinedSet - .entrySet()) { - newDataTimes.add(entry.getKey()); - } - Collections.sort(newDataTimes); - dataTimes = newDataTimes; - } - } - } - - /** - * Condense the PDOs to one pdo per level per DataTime based on - * the gridVersion. - */ - private void condensePDOs() { - Map>> dateMap = new HashMap>>(); - List newList = new ArrayList(); - - for (PluginDataObject pdo : pdosToParse) { - if (pdo instanceof RequestableDataRecord) { - String level = null; - if (!dateMap.containsKey(pdo.getDataTime())) { - Map> levelMap = new HashMap>(); - - RequestableDataRecord rdr = (RequestableDataRecord) pdo; - level = rdr.getModelInfo().getLevel().getLevelInfo(); - levelMap.put(level, new ArrayList()); - dateMap.put(pdo.getDataTime(), levelMap); - } - - Map> levelsMap = dateMap.get(pdo - .getDataTime()); - String lvl = ((RequestableDataRecord) pdo).getModelInfo() - .getLevelInfo(); - if (!levelsMap.containsKey(lvl)) { - levelsMap.put(lvl, new ArrayList()); - } - levelsMap.get(lvl).add(pdo); - } - } - - // loop over each date - for (DataTime time : dateMap.keySet()) { - Map> levelMap = dateMap.get(time); - - // loop over each level - for (String key : levelMap.keySet()) { - List pdos = levelMap.get(key); - - PluginDataObject maxVersionedPdo = null; - int maxVersion = -1; - - // loop over all the pdos for this level - for (PluginDataObject pdo : pdos) { - RequestableDataRecord rdr = (RequestableDataRecord) pdo; - int version = ((GribRecord) rdr).getGridVersion(); - if (version > maxVersion) { - maxVersion = version; - maxVersionedPdo = pdo; - } - } - - newList.add(maxVersionedPdo); - } - } - - if (!newList.isEmpty()) { - pdosToParse.clear(); - pdosToParse.addAll(newList); - } - } - - /** - * Combine the given tiles sets - * - * @param gridMemoryBasedTileSet - * @param gridMemoryBasedTileSet2 - * @param dataTime - */ - private GridMemoryBasedTileSet combineResourceData( - GridMemoryBasedTileSet sourceTileSet) { - - GridCoverage sourceCoverage = gridCoverage; - PluginDataObject sourcePdo = sourceTileSet.getPluginDataObject(); - if (!(sourcePdo instanceof CombinedGribRecord)) { - return sourceTileSet; - } - GribModel modelInfo = ((CombinedGribRecord) sourcePdo) - .getSecondaryGribRecord().getModelInfo(); - GridCoverage targetCoverage = modelInfo.getLocation(); - Unit targetUnits = modelInfo.getParameterUnitObject(); - - try { - IDataRecord[] sourceData = DataCubeContainer - .getDataRecord(((CombinedGribRecord) sourcePdo) - .getPrimaryGribRecord()); - IDataRecord[] targetData = DataCubeContainer - .getDataRecord(((CombinedGribRecord) sourcePdo) - .getSecondaryGribRecord()); - FloatDataRecord sourceDataRecord = (FloatDataRecord) sourceData[0]; - FloatDataRecord targetDataRecord = (FloatDataRecord) targetData[0]; - GridGeometry2D newTarget = targetCoverage.getGridGeometry(); - float primaryMin = getDataMin(sourceDataRecord); - float primaryMax = getDataMax(sourceDataRecord); - float secondaryMin = getDataMin(targetDataRecord); - float secondaryMax = getDataMax(targetDataRecord); - - if (sourceCoverage.equals(targetCoverage)) { - diffData(sourceDataRecord, targetDataRecord, primaryMin, - primaryMax, secondaryMin, secondaryMax, targetUnits); - sourceTileSet = new GridMemoryBasedTileSet( - sourcePdo.getDataURI(), "Data", numLevels, 512, - newTarget, this, conversion, PixelInCell.CELL_CORNER, - ((GribRecord) sourcePdo), viewType); - sourceTileSet.setMapDescriptor(descriptor); - sourceTileSet.init(target); - sourceTileSet.setDataRecord(sourceDataRecord, 0); - sourceTileSet.setCombined(true); - this.updateColorMap(sourceTileSet); - - return sourceTileSet; - } - double sourcePixeWidth = getPixelWidth( - sourceCoverage.getGridGeometry(), descriptor); - double targetPixeWidth = getPixelWidth( - targetCoverage.getGridGeometry(), descriptor); - if (sourcePixeWidth >= targetPixeWidth) { - double sizeMultiplier = sourcePixeWidth / targetPixeWidth; - sizeMultiplier = sizeMultiplier > 4 ? 1 : 4; - long[] newSizes = { - (long) (targetDataRecord.getSizes()[0] * sizeMultiplier), - (long) (targetDataRecord.getSizes()[1] * sizeMultiplier) }; - newTarget = MapUtil.createFineIntersectingGeometry( - sourceCoverage.getGridGeometry().getEnvelope(), - targetCoverage.getGridGeometry().getEnvelope(), - newSizes); - } else { - double sizeMultiplier = targetPixeWidth / sourcePixeWidth; - sizeMultiplier = sizeMultiplier > 4 ? 1 : 4; - long[] newSizes = { - (long) (sourceDataRecord.getSizes()[0] * sizeMultiplier), - (long) (sourceDataRecord.getSizes()[1] * sizeMultiplier) }; - newTarget = MapUtil.createFineIntersectingGeometry( - targetCoverage.getGridGeometry().getEnvelope(), - sourceCoverage.getGridGeometry().getEnvelope(), - newSizes); - } - - targetDataRecord = remapGrid(targetDataRecord, newTarget, - targetCoverage.getGridGeometry()); - sourceDataRecord = remapGrid(sourceDataRecord, newTarget, - sourceCoverage.getGridGeometry()); - - diffData(sourceDataRecord, targetDataRecord, primaryMin, - primaryMax, secondaryMin, secondaryMax, targetUnits); - - sourceTileSet = new GridMemoryBasedTileSet(sourcePdo.getDataURI(), - "Data", numLevels, 512, newTarget, this, conversion, - PixelInCell.CELL_CORNER, ((GribRecord) sourcePdo), viewType); - sourceTileSet.setMapDescriptor(descriptor); - sourceTileSet.init(target); - sourceTileSet.setDataRecord(sourceDataRecord, 0); - sourceTileSet.setCombined(true); - this.updateColorMap(sourceTileSet); - - return sourceTileSet; - - } catch (VizException e) { - throw new RuntimeException( - "Unable to remap secondary resource grid data from " - + sourceCoverage.getName() + " to" - + targetCoverage.getName(), e); - } catch (Exception e) { - throw new RuntimeException( - "Unable to remap secondary resource grid data from " - + sourceCoverage.getName() + " to" - + targetCoverage.getName(), e); - } - } - - public double getPixelWidth(GridGeometry2D gridGeometry, - IMapDescriptor descriptor) throws VizException { - double pixelWidth = 0; - try { - double xCenter = gridGeometry.getGridRange().getSpan(0) / 2.0; - double yCenter = gridGeometry.getGridRange().getSpan(1) / 2.0; - - double[] input = new double[] { xCenter, yCenter, xCenter + 1, - yCenter }; - double[] output = new double[input.length]; - - MathTransform mathTransform = gridGeometry - .getGridToCRS(PixelInCell.CELL_CORNER); - // convert the point s to lat/lon - mathTransform.transform(input, 0, output, 0, input.length / 2); - MathTransform localProjToLL = CRS.findMathTransform( - gridGeometry.getCoordinateReferenceSystem(), - DefaultGeographicCRS.WGS84); - localProjToLL.transform(output, 0, output, 0, 2); - - double[] p1 = descriptor.worldToPixel(new double[] { output[0], - output[1] }); - double[] p2 = descriptor.worldToPixel(new double[] { output[2], - output[3] }); - - // compute the number of map pixels per tile pixel - pixelWidth = Math.abs(p2[0] - p1[0]); - } catch (org.opengis.referencing.operation.NoninvertibleTransformException e) { - throw new VizException(e); - - } catch (TransformException e) { - throw new VizException(e); - - } catch (InvalidGridGeometryException e) { - throw new VizException(e); - - } catch (FactoryException e) { - throw new VizException(e); - } - return pixelWidth; - } - - public float getDataMin(FloatDataRecord dataRecord) { - float dataMin = Float.POSITIVE_INFINITY; - float[] floatData = dataRecord.getFloatData(); - for (int i = 0; i < floatData.length; i++) { - if (!Float.isNaN(floatData[i]) && floatData[i] != -999999) { - dataMin = Math.min(dataMin, floatData[i]); - } - } - return dataMin; - } - - public float getDataMax(FloatDataRecord dataRecord) { - float dataMax = Float.NEGATIVE_INFINITY; - - float[] floatData = dataRecord.getFloatData(); - for (int i = 0; i < floatData.length; i++) { - if (!Float.isNaN(floatData[i]) && floatData[i] != -999999) { - dataMax = Math.max(dataMax, floatData[i]); - } - } - - return dataMax; - - } - - private FloatDataRecord remapGrid(FloatDataRecord targetDataRecord, - GridGeometry2D newTarget, GeneralGridGeometry gridGeometry) - throws VizException { - try { - GridGeometry2D remappedImageGeometry = newTarget; - NearestNeighborInterpolation interp = new NearestNeighborInterpolation(); - GridReprojection reproj = new GridReprojection(gridGeometry, - remappedImageGeometry); - float[] data = targetDataRecord.getFloatData(); - FloatArrayWrapper source = new FloatArrayWrapper(data, gridGeometry); - source.setValidRange(-9998, Double.POSITIVE_INFINITY); - FloatArrayWrapper dest = new FloatArrayWrapper( - remappedImageGeometry); - dest.setFillValue(-999999); - data = reproj.reprojectedGrid(interp, source, dest).getArray(); - FloatDataRecord remapGrid = (FloatDataRecord) targetDataRecord - .clone(); - remapGrid.setIntSizes(new int[] { - remappedImageGeometry.getGridRange2D().width, - remappedImageGeometry.getGridRange2D().height }); - remapGrid.setFloatData(data); - return remapGrid; - } catch (FactoryException e) { - throw new VizException(e); - } catch (TransformException e) { - throw new VizException(e); - } - } - - /** - * Subtracts the second parameter from the first. - * - * @param floatDataRecord1 - * @param floatDataRecord2 - * @param primaryMax - * @param primaryMin - * @param secondaryMax - * @param secondaryMin - * @param targetUnits - */ - private void diffData(FloatDataRecord floatDataRecord1, - FloatDataRecord floatDataRecord2, float primaryMin, - float primaryMax, float secondaryMin, float secondaryMax, - Unit targetUnits) { - if (this.styleRule != null) { - Unit primaryUnit = resourceData.getModelInfo() - .getParameterUnitObject(); - - UnitConverter primaryUnitConverter = primaryUnit - .getConverterTo(this.styleRule.getPreferences() - .getDisplayUnits()); - UnitConverter secondaryUnitConverter = targetUnits - .getConverterTo(this.styleRule.getPreferences() - .getDisplayUnits()); - - for (int i = 0; i < floatDataRecord2.getFloatData().length; i++) { - - float n1 = (float) primaryUnitConverter - .convert(floatDataRecord1.getFloatData()[i] < primaryMin - || floatDataRecord1.getFloatData()[i] > primaryMax ? Float.NaN - : floatDataRecord1.getFloatData()[i]); - // convert secondary data to primary - float n2 = (float) secondaryUnitConverter - .convert(floatDataRecord2.getFloatData()[i] < secondaryMin - || floatDataRecord2.getFloatData()[i] > secondaryMax ? Float.NaN - : floatDataRecord2.getFloatData()[i]); - if (combineOperation == CombineOperation.DIFFERENCE) { - floatDataRecord1.getFloatData()[i] = (float) primaryUnitConverter - .inverse().convert(n1 - n2); - } - } - } else { - for (int i = 0; i < floatDataRecord2.getFloatData().length; i++) { - - float n1 = floatDataRecord1.getFloatData()[i] == -999999 ? Float.NaN - : floatDataRecord1.getFloatData()[i]; - float n2 = floatDataRecord2.getFloatData()[i] == -999999 ? Float.NaN - : floatDataRecord2.getFloatData()[i]; - floatDataRecord1.getFloatData()[i] = (n1 - n2); - if (Float - .compare(floatDataRecord1.getFloatData()[i], Float.NaN) == 0) { - floatDataRecord1.getFloatData()[i] = -999999; - } - } - } - } - - /** - * Dynamically scale the color map based on the data in the given tileset - * - * @param gridMemoryBasedTileSet - */ - private void updateColorMap(GridMemoryBasedTileSet gridMemoryBasedTileSet) { - - ColorMapParameters colorParameters = this.getCapability( - ColorMapCapability.class).getColorMapParameters(); - - // set the min and max range from the tile data. increase the range - // approximately 5% larger - - colorParameters.setDataMin(Math.min( - gridMemoryBasedTileSet.getDataMin(), - colorParameters.getDataMin()) * 1.022f); - colorParameters.setDataMax(Math.max( - gridMemoryBasedTileSet.getDataMax(), - gridMemoryBasedTileSet.getDataMax()) * 1.022f); - colorParameters.setColorMapMin(colorParameters.getDataMin()); - colorParameters.setColorMapMax(colorParameters.getDataMax()); - - float[] colorBarIntervals = new float[5]; - - float increment = (colorParameters.getDataMax() - colorParameters - .getDataMin()) / 4; - - for (int i = 0; i < colorBarIntervals.length; i++) { - if (conversion != null) { - colorBarIntervals[i] = (float) conversion - .convert((colorParameters.getDataMin() * 0.975) - + (increment * i)); - } else { - colorBarIntervals[i] = (float) (colorParameters.getDataMin() * 0.975) - + (increment * i); - } - } - - colorParameters.setColorBarIntervals(colorBarIntervals); - - } - - @Override - protected void paintInternal(IGraphicsTarget target, - PaintProperties paintProps) throws VizException { - this.target = target; - - DataTime time = paintProps.getDataTime(); - Map tileGroup = tileSet.get(time); - if (tileGroup == null) { - return; - } - float actualLevel = displayedLevel; - GridMemoryBasedTileSet tile = tileGroup.get(displayedLevel); - if (tile == null) { - // TODO cleanup - actualLevel = tileGroup.keySet().iterator().next(); - tile = tileGroup.get(actualLevel); - } - - if (tile == null) { - return; - } - - if (CombineOperation.DIFFERENCE.equals(combineOperation) - && !tile.isCombined()) { - tile = combineResourceData(tile); - tileGroup.put(actualLevel, tile); - if (tile.isCombined()) { - tile.paint(target, paintProps); - } - } else { - tile.paint(target, paintProps); - } - } - - @Override - public void setDescriptor(MapDescriptor descriptor) { - this.descriptor = descriptor; - synchronized (timeLock) { - for (Map.Entry> set : tileSet - .entrySet()) { - for (Map.Entry tile : set - .getValue().entrySet()) { - tile.getValue().setMapDescriptor(this.descriptor); - } - } - } - } - - @Override - public void project(CoordinateReferenceSystem mapData) throws VizException { - boolean reproject = false; - if (gridCoverage != null - && gridCoverage.getSpacingUnit().equals("degree")) { - double dx = gridCoverage.getDx(); - Integer nx = gridCoverage.getNx(); - if (dx * nx >= 360) { - reproject = true; - } - } - if (reproject) { - synchronized (timeLock) { - // If we are reprojecting to screen space, clear all tiles - for (Map.Entry> set : tileSet - .entrySet()) { - for (Map.Entry tile : set - .getValue().entrySet()) { - tile.getValue().dispose(); - pdosToParse.add(tile.getValue().getPluginDataObject()); - } - } - tileSet.clear(); - baseTiles.clear(); - if (pdosToParse.size() > 0) { - for (PluginDataObject pdo : pdosToParse) { - createTile(pdo); - } - pdosToParse.clear(); - } - } - } else { - for (GridMemoryBasedTileSet tile : baseTiles.values()) { - tile.reproject(); - } - for (Map.Entry> set : tileSet - .entrySet()) { - for (Map.Entry tile : set - .getValue().entrySet()) { - tile.getValue().reproject(); - } - } - } - - } - - @Override - public String inspect(ReferencedCoordinate coord) throws VizException { - - Map map = tileSet.get(descriptor - .getFramesInfo().getTimeForResource(this)); - if (map == null) { - return NO_DATA; - } - float actualLevel = displayedLevel; - GridMemoryBasedTileSet tile = map.get(displayedLevel); - if (tile == null) { - // TODO cleanup - actualLevel = map.keySet().iterator().next(); - tile = map.get(actualLevel); - } - - if (tile == null) { - return NO_DATA; - } - - if (!tile.hasDataPreloaded()) { - tile.preloadDataObject(); - } - if (!tile.hasDataPreloaded()) { - return NO_DATA; - } - - Coordinate latLon; - try { - latLon = coord.asLatLon(); - } catch (Exception e) { - throw new VizException("Error transforming coordinate to lat/lon", - e); - } - - GridCoverage gc = this.getResourceData().getModelInfo().getLocation(); - if (gc instanceof LatLonGridCoverage) { - LatLonGridCoverage llgc = (LatLonGridCoverage) gc; - Envelope2D envelope = llgc.getGridGeometry().getEnvelope2D(); - latLon = (Coordinate) latLon.clone(); - try { - // Try really hard to get this within the gridRange - Coordinate projectedLatLon = JTS.transform(latLon, - new Coordinate(), MapUtil - .getTransformFromLatLon(envelope - .getCoordinateReferenceSystem())); - if (projectedLatLon.x < envelope.x) { - latLon.x += 360.0; - } else if (projectedLatLon.x > envelope.x + envelope.width) { - latLon.x -= 360.0; - } - } catch (Exception e) { - throw new VizException(e); - } - - } - - double tileCoordinateValue = Double.NaN; - if (getCapability(ImagingCapability.class).isInterpolationState()) { - FloatArrayWrapper source = new FloatArrayWrapper( - tile.getLoadedData(), tile.getGridGeometry()); - source.setValidRange(-9998, Double.POSITIVE_INFINITY); - GridSampler sampler = new GridSampler(source, - new BilinearInterpolation()); - try { - Coordinate pixel = coord.asPixel(tile.getGridGeometry()); - tileCoordinateValue = sampler.sample(pixel.x, pixel.y); - UnitConverter converter = getCapability( - ColorMapCapability.class).getColorMapParameters() - .getDataToDisplayConverter(); - if (converter != null) { - tileCoordinateValue = converter - .convert(tileCoordinateValue); - } - } catch (Exception e) { - throw new VizException(e); - } - } else { - double[] envelopeCoordinates = new double[2]; - double[] valueCoordinate = new double[2]; - tile.getImageCoordinates(latLon, envelopeCoordinates, - valueCoordinate); - - tileCoordinateValue = tile.getTileCoordinateValue(false, - envelopeCoordinates, valueCoordinate); - - } - if (Double.isNaN(tileCoordinateValue)) { - return NO_DATA; - } - - // check if data mapping preferences exist - DataMappingPreferences dataMapping = getCapability( - ColorMapCapability.class).getColorMapParameters() - .getDataMapping(); - if (dataMapping != null) { - // if the pixel value matches the data mapping entry use that - // label instead - String label = dataMapping - .getLabelValueForDataValue(tileCoordinateValue); - if (label != null) { - return label; - } - } - - return sampleFormat.format(tileCoordinateValue) + units; - } - - public float interpolateBiCubic(Coordinate latLon, - GridMemoryBasedTileSet tile) throws VizException { - - double[] envelopeCoordinates = new double[2]; - double[] imageCoordinates = new double[2]; - tile.getImageCoordinates(latLon, envelopeCoordinates, imageCoordinates); - - double y = imageCoordinates[1] - 1; - float[][] gridVals = new float[4][4]; - float missing = 1.0f; - for (int i = 0; i < 4; i++) { - double x = imageCoordinates[0] - 1; - for (int j = 0; j < 4; j++) { - if (y < 0 || y > tile.getDims()[0][1] - 1 || x < 0 - || x > tile.getDims()[0][0] - 1) { - gridVals[i][j] = -999999f; - missing -= .125; - } else { - double[] coordinate = new double[] { x, y }; - gridVals[i][j] = (float) tile.getTileCoordinateValue(false, - envelopeCoordinates, coordinate); - } - x += 1; - } - y += 1; - } - Interpolation interpolation = Interpolation - .getInstance(Interpolation.INTERP_BICUBIC); - float xfrac = (float) (imageCoordinates[0] - Math - .floor(imageCoordinates[0])); - float yfrac = (float) (imageCoordinates[1] - Math - .floor(imageCoordinates[1])); - float val = interpolation.interpolate(gridVals, xfrac, yfrac); - if (missing > 0.25 && !Double.isNaN(val)) { - val = val / missing; - return val; - } - return Float.NaN; - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.rsc.capabilities.IVertSeqResource#getVerticalLevels - * () - */ - public SingleLevel[] getVerticalLevels() { - return levels; - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.rsc.capabilities.IVertSeqResource#getVerticalLevelType - * () - */ - public Level.LevelType getVerticalLevelType() { - return level.getType(); - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.rsc.capabilities.IVertSeqResource#setVerticalLevel - * (float) - */ - public void setVerticalLevel(SingleLevel level) { - displayedLevel = (float) level.getValue(); - } - - @Override - public void remove(DataTime dataTime) { - synchronized (timeLock) { - Map ts = tileSet.remove(dataTime); - if (ts == null) { - return; - } - - for (Map.Entry tile : ts.entrySet()) { - tile.getValue().dispose(); - } - Set dateSet = tileSet.keySet(); - dataTimes.clear(); - Iterator dateIterator = dateSet.iterator(); - while (dateIterator.hasNext()) { - dataTimes.add(dateIterator.next()); - } - - Collections.sort(dataTimes); - } - } - - @Override - public void resourceChanged(ChangeType type, Object object) { - if (type.equals(ChangeType.DATA_UPDATE)) { - PluginDataObject[] pdos = (PluginDataObject[]) object; - synchronized (timeLock) { - for (PluginDataObject pdo : pdos) { - - if (pdo != null) { - if (CombineOperation.DIFFERENCE - .equals(combineOperation) - && !(pdo instanceof CombinedGribRecord)) { - // Do nothing, timematcher will take care of it. - } else { - if (target != null) { - createTile(pdo); - } else { - pdosToParse.add(pdo); - } - } - } - } - } - } else if (type.equals(ChangeType.CAPABILITY)) { - if (object instanceof ImagingCapability) { - // TODO: check if interpolation state really changed - try { - if (descriptor != null) { - project(descriptor.getGridGeometry() - .getCoordinateReferenceSystem()); - } - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error updating grid resource imaging", e); - } - } - } - - issueRefresh(); - } - - private void createTile(PluginDataObject pdo) { - GridMemoryBasedTileSet mbts; - try { - mbts = addRecord((GribRecord) pdo); - if (mbts != null) { - mbts.setMapDescriptor(descriptor); - mbts.init(target); - dataRetriever.retrieve(mbts); - } - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error updating grid resource", e); - } - } - - /* - * (non-Javadoc) - * - * @see com.raytheon.uf.viz.core.rsc.AbstractVizResource#getName() - */ - @Override - public String getName() { - - if (combineOperation != null - && combineOperation != CombineOperation.NONE) { - return getCombinedName(); - } else { - return super.getName(); - } - - } - - private String getCombinedName() { - GridNameGenerator secondaryGenerator = (GridNameGenerator) resourceData.secondaryResourceData - .getNameGenerator(); - if (secondaryGenerator == null) { - secondaryGenerator = new GridNameGenerator(); - } - String secondaryName; - try { - LegendParameters legendParams = new LegendParameters(); - GribRecord secondaryGribRecord = ((CombinedGribRecord) resourceData.records[0]) - .getSecondaryGribRecord(); - GribModel modelInfo = secondaryGribRecord.getModelInfo(); - modelInfo.getParameterAbbreviation(); - String secondaryUnits = modelInfo.getParameterUnit(); - ParamLevelMatchCriteria match = new ParamLevelMatchCriteria(); - match.setLevel(GridLevelTranslator - .constructMatching(secondaryGribRecord)); - match.setParameterName(Arrays.asList(modelInfo - .getParameterAbbreviation())); - match.setCreatingEntityNames(Arrays.asList(modelInfo.getModelName())); - StyleRule secondaryStyleRule = StyleManager.getInstance() - .getStyleRule(StyleType.IMAGERY, match); - if (secondaryStyleRule != null - && secondaryStyleRule.getPreferences() - .getDisplayUnitLabel() != null) { - secondaryUnits = secondaryStyleRule.getPreferences() - .getDisplayUnitLabel(); - } - legendParams.model = modelInfo; - legendParams.unit = secondaryUnits; - legendParams.dataTime = descriptor.getFramesInfo() - .getTimeForResource(this); - legendParams.type = "Img"; - secondaryName = secondaryGenerator.getName(legendParams, - resourceData.secondaryResourceData); - } catch (Exception e) { - return null; - } - - return CombineUtil.getName(super.getName(), secondaryName, - combineOperation); - } - - /** - * Initialize the colormap parameters given the record, units and model - */ - protected ColorMapParameters initColorMapParameters(GribRecord record) - throws VizException { - String model = "" + record.getModelInfo().getModelName(); - Unit gridUnits = record.getModelInfo().getParameterUnitObject(); - - ColorMapParameters parameters = null; - PersistedParameters persisted = null; - IColorMap mapToUse = null; - String colorMapName = null; - if (hasCapability(ColorMapCapability.class)) { - parameters = getCapability(ColorMapCapability.class) - .getColorMapParameters(); - if (parameters != null) { - mapToUse = parameters.getColorMap(); - colorMapName = parameters.getColorMapName(); - persisted = parameters.getPersisted(); - } - } - if (record instanceof CombinedGribRecord) { - parameters = ColorMapParameterFactory.build( - ((CombinedGribRecord) record).getPrimaryGribRecord(), - parameterAbbrev, gridUnits, level, model); - } else { - parameters = ColorMapParameterFactory.build(record, - parameterAbbrev, gridUnits, level, model); - } - - // These three ifs attempt to bring data within range of 16bit - // float, - // if 32 bit floats are passed to the graphics cards this can be - // removed and will improve performance for cases where this hits, - // which should be very few(only a few derived parameters) - Unit newUnits = null; - if (Math.abs(parameters.getDataMax()) > 65500) { - // 65500 is the maximum size for 16 bit floats - // newUnits = gridUnits.times(Math.abs(parameters.getDataMax())) - // .divide(65500); - - // just convert all the way - newUnits = parameters.getDisplayUnit(); - } - if (Math.abs(parameters.getDataMin()) != 0.0 - && Math.abs(parameters.getDataMin()) < 0.000061) { - // 0.000061 is very close to the minimum size for normal 16 bit - // floats. The mimumum for subnormal numbers is near - // 0.0000000596 which allows a larger range but causes much more - // loss of precision - // newUnits = gridUnits.times(Math.abs(parameters.getDataMin())) - // .divide(0.000061); - - // just convert all the way - newUnits = parameters.getDisplayUnit(); - } - - if (newUnits != null) { - UnitConverter converter = gridUnits.getConverterTo(newUnits); - parameters.setDataMin((float) converter.convert(parameters - .getDataMin())); - parameters.setDataMax((float) converter.convert(parameters - .getDataMax())); - parameters.setColorMapMin((float) converter.convert(parameters - .getColorMapMin())); - parameters.setColorMapMax((float) converter.convert(parameters - .getColorMapMax())); - parameters.setDataUnit(newUnits); - parameters.setImageUnit(newUnits); - } - - if (mapToUse == null) { - // No IColorMap specified - if (colorMapName == null) { - // No name specified, check current name from - // ColorMapParametersFactory - colorMapName = parameters.getColorMapName(); - if (colorMapName == null) { - // No name, default - colorMapName = "Grid/gridded data"; - } - } - // Load the color map - mapToUse = ColorMapLoader.loadColorMap(colorMapName); - } - // Set colormap and name - parameters.setColorMap(mapToUse); - parameters.setColorMapName(colorMapName); - - ParamLevelMatchCriteria match = new ParamLevelMatchCriteria(); - match.setLevel(level); - match.setParameterName(Arrays.asList(parameterAbbrev)); - match.setCreatingEntityNames(Arrays.asList(model)); - styleRule = StyleManager.getInstance().getStyleRule(StyleType.IMAGERY, - match); - // Pull the parameters out and use them - if (parameters.getDisplayUnit() != null) { - - if (gridUnits.isCompatible(parameters.getDisplayUnit())) { - - conversion = gridUnits.getConverterTo(parameters - .getDisplayUnit()); - } else { - conversion = UnitConverter.IDENTITY; - String message = "Data unit: " + gridUnits - + " cannot be converted to desired unit: " - + parameters.getDisplayUnit() - + " Data displayed will be displayed with unit: " - + gridUnits; - statusHandler.handle(Priority.VERBOSE, message); - } - - if (styleRule != null - && styleRule.getPreferences().getDisplayUnitLabel() != null) { - units = styleRule.getPreferences().getDisplayUnitLabel(); - } - } - if (this.styleRule != null - && this.styleRule.getPreferences() instanceof ImagePreferences) { - boolean interpolationState = ((ImagePreferences) this.styleRule - .getPreferences()).isInterpolate(); - this.getCapability(ImagingCapability.class).setInterpolationState( - interpolationState); - } - - if (persisted != null) { - // Restore any persisted data - parameters.applyPersistedParameters(persisted); - } - return parameters; - } - -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResourceData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResourceData.java index 32dd1b967d..35329b69cb 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResourceData.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridResourceData.java @@ -31,14 +31,12 @@ import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.CombinedGribRecord; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.IDataRecord; -import com.raytheon.uf.common.time.CombinedDataTime; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; import com.raytheon.uf.viz.core.drawables.IDescriptor; @@ -47,24 +45,20 @@ import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData; import com.raytheon.uf.viz.core.rsc.AbstractResourceData; import com.raytheon.uf.viz.core.rsc.AbstractVizResource; -import com.raytheon.uf.viz.core.rsc.DisplayType; import com.raytheon.uf.viz.core.rsc.IResourceGroup; import com.raytheon.uf.viz.core.rsc.LoadProperties; import com.raytheon.uf.viz.core.rsc.ResourceList; -import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability; import com.raytheon.uf.viz.d2d.core.map.IDataScaleResource; -import com.raytheon.uf.viz.d2d.core.time.LoadMode; -import com.raytheon.uf.viz.d2d.core.time.TimeMatcher; import com.raytheon.viz.core.rsc.ICombinedResourceData; import com.raytheon.viz.grid.inv.GribDataCubeAlertMessageParser; import com.raytheon.viz.grid.inv.GridInventory; -import com.raytheon.viz.grid.rsc.general.D2DGribGridResource; +import com.raytheon.viz.grid.rsc.general.D2DGridResource; import com.raytheon.viz.grid.rsc.general.DifferenceGridResourceData; import com.raytheon.viz.grid.util.TiltRequest; import com.vividsolutions.jts.geom.Coordinate; /** - * Resource data for grids from GribRecords + * Resource data for grids from GridRecords * *
  * 
@@ -82,7 +76,7 @@ import com.vividsolutions.jts.geom.Coordinate;
 public class GridResourceData extends AbstractRequestableResourceData implements
         ICombinedResourceData {
 
-    protected GribRecord[] records;
+    protected GridRecord[] records;
 
     @XmlElement
     protected GridResourceData secondaryResourceData;
@@ -99,10 +93,6 @@ public class GridResourceData extends AbstractRequestableResourceData implements
     @XmlAttribute
     protected boolean spatial = false;
 
-    private DataTime[] dataTimes;
-
-    private GribModel modelInfo;
-
     public GridResourceData() {
         setAlertParser(new GribDataCubeAlertMessageParser());
     }
@@ -110,14 +100,8 @@ public class GridResourceData extends AbstractRequestableResourceData implements
     @Override
     public AbstractVizResource construct(LoadProperties loadProperties,
             IDescriptor descriptor) throws VizException {
-        DisplayType displayType = loadProperties.getCapabilities()
-                .getCapability(this, DisplayTypeCapability.class)
-                .getDisplayType();
-        if (secondaryResourceData != null
-                && (displayType == DisplayType.BARB
-                        || displayType == DisplayType.ARROW
-                        || displayType == DisplayType.DUALARROW || displayType == DisplayType.STREAMLINE)) {
-            // GribGridResource does not support diff through a secondary
+        if (secondaryResourceData != null) {
+            // GridResource does not support diff through a secondary
             // resource, instead it must use a DifferenceGridResource.
             ResourcePair one = new ResourcePair();
             one.setResourceData(this);
@@ -136,42 +120,25 @@ public class GridResourceData extends AbstractRequestableResourceData implements
     protected AbstractVizResource constructResource(
             LoadProperties loadProperties, PluginDataObject[] objects)
             throws VizException {
-        records = new GribRecord[objects.length];
+        records = new GridRecord[objects.length];
         for (int i = 0; i < objects.length; i++) {
-            records[i] = (GribRecord) objects[i];
-        }
-        switch (loadProperties.getCapabilities()
-                .getCapability(this, DisplayTypeCapability.class)
-                .getDisplayType()) {
-        case IMAGE:
-            sampling = sampling == null ? true : sampling;
-            return new GridResource(this, loadProperties);
-        case ICON:
-            sampling = sampling == null ? false : sampling;
-            return new GridIconResource(this, loadProperties);
-        case BARB:
-            sampling = sampling == null ? false : sampling;
-        case ARROW:
-        case DUALARROW:
-        case STREAMLINE:
-            // TODO eventually contour and image should also use
-            // D2DGribGridResource so that all data requesta nd transform of
-            // grib data in D2D is in one location. There are only a few
-            // products that do not work correctly, contours of vector
-            // direction, and data mapped images.
-            sampling = sampling == null ? true : sampling;
-            return new D2DGribGridResource(this, loadProperties);
-        case CONTOUR:
-        default:
-            sampling = sampling == null ? false : sampling;
-            return new GridVectorResource(this, loadProperties);
+            if (objects[i] instanceof GridRecord) {
+                records[i] = (GridRecord) objects[i];
+            } else {
+                throw new IllegalArgumentException(
+                        "GridResourceData only supports data for the grid plugin, the "
+                                + objects[i].getPluginName()
+                                + " plugin is not supported.");
+            }
         }
+        sampling = sampling == null ? false : sampling;
+        return new D2DGridResource(this, loadProperties);
     }
 
     /**
      * @return the records
      */
-    public GribRecord[] getRecords() {
+    public GridRecord[] getRecords() {
         return records;
     }
 
@@ -179,7 +146,7 @@ public class GridResourceData extends AbstractRequestableResourceData implements
      * @param records
      *            the records to set
      */
-    public void setRecords(GribRecord[] records) {
+    public void setRecords(GridRecord[] records) {
         this.records = records;
     }
 
@@ -298,41 +265,13 @@ public class GridResourceData extends AbstractRequestableResourceData implements
     @Override
     public DataTime[] getAvailableTimes() throws VizException {
         if (!spatial) {
-            if (secondaryResourceData != null) {
-                DataTime[] secondaryTimes = secondaryResourceData
-                        .getAvailableTimes();
-                DataTime[] primaryTimes = super.getAvailableTimes();
-                if (primaryTimes == null || secondaryTimes == null) {
-                    return null;
-                }
-                if (primaryTimes.length > secondaryTimes.length) {
-                    secondaryTimes = TimeMatcher.doValTimOverlay(
-                            secondaryTimes, primaryTimes, 0,
-                            LoadMode.VALID_TIME_SEQ, null, 0.5F);
-
-                } else {
-                    primaryTimes = TimeMatcher.doValTimOverlay(primaryTimes,
-                            secondaryTimes, 0, LoadMode.VALID_TIME_SEQ, null,
-                            0.5F);
-
-                }
-                List availDataTimes = new ArrayList();
-                for (int i = 0; i < primaryTimes.length; i++) {
-                    if (primaryTimes[i] != null && secondaryTimes[i] != null) {
-                        availDataTimes.add(new CombinedDataTime(
-                                primaryTimes[i], secondaryTimes[i]));
-                    }
-                }
-                return availDataTimes.toArray(new DataTime[availDataTimes
-                        .size()]);
-            }
-
             return super.getAvailableTimes();
         }
 
         DataTime[] times = super.getAvailableTimes();
         Set levels = ((GridInventory) DataCubeContainer
-                .getInventory("grib")).getAvailableLevels(metadataMap);
+                .getInventory(GridConstants.GRID))
+                .getAvailableLevels(metadataMap);
         List timesWithLevels = new ArrayList();
         for (int i = 0; i < times.length; ++i) {
             for (Level l : levels) {
@@ -350,9 +289,6 @@ public class GridResourceData extends AbstractRequestableResourceData implements
     public PluginDataObject[] getLatestPluginDataObjects(DataTime[] desired,
             DataTime[] current) throws VizException {
         if (!spatial) {
-            if (secondaryResourceData != null) {
-                return getCombinedPluginDataObjects(desired, current);
-            }
             return super.getLatestPluginDataObjects(desired, current);
         }
         Set stripped = new HashSet(desired.length);
@@ -388,126 +324,27 @@ public class GridResourceData extends AbstractRequestableResourceData implements
             this.metadataMap.put(GridInventory.LEVEL_ONE_QUERY,
                     new RequestConstraint(levelValue.toString()));
         }
-        PluginDataObject[] objs;
-        if (secondaryResourceData != null) {
-            objs = getCombinedPluginDataObjects(desired, current);
-        } else {
-            objs = super.getLatestPluginDataObjects(
-                    stripped.toArray(new DataTime[0]), new DataTime[0]);
-        }
+        PluginDataObject[] objs = super.getLatestPluginDataObjects(
+                stripped.toArray(new DataTime[0]), new DataTime[0]);
         this.metadataMap = originalMetadataMap;
         for (PluginDataObject obj : objs) {
-            GribRecord record = (GribRecord) obj;
+            GridRecord record = (GridRecord) obj;
             DataTime time = obj.getDataTime().clone();
-            time.setLevelValue(record.getModelInfo().getLevelOneValue());
+            time.setLevelValue(record.getLevel().getLevelonevalue());
             obj.setDataTime(time);
         }
         return objs;
     }
 
-    private CombinedGribRecord[] getCombinedPluginDataObjects(
-            DataTime[] desired, DataTime[] current) throws VizException {
-
-        DataTime[] currentPrimaryDataTimes = new DataTime[current.length];
-        DataTime[] desiredPrimaryDataTimes = new DataTime[desired.length];
-
-        DataTime[] currentSecondaryDataTimes = new DataTime[current.length];
-        DataTime[] desiredSecondaryDataTimes = new DataTime[desired.length];
-
-        for (int i = 0; i < current.length; i++) {
-            if (!(current[i] instanceof CombinedDataTime)) {
-                current = dataTimes;
-                break;
-            }
-        }
-        for (int i = 0; i < desired.length; i++) {
-            if (!(desired[i] instanceof CombinedDataTime)) {
-                desired = getAvailableTimes();
-                break;
-            }
-        }
-
-        for (int i = 0; i < current.length; i++) {
-            currentPrimaryDataTimes[i] = ((CombinedDataTime) current[i])
-                    .getPrimaryDataTime();
-            currentSecondaryDataTimes[i] = ((CombinedDataTime) current[i])
-                    .getAdditionalDataTime();
-        }
-
-        for (int i = 0; i < desired.length; i++) {
-            desiredPrimaryDataTimes[i] = ((CombinedDataTime) desired[i])
-                    .getPrimaryDataTime();
-            desiredSecondaryDataTimes[i] = ((CombinedDataTime) desired[i])
-                    .getAdditionalDataTime();
-        }
-
-        PluginDataObject[] primaryPdos = super.getLatestPluginDataObjects(
-                desiredPrimaryDataTimes, currentPrimaryDataTimes);
-
-        secondaryResourceData.dataTimes = desiredSecondaryDataTimes;
-        PluginDataObject[] secondaryPdos = secondaryResourceData
-                .getLatestPluginDataObjects(desiredSecondaryDataTimes,
-                        currentSecondaryDataTimes);
-        // Combine
-        List combinedGribRecords = new ArrayList();
-        for (int i = 0; i < desired.length; i++) {
-            boolean found = false;
-            for (PluginDataObject primaryPdo : primaryPdos) {
-                if (found) {
-                    break;
-                }
-                if (((CombinedDataTime) desired[i]).equals(primaryPdo
-                        .getDataTime())) {
-                    for (PluginDataObject secondaryPdo : secondaryPdos) {
-                        if (((CombinedDataTime) desired[i])
-                                .getAdditionalDataTime().equals(
-                                        secondaryPdo.getDataTime())) {
-                            // primary and secondary match the datatimes
-                            // now combine them
-                            CombinedGribRecord combinedGribRecord = new CombinedGribRecord(
-                                    (GribRecord) primaryPdo,
-                                    (GribRecord) secondaryPdo);
-                            combinedGribRecord.setDataTime(desired[i]);
-                            combinedGribRecords.add(combinedGribRecord);
-                            found = true;
-                            break;
-                        }
-                    }
-                }
-            }
-        }
-        return combinedGribRecords
-                .toArray(new CombinedGribRecord[combinedGribRecords.size()]);
-    }
-
-    /**
-     * Gets the model information
-     * 
-     * @return The model information
-     */
-    public GribModel getModelInfo() {
-        if (this.modelInfo != null) {
-            return this.modelInfo;
-        }
-        for (GribRecord record : records) {
-            if (record.getModelInfo() != null) {
-                this.modelInfo = record.getModelInfo();
-                return this.modelInfo;
-            }
-        }
-        return null;
-    }
-
     @Override
     public AbstractVizResource getSecondaryResource() {
         // TODO Auto-generated method stub
         return null;
     }
 
-    public static IDataRecord[] getDataRecordsForTilt(GribRecord record,
+    public static IDataRecord[] getDataRecordsForTilt(GridRecord record,
             IDescriptor descriptor) throws VizException {
-        if (record.getModelInfo().getLevel().getMasterLevel().getName()
-                .equals("TILT")) {
+        if (record.getLevel().getMasterLevel().getName().equals("TILT")) {
             Coordinate tiltLoc = findTiltLocation(descriptor.getResourceList());
             if (tiltLoc != null) {
                 TiltRequest request = new TiltRequest();
@@ -537,4 +374,5 @@ public class GridResourceData extends AbstractRequestableResourceData implements
         }
         return null;
     }
+
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridVectorResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridVectorResource.java
deleted file mode 100644
index 41783bd7c4..0000000000
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GridVectorResource.java
+++ /dev/null
@@ -1,754 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.viz.grid.rsc;
-
-import java.awt.Point;
-import java.io.FileNotFoundException;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Iterator;
-import java.util.Set;
-
-import javax.measure.unit.Unit;
-import javax.media.jai.Interpolation;
-
-import org.geotools.coverage.grid.GeneralGridGeometry;
-import org.geotools.coverage.grid.GridGeometry2D;
-import org.geotools.coverage.grid.InvalidGridGeometryException;
-import org.geotools.geometry.DirectPosition2D;
-import org.opengis.referencing.FactoryException;
-import org.opengis.referencing.crs.CoordinateReferenceSystem;
-import org.opengis.referencing.operation.MathTransform;
-import org.opengis.referencing.operation.TransformException;
-
-import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.CombinedGribRecord;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-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.MapUtil;
-import com.raytheon.uf.common.geospatial.PointUtil;
-import com.raytheon.uf.common.geospatial.ReferencedCoordinate;
-import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation;
-import com.raytheon.uf.common.geospatial.interpolation.GridReprojection;
-import com.raytheon.uf.common.geospatial.interpolation.GridSampler;
-import com.raytheon.uf.common.geospatial.interpolation.data.FloatArrayWrapper;
-import com.raytheon.uf.common.status.IUFStatusHandler;
-import com.raytheon.uf.common.status.UFStatus;
-import com.raytheon.uf.common.status.UFStatus.Priority;
-import com.raytheon.uf.common.time.DataTime;
-import com.raytheon.uf.viz.core.exception.VizException;
-import com.raytheon.uf.viz.core.map.MapDescriptor;
-import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData;
-import com.raytheon.uf.viz.core.rsc.AbstractVizResource;
-import com.raytheon.uf.viz.core.rsc.IResourceDataChanged;
-import com.raytheon.uf.viz.core.rsc.LoadProperties;
-import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability;
-import com.raytheon.uf.viz.core.style.ParamLevelMatchCriteria;
-import com.raytheon.uf.viz.core.style.StyleManager;
-import com.raytheon.uf.viz.core.style.StyleManager.StyleType;
-import com.raytheon.uf.viz.core.style.StyleRule;
-import com.raytheon.viz.core.contours.ContourRenderable;
-import com.raytheon.viz.core.contours.rsc.displays.AbstractGriddedDisplay;
-import com.raytheon.viz.core.contours.rsc.displays.GriddedVectorDisplay;
-import com.raytheon.viz.core.rsc.ICombinedResourceData.CombineOperation;
-import com.raytheon.viz.core.rsc.ICombinedResourceData.CombineUtil;
-import com.raytheon.viz.grid.GridLevelTranslator;
-import com.raytheon.viz.grid.rsc.GridNameGenerator.IGridNameResource;
-import com.raytheon.viz.grid.rsc.GridNameGenerator.LegendParameters;
-import com.raytheon.viz.grid.util.ConformalityUtil;
-import com.raytheon.viz.grid.util.CoverageUtils;
-import com.raytheon.viz.grid.util.RemappedImage;
-import com.raytheon.viz.grid.xml.FieldDisplayTypesFactory;
-import com.raytheon.viz.pointdata.PointWindDisplay.DisplayType;
-import com.vividsolutions.jts.geom.Coordinate;
-
-/**
- * GridContourResource
- * 
- * Implements contouring for grid data
- * 
- * 
- * 
- *    SOFTWARE HISTORY
- *   
- *    Date         Ticket#     Engineer    Description
- *    ------------ ----------  ----------- --------------------------
- *    Oct 23, 2007             chammack    Initial Creation.
- *    02/16/09                 njensen     Refactored to new rsc architecture
- *    01/07/11     7948        bkowal      wind direction will be displayed in
- *                                         addition to wind speed when sampling
- *                                         is on.
- *    01/31/12   14306        kshresth     Cursor readout as you sample the dispay
- *    02/10/12     14472       mhuang      Fixed VB 'Height' field legend display error
- *                                         when click 'Diff' button.
- *    05/08/2012   14828       D. Friedman Use nearest-neighbor interpolation for
- *                                         reprojected grids.
- *    05/16/2012   14993       D. Friedman Fix "blocky" contours
- *    06/19/2012   14988       D. Friedman Reproject based on conformality 
- *    07/09/2012   14940       M. Porricelli Apply reprojection to streamlines 
- *    07/23/2012   14968       M. Porricelli Changed wording of streamline legend
- * 
- * 
- * - * @author chammack - * @version 1 - */ -public class GridVectorResource extends AbstractMapVectorResource implements - IResourceDataChanged, IGridNameResource { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(GridVectorResource.class); - - private GridGeometry2D remappedImageGeometry; - - private LegendParameters legendParams; - - public GridVectorResource(GridResourceData data, LoadProperties props) { - super(data, props); - - data.addChangeListener(this); - String paramAbbrev = ""; - GribRecord emptyRecord = new GribRecord(); - for (GribRecord rec : data.getRecords()) { - try { - // don't add empty records - if (!emptyRecord.equals(rec)) { - paramAbbrev = rec.getModelInfo().getParameterAbbreviation(); - this.addRecord(rec); - } - } catch (VizException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - Collections.sort(this.dataTimes); - this.getCapability(DisplayTypeCapability.class) - .setAlternativeDisplayTypes( - FieldDisplayTypesFactory.getInstance().getDisplayTypes( - paramAbbrev)); - - if (resourceData.getNameGenerator() == null) { - resourceData.setNameGenerator(new GridNameGenerator()); - } - } - - @Override - public String getName() { - - if (combineOperation != null - && combineOperation != CombineOperation.NONE) { - return getCombinedName(); - } else { - return super.getName(); - } - - } - - private String getCombinedName() { - GridNameGenerator secondaryGenerator = (GridNameGenerator) ((GridResourceData) resourceData).secondaryResourceData - .getNameGenerator(); - if (secondaryGenerator == null) { - secondaryGenerator = new GridNameGenerator(); - } - String secondaryName; - try { - LegendParameters legendParams = new LegendParameters(); - GribRecord secondaryGribRecord = ((CombinedGribRecord) ((GridResourceData) resourceData).records[0]) - .getSecondaryGribRecord(); - GribModel modelInfo = secondaryGribRecord.getModelInfo(); - modelInfo.getParameterAbbreviation(); - String secondaryUnits = modelInfo.getParameterUnit(); - ParamLevelMatchCriteria match = new ParamLevelMatchCriteria(); - match.setLevel(GridLevelTranslator - .constructMatching(secondaryGribRecord)); - match.setParameterName(Arrays.asList(modelInfo - .getParameterAbbreviation())); - match.setCreatingEntityNames(Arrays.asList(modelInfo.getModelName())); - String parameterName = modelInfo.getParameterName(); - StyleType st = null; - if (parameterName.equals("Height")) { - st = StyleType.CONTOUR; - } else if (parameterName.equals("Wind") - || parameterName.equals("Total Wind") - || parameterName.equals("Total Wind (Vector)")) { - st = StyleType.ARROW; - } else { - st = StyleType.IMAGERY; - } - StyleRule secondaryStyleRule = StyleManager.getInstance() - .getStyleRule(st, match); - if (secondaryStyleRule != null - && secondaryStyleRule.getPreferences() - .getDisplayUnitLabel() != null) { - secondaryUnits = secondaryStyleRule.getPreferences() - .getDisplayUnitLabel(); - } - legendParams.model = modelInfo; - legendParams.unit = secondaryUnits; - legendParams.dataTime = getDisplayedDataTime(); - secondaryName = secondaryGenerator.getName(legendParams, - ((GridResourceData) resourceData).secondaryResourceData); - } catch (Exception e) { - return null; - } - - return CombineUtil.getName(super.getName(), secondaryName, - combineOperation); - } - - public GridVectorResource(GridResourceData data, LoadProperties props, - DisplayType type) { - this(data, props); - displayType = type; - } - - @Override - protected IDataRecord[] getDataRecord(PluginDataObject pdo, - StyleRule styleRule) throws FileNotFoundException, - StorageException, VizException { - IDataRecord[] results = super.getDataRecord(pdo, styleRule); - GribRecord gribRecord = (GribRecord) pdo; - - // We need to reproject global data to prevent a gap in the data - boolean reproject = false; - GridCoverage location = gribRecord.getModelInfo().getLocation(); - if (location != null && location.getSpacingUnit().equals("degree")) { - double dx = location.getDx(); - Integer nx = location.getNx(); - //if (dx * nx >= 360) { // Test changed for DR 14988 to the following - if (! ConformalityUtil.testConformality(location.getGridGeometry(), - descriptor.getGridGeometry())) { - reproject = true; - } - } - if (reproject == true) { - GeneralGridGeometry gridGeometry = location.getGridGeometry(); - - try { - - GridGeometry2D remappedImageGeometry = GridGeometry2D - .wrap(MapUtil.reprojectGeometry(gridGeometry, - descriptor.getGridGeometry().getEnvelope(), - true, 2)); - IDataRecord[] newData = new IDataRecord[results.length]; - GridReprojection reproj = new GridReprojection(gridGeometry, - remappedImageGeometry); - BilinearInterpolation interp = new BilinearInterpolation(); - interp.setMissingThreshold(1.0f); - - /* - * Convert speed/dirs into U, V before interpolation. - */ - int len = ((FloatDataRecord) results[0]).getFloatData().length; - float[] uu = new float[len]; - float[] vv = new float[len]; - - boolean isVector = false; - if (displayType == DisplayType.BARB - || displayType == DisplayType.ARROW - || displayType == DisplayType.STREAMLINE) { - isVector = true; - - for (int i = 0; i < len; i++) { - float spd = ((FloatDataRecord) results[0]) - .getFloatData()[i]; - float dir = ((FloatDataRecord) results[1]) - .getFloatData()[i]; - - if (spd > -999999.0f && dir > -999999.0f) { - uu[i] = (float) (-spd * Math.sin(dir * Math.PI - / 180)); - vv[i] = (float) (-spd * Math.cos(dir * Math.PI - / 180)); - } else { - uu[i] = -999999.0f; - vv[i] = -999999.0f; - } - } - } - - for (int i = 0; i < results.length; i++) { - if (results[i] instanceof FloatDataRecord) { - float[] data = new float[len]; - if (isVector) { - data = i == 0 ? uu : vv; - } else { - data = ((FloatDataRecord) results[i]) - .getFloatData(); - } - - FloatArrayWrapper source = new FloatArrayWrapper(data, - gridGeometry); - source.setValidRange(-9998, Double.POSITIVE_INFINITY); - FloatArrayWrapper dest = new FloatArrayWrapper( - remappedImageGeometry); - dest.setFillValue(-999999); - data = reproj.reprojectedGrid(interp, source, dest) - .getArray(); - newData[i] = results[i].clone(); - newData[i] - .setIntSizes(new int[] { - remappedImageGeometry.getGridRange2D().width, - remappedImageGeometry.getGridRange2D().height }); - ((FloatDataRecord) newData[i]).setFloatData(data); - } - } - uu = null; - vv = null; - - if (isVector) { - /* - * Convert U, V back to speed/dirs - */ - len = ((FloatDataRecord) newData[0]).getFloatData().length; - float[] new_spds = new float[len]; - float[] new_dirs = new float[len]; - for (int i = 0; i < len; i++) { - float u = ((FloatDataRecord) newData[0]).getFloatData()[i]; - float v = ((FloatDataRecord) newData[1]).getFloatData()[i]; - - if (u > -999999.0f && v > -999999.0f) { - new_spds[i] = (float) Math.hypot(u, v); - new_dirs[i] = (float) (Math.atan2(u, v) * 180 / Math.PI) + 180; - - if (new_dirs[i] > 360) - new_dirs[i] -= 360; - if (new_dirs[i] < 0) - new_dirs[i] += 360; - - } else { - new_spds[i] = new_dirs[i] = -999999.0f; - } - } - ((FloatDataRecord) newData[0]).setFloatData(new_spds); - new_spds = null; - - // When reprojecting it is necessary to recalculate the - // direction of vectors based off the change in the "up" - // direction - MathTransform grid2crs = remappedImageGeometry - .getGridToCRS(); - MathTransform crs2ll = MapUtil - .getTransformToLatLon(remappedImageGeometry - .getCoordinateReferenceSystem()); - - for (int i = 0; i < remappedImageGeometry.getGridRange2D().width; i++) { - for (int j = 0; j < remappedImageGeometry - .getGridRange2D().height; j++) { - int index = i - + j - * remappedImageGeometry.getGridRange2D().width; - if (new_dirs[index] > -9999) { - DirectPosition2D dp = new DirectPosition2D(i, j); - grid2crs.transform(dp, dp); - crs2ll.transform(dp, dp); - Coordinate ll = new Coordinate(dp.x, dp.y); - double rot = MapUtil.rotation(ll, - remappedImageGeometry); - double rot2 = MapUtil.rotation(ll, - GridGeometry2D.wrap(gridGeometry)); - new_dirs[index] -= rot += rot2; - } - } - } - - ((FloatDataRecord) newData[1]).setFloatData(new_dirs); - new_dirs = null; - - } - this.remappedImageGeometry = remappedImageGeometry; - results = newData; - } catch (FactoryException e) { - throw new VizException(e); - } catch (TransformException e) { - throw new VizException(e); - } - - } - if (styleRule != null - && styleRule.getPreferences().getDisplayFlags() - .hasFlag("RotateVectorDir")) { - // Rotate the direction of contours to be relative to the North pole - // instead of the up direction of the grid - if (results.length == 1 && results[0] instanceof FloatDataRecord) { - FloatDataRecord oldRec = (FloatDataRecord) results[0]; - FloatDataRecord newRec = (FloatDataRecord) oldRec.clone(); - - GridGeometry2D geom = GridGeometry2D.wrap(location - .getGridGeometry()); - MathTransform grid2crs = geom.getGridToCRS(); - try { - MathTransform crs2ll = MapUtil.getTransformToLatLon(geom - .getCoordinateReferenceSystem()); - for (int i = 0; i < geom.getGridRange2D().width; i++) { - for (int j = 0; j < geom.getGridRange2D().height; j++) { - int index = i + j * geom.getGridRange2D().width; - float dir = newRec.getFloatData()[index]; - if (dir > -9999) { - DirectPosition2D dp = new DirectPosition2D(i, j); - grid2crs.transform(dp, dp); - crs2ll.transform(dp, dp); - Coordinate ll = new Coordinate(dp.x, dp.y); - float rot = (float) MapUtil.rotation(ll, geom); - dir = (dir + rot + 180) % 360; - newRec.getFloatData()[index] = dir; - } - } - } - results = new FloatDataRecord[] { newRec }; - } catch (TransformException e) { - throw new VizException(e); - } catch (InvalidGridGeometryException e) { - throw new VizException(e); - } catch (FactoryException e) { - throw new VizException(e); - } - } - } - return results; - } - - @Override - protected void getAllData() throws VizException { - System.out.println("Retrieving All Data"); - - this.vcrManagerJob.reset(); - this.gdManagerJob.reset(); - - Set keySet = this.getDataObjectMap().keySet(); - Iterator keySetItr = keySet.iterator(); - GribRecord emptyRecord = new GribRecord(); - while (keySetItr.hasNext()) { - DataTime dataTime = keySetItr.next(); - GribRecord pdo = (GribRecord) this.getDataObjectMap().get(dataTime); - if (emptyRecord.equals(pdo)) { - // don't request for empty records - continue; - } - this.addJobRequest(dataTime); - } - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.AbstractMapContourResource#getGridGeometry - * (com.raytheon.edex.db.objects.PluginDataObject) - */ - @Override - protected GeneralGridGeometry getGridGeometry(PluginDataObject obj) { - GribRecord gribRecord = (GribRecord) obj; - if (remappedImageGeometry != null) { - return remappedImageGeometry; - } - return gribRecord.getModelInfo().getLocation().getGridGeometry(); - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.AbstractMapContourResource#validateRecord - * (com.raytheon.edex.db.objects.PluginDataObject) - */ - @Override - protected boolean validateRecord(PluginDataObject obj) { - return (obj instanceof GribRecord); - } - - public LegendParameters getLegendParameters() { - setDisplayedDataTime(descriptor.getTimeForResource(this)); - PluginDataObject pdo = getDataObjectMap().get(getDisplayedDataTime()); - if (pdo == null || pdo.equals(new GribRecord())) { - ((GridResourceData) resourceData).getModelInfo(); - if (legendParams == null) { - legendParams = new LegendParameters(); - } - legendParams.model = ((GridResourceData) resourceData) - .getModelInfo(); - legendParams.dataTime = getDisplayedDataTime(); - - if (displayType == DisplayType.STREAMLINE) { - legendParams.type = " Strmlns"; - } else if (displayType == DisplayType.BARB) { - legendParams.type = "Wind Barbs"; - } else if (displayType == DisplayType.ARROW) { - legendParams.type = "Arrows"; - } - return legendParams; - } - GribRecord record = (GribRecord) pdo; - if (legendParams == null) { - legendParams = new LegendParameters(); - try { - StyleRule styleRule = getStyleRule(pdo); - if (styleRule != null - && styleRule.getPreferences().getDisplayUnits() != null - && (styleRule.getPreferences()).getDisplayUnits() - .toString() != null) { - legendParams.isPlaneLabelDisplayed = !styleRule - .getPreferences().getDisplayFlags() - .hasFlag("NoPlane"); - legendParams.unit = styleRule.getPreferences() - .getDisplayUnitLabel(); - } else { - legendParams.unit = record.getModelInfo() - .getParameterUnit(); - } - } catch (VizException e) { - statusHandler.handle(Priority.VERBOSE, e.getLocalizedMessage(), - e); - } - } - legendParams.model = record.getModelInfo(); - legendParams.dataTime = getDisplayedDataTime(); - - if (displayType == DisplayType.STREAMLINE) { - legendParams.type = " Strmlns"; - } else if (displayType == DisplayType.BARB) { - legendParams.type = "Wind Barbs"; - } else if (displayType == DisplayType.ARROW) { - legendParams.type = "Arrows"; - } - return legendParams; - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.rsc.AbstractMapContourResource#getStyleRule - * (com.raytheon.edex.db.objects.PluginDataObject) - */ - @Override - public synchronized StyleRule getStyleRule(PluginDataObject obj) - throws VizException { - GribRecord record = (GribRecord) obj; - - com.raytheon.uf.viz.core.style.level.Level level = GridLevelTranslator - .constructMatching(record); - - if (level == null) { - throw new VizException("Unhandled layer type: " - + record.getModelInfo().getLevelName()); - } - - ParamLevelMatchCriteria match = new ParamLevelMatchCriteria(); - match.setLevel(level); - match.setParameterName(Arrays.asList(record.getModelInfo() - .getParameterAbbreviation())); - match.setCreatingEntityNames(Arrays.asList(record.getModelInfo() - .getModelName())); - StyleRule sr = null; - if (displayType == DisplayType.ARROW || displayType == DisplayType.BARB - || displayType == DisplayType.DUALARROW) { - sr = StyleManager.getInstance().getStyleRule( - StyleManager.StyleType.ARROW, match); - } else { - sr = StyleManager.getInstance().getStyleRule( - StyleManager.StyleType.CONTOUR, match); - } - return sr; - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.rsc.AbstractMapContourResource#getDataUnits - * (com.raytheon.edex.db.objects.PluginDataObject) - */ - @Override - protected Unit getDataUnits(PluginDataObject obj) { - return ((GribRecord) obj).getModelInfo().getParameterUnitObject(); - } - - @SuppressWarnings("unchecked") - @Override - public AbstractVizResource getImageryResource() - throws VizException { - Collection pdo = getDataObjectMap().values(); - GribRecord[] recs = new GribRecord[pdo.size()]; - Iterator pdoIter = pdo.iterator(); - int i = 0; - while (pdoIter.hasNext()) { - recs[i] = (GribRecord) pdoIter.next(); - i++; - } - - return (AbstractVizResource) resourceData - .construct(new GridLoadProperties( - com.raytheon.uf.viz.core.rsc.DisplayType.IMAGE), - descriptor); - } - - @Override - protected FloatDataRecord remapGrid(GridCoverage location, - GridCoverage location2, FloatDataRecord dataRecord, - Interpolation interpolation) { - try { - RemappedImage remappedImage = CoverageUtils.getInstance() - .remapGrid(location, location2, dataRecord, interpolation); - FloatDataRecord remapGrid = remappedImage.getFloatDataRecord(); - this.setRemappedImageGeometry(remappedImage.getGridGeometry()); - return remapGrid; - } catch (VizException e) { - throw new RuntimeException( - "Unable to remap secondary resource grid data from " - + location.getName() + " to" + location2.getName(), - e); - } - } - - private void setRemappedImageGeometry(GridGeometry2D remappedImageGeometry) { - this.remappedImageGeometry = remappedImageGeometry; - } - - @Override - public void resourceChanged(ChangeType type, Object object) { - if (type.equals(ChangeType.DATA_UPDATE)) { - PluginDataObject[] pdos = (PluginDataObject[]) object; - - for (PluginDataObject pdo : pdos) { - if (CombineOperation.DIFFERENCE.equals(combineOperation) - && !(pdo instanceof CombinedGribRecord)) { - // Do nothing, timematcher will take care of it. - } else { - try { - if (pdo != null) { - addRecord(pdo); - } - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, - "Error updating grid resource", e); - } - } - } - } - issueRefresh(); - } - - @Override - public String inspect(ReferencedCoordinate coord) throws VizException { - if (!((GridResourceData) resourceData).isSampling()) { - if (displayType != DisplayType.ARROW) { - return super.inspect(coord); - } - } - GribRecord record = (GribRecord) getDataObjectMap().get( - getDisplayedDataTime()); - // If we have no record then there is no data - if (record == null) { - return "No Data"; - } - - ISpatialObject spatialArea = record.getSpatialObject(); - GridGeometry2D dataGeom = MapUtil.getGridGeometry(spatialArea); - String extension = ""; - Number value = null; - try { - if (displayType == DisplayType.ARROW - || displayType == DisplayType.BARB - || displayType == DisplayType.DUALARROW) { - Point position = PointUtil.determineIndex(coord.asLatLon(), - spatialArea.getCrs(), dataGeom); - // Outside the grid boundaries - if (position.y < 0 || position.y >= spatialArea.getNy() - || position.x < 0 || position.x >= spatialArea.getNx()) { - return "No Data"; - } - int index = position.y * spatialArea.getNx() + position.x; - Number direction = null; - - AbstractGriddedDisplay vectorDisplay = gdManagerJob - .request(getDisplayedDataTime()); - if (vectorDisplay != null - && vectorDisplay instanceof GriddedVectorDisplay) { - value = ((GriddedVectorDisplay) vectorDisplay) - .getMagnitude().get(index); - direction = ((GriddedVectorDisplay) vectorDisplay) - .getDirection().get(index); - if (direction != null - && !Float.isNaN(direction.floatValue())) { - /* For Wind Direction In Degrees */ - extension = String.format("%.0f\u00B0 ", direction); - } - } - } else { - ContourRenderable contourGroup; - contourGroup = this.vcrManagerJob.request(this - .getDisplayedDataTime()); - if (contourGroup == null || contourGroup.getData() == null) { - return "No Data"; - } - GridSampler sampler = new GridSampler( - new BilinearInterpolation()); - sampler.setSource(new FloatArrayWrapper( - ((FloatDataRecord) contourGroup.getData()[0]) - .getFloatData(), dataGeom)); - Coordinate pixel = coord.asPixel(dataGeom); - value = sampler.sample(pixel.x, pixel.y); - - } - // No data here - if (value == null || value.intValue() <= -9999) { - return "No Data"; - } - // Everything is good - String unitString = legendParams.unit == null ? record - .getModelInfo().getParameterUnit() : legendParams.unit; - if (value.intValue() < 99 || value.intValue() > 99999) { - return String.format("%s = %s%.3g%s", record.getModelInfo() - .getParameterAbbreviation(), extension, value, - unitString); - } else if (value.intValue() < 999) { - return String.format("%s = %s%.1f%s", record.getModelInfo() - .getParameterAbbreviation(), extension, value, - unitString); - } else { - return String.format("%s = %s%.0f%s", record.getModelInfo() - .getParameterAbbreviation(), extension, value, - unitString); - } - } catch (Exception e) { - throw new VizException("Error occured during Sampling", e); - } - } - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.viz.core.contours.rsc.AbstractMapVectorResource#project( - * org.opengis.referencing.crs.CoordinateReferenceSystem) - */ - @Override - public void project(CoordinateReferenceSystem mapData) throws VizException { - remappedImageGeometry = null; - super.project(mapData); - } - -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedDisplayManagerJob.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedDisplayManagerJob.java deleted file mode 100644 index 47fdabcd62..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedDisplayManagerJob.java +++ /dev/null @@ -1,242 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.rsc; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Map.Entry; - -import org.eclipse.core.runtime.IProgressMonitor; -import org.eclipse.core.runtime.IStatus; -import org.eclipse.core.runtime.Status; -import org.eclipse.core.runtime.jobs.Job; -import org.eclipse.swt.widgets.Display; -import org.eclipse.ui.PlatformUI; - -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.viz.core.contours.Activator; -import com.raytheon.viz.core.contours.rsc.displays.AbstractGriddedDisplay; -import com.raytheon.viz.grid.rsc.AbstractMapVectorResource.GriddedDisplayRequest; - -/** - * Uses the Eclipse Job Manager to manage a thread that is used to retrieve - * gridded display information. A priority queue is used to keep track of the - * date/time(s) that display information needs to be retrieved for. Once the job - * is started it will continue until either: the priority queue is empty or it - * receives a "Kill" signal because the user clicked on the clear button or - * removed a layer with displays from the map. - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Aug 09, 2010            rjpeter    Initial creation
- * 
- * 
- * - * @author rjpeter - * @version 1.0 - */ - -public class GriddedDisplayManagerJob extends Job { - - /** - * requestMap is an LRU, we will process the requests in the reverse so that - * the MRU request is done next. - */ - private LinkedHashMap requestMap = new LinkedHashMap( - 16, 0.75f, true); - - private Map> responseMap = new HashMap>(); - - private boolean shutdownIndicator = false; - - public class RenderableDisposer implements Runnable { - private AbstractGriddedDisplay display; - - public RenderableDisposer(AbstractGriddedDisplay display) { - this.display = display; - } - - @Override - public void run() { - this.display.dispose(); - this.display = null; - } - } - - public GriddedDisplayManagerJob() { - super("Processing Gridded Displays"); - } - - public Collection> getResponseMapAsCollection() { - synchronized (responseMap) { - // Copy to avoid concurrent modification if caller iterates. - return new ArrayList>( - this.responseMap.values()); - } - } - - public void clearResponseMap() { - Display display = PlatformUI.getWorkbench().getDisplay(); - synchronized (responseMap) { - for (AbstractGriddedDisplay griddedDisplay : this.responseMap - .values()) { - display.asyncExec(new RenderableDisposer(griddedDisplay)); - } - this.responseMap.clear(); - } - } - - public void addRequest(DataTime dt, GriddedDisplayRequest request) { - synchronized (requestMap) { - this.requestMap.put(dt, request); - } - if (this.getState() != Job.RUNNING) { - this.schedule(); - } - - } - - public void removeDataTime(DataTime dt) { - Display display = PlatformUI.getWorkbench().getDisplay(); - synchronized (requestMap) { - this.requestMap.remove(dt); - } - - synchronized (responseMap) { - AbstractGriddedDisplay griddedDisplay = this.responseMap - .remove(dt); - if (griddedDisplay != null) { - display.asyncExec(new RenderableDisposer(griddedDisplay)); - griddedDisplay = null; - } - } - } - - public void makeHighestPriority(DataTime dt) { - synchronized (requestMap) { - requestMap.get(dt); - } - } - - public AbstractGriddedDisplay request(DataTime dt) { - AbstractGriddedDisplay rval = null; - synchronized (responseMap) { - rval = responseMap.get(dt); - } - - if (rval == null) { - synchronized (requestMap) { - /* The Request Has Not Been Serviced Yet */ - if (this.requestMap.containsKey(dt)) { - // Bump up the priority - requestMap.get(dt); - } - } - } - - return rval; - } - - public void reset() { - this.shutdownIndicator = false; - } - - public void shutdown() { - this.shutdownIndicator = true; - } - - public void disposeInternal() { - this.clearResponseMap(); - } - - /* - * (non-Javadoc) - * - * @seeorg.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime. - * IProgressMonitor) - */ - @Override - protected IStatus run(IProgressMonitor monitor) { - while (this.requestMap.size() > 0) { - if (this.shutdownIndicator) { - this.requestMap.clear(); - break; - } - - DataTime dt = null; - GriddedDisplayRequest req = null; - - Entry nextTask = null; - synchronized (requestMap) { - // Grab the first key(most recently accessed) - Iterator> it = this.requestMap - .entrySet().iterator(); - while (it.hasNext()) { - nextTask = it.next(); - } - } - if (nextTask != null) { - dt = nextTask.getKey(); - req = nextTask.getValue(); - } - - if (dt == null || req == null) { - break; - } - try { - AbstractGriddedDisplay griddedDisplay = req.getData(); - synchronized (requestMap) { - GriddedDisplayRequest request = this.requestMap.get(dt); - synchronized (responseMap) { - AbstractGriddedDisplay oldDisplay = responseMap - .remove(dt); - if (oldDisplay != null) { - // Make sure we dispose existing renderable - Display display = PlatformUI.getWorkbench() - .getDisplay(); - display.asyncExec(new RenderableDisposer(oldDisplay)); - } - if (request != null) { - // If request is null then this was canceled - this.responseMap.put(dt, griddedDisplay); - } - } - if (request == req) { - this.requestMap.remove(dt); - } else { - // We will process this time again with the new request. - } - } - } catch (Throwable e) { - return new Status(Status.ERROR, Activator.PLUGIN_ID, - "Error creating contours", e); - } - } - - return Status.OK_STATUS; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedIconDisplay.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedIconDisplay.java index 7e27c43582..fedefeda79 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedIconDisplay.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GriddedIconDisplay.java @@ -41,7 +41,8 @@ import com.raytheon.viz.pointdata.drawables.IPointImageExtension.PointImage; import com.vividsolutions.jts.geom.Coordinate; /** - * TODO Add Description + * A renderable that can be used to display grids where every cell represents a + * value that can be mapped toa symbol in the WXSymbol font. * *
  * 
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResource.java
index ff41f4806c..edf1c205c3 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResource.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResource.java
@@ -19,20 +19,22 @@
  **/
 package com.raytheon.viz.grid.rsc;
 
-import javax.measure.converter.UnitConverter;
+import java.nio.FloatBuffer;
+import java.text.ParsePosition;
+import java.util.Map;
 
-import org.geotools.coverage.grid.GridGeometry2D;
-import org.opengis.referencing.datum.PixelInCell;
+import javax.measure.unit.Unit;
+import javax.measure.unit.UnitFormat;
 
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.datastorage.StorageException;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.geospatial.ReferencedCoordinate;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.core.rsc.LoadProperties;
-import com.raytheon.viz.core.rsc.hdf5.AbstractTileSet;
+import com.raytheon.viz.grid.rsc.general.D2DGridResource;
+import com.raytheon.viz.grid.rsc.general.GeneralGridData;
 
 /**
- * TODO Add Description
+ * TODO This whole class should be handled from style rules
  * 
  * 
  * 
@@ -47,76 +49,9 @@ import com.raytheon.viz.core.rsc.hdf5.AbstractTileSet;
  * @version 1.0
  */
 
-public class RcmResource extends GridResource {
+public class RcmResource extends D2DGridResource {
 
-    /**
-     * Extends the MemoryBasedTileSet class so that we can have direct access to
-     * the loadedData
-     */
-    private class RcmMemoryBasedTileSet extends GridMemoryBasedTileSet {
-
-        /**
-         * @param group
-         * @param dataset
-         * @param sharedGeometryTileset
-         * @param converter
-         * @param pdo
-         * @throws VizException
-         */
-        public RcmMemoryBasedTileSet(String group, String dataset,
-                AbstractTileSet sharedGeometryTileset, UnitConverter converter,
-                GribRecord pdo) throws VizException {
-            super(group, dataset, sharedGeometryTileset, converter, pdo);
-        }
-
-        /**
-         * @param dataURI
-         * @param string
-         * @param numLevels
-         * @param i
-         * @param gridGeometry2D
-         * @param gridResource
-         * @param conversion
-         * @param cellCorner
-         * @param record
-         * @param viewType
-         * @throws VizException
-         */
-        public RcmMemoryBasedTileSet(String dataURI, String string,
-                int numLevels, int i, GridGeometry2D gridGeometry2D,
-                GridResource gridResource, UnitConverter conversion,
-                PixelInCell cellCorner, GribRecord record, String viewType)
-                throws VizException {
-            super(dataURI, string, numLevels, i, gridGeometry2D, gridResource,
-                    conversion, cellCorner, record, viewType);
-        }
-
-        @Override
-        public float[] getLoadedData() {
-            return (float[]) loadedData[0];
-        }
-
-        /*
-         * (non-Javadoc)
-         * 
-         * @see
-         * com.raytheon.viz.core.rsc.hdf5.MemoryBasedTileSet#preloadDataObject
-         * (int)
-         */
-        @Override
-        protected void preloadDataObject(int level) throws StorageException {
-            // TODO Auto-generated method stub
-            super.preloadDataObject(level);
-            float[] data = new float[((float[]) loadedData[0]).length];
-            for (int i = 0; i < data.length; i++) {
-                data[i] = ((float[]) loadedData[0])[i];
-            }
-            data = transformRCMData(data);
-            for (int i = 0; i < data.length; i++) {
-                ((float[]) loadedData[0])[i] = data[i];
-            }
-        }
-    }
+    private static Unit DBZ;
 
     /**
      * @param data
@@ -124,27 +59,19 @@ public class RcmResource extends GridResource {
      */
     public RcmResource(RcmResourceData data, LoadProperties props) {
         super(data, props);
-        this.units = "dBZ";
+        if (DBZ == null) {
+            DBZ = UnitFormat.getUCUMInstance().parseObject("dBZ",
+                    new ParsePosition(0));
+        }
     }
 
     @Override
     public String inspect(ReferencedCoordinate coord) throws VizException {
-        String tmp = super.inspect(coord);
-        if ("No Data".equals(tmp)) {
-            return tmp;
+        Map map = interrogate(coord);
+        if (map == null) {
+            return "NO DATA";
         }
-        tmp = tmp.replace("dBZ", "");
-        float x = Float.parseFloat(tmp);
-        return dBZasString(x);
-    }
-
-    /**
-     * Takes the value of the cell and changes it to be a range for sampling
-     * 
-     * @param val
-     * @return
-     */
-    private String dBZasString(float val) {
+        float val = (Float) map.get(INTERROGATE_VALUE);
         String sampleVal = "";
         if (val < 1f) {
             sampleVal = "No Data";
@@ -166,54 +93,36 @@ public class RcmResource extends GridResource {
         return sampleVal;
     }
 
-    /**
-     * Takes the value of the cell and changes it to be a range for sampling
-     * 
-     * @param val
-     * @return
-     */
-    private float[] transformRCMData(float[] rcmData) {
-        for (int i = 0; i < rcmData.length; i++) {
-            if (rcmData[i] < 1f) {
-                rcmData[i] = 1f;
-            } else if (rcmData[i] < 2) {
-                rcmData[i] = 48f;
-            } else if (rcmData[i] < 3) {
-                rcmData[i] = 96f;
-            } else if (rcmData[i] < 4) {
-                rcmData[i] = 128f;
-            } else if (rcmData[i] < 5) {
-                rcmData[i] = 144f;
-            } else if (rcmData[i] < 6) {
-                rcmData[i] = 160f;
-            } else if (rcmData[i] < 7) {
-                rcmData[i] = 176f;
+    @Override
+    protected GeneralGridData getData(GridRecord gridRecord)
+            throws VizException {
+        GeneralGridData data = super.getData(gridRecord);
+        FloatBuffer floatData = data.getScalarData();
+        FloatBuffer newFloatData = FloatBuffer.allocate(floatData.capacity());
+        floatData.rewind();
+        newFloatData.rewind();
+        while (floatData.hasRemaining()) {
+            float value = floatData.get();
+            if (value < 1f) {
+                newFloatData.put(1f);
+            } else if (value < 2) {
+                newFloatData.put(48f);
+            } else if (value < 3) {
+                newFloatData.put(96f);
+            } else if (value < 4) {
+                newFloatData.put(128f);
+            } else if (value < 5) {
+                newFloatData.put(144f);
+            } else if (value < 6) {
+                newFloatData.put(160f);
+            } else if (value < 7) {
+                newFloatData.put(176f);
             } else {
-                rcmData[i] = 0f;
+                newFloatData.put(0f);
             }
         }
-        return rcmData;
+        return GeneralGridData.createScalarData(data.getGridGeometry(),
+                newFloatData, data.getDataUnit());
     }
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @see
-     * com.raytheon.viz.grid.rsc.GridResource#createTile(com.raytheon.uf.common
-     * .dataplugin.grib.GribRecord, java.lang.String)
-     */
-    @Override
-    public GridMemoryBasedTileSet createTile(GribRecord record,
-            GridMemoryBasedTileSet commonTile) throws VizException {
-        if (commonTile != null) {
-            return new RcmMemoryBasedTileSet(record.getDataURI(), "Data",
-                    commonTile, conversion, record);
-        }
-
-        GridGeometry2D gridGeometry2D = record.getModelInfo().getLocation()
-                .getGridGeometry();
-        return new RcmMemoryBasedTileSet(record.getDataURI(), "Data",
-                numLevels, 256, gridGeometry2D, this, conversion,
-                PixelInCell.CELL_CORNER, record, viewType);
-    }
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResourceData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResourceData.java
index d239c90c98..f6cde2cdf5 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResourceData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/RcmResourceData.java
@@ -23,13 +23,13 @@ import javax.xml.bind.annotation.XmlAccessType;
 import javax.xml.bind.annotation.XmlAccessorType;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.viz.core.alerts.DataCubeAlertMessageParser;
 import com.raytheon.uf.viz.core.rsc.AbstractVizResource;
 import com.raytheon.uf.viz.core.rsc.LoadProperties;
 
 /**
- * TODO Add Description
+ * resourceData for constructing RcmResources.
  * 
  * 
  * 
@@ -55,9 +55,9 @@ public class RcmResourceData extends GridResourceData {
     protected AbstractVizResource constructResource(
             LoadProperties loadProperties, PluginDataObject[] objects) {
         if (loadProperties instanceof GridLoadProperties) {
-            records = new GribRecord[objects.length];
+            records = new GridRecord[objects.length];
             for (int i = 0; i < objects.length; i++) {
-                records[i] = (GribRecord) objects[i];
+                records[i] = (GridRecord) objects[i];
             }
         }
         return new RcmResource(this, loadProperties);
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/VectorContourRenderableManagerJob.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/VectorContourRenderableManagerJob.java
deleted file mode 100644
index 0b330aa9b5..0000000000
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/VectorContourRenderableManagerJob.java
+++ /dev/null
@@ -1,251 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.viz.grid.rsc;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.IStatus;
-import org.eclipse.core.runtime.Status;
-import org.eclipse.core.runtime.jobs.Job;
-import org.eclipse.swt.widgets.Display;
-import org.eclipse.ui.PlatformUI;
-
-import com.raytheon.uf.common.time.DataTime;
-import com.raytheon.viz.core.contours.Activator;
-import com.raytheon.viz.core.contours.ContourRenderable;
-import com.raytheon.viz.grid.rsc.AbstractMapVectorResource.VectorContourRenderable;
-
-/**
- * Uses the Eclipse Job Manager to manage a thread that is used to retrieve
- * contour information.A priority queue is used to keep track of the
- * date/time(s) that contour information needs to be retrieved for. Once the job
- * is started it will continue until either: the priority queue is empty or it
- * receives a "Kill" signal because the user clicked on the clear button or
- * removed a layer with contours from the map.
- * 
- * 
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Jun 25, 2010            bkowal     Initial creation
- * Jul 9, 2010  #6851      bkowal     We let the UI-Thread dispose the renderables
- *                                    now.
- * 
- * 
- * - * @author bkowal - * @version 1.0 - */ - -public class VectorContourRenderableManagerJob extends Job { - - /** - * requestMap is an LRU, we will process the requests in the reverse so that - * the MRU request is done next. - */ - private LinkedHashMap requestMap = new LinkedHashMap( - 16, 0.75f, true); - - private Map responseMap = new HashMap(); - - private boolean shutdownIndicator = false; - - public class RenderableDisposer implements Runnable { - private ContourRenderable renderable; - - public RenderableDisposer(ContourRenderable renderable) { - this.renderable = renderable; - } - - @Override - public void run() { - this.renderable.dispose(); - this.renderable = null; - } - } - - public VectorContourRenderableManagerJob() { - super("Processing Contours"); - } - - public Collection getRequestMapAsCollection() { - synchronized (requestMap) { - // Copy to avoid concurrent modification if caller iterates. - return new ArrayList( - this.requestMap.values()); - } - } - - public Collection getResponseMapAsCollection() { - synchronized (responseMap) { - // Copy to avoid concurrent modification if caller iterates. - return new ArrayList( - this.responseMap.values()); - } - } - - public void clearResponseMap() { - Display display = PlatformUI.getWorkbench().getDisplay(); - synchronized (responseMap) { - for (ContourRenderable renderable : this.responseMap.values()) { - display.asyncExec(new RenderableDisposer(renderable)); - } - this.responseMap.clear(); - } - } - - public void addRequest(DataTime dt, VectorContourRenderable cr) { - synchronized (requestMap) { - this.requestMap.put(dt, cr); - } - if (this.getState() != Job.RUNNING) { - this.schedule(); - } - - } - - public void removeDataTime(DataTime dt) { - Display display = PlatformUI.getWorkbench().getDisplay(); - synchronized (requestMap) { - VectorContourRenderable renderable = this.requestMap.remove(dt); - if (renderable != null) { - display.asyncExec(new RenderableDisposer(renderable)); - } - } - - synchronized (responseMap) { - ContourRenderable renderable = this.responseMap.remove(dt); - if (renderable != null) { - display.asyncExec(new RenderableDisposer(renderable)); - renderable = null; - } - } - } - - public void makeHighestPriority(DataTime dt) { - synchronized (requestMap) { - requestMap.get(dt); - } - } - - public ContourRenderable request(DataTime dt) { - synchronized (responseMap) { - if (this.responseMap.containsKey(dt)) { - return this.responseMap.get(dt); - } - } - - synchronized (requestMap) { - /* The Request Has Not Been Serviced Yet */ - if (this.requestMap.containsKey(dt)) { - // Bump up the priority - requestMap.get(dt); - } - } - - return null; - } - - public void reset() { - this.shutdownIndicator = false; - } - - public void shutdown() { - this.shutdownIndicator = true; - } - - public void disposeInternal() { - this.clearResponseMap(); - } - - /* - * (non-Javadoc) - * - * @seeorg.eclipse.core.runtime.jobs.Job#run(org.eclipse.core.runtime. - * IProgressMonitor) - */ - @Override - protected IStatus run(IProgressMonitor monitor) { - while (this.requestMap.size() > 0) { - if (this.shutdownIndicator) { - this.requestMap.clear(); - break; - } - - DataTime dt = null; - VectorContourRenderable cr = null; - - Entry nextTask = null; - synchronized (requestMap) { - // Grab the last key(most recently accessed) - Iterator> it = this.requestMap - .entrySet().iterator(); - while (it.hasNext()) { - nextTask = it.next(); - } - } - if (nextTask != null) { - dt = nextTask.getKey(); - cr = nextTask.getValue(); - } - - if (dt == null || cr == null) { - break; - } - try { - cr.getData(); - synchronized (requestMap) { - ContourRenderable request = this.requestMap.get(dt); - synchronized (responseMap) { - ContourRenderable oldCR = responseMap.remove(dt); - if (oldCR != null) { - // Make sure we dispose existing renderable - Display display = PlatformUI.getWorkbench() - .getDisplay(); - display.asyncExec(new RenderableDisposer(oldCR)); - } - if (request != null) { - // If request is null then this was canceled - this.responseMap.put(dt, cr); - } - } - if (request == cr) { - this.requestMap.remove(dt); - } else { - // We will process this time again with the new cr. - } - } - } catch (Throwable e) { - return new Status(Status.ERROR, Activator.PLUGIN_ID, - "Error creating contours", e); - } - } - - return Status.OK_STATUS; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/AbstractGridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/AbstractGridResource.java index dff225ad8c..4308109a39 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/AbstractGridResource.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/AbstractGridResource.java @@ -28,9 +28,6 @@ import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import javax.measure.Measure; -import javax.measure.quantity.Angle; -import javax.measure.unit.NonSI; import javax.measure.unit.Unit; import javax.measure.unit.UnitFormat; @@ -43,6 +40,7 @@ import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation; import com.raytheon.uf.common.geospatial.interpolation.GridSampler; +import com.raytheon.uf.common.geospatial.interpolation.Interpolation; import com.raytheon.uf.common.geospatial.interpolation.NearestNeighborInterpolation; import com.raytheon.uf.common.geospatial.interpolation.data.FloatBufferWrapper; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -55,7 +53,6 @@ import com.raytheon.uf.viz.core.drawables.ColorMapLoader; import com.raytheon.uf.viz.core.drawables.ColorMapParameters; import com.raytheon.uf.viz.core.drawables.IRenderable; import com.raytheon.uf.viz.core.drawables.PaintProperties; -import com.raytheon.uf.viz.core.drawables.PaintStatus; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.map.IMapDescriptor; import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData; @@ -75,6 +72,7 @@ import com.raytheon.uf.viz.core.rsc.capabilities.ImagingCapability; import com.raytheon.uf.viz.core.rsc.capabilities.MagnificationCapability; import com.raytheon.uf.viz.core.rsc.capabilities.OutlineCapability; import com.raytheon.uf.viz.core.style.AbstractStylePreferences; +import com.raytheon.uf.viz.core.style.MatchCriteria; import com.raytheon.uf.viz.core.style.ParamLevelMatchCriteria; import com.raytheon.uf.viz.core.style.StyleManager; import com.raytheon.uf.viz.core.style.StyleManager.StyleType; @@ -120,16 +118,22 @@ public abstract class AbstractGridResource private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(AbstractGridResource.class); + public static final String INTERROGATE_VALUE = "value"; + + public static final String INTERROGATE_UNIT = "unit"; + + public static final String INTERROGATE_DIRECTION = "direction"; + private final GridDataRequestJob requestJob; - private Map> pdos = new HashMap>(); + private Map> pdoMap = new ConcurrentHashMap>(); - private Map renderables = new ConcurrentHashMap(); + private Map> renderableMap = new ConcurrentHashMap>(); /** * This is a local cache of data that is used when sampling or reprojected. */ - private Map data = new ConcurrentHashMap(); + private Map> dataMap = new ConcurrentHashMap>(); /** * StylePreferences from the styleManager appropriate for the display type @@ -142,11 +146,6 @@ public abstract class AbstractGridResource */ protected DecimalFormat sampleFormat = new DecimalFormat("0.00"); - /** - * The interpolation used when sampling to sample between data points. - */ - protected GridSampler sampleInterpolion; - protected AbstractGridResource(T resourceData, LoadProperties loadProperties) { super(resourceData, loadProperties); resourceData.addChangeListener(new IResourceDataChanged() { @@ -168,8 +167,14 @@ public abstract class AbstractGridResource } else if (type == ChangeType.CAPABILITY) { if (object instanceof AbstractCapability) { AbstractCapability capability = (AbstractCapability) object; - for (IRenderable renderable : renderables.values()) { - updataRenderableCapabilities(renderable, capability); + synchronized (renderableMap) { + for (List renderableList : renderableMap + .values()) { + for (IRenderable renderable : renderableList) { + updataRenderableCapabilities(renderable, + capability); + } + } } } } @@ -196,20 +201,28 @@ public abstract class AbstractGridResource time = resourceData.getBinOffset().getNormalizedTime(time); } } - List pdos = this.pdos.get(time); + List pdos = this.pdoMap.get(time); if (pdos == null) { pdos = new ArrayList(); - this.pdos.put(time, pdos); + this.pdoMap.put(time, pdos); } if (pdos.contains(pdo)) { pdos.remove(pdo); } pdos.add(pdo); - if (renderables.containsKey(time)) { - disposeRenderable(renderables.remove(time)); + synchronized (renderableMap) { + if (renderableMap.containsKey(time)) { + List renderableList = this.renderableMap + .remove(time); + if (renderableList != null) { + for (IRenderable renderable : renderableList) { + disposeRenderable(renderable); + } + } + } } requestJob.remove(time); - data.remove(time); + dataMap.remove(time); if (!dataTimes.contains(dataTimes)) { dataTimes.add(time); } @@ -221,9 +234,9 @@ public abstract class AbstractGridResource * * @param data */ - protected void setData(Map data) { - if (this.data.isEmpty()) { - this.data.putAll(data); + protected void setData(Map> data) { + if (this.dataMap.isEmpty()) { + this.dataMap.putAll(data); } } @@ -235,11 +248,7 @@ public abstract class AbstractGridResource */ protected void updataRenderableCapabilities(IRenderable renderable, AbstractCapability capability) { - if (renderable instanceof GriddedImageDisplay2) { - if (capability instanceof ImagingCapability) { - initSampling(); - } - } else if (renderable instanceof AbstractGriddedDisplay) { + if (renderable instanceof AbstractGriddedDisplay) { AbstractGriddedDisplay gridDisplay = (AbstractGriddedDisplay) renderable; if (capability instanceof ColorableCapability) { gridDisplay.setColor(getCapability(ColorableCapability.class) @@ -338,25 +347,34 @@ public abstract class AbstractGridResource protected void initStylePreferences() throws VizStyleException { DisplayType displayType = getDisplayType(); StyleRule styleRule = null; - switch (displayType) { - case IMAGE: - styleRule = StyleManager.getInstance().getStyleRule( - StyleType.IMAGERY, getMatchCriteria()); - break; - case CONTOUR: - case STREAMLINE: - styleRule = StyleManager.getInstance().getStyleRule( - StyleType.CONTOUR, getMatchCriteria()); - break; - case BARB: - case ARROW: - case DUALARROW: - styleRule = StyleManager.getInstance().getStyleRule( - StyleType.ARROW, getMatchCriteria()); - break; + MatchCriteria criteria = getMatchCriteria(); + if (criteria != null) { + switch (displayType) { + case IMAGE: + styleRule = StyleManager.getInstance().getStyleRule( + StyleType.IMAGERY, criteria); + break; + case CONTOUR: + case STREAMLINE: + styleRule = StyleManager.getInstance().getStyleRule( + StyleType.CONTOUR, criteria); + break; + case BARB: + case ARROW: + case DUALARROW: + styleRule = StyleManager.getInstance().getStyleRule( + StyleType.ARROW, criteria); + break; + } } if (styleRule != null) { stylePreferences = styleRule.getPreferences(); + if (stylePreferences instanceof ImagePreferences) { + boolean interpolationState = ((ImagePreferences) styleRule + .getPreferences()).isInterpolate(); + this.getCapability(ImagingCapability.class) + .setInterpolationState(interpolationState); + } } } @@ -364,18 +382,6 @@ public abstract class AbstractGridResource * Create an interpolation and format to be used when sampling */ protected void initSampling() { - if (this.hasCapability(ImagingCapability.class)) { - ImagingCapability imagingCap = this - .getCapability(ImagingCapability.class); - if (imagingCap.isInterpolationState()) { - sampleInterpolion = new GridSampler(new BilinearInterpolation()); - } else { - sampleInterpolion = new GridSampler( - new NearestNeighborInterpolation()); - } - } else { - sampleInterpolion = new GridSampler(new BilinearInterpolation()); - } if (stylePreferences != null && stylePreferences instanceof ImagePreferences) { ImagePreferences prefs = (ImagePreferences) stylePreferences; @@ -408,24 +414,30 @@ public abstract class AbstractGridResource } if (time == null) { return; - } else if (renderables.containsKey(time)) { - renderables.get(time).paint(target, paintProps); - return; } + synchronized (renderableMap) { + if (renderableMap.containsKey(time)) { + for (IRenderable renderable : renderableMap.get(time)) { + renderable.paint(target, paintProps); + } + return; + } - GeneralGridData data = requestData(time); - if (data == null) { - updatePaintStatus(PaintStatus.INCOMPLETE); - return; - } + List dataList = requestData(time); + if (dataList == null) { + return; + } - IRenderable renderable = createRenderable(target, data); - - if (renderable != null) { - renderables.put(time, renderable); - renderable.paint(target, paintProps); - } else { - updatePaintStatus(PaintStatus.INCOMPLETE); + List renderableList = new ArrayList( + dataList.size()); + for (GeneralGridData data : dataList) { + IRenderable renderable = createRenderable(target, data); + if (renderable != null) { + renderableList.add(renderable); + renderable.paint(target, paintProps); + } + } + renderableMap.put(time, renderableList); } } @@ -442,13 +454,13 @@ public abstract class AbstractGridResource IRenderable renderable = null; - GridGeometry2D gridGeometry = getGridGeometry(); + GridGeometry2D gridGeometry = data.getGridGeometry(); DisplayType displayType = getDisplayType(); switch (displayType) { case IMAGE: - if (renderables.isEmpty()) { + if (renderableMap.isEmpty()) { ColorMapParameters params = createColorMapParameters(data); if (params.getColorMap() == null) { if (params.getColorMapName() == null) { @@ -460,6 +472,9 @@ public abstract class AbstractGridResource this.getCapability(ColorMapCapability.class) .setColorMapParameters(params); } + ColorMapParameters params = getCapability(ColorMapCapability.class) + .getColorMapParameters(); + data.convert(params.getImageUnit()); GriddedImageDisplay2 imageRenderable = new GriddedImageDisplay2( data.getScalarData(), gridGeometry, this, "2D"); imageRenderable.init(target); @@ -569,8 +584,20 @@ public abstract class AbstractGridResource && !criteria.getCreatingEntityNames().isEmpty()) { creatingEntity = criteria.getCreatingEntityNames().get(0); } - return ColorMapParameterFactory.build(data.getScalarData().array(), - parameter, parameterUnits, level, creatingEntity); + ColorMapParameters newParameters = ColorMapParameterFactory.build(data + .getScalarData().array(), parameter, parameterUnits, level, + creatingEntity); + ColorMapParameters oldParameters = this.getCapability( + ColorMapCapability.class).getColorMapParameters(); + if (oldParameters != null + && oldParameters.getDataMin() <= newParameters.getDataMin() + && oldParameters.getDataMax() >= newParameters.getDataMax()) { + // if the oldParameters have a larger range than the new parameters, + // reuse the old parameters. This is useful when the resource is + // sharing capabilities, for example in an FFGVizGroupResource. + newParameters = oldParameters; + } + return newParameters; } /** @@ -580,13 +607,6 @@ public abstract class AbstractGridResource */ public abstract ParamLevelMatchCriteria getMatchCriteria(); - /** - * The gridGeometry to use for this data. - * - * @return - */ - public abstract GridGeometry2D getGridGeometry(); - /** * This method should return a data object for the given time and/or pdos. * @@ -595,29 +615,54 @@ public abstract class AbstractGridResource * @return * @throws VizException */ - public abstract GeneralGridData getData(DataTime time, + public abstract List getData(DataTime time, List pdos) throws VizException; - protected GeneralGridData requestData(DataTime time) { + protected List requestData(DataTime time) { synchronized (requestJob) { - GeneralGridData data = this.data.get(time); + List data = this.dataMap.get(time); if (data == null) { - data = requestJob.requestData(time, pdos.get(time)); + data = requestJob.requestData(time, pdoMap.get(time)); if (data != null) { - this.data.put(time, data); + data = mergeData(data); + this.dataMap.put(time, data); } } return data; } } + /** + * Combine data records that are in the same grid space to avoid areas of + * overlapping data. + * + * @param dataList + * @return + */ + protected List mergeData(List dataList) { + if (dataList == null || dataList.size() < 2) { + return dataList; + } + for (int i = 0; i < dataList.size(); i += 1) { + GeneralGridData data1 = dataList.get(i); + for (int j = i + 1; j < dataList.size(); j += 1) { + GeneralGridData data2 = dataList.get(j); + GeneralGridData merged = GeneralGridData + .mergeData(data1, data2); + if (merged != null) { + dataList.set(i, merged); + dataList.remove(j); + j -= 1; + } + + } + } + return dataList; + } + @Override protected void disposeInternal() { - requestJob.stopAndClear(); - for (IRenderable renderable : renderables.values()) { - disposeRenderable(renderable); - } - renderables.clear(); + clearRequestedData(); } /** @@ -648,15 +693,28 @@ public abstract class AbstractGridResource @Override public void project(CoordinateReferenceSystem crs) throws VizException { - Iterator iter = renderables.values().iterator(); - while (iter.hasNext()) { - IRenderable renderable = iter.next(); - if (!projectRenderable(renderable, crs)) { - disposeRenderable(renderable); - iter.remove(); + synchronized (renderableMap) { + Iterator> iter = renderableMap.values() + .iterator(); + while (iter.hasNext()) { + List renderableList = iter.next(); + boolean remove = false; + for (IRenderable renderable : renderableList) { + if (!projectRenderable(renderable, crs)) { + remove = true; + break; + } + } + // If any one renderable fails to reproject then dispose them + // all, so that the whole frame gets regenerated. + if (remove) { + for (IRenderable renderable : renderableList) { + disposeRenderable(renderable); + } + iter.remove(); + } } } - initSampling(); } /** @@ -685,7 +743,7 @@ public abstract class AbstractGridResource return descriptor.getTimeForResource(this); } - protected GeneralGridData getCurrentData() { + protected List getCurrentData() { DataTime time = getTimeForResource(); if (time == null) { return null; @@ -693,119 +751,133 @@ public abstract class AbstractGridResource return requestData(time); } - public Measure inspectValue(ReferencedCoordinate coord) - throws VizException { - GeneralGridData data = getCurrentData(); - if (data == null) { - return null; - } - sampleInterpolion.setSource(new FloatBufferWrapper( - data.getScalarData(), getGridGeometry())); - float value = Float.NaN; - try { - Coordinate xy = coord.asPixel(getGridGeometry()); - value = (float) sampleInterpolion.sample(xy.x, xy.y); - } catch (FactoryException e) { - throw new VizException(e); - } catch (TransformException e) { - throw new VizException(e); - } - - sampleInterpolion.setSource(null); - Unit unit = data.getDataUnit(); - - if (stylePreferences != null) { - Unit styleUnit = stylePreferences.getDisplayUnits(); - if (unit != null && !unit.equals(styleUnit) - && unit.isCompatible(styleUnit)) { - value = (float) unit.getConverterTo(styleUnit).convert(value); - unit = styleUnit; + protected Interpolation getInspectInterpolation(GeneralGridData data) { + Interpolation sampleInterpolion = null; + if (this.hasCapability(ImagingCapability.class)) { + ImagingCapability imagingCap = this + .getCapability(ImagingCapability.class); + if (imagingCap.isInterpolationState()) { + sampleInterpolion = new BilinearInterpolation(); + } else { + sampleInterpolion = new NearestNeighborInterpolation(); } + } else { + sampleInterpolion = new BilinearInterpolation(); } - - return Measure.valueOf(value, unit); - } - - public Measure inspectDirection(ReferencedCoordinate coord) - throws VizException { - GeneralGridData data = getCurrentData(); - if (data == null) { - return null; - } - if (!data.isVector()) { - return null; - } - sampleInterpolion.setSource(new FloatBufferWrapper(data.getDirection(), - getGridGeometry())); - float value = Float.NaN; - try { - Coordinate xy = coord.asPixel(getGridGeometry()); - value = (float) sampleInterpolion.sample(xy.x, xy.y); - } catch (FactoryException e) { - throw new VizException(e); - } catch (TransformException e) { - throw new VizException(e); - } - - sampleInterpolion.setSource(null); - - return Measure.valueOf(value, NonSI.DEGREE_ANGLE); + return sampleInterpolion; } @Override public String inspect(ReferencedCoordinate coord) throws VizException { - Measure value = inspectValue(coord); - if (value == null) { - return null; - } - if (value.getValue().isNaN()) { + Map map = interrogate(coord); + if (map == null) { return "NO DATA"; } - Measure dir = inspectDirection(coord); - if (dir != null) { - return String.format("%.0f\u00B0 ", - dir.floatValue(NonSI.DEGREE_ANGLE)) - + formatInspect(value); - } else { - return formatInspect(value); + double value = (Double) map.get(INTERROGATE_VALUE); + String result = sampleFormat.format(value) + map.get(INTERROGATE_UNIT); + // Data mapping images. + if (hasCapability(ColorMapCapability.class)) { + ColorMapParameters cmp = getCapability(ColorMapCapability.class) + .getColorMapParameters(); + if (cmp.getDataMapping() != null) { + double imageVal = cmp.getDisplayToImageConverter().convert( + value); + String mapResult = cmp.getDataMapping() + .getLabelValueForDataValue(imageVal); + if (mapResult != null && !mapResult.isEmpty()) { + return mapResult; + } + } } + if (map.containsKey(INTERROGATE_DIRECTION)) { + double dir = (Double) map.get(INTERROGATE_DIRECTION); + result += String.format("%.0f\u00B0 ", dir); + } + return result; } - /** - * Format the value and return the sample string. - * - * @param value - * @param unit - * @return - */ - protected String formatInspect(Measure value) { - Unit dataUnit = value.getUnit(); - - if (dataUnit == null) { - return sampleFormat.format(value); + protected Map interrogate(ReferencedCoordinate coord, + GeneralGridData data) throws VizException { + Coordinate pixel = null; + try { + pixel = coord.asPixel(data.getGridGeometry()); + } catch (TransformException e) { + // this should never happen, if your data geometry and screen + // geometry are incompatible then you probably already saw piles of + // errors in paint. + throw new VizException( + "Error transforming coordinate for interrogate", e); + } catch (FactoryException e) { + // again, this should never hit. + throw new VizException( + "Error transforming coordinate for interrogate", e); } - Unit styleUnit = null; + Interpolation interpolation = getInspectInterpolation(data); + GridSampler sampler = new GridSampler(new FloatBufferWrapper( + data.getScalarData(), data.getGridGeometry()), interpolation); + double value = sampler.sample(pixel.x, pixel.y); + if (Double.isNaN(value)) { + return null; + } + String unitString = null; + Unit unit = data.getDataUnit(); if (stylePreferences != null) { - styleUnit = stylePreferences.getDisplayUnits(); + Unit styleUnit = stylePreferences.getDisplayUnits(); + if (unit != null && unit.isCompatible(styleUnit)) { + value = (float) unit.getConverterTo(styleUnit).convert(value); + unit = styleUnit; + unitString = stylePreferences.getDisplayUnitLabel(); + } } - if (dataUnit.equals(styleUnit)) { - return sampleFormat.format(value.getValue()) - + stylePreferences.getDisplayUnitLabel(); + Map result = new HashMap(); + result.put(INTERROGATE_VALUE, value); + if (unitString != null) { + result.put(INTERROGATE_UNIT, unitString); + } else if (unit != null && !unit.equals(Unit.ONE)) { + result.put(INTERROGATE_UNIT, + UnitFormat.getUCUMInstance().format(unit)); } else { - return sampleFormat.format(value.getValue()) - + UnitFormat.getUCUMInstance().format(value.getUnit()); + result.put(INTERROGATE_UNIT, ""); } + if (data.isVector()) { + sampler.setSource(new FloatBufferWrapper(data.getScalarData(), data + .getGridGeometry())); + Double dir = sampler.sample(pixel.x, pixel.y); + result.put(INTERROGATE_DIRECTION, dir); + } + return result; + } + + @Override + public Map interrogate(ReferencedCoordinate coord) + throws VizException { + List dataList = getCurrentData(); + if (dataList == null) { + return null; + } + for (GeneralGridData data : dataList) { + Map result = interrogate(coord, data); + if (result != null) { + return result; + } + } + + return null; } @Override public void remove(DataTime dataTime) { - pdos.remove(dataTime); - data.remove(dataTime); + pdoMap.remove(dataTime); + dataMap.remove(dataTime); requestJob.remove(dataTime); dataTimes.remove(dataTime); - IRenderable renderable = renderables.remove(dataTime); - if (renderable != null) { - disposeRenderable(renderable); + synchronized (renderableMap) { + List renderableList = renderableMap.remove(dataTime); + if (renderableList != null) { + for (IRenderable renderable : renderableList) { + disposeRenderable(renderable); + } + } } } @@ -840,19 +912,30 @@ public abstract class AbstractGridResource */ protected void clearRequestedData() { requestJob.stopAndClear(); - for (IRenderable renderable : renderables.values()) { - disposeRenderable(renderable); + synchronized (renderableMap) { + for (List renderableList : renderableMap.values()) { + for (IRenderable renderable : renderableList) { + disposeRenderable(renderable); + } + } + renderableMap.clear(); } - renderables.clear(); - data.clear(); + dataMap.clear(); } protected List getCurrentPluginDataObjects() { - return pdos.get(getTimeForResource()); + return getPluginDataObjects(getTimeForResource()); } protected List getPluginDataObjects(DataTime time) { - return pdos.get(time); + if (time == null) { + return null; + } + List list = pdoMap.get(time); + if (list == null) { + return null; + } + return new ArrayList(list); } } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/D2DGribGridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/D2DGribGridResource.java deleted file mode 100644 index 99df74b47f..0000000000 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/D2DGribGridResource.java +++ /dev/null @@ -1,345 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.viz.grid.rsc.general; - -import java.nio.FloatBuffer; -import java.util.List; - -import org.geotools.coverage.grid.GeneralGridGeometry; -import org.geotools.coverage.grid.GridEnvelope2D; -import org.geotools.coverage.grid.GridGeometry2D; -import org.geotools.geometry.DirectPosition2D; -import org.opengis.referencing.FactoryException; -import org.opengis.referencing.crs.CoordinateReferenceSystem; -import org.opengis.referencing.operation.MathTransform; -import org.opengis.referencing.operation.TransformException; - -import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.datastorage.records.IDataRecord; -import com.raytheon.uf.common.geospatial.MapUtil; -import com.raytheon.uf.common.geospatial.ReferencedCoordinate; -import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation; -import com.raytheon.uf.common.geospatial.interpolation.GridReprojection; -import com.raytheon.uf.common.geospatial.interpolation.Interpolation; -import com.raytheon.uf.common.geospatial.interpolation.data.DataSource; -import com.raytheon.uf.common.geospatial.interpolation.data.FloatArrayWrapper; -import com.raytheon.uf.common.geospatial.interpolation.data.FloatBufferWrapper; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.viz.core.IGraphicsTarget; -import com.raytheon.uf.viz.core.exception.VizException; -import com.raytheon.uf.viz.core.map.IMapDescriptor; -import com.raytheon.uf.viz.core.rsc.AbstractNameGenerator; -import com.raytheon.uf.viz.core.rsc.DisplayType; -import com.raytheon.uf.viz.core.rsc.LoadProperties; -import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability; -import com.raytheon.viz.grid.rsc.GridNameGenerator; -import com.raytheon.viz.grid.rsc.GridNameGenerator.IGridNameResource; -import com.raytheon.viz.grid.rsc.GridNameGenerator.LegendParameters; -import com.raytheon.viz.grid.rsc.GridResourceData; -import com.raytheon.viz.grid.util.ConformalityUtil; -import com.raytheon.viz.grid.xml.FieldDisplayTypesFactory; -import com.vividsolutions.jts.geom.Coordinate; - -/** - * - * A much more complex grib grid resource that attempts to match A1 displays - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Mar 9, 2011            bsteffen     Initial creation
- * 06/19/2012   14988      D. Friedman Reproject based on conformality
- * 07/23/2012   14968     M. Porricelli Changed wording of streamline
- *                                      legend
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ -public class D2DGribGridResource extends GribGridResource - implements IGridNameResource { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(D2DGribGridResource.class); - - private GridReprojection reprojectionInterpolation; - - public D2DGribGridResource(GridResourceData resourceData, - LoadProperties loadProperties) { - super(resourceData, loadProperties); - if (resourceData.getNameGenerator() == null) { - resourceData.setNameGenerator(new GridNameGenerator()); - } - - } - - @Override - protected void initInternal(IGraphicsTarget target) throws VizException { - String paramAbbrev = ""; - for (GribRecord record : resourceData.getRecords()) { - paramAbbrev = record.getModelInfo().getParameterAbbreviation(); - addDataObject(record); - } - this.getCapability(DisplayTypeCapability.class) - .setAlternativeDisplayTypes( - FieldDisplayTypesFactory.getInstance().getDisplayTypes( - paramAbbrev)); - super.initInternal(target); - } - - @Override - public void addDataObject(PluginDataObject pdo) { - if (gribModel == null) { - super.addDataObject(pdo); - calculateReprojection(); - } else { - super.addDataObject(pdo); - } - requestData(pdo.getDataTime()); - } - - @Override - public GridGeometry2D getGridGeometry() { - if (reprojectionInterpolation == null) { - return super.getGridGeometry(); - } else { - return GridGeometry2D.wrap(reprojectionInterpolation - .getTargetGeometry()); - } - } - - @Override - public GeneralGridData getData(DataTime time, List pdos) - throws VizException { - GeneralGridData data = null; - if (pdos == null) { - return null; - } - // Attempt to figure out if there is a special tilt data request. - GribRecord gribRecord = (GribRecord) pdos.get(0); - IDataRecord[] recs = GridResourceData.getDataRecordsForTilt(gribRecord, - descriptor); - if (recs != null) { - data = getData(recs, gribRecord.getModelInfo() - .getParameterUnitObject()); - } - // If there was no special tilt data just request data from super. - if (data == null) { - data = super.getData(time, pdos); - } - // Now reproject if we need to. - if (reprojectionInterpolation != null) { - try { - Interpolation interp = new BilinearInterpolation(); - if (data.isVector()) { - DataSource source = new FloatBufferWrapper( - data.getUComponent(), super.getGridGeometry()); - FloatArrayWrapper dest = new FloatArrayWrapper( - reprojectionInterpolation.getTargetGeometry()); - float[] udata = reprojectionInterpolation.reprojectedGrid( - interp, source, dest).getArray(); - source = new FloatBufferWrapper(data.getVComponent(), - super.getGridGeometry()); - dest = new FloatArrayWrapper( - reprojectionInterpolation.getTargetGeometry()); - float[] vdata = reprojectionInterpolation.reprojectedGrid( - interp, source, dest).getArray(); - // When reprojecting it is necessary to recalculate the - // direction of vectors based off the change in the "up" - // direction - GridGeometry2D sourceGeometry = GridGeometry2D - .wrap(reprojectionInterpolation.getSourceGeometry()); - GridGeometry2D targetGeometry = GridGeometry2D - .wrap(reprojectionInterpolation.getTargetGeometry()); - GridEnvelope2D targetRange = targetGeometry - .getGridRange2D(); - - MathTransform grid2crs = targetGeometry.getGridToCRS(); - MathTransform crs2ll = MapUtil - .getTransformToLatLon(targetGeometry - .getCoordinateReferenceSystem()); - - for (int i = 0; i < targetRange.width; i++) { - for (int j = 0; j < targetRange.height; j++) { - int index = i + j * targetRange.width; - if (udata[index] > -9999) { - DirectPosition2D dp = new DirectPosition2D(i, j); - grid2crs.transform(dp, dp); - crs2ll.transform(dp, dp); - Coordinate ll = new Coordinate(dp.x, dp.y); - double rot = MapUtil.rotation(ll, - targetGeometry); - double rot2 = MapUtil.rotation(ll, - sourceGeometry); - double cos = Math.cos(Math.toRadians(180 + rot - - rot2)); - double sin = Math.sin(Math.toRadians(180 + rot - - rot2)); - double u = udata[index]; - double v = vdata[index]; - udata[index] = (float) (cos * u - sin * v); - vdata[index] = (float) (sin * u + cos * v); - } - } - } - data = GeneralGridData.createVectorDataUV( - FloatBuffer.wrap(udata), FloatBuffer.wrap(vdata), - data.getDataUnit()); - - } else { - DataSource source = new FloatBufferWrapper( - data.getScalarData(), super.getGridGeometry()); - FloatArrayWrapper dest = new FloatArrayWrapper( - reprojectionInterpolation.getTargetGeometry()); - float[] fdata = reprojectionInterpolation.reprojectedGrid( - interp, source, dest).getArray(); - data = GeneralGridData.createScalarData( - FloatBuffer.wrap(fdata), data.getDataUnit()); - } - } catch (TransformException e) { - throw new VizException(e); - } catch (FactoryException e) { - throw new VizException(e); - } - } - // TODO before contours can be switched, we need to handle vector - // direction style rule and reprojection of this data. - // TODO before imaging can be switched over data mapping needs to be - // incorporated. - return data; - } - - @Override - public LegendParameters getLegendParameters() { - LegendParameters legendParams = new LegendParameters(); - List pdos = getCurrentPluginDataObjects(); - if (pdos != null && !pdos.isEmpty()) { - gribModel = ((GribRecord) pdos.get(0)).getModelInfo(); - } - legendParams.model = gribModel; - if (stylePreferences != null) { - legendParams.unit = stylePreferences.getDisplayUnitLabel(); - } - - List displayTypes = null; - if (gribModel != null) { - if (legendParams.unit == null || legendParams.unit.isEmpty()) { - legendParams.unit = gribModel.getParameterUnit(); - } - displayTypes = FieldDisplayTypesFactory.getInstance() - .getDisplayTypes(gribModel.getParameterAbbreviation()); - } - DisplayType displayType = getDisplayType(); - if (displayTypes != null && !displayTypes.isEmpty() - && displayTypes.get(0).equals(displayType)) { - // The default type does not display in the legend - legendParams.type = ""; - } else if (displayType == DisplayType.STREAMLINE) { - legendParams.type = "Strmlns"; - } else if (displayType == DisplayType.BARB) { - legendParams.type = "Wind Barbs"; - } else if (displayType == DisplayType.ARROW) { - legendParams.type = "Arrows"; - } else if (displayType == DisplayType.IMAGE) { - legendParams.type = "Img"; - } - - return legendParams; - } - - private void calculateReprojection() { - if (descriptor == null || gribModel == null) { - return; - } - GridCoverage location = gribModel.getLocation(); - if (location != null && location.getSpacingUnit().equals("degree")) { - double dx = location.getDx(); - Integer nx = location.getNx(); - // if (dx * nx >= 360) { // Test changed for DR 14988 to the - // following - - if (!ConformalityUtil.testConformality(location.getGridGeometry(), - descriptor.getGridGeometry())) { - try { - GridGeometry2D sourceGeometry = location.getGridGeometry(); - GeneralGridGeometry targetGeometry = sourceGeometry; - if (descriptor != null) { - targetGeometry = MapUtil.reprojectGeometry( - sourceGeometry, descriptor.getGridGeometry() - .getEnvelope(), true, 2); - } - reprojectionInterpolation = new GridReprojection( - sourceGeometry, targetGeometry); - reprojectionInterpolation.computeTransformTable(); - clearRequestedData(); - } catch (Exception e) { - reprojectionInterpolation = null; - statusHandler - .handle(Priority.PROBLEM, - "Error reprojecting grid, grid will not be reprojected", - e); - } - } - } - } - - @Override - public void project(CoordinateReferenceSystem crs) throws VizException { - super.project(crs); - calculateReprojection(); - } - - @Override - public void setDescriptor(IMapDescriptor descriptor) { - super.setDescriptor(descriptor); - calculateReprojection(); - } - - @Override - public String inspect(ReferencedCoordinate coord) throws VizException { - if (resourceData.isSampling()) { - return gribModel.getParameterAbbreviation() + " = " - + super.inspect(coord); - } else { - return null; - } - } - - @Override - public String getName() { - if (resourceData == null) { - return super.getName(); - } - AbstractNameGenerator generator = resourceData.getNameGenerator(); - if (generator == null) { - return super.getName(); - } - return generator.getName(this); - } - -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/D2DGridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/D2DGridResource.java new file mode 100644 index 0000000000..08c1603d2b --- /dev/null +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/D2DGridResource.java @@ -0,0 +1,299 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.grid.rsc.general; + +import java.util.List; + +import javax.measure.unit.Unit; + +import org.geotools.coverage.grid.GeneralGridGeometry; +import org.geotools.coverage.grid.GridGeometry2D; +import org.geotools.coverage.grid.InvalidGridGeometryException; +import org.geotools.geometry.DirectPosition2D; +import org.opengis.referencing.FactoryException; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.referencing.operation.TransformException; + +import com.raytheon.uf.common.dataplugin.PluginDataObject; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; +import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.geospatial.ReferencedCoordinate; +import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation; +import com.raytheon.uf.common.geospatial.interpolation.Interpolation; +import com.raytheon.uf.common.geospatial.interpolation.NearestNeighborInterpolation; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.viz.core.IGraphicsTarget; +import com.raytheon.uf.viz.core.datastructure.DataCubeContainer; +import com.raytheon.uf.viz.core.exception.VizException; +import com.raytheon.uf.viz.core.rsc.AbstractNameGenerator; +import com.raytheon.uf.viz.core.rsc.DisplayType; +import com.raytheon.uf.viz.core.rsc.LoadProperties; +import com.raytheon.uf.viz.core.rsc.capabilities.DisplayTypeCapability; +import com.raytheon.uf.viz.core.rsc.capabilities.ImagingCapability; +import com.raytheon.viz.grid.rsc.GridNameGenerator; +import com.raytheon.viz.grid.rsc.GridNameGenerator.IGridNameResource; +import com.raytheon.viz.grid.rsc.GridNameGenerator.LegendParameters; +import com.raytheon.viz.grid.rsc.GridResourceData; +import com.raytheon.viz.grid.util.ConformalityUtil; +import com.raytheon.viz.grid.xml.FieldDisplayTypesFactory; +import com.vividsolutions.jts.geom.Coordinate; + +/** + * + * A much more complex grib grid resource that attempts to match A1 displays + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 9, 2011            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class D2DGridResource extends GridResource implements + IGridNameResource { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(D2DGridResource.class); + + private boolean reprojectedData = false; + + public D2DGridResource(GridResourceData resourceData, + LoadProperties loadProperties) { + super(resourceData, loadProperties); + if (resourceData.getNameGenerator() == null) { + resourceData.setNameGenerator(new GridNameGenerator()); + } + + } + + @Override + protected void initInternal(IGraphicsTarget target) throws VizException { + String paramAbbrev = ""; + for (GridRecord record : resourceData.getRecords()) { + paramAbbrev = record.getParameter().getAbbreviation(); + addDataObject(record); + } + this.getCapability(DisplayTypeCapability.class) + .setAlternativeDisplayTypes( + FieldDisplayTypesFactory.getInstance().getDisplayTypes( + paramAbbrev)); + super.initInternal(target); + } + + @Override + public void addDataObject(PluginDataObject pdo) { + super.addDataObject(pdo); + requestData(pdo.getDataTime()); + } + + @Override + protected GeneralGridData getData(GridRecord gridRecord) + throws VizException { + Unit dataUnit = gridRecord.getParameter().getUnit(); + // Reqest data for tilts if this is Std Env sampling. + IDataRecord[] dataRecs = GridResourceData.getDataRecordsForTilt( + gridRecord, descriptor); + if (dataRecs == null) { + dataRecs = DataCubeContainer.getDataRecord(gridRecord); + if (dataRecs == null) { + return null; + } + } + // For world wide lat lon grids we reproject, this is done to match A1, + // but it also makes the wind barbs look more evenly spaced near the + // pole. + GridCoverage location = gridRecord.getLocation(); + GeneralGridData data = getData(dataRecs, location.getGridGeometry(), + dataUnit); + if (location != null && location.getSpacingUnit().equals("degree")) { + if (!ConformalityUtil.testConformality(location.getGridGeometry(), + descriptor.getGridGeometry())) { + data = reprojectData(data); + } + } + // Wind Direction(and possibly others) can be set so that we rotate the + // direction to be relative to the north pole instead of grid relative. + if (stylePreferences != null + && stylePreferences.getDisplayFlags() + .hasFlag("RotateVectorDir")) { + GridGeometry2D geom = GridGeometry2D.wrap(location + .getGridGeometry()); + MathTransform grid2crs = geom.getGridToCRS(); + try { + MathTransform crs2ll = MapUtil.getTransformToLatLon(geom + .getCoordinateReferenceSystem()); + for (int i = 0; i < geom.getGridRange2D().width; i++) { + for (int j = 0; j < geom.getGridRange2D().height; j++) { + int index = i + j * geom.getGridRange2D().width; + float dir = data.getScalarData().get(index); + if (dir > -9999) { + DirectPosition2D dp = new DirectPosition2D(i, j); + grid2crs.transform(dp, dp); + crs2ll.transform(dp, dp); + Coordinate ll = new Coordinate(dp.x, dp.y); + float rot = (float) MapUtil.rotation(ll, geom); + dir = (dir + rot + 180) % 360; + data.getScalarData().put(index, dir); + } + } + } + } catch (TransformException e) { + throw new VizException(e); + } catch (InvalidGridGeometryException e) { + throw new VizException(e); + } catch (FactoryException e) { + throw new VizException(e); + } + } + return data; + } + + public GeneralGridData reprojectData(GeneralGridData data) { + if (descriptor == null) { + return data; + } + try { + GeneralGridGeometry targetGeometry = MapUtil.reprojectGeometry(data + .getGridGeometry(), descriptor.getGridGeometry() + .getEnvelope(), true, 2); + reprojectedData = true; + Interpolation interpolation = null; + if (this.hasCapability(ImagingCapability.class) + && !this.getCapability(ImagingCapability.class) + .isInterpolationState()) { + interpolation = new NearestNeighborInterpolation(); + } else { + BilinearInterpolation bilinear = new BilinearInterpolation(); + bilinear.setMissingThreshold(1.0f); + interpolation = bilinear; + } + data = data.reproject(targetGeometry, interpolation); + } catch (FactoryException e) { + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); + } catch (TransformException e) { + statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); + } + // If exceptions happened just return the original data, the display + // should still work just fine. + return data; + } + + @Override + public LegendParameters getLegendParameters() { + GridRecord record = getCurrentGridRecord(); + if (record == null) { + record = getAnyGridRecord(); + if (record == null) { + return null; + } + } + LegendParameters legendParams = new LegendParameters(); + DatasetInfo info = DatasetInfoLookup.getInstance().getInfo( + record.getDatasetId()); + if (info == null) { + legendParams.model = record.getDatasetId(); + } else { + legendParams.model = info.getTitle(); + } + legendParams.level = record.getLevel(); + legendParams.parameter = record.getParameter().getName(); + legendParams.ensembleId = record.getEnsembleId(); + legendParams.dataTime = descriptor.getFramesInfo().getTimeForResource( + this); + + if (stylePreferences != null) { + legendParams.unit = stylePreferences.getDisplayUnitLabel(); + } + + if (legendParams.unit == null || legendParams.unit.isEmpty()) { + if (record.getParameter().getUnit().equals(Unit.ONE)) { + legendParams.unit = ""; + } else { + legendParams.unit = record.getParameter().getUnitString(); + } + } + List displayTypes = FieldDisplayTypesFactory.getInstance() + .getDisplayTypes(record.getParameter().getAbbreviation()); + DisplayType displayType = getDisplayType(); + if (displayTypes != null && !displayTypes.isEmpty() + && displayTypes.get(0).equals(displayType)) { + // The default type does not display in the legend + legendParams.type = ""; + } else if (displayType == DisplayType.STREAMLINE) { + legendParams.type = "Streamlines"; + } else if (displayType == DisplayType.BARB) { + legendParams.type = "Wind Barbs"; + } else if (displayType == DisplayType.ARROW) { + legendParams.type = "Arrows"; + } else if (displayType == DisplayType.IMAGE) { + legendParams.type = "Img"; + } + return legendParams; + } + + @Override + public String inspect(ReferencedCoordinate coord) throws VizException { + if (getDisplayType() == DisplayType.IMAGE) { + return super.inspect(coord); + } else if (resourceData.isSampling()) { + GridRecord record = getCurrentGridRecord(); + if (record == null) { + return super.inspect(coord); + } + return record.getParameter().getAbbreviation() + "=" + + super.inspect(coord); + } else { + return null; + } + } + + @Override + public String getName() { + if (resourceData == null) { + return super.getName(); + } + AbstractNameGenerator generator = resourceData.getNameGenerator(); + if (generator == null) { + return super.getName(); + } + return generator.getName(this); + } + + @Override + public void project(CoordinateReferenceSystem crs) throws VizException { + if (reprojectedData) { + clearRequestedData(); + } + super.project(crs); + } + +} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResource.java index 69c305815d..59785ce953 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResource.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResource.java @@ -20,9 +20,11 @@ package com.raytheon.viz.grid.rsc.general; import java.nio.FloatBuffer; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; -import javax.measure.Measure; import javax.measure.unit.Unit; import org.geotools.coverage.grid.GeneralGridEnvelope; @@ -30,19 +32,16 @@ import org.geotools.coverage.grid.GridGeometry2D; import org.geotools.geometry.jts.ReferencedEnvelope; import org.opengis.coverage.grid.GridEnvelope; import org.opengis.referencing.FactoryException; +import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.TransformException; import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; import com.raytheon.uf.common.geospatial.interpolation.BilinearInterpolation; -import com.raytheon.uf.common.geospatial.interpolation.GridReprojection; -import com.raytheon.uf.common.geospatial.interpolation.Interpolation; -import com.raytheon.uf.common.geospatial.interpolation.data.DataSource; -import com.raytheon.uf.common.geospatial.interpolation.data.FloatArrayWrapper; -import com.raytheon.uf.common.geospatial.interpolation.data.FloatBufferWrapper; import com.raytheon.uf.common.time.CombinedDataTime; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.viz.core.IGraphicsTarget; +import com.raytheon.uf.viz.core.drawables.IRenderable; import com.raytheon.uf.viz.core.drawables.PaintProperties; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.IResourceGroup; @@ -55,7 +54,8 @@ import com.raytheon.viz.core.rsc.ICombinedResourceData.CombineUtil; /** * - * TODO Add Description + * Resource which calculates the difference of two grid resources and displays + * the value as a grid. * *
  * 
@@ -82,10 +82,6 @@ public class DifferenceGridResource extends
 
     private final AbstractGridResource two;
 
-    private GridReprojection oneInterpolation;
-
-    private GridReprojection twoInterpolation;
-
     public DifferenceGridResource(DifferenceGridResourceData resourceData,
             LoadProperties loadProperties, AbstractGridResource one,
             AbstractGridResource two) {
@@ -115,128 +111,138 @@ public class DifferenceGridResource extends
         super.paintInternal(target, paintProps);
     }
 
+    @Override
+    public Map interrogate(ReferencedCoordinate coord)
+            throws VizException {
+        Map oneMap = one.interrogate(coord);
+        Map twoMap = two.interrogate(coord);
+        if (oneMap == null || twoMap == null) {
+            return super.interrogate(coord);
+        }
+        Map myMap = new HashMap();
+        float oneVal = (Float) oneMap.get(INTERROGATE_VALUE);
+        float twoVal = (Float) twoMap.get(INTERROGATE_VALUE);
+        myMap.put(INTERROGATE_VALUE, oneVal - twoVal);
+        if (oneMap.get(INTERROGATE_UNIT).equals(twoMap.get(INTERROGATE_UNIT))) {
+            myMap.put(INTERROGATE_UNIT, oneMap.get(INTERROGATE_UNIT));
+        } else {
+            myMap.put(INTERROGATE_UNIT, "(" + oneMap.get(INTERROGATE_UNIT)
+                    + "-" + twoMap.get(INTERROGATE_UNIT) + ")");
+        }
+        if (myMap.containsKey(INTERROGATE_DIRECTION)
+                && twoMap.containsKey(INTERROGATE_DIRECTION)) {
+            float oneDir = (Float) oneMap.get(INTERROGATE_DIRECTION);
+            float twoDir = (Float) twoMap.get(INTERROGATE_DIRECTION);
+            myMap.put(INTERROGATE_DIRECTION, oneDir - twoDir);
+        }
+        return myMap;
+    }
+
     @Override
     public ParamLevelMatchCriteria getMatchCriteria() {
         return one.getMatchCriteria();
     }
 
     @Override
-    public GridGeometry2D getGridGeometry() {
-        if (oneInterpolation == null) {
-            GridGeometry2D oneGeometry = one.getGridGeometry();
-            GridGeometry2D twoGeometry = two.getGridGeometry();
-            GridGeometry2D newGeometry = null;
-            if (oneGeometry.equals(twoGeometry)) {
-                newGeometry = oneGeometry;
-            } else {
-                ReferencedEnvelope oneEnv = new ReferencedEnvelope(
-                        oneGeometry.getEnvelope());
-                ReferencedEnvelope twoEnv = new ReferencedEnvelope(
-                        oneGeometry.getEnvelope());
-                if (!oneEnv.getCoordinateReferenceSystem().equals(
-                        twoEnv.getCoordinateReferenceSystem())) {
-                    // If they aren't the same crs just go to screen space.
-                    try {
-                        oneEnv = oneEnv.transform(descriptor.getCRS(), true);
-                        twoEnv = twoEnv.transform(descriptor.getCRS(), true);
-                    } catch (TransformException e) {
-                        throw new RuntimeException(e);
-                    } catch (FactoryException e) {
-                        throw new RuntimeException(e);
-                    }
-                }
-                ReferencedEnvelope newEnv = new ReferencedEnvelope(
-                        oneEnv.intersection(twoEnv), descriptor.getCRS());
-                newGeometry = new GridGeometry2D(GRID_ENVELOPE, newEnv);
-            }
-            oneInterpolation = new GridReprojection(oneGeometry, newGeometry);
-            twoInterpolation = new GridReprojection(twoGeometry, newGeometry);
-        }
-        return GridGeometry2D.wrap(oneInterpolation.getTargetGeometry());
-    }
-
-    @Override
-    public GeneralGridData getData(DataTime time, List pdos)
-            throws VizException {
+    public List getData(DataTime time,
+            List pdos) throws VizException {
         if (!(time instanceof CombinedDataTime)) {
             throw new VizException("Unexpected single time in diff resource");
         }
         CombinedDataTime cTime = (CombinedDataTime) time;
         DataTime oneTime = cTime.getPrimaryDataTime();
         DataTime twoTime = cTime.getAdditionalDataTime();
-        if (oneInterpolation == null || twoInterpolation == null) {
-            getGridGeometry();
-        }
-        GeneralGridData oneData = one.requestData(oneTime);
-        GeneralGridData twoData = two.requestData(twoTime);
-        if (oneData == null || twoData == null) {
+        List oneDataList = one.requestData(oneTime);
+        List twoDataList = two.requestData(twoTime);
+        if (oneDataList == null || oneDataList.isEmpty() || twoDataList == null
+                || twoDataList.isEmpty()) {
             return null;
         }
-        Unit dataUnit = Unit.ONE;
+        List newDataList = new ArrayList();
+        for (GeneralGridData oneData : oneDataList) {
+            for (GeneralGridData twoData : twoDataList) {
+                GeneralGridData newData = difference(oneData, twoData);
+                if (newData != null) {
+                    newDataList.add(newData);
+                }
+            }
+        }
+        return newDataList;
+    }
+
+    private GeneralGridData difference(GeneralGridData oneData,
+            GeneralGridData twoData) throws VizException {
+        Unit newUnit = oneData.getDataUnit();
         if (stylePreferences != null) {
-            dataUnit = stylePreferences.getDisplayUnits();
-            oneData.convert(dataUnit);
-            twoData.convert(dataUnit);
-        } else if (oneData.getDataUnit().isCompatible(twoData.getDataUnit())) {
-            dataUnit = oneData.getDataUnit();
-            twoData.convert(dataUnit);
+            newUnit = stylePreferences.getDisplayUnits();
+        }
+        if (!oneData.convert(newUnit)) {
+            // if oneData is somehow incompatible with our style rule then just
+            // convert to its style units
+            if (one.stylePreferences != null) {
+                oneData.convert(one.stylePreferences.getDisplayUnits());
+            }
+        }
+        if (!twoData.convert(newUnit)) {
+            // if twoData is somehow incompatible with our style rule then just
+            // convert to its style units
+            if (two.stylePreferences != null) {
+                twoData.convert(two.stylePreferences.getDisplayUnits());
+            }
+        }
+        GridGeometry2D newGeom = oneData.getGridGeometry();
+        if (!newGeom.equals(twoData.getGridGeometry())) {
+            ReferencedEnvelope oneEnv = new ReferencedEnvelope(oneData
+                    .getGridGeometry().getEnvelope());
+            ReferencedEnvelope twoEnv = new ReferencedEnvelope(twoData
+                    .getGridGeometry().getEnvelope());
+            if (!oneEnv.getCoordinateReferenceSystem().equals(
+                    twoEnv.getCoordinateReferenceSystem())) {
+                // If they aren't the same crs just go to screen space.
+                try {
+                    oneEnv = oneEnv.transform(descriptor.getCRS(), true);
+                    twoEnv = twoEnv.transform(descriptor.getCRS(), true);
+                } catch (TransformException e) {
+                    throw new RuntimeException(e);
+                } catch (FactoryException e) {
+                    throw new RuntimeException(e);
+                }
+            }
+            ReferencedEnvelope newEnv = new ReferencedEnvelope(
+                    oneEnv.intersection(twoEnv),
+                    oneEnv.getCoordinateReferenceSystem());
+            if (newEnv.isEmpty()) {
+                return null;
+            }
+            newGeom = new GridGeometry2D(GRID_ENVELOPE, newEnv);
         }
         GeneralGridData newData = null;
         try {
-            Interpolation interp = new BilinearInterpolation();
+            oneData = oneData.reproject(newGeom, new BilinearInterpolation());
+            twoData = twoData.reproject(newGeom, new BilinearInterpolation());
             if (oneData.isVector() && twoData.isVector()) {
-                DataSource oneSourceU = new FloatBufferWrapper(
-                        oneData.getUComponent(),
-                        oneInterpolation.getSourceGeometry());
-                DataSource oneSourceV = new FloatBufferWrapper(
-                        oneData.getVComponent(),
-                        oneInterpolation.getSourceGeometry());
-                DataSource twoSourceU = new FloatBufferWrapper(
-                        twoData.getUComponent(),
-                        twoInterpolation.getSourceGeometry());
-                DataSource twoSourceV = new FloatBufferWrapper(
-                        twoData.getVComponent(),
-                        twoInterpolation.getSourceGeometry());
-                float[] oneU = oneInterpolation.reprojectedGrid(interp,
-                        oneSourceU, new FloatArrayWrapper(getGridGeometry()))
-                        .getArray();
-                float[] oneV = oneInterpolation.reprojectedGrid(interp,
-                        oneSourceV, new FloatArrayWrapper(getGridGeometry()))
-                        .getArray();
-                float[] twoU = twoInterpolation.reprojectedGrid(interp,
-                        twoSourceU, new FloatArrayWrapper(getGridGeometry()))
-                        .getArray();
-                float[] twoV = twoInterpolation.reprojectedGrid(interp,
-                        twoSourceV, new FloatArrayWrapper(getGridGeometry()))
-                        .getArray();
+                float[] oneU = oneData.getUComponent().array();
+                float[] oneV = oneData.getVComponent().array();
+                float[] twoU = twoData.getUComponent().array();
+                float[] twoV = twoData.getVComponent().array();
                 float[] newU = new float[oneU.length];
                 float[] newV = new float[oneV.length];
                 for (int i = 0; i < newU.length; i++) {
                     newU[i] = oneU[i] - twoU[i];
                     newV[i] = oneV[i] - twoV[i];
                 }
-                newData = GeneralGridData.createVectorDataUV(
-                        FloatBuffer.wrap(newU), FloatBuffer.wrap(newV),
-                        dataUnit);
+                newData = GeneralGridData
+                        .createVectorDataUV(newGeom, FloatBuffer.wrap(newU),
+                                FloatBuffer.wrap(newV), newUnit);
             } else {
-                DataSource oneSource = new FloatBufferWrapper(
-                        oneData.getScalarData(),
-                        oneInterpolation.getSourceGeometry());
-                DataSource twoSource = new FloatBufferWrapper(
-                        twoData.getScalarData(),
-                        twoInterpolation.getSourceGeometry());
-                float[] oneScalar = oneInterpolation.reprojectedGrid(interp,
-                        oneSource, new FloatArrayWrapper(getGridGeometry()))
-                        .getArray();
-                float[] twoScalar = twoInterpolation.reprojectedGrid(interp,
-                        twoSource, new FloatArrayWrapper(getGridGeometry()))
-                        .getArray();
+                float[] oneScalar = oneData.getScalarData().array();
+                float[] twoScalar = twoData.getScalarData().array();
                 float[] newScalar = new float[oneScalar.length];
                 for (int i = 0; i < newScalar.length; i++) {
                     newScalar[i] = oneScalar[i] - twoScalar[i];
                 }
-                newData = GeneralGridData.createScalarData(
-                        FloatBuffer.wrap(newScalar), dataUnit);
+                newData = GeneralGridData.createScalarData(newGeom,
+                        FloatBuffer.wrap(newScalar), newUnit);
             }
         } catch (FactoryException e) {
             throw new VizException(e);
@@ -256,36 +262,6 @@ public class DifferenceGridResource extends
         return new CombinedDataTime(oneTime, twoTime);
     }
 
-    @Override
-    public Measure inspectValue(ReferencedCoordinate coord)
-            throws VizException {
-        Measure oneVal = one.inspectValue(coord);
-        Measure twoVal = two.inspectValue(coord);
-        if (oneVal == null || twoVal == null) {
-            return null;
-        }
-        Unit dataUnit = Unit.ONE;
-        if (stylePreferences != null) {
-            dataUnit = stylePreferences.getDisplayUnits();
-            if (oneVal.getUnit().isCompatible(dataUnit)) {
-                oneVal = Measure.valueOf((float) oneVal.getUnit()
-                        .getConverterTo(dataUnit).convert(oneVal.getValue()),
-                        dataUnit);
-            }
-            if (twoVal.getUnit().isCompatible(dataUnit)) {
-                twoVal = Measure.valueOf((float) twoVal.getUnit()
-                        .getConverterTo(dataUnit).convert(twoVal.getValue()),
-                        dataUnit);
-            }
-        } else if (oneVal.getUnit().isCompatible(twoVal.getUnit())) {
-            dataUnit = oneVal.getUnit();
-            twoVal = Measure.valueOf(
-                    (float) twoVal.getUnit().getConverterTo(dataUnit)
-                            .convert(twoVal.getValue()), dataUnit);
-        }
-        return Measure.valueOf(oneVal.getValue() - twoVal.getValue(), dataUnit);
-    }
-
     @Override
     public String getName() {
         DataTime oneTime = descriptor.getTimeForResource(one);
@@ -302,4 +278,13 @@ public class DifferenceGridResource extends
         return resourceData.getResourceList();
     }
 
+    @Override
+    protected boolean projectRenderable(IRenderable renderable,
+            CoordinateReferenceSystem crs) throws VizException {
+        // Always rebuild the renderables in case we projected into descriptor
+        // space.
+        return false;
+
+    }
+
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResourceData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResourceData.java
index 9c06465665..bb33eea5f4 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResourceData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/DifferenceGridResourceData.java
@@ -40,7 +40,7 @@ import com.raytheon.uf.viz.core.rsc.ResourceList;
 
 /**
  * 
- * TODO Add Description
+ * ResourceData for constructing Difference Resources.
  * 
  * 
  * 
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GeneralGridData.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GeneralGridData.java
index c8dee9123a..a199f7f0e7 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GeneralGridData.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GeneralGridData.java
@@ -19,11 +19,32 @@
  **/
 package com.raytheon.viz.grid.rsc.general;
 
+import java.awt.geom.Rectangle2D;
 import java.nio.FloatBuffer;
 
 import javax.measure.converter.UnitConverter;
 import javax.measure.unit.Unit;
 
+import org.geotools.coverage.grid.GeneralGridGeometry;
+import org.geotools.coverage.grid.GridEnvelope2D;
+import org.geotools.coverage.grid.GridGeometry2D;
+import org.geotools.geometry.DirectPosition2D;
+import org.geotools.geometry.Envelope2D;
+import org.opengis.coverage.grid.GridEnvelope;
+import org.opengis.geometry.Envelope;
+import org.opengis.referencing.FactoryException;
+import org.opengis.referencing.crs.CoordinateReferenceSystem;
+import org.opengis.referencing.operation.MathTransform;
+import org.opengis.referencing.operation.TransformException;
+
+import com.raytheon.uf.common.geospatial.MapUtil;
+import com.raytheon.uf.common.geospatial.interpolation.GridReprojection;
+import com.raytheon.uf.common.geospatial.interpolation.GridSampler;
+import com.raytheon.uf.common.geospatial.interpolation.Interpolation;
+import com.raytheon.uf.common.geospatial.interpolation.data.FloatArrayWrapper;
+import com.raytheon.uf.common.geospatial.interpolation.data.FloatBufferWrapper;
+import com.vividsolutions.jts.geom.Coordinate;
+
 /**
  * 
  * A class which holds data for a grid. Includes FloatBuffers for holding scalar
@@ -44,6 +65,8 @@ import javax.measure.unit.Unit;
  */
 public class GeneralGridData {
 
+    private GridGeometry2D gridGeometry;
+
     private FloatBuffer scalarData;
 
     private FloatBuffer direction = null;
@@ -61,9 +84,10 @@ public class GeneralGridData {
      * @param dataUnit
      * @return
      */
-    public static GeneralGridData createScalarData(FloatBuffer scalarData,
+    public static GeneralGridData createScalarData(
+            GeneralGridGeometry gridGeometry, FloatBuffer scalarData,
             Unit dataUnit) {
-        return new GeneralGridData(scalarData, dataUnit);
+        return new GeneralGridData(gridGeometry, scalarData, dataUnit);
     }
 
     /**
@@ -79,11 +103,12 @@ public class GeneralGridData {
      * @param dataUnit
      * @return
      */
-    public static GeneralGridData createVectorData(FloatBuffer magnitude,
+    public static GeneralGridData createVectorData(
+            GeneralGridGeometry gridGeometry, FloatBuffer magnitude,
             FloatBuffer direction, FloatBuffer uComponent,
             FloatBuffer vComponent, Unit dataUnit) {
-        return new GeneralGridData(magnitude, direction, uComponent,
-                vComponent, dataUnit);
+        return new GeneralGridData(gridGeometry, magnitude, direction,
+                uComponent, vComponent, dataUnit);
     }
 
     /**
@@ -95,9 +120,11 @@ public class GeneralGridData {
      * @param dataUnit
      * @return
      */
-    public static GeneralGridData createVectorData(FloatBuffer magnitude,
+    public static GeneralGridData createVectorData(
+            GeneralGridGeometry gridGeometry, FloatBuffer magnitude,
             FloatBuffer direction, Unit dataUnit) {
-        return new GeneralGridData(magnitude, direction, null, null, dataUnit);
+        return new GeneralGridData(gridGeometry, magnitude, direction, null,
+                null, dataUnit);
     }
 
     /**
@@ -109,18 +136,24 @@ public class GeneralGridData {
      * @param dataUnit
      * @return
      */
-    public static GeneralGridData createVectorDataUV(FloatBuffer uComponent,
+    public static GeneralGridData createVectorDataUV(
+            GeneralGridGeometry gridGeometry, FloatBuffer uComponent,
             FloatBuffer vComponent, Unit dataUnit) {
-        return new GeneralGridData(null, null, uComponent, vComponent, dataUnit);
+        return new GeneralGridData(gridGeometry, null, null, uComponent,
+                vComponent, dataUnit);
     }
 
-    private GeneralGridData(FloatBuffer scalarData, Unit dataUnit) {
+    private GeneralGridData(GeneralGridGeometry gridGeometry,
+            FloatBuffer scalarData, Unit dataUnit) {
+        this.gridGeometry = GridGeometry2D.wrap(gridGeometry);
         this.scalarData = scalarData;
         this.dataUnit = dataUnit;
     }
 
-    private GeneralGridData(FloatBuffer magnitude, FloatBuffer direction,
+    private GeneralGridData(GeneralGridGeometry gridGeometry,
+            FloatBuffer magnitude, FloatBuffer direction,
             FloatBuffer uComponent, FloatBuffer vComponent, Unit dataUnit) {
+        this.gridGeometry = GridGeometry2D.wrap(gridGeometry);
         this.scalarData = magnitude;
         this.direction = direction;
         this.uComponent = uComponent;
@@ -138,13 +171,17 @@ public class GeneralGridData {
     public boolean convert(Unit unit) {
         if (dataUnit == null && unit == null) {
             return true;
-        } else if (dataUnit == null) {
+        } else if (dataUnit == null || unit == null) {
             return false;
         }
         if (!dataUnit.isCompatible(unit)) {
             return false;
         }
         UnitConverter converter = dataUnit.getConverterTo(unit);
+        if (converter.equals(UnitConverter.IDENTITY)) {
+            // no need to actually convert if they are the same.
+            return true;
+        }
         if (scalarData != null) {
             scalarData.rewind();
             FloatBuffer newData = FloatBuffer.allocate(scalarData.capacity());
@@ -176,6 +213,65 @@ public class GeneralGridData {
         return true;
     }
 
+    public GeneralGridData reproject(GeneralGridGeometry newGridGeometry,
+            Interpolation interpolation) throws FactoryException,
+            TransformException {
+        GridGeometry2D newGeom = GridGeometry2D.wrap(newGridGeometry);
+        GridReprojection reproj = new GridReprojection(gridGeometry, newGeom);
+        GridSampler sampler = new GridSampler(interpolation);
+        if (isVector()) {
+            sampler.setSource(new FloatBufferWrapper(getUComponent(),
+                    gridGeometry));
+            float[] udata = reproj.reprojectedGrid(sampler,
+                    new FloatArrayWrapper(newGeom)).getArray();
+            sampler.setSource(new FloatBufferWrapper(getVComponent(),
+                    gridGeometry));
+            float[] vdata = reproj.reprojectedGrid(sampler,
+                    new FloatArrayWrapper(newGeom)).getArray();
+            // When reprojecting it is necessary to recalculate the
+            // direction of vectors based off the change in the "up"
+            // direction
+            GridEnvelope2D targetRange = newGeom.getGridRange2D();
+
+            MathTransform grid2crs = newGeom.getGridToCRS();
+            MathTransform crs2ll = MapUtil.getTransformToLatLon(newGeom
+                    .getCoordinateReferenceSystem());
+
+            for (int i = 0; i < targetRange.width; i++) {
+                for (int j = 0; j < targetRange.height; j++) {
+                    int index = i + j * targetRange.width;
+                    if (udata[index] > -9999) {
+                        DirectPosition2D dp = new DirectPosition2D(i, j);
+                        grid2crs.transform(dp, dp);
+                        crs2ll.transform(dp, dp);
+                        Coordinate ll = new Coordinate(dp.x, dp.y);
+                        double rot = MapUtil.rotation(ll, newGeom);
+                        double rot2 = MapUtil.rotation(ll, gridGeometry);
+                        double cos = Math.cos(Math.toRadians(180 + rot - rot2));
+                        double sin = Math.sin(Math.toRadians(180 + rot - rot2));
+                        double u = udata[index];
+                        double v = vdata[index];
+                        udata[index] = (float) (cos * u - sin * v);
+                        vdata[index] = (float) (sin * u + cos * v);
+                    }
+                }
+            }
+            return createVectorDataUV(newGridGeometry, FloatBuffer.wrap(udata),
+                    FloatBuffer.wrap(vdata), dataUnit);
+        } else {
+            sampler.setSource(new FloatBufferWrapper(getScalarData(),
+                    gridGeometry));
+            FloatBuffer data = reproj.reprojectedGrid(sampler,
+                    new FloatBufferWrapper(newGeom)).getBuffer();
+            return createScalarData(newGridGeometry, data, dataUnit);
+        }
+
+    }
+
+    public GridGeometry2D getGridGeometry() {
+        return gridGeometry;
+    }
+
     public boolean isVector() {
         return (scalarData != null && direction != null)
                 || (uComponent != null && vComponent != null);
@@ -253,4 +349,120 @@ public class GeneralGridData {
         return dataUnit;
     }
 
+    /**
+     * Given two grid data with compatible geometries and compatible units, this
+     * will combine them into a single data object. Compatible geometries will
+     * have the same CRS and grid spacing. This function will create a larger
+     * grid geometry which incorporates the data from both sources and fills in
+     * NaN for any areas which are not covered by either source.
+     * 
+     * 
+     * @param data1
+     * @param data2
+     * @return merged data or null if they are not compatible
+     */
+    public static GeneralGridData mergeData(GeneralGridData data1,
+            GeneralGridData data2) {
+        GridGeometry2D geometry1 = data1.getGridGeometry();
+        GridGeometry2D geometry2 = data2.getGridGeometry();
+        CoordinateReferenceSystem crs = geometry1
+                .getCoordinateReferenceSystem();
+        CoordinateReferenceSystem crs2 = geometry2
+                .getCoordinateReferenceSystem();
+        if (!crs.equals(crs2)) {
+            // Coordinate System is different, incompatible
+            return null;
+        }
+        Envelope2D envelope1 = geometry1.getEnvelope2D();
+        GridEnvelope2D range1 = geometry1.getGridRange2D();
+        double dx = envelope1.width / range1.width;
+
+        Envelope2D envelope2 = geometry2.getEnvelope2D();
+        GridEnvelope2D range2 = geometry2.getGridRange2D();
+        double dx2 = envelope2.width / range2.width;
+        if (Math.abs(dx - dx2) > 0.00001) {
+            // X Spacing is different, incompatible
+            return null;
+        }
+        double dy = envelope1.height / range1.height;
+        double dy2 = envelope2.height / range2.height;
+        if (Math.abs(dy - dy2) > 0.00001) {
+            // Y Spacing is different, incompatible
+            return null;
+        }
+        double xShift = (envelope1.getMinX() - envelope2.getMinX()) / dx;
+        if (Math.abs(xShift - Math.round(xShift)) > 0.00001) {
+            // grids are not aligned in the x direction
+            return null;
+        }
+        double yShift = (envelope1.getMinY() - envelope2.getMinY()) / dy;
+        if (Math.abs(yShift - Math.round(yShift)) > 0.00001) {
+            // grids are not aligned in the y direction
+            return null;
+        }
+        if (!data2.convert(data1.getDataUnit())) {
+            // units are not compatible
+            return null;
+        }
+        Rectangle2D rectangle = envelope1.createUnion(envelope2);
+        Envelope2D envelope = new Envelope2D(crs, rectangle);
+        int nx = (int) Math.round(rectangle.getWidth() / dx);
+        int ny = (int) Math.round(rectangle.getHeight() / dy);
+        GridEnvelope2D range = new GridEnvelope2D(0, 0, nx, ny);
+
+        GridGeometry2D geometry = new GridGeometry2D((GridEnvelope) range,
+                (Envelope) envelope);
+        // Shift the ranges to be relative to the new geometry
+        range1.x = (int) Math.round((envelope1.x - envelope.x) / dx);
+        range2.x = (int) Math.round((envelope2.x - envelope.x) / dx);
+        // y axis is swapped, our grids start at upper left and y increases down
+        // and y axis increases up.
+        range1.y = (int) Math.round((envelope.getMaxY() - envelope1.getMaxY())
+                / dy);
+        range2.y = (int) Math.round((envelope.getMaxY() - envelope2.getMaxY())
+                / dy);
+        if (data1.isVector() && data2.isVector()) {
+            FloatBuffer newU = FloatBuffer.allocate(nx * ny);
+            mergeData(data1.getUComponent(), range1, data2.getUComponent(),
+                    range2, newU, range);
+            FloatBuffer newV = FloatBuffer.allocate(nx * ny);
+            mergeData(data1.getVComponent(), range1, data2.getVComponent(),
+                    range2, newV, range);
+            return createVectorDataUV(geometry, newU, newV, data1.getDataUnit());
+        } else {
+            FloatBuffer newData = FloatBuffer.allocate(nx * ny);
+            mergeData(data1.getScalarData(), range1, data2.getScalarData(),
+                    range2, newData, range);
+            return createScalarData(geometry, newData, data1.getDataUnit());
+        }
+    }
+
+    private static void mergeData(FloatBuffer data1, GridEnvelope2D env1,
+            FloatBuffer data2, GridEnvelope2D env2, FloatBuffer destData,
+            GridEnvelope2D destEnv) {
+        data1.rewind();
+        data2.rewind();
+        destData.rewind();
+        for (int y = 0; y < destEnv.height; y++) {
+            for (int x = 0; x < destEnv.width; x++) {
+                float v1 = Float.NaN;
+                float v2 = Float.NaN;
+                if (env1.contains(x, y)) {
+                    v1 = data1.get();
+                }
+                if (env2.contains(x, y)) {
+                    v2 = data2.get();
+                }
+                if (Float.isNaN(v1) && Float.isNaN(v2)) {
+                    destData.put(Float.NaN);
+                } else if (Float.isNaN(v1)) {
+                    destData.put(v2);
+                } else if (Float.isNaN(v2)) {
+                    destData.put(v1);
+                } else {
+                    destData.put((v1 + v2) / 2);
+                }
+            }
+        }
+    }
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridDataRequestJob.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridDataRequestJob.java
index eedacc4350..7040cfe165 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridDataRequestJob.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridDataRequestJob.java
@@ -37,7 +37,7 @@ import com.raytheon.uf.viz.core.exception.VizException;
 
 /**
  * 
- * TODO Add Description
+ * A Job for asynchronously requesting data for GridResources.
  * 
  * 
  * 
@@ -63,7 +63,7 @@ class GridDataRequestJob extends Job {
 
         public final List pdos;
 
-        public GeneralGridData gridData;
+        public List gridData;
 
         public GridDataRequest(DataTime time, List pdos) {
             this.time = time;
@@ -117,7 +117,7 @@ class GridDataRequestJob extends Job {
         return null;
     }
 
-    public GeneralGridData requestData(DataTime time,
+    public List requestData(DataTime time,
             List pdos) {
         synchronized (requests) {
             GridDataRequest request = new GridDataRequest(time, pdos);
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GribGridResource.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridResource.java
similarity index 52%
rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GribGridResource.java
rename to cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridResource.java
index ccdd9f4345..9343dcea25 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GribGridResource.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/general/GridResource.java
@@ -26,11 +26,10 @@ import java.util.List;
 
 import javax.measure.unit.Unit;
 
-import org.geotools.coverage.grid.GridGeometry2D;
+import org.geotools.coverage.grid.GeneralGridGeometry;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
 import com.raytheon.uf.common.datastorage.records.IDataRecord;
 import com.raytheon.uf.common.time.DataTime;
@@ -45,7 +44,7 @@ import com.raytheon.viz.grid.GridLevelTranslator;
 
 /**
  * 
- * TODO Add Description
+ * A version of AbstractGridResource that displays data from GridRecords.
  * 
  * 
  * 
@@ -60,59 +59,61 @@ import com.raytheon.viz.grid.GridLevelTranslator;
  * @author bsteffen
  * @version 1.0
  */
-public class GribGridResource extends
+public class GridResource extends
         AbstractGridResource {
 
-    protected GribModel gribModel;
-
-    public GribGridResource(T resourceData, LoadProperties loadProperties) {
+    public GridResource(T resourceData, LoadProperties loadProperties) {
         super(resourceData, loadProperties);
     }
 
     @Override
-    public void addDataObject(PluginDataObject pdo) {
-        if (pdo instanceof GribRecord) {
-            if (gribModel == null) {
-                GribRecord gribRecord = (GribRecord) pdo;
-                gribModel = gribRecord.getModelInfo();
-            }
-            super.addDataObject(pdo);
-        }
-    }
-
-    @Override
-    public GridGeometry2D getGridGeometry() {
-        return gribModel.getLocation().getGridGeometry();
-    }
-
-    @Override
-    public GeneralGridData getData(DataTime time, List pdos)
-            throws VizException {
+    public List getData(DataTime time,
+            List pdos) throws VizException {
         if (pdos == null) {
             return null;
         }
-        GribRecord gribRecord = (GribRecord) pdos.get(0);
-        Unit dataUnit = gribRecord.getModelInfo().getParameterUnitObject();
-        IDataRecord[] dataRecs = DataCubeContainer.getDataRecord(gribRecord);
-        return getData(dataRecs, dataUnit);
+        List dataList = new ArrayList(
+                pdos.size());
+        for (PluginDataObject pdo : pdos) {
+            GeneralGridData data = getData((GridRecord) pdo);
+            if (data != null) {
+                dataList.add(data);
+            }
+        }
+        return dataList;
     }
 
-    protected GeneralGridData getData(IDataRecord[] dataRecs, Unit dataUnit) {
+    protected GeneralGridData getData(GridRecord gridRecord)
+            throws VizException {
+        Unit dataUnit = gridRecord.getParameter().getUnit();
+        IDataRecord[] dataRecs = DataCubeContainer.getDataRecord(gridRecord);
+        if (dataRecs == null) {
+            return null;
+        }
+        return getData(dataRecs, gridRecord.getLocation().getGridGeometry(),
+                dataUnit);
+    }
+
+    protected GeneralGridData getData(IDataRecord[] dataRecs,
+            GeneralGridGeometry gridGeometry, Unit dataUnit) {
         if (dataRecs.length == 1) {
             if (dataRecs[0] instanceof FloatDataRecord) {
-                return GeneralGridData.createScalarData(
+                return GeneralGridData.createScalarData(gridGeometry,
                         wrapDataRecord(dataRecs[0]), dataUnit);
+
             }
         } else if (dataRecs.length == 2) {
             FloatBuffer mag = wrapDataRecord(dataRecs[0]);
             FloatBuffer dir = wrapDataRecord(dataRecs[1]);
-            return GeneralGridData.createVectorData(mag, dir, dataUnit);
+            return GeneralGridData.createVectorData(gridGeometry, mag, dir,
+                    dataUnit);
         } else if (dataRecs.length == 4) {
             FloatBuffer mag = wrapDataRecord(dataRecs[0]);
             FloatBuffer dir = wrapDataRecord(dataRecs[1]);
             FloatBuffer u = wrapDataRecord(dataRecs[2]);
             FloatBuffer v = wrapDataRecord(dataRecs[3]);
-            return GeneralGridData.createVectorData(mag, dir, u, v, dataUnit);
+            return GeneralGridData.createVectorData(gridGeometry, mag, dir, u,
+                    v, dataUnit);
         }
         return null;
     }
@@ -133,38 +134,60 @@ public class GribGridResource extends
 
     @Override
     public ParamLevelMatchCriteria getMatchCriteria() {
-        if (gribModel == null) {
+        GridRecord record = getAnyGridRecord();
+        if (record == null) {
             return null;
         }
-        ParamLevelMatchCriteria criteria = new ParamLevelMatchCriteria();
-        criteria.setParameterName(new ArrayList());
-        criteria.setLevels(new ArrayList());
-        criteria.setCreatingEntityNames(new ArrayList());
-        String parameter = gribModel.getParameterAbbreviation();
-        SingleLevel level = GridLevelTranslator.constructMatching(gribModel
+        ParamLevelMatchCriteria matchCriteria = new ParamLevelMatchCriteria();
+        matchCriteria.setParameterName(new ArrayList());
+        matchCriteria.setLevels(new ArrayList());
+        matchCriteria.setCreatingEntityNames(new ArrayList());
+        String parameter = record.getParameter().getAbbreviation();
+        SingleLevel level = GridLevelTranslator.constructMatching(record
                 .getLevel());
-        String creatingEntity = gribModel.getModelName();
-        if (!criteria.getParameterNames().contains(parameter)) {
-            criteria.getParameterNames().add(parameter);
+        String creatingEntity = record.getDatasetId();
+        if (!matchCriteria.getParameterNames().contains(parameter)) {
+            matchCriteria.getParameterNames().add(parameter);
         }
-        if (!criteria.getLevels().contains(level)) {
-            criteria.getLevels().add(level);
+        if (!matchCriteria.getLevels().contains(level)) {
+            matchCriteria.getLevels().add(level);
         }
-        if (!criteria.getCreatingEntityNames().contains(creatingEntity)) {
-            criteria.getCreatingEntityNames().add(creatingEntity);
+        if (!matchCriteria.getCreatingEntityNames().contains(creatingEntity)) {
+            matchCriteria.getCreatingEntityNames().add(creatingEntity);
         }
-        return criteria;
+        return matchCriteria;
     }
 
     @Override
     public String getName() {
-        if (gribModel == null) {
+        GridRecord record = getCurrentGridRecord();
+        if (record == null) {
             return "Grib Data";
-        } else {
-            return gribModel.getModelTitle() + " "
-                    + gribModel.getLevel().toString() + " "
-                    + gribModel.getParameterName();
         }
+        return record.getDatasetId() + " " + record.getLevel().toString() + " "
+                + record.getParameter().getName();
+    }
+
+    protected GridRecord getCurrentGridRecord() {
+        List pdos = getCurrentPluginDataObjects();
+        if (pdos == null || pdos.isEmpty()) {
+            return null;
+        }
+        return (GridRecord) pdos.get(0);
+    }
+
+    protected GridRecord getAnyGridRecord() {
+        GridRecord record = getCurrentGridRecord();
+        if (record == null) {
+            for (DataTime time : getDataTimes()) {
+                List pdos = getPluginDataObjects(time);
+                if (pdos != null && !pdos.isEmpty()) {
+                    record = (GridRecord) pdos.get(0);
+                    break;
+                }
+            }
+        }
+        return record;
     }
 
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/spatial/StereographicCoverage.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/spatial/StereographicCoverage.java
deleted file mode 100644
index 1bb63ece43..0000000000
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/spatial/StereographicCoverage.java
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.viz.grid.spatial;
-
-import org.apache.commons.lang.builder.HashCodeBuilder;
-
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid;
-import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef;
-
-/**
- * Stereographic Coverage used by radar data.
- * 
- * 
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Apr 7, 2010  #4473     rjpeter     Initial creation
- * 
- * 
- * - * @author rjpeter - * @version 1.0 - */ - -public class StereographicCoverage extends GridCoverage { - private Integer nx; - - private Integer ny; - - @Override - public void generateName() { - } - - @Override - public String getProjectionType() { - return "Stereographic"; - } - - @Override - public void initialize() throws GribException { - } - - @Override - public GridCoverage trim(SubGridDef subGridDef, SubGrid subGrid) { - // NOT SUPPORTED - return null; - } - - @Override - public Integer getNx() { - return nx; - } - - @Override - public Integer getNy() { - return ny; - } - - public void setNx(Integer nx) { - this.nx = nx; - } - - public void setNy(Integer ny) { - this.ny = ny; - } - - @Override - public int generateHash() { - HashCodeBuilder hashBuilder = new HashCodeBuilder(); - hashBuilder.append(nx); - hashBuilder.append(ny); - hashBuilder.append(gridGeometry); - hashBuilder.append(crs); - return hashBuilder.toHashCode(); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - StereographicCoverage other = (StereographicCoverage) obj; - if (nx == null) { - if (other.nx != null) - return false; - } else if (!nx.equals(other.nx)) - return false; - if (ny == null) { - if (other.ny != null) - return false; - } else if (!ny.equals(other.ny)) - return false; - if (gridGeometry == null) { - if (other.gridGeometry != null) - return false; - } else if (!gridGeometry.equals(other.gridGeometry)) - return false; - if (crs == null) { - if (other.crs != null) - return false; - } else if (!crs.equals(other.crs)) - return false; - return true; - } -} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/units/GridUnits.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/units/GridUnits.java index d542b3dba9..837a58b77f 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/units/GridUnits.java +++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/units/GridUnits.java @@ -19,14 +19,10 @@ **/ package com.raytheon.viz.grid.units; -import javax.measure.unit.NonSI; -import javax.measure.unit.SI; -import javax.measure.unit.UnitFormat; - import com.raytheon.viz.core.units.IUnitRegistrar; /** - * TODO Add Description + * registrar for nonstandard units used by grid * *
  * 
@@ -50,20 +46,7 @@ public class GridUnits implements IUnitRegistrar {
      */
     @Override
     public void register() {
-        UnitFormat.getInstance().alias(SI.METER, "gpm");
-        UnitFormat.getUCUMInstance().alias(SI.METER, "gpm");
-        UnitFormat.getInstance().alias(SI.MILLI(NonSI.BAR), "mb");
-        UnitFormat.getUCUMInstance().alias(SI.MILLI(NonSI.BAR), "mb");
-        UnitFormat.getInstance().alias(SI.CELSIUS, "C");
-        UnitFormat.getUCUMInstance().alias(SI.CELSIUS, "C");
-        UnitFormat.getInstance().alias(NonSI.FAHRENHEIT, "F");
-        UnitFormat.getUCUMInstance().alias(NonSI.FAHRENHEIT, "F");
-        UnitFormat.getInstance().alias(NonSI.DEGREE_ANGLE, "deg");
-        UnitFormat.getUCUMInstance().alias(NonSI.DEGREE_ANGLE, "deg");
-        UnitFormat.getInstance().alias(NonSI.KNOT, "kt");
-        UnitFormat.getUCUMInstance().alias(NonSI.KNOT, "kt");
-        UnitFormat.getInstance().alias(SI.SECOND, "sec");
-        UnitFormat.getUCUMInstance().alias(SI.SECOND, "sec");
+        com.raytheon.uf.common.dataplugin.grid.units.GridUnits.register();
     }
 
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/CoverageUtils.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/CoverageUtils.java
index adab327886..ad17118350 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/CoverageUtils.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/CoverageUtils.java
@@ -26,8 +26,10 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import javax.media.jai.BorderExtender;
 import javax.media.jai.Interpolation;
@@ -42,16 +44,24 @@ import org.geotools.coverage.grid.ViewType;
 import org.geotools.coverage.processing.Operations;
 import org.opengis.geometry.Envelope;
 
-import com.raytheon.uf.common.dataplugin.grib.request.GetCoverageRequest;
-import com.raytheon.uf.common.dataplugin.grib.request.GetCoveragesRequest;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridInfoConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridInfoRecord;
+import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
+import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
+import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
 import com.raytheon.uf.common.geospatial.MapUtil;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
+import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup;
+import com.raytheon.uf.viz.core.alerts.AlertMessage;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.core.requests.ThriftClient;
+import com.raytheon.viz.alerts.IAlertObserver;
+import com.raytheon.viz.alerts.observers.ProductAlertObserver;
 
 /**
- * TODO Add Description
+ * Cache for coverages as well as several utility methods for reprojecting data.
  * 
  * 
  * 
@@ -66,10 +76,12 @@ import com.raytheon.uf.viz.core.requests.ThriftClient;
  * @version 1.0
  */
 
-public class CoverageUtils {
+public class CoverageUtils implements IAlertObserver {
     private static CoverageUtils instance;
 
-    private final Map coverageCache = new HashMap();
+    private final Map> coverageCache = new HashMap>();
+
+    private boolean hasPerformedBulkQuery = false;
 
     private CoverageUtils() {
     }
@@ -77,62 +89,67 @@ public class CoverageUtils {
     public static synchronized CoverageUtils getInstance() {
         if (instance == null) {
             instance = new CoverageUtils();
+            ProductAlertObserver.addObserver(GridConstants.GRID, instance);
         }
 
         return instance;
     }
 
-    public GridCoverage getCoverage(String modelName) throws VizException {
-        synchronized (coverageCache) {
-            GridCoverage rval = coverageCache.get(modelName);
-
-            if (rval == null) {
-                GetCoverageRequest request = new GetCoverageRequest();
-                request.setModelName(modelName);
-                Object obj = ThriftClient.sendRequest(request);
-
-                if (obj != null) {
-                    if (obj instanceof GridCoverage) {
-                        rval = (GridCoverage) obj;
-                        coverageCache.put(modelName, rval);
-                    } else {
-                        throw new VizException(
-                                "GetCoverageRequest returned object of type ["
-                                        + obj.getClass().getName()
-                                        + "], expected ["
-                                        + GridCoverage.class.getName() + "]");
-                    }
-                }
-            }
-            return rval;
-        }
-    }
-
-    public Map getCoverages(Collection modelNames)
+    /**
+     * Return an unordered collection of all GridCoverages that are used for a
+     * given datasetId.
+     * 
+     * @param datasetId
+     * @return
+     * @throws VizException
+     */
+    public Collection getCoverages(String datasetId)
             throws VizException {
-        Map coverages = new HashMap();
-        List toRequest = new ArrayList();
-        synchronized (coverageCache) {
-            for (String modelName : modelNames) {
-                GridCoverage coverage = coverageCache.get(modelName);
-                if (coverage == null) {
-                    toRequest.add(modelName);
-                } else {
-                    coverages.put(modelName, coverage);
-                }
+        Collection rval = coverageCache.get(datasetId);
+
+        if (rval == null) {
+            DbQueryRequest query = new DbQueryRequest();
+            query.setEntityClass(GridInfoRecord.class.getName());
+            query.setDistinct(true);
+            query.addRequestField(GridInfoConstants.DATASET_ID);
+            query.addRequestField(GridInfoConstants.LOCATION_ID);
+            if (hasPerformedBulkQuery) {
+                // first time through just request everything.
+                // if the cache is empty request data for all models.
+                query.addConstraint(GridInfoConstants.DATASET_ID,
+                        new RequestConstraint(datasetId));
             }
-            if (!toRequest.isEmpty()) {
-                GetCoveragesRequest request = new GetCoveragesRequest();
-                request.setModelNames(toRequest);
-                List list = (List) ThriftClient.sendRequest(request);
-                for (int i = 0; i < list.size(); i++) {
-                    coverageCache.put(toRequest.get(i),
-                            (GridCoverage) list.get(i));
-                    coverages.put(toRequest.get(i), (GridCoverage) list.get(i));
-                }
+            hasPerformedBulkQuery = true;
+            DbQueryResponse resp = (DbQueryResponse) ThriftClient
+                    .sendRequest(query);
+            // do a bulk request to GridCoverageLookup as it enables more
+            // possible optimizations.
+            List locationsToRequest = new ArrayList(resp
+                    .getResults().size());
+            for (Map map : resp.getResults()) {
+                Integer locationId = (Integer) map
+                        .get(GridInfoConstants.LOCATION_ID);
+                locationsToRequest.add(locationId);
             }
+            Map requestedLocations = GridCoverageLookup
+                    .getInstance().getCoverages(locationsToRequest);
+            for (Map map : resp.getResults()) {
+                Integer locationId = (Integer) map
+                        .get(GridInfoConstants.LOCATION_ID);
+                String resultId = (String) map
+                        .get(GridInfoConstants.DATASET_ID);
+                GridCoverage coverage = requestedLocations.get(locationId);
+                Set set = coverageCache.get(resultId);
+                if (set == null) {
+                    set = new HashSet();
+                    coverageCache.put(resultId, set);
+                }
+                set.add(coverage);
+            }
+            rval = coverageCache.get(datasetId);
         }
-        return coverages;
+
+        return rval;
     }
 
     /**
@@ -144,14 +161,19 @@ public class CoverageUtils {
      */
     public void setCoverage(String modelName, GridCoverage coverage) {
         if (modelName != null && coverage != null) {
-            coverageCache.put(modelName, coverage);
+            Set set = coverageCache.get(modelName);
+            if (set == null) {
+                set = new HashSet();
+                coverageCache.put(modelName, set);
+            }
+            set.add(coverage);
         }
     }
 
-    public synchronized RemappedImage remapGrid(GridCoverage sourceGrid,
+    public RemappedImage remapGrid(GridCoverage sourceGrid,
             GridCoverage destinationGrid, FloatDataRecord inputData,
             Interpolation interpolation) throws VizException {
-        if (sourceGrid.getName().equals(destinationGrid.getName())) {
+        if (sourceGrid.getId().equals(destinationGrid.getId())) {
             // we don't need to remap anything. the grids are the same
             return new RemappedImage(inputData);
         }
@@ -297,4 +319,18 @@ public class CoverageUtils {
         return scaledImg;
     }
 
+    @Override
+    public void alertArrived(Collection alertMessages) {
+        for (AlertMessage alertMessage : alertMessages) {
+            String datasetId = (String) alertMessage.decodedAlert
+                    .get(GridConstants.DATASET_ID);
+            GridCoverage coverage = (GridCoverage) alertMessage.decodedAlert
+                    .get(GridConstants.LOCATION);
+            Set set = coverageCache.get(datasetId);
+            if (set != null && coverage != null) {
+                set.add(coverage);
+            }
+        }
+    }
+
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GribDataCubeAdapter.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridDataCubeAdapter.java
similarity index 73%
rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GribDataCubeAdapter.java
rename to cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridDataCubeAdapter.java
index dd2e5c7bc6..80b00bcd3d 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GribDataCubeAdapter.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridDataCubeAdapter.java
@@ -24,6 +24,7 @@ import java.io.File;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Calendar;
+import java.util.Collection;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Iterator;
@@ -35,7 +36,9 @@ import java.util.Set;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
 import com.raytheon.uf.common.dataplugin.PluginException;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridPathProvider;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
 import com.raytheon.uf.common.datastorage.DataStoreFactory;
 import com.raytheon.uf.common.datastorage.IDataStore;
@@ -44,10 +47,10 @@ import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
 import com.raytheon.uf.common.datastorage.records.IDataRecord;
 import com.raytheon.uf.common.geospatial.ISpatialEnabled;
 import com.raytheon.uf.common.geospatial.ISpatialObject;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
-import com.raytheon.uf.common.status.UFStatus.Priority;
 import com.raytheon.uf.common.time.DataTime;
 import com.raytheon.uf.viz.core.HDF5Util;
 import com.raytheon.uf.viz.core.catalog.LayerProperty;
@@ -56,14 +59,18 @@ import com.raytheon.uf.viz.core.datastructure.VizDataCubeException;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractDataCubeAdapter;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
+import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer;
+import com.raytheon.uf.viz.derivparam.inv.MetadataContainer;
 import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
-import com.raytheon.viz.grid.data.GribRequestableData;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
+import com.raytheon.viz.grid.data.GridRequestableData;
 import com.raytheon.viz.grid.inv.GridInventory;
+import com.raytheon.viz.grid.inv.GridMetadataContainer;
 import com.raytheon.viz.grid.record.RequestableDataRecord;
 
 /**
- * TODO Add Description
+ * DataCubeAdapter for Grid, the primary role is to link the grid datatype into
+ * derived parameters.
  * 
  * 
  * 
@@ -77,12 +84,12 @@ import com.raytheon.viz.grid.record.RequestableDataRecord;
  * @author brockwoo
  * @version 1.0
  */
-public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
+public class GridDataCubeAdapter extends AbstractDataCubeAdapter {
     private static final transient IUFStatusHandler statusHandler = UFStatus
-            .getHandler(GribDataCubeAdapter.class);
+            .getHandler(GridDataCubeAdapter.class);
 
-    public GribDataCubeAdapter() {
-        super(new String[] { "grib" });
+    public GridDataCubeAdapter() {
+        super(new String[] { GridConstants.GRID });
     }
 
     private GridInventory gridInventory;
@@ -117,14 +124,17 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
         }
         try {
             IDataRecord record = null;
-            if (((GribRecord) obj).getModelInfo().getParameterAbbreviation()
-                    .equals("staticTopo")) {
+            if (GridPathProvider.STATIC_PARAMETERS.contains(((GridRecord) obj)
+                    .getParameter().getAbbreviation())) {
+                GridRecord gridRec = (GridRecord) obj;
                 IDataStore ds = DataStoreFactory.getDataStore(HDF5Util
                         .findHDF5Location(obj));
                 try {
-                    record = ds.retrieve("/", "staticTopo", req);
+                    record = ds.retrieve("/" + gridRec.getLocation().getId(),
+                            gridRec.getParameter().getAbbreviation(), req);
                 } catch (Exception e) {
-                    throw new VizException("Error retrieving staticTopo data!");
+                    throw new VizException("Error retrieving staticTopo data!",
+                            e);
                 }
             } else {
                 record = CubeUtil.retrieveData(obj, obj.getPluginName(), req,
@@ -266,7 +276,7 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
     @Override
     public void getRecords(List objs, Request req,
             String dataset) throws VizDataCubeException {
-        Set realData = new HashSet();
+        Set realData = new HashSet();
         ISpatialObject area = null;
         for (PluginDataObject obj : objs) {
             if (area == null) {
@@ -277,19 +287,19 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
             }
         }
 
-        Map> fileMap = new HashMap>();
-        for (GribRequestableData data : realData) {
-            if (data.getGribSource().getModelInfo().getParameterAbbreviation()
-                    .equals("staticTopo")) {
+        Map> fileMap = new HashMap>();
+        for (GridRequestableData data : realData) {
+            if (GridPathProvider.STATIC_PARAMETERS.contains(data
+                    .getGridSource().getParameter().getAbbreviation())) {
                 continue;
             }
-            GribRecord record = data.getGribSource();
-            area = record.getSpatialObject();
+            GridRecord record = data.getGridSource();
+            area = record.getLocation();
             String file = HDF5Util.findHDF5Location(record).getAbsolutePath();
             if (file != null) {
-                List list = fileMap.get(file);
+                List list = fileMap.get(file);
                 if (list == null) {
-                    list = new LinkedList();
+                    list = new LinkedList();
                     fileMap.put(file, list);
                 }
                 list.add(data);
@@ -308,12 +318,12 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
         if (!realData.isEmpty()) {
             // The values are held weakly in cache, so we hold them strongly
             // here to prevent them from getting garbage collected to soon
-            for (Entry> entry : fileMap
+            for (Entry> entry : fileMap
                     .entrySet()) {
-                List list = entry.getValue();
-                Iterator iter = list.iterator();
+                List list = entry.getValue();
+                Iterator iter = list.iterator();
                 while (iter.hasNext()) {
-                    GribRequestableData data = iter.next();
+                    GridRequestableData data = iter.next();
                     if (!data.needsRequest(request)) {
                         iter.remove();
                     }
@@ -321,8 +331,8 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
 
                 if (list.size() > 0) {
                     List groups = new ArrayList(list.size());
-                    for (GribRequestableData data : list) {
-                        groups.add(data.getGribSource().getDataURI());
+                    for (GridRequestableData data : list) {
+                        groups.add(data.getGridSource().getDataURI());
                     }
 
                     IDataStore ds = DataStoreFactory.getDataStore(new File(
@@ -333,7 +343,7 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
                                 groups.toArray(new String[groups.size()]),
                                 request);
                         for (int i = 0; i < list.size(); i++) {
-                            GribRequestableData data = list.get(i);
+                            GridRequestableData data = list.get(i);
                             IDataRecord[] value = new IDataRecord[] { records[i] };
                             references.add(value);
                             data.setDataValue(request, value);
@@ -376,7 +386,7 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
      * evaluateRequestConstraints(java.util.Map)
      */
     @Override
-    protected List evaluateRequestConstraints(
+    protected List evaluateRequestConstraints(
             Map constraints) {
         return gridInventory.evaluateRequestConstraints(constraints);
     }
@@ -406,13 +416,16 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
             List requesters) throws VizException {
         List results = new ArrayList(requesters.size());
         for (AbstractRequestableData requester : requesters) {
-            if (requester.getDataTime() == null) {
+            List records = new ArrayList();
+            if (requester.getDataTime() == null
+                    || requester.getTimeAndSpace().isTimeAgnostic()) {
                 DataTime[] entryTime = property.getSelectedEntryTime();
                 if (entryTime != null && entryTime.length > 0) {
                     List entryTimes = new ArrayList(
                             Arrays.asList(entryTime));
                     for (DataTime time : entryTimes) {
-                        GribRecord rec = new RequestableDataRecord(requester);
+                        RequestableDataRecord rec = new RequestableDataRecord(
+                                requester);
                         rec.setDataTime(time.clone());
                         try {
                             rec.setDataURI(null);
@@ -422,37 +435,78 @@ public class GribDataCubeAdapter extends AbstractDataCubeAdapter {
                         }
                         boolean n = true;
                         for (Object result : results) {
-                            if (((GribRecord) result).getDataURI().equals(
+                            if (((GridRecord) result).getDataURI().equals(
                                     rec.getDataURI())) {
                                 n = false;
+                                break;
                             }
                         }
                         if (n) {
-                            results.add(rec);
+                            records.add(rec);
                         }
                     }
                 } else {
-                    GribRecord rec = new RequestableDataRecord(requester);
+                    RequestableDataRecord rec = new RequestableDataRecord(
+                            requester);
                     rec.setDataTime(new DataTime(Calendar.getInstance()));
-                    results.add(rec);
+                    records.add(rec);
                 }
             } else {
-                GribRecord rec = new RequestableDataRecord(requester);
-                results.add(rec);
+                RequestableDataRecord rec = new RequestableDataRecord(requester);
+                records.add(rec);
             }
+            if (requester.getSpace() == null
+                    || requester.getTimeAndSpace().isSpaceAgnostic()) {
+                Collection coverages = CoverageUtils
+                        .getInstance().getCoverages(requester.getSource());
+                if (coverages != null && !coverages.isEmpty()) {
+                    List spaceRecords = new ArrayList();
+                    for (RequestableDataRecord record : records) {
+                        for (GridCoverage coverage : coverages) {
+                            record = new RequestableDataRecord(record);
+                            record.setLocation(coverage);
+                            try {
+                                record.setDataURI(null);
+                                record.constructDataURI();
+                            } catch (PluginException e) {
+                                throw new VizException(e);
+                            }
+                            spaceRecords.add(record);
+                        }
+                    }
+                    records = spaceRecords;
+                }
+            }
+            results.addAll(records);
         }
         if (property.getEntryQueryParameters(false).containsKey(
-                GridInventory.PERT_QUERY)) {
-            String pert = property.getEntryQueryParameters(false)
-                    .get(GridInventory.PERT_QUERY).getConstraintValue();
-            if (pert != null) {
+                GridInventory.ENSEMBLE_QUERY)) {
+            String ensemble = property.getEntryQueryParameters(false)
+                    .get(GridInventory.ENSEMBLE_QUERY).getConstraintValue();
+            if (ensemble != null) {
                 for (Object rec : results) {
-                    ((GribRecord) rec).getModelInfo().setPerturbationNumber(
-                            Integer.parseInt(pert));
+                    ((GridRecord) rec).setEnsembleId(ensemble);
                 }
             }
         }
         return results;
     }
 
+    @Override
+    protected MetadataContainer createMetadataContainer(
+            Map constraints) {
+        return new GridMetadataContainer(constraints,
+                createAvailabilityContainer(constraints));
+    }
+
+    @Override
+    protected AvailabilityContainer createAvailabilityContainer(
+            Map constraints) {
+        // using a grid specific container which is able to merge constraints
+        // will result in faster database queries, however the extra processing
+        // time it takes to route the times to the correct nodes is larger than
+        // the time saved.
+        return super.createAvailabilityContainer(constraints);
+    }
+
 }
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridTreeGrapher.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridTreeGrapher.java
index f9531b06ff..c18022f17d 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridTreeGrapher.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/GridTreeGrapher.java
@@ -20,24 +20,21 @@
 package com.raytheon.viz.grid.util;
 
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 
 import com.raytheon.uf.common.dataplugin.level.Level;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
 import com.raytheon.uf.common.derivparam.tree.LevelNode;
-import com.raytheon.uf.viz.core.catalog.LayerProperty;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
 import com.raytheon.uf.viz.derivparam.data.FloatRequestableData;
 import com.raytheon.uf.viz.derivparam.library.IDerivParamField;
-import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode.Dependency;
+import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode.Dependency;
 import com.raytheon.uf.viz.derivparam.tree.DerivedLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.StaticDataLevelNode;
-import com.raytheon.viz.grid.inv.GribRequestableLevelNode;
 import com.raytheon.viz.grid.inv.GridInventory;
+import com.raytheon.viz.grid.inv.GridRequestableNode;
 
 /**
  * This is a tool intended only for use by developers to help to visualize the
@@ -114,12 +111,8 @@ public class GridTreeGrapher {
             }
         } else if (node instanceof StaticDataLevelNode) {
             StaticDataLevelNode cNode = (StaticDataLevelNode) node;
-            AbstractRequestableData staticData = cNode
-                    .getData(
-                            new LayerProperty(),
-                            0,
-                            new HashMap>())
-                    .get(0);
+            AbstractRequestableData staticData = cNode.getData(null, null)
+                    .iterator().next();
             if (staticData instanceof FloatRequestableData) {
                 String abbr = node.getClass().getSimpleName();
                 if (cNode.getDesc() != null) {
@@ -142,8 +135,8 @@ public class GridTreeGrapher {
                     System.out.println("node" + i + " -> node" + that);
                 }
             }
-        } else if (node instanceof AbstractDerivedLevelNode) {
-            AbstractDerivedLevelNode cNode = (AbstractDerivedLevelNode) node;
+        } else if (node instanceof AbstractDerivedDataNode) {
+            AbstractDerivedDataNode cNode = (AbstractDerivedDataNode) node;
             String abbr = node.getClass().getSimpleName();
             if (cNode.getDesc() != null) {
                 abbr = cNode.getDesc().getAbbreviation();
@@ -158,10 +151,10 @@ public class GridTreeGrapher {
         } else if (node instanceof FloatRequestableData) {
             System.out.println("node" + i + " [label=\"Constant: "
                     + ((FloatRequestableData) node).getDataValue() + "\"];");
-        } else if (node instanceof GribRequestableLevelNode) {
-            Map rcMap = ((GribRequestableLevelNode) node)
+        } else if (node instanceof GridRequestableNode) {
+            Map rcMap = ((GridRequestableNode) node)
                     .getRequestConstraintMap();
-            Level level = ((GribRequestableLevelNode) node).getLevel();
+            Level level = ((GridRequestableNode) node).getLevel();
             String label = rcMap.get(GridInventory.MODEL_NAME_QUERY)
                     .getConstraintValue()
                     + "\\n"
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/RadarAdapter.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/RadarAdapter.java
index 7d2c2b252a..b073829afa 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/RadarAdapter.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/RadarAdapter.java
@@ -28,9 +28,7 @@ import java.util.Set;
 
 import javax.measure.unit.Unit;
 
-import org.geotools.coverage.grid.GridGeometry2D;
 import org.geotools.geometry.DirectPosition2D;
-import org.opengis.geometry.DirectPosition;
 import org.opengis.referencing.crs.ProjectedCRS;
 import org.opengis.referencing.operation.MathTransform;
 
@@ -47,6 +45,11 @@ import com.raytheon.uf.common.derivparam.tree.LevelNode;
 import com.raytheon.uf.common.derivparam.tree.ParameterNode;
 import com.raytheon.uf.common.derivparam.tree.SourceNode;
 import com.raytheon.uf.common.geospatial.MapUtil;
+import com.raytheon.uf.common.gridcoverage.Corner;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
+import com.raytheon.uf.common.gridcoverage.StereographicGridCoverage;
+import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException;
+import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
@@ -59,14 +62,13 @@ import com.raytheon.uf.viz.core.style.level.Level.LevelType;
 import com.raytheon.uf.viz.core.style.level.SingleLevel;
 import com.raytheon.uf.viz.derivparam.library.DerivParamDesc;
 import com.raytheon.uf.viz.derivparam.library.DerivParamMethod;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
 import com.raytheon.uf.viz.derivparam.tree.OrLevelNode;
 import com.raytheon.uf.viz.derivparam.tree.StaticDataLevelNode;
 import com.raytheon.viz.core.drawables.ColorMapParameterFactory;
 import com.raytheon.viz.grid.data.TopoRequestableData;
 import com.raytheon.viz.grid.inv.RadarRequestableLevelNode;
 import com.raytheon.viz.grid.inv.RadarUpdater;
-import com.raytheon.viz.grid.spatial.StereographicCoverage;
 import com.raytheon.viz.radar.util.StationUtils;
 
 /**
@@ -117,11 +119,7 @@ public class RadarAdapter {
 
     private RadarStation configuredRadar = null;
 
-    private ProjectedCRS crs = null;
-
-    private GridGeometry2D gridGeometry = null;
-
-    private StereographicCoverage coverage = null;
+    private GridCoverage coverage = null;
 
     static {
         instance = new RadarAdapter();
@@ -143,37 +141,41 @@ public class RadarAdapter {
                     || !configuredRadar.getRdaId().equals(station.getRdaId())) {
                 configuredRadar = station;
                 RadarUpdater.getInstance().clearCache();
-                crs = RadarUtil
-                        .constructCRS(station.getLat(), station.getLon());
-                gridGeometry = RadarUtil.constructGridGeometry(crs,
-                        (double) GRID_SPACING * GRID_SIZE / 2, GRID_SIZE);
-                coverage = new StereographicCoverage();
+                ProjectedCRS crs = RadarUtil.constructCRS(station.getLat(),
+                        station.getLon());
+                StereographicGridCoverage coverage = new StereographicGridCoverage();
                 coverage.setNx(GRID_SIZE);
                 coverage.setNy(GRID_SIZE);
-                coverage.setCrs(crs);
+                coverage.setDx(GRID_SPACING);
+                coverage.setDy(GRID_SPACING);
+                coverage.setLov(station.getLon());
+                coverage.setLad(station.getLat());
                 coverage.setSpacingUnit("m");
-                coverage.setGridGeometry(gridGeometry);
-
+                coverage.setName(station.getRdaId() + " Generated Coverage");
                 try {
                     MathTransform toLatLon = MapUtil.getTransformToLatLon(crs);
-                    DirectPosition lowerCorner = gridGeometry.getEnvelope()
-                            .getLowerCorner();
-                    DirectPosition upperCorner = gridGeometry.getEnvelope()
-                            .getUpperCorner();
-                    DirectPosition2D lowerCornerLL = new DirectPosition2D();
-                    DirectPosition2D upperCornerLL = new DirectPosition2D();
-                    toLatLon.transform(lowerCorner, lowerCornerLL);
-                    toLatLon.transform(upperCorner, upperCornerLL);
-
-                    // TODO verify upper left vs upper right
-                    coverage.setGeometry(MapUtil.createGeometry(
-                            upperCornerLL.y, upperCornerLL.x, lowerCornerLL.y,
-                            lowerCornerLL.x));
+                    int minExtent = -1 * GRID_SPACING * GRID_SIZE / 2;
+                    DirectPosition2D lowerLeft = new DirectPosition2D(
+                            minExtent, minExtent);
+                    toLatLon.transform(lowerLeft, lowerLeft);
+                    coverage.setFirstGridPointCorner(Corner.LowerLeft);
+                    coverage.setLa1(lowerLeft.getY());
+                    coverage.setLo1(lowerLeft.getX());
                 } catch (Exception e) {
                     // shouldn't occur since parsing well known geometry
                 }
-
-                CoverageUtils.getInstance().setCoverage(RADAR_SOURCE, coverage);
+                try {
+                    coverage.initialize();
+                } catch (GridCoverageException e) {
+                    statusHandler.handle(Priority.PROBLEM,
+                            e.getLocalizedMessage(), e);
+                    configuredRadar = null;
+                    return status;
+                }
+                this.coverage = GridCoverageLookup.getInstance().getCoverage(
+                        coverage, true);
+                CoverageUtils.getInstance().setCoverage(RADAR_SOURCE,
+                        this.coverage);
 
                 System.out.println("Home RADAR set to "
                         + configuredRadar.getRdaId());
@@ -266,12 +268,9 @@ public class RadarAdapter {
                             if (gridLevelNode == null) {
                                 DerivParamMethod method = new DerivParamMethod();
                                 method.setName("Supplement");
-                                gridLevelNode = new OrLevelNode(
-                                        l,
-                                        desc,
-                                        method,
-                                        RADAR_SOURCE,
-                                        new ArrayList(
+                                gridLevelNode = new OrLevelNode(l, desc,
+                                        method, RADAR_SOURCE,
+                                        new ArrayList(
                                                 productCodes.size()), false);
                                 gridParameterNode.addChildNode(gridLevelNode);
                             }
@@ -326,9 +325,11 @@ public class RadarAdapter {
         topoParam.setParameterUnit("m");
         topoParam.setValue("Topo");
 
-        StaticDataLevelNode topoNode = new StaticDataLevelNode(sfc, topo,
-                new TopoRequestableData(modelNameNode.getValue()),
+        TopoRequestableData topoData = new TopoRequestableData(
                 modelNameNode.getValue());
+        topoData.setSpace(getCoverage());
+        StaticDataLevelNode topoNode = new StaticDataLevelNode(sfc, topo,
+                topoData, modelNameNode.getValue());
         topoNode.setLevel(sfc);
         topoParam.addChildNode(topoNode);
         modelNameNode.addChildNode(topoParam);
@@ -360,10 +361,6 @@ public class RadarAdapter {
         return rval;
     }
 
-    public ProjectedCRS getCrs() {
-        return crs;
-    }
-
     public static int getGridSize() {
         return GRID_SIZE;
     }
@@ -372,11 +369,7 @@ public class RadarAdapter {
         return GRID_SPACING;
     }
 
-    public GridGeometry2D getGridGeometry() {
-        return gridGeometry;
-    }
-
-    public StereographicCoverage getCoverage() {
+    public GridCoverage getCoverage() {
         return coverage;
     }
 
diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/TiltUtils.java b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/TiltUtils.java
index b69a2e77dc..0794289056 100644
--- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/TiltUtils.java
+++ b/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/util/TiltUtils.java
@@ -30,11 +30,10 @@ import org.geotools.referencing.GeodeticCalculator;
 import org.opengis.referencing.operation.MathTransform;
 import org.opengis.referencing.operation.TransformException;
 
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage;
 import com.raytheon.uf.common.dataplugin.radar.RadarStation;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
 import com.raytheon.uf.common.geospatial.MapUtil;
+import com.raytheon.uf.common.gridcoverage.GridCoverage;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
@@ -62,13 +61,13 @@ public class TiltUtils {
 
     private static class CacheKey {
 
-        private final int coverageId;
+        private final Integer coverageId;
 
         private final double lat;
 
         private final double lon;
 
-        public CacheKey(int coverageId, double lon, double lat) {
+        public CacheKey(Integer coverageId, double lon, double lat) {
             this.coverageId = coverageId;
             this.lat = lat;
             this.lon = lon;
@@ -78,7 +77,8 @@ public class TiltUtils {
         public int hashCode() {
             final int prime = 31;
             int result = 1;
-            result = prime * result + coverageId;
+            result = prime * result
+                    + ((coverageId == null) ? 0 : coverageId.hashCode());
             long temp;
             temp = Double.doubleToLongBits(lat);
             result = prime * result + (int) (temp ^ (temp >>> 32));
@@ -96,7 +96,10 @@ public class TiltUtils {
             if (getClass() != obj.getClass())
                 return false;
             CacheKey other = (CacheKey) obj;
-            if (coverageId != other.coverageId)
+            if (coverageId == null) {
+                if (other.coverageId != null)
+                    return false;
+            } else if (!coverageId.equals(other.coverageId))
                 return false;
             if (Double.doubleToLongBits(lat) != Double
                     .doubleToLongBits(other.lat))
@@ -148,9 +151,9 @@ public class TiltUtils {
 
     private FloatDataRecord getHeightGrid(RadarStation radar,
             GridCoverage coverage, double tilt) {
-        CacheKey cacheKey = new CacheKey(coverage.getId(), radar.getLon(),
-                radar.getLat());
         if (radar != null) {
+            CacheKey cacheKey = new CacheKey(coverage.getId(), radar.getLon(),
+                    radar.getLat());
             GridGeometry2D geometry = MapUtil.getGridGeometry(coverage);
             GridEnvelope2D gridRange = geometry.getGridRange2D();
             double[] radius = null;
@@ -160,44 +163,33 @@ public class TiltUtils {
             }
             if (radius == null) {
                 try {
+                    MathTransform gridToCrs = geometry.getGridToCRS();
+                    MathTransform fromLatLon = MapUtil
+                            .getTransformFromLatLon(coverage.getCrs());
 
-                    if (!(coverage instanceof LatLonGridCoverage)) {
-                        MathTransform gridToCrs = geometry.getGridToCRS();
-                        MathTransform fromLatLon = MapUtil
-                                .getTransformFromLatLon(coverage.getCrs());
-
-                        double[] radarLonLat = new double[] { radar.getLon(),
-                                radar.getLat() };
-                        double[] radarCrsCoord = new double[2];
-                        fromLatLon.transform(radarLonLat, 0, radarCrsCoord, 0,
-                                1);
-                        int numPoints = gridRange.height * gridRange.width;
-                        double[] gridCoordGrid = new double[numPoints * 2];
-                        int offset = 0;
-                        for (int j = 0; j < gridRange.height; j++) {
-                            for (int i = 0; i < gridRange.width; i++) {
-                                gridCoordGrid[offset++] = i;
-                                gridCoordGrid[offset++] = j;
-                            }
+                    double[] radarLonLat = new double[] { radar.getLon(),
+                            radar.getLat() };
+                    double[] radarCrsCoord = new double[2];
+                    fromLatLon.transform(radarLonLat, 0, radarCrsCoord, 0, 1);
+                    int numPoints = gridRange.height * gridRange.width;
+                    double[] gridCoordGrid = new double[numPoints * 2];
+                    int offset = 0;
+                    for (int j = 0; j < gridRange.height; j++) {
+                        for (int i = 0; i < gridRange.width; i++) {
+                            gridCoordGrid[offset++] = i;
+                            gridCoordGrid[offset++] = j;
                         }
-                        gridToCrs.transform(gridCoordGrid, 0, gridCoordGrid, 0,
-                                numPoints);
-                        radius = new double[numPoints];
-                        offset = 0;
-                        for (int i = 0; i < numPoints; i++) {
-                            double xDist = radarCrsCoord[0]
-                                    - gridCoordGrid[offset++];
-                            double yDist = radarCrsCoord[1]
-                                    - gridCoordGrid[offset++];
-                            radius[i] = Math
-                                    .sqrt(xDist * xDist + yDist * yDist);
-                        }
-                    } else {
-                        // use geodetic calculator
-                        MathTransform gridToLatLon = geometry.getGridToCRS();
-
-                        radius = getRadius(radar, gridRange, gridToLatLon);
-
+                    }
+                    gridToCrs.transform(gridCoordGrid, 0, gridCoordGrid, 0,
+                            numPoints);
+                    radius = new double[numPoints];
+                    offset = 0;
+                    for (int i = 0; i < numPoints; i++) {
+                        double xDist = radarCrsCoord[0]
+                                - gridCoordGrid[offset++];
+                        double yDist = radarCrsCoord[1]
+                                - gridCoordGrid[offset++];
+                        radius[i] = Math.sqrt(xDist * xDist + yDist * yDist);
                     }
                     gridRadiusCache.put(cacheKey, new SoftReference(
                             radius));
@@ -206,11 +198,13 @@ public class TiltUtils {
                             .handle(Priority.PROBLEM,
                                     "Error occurred generating height grid for radar tilt",
                                     e);
+                    return null;
                 }
             }
             return getHeightGrid(radar, gridRange, radius, tilt);
+        } else {
+            return null;
         }
-        return null;
     }
 
     public FloatDataRecord getHeightGrid(GridEnvelope2D gridRange,
diff --git a/cave/com.raytheon.viz.hydro/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.hydro/META-INF/MANIFEST.MF
index 05a92fd114..e229dbee43 100644
--- a/cave/com.raytheon.viz.hydro/META-INF/MANIFEST.MF
+++ b/cave/com.raytheon.viz.hydro/META-INF/MANIFEST.MF
@@ -19,7 +19,7 @@ Require-Bundle: org.eclipse.ui,
  javax.measure;bundle-version="1.0.0",
  com.raytheon.uf.viz.app.launcher;bundle-version="1.11.4",
  com.raytheon.uf.common.hydro;bundle-version="1.11.13",
- com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.17",
+ com.raytheon.uf.common.dataplugin.grid,
  com.raytheon.edex.meteolib;bundle-version="1.11.17",
  com.raytheon.viz.grid;bundle-version="1.11.17",
  com.raytheon.uf.common.dissemination;bundle-version="1.0.0",
diff --git a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/AutoSPE.xml b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/AutoSPE.xml
index 10c460f87f..c48a697660 100644
--- a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/AutoSPE.xml
+++ b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/AutoSPE.xml
@@ -38,14 +38,14 @@
                     
                     
                         
-                            
+                            
                                 
                             
-                            
+                            
                                 
                             
                             
-                                
+                                
                             
                         
                     
diff --git a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGLmosaic.xml b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGLmosaic.xml
index 1595a5dcb8..d57a5a8bd5 100644
--- a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGLmosaic.xml
+++ b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGLmosaic.xml
@@ -40,13 +40,13 @@
                     
                         
-                            
+                            
                                 
                             
                             
-                                
+                                
                             
-							
+							
 								
 							
@@ -64,13 +64,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -89,13 +89,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -114,13 +114,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -139,13 +139,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -164,13 +164,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -189,13 +189,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -214,13 +214,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -239,13 +239,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -264,13 +264,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -289,13 +289,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -314,13 +314,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -339,13 +339,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
@@ -364,13 +364,13 @@
  			                
 		                    
 		                        
-		                            
+		                            
 		                                
 		                            
 		                            
-		                                
+		                                
 		                            
-		                            
+		                            
 		                                
 		                            
 		                        
diff --git a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGmosaic.xml b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGmosaic.xml
index bd1c845231..2d80b4de72 100644
--- a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGmosaic.xml
+++ b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/FFGmosaic.xml
@@ -38,13 +38,13 @@
                     
                     
                         
-                            
+                            
                                 
                             
                             
-                                
+                                
                             
-                            
+                            
                                 
                             
                         
diff --git a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/HV-FFG.xml b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/HV-FFG.xml
index 8b2f452ade..ada49536ab 100644
--- a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/HV-FFG.xml
+++ b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/HV-FFG.xml
@@ -35,19 +35,19 @@
                     
                     
                         
-                            
+                            
                                 
                             
                             
                                 
                             
-                            
-                                
+                            
+                                
                             
                             
-                                
+                                
                             
-                            
+                            
                                 
                             
                         
diff --git a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/ManSPE.xml b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/ManSPE.xml
index 5662aca60d..47a50fb156 100644
--- a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/ManSPE.xml
+++ b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/ManSPE.xml
@@ -38,16 +38,16 @@
                     
                     
                         
-                            
+                            
                                 
                             
                             
                                 
                             
                             
-                                
+                                
                             
-                            
+                            
                                 
                             
                         
diff --git a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/zeroToThreeHourRadarQPF.xml b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/zeroToThreeHourRadarQPF.xml
index b1019fc7db..0c51ac0cf1 100644
--- a/cave/com.raytheon.viz.hydro/localization/bundles/hydro/zeroToThreeHourRadarQPF.xml
+++ b/cave/com.raytheon.viz.hydro/localization/bundles/hydro/zeroToThreeHourRadarQPF.xml
@@ -37,13 +37,13 @@
                     
                     
                         
-                            
+                            
                                 
                             
                             
-                                
+                                
                             
-                            
+                            
                                 
                             
                         
diff --git a/cave/com.raytheon.viz.hydro/localization/menus/hydro/baseHPCStation.xml b/cave/com.raytheon.viz.hydro/localization/menus/hydro/baseHPCStation.xml
index 9665c2e9b6..abdc1430db 100644
--- a/cave/com.raytheon.viz.hydro/localization/menus/hydro/baseHPCStation.xml
+++ b/cave/com.raytheon.viz.hydro/localization/menus/hydro/baseHPCStation.xml
@@ -24,7 +24,7 @@
 			 menuText="MaxT/MinT" id="HPCmaxTminT" >
 	        	
         		
-	    		
+	    		
 	    
 	    
diff --git a/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDataManager.java b/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDataManager.java
index 1b0642d0a3..96db3484ed 100644
--- a/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDataManager.java
+++ b/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDataManager.java
@@ -21,7 +21,6 @@ package com.raytheon.viz.hydro.flashfloodguidance;
 
 import java.io.FileNotFoundException;
 import java.text.SimpleDateFormat;
-import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
@@ -29,17 +28,19 @@ import java.util.Map;
 import java.util.TimeZone;
 
 import com.raytheon.uf.common.dataplugin.PluginException;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
+import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
+import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType;
 import com.raytheon.uf.common.datastorage.StorageException;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
+import com.raytheon.uf.viz.core.catalog.DbQuery;
 import com.raytheon.uf.viz.core.catalog.DirectDbQuery;
 import com.raytheon.uf.viz.core.catalog.DirectDbQuery.QueryLanguage;
 import com.raytheon.uf.viz.core.exception.VizException;
-import com.raytheon.viz.hydro.Activator;
 import com.raytheon.viz.hydrocommon.HydroConstants;
-import com.raytheon.viz.hydrocommon.constants.StatusConstants;
 
 /**
  * Class for managing database query calls. FlashFloodGuidanceDataManager.java
@@ -62,11 +63,8 @@ public class FlashFloodGuidanceDataManager {
     /** Instance of this class */
     private static FlashFloodGuidanceDataManager instance = null;
 
-    /** Query to find available gridded data */
-    private static final String AVAILABLE_DATA_QUERY = "select grib_models.modelname, grib_models.parameterabbreviation, grib.reftime, grib.datauri, grib.id from grib, grib_models where grib_models.modelname like 'FFG%' and grib_models.id = grib.modelinfo_id and grib.gridversion = 0 order by grib_models.modelname, grib_models.parameterabbreviation, grib.reftime asc";
-
     private static final String LINESEGS_QUERY = "select hrap_row, hrap_beg_col, "
-        + "hrap_end_col, area from linesegs";
+            + "hrap_end_col, area from linesegs";
 
     /** RFC Site name to RFC lookup map */
     public static Map RFCMAP = new HashMap();
@@ -130,15 +128,28 @@ public class FlashFloodGuidanceDataManager {
      * 
      * @return ArrayList of data
      */
-    public ArrayList getGriddedDataList() {
-        ArrayList rs = null;
+    public List getGriddedDataList() {
+        List rs = null;
 
+        /** Query to find available gridded data */
+        DbQuery query = new DbQuery(GridRecord.class, "metadata");
+        query.addColumn(GridConstants.DATASET_ID);
+        query.addColumn(GridConstants.PARAMETER_ABBREVIATION);
+        query.addColumn("dataTime.refTime");
+        query.addColumn("dataURI");
+        query.addColumn("id");
+        query.addConstraint(GridConstants.DATASET_ID, new RequestConstraint(
+                "FFG%", ConstraintType.LIKE));
+        query.addConstraint(GridConstants.SECONDARY_ID, "Version0");
+        query.addOrderBy(GridConstants.DATASET_ID);
+        query.addOrderBy(GridConstants.PARAMETER_ABBREVIATION);
+        query.addOrderBy("dataTime.refTime");
         try {
-            rs = (ArrayList) DirectDbQuery.executeQuery(
-                    AVAILABLE_DATA_QUERY, "metadata", QueryLanguage.SQL);
+            rs = query.performQuery();
         } catch (VizException e) {
+            e.printStackTrace();
             statusHandler.handle(Priority.PROBLEM, "Data Query:"
-                            + " Error querying Metadata for FFG data.");
+                    + " Error querying Metadata for FFG data.");
         }
 
         return rs;
@@ -163,20 +174,20 @@ public class FlashFloodGuidanceDataManager {
         return null;
     }
 
-    public GribRecord getGribRecord(String uri) throws PluginException,
+    public GridRecord getGridRecord(String uri) throws PluginException,
             FileNotFoundException, StorageException {
         StringBuilder query = new StringBuilder();
         query.append("from "
-                + com.raytheon.uf.common.dataplugin.grib.GribRecord.class
+                + com.raytheon.uf.common.dataplugin.grid.GridRecord.class
                         .getName());
-        GribRecord gr = null;
+        GridRecord gr = null;
         try {
-            List results = DirectDbQuery.executeQuery(query
-                    .toString(), "metadata", QueryLanguage.HQL);
-            gr = (GribRecord) results.get(0)[0];
+            List results = DirectDbQuery.executeQuery(
+                    query.toString(), "metadata", QueryLanguage.HQL);
+            gr = (GridRecord) results.get(0)[0];
         } catch (VizException e) {
             statusHandler.handle(Priority.PROBLEM, "FFG Query"
-                            + " Error querying for areal FFG");
+                    + " Error querying for areal FFG");
         }
 
         return gr;
@@ -190,19 +201,19 @@ public class FlashFloodGuidanceDataManager {
                     HydroConstants.IHFS, QueryLanguage.SQL);
         } catch (VizException e) {
             statusHandler.handle(Priority.PROBLEM, "FFG Query"
-                            + " Error querying GeoArea table");
+                    + " Error querying GeoArea table");
         }
 
         return rs;
     }
-    
+
     public List getContingencyValue(String areaId, int duration, Date refTime) {
         List rs = null;
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
-        
+
         String date = sdf.format(refTime);
-        duration = duration / (1000*60*60);
+        duration = duration / (1000 * 60 * 60);
         int dur = 1001;
         if (duration == 1) {
             dur = 1001;
@@ -226,20 +237,19 @@ public class FlashFloodGuidanceDataManager {
                     HydroConstants.IHFS, QueryLanguage.SQL);
         } catch (VizException e) {
             statusHandler.handle(Priority.PROBLEM, "FFG Query"
-                            + " Error querying ContingencyValue table");
+                    + " Error querying ContingencyValue table");
             e.printStackTrace();
         }
 
-        return rs;        
+        return rs;
     }
-    
+
     public List getContingencyValue(String boundaryType) {
         List rs = null;
         
         String where = " where pe='PP' and ts='CF' and lid in (select area_id from " +
         "GeoArea where boundary_type = '" + boundaryType.toUpperCase() +
         "') order by validtime desc, dur asc";
-        
         String sql = "select distinct(validtime), dur from contingencyvalue";
         
         try {
@@ -247,7 +257,7 @@ public class FlashFloodGuidanceDataManager {
                     HydroConstants.IHFS, QueryLanguage.SQL);
         } catch (VizException e) {
             statusHandler.handle(Priority.PROBLEM, "FFG Query"
-                            + " Error querying ContingencyValue table");
+                    + " Error querying ContingencyValue table");
             e.printStackTrace();
         }
 
diff --git a/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDlg.java b/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDlg.java
index b91ddd7bbb..5f6efb7dad 100644
--- a/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDlg.java
+++ b/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/flashfloodguidance/FlashFloodGuidanceDlg.java
@@ -787,7 +787,7 @@ public class FlashFloodGuidanceDlg extends CaveSWTDialog {
 
         /* Check the FFG mode. */
         if (ffgAreaCbo.getItem(ffgAreaCbo.getSelectionIndex()).equals("RFC")) {
-            ArrayList rs = dman.getGriddedDataList();
+            java.util.List rs = dman.getGriddedDataList();
 
             if ((rs != null) && (rs.size() > 0)) {
                 for (Object[] oa : rs) {
@@ -904,16 +904,21 @@ public class FlashFloodGuidanceDlg extends CaveSWTDialog {
                         String fileWfo = xmrg.getName().substring(0, 3);
                         int index = xmrg.getName().indexOf("20");
                         /* Parse the filename for duration and time stamp here. */
-                        String year = xmrg.getName().substring(index, index + 4);
-                        String month = xmrg.getName().substring(index + 4, index + 6);
-                        String day = xmrg.getName().substring(index + 6, index + 8);
-                        String hour = xmrg.getName().substring(index + 8, index + 10);
-                        String durString = xmrg.getName().substring(index + 10, index + 12);
-//                        String year = xmrg.getName().substring(3, 7);
-//                        String month = xmrg.getName().substring(7, 9);
-//                        String day = xmrg.getName().substring(9, 11);
-//                        String hour = xmrg.getName().substring(11, 13);
-//                        String durString = xmrg.getName().substring(13, 15);
+                        String year = xmrg.getName()
+                                .substring(index, index + 4);
+                        String month = xmrg.getName().substring(index + 4,
+                                index + 6);
+                        String day = xmrg.getName().substring(index + 6,
+                                index + 8);
+                        String hour = xmrg.getName().substring(index + 8,
+                                index + 10);
+                        String durString = xmrg.getName().substring(index + 10,
+                                index + 12);
+                        // String year = xmrg.getName().substring(3, 7);
+                        // String month = xmrg.getName().substring(7, 9);
+                        // String day = xmrg.getName().substring(9, 11);
+                        // String hour = xmrg.getName().substring(11, 13);
+                        // String durString = xmrg.getName().substring(13, 15);
 
                         Calendar cal = Calendar.getInstance(TimeZone
                                 .getTimeZone("GMT"));
@@ -1126,7 +1131,8 @@ public class FlashFloodGuidanceDlg extends CaveSWTDialog {
         String day = parts[2];
         String date = parts[3];
         String hour = parts[4];
-        duration = Integer.parseInt(durationStr) * FFGConstants.SECONDS_PER_HOUR;
+        duration = Integer.parseInt(durationStr)
+                * FFGConstants.SECONDS_PER_HOUR;
 
         String paramAbr = "FFG" + durationStr + "24hr";
 
diff --git a/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/timeseries/TimeSeriesDisplayCanvas.java b/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/timeseries/TimeSeriesDisplayCanvas.java
index f84e2505e8..b63d3dc5df 100644
--- a/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/timeseries/TimeSeriesDisplayCanvas.java
+++ b/cave/com.raytheon.viz.hydro/src/com/raytheon/viz/hydro/timeseries/TimeSeriesDisplayCanvas.java
@@ -131,8 +131,6 @@ import com.raytheon.viz.hydrocommon.util.DbUtils;
  * 06 Nov   2012 15400   lbousaidi    Changed logic in buildPointString routine, added discharge2stage
  *                                    to display stage value, also added checking for rating curve for both 
  *                                    stage and discharge. 
- * 13 Nov   2012 15416   lbousaidi    added a check when the colorname is null and a call to 
- *                                    getGroupModeColor                                 
  * @author lvenable
  * @version 1.0
  * 
@@ -908,15 +906,14 @@ public class TimeSeriesDisplayCanvas extends TimeSeriesGraphCanvas implements
                         }
 
                         /* Top left point of bar */
-                        int x = pointArray[i].getPixelX() + GRAPHBORDER_LEFT;// - 20;
+                        int x = pointArray[i].getPixelX() + GRAPHBORDER;// - 20;
 
                         if ((x < GRAPHBORDER_LEFT) || (x > GRAPHBORDER_LEFT + graphAreaWidth)) {
                             continue;
                         }
 
-                        int x2 = x;
-                        x = x2pixel(graphData, pointArray[i].getX()
-                                .getTime() - 3600000)
+                        int x2 = x2pixel(graphData, pointArray[i].getX()
+                                .getTime() + 3600000)
                                 + GRAPHBORDER_LEFT;// - 20;
                         int y = pointArray[i].getPixelY() + GRAPHBORDER;
                         ia[0] = x;
@@ -2498,13 +2495,8 @@ public class TimeSeriesDisplayCanvas extends TimeSeriesGraphCanvas implements
                 gc.setBackground(new Color(parentComp.getDisplay(), HydroUtils
                         .getColor(traceIndex)));
             } else if (groupMode) {
-                  if (td.getColorName() != null && HydroUtils.getColor(td.getColorName()) != null) {
-                       gc.setBackground(new Color(parentComp.getDisplay(), HydroUtils
-                            .getColor(td.getColorName())));
-                  } else {
-                       gc.setBackground(new Color(parentComp.getDisplay(),
-                            HydroUtils.getGroupModeColor(traceIndex)));
-            	}
+                gc.setBackground(new Color(parentComp.getDisplay(), HydroUtils
+                        .getColor(td.getColorName())));
             }
         }
     }
diff --git a/cave/com.raytheon.viz.hydrobase/src/com/raytheon/viz/hydrobase/dialogs/AddModifyLocationDlg.java b/cave/com.raytheon.viz.hydrobase/src/com/raytheon/viz/hydrobase/dialogs/AddModifyLocationDlg.java
index 222d3cd4b1..300697e8f4 100644
--- a/cave/com.raytheon.viz.hydrobase/src/com/raytheon/viz/hydrobase/dialogs/AddModifyLocationDlg.java
+++ b/cave/com.raytheon.viz.hydrobase/src/com/raytheon/viz/hydrobase/dialogs/AddModifyLocationDlg.java
@@ -77,7 +77,6 @@ import com.raytheon.viz.ui.dialogs.CaveSWTDialog;
  *                                     case in Location box.
  * 10 May 2011  9309       djingtao    the elevation fields should be defaults as 0.0 when user
  *                                     wipe out the field (e.g. blank)
- * 26 Nov 2012 15440       lbousaidi   display lat/lon in the GUI in decimal degrees                                   
  * 
  * 
  * 
@@ -818,7 +817,7 @@ public class AddModifyLocationDlg extends CaveSWTDialog implements
         Group stationGroup = new Group(parentComp, SWT.NONE);
         stationGroup.setLayout(new GridLayout(3, false));
         stationGroup.setLayoutData(gd);
-        stationGroup.setText(" Station Characteristics (View-Only) ");
+        stationGroup.setText(" Station Characteritics (View-Only) ");
 
         // -----------------------------------------------
         // Create Station Type controls
@@ -1323,12 +1322,13 @@ public class AddModifyLocationDlg extends CaveSWTDialog implements
         basinTF.setText(locData.getRiverBasin());
 
         // Only Display Lat/Lon if not missing
-      
-       latTF.setText((locData.getLatitude() != HydroConstants.MISSING_VALUE) ?
-                String.valueOf(locData.getLatitude()): "");
-       lonTF.setText((locData.getLongitude() != HydroConstants.MISSING_VALUE) ?
-              String.valueOf(locData.getLongitude()): "");
-       
+        latTF.setText((locData.getLatitude() != HydroConstants.MISSING_VALUE) ? GeoUtil
+                .getInstance().cvt_latlon_from_double(locData.getLatitude())
+                : "");
+        lonTF.setText((locData.getLongitude() != HydroConstants.MISSING_VALUE) ? GeoUtil
+                .getInstance().cvt_latlon_from_double(locData.getLongitude())
+                : "");
+
         // Only display elevation if it isn't missing, i.e. null in DB
         elevationTF
                 .setText((locData.getElevation() != HydroConstants.MISSING_VALUE) ? String
diff --git a/cave/com.raytheon.viz.hydrocommon/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.hydrocommon/META-INF/MANIFEST.MF
index 87047e484d..632efee340 100644
--- a/cave/com.raytheon.viz.hydrocommon/META-INF/MANIFEST.MF
+++ b/cave/com.raytheon.viz.hydrocommon/META-INF/MANIFEST.MF
@@ -20,8 +20,9 @@ Require-Bundle: org.eclipse.ui,
  com.raytheon.uf.common.colormap;bundle-version="1.11.13",
  com.raytheon.uf.common.mpe;bundle-version="1.11.13",
  com.raytheon.uf.viz.core.maps;bundle-version="1.0.0",
- com.raytheon.uf.common.dataplugin.grib,
- com.raytheon.uf.common.dataplugin.shef;bundle-version="1.12.1174"
+ com.raytheon.uf.common.dataplugin.grid,
+ com.raytheon.uf.common.dataplugin.shef;bundle-version="1.12.1174",
+ com.raytheon.uf.common.gridcoverage;bundle-version="1.0.0"
 Bundle-ActivationPolicy: lazy
 Export-Package: com.raytheon.viz.hydrocommon,
  com.raytheon.viz.hydrocommon.actions,
@@ -45,6 +46,5 @@ Export-Package: com.raytheon.viz.hydrocommon,
  com.raytheon.viz.hydrocommon.util,
  com.raytheon.viz.hydrocommon.whfslib,
  com.raytheon.viz.hydrocommon.whfslib.colorthreshold
-Import-Package: com.raytheon.uf.common.dataplugin.grib,
- com.raytheon.uf.common.ohd,
+Import-Package: com.raytheon.uf.common.ohd,
  com.raytheon.viz.grid.rsc
diff --git a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/HydroDisplayManager.java b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/HydroDisplayManager.java
index 73f86d2d0b..a08f5278f8 100644
--- a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/HydroDisplayManager.java
+++ b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/HydroDisplayManager.java
@@ -35,7 +35,8 @@ import org.eclipse.swt.widgets.Shell;
 import org.eclipse.ui.IEditorPart;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.dataplugin.shef.tables.Colorvalue;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
@@ -298,13 +299,12 @@ public class HydroDisplayManager {
 
             // Get the Grib data
             Map reqMap = new HashMap();
-            reqMap.put("pluginName", new RequestConstraint("grib"));
-            reqMap.put("modelInfo.parameterAbbreviation",
+            reqMap.put(GridConstants.PLUGIN_NAME, new RequestConstraint(GridConstants.GRID));
+            reqMap.put(GridConstants.PARAMETER_ABBREVIATION,
                     new RequestConstraint(paramAbr));
             reqMap.put("dataTime.refTime",
                     new RequestConstraint(sdf.format(date)));
-            reqMap.put("modelInfo.modelName", new RequestConstraint("FFG-"
-                    + rfc));
+            reqMap.put(GridConstants.DATASET_ID, new RequestConstraint("FFG-" + rfc));
 
             try {
                 LayerProperty lp = new LayerProperty();
@@ -312,10 +312,10 @@ public class HydroDisplayManager {
                 lp.setEntryQueryParameters(reqMap, false);
 
                 List dataList = DataCubeContainer.getData(lp, 30);
-                GribRecord gr = null;
+                GridRecord gr = null;
                 int i = 0;
                 for (Object o : dataList) {
-                    gr = (GribRecord) o;
+                    gr = (GridRecord) o;
                     IDataRecord[] recArr = DataCubeContainer
                             .getDataRecord((PluginDataObject) o);
                     gr.setMessageData(((FloatDataRecord) recArr[0])
@@ -465,13 +465,12 @@ public class HydroDisplayManager {
 
             // Get the Grib data
             Map reqMap = new HashMap();
-            reqMap.put("pluginName", new RequestConstraint("grib"));
-            reqMap.put("modelInfo.parameterAbbreviation",
+            reqMap.put(GridConstants.PLUGIN_NAME, new RequestConstraint(GridConstants.GRID));
+            reqMap.put(GridConstants.PARAMETER_ABBREVIATION,
                     new RequestConstraint(paramAbr));
             reqMap.put("dataTime.refTime",
                     new RequestConstraint(sdf.format(date)));
-            reqMap.put("modelInfo.modelName", new RequestConstraint("FFG-"
-                    + rfc));
+            reqMap.put(GridConstants.DATASET_ID, new RequestConstraint("FFG-" + rfc));
 
             try {
                 LayerProperty lp = new LayerProperty();
@@ -479,10 +478,10 @@ public class HydroDisplayManager {
                 lp.setEntryQueryParameters(reqMap, false);
 
                 List dataList = DataCubeContainer.getData(lp, 30);
-                GribRecord gr = null;
+                GridRecord gr = null;
                 int i = 0;
                 for (Object o : dataList) {
-                    gr = (GribRecord) o;
+                    gr = (GridRecord) o;
                     IDataRecord[] recArr = DataCubeContainer
                             .getDataRecord((PluginDataObject) o);
                     gr.setMessageData(((FloatDataRecord) recArr[0])
diff --git a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResource.java b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResource.java
index 6d12ba1311..d85b19f8b1 100644
--- a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResource.java
+++ b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResource.java
@@ -43,10 +43,10 @@ import org.opengis.referencing.crs.CoordinateReferenceSystem;
 import org.opengis.referencing.datum.PixelInCell;
 import org.opengis.referencing.operation.TransformException;
 
-import com.raytheon.uf.common.dataplugin.shef.tables.Colorvalue;
 import com.raytheon.uf.common.colormap.Color;
 import com.raytheon.uf.common.colormap.ColorMap;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
+import com.raytheon.uf.common.dataplugin.shef.tables.Colorvalue;
 import com.raytheon.uf.common.geospatial.MapUtil;
 import com.raytheon.uf.common.geospatial.ReferencedCoordinate;
 import com.raytheon.uf.common.hydro.spatial.HRAP;
@@ -128,7 +128,7 @@ public class FFGGridResource extends
 
     private boolean isInterpolated;
 
-    private GribRecord gr;
+    private GridRecord gr;
 
     private Rectangle rfcExtent;
 
@@ -147,7 +147,7 @@ public class FFGGridResource extends
     }
 
     private void loadData() {
-        gr = resourceData.getGribRecord();
+        gr = resourceData.getGridRecord();
 
         if (gr == null) {
             return;
@@ -201,7 +201,7 @@ public class FFGGridResource extends
         parameters.setDataMin(0);
         cvt = parameters.getDataToImageConverter();
 
-        gridGeometry = gr.getModelInfo().getLocation().getGridGeometry();
+        gridGeometry = gr.getLocation().getGridGeometry();
 
         try {
             data = new float[((float[]) gr.getMessageData()).length];
@@ -222,10 +222,10 @@ public class FFGGridResource extends
             HRAP hrap;
             Coordinate org = MapUtil.gridCoordinateToLatLon(
                     new Coordinate(0, 0), PixelOrientation.LOWER_LEFT,
-                    gr.getSpatialObject());
+                    gr.getLocation());
 
-            int nx = gr.getSpatialObject().getNx();
-            int ny = gr.getSpatialObject().getNy();
+            int nx = gr.getLocation().getNx();
+            int ny = gr.getLocation().getNy();
 
             hrap = HRAP.getInstance();
 
@@ -348,8 +348,8 @@ public class FFGGridResource extends
         Map values = new HashMap();
 
         try {
-            int nx = gr.getSpatialObject().getNx();
-            int ny = gr.getSpatialObject().getNy();
+            int nx = gr.getLocation().getNx();
+            int ny = gr.getLocation().getNy();
 
             Coordinate gridCell = coord.asGridCell(HRAP.getInstance()
                     .getGridGeometry(), PixelInCell.CELL_CORNER);
diff --git a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResourceData.java b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResourceData.java
index a3c853c4e5..4e1d5dbbb6 100644
--- a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResourceData.java
+++ b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/FFGGridResourceData.java
@@ -23,7 +23,7 @@ import java.util.Date;
 
 import javax.xml.bind.annotation.XmlType;
 
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.viz.core.drawables.IDescriptor;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.core.rsc.AbstractResourceData;
@@ -35,38 +35,38 @@ import com.raytheon.viz.hydrocommon.constants.FFGConstants.ResolutionLevel;
  * FFG Resource Data.
  * 
  * 
- *
+ * 
  * SOFTWARE HISTORY
- *
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Oct 14, 2009 2256       mpduff     Initial creation.  Moved here
  *                                    for additional functionality.
- *
+ * 
  * 
- * + * * @author mpduff - * @version 1.0 + * @version 1.0 */ -@XmlType(name="ffgGridResourceData") +@XmlType(name = "ffgGridResourceData") public class FFGGridResourceData extends AbstractResourceData { private int duration; - - private GribRecord gribRecord; - + + private GridRecord gridRecord; + private ResolutionLevel resolution; - + private Date dataDate; - + public FFGGridResourceData() { - + } - - public FFGGridResourceData(int duration, GribRecord gr, + + public FFGGridResourceData(int duration, GridRecord gr, ResolutionLevel resolution, Date dataDate) { this.setDuration(duration); - this.setGribRecord(gr); + this.setGridRecord(gr); this.setResolution(resolution); this.setDataDate(dataDate); } @@ -88,7 +88,7 @@ public class FFGGridResourceData extends AbstractResourceData { @Override public AbstractVizResource construct(LoadProperties loadProperties, IDescriptor descriptor) throws VizException { - + return new FFGGridResource(this, loadProperties); } @@ -98,7 +98,7 @@ public class FFGGridResourceData extends AbstractResourceData { @Override public void update(Object updateData) { // TODO Auto-generated method stub - + } /** @@ -118,15 +118,15 @@ public class FFGGridResourceData extends AbstractResourceData { /** * @param gribRecord the gribRecord to set */ - public void setGribRecord(GribRecord gribRecord) { - this.gribRecord = gribRecord; + public void setGridRecord(GridRecord gridRecord) { + this.gridRecord = gridRecord; } /** * @return the gribRecord */ - public GribRecord getGribRecord() { - return gribRecord; + public GridRecord getGridRecord() { + return gridRecord; } /** @@ -142,7 +142,7 @@ public class FFGGridResourceData extends AbstractResourceData { public ResolutionLevel getResolution() { return resolution; } - + /** * @param dataDate the dataDate to set */ diff --git a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResource.java b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResource.java index 976ab83f02..67479e3502 100644 --- a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResource.java +++ b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResource.java @@ -41,10 +41,10 @@ import org.opengis.metadata.spatial.PixelOrientation; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.datum.PixelInCell; -import com.raytheon.uf.common.dataplugin.shef.tables.Colorvalue; import com.raytheon.uf.common.colormap.Color; import com.raytheon.uf.common.colormap.ColorMap; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataplugin.shef.tables.Colorvalue; import com.raytheon.uf.common.geospatial.MapUtil; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; import com.raytheon.uf.common.hydro.spatial.HRAP; @@ -116,7 +116,7 @@ public class RFCGriddedBasinFFGResource extends private Rectangle rfcExtent; - private GribRecord gr; + private GridRecord gr; private float minArea = 9.0f; @@ -148,7 +148,7 @@ public class RFCGriddedBasinFFGResource extends private void loadData() { initColorMapParams(); - gridGeometry = gr.getModelInfo().getLocation().getGridGeometry(); + gridGeometry = gr.getLocation().getGridGeometry(); try { data = new float[((float[]) gr.getMessageData()).length]; @@ -161,10 +161,10 @@ public class RFCGriddedBasinFFGResource extends HRAP hrap; Coordinate org = MapUtil.gridCoordinateToLatLon( new Coordinate(0, 0), PixelOrientation.CENTER, - gr.getSpatialObject()); + gr.getLocation()); - int nx = gr.getSpatialObject().getNx(); - int ny = gr.getSpatialObject().getNy(); + int nx = gr.getLocation().getNx(); + int ny = gr.getLocation().getNy(); hrap = HRAP.getInstance(); diff --git a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResourceData.java b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResourceData.java index 56d233dc27..aff3caad1f 100644 --- a/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResourceData.java +++ b/cave/com.raytheon.viz.hydrocommon/src/com/raytheon/viz/hydrocommon/resource/RFCGriddedBasinFFGResourceData.java @@ -22,8 +22,8 @@ package com.raytheon.viz.hydrocommon.resource; import java.util.Date; import java.util.List; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.shef.tables.Colorvalue; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; import com.raytheon.uf.viz.core.drawables.IDescriptor; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.AbstractResourceData; @@ -51,12 +51,14 @@ import com.raytheon.viz.hydrocommon.constants.FFGConstants.ResolutionLevel; public class RFCGriddedBasinFFGResourceData extends AbstractResourceData { private ResolutionLevel resolution; + private int duration; + private Date dataDate; - - private GribRecord gr; - - public RFCGriddedBasinFFGResourceData(int duration, GribRecord gr, + + private GridRecord gr; + + public RFCGriddedBasinFFGResourceData(int duration, GridRecord gr, ResolutionLevel resolution, Date dataDate) { this.duration = duration; this.gr = gr; @@ -126,14 +128,14 @@ public class RFCGriddedBasinFFGResourceData extends AbstractResourceData { /** * @return the gr */ - public GribRecord getGr() { + public GridRecord getGr() { return gr; } /** * @param gr the gr to set */ - public void setGr(GribRecord gr) { + public void setGr(GridRecord gr) { this.gr = gr; } diff --git a/cave/com.raytheon.viz.lightning/src/com/raytheon/viz/lightning/LightningProductBrowserDataDefinition.java b/cave/com.raytheon.viz.lightning/src/com/raytheon/viz/lightning/LightningProductBrowserDataDefinition.java index 289cc8e4c6..cace425629 100644 --- a/cave/com.raytheon.viz.lightning/src/com/raytheon/viz/lightning/LightningProductBrowserDataDefinition.java +++ b/cave/com.raytheon.viz.lightning/src/com/raytheon/viz/lightning/LightningProductBrowserDataDefinition.java @@ -63,7 +63,7 @@ public class LightningProductBrowserDataDefinition extends public LightningProductBrowserDataDefinition() { productName = "binlightning"; displayName = "Lightning"; - order = new String[] { "pluginName", "startTime", "type" }; + order = new String[] { "startTime", "type" }; order = getOrder(); loadProperties = new LoadProperties(); loadProperties.setResourceType(getResourceType()); @@ -78,17 +78,26 @@ public class LightningProductBrowserDataDefinition extends */ @Override public List populateData(String[] selection) { - if (selection.length == 1) { + List labels = null; + if (order[selection.length - 1].equals("startTime")) { String[] strings = new String[offsets.length]; for (int i = 0; i < offsets.length; i++) { strings[i] = String.valueOf(offsets[i]); } - return formatData("pluginName", strings); - } else if (selection.length == 2) { - return formatData("startTime", types); - } else { - return formatData("type", types); + + labels = formatData("startTime", strings); + } else if (order[selection.length - 1].equals("type")) { + labels = formatData("type", types); } + + for (ProductBrowserLabel label : labels) { + if (selection.length == order.length) { + label.setProduct(true); + } else { + label.setProduct(false); + } + } + return labels; } /* @@ -101,24 +110,21 @@ public class LightningProductBrowserDataDefinition extends @Override public List formatData(String param, String[] parameters) { - if ("pluginName".equals(param)) { + if ("startTime".equals(param)) { List labels = new ArrayList(); for (int i = 0; i < offsets.length; i++) { labels.add(new ProductBrowserLabel((offsets[i] / 60) + " min", "" + offsets[i])); - labels.get(i).setProduct(false); } return labels; - } else if ("startTime".equals(param)) { + } else if ("type".equals(param)) { List labels = new ArrayList(); for (int i = 0; i < types.length; i++) { labels.add(new ProductBrowserLabel(types[i], types[i])); - labels.get(i).setProduct(true); } return labels; - } else { - return null; } + return null; } /* @@ -153,8 +159,17 @@ public class LightningProductBrowserDataDefinition extends @Override public void constructResource(String[] selection, ResourceType type) { String[] sel = new String[] { selection[0] }; - negativeOffset = Integer.parseInt(selection[1]); - lightningType = selection[selection.length - 1]; + int timeOffset = 0; + int posNegOffset = 0; + for (int i = 0; i < order.length; i++) { + if ("startTime".equals(order[i])) { + timeOffset = i; + } else if ("type".equals(order[i])) { + posNegOffset = i; + } + } + negativeOffset = Integer.parseInt(selection[timeOffset + 1]); + lightningType = selection[posNegOffset + 1]; super.constructResource(sel, type); } diff --git a/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/actions/SaveLevel2Data.java b/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/actions/SaveLevel2Data.java index 44896a2401..eab564312b 100644 --- a/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/actions/SaveLevel2Data.java +++ b/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/actions/SaveLevel2Data.java @@ -689,13 +689,6 @@ public class SaveLevel2Data { gm.get(Calendar.MONTH) + 1, gm.get(Calendar.DAY_OF_MONTH)); - //copy DailyQcUtils.pcp.value to datavals - for (int h = 0; h < hrap_grid.maxj; h++) { - for (int i = 0; i < hrap_grid.maxi; i++) { - datavals[i][h] = (DailyQcUtils.pcp.value[i][h] / 100.f); - } - } - /* output grid to file in ascii xmrg format */ WriteQPFGrids wqg = new WriteQPFGrids(); wqg.write_qpf_grids(dbuf); diff --git a/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/rsc/PlotGriddedTempResource.java b/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/rsc/PlotGriddedTempResource.java index 9a277fb097..1bd05b9319 100644 --- a/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/rsc/PlotGriddedTempResource.java +++ b/cave/com.raytheon.viz.mpe.ui/src/com/raytheon/viz/mpe/ui/rsc/PlotGriddedTempResource.java @@ -89,6 +89,7 @@ import com.vividsolutions.jts.geom.GeometryFactory; * Feb 29 2010 9909 lbousaidi changed the for loop for getting * the HRAP grid bin * Apr 17, 2012 9602 mgamazaychikm Changed the HRAP grid j index for loop + * Nov 02, 2012 1302 djohnson Remove target.setUseBuiltinColorbar(). * * * @author snaples @@ -107,9 +108,9 @@ public class PlotGriddedTempResource extends private GridGeometry2D gridGeometry; - private float brightness = 1.0f; + private final float brightness = 1.0f; - private float contrast = 1.0f; + private final float contrast = 1.0f; private boolean isInterpolated; @@ -127,7 +128,7 @@ public class PlotGriddedTempResource extends private static final GeometryFactory gf = new GeometryFactory(); - private List colorSet; + private final List colorSet; Hrap_Grid hrap_grid = DailyQcUtils.getHrap_grid(); @@ -441,6 +442,7 @@ public class PlotGriddedTempResource extends @Override protected void paintInternal(IGraphicsTarget target, PaintProperties paintProps) throws VizException { + if (buf == null || DailyQcUtils.grids_flag != 1 || displayMgr.isMaxmin() != true) { return; diff --git a/cave/com.raytheon.viz.mpe/src/com/raytheon/viz/mpe/util/AutoDailyQC.java b/cave/com.raytheon.viz.mpe/src/com/raytheon/viz/mpe/util/AutoDailyQC.java index 76a1656edf..60d2a9c946 100644 --- a/cave/com.raytheon.viz.mpe/src/com/raytheon/viz/mpe/util/AutoDailyQC.java +++ b/cave/com.raytheon.viz.mpe/src/com/raytheon/viz/mpe/util/AutoDailyQC.java @@ -186,7 +186,7 @@ public class AutoDailyQC { * 0 represents the time frame 12 - 18, 1 represents time frame 18-00, 2 * represents time frame 00-06Z, 3 represents time frame 06-12z */ - /*if (precip_flag == true) { + if (precip_flag == true) { if (DailyQcUtils.curHr18_00 == 1) { DailyQcUtils.pdata[0].used[1] = 0; DailyQcUtils.pdata[0].used[2] = 0; @@ -200,7 +200,7 @@ public class AutoDailyQC { DailyQcUtils.pdata[0].used[3] = 0; DailyQcUtils.pdata[0].used[4] = 0; } - } else*/ if (freezingl_flag == true) { + } else if (freezingl_flag == true) { if (DailyQcUtils.curHr18_00 == 1) { DailyQcUtils.zdata[0].used[1] = 0; DailyQcUtils.zdata[0].used[2] = 0; @@ -345,13 +345,6 @@ public class AutoDailyQC { WriteQPFGrids wq = new WriteQPFGrids(); wq.write_qpf_grids(dbuf); - //copy data from DailyQcUtils.pcp.value to datavals - for (int y = 0; y < hrap_grid.maxj; y++) { - for (int x = 0; x < hrap_grid.maxi; x++) { - datavals[x][y] = (DailyQcUtils.pcp.value[x][y] / 100.f); - } - } - /* output grid to file in grib format */ // create netCDF file from data, write it out then call diff --git a/cave/com.raytheon.viz.pointdata/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.pointdata/META-INF/MANIFEST.MF index 5d52f067c9..6c4bd232bd 100644 --- a/cave/com.raytheon.viz.pointdata/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.viz.pointdata/META-INF/MANIFEST.MF @@ -11,7 +11,6 @@ Require-Bundle: org.apache.batik, org.eclipse.core.runtime, com.raytheon.viz.core, com.raytheon.uf.viz.core, - org.geotools, com.raytheon.viz.ui, org.apache.commons.lang, javax.measure, @@ -28,12 +27,12 @@ Export-Package: com.raytheon.viz.pointdata, com.raytheon.viz.pointdata.util Import-Package: com.raytheon.edex.meteoLib, com.raytheon.uf.common.comm, + com.raytheon.uf.common.dataplugin.grid, com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.derivparam.tree, com.raytheon.uf.common.message.response, com.raytheon.uf.common.pointdata, com.raytheon.uf.common.pointdata.accumulate, - com.raytheon.uf.common.serialization.comm, com.raytheon.uf.viz.derivparam.data, com.raytheon.uf.viz.derivparam.inv, com.raytheon.uf.viz.derivparam.library, diff --git a/cave/com.raytheon.viz.pointdata/plugin.xml b/cave/com.raytheon.viz.pointdata/plugin.xml index 75332bb6e2..d12486c531 100644 --- a/cave/com.raytheon.viz.pointdata/plugin.xml +++ b/cave/com.raytheon.viz.pointdata/plugin.xml @@ -130,7 +130,7 @@ point="com.raytheon.uf.viz.localization.localizationpath"> getProductParameters( String[] selection, String[] order) { HashMap queryList = new HashMap(); - queryList.put(order[0], new RequestConstraint(selection[1])); + queryList.put(PLUGIN_NAME, new RequestConstraint(selection[1])); PointDataInventory inv = getInventory(); if (!inv.getTypeKey(selection[1]) .equals(PointDataInventory.PLUGIN_NAME)) { @@ -129,7 +129,7 @@ public class PlotModelDataDefinition extends String param = null; if (selection.length == 1) { results = inv.getPlugins().toArray(new String[0]); - param = order[0]; + param = PLUGIN_NAME; return formatData(param, results); } String source = selection[1]; @@ -151,13 +151,13 @@ public class PlotModelDataDefinition extends } if ((hasType && selection.length == 3) || selection.length == 2) { results = getModels(source); - param = order[2]; + param = order[1]; return formatData(param, results); } if ((hasType && selection.length == 4) || selection.length == 3) { results = getLevels(source, selection[selection.length - 1]); - param = order[3]; + param = order[2]; return formatData(param, results); } return null; @@ -169,13 +169,13 @@ public class PlotModelDataDefinition extends Arrays.sort(parameters); List labels = new ArrayList(); for (int i = 0; i < parameters.length; i++) { - if (param == order[2]) { + if (param == order[1]) { labels.add(new ProductBrowserLabel(parameters[i].replace( ".svg", ""), parameters[i])); } else { labels.add(new ProductBrowserLabel(parameters[i], parameters[i])); } - labels.get(i).setProduct(param == order[3]); + labels.get(i).setProduct(param == order[2]); } return labels; } diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/rsc/AdaptivePlotResourceData.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/rsc/AdaptivePlotResourceData.java index 1bae858e16..f89e1a2485 100644 --- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/rsc/AdaptivePlotResourceData.java +++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/rsc/AdaptivePlotResourceData.java @@ -161,8 +161,7 @@ public class AdaptivePlotResourceData extends AbstractResourceData implements LoadProperties loadProperties, IDescriptor descriptor) throws VizException { if (file == null) { - fileUpdated(new FileUpdatedMessage(null, null, - FileChangeType.DELETED)); + fileUpdated(FileChangeType.ADDED, filePath); } if (file == null) { @@ -186,10 +185,17 @@ public class AdaptivePlotResourceData extends AbstractResourceData implements */ @Override public synchronized void fileUpdated(FileUpdatedMessage message) { + fileUpdated(message.getChangeType(), message.getFileName()); + } + + private void fileUpdated(FileChangeType changeType, String filePath) { Set newObjects = new HashSet(); - switch (message.getChangeType()) { + switch (changeType) { case DELETED: case ADDED: { + if (file != null) { + file.removeFileUpdatedObserver(this); + } // Our old file was deleted, search for file file = PathManagerFactory.getPathManager() .getStaticLocalizationFile(filePath); diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/AbstractPointDataInventory.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/AbstractPointDataInventory.java index cec653fa2a..26a6fd0bfa 100644 --- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/AbstractPointDataInventory.java +++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/AbstractPointDataInventory.java @@ -49,11 +49,12 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamDesc; import com.raytheon.uf.viz.derivparam.library.DerivParamField; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod; import com.raytheon.uf.viz.derivparam.library.DerivParamMethod.MethodType; -import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode; -import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode; +import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode; /** - * TODO Add Description + * Abstract implementation of a point data inventory that can be used by + * datatypes that have point data but don't adhere fully to the point data api. * *
  * 
@@ -95,7 +96,7 @@ public abstract class AbstractPointDataInventory extends AbstractInventory {
         }
     }
 
-    public List getNodes(String source,
+    public List getNodes(String source,
             List parameters, List levels) throws VizException {
         parameters = new ArrayList(parameters);
         try {
@@ -176,15 +177,15 @@ public abstract class AbstractPointDataInventory extends AbstractInventory {
     }
 
     @Override
-    protected AbstractDerivedLevelNode getImportNode(
+    protected AbstractDerivedDataNode getImportNode(
             AbstractRequestableData nodeToImport, SourceNode destSourceNode,
             DerivParamDesc desc, DerivParamMethod method, Level level) {
         return null;
     }
 
     @Override
-    protected AbstractDerivedLevelNode getImportNode(
-            AbstractRequestableLevelNode nodeToImport,
+    protected AbstractDerivedDataNode getImportNode(
+            AbstractRequestableNode nodeToImport,
             String nodeToImportSourceName, SourceNode destSourceNode,
             DerivParamDesc desc, DerivParamMethod method, Level level) {
         return null;
@@ -212,7 +213,7 @@ public abstract class AbstractPointDataInventory extends AbstractInventory {
     }
 
     @Override
-    protected AbstractDerivedLevelNode createDerivedNode(DerivParamDesc desc,
+    protected AbstractDerivedDataNode createDerivedNode(DerivParamDesc desc,
             DerivParamMethod method, Level level, List fields,
             SourceNode source) {
         if (method.getMethodType() == MethodType.OTHER) {
@@ -220,22 +221,23 @@ public abstract class AbstractPointDataInventory extends AbstractInventory {
                 int index = fields.size() - 1;
                 index -= 4; // The last 4 fields in order are time, paramName,
                             // totalTime, time increment
-                AbstractRequestableLevelNode tNode = (AbstractRequestableLevelNode) fields
+                AbstractRequestableNode tNode = (AbstractRequestableNode) fields
                         .get(index + 1);
-                List idNodes = new ArrayList(
+                List idNodes = new ArrayList(
                         index + 1);
                 for (int i = 0; i <= index; i++) {
-                    idNodes.add((AbstractRequestableLevelNode) fields.get(i));
+                    idNodes.add((AbstractRequestableNode) fields.get(i));
                 }
-                return new PointAccumLevelNode(desc, method, idNodes, tNode);
+                return new PointAccumLevelNode(desc, method, idNodes, tNode,
+                        source.getValue());
             } else if (method.getName().equalsIgnoreCase("HeightOf")) {
-                AbstractRequestableLevelNode latNode = (AbstractRequestableLevelNode) fields
+                AbstractRequestableNode latNode = (AbstractRequestableNode) fields
                         .get(0);
-                AbstractRequestableLevelNode lonNode = (AbstractRequestableLevelNode) fields
+                AbstractRequestableNode lonNode = (AbstractRequestableNode) fields
                         .get(1);
-                AbstractRequestableLevelNode timeNode = null;
+                AbstractRequestableNode timeNode = null;
                 if (fields.size() > 2) {
-                    timeNode = (AbstractRequestableLevelNode) fields.get(2);
+                    timeNode = (AbstractRequestableNode) fields.get(2);
                 }
                 return new HeightOfLevelNode(level, desc, method, latNode,
                         lonNode, timeNode);
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfLevelNode.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfLevelNode.java
index 42049dbc32..163b5b2097 100644
--- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfLevelNode.java
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfLevelNode.java
@@ -20,23 +20,24 @@
 package com.raytheon.viz.pointdata.util;
 
 import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import com.raytheon.uf.common.dataplugin.level.Level;
-import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest;
-import com.raytheon.uf.common.time.DataTime;
-import com.raytheon.uf.viz.core.catalog.LayerProperty;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
+import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer;
+import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace;
 import com.raytheon.uf.viz.derivparam.library.DerivParamDesc;
 import com.raytheon.uf.viz.derivparam.library.DerivParamMethod;
-import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
 
 /**
- * TODO Add Description
+ * Node for the HeightOf point data derived parameter
  * 
  * 
  * 
@@ -51,13 +52,13 @@ import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
  * @version 1.0
  */
 
-public class HeightOfLevelNode extends AbstractDerivedLevelNode {
+public class HeightOfLevelNode extends AbstractDerivedDataNode {
 
-    private AbstractRequestableLevelNode latNode;
+    private AbstractRequestableNode latNode;
 
-    private AbstractRequestableLevelNode lonNode;
+    private AbstractRequestableNode lonNode;
 
-    private AbstractRequestableLevelNode timeNode;
+    private AbstractRequestableNode timeNode;
 
     /**
      * @param desc
@@ -66,40 +67,44 @@ public class HeightOfLevelNode extends AbstractDerivedLevelNode {
      * @param lonNode
      */
     public HeightOfLevelNode(Level level, DerivParamDesc desc,
-            DerivParamMethod method, AbstractRequestableLevelNode latNode,
-            AbstractRequestableLevelNode lonNode,
-            AbstractRequestableLevelNode timeNode) {
+            DerivParamMethod method, AbstractRequestableNode latNode,
+            AbstractRequestableNode lonNode, AbstractRequestableNode timeNode) {
         super(level, desc, method, null);
         this.latNode = latNode;
         this.lonNode = lonNode;
         this.timeNode = timeNode;
     }
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * getDataInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int,
-     * java.util.Map)
-     */
     @Override
-    protected List getDataInternal(
-            LayerProperty property,
-            int timeOut,
-            Map> cache)
+    public Map> getDataDependency(
+            Set availability,
+            AvailabilityContainer availabilityContainer) throws VizException {
+        Map> result = new HashMap>();
+        result.put(latNode, availability);
+        result.put(lonNode, availability);
+        if (timeNode != null) {
+            result.put(timeNode, availability);
+        }
+        return result;
+    }
+
+    @Override
+    public Set getData(
+            Set availability,
+            Map> dependencyData)
             throws VizException {
-        AbstractRequestableData latRequest = latNode.getData(property, timeOut,
-                cache).get(0);
-        AbstractRequestableData lonRequest = lonNode.getData(property, timeOut,
-                cache).get(0);
+        AbstractRequestableData latRequest = dependencyData.get(latNode)
+                .iterator().next();
+        AbstractRequestableData lonRequest = dependencyData.get(lonNode)
+                .iterator().next();
         AbstractRequestableData timeRequest = null;
         if (timeNode != null) {
-            timeRequest = timeNode.getData(property, timeOut, cache).get(0);
+            timeRequest = dependencyData.get(timeNode).iterator().next();
         }
         AbstractRequestableData heightOf = new HeightOfRequestableData(
                 this.getLevel(), this.desc.getAbbreviation(), latRequest,
                 lonRequest, timeRequest);
-        return Arrays.asList(heightOf);
+        return new HashSet(Arrays.asList(heightOf));
     }
 
     /*
@@ -119,23 +124,10 @@ public class HeightOfLevelNode extends AbstractDerivedLevelNode {
         }
     }
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * timeQueryInternal(boolean, java.util.Map)
-     */
     @Override
-    protected Set timeQueryInternal(TimeQueryRequest originalRequest,
-            boolean latestOnly,
-            Map> cache,
-            Map> latestOnlyCache)
+    public Set getAvailability(
+            Map> availability)
             throws VizException {
-        return TIME_AGNOSTIC;
-    }
-
-    @Override
-    public boolean isTimeAgnostic() {
-        return true;
+        return AvailabilityContainer.AGNOSTIC_SET;
     }
 }
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfRequestableData.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfRequestableData.java
index 8105b4b388..69a468754e 100644
--- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfRequestableData.java
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/HeightOfRequestableData.java
@@ -31,6 +31,7 @@ import org.opengis.referencing.crs.CoordinateReferenceSystem;
 
 import com.raytheon.edex.meteoLib.Controller;
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
 import com.raytheon.uf.common.dataplugin.level.Level;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
@@ -48,7 +49,7 @@ import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
 import com.vividsolutions.jts.geom.Coordinate;
 
 /**
- * TODO Add Description
+ * Determines the height of a point using gridded data if it is available.
  * 
  * 
  * 
@@ -185,16 +186,18 @@ public class HeightOfRequestableData extends AbstractRequestableData {
 
     private Map getConstraints() {
         Map constraints = new HashMap();
-        constraints.put("pluginName", new RequestConstraint("grib"));
-        constraints.put("modelInfo.parameterAbbreviation",
+        constraints.put(GridConstants.PLUGIN_NAME, new RequestConstraint(
+                GridConstants.GRID));
+        constraints.put(GridConstants.PARAMETER_ABBREVIATION,
                 new RequestConstraint("GH"));
-        constraints.put("modelInfo.modelName", new RequestConstraint("GFS212"));
-        constraints.put("modelInfo.level.masterLevel.name",
-                new RequestConstraint(level.getMasterLevel().getName()));
-        constraints.put("modelInfo.level.levelonevalue", new RequestConstraint(
-                level.getLevelOneValueAsString().toString()));
-        constraints.put("modelInfo.level.leveltwovalue", new RequestConstraint(
-                Level.getInvalidLevelValueAsString()));
+        constraints.put(GridConstants.DATASET_ID, new RequestConstraint(
+                "GFS212"));
+        constraints.put(GridConstants.MASTER_LEVEL_NAME, new RequestConstraint(
+                level.getMasterLevel().getName()));
+        constraints.put(GridConstants.LEVEL_ONE, new RequestConstraint(level
+                .getLevelOneValueAsString().toString()));
+        constraints.put(GridConstants.LEVEL_TWO,
+                new RequestConstraint(Level.getInvalidLevelValueAsString()));
         return constraints;
     }
 
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumLevelNode.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumLevelNode.java
index 97ba8f5800..b867af2950 100644
--- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumLevelNode.java
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumLevelNode.java
@@ -21,22 +21,24 @@ package com.raytheon.viz.pointdata.util;
 
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest;
-import com.raytheon.uf.common.time.DataTime;
-import com.raytheon.uf.viz.core.catalog.LayerProperty;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
+import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer;
+import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace;
 import com.raytheon.uf.viz.derivparam.library.DerivParamDesc;
 import com.raytheon.uf.viz.derivparam.library.DerivParamMethod;
-import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractDerivedDataNode;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
 
 /**
- * TODO Add Description
+ * A Node representing the Accum derived paramteer method which is used by point
+ * data to generate accumulations over time.
  * 
  * 
  * 
@@ -51,52 +53,62 @@ import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
  * @version 1.0
  */
 
-public class PointAccumLevelNode extends AbstractDerivedLevelNode {
+public class PointAccumLevelNode extends AbstractDerivedDataNode {
 
-    private List idNodes;
+    private List idNodes;
 
-    private AbstractRequestableLevelNode timeNode;
+    private AbstractRequestableNode timeNode;
+
+    private String plugin;
 
     public PointAccumLevelNode(PointAccumLevelNode that) {
         super(that);
         this.idNodes = that.idNodes;
         this.timeNode = that.timeNode;
+        this.plugin = that.plugin;
     }
 
     public PointAccumLevelNode(DerivParamDesc desc, DerivParamMethod method,
-            List idNodes,
-            AbstractRequestableLevelNode timeNode) {
+            List idNodes,
+            AbstractRequestableNode timeNode, String plugin) {
         super(PointDataInventory.getStationLevel(), desc, method, null);
         this.idNodes = idNodes;
         this.timeNode = timeNode;
+        this.plugin = plugin;
     }
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * getDataInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int,
-     * java.util.Map)
-     */
     @Override
-    protected List getDataInternal(
-            LayerProperty property,
-            int timeOut,
-            Map> cache)
+    public Map> getDataDependency(
+            Set availability,
+            AvailabilityContainer availabilityContainer) throws VizException {
+        Map> rval = new HashMap>();
+        for (AbstractRequestableNode idNode : idNodes) {
+            rval.put(idNode, availability);
+        }
+        rval.put(timeNode, availability);
+        return rval;
+    }
+
+    @Override
+    public Set getData(
+            Set availability,
+            Map> dependencyData)
             throws VizException {
         List idRequesters = new ArrayList(
                 idNodes.size());
-        for (AbstractRequestableLevelNode idNode : idNodes) {
-            idRequesters.add(idNode.getData(property, timeOut, cache).get(0));
+        for (AbstractRequestableNode idNode : idNodes) {
+            AbstractRequestableData idRequester = dependencyData.get(idNode)
+                    .iterator().next();
+            idRequesters.add(idRequester);
         }
+
         AbstractRequestableData rData = new PointAccumRequestableData(
-                idRequesters,
-                timeNode.getData(property, timeOut, cache).get(0), method,
-                property);
+                idRequesters, dependencyData.get(timeNode).iterator().next(),
+                method, plugin);
         rData.setParameter(desc.getAbbreviation());
         rData.setParameterName(desc.getName());
         rData.setUnit(desc.getUnit());
-        return Arrays.asList(rData);
+        return new HashSet(Arrays.asList(rData));
     }
 
     /*
@@ -109,30 +121,17 @@ public class PointAccumLevelNode extends AbstractDerivedLevelNode {
     public List getDependencies() {
         List dependencies = new ArrayList();
         dependencies.add(new Dependency(timeNode, 0));
-        for (AbstractRequestableLevelNode idNode : idNodes) {
+        for (AbstractRequestableNode idNode : idNodes) {
             dependencies.add(new Dependency(idNode, 0));
         }
         return dependencies;
     }
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * timeQueryInternal(boolean, java.util.Map)
-     */
     @Override
-    protected Set timeQueryInternal(TimeQueryRequest originalRequest,
-            boolean latestOnly,
-            Map> cache,
-            Map> latestOnlyCache)
+    public Set getAvailability(
+            Map> availability)
             throws VizException {
-        return TIME_AGNOSTIC;
-    }
-
-    @Override
-    public boolean isTimeAgnostic() {
-        return true;
+        return AvailabilityContainer.AGNOSTIC_SET;
     }
 
     public PointAccumLevelNode clone() {
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumRequestableData.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumRequestableData.java
index 4275b2d530..2942f38b47 100644
--- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumRequestableData.java
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointAccumRequestableData.java
@@ -30,7 +30,6 @@ import com.raytheon.uf.common.datastorage.records.IntegerDataRecord;
 import com.raytheon.uf.common.datastorage.records.LongDataRecord;
 import com.raytheon.uf.common.datastorage.records.StringDataRecord;
 import com.raytheon.uf.common.pointdata.accumulate.AccumDataRequestMessage;
-import com.raytheon.uf.viz.core.catalog.LayerProperty;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.core.requests.ThriftClient;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
@@ -39,7 +38,8 @@ import com.raytheon.uf.viz.derivparam.library.DerivParamField;
 import com.raytheon.uf.viz.derivparam.library.DerivParamMethod;
 
 /**
- * TODO Add Description
+ * Carries out the Accum derived parameter method by sending an accum request to
+ * edex.
  * 
  * 
  * 
@@ -65,12 +65,10 @@ public class PointAccumRequestableData extends AbstractRequestableData {
     public PointAccumRequestableData(
             List idRequesters,
             AbstractRequestableData timeRequester, DerivParamMethod method,
-            LayerProperty property) throws VizException {
+            String plugin) throws VizException {
         this.idRequesters = idRequesters;
         this.timeRequester = timeRequester;
         this.request = new AccumDataRequestMessage();
-        String plugin = property.getEntryQueryParameters(false)
-                .get("pluginName").getConstraintValue();
         int index = method.getFields().size() - 1;
         int minutes = ((DerivParamConstantField) method.getFields()
                 .get(index--)).getValue().intValue();
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataCubeAdapter.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataCubeAdapter.java
index 26fcd0bbf3..5ebbb8282e 100644
--- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataCubeAdapter.java
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataCubeAdapter.java
@@ -22,11 +22,8 @@ package com.raytheon.viz.pointdata.util;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 
 import com.raytheon.uf.common.dataplugin.PluginDataObject;
 import com.raytheon.uf.common.dataplugin.level.Level;
@@ -52,17 +49,19 @@ import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.core.level.LevelMappingFactory;
 import com.raytheon.uf.viz.core.requests.ThriftClient;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
+import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer;
 import com.raytheon.uf.viz.derivparam.library.DerivedParameterGenerator;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode.Dependency;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
 import com.raytheon.viz.pointdata.PointDataRequest;
 
 /**
  * This adapter allows a user to request derived parameters from point data
- * sets. It is important to note that the parameter names differ between grid
- * and point datasets so any derived parameter writer will need to provide
- * execute methods for both data types. An obvious example would be Wind Chill
- * but would easily apply to other derived parameters.
+ * sets. It is important to note that derived parameters for point data is much
+ * different than grid. The primary difference is that while grid is combining
+ * multiple records that represent different parameters, point data is combining
+ * multiple paramters within a single record. As a result point data does not
+ * use the time and space matching functions of derived parameters since they
+ * are guaranteed to match for all parameters within a record.
  * 
  * 
  * 
@@ -146,51 +145,22 @@ public class PointDataCubeAdapter implements IDataCubeAdapter {
 
         List levels = LevelMappingFactory.getInstance()
                 .getLevelMappingForKey(levelKey).getLevels();
-        List nodes = inventory.getNodes(source,
+        List nodes = inventory.getNodes(source,
                 Arrays.asList(parameters), levels);
-        // Now we have the nodes, rig the dependencies
-        List deps = new ArrayList(
-                nodes);
-        Set baseNodes = new HashSet();
-        Set baseParams = new HashSet();
-        for (int i = 0; i < deps.size(); i++) {
-            AbstractRequestableLevelNode node = deps.get(i);
-            if (node instanceof PointDataLevelNode) {
-                baseNodes.add((PointDataLevelNode) node);
-                baseParams.add(((PointDataLevelNode) node).getParameter());
-            } else {
-                for (Dependency dep : node.getDependencies()) {
-                    deps.add(dep.node);
-                }
-            }
+        PointMetadataContainer pmc = new PointMetadataContainer(queryParams,
+                Arrays.asList(parameters), this);
+        for (AbstractRequestableNode node : nodes) {
+            pmc.prepareRequests(node, AvailabilityContainer.AGNOSTIC_SET);
         }
-        if (Arrays.asList(parameters).contains("dataURI")) {
-            baseParams.add("dataURI");
-        }
-        PointDataContainer pdc = getBaseRecords(baseParams, queryParams);
-        if (pdc == null) {
-            return pdc;
-        }
-        Map> cache = new HashMap>();
-        for (PointDataLevelNode node : baseNodes) {
-            IDataRecord rec = pdc.getParameterRecord(node.getParameter());
-            cache.put(node, Arrays
-                    .asList((AbstractRequestableData) new PointRequestableData(
-                            rec, pdc.getDescription(node.getParameter())
-                                    .getUnitObject())));
-            if (nodes.contains(node)) {
-                nodes.remove(node);
-            } else if (!Arrays.asList("id", "latitude", "longitude", "dataURI")
-                    .contains(rec.getName())) {
-                pdc.remove(rec.getName());
-            }
-        }
-        LayerProperty lp = new LayerProperty();
-        lp.setEntryQueryParameters(queryParams, false);
         List requests = new ArrayList();
-        for (AbstractRequestableLevelNode node : nodes) {
 
-            requests.addAll(node.getData(lp, 60000, cache));
+        for (AbstractRequestableNode node : nodes) {
+            requests.addAll(pmc.getData(node,
+                    AvailabilityContainer.AGNOSTIC_SET));
+        }
+        PointDataContainer pdc = pmc.getContainer();
+        if (pdc == null) {
+            return null;
         }
         for (AbstractRequestableData request : requests) {
             String unit = request.getUnit() == null ? null : request.getUnit()
@@ -253,7 +223,7 @@ public class PointDataCubeAdapter implements IDataCubeAdapter {
         return type;
     }
 
-    protected PointDataContainer getBaseRecords(Collection baseParams,
+    public PointDataContainer getBaseRecords(Collection baseParams,
             Map queryParams) throws VizException {
         String plugin = queryParams.get(PLUGIN_NAME).getConstraintValue();
         return PointDataRequest.requestPointDataAllLevels(null, plugin,
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataLevelNode.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataLevelNode.java
index 6a12f9e190..f55e8ee991 100644
--- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataLevelNode.java
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointDataLevelNode.java
@@ -19,24 +19,21 @@
  **/
 package com.raytheon.viz.pointdata.util;
 
-import java.util.Collections;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
 import com.raytheon.uf.common.dataquery.requests.DbQueryRequest;
 import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
-import com.raytheon.uf.common.dataquery.requests.TimeQueryRequest;
-import com.raytheon.uf.common.dataquery.responses.DbQueryResponse;
 import com.raytheon.uf.common.derivparam.tree.LevelNode;
-import com.raytheon.uf.common.time.DataTime;
-import com.raytheon.uf.viz.core.catalog.LayerProperty;
 import com.raytheon.uf.viz.core.exception.VizException;
 import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
-import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
+import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer;
+import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace;
+import com.raytheon.uf.viz.derivparam.tree.AbstractBaseDataNode;
 
 /**
- * TODO Add Description
+ * A BaseDataNode for PointData types so that they can be used within derived
+ * parameters.
  * 
  * 
  * 
@@ -51,7 +48,7 @@ import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode;
  * @version 1.0
  */
 
-public class PointDataLevelNode extends AbstractRequestableLevelNode {
+public class PointDataLevelNode extends AbstractBaseDataNode {
 
     private String parameter;
 
@@ -72,101 +69,19 @@ public class PointDataLevelNode extends AbstractRequestableLevelNode {
         return parameter;
     }
 
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * getDataInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int,
-     * java.util.Map)
-     */
     @Override
-    protected List getDataInternal(
-            LayerProperty property,
-            int timeOut,
-            Map> cache)
-            throws VizException {
-        return cache.remove(this);
-    }
-
-    /*
-     * (non-Javadoc)
-     * 
-     * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * getDataQueryInternal(com.raytheon.uf.viz.core.catalog.LayerProperty, int,
-     * java.util.Map)
-     */
-    @Override
-    protected DbQueryRequest getDataQueryInternal(
-            LayerProperty property,
-            int timeOut,
-            Map> cache)
-            throws VizException {
-        throw new UnsupportedOperationException(
-                "PointData nodes do not support returning data query");
-    }
-
-    /*
-     * (non-Javadoc)
-     * 
-     * @see com.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * processQueryResults
-     * (com.raytheon.uf.common.dataquery.responses.DbQueryResponse)
-     */
-    @Override
-    protected List processDataQueryResults(
-            DbQueryResponse queryResponse) throws VizException {
-        throw new UnsupportedOperationException(
-                "PointData nodes do not support processing data query");
-    }
-
-    @Override
-    protected TimeQueryRequest getTimeQueryInternal(
-            TimeQueryRequest originalRequest, boolean latestOnly,
-            Map> cache)
-            throws VizException {
-        throw new UnsupportedOperationException(
-                "PointData nodes do not support returning time query");
-    }
-
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * getDependencies()
-     */
-    @Override
-    public List getDependencies() {
-        return Collections.emptyList();
-    }
-
-    /*
-     * (non-Javadoc)
-     * 
-     * @seecom.raytheon.uf.viz.derivparam.tree.AbstractRequestableLevelNode#
-     * timeQueryInternal(boolean, java.util.Map)
-     */
-    @Override
-    protected Set timeQueryInternal(TimeQueryRequest originalRequest,
-            boolean latestOnly,
-            Map> cache,
-            Map> latestOnlyCache)
-            throws VizException {
-        return TIME_AGNOSTIC;
-    }
-
-    @Override
-    public boolean isTimeAgnostic() {
-        return true;
-    }
-
-    @Override
-    public Map getRequestConstraintMap() {
+    public DbQueryRequest getDataRequest(
+            Map orignalConstraints,
+            Set availability) {
         return null;
     }
 
     @Override
-    public boolean hasRequestConstraints() {
-        return false;
+    public Set getData(
+            Map orignalConstraints,
+            Set availability, Object response)
+            throws VizException {
+        return null;
     }
 
     /*
@@ -209,4 +124,17 @@ public class PointDataLevelNode extends AbstractRequestableLevelNode {
     public PointDataLevelNode clone() {
         return new PointDataLevelNode(this);
     }
+
+    @Override
+    public DbQueryRequest getAvailabilityRequest(
+            Map originalConstraints) {
+        return null;
+    }
+
+    @Override
+    public Set getAvailability(
+            Map originalConstraints, Object response) {
+        return AvailabilityContainer.AGNOSTIC_SET;
+    }
+
 }
diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointMetadataContainer.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointMetadataContainer.java
new file mode 100644
index 0000000000..35e06b2f6f
--- /dev/null
+++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointMetadataContainer.java
@@ -0,0 +1,117 @@
+/**
+ * This software was developed and / or modified by Raytheon Company,
+ * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
+ * 
+ * U.S. EXPORT CONTROLLED TECHNICAL DATA
+ * This software product contains export-restricted data whose
+ * export/transfer/disclosure is restricted by U.S. law. Dissemination
+ * to non-U.S. persons whether in the United States or abroad requires
+ * an export license or other authorization.
+ * 
+ * Contractor Name:        Raytheon Company
+ * Contractor Address:     6825 Pine Street, Suite 340
+ *                         Mail Stop B8
+ *                         Omaha, NE 68106
+ *                         402.291.0100
+ * 
+ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
+ * further licensing information.
+ **/
+package com.raytheon.viz.pointdata.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import com.raytheon.uf.common.dataquery.requests.RequestConstraint;
+import com.raytheon.uf.common.datastorage.records.IDataRecord;
+import com.raytheon.uf.common.pointdata.PointDataContainer;
+import com.raytheon.uf.viz.core.exception.VizException;
+import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData;
+import com.raytheon.uf.viz.derivparam.inv.AvailabilityContainer;
+import com.raytheon.uf.viz.derivparam.inv.MetadataContainer;
+import com.raytheon.uf.viz.derivparam.tree.AbstractRequestableNode;
+
+/**
+ * A MetadataContainer that is optimized for point data. This container ensures
+ * that the point data api is used properly to bulk request all the base
+ * parameters at once.
+ * 
+ * 
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Apr 13, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class PointMetadataContainer extends MetadataContainer { + + private final PointDataCubeAdapter pdca; + + private final List requestedParameters; + + private PointDataContainer pdc; + + public PointMetadataContainer( + Map originalConstraints, + List requestedParameters, PointDataCubeAdapter pdca) { + super(originalConstraints, new AvailabilityContainer( + originalConstraints)); + this.requestedParameters = requestedParameters; + this.pdca = pdca; + } + + public PointDataContainer getContainer() { + return pdc; + } + + /** + * For point data need the full data record instead of just a simple db + * request, this method handles requesting all the parameters using the + * point data API at one time. + */ + @Override + protected void processRequests() throws VizException { + List nodes = new ArrayList(); + List baseParams = new ArrayList(); + for (AbstractRequestableNode node : availCache.keySet()) { + if (dataCache.containsKey(node)) { + continue; + } + if (node instanceof PointDataLevelNode) { + PointDataLevelNode dataNode = (PointDataLevelNode) node; + nodes.add(dataNode); + baseParams.add(dataNode.getParameter()); + } + } + if (baseParams.isEmpty()) { + return; + } + if (requestedParameters.contains("dataURI")) { + baseParams.add("dataURI"); + } + pdc = pdca.getBaseRecords(baseParams, originalConstraints); + for (PointDataLevelNode node : nodes) { + IDataRecord rec = pdc.getParameterRecord(node.getParameter()); + Set cacheSet = new HashSet(); + cacheSet.add(new PointRequestableData(rec, pdc.getDescription( + node.getParameter()).getUnitObject())); + dataCache.put(node, cacheSet); + if (!Arrays.asList("id", "latitude", "longitude", "dataURI") + .contains(rec.getName())) { + pdc.remove(rec.getName()); + } + } + } + +} diff --git a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointRequestableData.java b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointRequestableData.java index 52b4fcc14c..e3a8e9da02 100644 --- a/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointRequestableData.java +++ b/cave/com.raytheon.viz.pointdata/src/com/raytheon/viz/pointdata/util/PointRequestableData.java @@ -24,9 +24,11 @@ import javax.measure.unit.Unit; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.derivparam.data.AbstractRequestableData; +import com.raytheon.uf.viz.derivparam.inv.TimeAndSpace; /** - * TODO Add Description + * Wraps a data record from a PointDataContainer in the AbstractRequestableData + * api so it can be used in Derived Parameters * *
  * 
@@ -50,6 +52,8 @@ public class PointRequestableData extends AbstractRequestableData {
         this.rec = rec;
         this.level = PointDataInventory.getStationLevel();
         this.parameter = rec.getName();
+        this.dataTime = TimeAndSpace.TIME_AGNOSTIC;
+        this.space = TimeAndSpace.SPACE_AGNOSTIC;
     }
 
     /*
diff --git a/cave/com.raytheon.viz.product.awips/developer.product b/cave/com.raytheon.viz.product.awips/developer.product
index e444cabd71..760b4375e3 100644
--- a/cave/com.raytheon.viz.product.awips/developer.product
+++ b/cave/com.raytheon.viz.product.awips/developer.product
@@ -47,7 +47,7 @@
    
 
    
-      
+      
       
    
 
diff --git a/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/RadarProductBrowserDataDefinition.java b/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/RadarProductBrowserDataDefinition.java
index 0387b61602..e8e0487610 100644
--- a/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/RadarProductBrowserDataDefinition.java
+++ b/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/RadarProductBrowserDataDefinition.java
@@ -86,8 +86,7 @@ public class RadarProductBrowserDataDefinition extends
         }
         productName = "radar";
         displayName = "Radar";
-        order = new String[] { "pluginName", "icao", "productCode",
-                "primaryElevationAngle" };
+        order = new String[] { "icao", "productCode", "primaryElevationAngle" };
         order = getOrder();
         loadProperties = new LoadProperties();
         loadProperties.getCapabilities().addCapability(ImagingCapability.class);
@@ -131,7 +130,8 @@ public class RadarProductBrowserDataDefinition extends
                                         .getResolution() / 1000) + " km ";
                     }
                     labels.add(new ProductBrowserLabel(infoDict.getInfo(tmp)
-                            .getName() + "::" + parm, parameters[i]));
+                            .getName() + " (" + tmp + ")" + "::" + parm,
+                            parameters[i]));
                 }
                 Collections.sort(labels);
                 for (int i = 0; i < parameters.length; i++) {
diff --git a/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/GraphicDataUtil.java b/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/GraphicDataUtil.java
index 8a7564106d..0ba93ac697 100644
--- a/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/GraphicDataUtil.java
+++ b/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/GraphicDataUtil.java
@@ -50,8 +50,6 @@ import com.vividsolutions.jts.geom.Envelope;
  * Jun 04  2012	 14710	   Xiaochuan 	The rank value should take  
  * 										from STRENGTH_RANK instead  
  * 										of 2D_STRENGTH_RANK.
- * Nov 09  2012	 15586	   Xiaochuan	In dataRowFormat, set MSI maximum  
- * 										size to 5.
  * 
  * 
* @@ -137,7 +135,7 @@ public class GraphicDataUtil { RadarDataPoint currPoint = symbologyData.get(key); if (currPoint.isVisible() || !checkVisibility) { - String dataRowFormat = " %4.4s %7.7s@%3.3s %9.9s %7.7s r%-2.2s %5.5s %8.8s %8.8s %8.8s %8.8s"; + String dataRowFormat = " %4.4s %7.7s@%3.3s %9.9s %7.7s r%-2.2s %4.4s %8.8s %8.8s %8.8s %8.8s"; AreaComponent currFeature; HashMap> currPointData = currPoint diff --git a/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/RadarDataCubeAdapter.java b/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/RadarDataCubeAdapter.java index c99594e88e..1ac9785836 100644 --- a/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/RadarDataCubeAdapter.java +++ b/cave/com.raytheon.viz.radar/src/com/raytheon/viz/radar/util/RadarDataCubeAdapter.java @@ -110,7 +110,7 @@ public class RadarDataCubeAdapter extends PointDataCubeAdapter { } @Override - protected PointDataContainer getBaseRecords( + public PointDataContainer getBaseRecords( Collection baseParameters, Map queryParams) throws VizException { return ((VwpInventory) inventory).getBaseRecords(baseParameters, diff --git a/cave/com.raytheon.viz.redbook/src/com/raytheon/viz/redbook/rsc/RedbookProductBrowserDataDefinition.java b/cave/com.raytheon.viz.redbook/src/com/raytheon/viz/redbook/rsc/RedbookProductBrowserDataDefinition.java index 06277a8d6f..b578eec134 100644 --- a/cave/com.raytheon.viz.redbook/src/com/raytheon/viz/redbook/rsc/RedbookProductBrowserDataDefinition.java +++ b/cave/com.raytheon.viz.redbook/src/com/raytheon/viz/redbook/rsc/RedbookProductBrowserDataDefinition.java @@ -65,7 +65,7 @@ public class RedbookProductBrowserDataDefinition extends public RedbookProductBrowserDataDefinition() { productName = "redbook"; displayName = "Redbook"; - order = new String[] { "pluginName", "wmoTTAAii" }; + order = new String[] { "wmoTTAAii" }; order = getOrder(); try { mapping = null; diff --git a/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/SatelliteProductBrowserDataDefinition.java b/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/SatelliteProductBrowserDataDefinition.java index b5d3fa1490..f5edb945ef 100644 --- a/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/SatelliteProductBrowserDataDefinition.java +++ b/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/SatelliteProductBrowserDataDefinition.java @@ -48,8 +48,7 @@ public class SatelliteProductBrowserDataDefinition extends public SatelliteProductBrowserDataDefinition() { productName = "satellite"; displayName = "Satellite"; - order = new String[] { "pluginName", "creatingEntity", "sectorID", - "physicalElement" }; + order = new String[] { "creatingEntity", "sectorID", "physicalElement" }; order = getOrder(); loadProperties = new LoadProperties(); loadProperties.setResourceType(getResourceType()); diff --git a/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/rsc/SatBestResResourceData.java b/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/rsc/SatBestResResourceData.java index def4e8f333..5b0184201e 100644 --- a/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/rsc/SatBestResResourceData.java +++ b/cave/com.raytheon.viz.satellite/src/com/raytheon/viz/satellite/rsc/SatBestResResourceData.java @@ -68,7 +68,6 @@ import com.vividsolutions.jts.geom.Polygon; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jul 30, 2010 mschenke Initial creation - * Oct 31, 2012 DR 15287 D. Friedman Fix overlap calculation * Nov 06, 2012 DR 15157 D. Friedman Allow configured inclusion percentage * *
@@ -342,7 +341,7 @@ public class SatBestResResourceData extends AbstractRequestableResourceData { for (Polygon last : prevs) { // Don't want to double include percentage areas - totalPercentage -= last.intersection(polygon).intersection(extent) + totalPercentage -= last.intersection(polygon) .getArea() / extent.getArea(); } } diff --git a/cave/com.raytheon.viz.skewT/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.skewT/META-INF/MANIFEST.MF index 892f55aec4..76cbdefa48 100644 --- a/cave/com.raytheon.viz.skewT/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.viz.skewT/META-INF/MANIFEST.MF @@ -24,8 +24,7 @@ Export-Package: com.raytheon.viz.skewt, com.raytheon.viz.skewt.rsc, com.raytheon.viz.skewt.rscdata, com.raytheon.viz.skewt.ui -Import-Package: com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.viz.d2d.core, +Import-Package: com.raytheon.uf.viz.d2d.core, com.raytheon.uf.viz.d2d.core.legend, com.raytheon.uf.viz.d2d.core.time, com.raytheon.uf.viz.sounding, diff --git a/cave/com.raytheon.viz.skewT/src/com/raytheon/viz/skewt/rscdata/GribSoundingSkewTResourceData.java b/cave/com.raytheon.viz.skewT/src/com/raytheon/viz/skewt/rscdata/GribSoundingSkewTResourceData.java index 3391c83a6e..be723e3e91 100644 --- a/cave/com.raytheon.viz.skewT/src/com/raytheon/viz/skewt/rscdata/GribSoundingSkewTResourceData.java +++ b/cave/com.raytheon.viz.skewT/src/com/raytheon/viz/skewt/rscdata/GribSoundingSkewTResourceData.java @@ -26,7 +26,7 @@ import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.sounding.adapter.AbstractVerticalSoundingAdapter; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.uf.viz.core.rsc.LoadProperties; -import com.raytheon.uf.viz.sounding.adapters.GribSoundingAdapter; +import com.raytheon.uf.viz.sounding.adapters.GridSoundingAdapter; import com.raytheon.uf.viz.sounding.adapters.IPointSounding; import com.raytheon.viz.skewt.rsc.SkewTResource; import com.vividsolutions.jts.geom.Coordinate; @@ -66,7 +66,7 @@ public class GribSoundingSkewTResourceData extends SkewTResourceData implements @Override protected SkewTResource constructResource(LoadProperties loadProperties, PluginDataObject[] objects) throws VizException { - AbstractVerticalSoundingAdapter adapter = new GribSoundingAdapter(this); + AbstractVerticalSoundingAdapter adapter = new GridSoundingAdapter(this); adapter.setObjects(objects); this.soundings = adapter.createSoundings(); SkewTResource rsc = new SkewTResource(this, loadProperties); diff --git a/cave/com.raytheon.viz.ui.personalities.awips/plugin.xml b/cave/com.raytheon.viz.ui.personalities.awips/plugin.xml index 16cdfc001e..663383e8f3 100644 --- a/cave/com.raytheon.viz.ui.personalities.awips/plugin.xml +++ b/cave/com.raytheon.viz.ui.personalities.awips/plugin.xml @@ -78,6 +78,30 @@ name="afterNewGroup" visible="true"> + + + + + + + + + + + + diff --git a/cave/com.raytheon.viz.ui/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.ui/META-INF/MANIFEST.MF index 6b26c568d4..3250d6323d 100644 --- a/cave/com.raytheon.viz.ui/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.viz.ui/META-INF/MANIFEST.MF @@ -28,10 +28,13 @@ Export-Package: com.raytheon.viz.ui, com.raytheon.viz.ui.panes, com.raytheon.viz.ui.parameter.converters, com.raytheon.viz.ui.perspectives, + com.raytheon.viz.ui.presenter, + com.raytheon.viz.ui.presenter.components, com.raytheon.viz.ui.statusline, com.raytheon.viz.ui.tools, com.raytheon.viz.ui.views, - com.raytheon.viz.ui.widgets + com.raytheon.viz.ui.widgets, + com.raytheon.viz.ui.widgets.duallist Bundle-Vendor: Raytheon Import-Package: com.raytheon.uf.common.colormap, com.raytheon.uf.common.message.response diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/AwipsCalendar.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/AwipsCalendar.java new file mode 100644 index 0000000000..df9da24787 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/AwipsCalendar.java @@ -0,0 +1,226 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.dialogs; + +import java.util.Calendar; +import java.util.Date; +import java.util.TimeZone; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.DateTime; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; +import org.eclipse.swt.widgets.Spinner; + +/** + * Awips Calendar Date Selection Dialog. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jan 9, 2012            mpduff     Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class AwipsCalendar extends CaveSWTDialogBase { + + /** The date selection calendar class */ + private DateTime calendar; + + /** The hour selection spinner class */ + private Spinner hourSpinner; + + /** The showHour flag */ + private boolean showHour = true; + + /** The showHour flag */ + private Date date = null; + + /** + * Constructor. + * + * @param parentShell + * @param showHour + */ + public AwipsCalendar(Shell parentShell, boolean showHour) { + super(parentShell, SWT.DIALOG_TRIM); + setText("Calendar"); + this.showHour = showHour; + } + + /** + * Constructor. + * + * @param parentShell + */ + public AwipsCalendar(Shell parentShell) { + super(parentShell, SWT.DIALOG_TRIM); + setText("Calendar"); + + + } + + /** + * Constructor. + * + * @param parentShell + * @param d Date to preset the calendar widget + * @param showHour true to display the hour spinner + */ + public AwipsCalendar(Shell parentShell, Date d, boolean showHour) { + super(parentShell, SWT.DIALOG_TRIM); + setText("Calendar"); + this.date = d; + this.showHour = showHour; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.viz.ui.dialogs.CaveSWTDialogBase#initializeComponents(org + * .eclipse.swt.widgets.Shell) + */ + @Override + protected void initializeComponents(Shell shell) { + + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + if (date != null) { + cal.setTime(date); + } + + + if (showHour) { + createTopWidgets(cal.get(Calendar.HOUR_OF_DAY)); + } + + calendar = new DateTime(shell, SWT.CALENDAR | SWT.BORDER_SOLID); + calendar.setDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH)); + + createButtons(); + } + + /** + * Create the top widgets + */ + private void createTopWidgets(int hour) { + GridLayout gl = new GridLayout(2, false); + GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, true, false); + + Composite top = new Composite(shell, SWT.NONE); + top.setLayout(gl); + top.setLayoutData(gd); + + gd = new GridData(SWT.LEFT, SWT.DEFAULT, true, false); + Label lbl = new Label(top, SWT.NONE); + lbl.setLayoutData(gd); + lbl.setText("Select Hour (Z) and Date: "); + + gd = new GridData(SWT.RIGHT, SWT.DEFAULT, true, false); + + hourSpinner = new Spinner(top, SWT.BORDER | SWT.RIGHT); + hourSpinner.setLayoutData(gd); + hourSpinner.setMinimum(0); + hourSpinner.setMaximum(23); + hourSpinner.setSelection(hour); + hourSpinner.setIncrement(1); + hourSpinner.setPageIncrement(1); + } + + /** + * Create the buttons + */ + private void createButtons() { + int buttonWidth = 75; + GridData btnData = new GridData(buttonWidth, SWT.DEFAULT); + + GridData gd = new GridData(SWT.CENTER, SWT.DEFAULT, true, false); + GridLayout gl = new GridLayout(3, false); + Composite btnComp = new Composite(shell, SWT.NONE); + btnComp.setLayout(gl); + btnComp.setLayoutData(gd); + + Button okBtn = new Button(btnComp, SWT.PUSH); + okBtn.setText("OK"); + okBtn.setLayoutData(btnData); + okBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleOk(); + shell.dispose(); + } + }); + + Button cancelBtn = new Button(btnComp, SWT.PUSH); + cancelBtn.setText("Cancel"); + cancelBtn.setLayoutData(btnData); + cancelBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + shell.dispose(); + } + }); + } + + /** + * Event handler action for OK button + */ + private void handleOk() { + Calendar selectedDate = Calendar.getInstance(TimeZone + .getTimeZone("GMT")); + selectedDate.set(Calendar.YEAR, calendar.getYear()); + selectedDate.set(Calendar.MONTH, calendar.getMonth()); + selectedDate.set(Calendar.DAY_OF_MONTH, calendar.getDay()); + if (showHour) { + selectedDate.set(Calendar.HOUR_OF_DAY, + Integer.parseInt(hourSpinner.getText())); + } else { + selectedDate.set(Calendar.HOUR_OF_DAY, 0); + } + selectedDate.set(Calendar.MINUTE, 0); + selectedDate.set(Calendar.SECOND, 0); + selectedDate.set(Calendar.MILLISECOND, 0); + this.setReturnValue(selectedDate); + } + + /** + * Main + * + * @param args + */ + public static void main(String[] args) { + AwipsCalendar ac = new AwipsCalendar(new Shell()); + ac.open(); + } + +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveJFACEDialog.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveJFACEDialog.java index 2d714ddb53..c261730321 100644 --- a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveJFACEDialog.java +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveJFACEDialog.java @@ -53,6 +53,8 @@ import com.raytheon.viz.ui.perspectives.VizPerspectiveListener; * of removing the dialog blocking capability. * 09/20/12 1196 rferrel Changes to setBlockOnOpen. * 09/27/12 1196 rferrel Added bringToTop + * 11/13/12 1298 rferrel Override open to work in a similar manner + * to CaveSWTDialogBase's open. * *
* @@ -279,4 +281,19 @@ public class CaveJFACEDialog extends Dialog implements super.setBlockOnOpen(blockOnOpen); // blockedOnOpen = blockOnOpen; } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.window.Window#open() + */ + @Override + public int open() { + if (isOpen()) { + bringToTop(); + return getReturnCode(); + } + + return super.open(); + } } diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveSWTDialogBase.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveSWTDialogBase.java index 26928a5584..7703329e18 100644 --- a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveSWTDialogBase.java +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/dialogs/CaveSWTDialogBase.java @@ -413,7 +413,7 @@ public abstract class CaveSWTDialogBase extends Dialog { * Returns if the dialog is disposed, a null dialog will not mean it is * disposed as it may not have been opened yet. * - * @return + * @return boolean */ public final boolean isDisposed() { return (shell != null && shell.isDisposed()); diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/IDisplay.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/IDisplay.java new file mode 100644 index 0000000000..7313bb864c --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/IDisplay.java @@ -0,0 +1,54 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter; + +/** + * Interface representing a way to display something to the user. This interface + * can be used in lieu of the IPresenterView where legacy code does not support + * a presenter. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 20, 2012 1286       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public interface IDisplay { + + /** + * Displays a prompt, returning the Yes/No response of the user. + * + * @param title + * the title for the message box + * @param message + * the message to prompt + * @return true if the user chooses yes + */ + boolean displayYesNoPopup(String title, String message); + +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/IPresenterView.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/IPresenterView.java new file mode 100644 index 0000000000..5e23d82ce4 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/IPresenterView.java @@ -0,0 +1,78 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter; + +/** + * A view interface that defines methods all views should provide an + * implementation for. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012 0743       djohnson     Initial creation
+ * Nov 20, 2012 1322       djohnson     Extend IDisplay for displayYesNoPopup.
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public interface IPresenterView extends IDisplay { + + /** + * Performs initialization of the view. + */ + void init(); + + /** + * Display a popup message. + * + * @param title + * the title + * @param message + * the message + */ + void displayPopup(String title, String message); + + /** + * Display an error popup message. + * + * @param title + * the title + * @param message + * the message + */ + void displayErrorPopup(String title, String message); + + /** + * Display a cancel/ok popup. + * + * @param title + * the title + * @param message + * the message + * + * @return boolean true if OK clicked, false if Cancel + */ + boolean displayOkCancelPopup(String title, String message); +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ButtonConf.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ButtonConf.java new file mode 100644 index 0000000000..5964e5bcd1 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ButtonConf.java @@ -0,0 +1,113 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter.components; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * GUI implementation independent representation of a button. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 24, 2012    223     mpduff      Initial creation.
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class ButtonConf extends LabeledWidgetConf { + /** + * Button enabled flag; + */ + private final boolean enabled; + + /** + * Event handler for the button. + */ + private final Runnable onClickAction; + + /** + * Constructor. + * + * @param enabled + * @param displayText + * @param toolTipText + * @param onClickAction + */ + public ButtonConf(boolean enabled, String displayText, String toolTipText, + Runnable onClickAction) { + super(displayText, toolTipText); + + this.enabled = enabled; + this.onClickAction = onClickAction; + } + + /** + * @return the enabled + */ + public boolean isEnabled() { + return enabled; + } + + /** + * @return the onClickAction + */ + public Runnable getOnClickAction() { + return onClickAction; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + HashCodeBuilder builder = new HashCodeBuilder(); + builder.append(enabled); + builder.append(onClickAction); + builder.appendSuper(super.hashCode()); + + return builder.toHashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ButtonConf) { + ButtonConf other = (ButtonConf) obj; + + EqualsBuilder builder = new EqualsBuilder(); + builder.append(enabled, other.enabled); + builder.append(onClickAction, other.onClickAction); + builder.appendSuper(super.equals(obj)); + + return builder.isEquals(); + } + return super.equals(obj); + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/CheckBoxConf.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/CheckBoxConf.java new file mode 100644 index 0000000000..e2be4b7bce --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/CheckBoxConf.java @@ -0,0 +1,99 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter.components; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * GUI implementation independent representation of a checkbox. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 15, 2012 0743       djohnson     Initial creation.
+ * Aug 29, 2012 0223       mpduff       Extend WidgetConf.
+ *
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public class CheckBoxConf extends LabeledWidgetConf { + private final boolean initiallyChecked; + + private final Runnable onCheckedChangeAction; + + public CheckBoxConf(String displayText, boolean initiallyChecked, + String toolTipText, Runnable onCheckedChangeAction) { + super(displayText, toolTipText); + + this.initiallyChecked = initiallyChecked; + this.onCheckedChangeAction = onCheckedChangeAction; + } + + /** + * @return the initiallyChecked + */ + public boolean isInitiallyChecked() { + return initiallyChecked; + } + + /** + * @return the onCheckedChangeAction + */ + public Runnable getOnCheckedChangeAction() { + return onCheckedChangeAction; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + HashCodeBuilder builder = new HashCodeBuilder(); + builder.append(initiallyChecked); + builder.append(onCheckedChangeAction); + builder.appendSuper(super.hashCode()); + + return builder.toHashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof CheckBoxConf) { + CheckBoxConf other = (CheckBoxConf) obj; + + EqualsBuilder builder = new EqualsBuilder(); + builder.append(initiallyChecked, other.initiallyChecked); + builder.append(onCheckedChangeAction, other.onCheckedChangeAction); + builder.appendSuper(super.equals(obj)); + + return builder.isEquals(); + } + return super.equals(obj); + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ComboBoxConf.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ComboBoxConf.java new file mode 100644 index 0000000000..2aacea3ef0 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ComboBoxConf.java @@ -0,0 +1,114 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter.components; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * GUI implementation independent representation of a combo box. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 16, 2012 0743       djohnson     Initial creation
+ * Aug 29, 2012 0223       mpduff       Extend WidgetConf.
+ * Sep 07, 2012 1102       djohnson     Add missing getter for toolTipText.
+ *
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class ComboBoxConf extends WidgetConf { + public static final String SELECT_ONE = "Select One"; + + public static final String NONE_AVAILABLE = "None Available"; + + private final boolean readOnly; + + private final Runnable onSelectionAction; + + /** + * Constructor setting up configuration. + * + * @param readOnly + * whether or not the combo box should be read only + * @param toolTipText + * the tool tip text + * @param onSelectionAction + * on selection action + */ + public ComboBoxConf(boolean readOnly, String toolTipText, + Runnable onSelectionAction) { + super(toolTipText); + this.readOnly = readOnly; + this.onSelectionAction = onSelectionAction; + } + + /** + * @return the readOnly + */ + public boolean isReadOnly() { + return readOnly; + } + + /** + * @return the onSelectionAction + */ + public Runnable getOnSelectionAction() { + return onSelectionAction; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + HashCodeBuilder builder = new HashCodeBuilder(); + builder.append(readOnly); + builder.append(onSelectionAction); + builder.appendSuper(super.hashCode()); + + return builder.toHashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof ComboBoxConf) { + ComboBoxConf other = (ComboBoxConf) obj; + + EqualsBuilder builder = new EqualsBuilder(); + builder.append(readOnly, other.readOnly); + builder.append(onSelectionAction, other.onSelectionAction); + builder.appendSuper(super.equals(obj)); + + return builder.isEquals(); + } + return super.equals(obj); + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/LabeledWidgetConf.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/LabeledWidgetConf.java new file mode 100644 index 0000000000..a5ed80b216 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/LabeledWidgetConf.java @@ -0,0 +1,92 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter.components; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * Configuration object for SWT widgets that have displayed text. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 18, 2012   223      mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class LabeledWidgetConf extends WidgetConf { + /** Display text */ + protected String displayText; + + /** + * Constructor. + * + * @param displayText + * @param tooltipText + */ + public LabeledWidgetConf(String displayText, String toolTipText) { + super(toolTipText); + this.displayText = displayText; + } + + /** + * @return the displayText + */ + public String getDisplayText() { + return displayText; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + HashCodeBuilder builder = new HashCodeBuilder(); + builder.append(displayText); + builder.appendSuper(super.hashCode()); + + return builder.toHashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof CheckBoxConf) { + CheckBoxConf other = (CheckBoxConf) obj; + + EqualsBuilder builder = new EqualsBuilder(); + builder.append(displayText, other.displayText); + builder.appendSuper(super.equals(obj)); + + return builder.isEquals(); + } + return super.equals(obj); + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ListConf.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ListConf.java new file mode 100644 index 0000000000..467d2c9a5d --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/ListConf.java @@ -0,0 +1,136 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter.components; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * Configuration object for org.eclipse.swt.widgets.List objects. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 12, 2012   223      mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class ListConf extends WidgetConf { + private String[] items; + + private boolean singleSelect = true; + + private final int width; + + private final int height; + + public ListConf(String toolTipText, String[] items, boolean singleSelect, int width, int height) { + super(toolTipText); + + this.items = items; + this.singleSelect = singleSelect; + this.width = width; + this.height = height; + } + + /** + * @param items the items to set + */ + public void setItems(String[] items) { + this.items = items; + } + + /** + * @return the items + */ + public String[] getItems() { + return items; + } + + /** + * @param singleSelect the singleSelect to set + */ + public void setSingleSelect(boolean singleSelect) { + this.singleSelect = singleSelect; + } + + /** + * @return the singleSelect + */ + public boolean isSingleSelect() { + return singleSelect; + } + + /** + * @return the width + */ + public int getWidth() { + return width; + } + + /** + * @return the height + */ + public int getHeight() { + return height; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + HashCodeBuilder builder = new HashCodeBuilder(); + builder.append(items); + builder.append(singleSelect); + builder.append(width); + builder.append(height); + builder.appendSuper(super.hashCode()); + + return builder.toHashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof CheckBoxConf) { + ListConf other = (ListConf) obj; + + EqualsBuilder builder = new EqualsBuilder(); + builder.append(items, other.getItems()); + builder.append(singleSelect, other.isSingleSelect()); + builder.append(width, other.getWidth()); + builder.append(height, other.getHeight()); + builder.appendSuper(super.equals(obj)); + + return builder.isEquals(); + } + return super.equals(obj); + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/WidgetConf.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/WidgetConf.java new file mode 100644 index 0000000000..13e9525713 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/presenter/components/WidgetConf.java @@ -0,0 +1,88 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.presenter.components; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +/** + * Base class for the widget configuration classes. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 26, 2012   223      mpduff     Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public abstract class WidgetConf { + public static final Runnable DO_NOTHING = new Runnable() { + @Override + public void run() { + } + }; + + protected String toolTipText; + + public WidgetConf(String toolTipText) { + this.toolTipText = toolTipText; + } + + /** + * @return the toolTipText + */ + public String getToolTipText() { + return toolTipText; + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + HashCodeBuilder builder = new HashCodeBuilder(); + builder.append(toolTipText); + + return builder.toHashCode(); + } + + /** + * {@inheritDoc} + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof WidgetConf) { + WidgetConf other = (WidgetConf) obj; + + EqualsBuilder builder = new EqualsBuilder(); + builder.append(toolTipText, other.toolTipText); + + return builder.isEquals(); + } + return super.equals(obj); + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/ButtonImages.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/ButtonImages.java new file mode 100644 index 0000000000..dc14bad71d --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/ButtonImages.java @@ -0,0 +1,397 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.widgets.duallist; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.DisposeEvent; +import org.eclipse.swt.events.DisposeListener; +import org.eclipse.swt.graphics.GC; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.graphics.ImageData; +import org.eclipse.swt.graphics.RGB; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Display; + +/** + * Images for the Add All, Add, Remove, Remove All, Move Up, and Move Down + * buttons. Reused from Data Delivery + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 31, 2012            mpduff     Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class ButtonImages { + + /** + * Parent composite. + */ + private Composite parent; + + /** + * Parent display. + */ + private Display parentDisplay; + + /** + * Array of button images. + */ + private Image[] buttonArray; + + /** + * Button image enumeration that identifies which image to use. + */ + public enum ButtonImage { + AddAll, Add, Remove, RemoveAll, Up, Down + }; + + /** + * Constructor. + * + * @param parent + * Parent composite. + */ + public ButtonImages(Composite parent) { + this.parent = parent; + parentDisplay = parent.getDisplay(); + + addDisposeToParent(); + + createButtonImages(); + } + + /** + * Add a dispose listener to the parent composite. When the parent composite + * is disposed, the images will be disposed of. + */ + private void addDisposeToParent() { + parent.addDisposeListener(new DisposeListener() { + @Override + public void widgetDisposed(DisposeEvent e) { + for (Image img : buttonArray) { + img.dispose(); + } + } + }); + } + + /** + * Create the button images. + */ + private void createButtonImages() { + int imgWidthSm = 12; + int imgWidth = 24; + int imgHeight = 12; + Image tmpImg; + + GC gc; + + buttonArray = new Image[ButtonImage.values().length]; + + for (int i = 0; i < ButtonImage.values().length; i++) { + if (ButtonImage.values()[i] == ButtonImage.Up || ButtonImage.values()[i] == ButtonImage.Down) { + buttonArray[i] = new Image(parentDisplay, imgWidthSm, imgHeight); + } + else { + buttonArray[i] = new Image(parentDisplay, imgWidth, imgHeight); + } + } + + /* + * Add all image + */ + tmpImg = new Image(parent.getDisplay(), imgWidth, imgHeight); + gc = new GC(tmpImg); + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_WHITE)); + gc.fillRectangle(0, 0, imgWidth, imgHeight); + gc.dispose(); + + ImageData idata = tmpImg.getImageData(); + + int whitePixel = idata.palette.getPixel(new RGB(255, 255, 255)); + idata.transparentPixel = whitePixel; + Image transparentIdeaImage = new Image(parent.getDisplay(), idata); + + gc = new GC(transparentIdeaImage); + drawAddAllImage(gc, imgWidth, imgHeight); + gc.dispose(); + + buttonArray[ButtonImage.AddAll.ordinal()] = transparentIdeaImage; + tmpImg.dispose(); + + /* + * Add image + */ + tmpImg = new Image(parent.getDisplay(), imgWidth, imgHeight); + gc = new GC(tmpImg); + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_WHITE)); + gc.fillRectangle(0, 0, imgWidth, imgHeight); + gc.dispose(); + + idata = tmpImg.getImageData(); + + whitePixel = idata.palette.getPixel(new RGB(255, 255, 255)); + idata.transparentPixel = whitePixel; + transparentIdeaImage = new Image(parent.getDisplay(), idata); + + gc = new GC(transparentIdeaImage); + drawAddImage(gc, imgWidth, imgHeight); + gc.dispose(); + + buttonArray[ButtonImage.Add.ordinal()] = transparentIdeaImage; + tmpImg.dispose(); + + /* + * Remove image + */ + tmpImg = new Image(parent.getDisplay(), imgWidth, imgHeight); + gc = new GC(tmpImg); + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_WHITE)); + gc.fillRectangle(0, 0, imgWidth, imgHeight); + gc.dispose(); + + idata = tmpImg.getImageData(); + + whitePixel = idata.palette.getPixel(new RGB(255, 255, 255)); + idata.transparentPixel = whitePixel; + transparentIdeaImage = new Image(parent.getDisplay(), idata); + + gc = new GC(transparentIdeaImage); + drawRemoveImage(gc, imgWidth, imgHeight); + gc.dispose(); + + buttonArray[ButtonImage.Remove.ordinal()] = transparentIdeaImage; + tmpImg.dispose(); + + /* + * Remove all image + */ + tmpImg = new Image(parent.getDisplay(), imgWidth, imgHeight); + gc = new GC(tmpImg); + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_WHITE)); + gc.fillRectangle(0, 0, imgWidth, imgHeight); + gc.dispose(); + + idata = tmpImg.getImageData(); + + whitePixel = idata.palette.getPixel(new RGB(255, 255, 255)); + idata.transparentPixel = whitePixel; + transparentIdeaImage = new Image(parent.getDisplay(), idata); + + gc = new GC(transparentIdeaImage); + drawRemoveAllImage(gc, imgWidth, imgHeight); + gc.dispose(); + + buttonArray[ButtonImage.RemoveAll.ordinal()] = transparentIdeaImage; + tmpImg.dispose(); + + /* + * Move up image + */ + tmpImg = new Image(parent.getDisplay(), imgWidthSm, imgHeight); + gc = new GC(tmpImg); + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_WHITE)); + gc.fillRectangle(0, 0, imgWidthSm, imgHeight); + gc.dispose(); + + idata = tmpImg.getImageData(); + + whitePixel = idata.palette.getPixel(new RGB(255, 255, 255)); + idata.transparentPixel = whitePixel; + transparentIdeaImage = new Image(parent.getDisplay(), idata); + + gc = new GC(transparentIdeaImage); + drawMoveUpImage(gc, imgWidthSm, imgHeight); + gc.dispose(); + + buttonArray[ButtonImage.Up.ordinal()] = transparentIdeaImage; + tmpImg.dispose(); + + /* + * Move down image + */ + tmpImg = new Image(parent.getDisplay(), imgWidthSm, imgHeight); + gc = new GC(tmpImg); + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_WHITE)); + gc.fillRectangle(0, 0, imgWidthSm, imgHeight); + gc.dispose(); + + idata = tmpImg.getImageData(); + + whitePixel = idata.palette.getPixel(new RGB(255, 255, 255)); + idata.transparentPixel = whitePixel; + transparentIdeaImage = new Image(parent.getDisplay(), idata); + + gc = new GC(transparentIdeaImage); + drawMoveDownImage(gc, imgWidthSm, imgHeight); + gc.dispose(); + + buttonArray[ButtonImage.Down.ordinal()] = transparentIdeaImage; + tmpImg.dispose(); + } + + /** + * Draw the "add all" image. + * + * @param gc + * Graphics context. + * @param imgWidth + * Image width. + * @param imgHeight + * Image height. + */ + private void drawAddAllImage(GC gc, int imgWidth, int imgHeight) { + gc.setAntialias(SWT.ON); + + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_BLACK)); + + // Draw the left arrow + int[] pointArray = new int[] { 10, 6, 1, 1, 1, 10, 10, 6 }; + gc.fillPolygon(pointArray); + + // Draw the right arrow + pointArray = new int[] { 22, 6, 13, 1, 13, 10, 22, 6 }; + gc.fillPolygon(pointArray); + } + + /** + * Draw the "add" image. + * + * @param gc + * Graphics context. + * @param imgWidth + * Image width. + * @param imgHeight + * Image height. + */ + private void drawAddImage(GC gc, int imgWidth, int imgHeight) { + gc.setAntialias(SWT.ON); + + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_BLACK)); + + // Draw the add arrow + int[] pointArray = new int[] { 17, 6, 8, 1, 8, 10, 17, 6 }; + gc.fillPolygon(pointArray); + } + + /** + * Draw the "remove" image. + * + * @param gc + * Graphics context. + * @param imgWidth + * Image width. + * @param imgHeight + * Image height. + */ + private void drawRemoveImage(GC gc, int imgWidth, int imgHeight) { + gc.setAntialias(SWT.ON); + + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_BLACK)); + + // Draw the add arrow + int[] pointArray = new int[] { 8, 6, 17, 1, 17, 10, 8, 6 }; + gc.fillPolygon(pointArray); + } + + /** + * Draw the "remove all" image. + * + * @param gc + * Graphics context. + * @param imgWidth + * Image width. + * @param imgHeight + * Image height. + */ + private void drawRemoveAllImage(GC gc, int imgWidth, int imgHeight) { + gc.setAntialias(SWT.ON); + + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_BLACK)); + + // Draw the left arrow + int[] pointArray = new int[] { 1, 6, 10, 1, 10, 10, 1, 6 }; + gc.fillPolygon(pointArray); + + // Draw the right arrow + pointArray = new int[] { 13, 6, 22, 1, 22, 10, 13, 6 }; + gc.fillPolygon(pointArray); + } + + /** + * Draw the "move up" image. + * + * @param gc + * Graphics context. + * @param imgWidth + * Image width. + * @param imgHeight + * Image height. + */ + private void drawMoveUpImage(GC gc, int imgWidth, int imgHeight) { + gc.setAntialias(SWT.ON); + + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_BLACK)); + + // Draw the add arrow + int[] pointArray = new int[] { 1, 10, 6, 1, 11, 10, 1, 10 }; + gc.fillPolygon(pointArray); + } + + /** + * Draw the "move down" image. + * + * @param gc + * Graphics context. + * @param imgWidth + * Image width. + * @param imgHeight + * Image height. + */ + private void drawMoveDownImage(GC gc, int imgWidth, int imgHeight) { + gc.setAntialias(SWT.ON); + + gc.setBackground(parentDisplay.getSystemColor(SWT.COLOR_BLACK)); + + // Draw the add arrow + int[] pointArray = new int[] { 1, 1, 6, 10, 11, 1, 1, 1 }; + gc.fillPolygon(pointArray); + } + + /** + * Get the image associated with the specified button image. + * + * @param bi + * Button image identifier. + * @return The associated button image. + */ + public Image getImage(ButtonImage bi) { + return this.buttonArray[bi.ordinal()]; + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/DualList.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/DualList.java new file mode 100644 index 0000000000..cda0de1e9b --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/DualList.java @@ -0,0 +1,945 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.widgets.duallist; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashSet; +import java.util.Map; +import java.util.TreeMap; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.SelectionAdapter; +import org.eclipse.swt.events.SelectionEvent; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.List; + +import com.raytheon.viz.ui.widgets.duallist.ButtonImages.ButtonImage; + +/** + * SWT Dual List Widget. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Feb 13, 2012            mpduff      Initial creation
+ * Feb 14, 2012            lvenable    Update code.
+ * Aug 08, 2012    863     jpiatt      Added checks for selection changes.
+ * Aug 10, 2012   1002     mpduff      Fixed sorting of numeric data on move left.
+ * Sep 07, 2012    684     mpduff      Deselect selection prior to selecting new items.
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class DualList extends Composite { + + /** + * Available List widget + */ + private List availableList; + + /** + * Selected List Widget + */ + private List selectedList; + + /** + * Dual List data/configuration object + */ + private DualListConfig config = new DualListConfig(); + + /** + * Button to move an item from the left list to the right list. + */ + private Button moveRightBtn; + + /** + * Button to move all items from the left list to the right list. + */ + private Button moveAllRightBtn; + + /** + * Button to move an item from the right list to the left list. + */ + private Button moveLeftBtn; + + /** + * Button to move all items from the right list to the left list. + */ + private Button moveAllLeftBtn; + + /** + * Move a selected item in the selected list up in the list. + */ + private Button moveUpBtn; + + /** + * Move a selected item in the selected list down in the list. + */ + private Button moveDownBtn; + + /** + * Callback when data has been selected or unselected. + */ + private IUpdate updateCallback = null; + + /** + * Number of columns. + */ + private int numberOfColumns = 3; + + /** + * Button Images. + */ + private ButtonImages btnImg; + + /** + * Button Height. + */ + private int buttonHeight = SWT.DEFAULT; + + /** + * Button Width. + */ + private final int buttonWidth = 45; + + /** + * Move left flag. + */ + boolean moveLeft = false; + + /** + * Move All flag. + */ + boolean moveAllLeft = false; + + /** + * Constructor + * + * @param parent + * Parent container + * @param style + * SWT Style + * @param config + * Data/Configuration object + */ + public DualList(Composite parent, int style, DualListConfig config) { + this(parent, style, config, null); + } + + /** + * Constructor + * + * @param parent + * Parent container + * @param style + * SWT Style + * @param config + * Data/Configuration object + * @param cb + * Update Callback + * + */ + public DualList(Composite parent, int style, DualListConfig config, + IUpdate cb) { + super(parent, style); + this.config = config; + this.updateCallback = cb; + init(); + } + + /** + * Initialize the controls. + */ + private void init() { + // Create the button image class + btnImg = new ButtonImages(this); + + if (config.getListHeight() <= 90) { + buttonHeight = 20; + } + + // Determine how many columns need to be on the layout. + // The default is three. + if (config.isShowUpDownBtns()) { + numberOfColumns = 4; + } + + GridLayout gl = new GridLayout(numberOfColumns, false); + gl.marginWidth = 2; + gl.marginHeight = 2; + GridData gd = new GridData(SWT.FILL, SWT.FILL, true, true); + this.setLayout(gl); + this.setLayoutData(gd); + + createListLabels(); + createAvailableListControl(); + createAddRemoveControls(); + createSelectedListControl(); + + if (config.isShowUpDownBtns()) { + createMoveUpDownControls(); + } + + populateLists(); + } + + /** + * Create the labels that will appear above the list controls. + */ + private void createListLabels() { + // Available label + GridData gd = new GridData(SWT.FILL, SWT.DEFAULT, false, false); + gd.horizontalIndent = 3; + + Label availableLbl = new Label(this, SWT.NONE); + availableLbl.setText(config.getAvailableListText()); + availableLbl.setLayoutData(gd); + + new Label(this, SWT.NONE); + + // Selected label + gd = new GridData(SWT.DEFAULT, SWT.DEFAULT, false, false); + gd.horizontalIndent = 3; + + Label selectedLbl = new Label(this, SWT.NONE); + selectedLbl.setText(config.getSelectedListText()); + selectedLbl.setLayoutData(gd); + + if (numberOfColumns == 4) { + new Label(this, SWT.NONE); + } + + } + + /** + * Create the available list control. + */ + private void createAvailableListControl() { + + GridData listData = new GridData(SWT.FILL, SWT.FILL, true, true); + listData.widthHint = config.getListWidth(); + listData.heightHint = config.getListHeight(); + availableList = new List(this, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL + | SWT.H_SCROLL); + availableList.setLayoutData(listData); + availableList.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (availableList.getSelectionCount() > 0) { + moveRightBtn.setEnabled(true); + } else { + moveRightBtn.setEnabled(false); + } + } + }); + + availableList.addMouseListener(new MouseAdapter() { + @Override + public void mouseDown(MouseEvent arg0) { + if (arg0.button == 3) { + if (config.getMenuData() != null + && config.getMenuData().isShowMenu()) { + showAvailableListMenu(); + } + } + } + }); + } + + /** + * Create the add and remove controls. + */ + private void createAddRemoveControls() { + /* + * Add and Remove Buttons + */ + GridData selectData = new GridData(SWT.DEFAULT, SWT.CENTER, false, true); + GridLayout selectLayout = new GridLayout(1, false); + selectLayout.verticalSpacing = 2; + + Composite selectComp = new Composite(this, SWT.NONE); + selectComp.setLayout(selectLayout); + selectComp.setLayoutData(selectData); + + // Left/Right buttons + GridData btnData = new GridData(buttonWidth, buttonHeight); + + moveAllRightBtn = new Button(selectComp, SWT.PUSH); + moveAllRightBtn.setImage(btnImg.getImage(ButtonImage.AddAll)); + moveAllRightBtn.setLayoutData(btnData); + moveAllRightBtn.setEnabled(false); + moveAllRightBtn.setToolTipText("Move all items right"); + moveAllRightBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleMoveAllRight(); + if (updateCallback != null) { + updateCallback.selectionChanged(); + } + } + }); + + btnData = new GridData(buttonWidth, buttonHeight); + moveRightBtn = new Button(selectComp, SWT.PUSH); + moveRightBtn.setImage(btnImg.getImage(ButtonImage.Add)); + moveRightBtn.setLayoutData(btnData); + moveRightBtn.setEnabled(false); + moveRightBtn.setToolTipText("Move selected item(s) right"); + moveRightBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleMoveRight(); + if (updateCallback != null) { + updateCallback.selectionChanged(); + } + } + }); + + btnData = new GridData(buttonWidth, buttonHeight); + moveLeftBtn = new Button(selectComp, SWT.PUSH); + moveLeftBtn.setImage(btnImg.getImage(ButtonImage.Remove)); + moveLeftBtn.setLayoutData(btnData); + moveLeftBtn.setEnabled(false); + moveLeftBtn.setToolTipText("Move selected item(s) left"); + moveLeftBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleMoveLeft(); + if (updateCallback != null) { + updateCallback.selectionChanged(); + } + } + }); + + btnData = new GridData(buttonWidth, buttonHeight); + moveAllLeftBtn = new Button(selectComp, SWT.PUSH); + moveAllLeftBtn.setImage(btnImg.getImage(ButtonImage.RemoveAll)); + moveAllLeftBtn.setLayoutData(btnData); + moveAllLeftBtn.setEnabled(false); + moveAllLeftBtn.setToolTipText("Move all items left"); + moveAllLeftBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleMoveAllLeft(true); + if (updateCallback != null) { + updateCallback.selectionChanged(); + } + } + }); + } + + /** + * Create the selected list control. + */ + private void createSelectedListControl() { + GridData listData = new GridData(SWT.FILL, SWT.FILL, true, true); + listData.widthHint = config.getListWidth(); + listData.heightHint = config.getListHeight(); + + selectedList = new List(this, SWT.BORDER | SWT.MULTI | SWT.V_SCROLL + | SWT.H_SCROLL); + selectedList.setLayoutData(listData); + selectedList.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent e) { + if (selectedList.getSelectionCount() > 0) { + moveLeftBtn.setEnabled(true); + } else { + moveLeftBtn.setEnabled(false); + } + + enableDisableUpDownButtons(); + } + }); + + selectedList.addMouseListener(new MouseAdapter() { + @Override + public void mouseDown(MouseEvent arg0) { + if (arg0.button == 3) { + if (config.getMenuData() != null + && config.getMenuData().isShowMenu()) { + showSelectedListMenu(); + } + } + } + }); + + } + + /** + * Create the move up/down controls + */ + private void createMoveUpDownControls() { + + GridData actionData = new GridData(SWT.DEFAULT, SWT.CENTER, false, true); + GridLayout actionLayout = new GridLayout(1, false); + Composite actionComp = new Composite(this, SWT.NONE); + actionComp.setLayout(actionLayout); + actionComp.setLayoutData(actionData); + + GridData btnData = new GridData(buttonWidth, buttonHeight); + + moveUpBtn = new Button(actionComp, SWT.PUSH); + moveUpBtn.setImage(btnImg.getImage(ButtonImage.Up)); + moveUpBtn.setLayoutData(btnData); + moveUpBtn.setEnabled(false); + moveUpBtn.setToolTipText("Move item up in the list"); + moveUpBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleMoveUp(); + } + }); + + btnData = new GridData(buttonWidth, buttonHeight); + moveDownBtn = new Button(actionComp, SWT.PUSH); + moveDownBtn.setImage(btnImg.getImage(ButtonImage.Down)); + moveDownBtn.setLayoutData(btnData); + moveDownBtn.setEnabled(false); + moveDownBtn.setToolTipText("Move item down in the list"); + moveDownBtn.addSelectionListener(new SelectionAdapter() { + @Override + public void widgetSelected(SelectionEvent event) { + handleMoveDown(); + } + }); + } + + /** + * Set FullList. + * + * @param fullList + * all users listed in notification table + */ + public void setFullList(ArrayList fullList) { + config.setFullList(fullList); + populateLists(); + } + + /** + * Populate the available and selected list controls. + */ + private void populateLists() { + availableList.removeAll(); + selectedList.removeAll(); + + if (config.getFullList().size() == 0) { + return; + } + + if (config.getFullList() != null) { + for (String s : config.getFullList()) { + if (s == null) { + continue; + } + if (config.getSelectedList().contains(s) == false) { + availableList.add(s); + } + } + } + if (config.getSelectedList() != null) { + for (String s : config.getSelectedList()) { + selectedList.add(s); + } + } + + if (availableList.getItemCount() > 0) { + moveAllRightBtn.setEnabled(true); + } + + if (selectedList.getItemCount() > 0) { + moveAllLeftBtn.setEnabled(true); + } + + entriesUpdated(); + } + + /** + * Move down event handler + */ + private void handleMoveDown() { + if (selectedList.getSelectionCount() == 1 + && selectedList.getItemCount() > 1) { + int selectedIdx = selectedList.getSelectionIndex(); + String item = selectedList.getItem(selectedIdx); + + if (selectedIdx < selectedList.getItemCount() - 2) { + selectedList.remove(selectedIdx); + selectedList.add(item, selectedIdx + 1); + selectedList.select(selectedIdx + 1); + } else if (selectedIdx < selectedList.getItemCount() - 1) { + selectedList.remove(selectedIdx); + selectedList.add(item); + selectedList.select(selectedList.getItemCount() - 1); + } + enableDisableUpDownButtons(); + } + } + + /** + * Move left event handler + */ + private void handleMoveLeft() { + int[] selectionIndices = selectedList.getSelectionIndices(); + + moveLeft = true; + + if (selectionIndices.length == 0) { + return; + } + + int firstIndex = selectionIndices[0]; + + HashSet list = config.getIncludeList(); + + if (list.contains(selectedList.getItem(firstIndex))) { + + return; + } + + reloadAvailableList(); + + selectedList.remove(selectionIndices); + + if (selectedList.getItemCount() > 0) { + if (firstIndex < selectedList.getItemCount()) { + selectedList.setSelection(firstIndex); + } else { + selectedList.setSelection(selectedList.getItemCount() - 1); + } + } else { + moveLeftBtn.setEnabled(false); + } + + moveAllRightBtn.setEnabled(true); + + entriesUpdated(); + enableDisableUpDownButtons(); + } + + /** + * Move all left event handler + */ + private void handleMoveAllLeft(boolean callEntriesUpdated) { + + HashSet list = config.getIncludeList(); + moveAllLeft = true; + + for (String sl : selectedList.getItems()) { + + if (!list.contains(sl)) { + selectedList.remove(sl); + } + + } + + reloadAvailableList(); + moveLeftBtn.setEnabled(false); + moveAllLeftBtn.setEnabled(false); + moveAllRightBtn.setEnabled(true); + + if (callEntriesUpdated == true) { + entriesUpdated(); + } + + enableDisableUpDownButtons(); + } + + /** + * Move up event handler + */ + private void handleMoveUp() { + if (selectedList.getSelectionCount() == 1) { + int selectedIdx = selectedList.getSelectionIndex(); + String col = selectedList.getItem(selectedIdx); + + if (selectedIdx > 0) { + selectedList.remove(selectedIdx); + selectedList.add(col, selectedIdx - 1); + selectedList.select(selectedIdx - 1); + } + enableDisableUpDownButtons(); + } + } + + /** + * Move all right event handler + */ + private void handleMoveAllRight() { + String[] items = availableList.getItems(); + + if (items.length == 0) { + return; + } + + for (String item : items) { + selectedList.add(item); + } + + availableList.removeAll(); + moveRightBtn.setEnabled(false); + moveAllRightBtn.setEnabled(false); + moveAllLeftBtn.setEnabled(true); + + entriesUpdated(); + enableDisableUpDownButtons(); + } + + /** + * Move right event handler + */ + private void handleMoveRight() { + String[] items = availableList.getSelection(); + + if (items.length == 0) { + return; + } + + int firstIdxSelected = availableList.indexOf(items[0]); + + for (String item : items) { + selectedList.add(item); + } + + availableList.remove(availableList.getSelectionIndices()); + + if (availableList.getItemCount() == 0) { + moveRightBtn.setEnabled(false); + } else { + if (firstIdxSelected > availableList.getItemCount() - 1) { + availableList.select(availableList.getItemCount() - 1); + } else { + availableList.select(firstIdxSelected); + } + } + + moveAllLeftBtn.setEnabled(true); + + entriesUpdated(); + enableDisableUpDownButtons(); + } + + /** + * Convenience method to handle the enabling/disabling of the up and down + * buttons. This depends on how many items are in the list, how many items + * are selected, where the selected it is in the list. + */ + private void enableDisableUpDownButtons() { + // Return if the buttons are now even visible. + if (config.isShowUpDownBtns() == false) { + return; + } + + if (selectedList.getSelectionCount() > 1 + || selectedList.getSelectionCount() == 0) { + moveUpBtn.setEnabled(false); + moveDownBtn.setEnabled(false); + } else { + if (selectedList.getSelectionIndex() == 0 + || selectedList.getItemCount() == 0) { + moveUpBtn.setEnabled(false); + } else { + moveUpBtn.setEnabled(true); + } + + if (selectedList.getSelectionIndex() == selectedList.getItemCount() - 1 + || selectedList.getItemCount() == 0) { + moveDownBtn.setEnabled(false); + } else { + moveDownBtn.setEnabled(true); + } + } + } + + /** + * Reload the availableList data preserving the original order of the list. + */ + private void reloadAvailableList() { + + String[] selectedStrings = availableList.getSelection(); + ArrayList availableListNew = new ArrayList(); + String search = config.getSearchField(); + + String[] selectedItemArray = selectedList.getItems(); + ArrayList selectedItemList = new ArrayList(); + + for (String selectedItem : selectedItemArray) { + selectedItemList.add(selectedItem); + } + + // Check if search field text present + if (config.getSearchField() == null) { + + // If no search field text + if (moveAllLeft) { + + availableList.removeAll(); + + for (String s : config.getFullList()) { + if (!selectedItemList.contains(s)) { + availableList.add(s); + } + } + } else if (moveLeft) { + // Add selected item matching search field text to available + // list + for (String s : selectedList.getSelection()) { + availableList.add(s); + } + + // Sort the list(); + availableListNew = sortAvailable(availableList); + + availableList.removeAll(); + + for (String b : availableListNew) { + availableList.add(b); + } + + } + } else { + + if (moveAllLeft) { + + availableList.removeAll(); + + // Add all matching search field text to available list + for (String s : config.getFullList()) { + if (s.contains(search)) { + availableList.add(s); + } + } + + } else if (moveLeft) { + + // Add selected item matching search field text to available + // list + for (String s : selectedList.getSelection()) { + availableList.add(s); + } + + // Sort the list + availableListNew = sortAvailable(availableList); + + availableList.removeAll(); + + for (String b : availableListNew) { + availableList.add(b); + } + } + } + + moveAllLeft = false; + moveLeft = false; + + availableList.setSelection(selectedStrings); + } + + private void showAvailableListMenu() { + IMenuData menuData = config.getMenuData(); + if (menuData.isShowMenu() && availableList.getSelectionCount() > 0) { + menuData.setListSelection(availableList.getSelection()[0]); + menuData.showListMenu(getShell(), config.getMenuData() + .getMenuText()); + } + } + + private void showSelectedListMenu() { + IMenuData menuData = config.getMenuData(); + if (menuData.isShowMenu() && selectedList.getSelectionCount() > 0) { + menuData.setListSelection(selectedList.getSelection()[0]); + menuData.showListMenu(getShell(), config.getMenuData() + .getMenuText()); + } + } + + private ArrayList sortAvailable(List oldAvailableList) { + + ArrayList availableListsorted = new ArrayList(); + String[] arr = oldAvailableList.getItems(); + + // Put available list in order + if (config.isNumericData()) { + // If data are numeric then must sort on the numeric value + try { + Map map = new TreeMap(); + for (String a : arr) { + map.put(Integer.parseInt(a), a); + } + + for (Integer i : map.keySet()) { + availableListsorted.add(map.get(i)); + } + } catch (NumberFormatException e) { + // numeric data not all numeric, string sorting + availableListsorted = (ArrayList) Arrays.asList(arr); + Collections.sort(availableListsorted); + } + } else { + for (String a : arr) { + availableListsorted.add(a); + } + + Collections.sort(availableListsorted); + } + + return availableListsorted; + } + + /** + * Calls the callback method to notify something has changed. + */ + private void entriesUpdated() { + if (updateCallback != null) { + if (selectedList.getItemCount() == 0) { + updateCallback.hasEntries(false); + } else { + updateCallback.hasEntries(true); + } + } + } + + /** + * Clear all users. + */ + public void clearSelection() { + handleMoveAllLeft(false); + } + + /** + * Clear Available Users list. + * + * @param clearSelectionList + */ + public void clearAvailableList(boolean clearSelectionList) { + this.availableList.removeAll(); + + if (clearSelectionList == true) { + clearSelection(); + } + } + + /** + * Set the Available List items. + * + * @param items + * the list items. + */ + public void setAvailableItems(java.util.List items) { + this.availableList.setItems(items.toArray(new String[items.size()])); + } + + /** + * Get the number of items in the list. + * + * @return the number of items. + */ + public int getItemCount() { + return selectedList.getItemCount(); + } + + /** + * Get the Selected List items. + * + * @return the items in the selected list. + */ + public String[] getSelectedListItems() { + return selectedList.getItems(); + } + + /** + * Get the selection. + * + * @return the selections. + */ + public String[] getSelectedSelection() { + return selectedList.getSelection(); + } + + /** + * Get the configuration. + * + * @return items in available list. + */ + public String[] getAvailableListItems() { + return availableList.getItems(); + } + + /** + * Set the Selected List items. + * + * @param items + * the list items. + */ + public void setSelectedItems(String[] items) { + selectedList.setItems(items); + reloadAvailableList(); + } + + /** + * Selected User items. + * + * @param selection + * selected user items + */ + public void selectItems(String[] selection) { + availableList.deselectAll(); + int[] selectedIndices = new int[selection.length]; + for (int i = 0; i < selection.length; i++) { + selectedIndices[i] = availableList.indexOf(selection[i]); + } + + availableList.select(selectedIndices); + handleMoveRight(); + } + + /** + * Get the configuration. + * + * @return the configuration. + */ + public DualListConfig getConfig() { + return config; + } + + /** + * Set the configuration. + * + * @param config + * the configuration. + */ + public void setConfig(DualListConfig config) { + this.config = config; + } +} \ No newline at end of file diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/DualListConfig.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/DualListConfig.java new file mode 100644 index 0000000000..9f07b12469 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/DualListConfig.java @@ -0,0 +1,297 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.widgets.duallist; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + + +/** + * Config file for DualList class. Reused from Data Delivery. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 31, 2012            mpduff      Initial creation.
+ * Aug 10, 2012  1002      mpduff      Added numeric flag for sorting.
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class DualListConfig { + + /** + * Available list text set to a default. + */ + private String availableListText = "Available:"; + + /** + * Selected list text set to a default. + */ + private String selectedListText = "Selected:"; + + /** + * Width of the list controls. + */ + private int listWidth = 100; + + /** + * Height of the list controls. + */ + private int listHeight = 125; + + /** + * Flag to determine if the up/down buttons should be shown. + */ + private boolean showUpDownBtns = false; + + /** + * List of items that should initially appear in the selected item list. + */ + private List selectedList = new ArrayList(); + + /** + * Full list of available items. + */ + private List fullList = new ArrayList(); + + /** + * The list to include. + */ + private HashSet includeList = new HashSet(); + + /** + * The search field. + */ + private String searchField = null; + + private IMenuData menuData; + + /** Flag for numeric data */ + private boolean numericData = false; + + /** + * Constructor. + */ + public DualListConfig() { + + } + + /** + * Get the include list. + * + * @return the include list. + */ + public HashSet getIncludeList() { + return includeList; + } + + /** + * Set the include list. + * + * @param includeList + * List to always include. + */ + public void setIncludeList(HashSet includeList) { + this.includeList = includeList; + } + + /** + * Get the available list header text. + * + * @return Available list header text. + */ + public String getAvailableListText() { + return availableListText; + } + + /** + * Set the available list header text. + * + * @param availableListLabel + * Available list header text. + */ + public void setAvailableListLabel(String availableListLabel) { + this.availableListText = availableListLabel; + } + + /** + * Get the selected list header text. + * + * @return Selected list header text. + */ + public String getSelectedListText() { + return selectedListText; + } + + /** + * Set the selected list header text. + * + * @param selectedListLabel + * Selected list header text. + */ + public void setSelectedListLabel(String selectedListLabel) { + this.selectedListText = selectedListLabel; + } + + /** + * Get the list control width. + * + * @return The list width. + */ + public int getListWidth() { + return listWidth; + } + + /** + * Set the width of the list control. + * + * @param listWidth + * Width of the list control. + */ + public void setListWidth(int listWidth) { + this.listWidth = listWidth; + } + + /** + * Get the height of the list control. + * + * @return The height of the list control. + */ + public int getListHeight() { + return listHeight; + } + + /** + * Set the height of the list control. + * + * @param listHeight + * The height of the list control. + */ + public void setListHeight(int listHeight) { + this.listHeight = listHeight; + } + + /** + * Check if the up/down buttons should be shown. + * + * @return True if the buttons are shown, false if hidden. + */ + public boolean isShowUpDownBtns() { + return showUpDownBtns; + } + + /** + * Set the show up/down button flag. + * + * @param showUpDownBtns + * True to show the buttons, false to not show the buttons. + */ + public void setShowUpDownBtns(boolean showUpDownBtns) { + this.showUpDownBtns = showUpDownBtns; + } + + /** + * Get an array of selected items. + * + * @return An array of selected items. + */ + public List getSelectedList() { + return selectedList; + } + + /** + * Set the array of selected items. + * + * @param selectedList + * Array of selected items. + */ + public void setSelectedList(List selectedList) { + this.selectedList = selectedList; + } + + /** + * Get an array of all of the available items. + * + * @return The array of all available items. + */ + public List getFullList() { + return fullList; + } + + /** + * Set the array of all of the available items. + * + * @param fullList + * The array of all available items. + */ + public void setFullList(List fullList) { + this.fullList = fullList; + } + + /** + * Get the search field text. + * + * @return the String + * the search field text. + */ + public String getSearchField() { + return searchField; + } + + /** + * Set the search field text. + * + * @param searchField + * the search field text. + */ + public void setSearchField(String searchField) { + this.searchField = searchField; + } + + public IMenuData getMenuData() { + return menuData; + } + + public void setMenuData(IMenuData menuData) { + this.menuData = menuData; + } + + /** + * @param numericData the numericData to set + */ + public void setNumericData(boolean numericData) { + this.numericData = numericData; + } + + /** + * @return the numericData + */ + public boolean isNumericData() { + return numericData; + } +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/IMenuData.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/IMenuData.java new file mode 100644 index 0000000000..144db7f93f --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/IMenuData.java @@ -0,0 +1,72 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.widgets.duallist; + + +import org.eclipse.swt.widgets.Shell; + +/** + * Interface representing menu data. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jun 1, 2012            mpduff     Initial creation
+ * Nov 02, 2012 1302       djohnson  Add javadoc.
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public interface IMenuData { + /** + * Show a popup menu on the list right click + * + * @param shell The shell + * @param menuText The menu text + */ + public void showListMenu(Shell shell, String menuText); + + /** + * Show a popup menu. + * + * @return true to show menu, false to not show a menu + */ + public boolean isShowMenu(); + + /** + * Get the list menu text. + * + * @return the menu text + */ + public String getMenuText(); + + /** + * Set the list selection. + * + * @param string The selection + */ + public void setListSelection(String string); +} diff --git a/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/IUpdate.java b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/IUpdate.java new file mode 100644 index 0000000000..6fb307f825 --- /dev/null +++ b/cave/com.raytheon.viz.ui/src/com/raytheon/viz/ui/widgets/duallist/IUpdate.java @@ -0,0 +1,55 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.viz.ui.widgets.duallist; + +/** + * Interface for an update. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 31, 2012            mpduff     Initial creation.
+ * Aug 08, 2012    863     jpiatt     Added selectedChange method for clean & dirty checks.
+ * Nov 02, 2012 1302       djohnson   Add javadoc.
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public interface IUpdate { + /** + * Method called when a control has items or when the control becomes empty. + * + * @param entries + * Entries flag. True if there are entries, false if there are no + * entries. + */ + void hasEntries(boolean entries); + + /** + * Method called when a change in selection occurs. + */ + void selectionChanged(); +} diff --git a/cave/com.raytheon.viz.volumebrowser/META-INF/MANIFEST.MF b/cave/com.raytheon.viz.volumebrowser/META-INF/MANIFEST.MF index 4732311e55..6ceafd4e11 100644 --- a/cave/com.raytheon.viz.volumebrowser/META-INF/MANIFEST.MF +++ b/cave/com.raytheon.viz.volumebrowser/META-INF/MANIFEST.MF @@ -11,28 +11,27 @@ Require-Bundle: org.eclipse.ui, com.raytheon.viz.core, com.raytheon.viz.ui, com.raytheon.viz.pointdata, - com.raytheon.viz.core.graphing, com.raytheon.uf.viz.xy.crosssection, com.raytheon.uf.viz.xy.timeheight, com.raytheon.uf.viz.xy.varheight, com.raytheon.viz.skewt, com.raytheon.viz.redbook, com.raytheon.viz.awipstools, - com.raytheon.edex.common, com.raytheon.viz.grid, com.raytheon.viz.satellite, - com.raytheon.viz.lightning, com.raytheon.viz.radar, com.raytheon.uf.viz.d2d.ui, - org.geotools, com.raytheon.uf.viz.xy.timeseries, com.raytheon.uf.viz.xy, - javax.measure, com.raytheon.uf.viz.objectiveanalysis, com.raytheon.uf.common.pointdata, net.sf.swtaddons;bundle-version="1.0.0", com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", - com.raytheon.uf.viz.points;bundle-version="1.0.0" + com.raytheon.uf.viz.points;bundle-version="1.0.0", + com.raytheon.uf.viz.d2d.nsharp;bundle-version="1.0.0", + gov.noaa.nws.ncep.ui.nsharp;bundle-version="1.0.0", + com.raytheon.uf.common.message;bundle-version="1.12.1174", + com.raytheon.viz.core.graphing;bundle-version="1.12.1174" Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.viz.volumebrowser, com.raytheon.viz.volumebrowser.catalog, @@ -40,33 +39,14 @@ Export-Package: com.raytheon.viz.volumebrowser, com.raytheon.viz.volumebrowser.vbui, com.raytheon.viz.volumebrowser.xml Import-Package: com.raytheon.uf.common.comm, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.grib.util, + com.raytheon.uf.common.dataplugin.grid, + com.raytheon.uf.common.dataplugin.grid.dataset, com.raytheon.uf.common.dataplugin.level, - com.raytheon.uf.common.dataplugin.obs.metar, - com.raytheon.uf.common.derivparam.tree, - com.raytheon.uf.common.menus, + com.raytheon.uf.common.gridcoverage, com.raytheon.uf.common.menus.xml, - com.raytheon.uf.common.message.response, com.raytheon.uf.viz.core.maps.display, - com.raytheon.uf.viz.d2d.core, - com.raytheon.uf.viz.d2d.core.map, com.raytheon.uf.viz.d2d.core.time, - com.raytheon.uf.viz.d2d.nsharp.display, - com.raytheon.uf.viz.d2d.nsharp.rsc, - com.raytheon.uf.viz.d2d.ui, - com.raytheon.uf.viz.derivparam, com.raytheon.uf.viz.derivparam.inv, - com.raytheon.uf.viz.profiler, - com.raytheon.uf.viz.profiler.ui, - com.raytheon.uf.viz.sounding, - com.raytheon.uf.viz.ui.menus, - com.raytheon.uf.viz.ui.menus.widgets, com.raytheon.uf.viz.ui.menus.xml, - com.raytheon.uf.viz.xy, - com.raytheon.uf.viz.xy.varheight.hodo, - com.vividsolutions.jts.geom, - gov.noaa.nws.ncep.ui.nsharp.display, - gov.noaa.nws.ncep.viz.common.soundingQuery + com.vividsolutions.jts.geom Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/GridAlterBundleContributor.java b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/GridAlterBundleContributor.java index cda728f0a8..e7021d0c87 100644 --- a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/GridAlterBundleContributor.java +++ b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/GridAlterBundleContributor.java @@ -25,8 +25,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; @@ -83,13 +84,13 @@ public class GridAlterBundleContributor extends AlterBundleContributorAdapter { modelTitleToNameMap.put(source.getName(), source.getKey()); } else { - GridModel model = GribModelLookup.getInstance() - .getModelByName(source.getKey()); - if (model == null) { + DatasetInfo info = DatasetInfoLookup.getInstance() + .getInfo(source.getKey()); + if (info == null) { modelTitleToNameMap.put(source.getKey(), source.getKey()); } else { - modelTitleToNameMap.put(model.getTitle(), + modelTitleToNameMap.put(info.getTitle(), source.getKey()); } } @@ -120,24 +121,22 @@ public class GridAlterBundleContributor extends AlterBundleContributorAdapter { String selectedString) { Map reqMap = data.getMetadataMap(); if (selectedString != null) { - reqMap.put("modelInfo.modelName", new RequestConstraint( + reqMap.put(GridConstants.DATASET_ID, new RequestConstraint( selectedString)); + DatasetInfoLookup lookup = DatasetInfoLookup.getInstance(); // next, need to modify for other displays (not plan view) if (data instanceof VarHeightResourceData) { - GribModelLookup lookup = GribModelLookup.getInstance(); - ((VarHeightResourceData) data).setSource(lookup.getModelByName( + ((VarHeightResourceData) data).setSource(lookup.getInfo( selectedString).getTitle()); } else if (data instanceof TimeSeriesResourceData) { - GribModelLookup lookup = GribModelLookup.getInstance(); - ((TimeSeriesResourceData) data).setSource(lookup - .getModelByName(selectedString).getTitle()); + ((TimeSeriesResourceData) data).setSource(lookup.getInfo( + selectedString).getTitle()); } else if (data instanceof GribNSharpResourceData) { ((D2DNSharpResourceData) data).setSoundingType(selectedString); } else if (data instanceof CrossSectionResourceData) { - GribModelLookup lookup = GribModelLookup.getInstance(); - ((CrossSectionResourceData) data).setSource(lookup - .getModelByName(selectedString).getTitle()); + ((CrossSectionResourceData) data).setSource(lookup.getInfo( + selectedString).getTitle()); } } } diff --git a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/catalog/GridDataCatalog.java b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/catalog/GridDataCatalog.java index 66d2f6fd9e..200a5bc4c2 100644 --- a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/catalog/GridDataCatalog.java +++ b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/catalog/GridDataCatalog.java @@ -41,8 +41,9 @@ import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Label; import com.raytheon.uf.common.comm.CommunicationException; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; @@ -68,7 +69,7 @@ import com.raytheon.viz.grid.rsc.GridResourceData; * updating when only the model time * changes * Aug 27, 2008 1502 dglazesk Updated to use JAXB marshalling - * Switched to GridModel from plugin-grib + * Switched to DatasetInfo from plugin-grib * *
* @@ -99,7 +100,7 @@ public class GridDataCatalog implements IDataCatalog { private LevelSelectionListener levelListener; - private static final String PLUGIN = "grib"; + private static final String PLUGIN = GridConstants.GRID; public GridDataCatalog() { } @@ -128,7 +129,8 @@ public class GridDataCatalog implements IDataCatalog { public void initDataCatalog(Label label1, Label label2, Label label3, ListViewer list1, ListViewer list2, ListViewer list3, Button addButton) { - inventory = (GridInventory) DataCubeContainer.getInventory("grib"); + inventory = (GridInventory) DataCubeContainer + .getInventory(GridConstants.GRID); label1.setText("Model"); label2.setText("Parameter"); @@ -205,14 +207,13 @@ public class GridDataCatalog implements IDataCatalog { } private void populateModelList() { - ArrayList modelTimes = new ArrayList(); + ArrayList modelTimes = new ArrayList(); if (inventory == null) { - GridModel[] empty = new GridModel[1]; - empty[0] = new GridModel(); - empty[0].setGrid(-9999); + DatasetInfo[] empty = new DatasetInfo[1]; + empty[0] = new DatasetInfo(); list1.setInput(empty); } else { - GribModelLookup modelLookup = GribModelLookup.getInstance(); + DatasetInfoLookup modelLookup = DatasetInfoLookup.getInstance(); BlockingQueue returnQueue = new LinkedBlockingQueue(); try { @@ -221,19 +222,19 @@ public class GridDataCatalog implements IDataCatalog { e.printStackTrace(); } for (String modelName : returnQueue) { - GridModel theGribData = modelLookup.getModelByName(modelName); + DatasetInfo theGribData = modelLookup.getInfo(modelName); if (theGribData != null) { modelTimes.add(theGribData); } else { // TODO: generate false entry - theGribData = new GridModel(); - theGribData.setName(modelName); + theGribData = new DatasetInfo(); + theGribData.setDatasetId(modelName); } } if (modelTimes.size() > 0) { - this.list1.setInput(modelTimes.toArray(new GridModel[] {})); + this.list1.setInput(modelTimes.toArray(new DatasetInfo[] {})); } } } @@ -285,11 +286,10 @@ public class GridDataCatalog implements IDataCatalog { class ModelContentProvider implements IStructuredContentProvider { public Object[] getElements(Object inputElement) { - GridModel[] models = (GridModel[]) inputElement; + DatasetInfo[] models = (DatasetInfo[]) inputElement; String[] modelNames = new String[models.length]; for (int i = 0; i < models.length; i++) { - modelNames[i] = models[i].getTitle() + " (" - + models[i].getGrid() + ")"; + modelNames[i] = models[i].getTitle(); } return models; } @@ -335,12 +335,9 @@ public class GridDataCatalog implements IDataCatalog { @Override public String getText(Object element) { - GridModel model = (GridModel) element; + DatasetInfo model = (DatasetInfo) element; // return (String) element; - if (model.getGrid() == -9999) { - return "No Data Available"; - } - return model.getTitle() + " (Grid " + model.getGrid() + ")"; + return model.getTitle(); } } @@ -377,10 +374,11 @@ public class GridDataCatalog implements IDataCatalog { StructuredSelection selectedModel = (StructuredSelection) event .getSelection(); - GridModel modelInfo = (GridModel) selectedModel.getFirstElement(); - if (modelInfo != null && modelInfo.getName() != null - && !modelInfo.getName().equals(modelName)) { - modelName = modelInfo.getName(); + DatasetInfo modelInfo = (DatasetInfo) selectedModel + .getFirstElement(); + if (modelInfo != null && modelInfo.getDatasetId() != null + && !modelInfo.getDatasetId().equals(modelName)) { + modelName = modelInfo.getDatasetId(); addDataButton.setEnabled(false); populateModelParameters(); } @@ -419,18 +417,24 @@ public class GridDataCatalog implements IDataCatalog { */ public HashMap getProductParameters() { HashMap parameters = new HashMap(); - parameters.put("pluginName", new RequestConstraint(PLUGIN)); - parameters.put("modelInfo.modelName", new RequestConstraint(modelName)); - parameters.put("modelInfo.parameterAbbreviation", + parameters + .put(GridConstants.PLUGIN_NAME, new RequestConstraint(PLUGIN)); + parameters.put(GridConstants.DATASET_ID, new RequestConstraint( + modelName)); + parameters.put(GridConstants.PARAMETER_ABBREVIATION, new RequestConstraint(parameter)); Level level = this.levelList.get(this.level); - parameters.put("modelInfo.level.masterLevel.name", - new RequestConstraint(level.getMasterLevel().getName())); - parameters.put("modelInfo.level.levelonevalue", new RequestConstraint( - Double.toString(level.getLevelonevalue()))); - parameters.put("modelInfo.level.leveltwovalue", new RequestConstraint( - Double.toString(level.getLeveltwovalue()))); + parameters.put(GridConstants.MASTER_LEVEL_NAME, new RequestConstraint( + level.getMasterLevel().getName())); + parameters + .put(GridConstants.LEVEL_ONE, + new RequestConstraint(Double.toString(level + .getLevelonevalue()))); + parameters + .put(GridConstants.LEVEL_TWO, + new RequestConstraint(Double.toString(level + .getLeveltwovalue()))); return parameters; } diff --git a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/DataCatalogManager.java b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/DataCatalogManager.java index 58067b1525..30b8f89d4b 100644 --- a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/DataCatalogManager.java +++ b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/DataCatalogManager.java @@ -168,7 +168,7 @@ public class DataCatalogManager { private DataCatalogManager() { // TODO these should be read from an extension point. catalogs = new ArrayList(); - catalogs.add(new GribDataCatalog()); + catalogs.add(new GridDataCatalog()); catalogs.add(new AcarsSoundingDataCatalog()); catalogs.add(new DmdDataCatalog()); catalogs.add(new PointDataCatalog()); diff --git a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GribDataCatalog.java b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GridDataCatalog.java similarity index 72% rename from cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GribDataCatalog.java rename to cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GridDataCatalog.java index 1f3cff5acc..49db9b9853 100644 --- a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GribDataCatalog.java +++ b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GridDataCatalog.java @@ -35,11 +35,12 @@ import org.geotools.geometry.Envelope2D; import org.geotools.geometry.jts.ReferencedEnvelope; import org.opengis.referencing.operation.MathTransform; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -50,14 +51,12 @@ import com.raytheon.uf.viz.core.level.LevelMappingFactory; import com.raytheon.uf.viz.core.level.LevelUtilities; import com.raytheon.uf.viz.core.rsc.AbstractRequestableResourceData; import com.raytheon.uf.viz.core.rsc.DisplayType; -import com.raytheon.uf.viz.core.rsc.LoadProperties; import com.raytheon.uf.viz.core.rsc.ResourceType; import com.raytheon.uf.viz.d2d.nsharp.rsc.D2DNSharpResourceData; import com.raytheon.uf.viz.d2d.nsharp.rsc.GribNSharpResourceData; import com.raytheon.uf.viz.points.PointsDataManager; import com.raytheon.viz.awipstools.ToolsDataManager; import com.raytheon.viz.grid.inv.GridInventory; -import com.raytheon.viz.grid.rsc.GribSkewTLoadProperties; import com.raytheon.viz.grid.rsc.GridNameGenerator; import com.raytheon.viz.grid.rsc.GridResourceData; import com.raytheon.viz.grid.util.CoverageUtils; @@ -88,9 +87,9 @@ import com.vividsolutions.jts.geom.LineString; * @author lvenable * @version 1.0 */ -public class GribDataCatalog extends AbstractInventoryDataCatalog { +public class GridDataCatalog extends AbstractInventoryDataCatalog { private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(GribDataCatalog.class); + .getHandler(GridDataCatalog.class); /** * Create the product entry in the grid data catalog. @@ -106,7 +105,7 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { if (!isValidSelection(selData)) { return null; } - GribDataCatalogEntry catalogEntry = new GribDataCatalogEntry(selData); + GridDataCatalogEntry catalogEntry = new GridDataCatalogEntry(selData); catalogEntry.modelName = selData.getSourcesKey(); catalogEntry.paramAbbreviation = selData.getFieldsKey(); @@ -127,7 +126,7 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { public void addProductParameters(IDataCatalogEntry entry, HashMap parameters) { - GribDataCatalogEntry catalogEntry = (GribDataCatalogEntry) entry; + GridDataCatalogEntry catalogEntry = (GridDataCatalogEntry) entry; ViewMenu viewSelection = catalogEntry.getDialogSettings() .getViewSelection(); @@ -230,7 +229,7 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { // if we fail to get a unit from the style rules use the parameter unit if (displayUnit == null) { - GribDataCatalogEntry gribDataCatalogEntry = ((GribDataCatalogEntry) catalogEntry); + GridDataCatalogEntry gribDataCatalogEntry = ((GridDataCatalogEntry) catalogEntry); return getInventory().getParameterUnit( gribDataCatalogEntry.modelName, gribDataCatalogEntry.paramAbbreviation); @@ -240,31 +239,6 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { } - /* - * (non-Javadoc) - * - * @seecom.raytheon.viz.volumebrowser.datacatalog.AbstractDataCatalog# - * getLoadProperties - * (com.raytheon.viz.volumebrowser.datacatalog.IDataCatalogEntry, - * com.raytheon.uf.viz.core.rsc.ResourceType, - * com.raytheon.uf.viz.core.rsc.DisplayType) - */ - @Override - protected LoadProperties getLoadProperties( - IDataCatalogEntry dataCatalogEntry, ResourceType resourceType, - DisplayType displayType) { - - if (resourceType == ResourceType.SOUNDING) { - GribSkewTLoadProperties loadProperties = new GribSkewTLoadProperties(); - loadProperties.setPoint(dataCatalogEntry.getSelectedData() - .getPlanesKey().replace("Point", "")); - return loadProperties; - } else { - return super.getLoadProperties(dataCatalogEntry, resourceType, - displayType); - } - } - /* * (non-Javadoc) * @@ -274,7 +248,7 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { */ @Override protected String[] getPlugins(ViewMenu setting) { - return new String[] { "grib" }; + return new String[] { GridInventory.PLUGIN_NAME }; } @Override @@ -319,24 +293,25 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { DisplayType displayType) { Map metadataMap = getProductParameters(catalogEntry); - List perts = null; + List ensemebles = null; try { - perts = getGridInventory().getPerts(metadataMap); + ensemebles = getGridInventory().getEnsembles(metadataMap); } catch (VizException e) { statusHandler.handle(Priority.PROBLEM, "Error occured during perturbation query.", e); } - if (perts != null && perts.size() > 1) { + if (ensemebles != null && ensemebles.size() > 1) { + Collections.sort(ensemebles); Collection requests = new ArrayList(); - for (Integer pert : perts) { + for (String ensemble : ensemebles) { Collection origRequests = super .getResourcesToLoad(catalogEntry, resourceType, displayType); for (ResourcePair request : origRequests) { ((AbstractRequestableResourceData) request .getResourceData()).getMetadataMap().put( - "modelInfo.perturbationNumber", - new RequestConstraint(pert.toString())); + GridConstants.ENSEMBLE_ID, + new RequestConstraint(ensemble.toString())); requests.add(request); } } @@ -431,71 +406,65 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { && lons.isEmpty()) { return null; } - List sources = getSupportedSourcesInternal(); - Map coverages = new HashMap(); - try { - coverages = CoverageUtils.getInstance().getCoverages(sources); - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); - } Set fileredSources = new HashSet(); - for (String source : sources) { + for (String source : getSupportedSourcesInternal()) { try { - GridCoverage coverage = coverages.get(source); - if (coverage == null) { - coverage = CoverageUtils.getInstance().getCoverage(source); - } - if (coverage == null) { + Collection coverages = CoverageUtils + .getInstance().getCoverages(source); + if (coverages == null) { fileredSources.add(source); continue; } - GridGeometry2D gridGeom = coverage.getGridGeometry(); - MathTransform llToCRS = MapUtil.getTransformFromLatLon(gridGeom - .getCoordinateReferenceSystem()); - Envelope2D env = gridGeom.getEnvelope2D(); - for (String letter : pointLetters) { + for (GridCoverage coverage : coverages) { + GridGeometry2D gridGeom = coverage.getGridGeometry(); + MathTransform llToCRS = MapUtil + .getTransformFromLatLon(gridGeom + .getCoordinateReferenceSystem()); + Envelope2D env = gridGeom.getEnvelope2D(); + for (String letter : pointLetters) { Coordinate c = PointsDataManager.getInstance() .getCoordinate(letter); - DirectPosition2D dp = new DirectPosition2D(c.x, c.y); - llToCRS.transform(dp, dp); - if (env.contains(dp.x, dp.y)) { - fileredSources.add(source); - break; - } - } - for (String letter : lineLetters) { - LineString ls = ToolsDataManager.getInstance().getBaseline( - letter); - Envelope2D lineEnv = null; - for (Coordinate c : ls.getCoordinates()) { DirectPosition2D dp = new DirectPosition2D(c.x, c.y); llToCRS.transform(dp, dp); - if (lineEnv == null) { - lineEnv = new Envelope2D( - gridGeom.getCoordinateReferenceSystem(), - dp.x, dp.y, 1, 1); - } else { - lineEnv.add(dp.x, dp.y); + if (env.contains(dp.x, dp.y)) { + fileredSources.add(source); + break; } } - if (lineEnv.intersects(env)) { - fileredSources.add(source); - break; + for (String letter : lineLetters) { + LineString ls = ToolsDataManager.getInstance() + .getBaseline(letter); + Envelope2D lineEnv = null; + for (Coordinate c : ls.getCoordinates()) { + DirectPosition2D dp = new DirectPosition2D(c.x, c.y); + llToCRS.transform(dp, dp); + if (lineEnv == null) { + lineEnv = new Envelope2D( + gridGeom.getCoordinateReferenceSystem(), + dp.x, dp.y, 1, 1); + } else { + lineEnv.add(dp.x, dp.y); + } + } + if (lineEnv.intersects(env)) { + fileredSources.add(source); + break; + } } - } - ReferencedEnvelope rEnv = new ReferencedEnvelope(env, - gridGeom.getCoordinateReferenceSystem()); - rEnv = rEnv.transform(MapUtil.getLatLonProjection(), true); - for (Double lat : lats) { - if (rEnv.getMinY() < lat && rEnv.getMaxY() > lat) { - fileredSources.add(source); - break; + ReferencedEnvelope rEnv = new ReferencedEnvelope(env, + gridGeom.getCoordinateReferenceSystem()); + rEnv = rEnv.transform(MapUtil.getLatLonProjection(), true); + for (Double lat : lats) { + if (rEnv.getMinY() < lat && rEnv.getMaxY() > lat) { + fileredSources.add(source); + break; + } } - } - for (Double lon : lons) { - if (rEnv.getMinX() < lon && rEnv.getMaxX() > lon) { - fileredSources.add(source); - break; + for (Double lon : lons) { + if (rEnv.getMinX() < lon && rEnv.getMaxX() > lon) { + fileredSources.add(source); + break; + } } } } catch (Exception e) { @@ -521,75 +490,70 @@ public class GribDataCatalog extends AbstractInventoryDataCatalog { } ToolsDataManager tdm = ToolsDataManager.getInstance(); PointsDataManager pdm = PointsDataManager.getInstance(); - Map coverages = new HashMap(); - try { - coverages = CoverageUtils.getInstance().getCoverages(sources); - } catch (VizException e) { - statusHandler.handle(Priority.PROBLEM, e.getLocalizedMessage(), e); - } Set validPlanes = new HashSet(sources.size()); for (String source : sources) { try { - GridCoverage coverage = coverages.get(source); - if (coverage == null) { - coverage = CoverageUtils.getInstance().getCoverage(source); - } - if (coverage == null) { + Collection coverages = CoverageUtils + .getInstance().getCoverages(source); + if (coverages == null) { Set results = new HashSet(); results.addAll(MenuItemManager.getInstance() .getLatLonKeys()); results.addAll(getPointLineKeys()); return results; } - GridGeometry2D gridGeom = coverage.getGridGeometry(); - MathTransform llToCRS = MapUtil.getTransformFromLatLon(gridGeom - .getCoordinateReferenceSystem()); - Envelope2D env = gridGeom.getEnvelope2D(); + for (GridCoverage coverage : coverages) { + GridGeometry2D gridGeom = coverage.getGridGeometry(); + MathTransform llToCRS = MapUtil + .getTransformFromLatLon(gridGeom + .getCoordinateReferenceSystem()); + Envelope2D env = gridGeom.getEnvelope2D(); for (String letter : pdm.getPointNames()) { Coordinate c = pdm.getCoordinate(letter); - DirectPosition2D dp = new DirectPosition2D(c.x, c.y); - llToCRS.transform(dp, dp); - if (env.contains(dp.x, dp.y)) { - validPlanes.add("Point" + letter); - } - } - for (String letter : tdm.getBaselineNames()) { - LineString ls = tdm.getBaseline(letter); - Envelope2D lineEnv = null; - for (Coordinate c : ls.getCoordinates()) { DirectPosition2D dp = new DirectPosition2D(c.x, c.y); llToCRS.transform(dp, dp); - if (lineEnv == null) { - lineEnv = new Envelope2D( - gridGeom.getCoordinateReferenceSystem(), - dp.x, dp.y, 1, 1); + if (env.contains(dp.x, dp.y)) { + validPlanes.add("Point" + letter); + } + } + for (String letter : tdm.getBaselineNames()) { + LineString ls = tdm.getBaseline(letter); + Envelope2D lineEnv = null; + for (Coordinate c : ls.getCoordinates()) { + DirectPosition2D dp = new DirectPosition2D(c.x, c.y); + llToCRS.transform(dp, dp); + if (lineEnv == null) { + lineEnv = new Envelope2D( + gridGeom.getCoordinateReferenceSystem(), + dp.x, dp.y, 1, 1); + } else { + lineEnv.add(dp.x, dp.y); + } + } + if (lineEnv.intersects(env)) { + validPlanes.add("Line" + letter); + } + } + ReferencedEnvelope rEnv = new ReferencedEnvelope(env, + gridGeom.getCoordinateReferenceSystem()); + rEnv = rEnv.transform(MapUtil.getLatLonProjection(), true); + for (String llKey : MenuItemManager.getInstance() + .getLatLonKeys()) { + if (llKey.startsWith("Lat")) { + double lat = Double.parseDouble(llKey.replace( + "Lat", "")); + if (rEnv.getMinY() < lat && rEnv.getMaxY() > lat) { + validPlanes.add(llKey); + } + } else if (llKey.startsWith("Lon")) { + double lon = Double.parseDouble(llKey.replace( + "Lon", "")); + if (rEnv.getMinX() < lon && rEnv.getMaxX() > lon) { + validPlanes.add(llKey); + } } else { - lineEnv.add(dp.x, dp.y); - } - } - if (lineEnv.intersects(env)) { - validPlanes.add("Line" + letter); - } - } - ReferencedEnvelope rEnv = new ReferencedEnvelope(env, - gridGeom.getCoordinateReferenceSystem()); - rEnv = rEnv.transform(MapUtil.getLatLonProjection(), true); - for (String llKey : MenuItemManager.getInstance() - .getLatLonKeys()) { - if (llKey.startsWith("Lat")) { - double lat = Double.parseDouble(llKey - .replace("Lat", "")); - if (rEnv.getMinY() < lat && rEnv.getMaxY() > lat) { validPlanes.add(llKey); } - } else if (llKey.startsWith("Lon")) { - double lon = Double.parseDouble(llKey - .replace("Lon", "")); - if (rEnv.getMinX() < lon && rEnv.getMaxX() > lon) { - validPlanes.add(llKey); - } - } else { - validPlanes.add(llKey); } } } catch (Exception e) { diff --git a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GribDataCatalogEntry.java b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GridDataCatalogEntry.java similarity index 76% rename from cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GribDataCatalogEntry.java rename to cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GridDataCatalogEntry.java index 7b4efd4b13..6f9f9bd8c9 100644 --- a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GribDataCatalogEntry.java +++ b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/datacatalog/GridDataCatalogEntry.java @@ -25,14 +25,30 @@ import java.util.Map; import com.raytheon.uf.viz.core.rsc.DisplayType; import com.raytheon.viz.volumebrowser.vbui.SelectedData; -public class GribDataCatalogEntry extends DataCatalogEntry { +/** + * + * A DataCatologEntry which stores some extra grid specific fields. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 25, 2012            bsteffen     Initial javadoc
+ * 
+ * 
+ * + * @version 1.0 + */ +public class GridDataCatalogEntry extends DataCatalogEntry { - public GribDataCatalogEntry(SelectedData selData) { + public GridDataCatalogEntry(SelectedData selData) { super(selData); this.nameMap = new HashMap(); } - public GribDataCatalogEntry(GribDataCatalogEntry entry) { + public GridDataCatalogEntry(GridDataCatalogEntry entry) { super(entry); this.nameMap = entry.nameMap; this.modelName = entry.modelName; diff --git a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/vbui/DataListsProdTableComp.java b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/vbui/DataListsProdTableComp.java index 22f870035f..9377500140 100644 --- a/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/vbui/DataListsProdTableComp.java +++ b/cave/com.raytheon.viz.volumebrowser/src/com/raytheon/viz/volumebrowser/vbui/DataListsProdTableComp.java @@ -48,8 +48,8 @@ import org.eclipse.swt.widgets.Combo; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Label; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -671,10 +671,10 @@ public class DataListsProdTableComp extends Composite implements mContrib.xml.menuText = source.getName(); } else { // Attempt a lookup in the grib model table - GridModel model = GribModelLookup.getInstance() - .getModelByName(source.getKey()); - if (model != null) { - mContrib.xml.menuText = model.getTitle(); + DatasetInfo info = DatasetInfoLookup.getInstance().getInfo( + source.getKey()); + if (info != null) { + mContrib.xml.menuText = info.getTitle(); } else { mContrib.xml.menuText = source.getKey(); } diff --git a/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/gui/WarngenLayer.java b/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/gui/WarngenLayer.java index 1ce3e3d2da..2dd146da63 100644 --- a/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/gui/WarngenLayer.java +++ b/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/gui/WarngenLayer.java @@ -143,7 +143,6 @@ import com.vividsolutions.jts.io.WKTReader; * 11/02/2012 DR 15455 Qinglu Lin Added setWarningAction(), called redrawBoxFromTrack() while * warningAction is neither null nor WarningAction.NEW, removed * some code from redrawBoxFromHatched(). - * 11/15/2012 DR 15430 D. Friedman Use correct county/zone in createGeometryForWatches. * *
* @@ -976,7 +975,7 @@ public class WarngenLayer extends AbstractStormTrackResource { Geometry area = buildArea(polygon); for (ActiveTableRecord activeTableRecord : records) { Map countyMap = FipsUtil - .parseCountyHeader(activeTableRecord.getUgcZone()); + .parseCountyHeader(activeTableRecord.getCountyheader()); // get area with precalculated area activeTableRecord.setGeometry(getArea(area, countyMap)); } diff --git a/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/template/TemplateRunner.java b/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/template/TemplateRunner.java index 7e60b53a88..d56029b705 100644 --- a/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/template/TemplateRunner.java +++ b/cave/com.raytheon.viz.warngen/src/com/raytheon/viz/warngen/template/TemplateRunner.java @@ -921,7 +921,10 @@ public class TemplateRunner { System.out.println("getWatches.createWatchGeometry time: " + (t1 - t0)); + t0 = System.currentTimeMillis(); rval = processATEntries(activeTable, warngenLayer); + System.out.println("getWatches.createPoritions time: " + + (t1 - t0)); } } @@ -1004,10 +1007,6 @@ public class TemplateRunner { if (!ar.getGeometry().isEmpty()) work.valid = true; - /* TODO: Currently adding all zones to the list even if they - * are not in the CWA. Validation is currently done in - * determineAffectedPortions to avoid redundant work. - */ work.ugcZone.add(ar.getUgcZone()); } @@ -1018,7 +1017,7 @@ public class TemplateRunner { */ if (!work.valid) continue; - if (determineAffectedPortions(work.ugcZone, asc, geoData, work.waw)) + if (determineAffectedPortions(work.ugcZone, asc, geoData, work.waw)); rval.addWaw(work.waw); } @@ -1027,8 +1026,7 @@ public class TemplateRunner { /** * Given the list of counties in a watch, fill out the "portions" part of - * the given WeatherAdvisoryWatch. Also checks if the given counties are - * actually in the CWA. + * the given WeatherAdvisoryWatch * * @param ugcs * @param asc @@ -1043,36 +1041,25 @@ public class TemplateRunner { HashMap> map = new HashMap>(); for (String ugc : ugcs) { - Map parsed = FipsUtil.parseCountyHeader(ugc); - Entry e = null; - - // Either zero or more than one sates/counties would be wrong - if (parsed.size() != 1 - || (e = parsed.entrySet().iterator().next()).getValue().length != 1) { - statusHandler.handle(Priority.ERROR, - "Invalid ugczone in active table entry: " + ugc); - continue; + for (Entry e : FipsUtil.parseCountyHeader(ugc).entrySet()) { + String stateAbbrev = e.getKey(); + if (e.getValue().length != 1) // either zero or more than one + // would be wrong + statusHandler.handle(Priority.ERROR, + "Invalid ugczone in active table entry"); + Set feAreas = map.get(stateAbbrev); + if (feAreas == null) { + feAreas = new HashSet(); + map.put(stateAbbrev, feAreas); + } + try { + feAreas.add(getFeArea(stateAbbrev, e.getValue()[0], asc, + geoData)); + } catch (RuntimeException exc) { + statusHandler.handle(Priority.ERROR, "Error generating included watches.", exc); + return false; + } } - - String stateAbbrev = e.getKey(); - String feArea = null; - try { - feArea = getFeArea(stateAbbrev, e.getValue()[0], asc, - geoData); - } catch (RuntimeException exc) { - statusHandler.handle(Priority.ERROR, "Error generating included watches.", exc); - return false; - } - if (feArea == NOT_IN_CWA) - continue; - - Set feAreas = map.get(stateAbbrev); - if (feAreas == null) { - feAreas = new HashSet(); - map.put(stateAbbrev, feAreas); - } - if (feArea != null) - feAreas.add(feArea); } ArrayList portions = new ArrayList(map.size()); @@ -1087,6 +1074,8 @@ public class TemplateRunner { } portion.partOfParentRegion = Area .converFeAreaToPartList(mungeFeAreas(e.getValue())); + System.out.format("Munged %s to %s (%s)\n", e.getValue(), + mungeFeAreas(e.getValue()), portion.partOfParentRegion); portions.add(portion); } waw.setPortions(portions); @@ -1207,17 +1196,7 @@ public class TemplateRunner { } return null; } - - private static String NOT_IN_CWA = new String("NOT_IN_CWA"); - /** Determines if the given UGC is in the CWA and if it is, returns - * the portion of the CWA. - * @param stateAbbrev - * @param ugc - * @param asc - * @param geoData - * @return - */ private static String getFeArea(String stateAbbrev, String ugc, AreaSourceConfiguration asc, GeospatialData[] geoData) { for (GeospatialData g : geoData) { @@ -1227,8 +1206,7 @@ public class TemplateRunner { return (String) g.attributes.get(asc.getFeAreaField()); } - // TODO: Is this the correct way to determine if the county is in the CWA? - return NOT_IN_CWA; + return null; } } diff --git a/cave/ohd.hseb.common/externaljars/jdom.jar b/cave/ohd.hseb.common/externaljars/jdom.jar index 6d04bac92f..288e64cb5c 100755 Binary files a/cave/ohd.hseb.common/externaljars/jdom.jar and b/cave/ohd.hseb.common/externaljars/jdom.jar differ diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java index 3b53a81afc..e556764351 100644 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java +++ b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLDecoder.java @@ -33,6 +33,7 @@ import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; +import org.jdom.output.Format; import org.jdom.output.XMLOutputter; @@ -539,14 +540,13 @@ public class SacXMLDecoder public String toString() { StringWriter stringWriter = new StringWriter(); - XMLOutputter outputter = new XMLOutputter(); + Format format = Format.getPrettyFormat(); + format = format.setIndent(" "); + XMLOutputter outputter = new XMLOutputter(format); String returnValue = null; try { - outputter.setTextTrim( true ); - outputter.setIndent( " " ); - outputter.setNewlines( true ); outputter.output( _doc, stringWriter ); returnValue = stringWriter.toString(); } diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java index 412dc41973..329605160f 100644 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java +++ b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLEncoder.java @@ -30,6 +30,7 @@ import ohd.hseb.util.StringParser; import org.jdom.Document; import org.jdom.Element; +import org.jdom.output.Format; import org.jdom.output.XMLOutputter; public class SacXMLEncoder @@ -552,7 +553,9 @@ public class SacXMLEncoder private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) { - XMLOutputter _xmlOutputter = new XMLOutputter(" ", true); + Format format = Format.getRawFormat(); + format.setIndent(" "); + XMLOutputter _xmlOutputter = new XMLOutputter(format); try { diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java index 62994deaca..ae2616b90b 100644 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java +++ b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SacXMLTester.java @@ -33,8 +33,9 @@ import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; +import org.jdom.output.Format.TextMode; import org.jdom.output.XMLOutputter; - +import org.jdom.output.Format; public class SacXMLTester { @@ -473,14 +474,13 @@ public class SacXMLTester public String toString() { StringWriter stringWriter = new StringWriter(); - XMLOutputter outputter = new XMLOutputter(); + Format format = Format.getPrettyFormat(); + format = format.setIndent(" "); + XMLOutputter outputter = new XMLOutputter(format); String returnValue = null; try { - outputter.setTextTrim( true ); - outputter.setIndent( " " ); - outputter.setNewlines( true ); outputter.output( _inputXMLDoc, stringWriter ); returnValue = stringWriter.toString(); } @@ -494,7 +494,9 @@ public class SacXMLTester private void writeXmlToFile(Document outputXmlDoc, String xmlFileName) { - XMLOutputter _xmlOutputter = new XMLOutputter(" ", true); + Format format = Format.getRawFormat(); + format.setIndent(" "); + XMLOutputter _xmlOutputter = new XMLOutputter(format); try { diff --git a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java index 87257d166b..3c8505738f 100644 --- a/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java +++ b/cave/ohd.hseb.sshp/src/ohd/hseb/sshp/messaging/SshpDataTransferMgr.java @@ -20,6 +20,7 @@ import org.jdom.Document; import org.jdom.Element; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; +import org.jdom.output.Format; import org.jdom.output.XMLOutputter; /** @@ -37,7 +38,7 @@ public class SshpDataTransferMgr private Document _controlDoc = null; private SAXBuilder _builder = new SAXBuilder(); - private XMLOutputter _xmlOutputter = new XMLOutputter(" ", true); + private XMLOutputter _xmlOutputter = null; private FileLogger _logger = null; private String _logFilePath = null; @@ -59,6 +60,10 @@ public class SshpDataTransferMgr _logger = new FileLogger(_logFilePath); + Format format = Format.getRawFormat(); + format.setIndent(" "); + this._xmlOutputter = new XMLOutputter(format); + loadControlFile(); return; diff --git a/cots/org.apache.activemq/.classpath b/cots/org.apache.activemq/.classpath index f594bcce8a..3fe6933ba5 100644 --- a/cots/org.apache.activemq/.classpath +++ b/cots/org.apache.activemq/.classpath @@ -8,7 +8,7 @@ - + diff --git a/cots/org.apache.commons.cxf/.classpath b/cots/org.apache.commons.cxf/.classpath new file mode 100644 index 0000000000..b7367d18f3 --- /dev/null +++ b/cots/org.apache.commons.cxf/.classpath @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/cots/org.springframework.dm/.project b/cots/org.apache.commons.cxf/.project similarity index 94% rename from cots/org.springframework.dm/.project rename to cots/org.apache.commons.cxf/.project index 4b0e634a65..dd2a3a9a91 100644 --- a/cots/org.springframework.dm/.project +++ b/cots/org.apache.commons.cxf/.project @@ -1,6 +1,6 @@ - org.springframework.dm + org.apache.commons.cxf diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/.settings/org.eclipse.jdt.core.prefs b/cots/org.apache.commons.cxf/.settings/org.eclipse.jdt.core.prefs similarity index 75% rename from cave/com.raytheon.uf.viz.datastorage.remote/.settings/org.eclipse.jdt.core.prefs rename to cots/org.apache.commons.cxf/.settings/org.eclipse.jdt.core.prefs index abdea984c3..53d69eaa31 100644 --- a/cave/com.raytheon.uf.viz.datastorage.remote/.settings/org.eclipse.jdt.core.prefs +++ b/cots/org.apache.commons.cxf/.settings/org.eclipse.jdt.core.prefs @@ -1,5 +1,6 @@ -#Mon Aug 03 13:10:34 CDT 2009 +#Tue Jan 24 11:51:33 CST 2012 eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error diff --git a/cots/org.apache.commons.cxf/FastInfoset-1.2.9.jar b/cots/org.apache.commons.cxf/FastInfoset-1.2.9.jar new file mode 100644 index 0000000000..93454a065e Binary files /dev/null and b/cots/org.apache.commons.cxf/FastInfoset-1.2.9.jar differ diff --git a/cots/org.apache.commons.cxf/META-INF/MANIFEST.MF b/cots/org.apache.commons.cxf/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..f04902caff --- /dev/null +++ b/cots/org.apache.commons.cxf/META-INF/MANIFEST.MF @@ -0,0 +1,67 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Cxf +Bundle-SymbolicName: org.apache.commons.cxf +Bundle-Version: 1.0.0.qualifier +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-ClassPath: cxf-2.5.0.jar, + FastInfoset-1.2.9.jar, + geronimo-activation_1.1_spec-1.1.jar, + geronimo-annotation_1.0_spec-1.1.1.jar, + geronimo-servlet_2.5_spec-1.1.2.jar, + geronimo-stax-api_1.0_spec-1.0.1.jar, + jsr311-api-1.1.1.jar, + neethi-3.0.1.jar, + stax2-api-3.1.1.jar, + woodstox-core-asl-4.1.1.jar, + wsdl4j-1.6.2.jar, + xml-resolver-1.2.jar, + xmlbeans-2.4.0.jar, + xmlschema-core-2.0.1.jar, + xmlsec-1.4.5.jar, + xmltooling-1.3.2-1.jar, + . +Export-Package: javax.servlet, + javax.servlet.http, + javax.ws.rs, + org.apache.cxf.binding.soap, + org.apache.cxf.binding.soap.blueprint, + org.apache.cxf.binding.soap.interceptor, + org.apache.cxf.binding.soap.jms.interceptor, + org.apache.cxf.binding.soap.model, + org.apache.cxf.binding.soap.saaj, + org.apache.cxf.binding.soap.spring, + org.apache.cxf.binding.soap.tcp, + org.apache.cxf.binding.soap.tcp.frames, + org.apache.cxf.binding.soap.wsdl11, + org.apache.cxf.databinding, + org.apache.cxf.helpers, + org.apache.cxf.interceptor, + org.apache.cxf.jaxrs.ext.xml, + org.apache.cxf.message, + org.apache.cxf.phase, + org.apache.cxf.service, + org.apache.cxf.service.model, + org.apache.cxf.staxutils, + org.opensaml.xml, + org.opensaml.xml.encryption, + org.opensaml.xml.encryption.impl, + org.opensaml.xml.encryption.validator, + org.opensaml.xml.io, + org.opensaml.xml.parse, + org.opensaml.xml.schema, + org.opensaml.xml.schema.impl, + org.opensaml.xml.schema.validator, + org.opensaml.xml.security, + org.opensaml.xml.security.credential, + org.opensaml.xml.security.credential.criteria, + org.opensaml.xml.security.criteria, + org.opensaml.xml.security.keyinfo, + org.opensaml.xml.security.keyinfo.provider, + org.opensaml.xml.security.trust, + org.opensaml.xml.security.x509, + org.opensaml.xml.signature, + org.opensaml.xml.signature.impl, + org.opensaml.xml.signature.validator, + org.opensaml.xml.util, + org.opensaml.xml.validation diff --git a/cots/org.apache.commons.cxf/build.properties b/cots/org.apache.commons.cxf/build.properties new file mode 100644 index 0000000000..d6fca503ad --- /dev/null +++ b/cots/org.apache.commons.cxf/build.properties @@ -0,0 +1,19 @@ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + cxf-2.5.0.jar,\ + FastInfoset-1.2.9.jar,\ + geronimo-activation_1.1_spec-1.1.jar,\ + geronimo-annotation_1.0_spec-1.1.1.jar,\ + geronimo-servlet_2.5_spec-1.1.2.jar,\ + geronimo-stax-api_1.0_spec-1.0.1.jar,\ + jsr311-api-1.1.1.jar,\ + neethi-3.0.1.jar,\ + stax2-api-3.1.1.jar,\ + woodstox-core-asl-4.1.1.jar,\ + wsdl4j-1.6.2.jar,\ + xml-resolver-1.2.jar,\ + xmlbeans-2.4.0.jar,\ + xmlschema-core-2.0.1.jar,\ + xmlsec-1.4.5.jar,\ + xmltooling-1.3.2-1.jar diff --git a/cots/org.apache.commons.cxf/cxf-2.5.0.jar b/cots/org.apache.commons.cxf/cxf-2.5.0.jar new file mode 100644 index 0000000000..1769b54f57 Binary files /dev/null and b/cots/org.apache.commons.cxf/cxf-2.5.0.jar differ diff --git a/cots/org.apache.commons.cxf/geronimo-activation_1.1_spec-1.1.jar b/cots/org.apache.commons.cxf/geronimo-activation_1.1_spec-1.1.jar new file mode 100644 index 0000000000..366494189a Binary files /dev/null and b/cots/org.apache.commons.cxf/geronimo-activation_1.1_spec-1.1.jar differ diff --git a/cots/org.apache.commons.cxf/geronimo-annotation_1.0_spec-1.1.1.jar b/cots/org.apache.commons.cxf/geronimo-annotation_1.0_spec-1.1.1.jar new file mode 100644 index 0000000000..2cdc01be7a Binary files /dev/null and b/cots/org.apache.commons.cxf/geronimo-annotation_1.0_spec-1.1.1.jar differ diff --git a/cots/org.apache.commons.cxf/geronimo-servlet_2.5_spec-1.1.2.jar b/cots/org.apache.commons.cxf/geronimo-servlet_2.5_spec-1.1.2.jar new file mode 100644 index 0000000000..94733327f2 Binary files /dev/null and b/cots/org.apache.commons.cxf/geronimo-servlet_2.5_spec-1.1.2.jar differ diff --git a/cots/org.apache.commons.cxf/geronimo-stax-api_1.0_spec-1.0.1.jar b/cots/org.apache.commons.cxf/geronimo-stax-api_1.0_spec-1.0.1.jar new file mode 100644 index 0000000000..ab1ee3ba60 Binary files /dev/null and b/cots/org.apache.commons.cxf/geronimo-stax-api_1.0_spec-1.0.1.jar differ diff --git a/cots/org.apache.commons.cxf/jsr311-api-1.1.1.jar b/cots/org.apache.commons.cxf/jsr311-api-1.1.1.jar new file mode 100644 index 0000000000..ec8bc81854 Binary files /dev/null and b/cots/org.apache.commons.cxf/jsr311-api-1.1.1.jar differ diff --git a/cots/org.apache.commons.cxf/neethi-3.0.1.jar b/cots/org.apache.commons.cxf/neethi-3.0.1.jar new file mode 100644 index 0000000000..a6c1b1a943 Binary files /dev/null and b/cots/org.apache.commons.cxf/neethi-3.0.1.jar differ diff --git a/cots/org.apache.commons.cxf/stax2-api-3.1.1.jar b/cots/org.apache.commons.cxf/stax2-api-3.1.1.jar new file mode 100644 index 0000000000..63a8a06467 Binary files /dev/null and b/cots/org.apache.commons.cxf/stax2-api-3.1.1.jar differ diff --git a/cots/org.apache.commons.cxf/woodstox-core-asl-4.1.1.jar b/cots/org.apache.commons.cxf/woodstox-core-asl-4.1.1.jar new file mode 100644 index 0000000000..dfc651d280 Binary files /dev/null and b/cots/org.apache.commons.cxf/woodstox-core-asl-4.1.1.jar differ diff --git a/cots/org.apache.commons.cxf/wsdl4j-1.6.2.jar b/cots/org.apache.commons.cxf/wsdl4j-1.6.2.jar new file mode 100644 index 0000000000..b9ffc36b9f Binary files /dev/null and b/cots/org.apache.commons.cxf/wsdl4j-1.6.2.jar differ diff --git a/cots/org.apache.commons.cxf/xml-resolver-1.2.jar b/cots/org.apache.commons.cxf/xml-resolver-1.2.jar new file mode 100644 index 0000000000..e535bdc073 Binary files /dev/null and b/cots/org.apache.commons.cxf/xml-resolver-1.2.jar differ diff --git a/cots/org.apache.commons.cxf/xmlbeans-2.4.0.jar b/cots/org.apache.commons.cxf/xmlbeans-2.4.0.jar new file mode 100644 index 0000000000..5f1016c1b3 Binary files /dev/null and b/cots/org.apache.commons.cxf/xmlbeans-2.4.0.jar differ diff --git a/cots/org.apache.commons.cxf/xmlschema-core-2.0.1.jar b/cots/org.apache.commons.cxf/xmlschema-core-2.0.1.jar new file mode 100644 index 0000000000..bd1cdda420 Binary files /dev/null and b/cots/org.apache.commons.cxf/xmlschema-core-2.0.1.jar differ diff --git a/cots/org.apache.commons.cxf/xmlsec-1.4.5.jar b/cots/org.apache.commons.cxf/xmlsec-1.4.5.jar new file mode 100644 index 0000000000..ac432baae4 Binary files /dev/null and b/cots/org.apache.commons.cxf/xmlsec-1.4.5.jar differ diff --git a/cots/org.apache.commons.cxf/xmltooling-1.3.2-1.jar b/cots/org.apache.commons.cxf/xmltooling-1.3.2-1.jar new file mode 100644 index 0000000000..8de8076bec Binary files /dev/null and b/cots/org.apache.commons.cxf/xmltooling-1.3.2-1.jar differ diff --git a/cots/org.apache.ws.security/.classpath b/cots/org.apache.ws.security/.classpath new file mode 100644 index 0000000000..9e4f48374a --- /dev/null +++ b/cots/org.apache.ws.security/.classpath @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/.project b/cots/org.apache.ws.security/.project similarity index 91% rename from edexOsgi/com.raytheon.uf.common.datastorage.remote/.project rename to cots/org.apache.ws.security/.project index b14433e2ca..a941433317 100644 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/.project +++ b/cots/org.apache.ws.security/.project @@ -1,6 +1,6 @@ - com.raytheon.uf.common.datastorage.remote + org.apache.ws.security diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/.settings/org.eclipse.jdt.core.prefs b/cots/org.apache.ws.security/.settings/org.eclipse.jdt.core.prefs similarity index 75% rename from edexOsgi/com.raytheon.uf.common.datastorage.remote/.settings/org.eclipse.jdt.core.prefs rename to cots/org.apache.ws.security/.settings/org.eclipse.jdt.core.prefs index b938cd0361..c143988cc0 100644 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/.settings/org.eclipse.jdt.core.prefs +++ b/cots/org.apache.ws.security/.settings/org.eclipse.jdt.core.prefs @@ -1,5 +1,6 @@ -#Fri Jul 31 08:04:53 CDT 2009 +#Thu Jul 19 11:13:44 CDT 2012 eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error diff --git a/cots/org.apache.ws.security/META-INF/MANIFEST.MF b/cots/org.apache.ws.security/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..127ebcf007 --- /dev/null +++ b/cots/org.apache.ws.security/META-INF/MANIFEST.MF @@ -0,0 +1,334 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Security +Bundle-SymbolicName: org.apache.ws.security +Bundle-Version: 1.0.0.qualifier +Bundle-Activator: org.apache.ws.security.Activator +Require-Bundle: org.eclipse.core.runtime, + org.apache.commons.logging;bundle-version="1.1.1", + org.junit;bundle-version="1.0.0", + org.apache.log4j;bundle-version="1.0.0", + org.slf4j;bundle-version="1.6.1" +Bundle-ActivationPolicy: lazy +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Bundle-ClassPath: bcprov-jdk15-1.46.jar, + commons-logging-1.1.1.jar, + joda-time-1.6.2.jar, + junit-4.8.2.jar, + log4j-1.2.16.jar, + openws-1.4.2-1.jar, + serializer-2.7.1.jar, + slf4j-api-1.6.1.jar, + slf4j-log4j12-1.6.1.jar, + wss4j-1.6.5.jar, + xalan-2.7.1.jar, + xercesImpl-2.9.1.jar, + xml-apis-1.3.04.jar, + xmlsec-1.5.1.jar, + xmltooling-1.3.2-1.jar, + esapi-2.0.1.jar, + opensaml-2.5.1.jar, + . +Export-Package: java_cup.runtime, + javax.xml, + javax.xml.crypto, + javax.xml.crypto.dom, + javax.xml.crypto.dsig, + javax.xml.crypto.dsig.dom, + javax.xml.crypto.dsig.keyinfo, + javax.xml.crypto.dsig.spec, + javax.xml.datatype, + javax.xml.namespace, + javax.xml.parsers, + javax.xml.transform, + javax.xml.transform.dom, + javax.xml.transform.sax, + javax.xml.transform.stream, + javax.xml.validation, + javax.xml.xpath, + org.apache.bcel, + org.apache.bcel.classfile, + org.apache.bcel.generic, + org.apache.bcel.util, + org.apache.bcel.verifier, + org.apache.bcel.verifier.exc, + org.apache.bcel.verifier.statics, + org.apache.bcel.verifier.structurals, + org.apache.html.dom, + org.apache.jcp.xml.dsig.internal, + org.apache.jcp.xml.dsig.internal.dom, + org.apache.regexp, + org.apache.wml, + org.apache.wml.dom, + org.apache.ws.security, + org.apache.ws.security.action, + org.apache.ws.security.cache, + org.apache.ws.security.components.crypto, + org.apache.ws.security.conversation, + org.apache.ws.security.conversation.dkalgo, + org.apache.ws.security.handler, + org.apache.ws.security.message, + org.apache.ws.security.message.token, + org.apache.ws.security.processor, + org.apache.ws.security.saml, + org.apache.ws.security.saml.ext, + org.apache.ws.security.saml.ext.bean, + org.apache.ws.security.saml.ext.builder, + org.apache.ws.security.spnego, + org.apache.ws.security.str, + org.apache.ws.security.transform, + org.apache.ws.security.util, + org.apache.ws.security.validate, + org.apache.xalan, + org.apache.xalan.client, + org.apache.xalan.extensions, + org.apache.xalan.lib, + org.apache.xalan.lib.sql, + org.apache.xalan.processor, + org.apache.xalan.res, + org.apache.xalan.serialize, + org.apache.xalan.templates, + org.apache.xalan.trace, + org.apache.xalan.transformer, + org.apache.xalan.xslt, + org.apache.xalan.xsltc, + org.apache.xalan.xsltc.cmdline, + org.apache.xalan.xsltc.cmdline.getopt, + org.apache.xalan.xsltc.compiler, + org.apache.xalan.xsltc.compiler.util, + org.apache.xalan.xsltc.dom, + org.apache.xalan.xsltc.runtime, + org.apache.xalan.xsltc.runtime.output, + org.apache.xalan.xsltc.trax, + org.apache.xalan.xsltc.util, + org.apache.xerces.dom, + org.apache.xerces.dom.events, + org.apache.xerces.dom3.as, + org.apache.xerces.impl, + org.apache.xerces.impl.dtd, + org.apache.xerces.impl.dtd.models, + org.apache.xerces.impl.dv, + org.apache.xerces.impl.dv.dtd, + org.apache.xerces.impl.dv.util, + org.apache.xerces.impl.dv.xs, + org.apache.xerces.impl.io, + org.apache.xerces.impl.msg, + org.apache.xerces.impl.validation, + org.apache.xerces.impl.xpath, + org.apache.xerces.impl.xpath.regex, + org.apache.xerces.impl.xs, + org.apache.xerces.impl.xs.identity, + org.apache.xerces.impl.xs.models, + org.apache.xerces.impl.xs.opti, + org.apache.xerces.impl.xs.traversers, + org.apache.xerces.impl.xs.util, + org.apache.xerces.jaxp, + org.apache.xerces.jaxp.datatype, + org.apache.xerces.jaxp.validation, + org.apache.xerces.parsers, + org.apache.xerces.util, + org.apache.xerces.xinclude, + org.apache.xerces.xni, + org.apache.xerces.xni.grammars, + org.apache.xerces.xni.parser, + org.apache.xerces.xpointer, + org.apache.xerces.xs, + org.apache.xerces.xs.datatypes, + org.apache.xml.dtm, + org.apache.xml.dtm.ref, + org.apache.xml.dtm.ref.dom2dtm, + org.apache.xml.dtm.ref.sax2dtm, + org.apache.xml.res, + org.apache.xml.security, + org.apache.xml.security.algorithms, + org.apache.xml.security.algorithms.implementations, + org.apache.xml.security.c14n, + org.apache.xml.security.c14n.helper, + org.apache.xml.security.c14n.implementations, + org.apache.xml.security.encryption, + org.apache.xml.security.exceptions, + org.apache.xml.security.keys, + org.apache.xml.security.keys.content, + org.apache.xml.security.keys.content.keyvalues, + org.apache.xml.security.keys.content.x509, + org.apache.xml.security.keys.keyresolver, + org.apache.xml.security.keys.keyresolver.implementations, + org.apache.xml.security.keys.storage, + org.apache.xml.security.keys.storage.implementations, + org.apache.xml.security.signature, + org.apache.xml.security.signature.reference, + org.apache.xml.security.transforms, + org.apache.xml.security.transforms.implementations, + org.apache.xml.security.transforms.params, + org.apache.xml.security.utils, + org.apache.xml.security.utils.resolver, + org.apache.xml.security.utils.resolver.implementations, + org.apache.xml.serialize, + org.apache.xml.serializer, + org.apache.xml.serializer.dom3, + org.apache.xml.serializer.utils, + org.apache.xml.utils, + org.apache.xml.utils.res, + org.apache.xmlcommons, + org.apache.xpath, + org.apache.xpath.axes, + org.apache.xpath.compiler, + org.apache.xpath.domapi, + org.apache.xpath.functions, + org.apache.xpath.jaxp, + org.apache.xpath.objects, + org.apache.xpath.operations, + org.apache.xpath.patterns, + org.apache.xpath.res, + org.joda.time, + org.joda.time.base, + org.joda.time.chrono, + org.joda.time.convert, + org.joda.time.field, + org.joda.time.format, + org.joda.time.tz, + org.opensaml, + org.opensaml.common, + org.opensaml.common.binding, + org.opensaml.common.binding.artifact, + org.opensaml.common.binding.decoding, + org.opensaml.common.binding.encoding, + org.opensaml.common.binding.security, + org.opensaml.common.impl, + org.opensaml.common.xml, + org.opensaml.saml1.binding, + org.opensaml.saml1.binding.artifact, + org.opensaml.saml1.binding.decoding, + org.opensaml.saml1.binding.encoding, + org.opensaml.saml1.core, + org.opensaml.saml1.core.impl, + org.opensaml.saml1.core.validator, + org.opensaml.saml2.binding, + org.opensaml.saml2.binding.artifact, + org.opensaml.saml2.binding.decoding, + org.opensaml.saml2.binding.encoding, + org.opensaml.saml2.binding.security, + org.opensaml.saml2.common, + org.opensaml.saml2.common.impl, + org.opensaml.saml2.core, + org.opensaml.saml2.core.impl, + org.opensaml.saml2.core.validator, + org.opensaml.saml2.ecp, + org.opensaml.saml2.ecp.impl, + org.opensaml.saml2.encryption, + org.opensaml.saml2.metadata, + org.opensaml.saml2.metadata.impl, + org.opensaml.saml2.metadata.provider, + org.opensaml.saml2.metadata.support, + org.opensaml.saml2.metadata.validator, + org.opensaml.samlext.idpdisco, + org.opensaml.samlext.saml1md, + org.opensaml.samlext.saml1md.impl, + org.opensaml.samlext.saml2delrestrict, + org.opensaml.samlext.saml2delrestrict.impl, + org.opensaml.samlext.saml2mdattr, + org.opensaml.samlext.saml2mdattr.impl, + org.opensaml.samlext.saml2mdquery, + org.opensaml.samlext.saml2mdquery.impl, + org.opensaml.samlext.saml2mdui, + org.opensaml.samlext.saml2mdui.impl, + org.opensaml.samlext.samlpthrpty, + org.opensaml.samlext.samlpthrpty.impl, + org.opensaml.security, + org.opensaml.util, + org.opensaml.util.resource, + org.opensaml.util.storage, + org.opensaml.ws, + org.opensaml.ws.message, + org.opensaml.ws.message.decoder, + org.opensaml.ws.message.encoder, + org.opensaml.ws.message.handler, + org.opensaml.ws.security, + org.opensaml.ws.security.provider, + org.opensaml.ws.soap.client, + org.opensaml.ws.soap.client.http, + org.opensaml.ws.soap.common, + org.opensaml.ws.soap.soap11, + org.opensaml.ws.soap.soap11.decoder, + org.opensaml.ws.soap.soap11.decoder.http, + org.opensaml.ws.soap.soap11.encoder, + org.opensaml.ws.soap.soap11.encoder.http, + org.opensaml.ws.soap.soap11.impl, + org.opensaml.ws.soap.soap12, + org.opensaml.ws.soap.util, + org.opensaml.ws.transport, + org.opensaml.ws.transport.http, + org.opensaml.ws.wsaddressing, + org.opensaml.ws.wsaddressing.impl, + org.opensaml.ws.wsaddressing.util, + org.opensaml.ws.wsfed, + org.opensaml.ws.wsfed.impl, + org.opensaml.ws.wspolicy, + org.opensaml.ws.wspolicy.impl, + org.opensaml.ws.wssecurity, + org.opensaml.ws.wssecurity.impl, + org.opensaml.ws.wssecurity.util, + org.opensaml.ws.wstrust, + org.opensaml.ws.wstrust.impl, + org.opensaml.xacml, + org.opensaml.xacml.ctx, + org.opensaml.xacml.ctx.impl, + org.opensaml.xacml.ctx.provider, + org.opensaml.xacml.impl, + org.opensaml.xacml.policy, + org.opensaml.xacml.policy.impl, + org.opensaml.xacml.profile.saml, + org.opensaml.xacml.profile.saml.impl, + org.opensaml.xml, + org.opensaml.xml.encryption, + org.opensaml.xml.encryption.impl, + org.opensaml.xml.encryption.validator, + org.opensaml.xml.io, + org.opensaml.xml.parse, + org.opensaml.xml.schema, + org.opensaml.xml.schema.impl, + org.opensaml.xml.schema.validator, + org.opensaml.xml.security, + org.opensaml.xml.security.credential, + org.opensaml.xml.security.credential.criteria, + org.opensaml.xml.security.criteria, + org.opensaml.xml.security.keyinfo, + org.opensaml.xml.security.keyinfo.provider, + org.opensaml.xml.security.trust, + org.opensaml.xml.security.x509, + org.opensaml.xml.signature, + org.opensaml.xml.signature.impl, + org.opensaml.xml.signature.validator, + org.opensaml.xml.util, + org.opensaml.xml.validation, + org.owasp.esapi, + org.owasp.esapi.codecs, + org.owasp.esapi.crypto, + org.owasp.esapi.errors, + org.owasp.esapi.filters, + org.owasp.esapi.reference, + org.owasp.esapi.reference.accesscontrol, + org.owasp.esapi.reference.accesscontrol.policyloader, + org.owasp.esapi.reference.crypto, + org.owasp.esapi.reference.validation, + org.owasp.esapi.tags, + org.owasp.esapi.util, + org.owasp.esapi.waf, + org.owasp.esapi.waf.actions, + org.owasp.esapi.waf.configuration, + org.owasp.esapi.waf.internal, + org.owasp.esapi.waf.rules, + org.w3c.dom, + org.w3c.dom.bootstrap, + org.w3c.dom.css, + org.w3c.dom.events, + org.w3c.dom.html, + org.w3c.dom.ls, + org.w3c.dom.ranges, + org.w3c.dom.stylesheets, + org.w3c.dom.traversal, + org.w3c.dom.views, + org.w3c.dom.xpath, + org.xml.sax, + org.xml.sax.ext, + org.xml.sax.helpers diff --git a/cots/org.apache.ws.security/bcprov-jdk15-1.46.jar b/cots/org.apache.ws.security/bcprov-jdk15-1.46.jar new file mode 100644 index 0000000000..daa0b54cc0 Binary files /dev/null and b/cots/org.apache.ws.security/bcprov-jdk15-1.46.jar differ diff --git a/cots/org.apache.ws.security/build.properties b/cots/org.apache.ws.security/build.properties new file mode 100644 index 0000000000..2a23e3c64f --- /dev/null +++ b/cots/org.apache.ws.security/build.properties @@ -0,0 +1,15 @@ +bin.includes = META-INF/,\ + .,\ + opensaml-2.5.1.jar,\ + bcprov-jdk15-1.46.jar,\ + esapi-2.0.1.jar,\ + joda-time-1.6.2.jar,\ + openws-1.4.2-1.jar,\ + serializer-2.7.1.jar,\ + wss4j-1.6.5.jar,\ + xacml20-policy-config.xml,\ + xalan-2.7.1.jar,\ + xercesImpl-2.9.1.jar,\ + xml-apis-1.3.04.jar,\ + xmlsec-1.5.1.jar,\ + xmltooling-1.3.2-1.jar diff --git a/cots/org.apache.ws.security/esapi-2.0.1.jar b/cots/org.apache.ws.security/esapi-2.0.1.jar new file mode 100644 index 0000000000..48e25a2b78 Binary files /dev/null and b/cots/org.apache.ws.security/esapi-2.0.1.jar differ diff --git a/cots/org.apache.ws.security/joda-time-1.6.2.jar b/cots/org.apache.ws.security/joda-time-1.6.2.jar new file mode 100644 index 0000000000..9b045c368e Binary files /dev/null and b/cots/org.apache.ws.security/joda-time-1.6.2.jar differ diff --git a/cots/org.apache.ws.security/opensaml-2.5.1.jar b/cots/org.apache.ws.security/opensaml-2.5.1.jar new file mode 100644 index 0000000000..aa16544e12 Binary files /dev/null and b/cots/org.apache.ws.security/opensaml-2.5.1.jar differ diff --git a/cots/org.apache.ws.security/openws-1.4.2-1.jar b/cots/org.apache.ws.security/openws-1.4.2-1.jar new file mode 100644 index 0000000000..5ad1bd5522 Binary files /dev/null and b/cots/org.apache.ws.security/openws-1.4.2-1.jar differ diff --git a/cots/org.apache.ws.security/serializer-2.7.1.jar b/cots/org.apache.ws.security/serializer-2.7.1.jar new file mode 100644 index 0000000000..99f98db9bf Binary files /dev/null and b/cots/org.apache.ws.security/serializer-2.7.1.jar differ diff --git a/cots/org.apache.ws.security/wss4j-1.6.5.jar b/cots/org.apache.ws.security/wss4j-1.6.5.jar new file mode 100644 index 0000000000..9efba2b7b4 Binary files /dev/null and b/cots/org.apache.ws.security/wss4j-1.6.5.jar differ diff --git a/cots/org.apache.ws.security/xacml20-policy-config.xml b/cots/org.apache.ws.security/xacml20-policy-config.xml new file mode 100644 index 0000000000..32de4dff05 --- /dev/null +++ b/cots/org.apache.ws.security/xacml20-policy-config.xml @@ -0,0 +1,570 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cots/org.apache.ws.security/xacml20-policy-config.xml.bak b/cots/org.apache.ws.security/xacml20-policy-config.xml.bak new file mode 100644 index 0000000000..9b2628fe81 --- /dev/null +++ b/cots/org.apache.ws.security/xacml20-policy-config.xml.bak @@ -0,0 +1,570 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cots/org.apache.ws.security/xacml20-policy-config.xml~ b/cots/org.apache.ws.security/xacml20-policy-config.xml~ new file mode 100644 index 0000000000..9b2628fe81 --- /dev/null +++ b/cots/org.apache.ws.security/xacml20-policy-config.xml~ @@ -0,0 +1,570 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cots/org.apache.ws.security/xalan-2.7.1.jar b/cots/org.apache.ws.security/xalan-2.7.1.jar new file mode 100644 index 0000000000..458fa73d96 Binary files /dev/null and b/cots/org.apache.ws.security/xalan-2.7.1.jar differ diff --git a/cots/org.apache.ws.security/xercesImpl-2.9.1.jar b/cots/org.apache.ws.security/xercesImpl-2.9.1.jar new file mode 100644 index 0000000000..547f56300d Binary files /dev/null and b/cots/org.apache.ws.security/xercesImpl-2.9.1.jar differ diff --git a/cots/org.apache.ws.security/xml-apis-1.3.04.jar b/cots/org.apache.ws.security/xml-apis-1.3.04.jar new file mode 100644 index 0000000000..d42c0ea6cf Binary files /dev/null and b/cots/org.apache.ws.security/xml-apis-1.3.04.jar differ diff --git a/cots/org.apache.ws.security/xmlsec-1.5.1.jar b/cots/org.apache.ws.security/xmlsec-1.5.1.jar new file mode 100644 index 0000000000..efa5937ab0 Binary files /dev/null and b/cots/org.apache.ws.security/xmlsec-1.5.1.jar differ diff --git a/cots/org.apache.ws.security/xmltooling-1.3.2-1.jar b/cots/org.apache.ws.security/xmltooling-1.3.2-1.jar new file mode 100644 index 0000000000..8de8076bec Binary files /dev/null and b/cots/org.apache.ws.security/xmltooling-1.3.2-1.jar differ diff --git a/cots/org.geotools/.classpath b/cots/org.geotools/.classpath index 023e775466..1454a30e4e 100644 --- a/cots/org.geotools/.classpath +++ b/cots/org.geotools/.classpath @@ -1,32 +1,54 @@ - - - - - - - - - - - - - + + + + + + + + + + + + - - + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/cots/org.geotools/.settings/org.eclipse.jdt.core.prefs b/cots/org.geotools/.settings/org.eclipse.jdt.core.prefs index edef664082..1ffe2d7934 100644 --- a/cots/org.geotools/.settings/org.eclipse.jdt.core.prefs +++ b/cots/org.geotools/.settings/org.eclipse.jdt.core.prefs @@ -1,7 +1,8 @@ -#Thu Mar 26 11:29:04 CDT 2009 +#Fri Jun 08 11:49:31 CDT 2012 eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 -org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 org.eclipse.jdt.core.compiler.problem.assertIdentifier=error org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.source=1.5 +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cots/org.geotools/META-INF/MANIFEST.MF b/cots/org.geotools/META-INF/MANIFEST.MF index 03b4ddf7c5..8e98e765a5 100644 --- a/cots/org.geotools/META-INF/MANIFEST.MF +++ b/cots/org.geotools/META-INF/MANIFEST.MF @@ -3,37 +3,58 @@ Bundle-ManifestVersion: 2 Bundle-Name: Geotools Plug-in Bundle-SymbolicName: org.geotools Bundle-Version: 2.6.4 -Bundle-Vendor: Raytheon-bundled OSS -Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Eclipse-BuddyPolicy: registered, ext, global -Bundle-ClassPath: geoapi-2.3-M1.jar, - geoapi-pending-2.3-M1.jar, - gt-api-2.6.4.jar, - gt-coverage-2.6.4.jar, - gt-epsg-wkt-2.6.4.jar, - gt-geotiff-2.6.4.jar, - gt-graph-2.6.4.jar, - gt-gtopo30-2.6.4.jar, - gt-image-2.6.4.jar, - gt-main-2.6.4.jar, - gt-metadata-2.6.4.jar, - gt-referencing-2.6.4.jar, - gt-referencing3D-2.6.4.jar, - gt-shapefile-2.6.4.jar, - gt-postgis-2.6.4.jar, - jts-1.10.jar, +Bundle-ClassPath: common-2.2.1.jar, commons-beanutils-1.7.0.jar, commons-codec-1.2.jar, commons-collections-3.1.jar, commons-dbcp-1.2.2.jar, commons-jxpath-1.2.jar, commons-lang-2.3.jar, - commons-logging-1.1.1.jar, commons-pool-1.5.3.jar, - common-2.2.1.jar, - jdom-1.0.jar + ecore-2.2.2.jar, + geoapi-2.3-M1.jar, + geoapi-pending-2.3-M1.jar, + gt-api-2.6.4.jar, + gt-coverage-2.6.4.jar, + gt-cql-2.6.4.jar, + gt-epsg-wkt-2.6.4.jar, + gt-geotiff-2.6.4.jar, + gt-graph-2.6.4.jar, + gt-gtopo30-2.6.4.jar, + gt-image-2.6.4.jar, + gt-jdbc-2.6.4.jar, + gt-jdbc-postgis-2.6.4.jar, + gt-main-2.6.4.jar, + gt-metadata-2.6.4.jar, + gt-referencing-2.6.4.jar, + gt-referencing3D-2.6.4.jar, + gt-render-2.6.4.jar, + gt-shapefile-2.6.4.jar, + gt-xml-2.6.4.jar, + gt-xsd-core-2.6.4.jar, + gt-xsd-filter-2.6.4.jar, + gt-xsd-gml2-2.6.4.jar, + gt-xsd-gml3-2.6.4.jar, + gt-xsd-kml-2.6.4.jar, + gt-xsd-sld-2.6.4.jar, + jdom-1.0.jar, + gt-postgis-2.6.4.jar, + gt-wfs-2.6.4.jar, + jts-1.10.jar, + picocontainer-1.2.jar, + xercesImpl-2.7.1.jar, + xml-apis-1.0.b2.jar, + xml-apis-xerces-2.7.1.jar, + xsd-2.2.2.jar, + gt-xsd-wfs-2.6.4.jar, + gt-xsd-ows-2.6.4.jar, + net.opengis.ows-2.6.4.jar, + net.opengis.wfs-2.6.4.jar, + net.opengis.wfsv-2.6.4.jar +Bundle-Vendor: Raytheon-bundled OSS Export-Package: com.vividsolutions.jts, com.vividsolutions.jts.algorithm, + com.vividsolutions.jts.algorithm.distance, com.vividsolutions.jts.algorithm.locate, com.vividsolutions.jts.geom, com.vividsolutions.jts.geom.impl, @@ -49,6 +70,7 @@ Export-Package: com.vividsolutions.jts, com.vividsolutions.jts.index.strtree, com.vividsolutions.jts.index.sweepline, com.vividsolutions.jts.io, + com.vividsolutions.jts.io.gml2, com.vividsolutions.jts.linearref, com.vividsolutions.jts.noding, com.vividsolutions.jts.noding.snapround, @@ -80,54 +102,236 @@ Export-Package: com.vividsolutions.jts, org.geotools.coverage.processing, org.geotools.coverage.processing.operation, org.geotools.data, + org.geotools.data.collection, org.geotools.data.crs, + org.geotools.data.jdbc, + org.geotools.data.jdbc.attributeio, + org.geotools.data.jdbc.datasource, + org.geotools.data.jdbc.fidmapper, + org.geotools.data.jdbc.referencing, + org.geotools.data.memory, + org.geotools.data.ows, org.geotools.data.postgis, + org.geotools.data.postgis.attributeio, + org.geotools.data.postgis.collection, + org.geotools.data.postgis.fidmapper, + org.geotools.data.postgis.referencing, org.geotools.data.shapefile, org.geotools.data.shapefile.dbf, org.geotools.data.shapefile.indexed, + org.geotools.data.shapefile.indexed.attribute, + org.geotools.data.shapefile.prj, + org.geotools.data.shapefile.shp, + org.geotools.data.shapefile.shp.xml, + org.geotools.data.store, + org.geotools.data.view, + org.geotools.data.wfs, org.geotools.factory, org.geotools.feature, + org.geotools.feature.collection, org.geotools.feature.simple, org.geotools.feature.type, + org.geotools.feature.visitor, org.geotools.filter, + org.geotools.filter.capability, + org.geotools.filter.expression, + org.geotools.filter.function, + org.geotools.filter.function.math, + org.geotools.filter.function.string, + org.geotools.filter.identity, + org.geotools.filter.spatial, + org.geotools.filter.text.commons, + org.geotools.filter.text.cql2, + org.geotools.filter.text.ecql, + org.geotools.filter.text.generated.parsers, + org.geotools.filter.v1_0, + org.geotools.filter.v1_0.capabilities, + org.geotools.filter.v1_1, + org.geotools.filter.v1_1.capabilities, + org.geotools.filter.visitor, org.geotools.gce.geotiff, + org.geotools.gce.geotiff.adapters, + org.geotools.gce.geotiff.codes, + org.geotools.gce.gtopo30, + org.geotools.gce.image, org.geotools.geometry, + org.geotools.geometry.coordinatesequence, org.geotools.geometry.jts, + org.geotools.geometry.jts.coordinatesequence, + org.geotools.geometry.text, + org.geotools.gml, + org.geotools.gml.producer, + org.geotools.gml2, + org.geotools.gml2.bindings, + org.geotools.gml3, + org.geotools.gml3.bindings, + org.geotools.gml3.bindings.smil, + org.geotools.gml3.smil, + org.geotools.gml3.v3_2, + org.geotools.gml3.v3_2.gco, + org.geotools.gml3.v3_2.gmd, + org.geotools.gml3.v3_2.gmx, + org.geotools.gml3.v3_2.gsr, + org.geotools.gml3.v3_2.gss, + org.geotools.gml3.v3_2.gts, + org.geotools.graph.build, + org.geotools.graph.build.basic, + org.geotools.graph.build.feature, + org.geotools.graph.build.line, + org.geotools.graph.build.opt, + org.geotools.graph.build.polygon, + org.geotools.graph.io, + org.geotools.graph.io.standard, + org.geotools.graph.path, + org.geotools.graph.structure, + org.geotools.graph.structure.basic, + org.geotools.graph.structure.line, + org.geotools.graph.structure.opt, + org.geotools.graph.traverse, + org.geotools.graph.traverse.basic, + org.geotools.graph.traverse.standard, + org.geotools.graph.util, + org.geotools.graph.util.delaunay, + org.geotools.graph.util.geom, + org.geotools.graph.util.graph, + org.geotools.image, + org.geotools.image.io, + org.geotools.image.jai, + org.geotools.image.palette, + org.geotools.index, + org.geotools.index.quadtree, + org.geotools.index.quadtree.fs, + org.geotools.io, + org.geotools.jdbc, + org.geotools.kml, + org.geotools.kml.bindings, + org.geotools.legend, + org.geotools.map, + org.geotools.map.event, org.geotools.math, + org.geotools.measure, + org.geotools.metadata, + org.geotools.metadata.iso, + org.geotools.metadata.iso.citation, + org.geotools.metadata.iso.constraint, + org.geotools.metadata.iso.content, + org.geotools.metadata.iso.distribution, + org.geotools.metadata.iso.extent, + org.geotools.metadata.iso.identification, + org.geotools.metadata.iso.lineage, + org.geotools.metadata.iso.maintenance, + org.geotools.metadata.iso.quality, + org.geotools.metadata.iso.spatial, + org.geotools.metadata.sql, + org.geotools.nature, + org.geotools.ows, org.geotools.parameter, org.geotools.referencing, org.geotools.referencing.crs, org.geotools.referencing.cs, org.geotools.referencing.datum, + org.geotools.referencing.factory, + org.geotools.referencing.factory.epsg, + org.geotools.referencing.factory.wms, org.geotools.referencing.operation, org.geotools.referencing.operation.builder, org.geotools.referencing.operation.matrix, org.geotools.referencing.operation.projection, org.geotools.referencing.operation.transform, + org.geotools.referencing.piecewise, org.geotools.referencing.wkt, + org.geotools.renderer, + org.geotools.renderer.crs, + org.geotools.renderer.i18n, + org.geotools.renderer.label, + org.geotools.renderer.lite, + org.geotools.renderer.lite.gridcoverage2d, + org.geotools.renderer.style, + org.geotools.renderer.style.shape, + org.geotools.resources, + org.geotools.resources.coverage, + org.geotools.resources.geometry, + org.geotools.resources.i18n, + org.geotools.resources.image, + org.geotools.sld, + org.geotools.sld.bindings, + org.geotools.styling, + org.geotools.styling.visitor, + org.geotools.util, org.geotools.util.logging, + org.geotools.xlink, + org.geotools.xml, + org.geotools.xml.filter, + org.geotools.xml.gml, + org.geotools.xml.handlers, + org.geotools.xml.handlers.xsi, + org.geotools.xml.impl, + org.geotools.xml.impl.jxpath, + org.geotools.xml.schema, + org.geotools.xml.schema.impl, + org.geotools.xml.styling, + org.geotools.xml.test, + org.geotools.xml.transform, + org.geotools.xml.xLink, + org.geotools.xml.xsi, + org.geotools.xs, + org.geotools.xs.bindings, + org.geotools.xs.facets, + org.opengis.annotation, org.opengis.coverage, org.opengis.coverage.grid, + org.opengis.coverage.grid.quadrilateral, org.opengis.coverage.processing, + org.opengis.display.canvas, + org.opengis.display.container, + org.opengis.display.primitive, org.opengis.feature, org.opengis.feature.simple, org.opengis.feature.type, org.opengis.filter, + org.opengis.filter.capability, org.opengis.filter.expression, + org.opengis.filter.identity, + org.opengis.filter.sort, + org.opengis.filter.spatial, org.opengis.geometry, + org.opengis.geometry.aggregate, + org.opengis.geometry.complex, org.opengis.geometry.coordinate, + org.opengis.geometry.primitive, org.opengis.metadata, + org.opengis.metadata.citation, + org.opengis.metadata.constraint, + org.opengis.metadata.content, + org.opengis.metadata.distribution, + org.opengis.metadata.extent, + org.opengis.metadata.identification, + org.opengis.metadata.lineage, + org.opengis.metadata.maintenance, + org.opengis.metadata.quality, org.opengis.metadata.spatial, + org.opengis.observation, + org.opengis.observation.coverage, + org.opengis.observation.sampling, org.opengis.parameter, org.opengis.referencing, org.opengis.referencing.crs, org.opengis.referencing.cs, org.opengis.referencing.datum, org.opengis.referencing.operation, - org.opengis.util -Bundle-ActivationPolicy: lazy + org.opengis.sld, + org.opengis.style, + org.opengis.style.portrayal, + org.opengis.temporal, + org.opengis.util, + org.opengis.webservice, + org.opengis.webservice.capability, + org.opengis.webservice.feature Require-Bundle: javax.vecmath;bundle-version="1.3.1", javax.measure;bundle-version="1.0.0", org.apache.commons.logging, org.apache.log4j, org.postgres;bundle-version="1.0.0" +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Eclipse-BuddyPolicy: registered, ext, global +Bundle-ActivationPolicy: lazy diff --git a/cots/org.geotools/build.properties b/cots/org.geotools/build.properties index c720c23ace..56a78ad6cf 100644 --- a/cots/org.geotools/build.properties +++ b/cots/org.geotools/build.properties @@ -1,9 +1,19 @@ bin.includes = META-INF/,\ .,\ + common-2.2.1.jar,\ + commons-beanutils-1.7.0.jar,\ + commons-codec-1.2.jar,\ + commons-collections-3.1.jar,\ + commons-dbcp-1.2.2.jar,\ + commons-jxpath-1.2.jar,\ + commons-lang-2.3.jar,\ + commons-pool-1.5.3.jar,\ + ecore-2.2.2.jar,\ geoapi-2.3-M1.jar,\ geoapi-pending-2.3-M1.jar,\ gt-api-2.6.4.jar,\ gt-coverage-2.6.4.jar,\ + gt-cql-2.6.4.jar,\ gt-epsg-wkt-2.6.4.jar,\ gt-geotiff-2.6.4.jar,\ gt-graph-2.6.4.jar,\ @@ -13,7 +23,16 @@ bin.includes = META-INF/,\ gt-metadata-2.6.4.jar,\ gt-referencing-2.6.4.jar,\ gt-referencing3D-2.6.4.jar,\ + gt-render-2.6.4.jar,\ gt-shapefile-2.6.4.jar,\ + gt-xml-2.6.4.jar,\ + gt-xsd-core-2.6.4.jar,\ + gt-xsd-filter-2.6.4.jar,\ + gt-xsd-gml2-2.6.4.jar,\ + gt-xsd-gml3-2.6.4.jar,\ + gt-xsd-kml-2.6.4.jar,\ + gt-xsd-sld-2.6.4.jar,\ + jdom-1.0.jar,\ jts-1.10.jar,\ commons-beanutils-1.7.0.jar,\ commons-codec-1.2.jar,\ @@ -26,4 +45,16 @@ bin.includes = META-INF/,\ jdom-1.0.jar,\ gt-postgis-2.6.4.jar,\ gt-jdbc-2.6.4.jar,\ - gt-jdbc-postgis-2.6.4.jar + gt-jdbc-postgis-2.6.4.jar,\ + picocontainer-1.2.jar,\ + xercesImpl-2.7.1.jar,\ + xml-apis-1.0.b2.jar,\ + xml-apis-xerces-2.7.1.jar,\ + xsd-2.2.2.jar,\ + gt-wfs-2.6.4.jar,\ + gt-xsd-wfs-2.6.4.jar,\ + gt-xsd-ows-2.6.4.jar,\ + net.opengis.ows-2.6.4.jar,\ + net.opengis.wfs-2.6.4.jar,\ + net.opengis.wfsv-2.6.4.jar + diff --git a/cots/org.geotools/ecore-2.2.2.jar b/cots/org.geotools/ecore-2.2.2.jar new file mode 100644 index 0000000000..d472c76b77 Binary files /dev/null and b/cots/org.geotools/ecore-2.2.2.jar differ diff --git a/cots/org.geotools/gt-cql-2.6.4.jar b/cots/org.geotools/gt-cql-2.6.4.jar new file mode 100644 index 0000000000..50cb35cb7f Binary files /dev/null and b/cots/org.geotools/gt-cql-2.6.4.jar differ diff --git a/cots/org.geotools/gt-render-2.6.4.jar b/cots/org.geotools/gt-render-2.6.4.jar new file mode 100644 index 0000000000..c6e0feb793 Binary files /dev/null and b/cots/org.geotools/gt-render-2.6.4.jar differ diff --git a/cots/org.geotools/gt-wfs-2.6.4.jar b/cots/org.geotools/gt-wfs-2.6.4.jar new file mode 100644 index 0000000000..4e09d57d86 Binary files /dev/null and b/cots/org.geotools/gt-wfs-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xml-2.6.4.jar b/cots/org.geotools/gt-xml-2.6.4.jar new file mode 100644 index 0000000000..4a089f7b0b Binary files /dev/null and b/cots/org.geotools/gt-xml-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-core-2.6.4.jar b/cots/org.geotools/gt-xsd-core-2.6.4.jar new file mode 100644 index 0000000000..a765c8c8af Binary files /dev/null and b/cots/org.geotools/gt-xsd-core-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-filter-2.6.4.jar b/cots/org.geotools/gt-xsd-filter-2.6.4.jar new file mode 100644 index 0000000000..5e0785b99f Binary files /dev/null and b/cots/org.geotools/gt-xsd-filter-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-gml2-2.6.4.jar b/cots/org.geotools/gt-xsd-gml2-2.6.4.jar new file mode 100644 index 0000000000..d76751cd40 Binary files /dev/null and b/cots/org.geotools/gt-xsd-gml2-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-gml3-2.6.4.jar b/cots/org.geotools/gt-xsd-gml3-2.6.4.jar new file mode 100644 index 0000000000..7a60845970 Binary files /dev/null and b/cots/org.geotools/gt-xsd-gml3-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-kml-2.6.4.jar b/cots/org.geotools/gt-xsd-kml-2.6.4.jar new file mode 100644 index 0000000000..8dcf45eea8 Binary files /dev/null and b/cots/org.geotools/gt-xsd-kml-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-ows-2.6.4.jar b/cots/org.geotools/gt-xsd-ows-2.6.4.jar new file mode 100644 index 0000000000..07abbbf8b1 Binary files /dev/null and b/cots/org.geotools/gt-xsd-ows-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-sld-2.6.4.jar b/cots/org.geotools/gt-xsd-sld-2.6.4.jar new file mode 100644 index 0000000000..22cf6802b1 Binary files /dev/null and b/cots/org.geotools/gt-xsd-sld-2.6.4.jar differ diff --git a/cots/org.geotools/gt-xsd-wfs-2.6.4.jar b/cots/org.geotools/gt-xsd-wfs-2.6.4.jar new file mode 100644 index 0000000000..0c60b58051 Binary files /dev/null and b/cots/org.geotools/gt-xsd-wfs-2.6.4.jar differ diff --git a/cots/org.geotools/net.opengis.ows-2.6.4.jar b/cots/org.geotools/net.opengis.ows-2.6.4.jar new file mode 100644 index 0000000000..43f0d49ba9 Binary files /dev/null and b/cots/org.geotools/net.opengis.ows-2.6.4.jar differ diff --git a/cots/org.geotools/net.opengis.wfs-2.6.4.jar b/cots/org.geotools/net.opengis.wfs-2.6.4.jar new file mode 100644 index 0000000000..cab8df7593 Binary files /dev/null and b/cots/org.geotools/net.opengis.wfs-2.6.4.jar differ diff --git a/cots/org.geotools/net.opengis.wfsv-2.6.4.jar b/cots/org.geotools/net.opengis.wfsv-2.6.4.jar new file mode 100644 index 0000000000..abc7e0d38c Binary files /dev/null and b/cots/org.geotools/net.opengis.wfsv-2.6.4.jar differ diff --git a/cots/org.geotools/picocontainer-1.2.jar b/cots/org.geotools/picocontainer-1.2.jar new file mode 100644 index 0000000000..fbb1c925b8 Binary files /dev/null and b/cots/org.geotools/picocontainer-1.2.jar differ diff --git a/cots/org.geotools/xercesImpl-2.7.1.jar b/cots/org.geotools/xercesImpl-2.7.1.jar new file mode 100644 index 0000000000..0b100e14b8 Binary files /dev/null and b/cots/org.geotools/xercesImpl-2.7.1.jar differ diff --git a/cots/org.geotools/xml-apis-1.0.b2.jar b/cots/org.geotools/xml-apis-1.0.b2.jar new file mode 100644 index 0000000000..ad33a5afa6 Binary files /dev/null and b/cots/org.geotools/xml-apis-1.0.b2.jar differ diff --git a/cots/org.geotools/xml-apis-xerces-2.7.1.jar b/cots/org.geotools/xml-apis-xerces-2.7.1.jar new file mode 100644 index 0000000000..243eaeaeb2 Binary files /dev/null and b/cots/org.geotools/xml-apis-xerces-2.7.1.jar differ diff --git a/cots/org.geotools/xsd-2.2.2.jar b/cots/org.geotools/xsd-2.2.2.jar new file mode 100644 index 0000000000..23487367f3 Binary files /dev/null and b/cots/org.geotools/xsd-2.2.2.jar differ diff --git a/cots/org.hibernate/.classpath b/cots/org.hibernate/.classpath index d4f85314f6..a49aca05d1 100644 --- a/cots/org.hibernate/.classpath +++ b/cots/org.hibernate/.classpath @@ -1,9 +1,11 @@ + + - + diff --git a/cots/org.hibernate/.settings/org.eclipse.jdt.core.prefs b/cots/org.hibernate/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..4443c832ba --- /dev/null +++ b/cots/org.hibernate/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Jun 08 11:53:01 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/cots/org.hibernate/META-INF/MANIFEST.MF b/cots/org.hibernate/META-INF/MANIFEST.MF index 8e39131001..fa6dd0f32e 100644 --- a/cots/org.hibernate/META-INF/MANIFEST.MF +++ b/cots/org.hibernate/META-INF/MANIFEST.MF @@ -3,10 +3,13 @@ Bundle-ManifestVersion: 2 Bundle-Name: Hibernate Plug-in Bundle-SymbolicName: org.hibernate Bundle-Version: 1.0.0.qualifier +Bundle-ClassPath: hibernate-spatial-1.0.jar, + hibernate-spatial-postgis-1.0.jar, + hibernate3.5.0-Final.jar, + javassist-3.9.0.GA.jar, + jta-1.1.jar Bundle-Vendor: Hibernate -Require-Bundle: org.slf4j -Export-Package: - org.hibernate, +Export-Package: org.hibernate, org.hibernate.action, org.hibernate.annotations, org.hibernate.annotations.common, @@ -171,7 +174,14 @@ Export-Package: org.hibernate.tuple.entity, org.hibernate.type, org.hibernate.usertype, - org.hibernate.util -Bundle-ClassPath: hibernate3.5.0-Final.jar, - javassist-3.9.0.GA.jar, - jta-1.1.jar + org.hibernate.util, + org.hibernatespatial, + org.hibernatespatial.cfg, + org.hibernatespatial.criterion, + org.hibernatespatial.helper, + org.hibernatespatial.mgeom, + org.hibernatespatial.pojo, + org.hibernatespatial.postgis, + org.hibernatespatial.readers, + org.hibernatespatial.spi +Require-Bundle: org.slf4j diff --git a/cots/org.hibernate/build.properties b/cots/org.hibernate/build.properties index 3fada6b622..802fa8462a 100644 --- a/cots/org.hibernate/build.properties +++ b/cots/org.hibernate/build.properties @@ -1,4 +1,6 @@ bin.includes = META-INF/,\ + hibernate-spatial-1.0.jar,\ + hibernate-spatial-postgis-1.0.jar,\ hibernate3.5.0-Final.jar,\ javassist-3.9.0.GA.jar,\ jta-1.1.jar diff --git a/cots/org.hibernate/hibernate-spatial-1.0.jar b/cots/org.hibernate/hibernate-spatial-1.0.jar new file mode 100644 index 0000000000..8d410502cb Binary files /dev/null and b/cots/org.hibernate/hibernate-spatial-1.0.jar differ diff --git a/cots/org.hibernate/hibernate-spatial-postgis-1.0.jar b/cots/org.hibernate/hibernate-spatial-postgis-1.0.jar new file mode 100644 index 0000000000..930f1e49c2 Binary files /dev/null and b/cots/org.hibernate/hibernate-spatial-postgis-1.0.jar differ diff --git a/cots/org.junit/.classpath b/cots/org.junit/.classpath index bd39c93d4e..7363c566f4 100644 --- a/cots/org.junit/.classpath +++ b/cots/org.junit/.classpath @@ -2,11 +2,14 @@ - - - + + + + + + diff --git a/cots/org.junit/META-INF/MANIFEST.MF b/cots/org.junit/META-INF/MANIFEST.MF index c448390ddc..7f2d8e6aba 100644 --- a/cots/org.junit/META-INF/MANIFEST.MF +++ b/cots/org.junit/META-INF/MANIFEST.MF @@ -3,25 +3,48 @@ Bundle-ManifestVersion: 2 Bundle-Name: Junit Plug-in Bundle-SymbolicName: org.junit Bundle-Version: 1.0.0.qualifier -Bundle-ClassPath: junit-4.3.1.jar, - hamcrest-api-1.0.jar, - hamcrest-library-1.0.jar, - jmock-2.0.0.jar, +Bundle-ClassPath: jmock-2.0.0.jar, jmock-junit3-2.0.0.jar, - jmock-junit4-2.0.0.jar -Export-Package: junit.extensions, + jmock-junit4-2.0.0.jar, + cglib-nodep-2.2.jar, + javassist-3.16.1-GA.jar, + mockito-all-1.9.0.jar, + objenesis-1.2.jar, + powermock-mockito-1.4.12-full.jar, + junit-4.10.jar +Export-Package: javassist, + javassist.bytecode, + javassist.bytecode.analysis, + javassist.bytecode.annotation, + javassist.bytecode.stackmap, + javassist.compiler, + javassist.compiler.ast, + javassist.convert, + javassist.expr, + javassist.runtime, + javassist.scopedpool, + javassist.tools, + javassist.tools.reflect, + javassist.tools.rmi, + javassist.tools.web, + javassist.util, + javassist.util.proxy, + junit.extensions, junit.framework, junit.runner, junit.textui, + net.sf.cglib.asm, + net.sf.cglib.asm.signature, + net.sf.cglib.beans, + net.sf.cglib.core, + net.sf.cglib.proxy, + net.sf.cglib.reflect, + net.sf.cglib.transform, + net.sf.cglib.transform.impl, + net.sf.cglib.util, org.hamcrest, - org.hamcrest.beans, - org.hamcrest.collection, org.hamcrest.core, org.hamcrest.internal, - org.hamcrest.number, - org.hamcrest.object, - org.hamcrest.text, - org.hamcrest.xml, org.jmock, org.jmock.api, org.jmock.example.qcon, @@ -35,11 +58,147 @@ Export-Package: junit.extensions, org.jmock.lib.action, org.jmock.syntax, org.junit, + org.junit.experimental, + org.junit.experimental.categories, + org.junit.experimental.max, + org.junit.experimental.results, + org.junit.experimental.runners, + org.junit.experimental.theories, + org.junit.experimental.theories.internal, + org.junit.experimental.theories.suppliers, org.junit.internal, + org.junit.internal.builders, + org.junit.internal.matchers, org.junit.internal.requests, org.junit.internal.runners, + org.junit.internal.runners.model, + org.junit.internal.runners.rules, + org.junit.internal.runners.statements, + org.junit.matchers, + org.junit.rules, org.junit.runner, org.junit.runner.manipulation, org.junit.runner.notification, - org.junit.runners + org.junit.runners, + org.junit.runners.model, + org.mockito, + org.mockito.asm, + org.mockito.asm.signature, + org.mockito.asm.tree, + org.mockito.asm.tree.analysis, + org.mockito.asm.util, + org.mockito.cglib.beans, + org.mockito.cglib.core, + org.mockito.cglib.proxy, + org.mockito.cglib.reflect, + org.mockito.cglib.transform, + org.mockito.cglib.transform.impl, + org.mockito.cglib.util, + org.mockito.configuration, + org.mockito.exceptions, + org.mockito.exceptions.base, + org.mockito.exceptions.misusing, + org.mockito.exceptions.verification, + org.mockito.exceptions.verification.junit, + org.mockito.internal, + org.mockito.internal.configuration, + org.mockito.internal.configuration.injection, + org.mockito.internal.configuration.injection.filter, + org.mockito.internal.creation, + org.mockito.internal.creation.cglib, + org.mockito.internal.creation.jmock, + org.mockito.internal.debugging, + org.mockito.internal.exceptions, + org.mockito.internal.exceptions.base, + org.mockito.internal.exceptions.util, + org.mockito.internal.invocation, + org.mockito.internal.invocation.finder, + org.mockito.internal.invocation.realmethod, + org.mockito.internal.listeners, + org.mockito.internal.matchers, + org.mockito.internal.matchers.apachecommons, + org.mockito.internal.progress, + org.mockito.internal.reporting, + org.mockito.internal.runners, + org.mockito.internal.runners.util, + org.mockito.internal.stubbing, + org.mockito.internal.stubbing.answers, + org.mockito.internal.stubbing.defaultanswers, + org.mockito.internal.util, + org.mockito.internal.util.junit, + org.mockito.internal.util.reflection, + org.mockito.internal.verification, + org.mockito.internal.verification.api, + org.mockito.internal.verification.argumentmatching, + org.mockito.internal.verification.checkers, + org.mockito.invocation, + org.mockito.listeners, + org.mockito.runners, + org.mockito.stubbing, + org.mockito.stubbing.answers, + org.mockito.verification, + org.objenesis, + org.objenesis.instantiator, + org.objenesis.instantiator.basic, + org.objenesis.instantiator.gcj, + org.objenesis.instantiator.jrockit, + org.objenesis.instantiator.perc, + org.objenesis.instantiator.sun, + org.objenesis.strategy, + org.powermock.api.extension.listener, + org.powermock.api.extension.proxyframework, + org.powermock.api.mockito, + org.powermock.api.mockito.expectation, + org.powermock.api.mockito.internal, + org.powermock.api.mockito.internal.configuration, + org.powermock.api.mockito.internal.expectation, + org.powermock.api.mockito.internal.invocationcontrol, + org.powermock.api.mockito.internal.mockcreation, + org.powermock.api.mockito.internal.verification, + org.powermock.api.mockito.mockpolicies, + org.powermock.api.mockito.powermocklistener, + org.powermock.api.mockito.verification, + org.powermock.api.support, + org.powermock.api.support.membermodification, + org.powermock.api.support.membermodification.strategy, + org.powermock.api.support.membermodification.strategy.impl, + org.powermock.classloading, + org.powermock.classloading.spi, + org.powermock.core, + org.powermock.core.classloader, + org.powermock.core.classloader.annotations, + org.powermock.core.spi, + org.powermock.core.spi.listener, + org.powermock.core.spi.support, + org.powermock.core.spi.testresult, + org.powermock.core.spi.testresult.impl, + org.powermock.core.testlisteners, + org.powermock.core.transformers, + org.powermock.core.transformers.impl, + org.powermock.mockpolicies, + org.powermock.mockpolicies.impl, + org.powermock.mockpolicies.support, + org.powermock.modules.junit3, + org.powermock.modules.junit3.internal, + org.powermock.modules.junit3.internal.impl, + org.powermock.modules.junit4, + org.powermock.modules.junit4.common.internal, + org.powermock.modules.junit4.common.internal.impl, + org.powermock.modules.junit4.internal.impl, + org.powermock.modules.junit4.internal.impl.testcaseworkaround, + org.powermock.modules.junit4.legacy, + org.powermock.modules.junit4.legacy.internal.impl, + org.powermock.modules.junit4.legacy.internal.impl.testcaseworkaround, + org.powermock.modules.testng, + org.powermock.modules.testng.internal, + org.powermock.reflect, + org.powermock.reflect.exceptions, + org.powermock.reflect.internal, + org.powermock.reflect.internal.matcherstrategies, + org.powermock.reflect.internal.primitivesupport, + org.powermock.reflect.matching, + org.powermock.reflect.proxyframework, + org.powermock.reflect.spi, + org.powermock.tests.utils, + org.powermock.tests.utils.impl Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/cots/org.junit/build.properties b/cots/org.junit/build.properties index 93e6e60d4c..da97b1e7e3 100644 --- a/cots/org.junit/build.properties +++ b/cots/org.junit/build.properties @@ -1,7 +1,11 @@ bin.includes = META-INF/,\ - junit-4.3.1.jar,\ - hamcrest-api-1.0.jar,\ - hamcrest-library-1.0.jar,\ jmock-2.0.0.jar,\ jmock-junit3-2.0.0.jar,\ - jmock-junit4-2.0.0.jar + jmock-junit4-2.0.0.jar,\ + cglib-nodep-2.2.jar,\ + javassist-3.16.1-GA.jar,\ + junit-4.8.2.jar,\ + mockito-all-1.9.0.jar,\ + objenesis-1.2.jar,\ + powermock-mockito-1.4.12-full.jar,\ + junit-4.10.jar diff --git a/cots/org.junit/cglib-nodep-2.2.jar b/cots/org.junit/cglib-nodep-2.2.jar new file mode 100644 index 0000000000..ed07cb507f Binary files /dev/null and b/cots/org.junit/cglib-nodep-2.2.jar differ diff --git a/cots/org.junit/hamcrest-api-1.0.jar b/cots/org.junit/hamcrest-api-1.0.jar deleted file mode 100644 index 5df3f19d92..0000000000 Binary files a/cots/org.junit/hamcrest-api-1.0.jar and /dev/null differ diff --git a/cots/org.junit/hamcrest-library-1.0.jar b/cots/org.junit/hamcrest-library-1.0.jar deleted file mode 100644 index e0b275f049..0000000000 Binary files a/cots/org.junit/hamcrest-library-1.0.jar and /dev/null differ diff --git a/cots/org.junit/javassist-3.16.1-GA.jar b/cots/org.junit/javassist-3.16.1-GA.jar new file mode 100644 index 0000000000..c29da0fae0 Binary files /dev/null and b/cots/org.junit/javassist-3.16.1-GA.jar differ diff --git a/cots/org.junit/junit-4.10-src.jar b/cots/org.junit/junit-4.10-src.jar new file mode 100644 index 0000000000..1449d28b5b Binary files /dev/null and b/cots/org.junit/junit-4.10-src.jar differ diff --git a/cots/org.junit/junit-4.10.jar b/cots/org.junit/junit-4.10.jar new file mode 100644 index 0000000000..bf5c0b9c6a Binary files /dev/null and b/cots/org.junit/junit-4.10.jar differ diff --git a/cots/org.junit/junit-4.3.1.jar b/cots/org.junit/junit-4.3.1.jar deleted file mode 100644 index ff5d1888fc..0000000000 Binary files a/cots/org.junit/junit-4.3.1.jar and /dev/null differ diff --git a/cots/org.junit/mockito-all-1.9.0.jar b/cots/org.junit/mockito-all-1.9.0.jar new file mode 100644 index 0000000000..273fd50feb Binary files /dev/null and b/cots/org.junit/mockito-all-1.9.0.jar differ diff --git a/cots/org.junit/objenesis-1.2.jar b/cots/org.junit/objenesis-1.2.jar new file mode 100644 index 0000000000..fb04d7fa64 Binary files /dev/null and b/cots/org.junit/objenesis-1.2.jar differ diff --git a/cots/org.junit/powermock-mockito-1.4.12-full.jar b/cots/org.junit/powermock-mockito-1.4.12-full.jar new file mode 100644 index 0000000000..b70358d164 Binary files /dev/null and b/cots/org.junit/powermock-mockito-1.4.12-full.jar differ diff --git a/cots/org.springframework.dm/.classpath b/cots/org.springframework.dm/.classpath deleted file mode 100644 index 89574b8582..0000000000 --- a/cots/org.springframework.dm/.classpath +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - - - - diff --git a/cots/org.springframework.dm/META-INF/MANIFEST.MF b/cots/org.springframework.dm/META-INF/MANIFEST.MF deleted file mode 100644 index f204b6691a..0000000000 --- a/cots/org.springframework.dm/META-INF/MANIFEST.MF +++ /dev/null @@ -1,58 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Spring OSGI -Bundle-SymbolicName: org.springframework.dm -Bundle-Version: 1.2.1 -Bundle-ClassPath: org.springframework.osgi.core-1.2.0.jar, - org.springframework.osgi.extender-1.2.0.jar, - org.springframework.osgi.io-1.2.0.jar -Export-Package: org.springframework.osgi, - org.springframework.osgi.bundle, - org.springframework.osgi.compendium.cm, - org.springframework.osgi.compendium.config, - org.springframework.osgi.compendium.internal.cm, - org.springframework.osgi.config, - org.springframework.osgi.config.internal.adapter, - org.springframework.osgi.config.internal.util, - org.springframework.osgi.context, - org.springframework.osgi.context.event, - org.springframework.osgi.context.internal.classloader, - org.springframework.osgi.context.support, - org.springframework.osgi.context.support.internal, - org.springframework.osgi.extender, - org.springframework.osgi.extender.event, - org.springframework.osgi.extender.internal.activator, - org.springframework.osgi.extender.internal.dependencies.shutdown, - org.springframework.osgi.extender.internal.dependencies.startup, - org.springframework.osgi.extender.internal.support, - org.springframework.osgi.extender.internal.util, - org.springframework.osgi.extender.internal.util.concurrent, - org.springframework.osgi.extender.support, - org.springframework.osgi.extender.support.internal, - org.springframework.osgi.extender.support.scanning, - org.springframework.osgi.io, - org.springframework.osgi.io.internal, - org.springframework.osgi.io.internal.resolver, - org.springframework.osgi.service, - org.springframework.osgi.service.dependency.internal, - org.springframework.osgi.service.exporter, - org.springframework.osgi.service.exporter.support, - org.springframework.osgi.service.exporter.support.internal.controller, - org.springframework.osgi.service.exporter.support.internal.support, - org.springframework.osgi.service.importer, - org.springframework.osgi.service.importer.event, - org.springframework.osgi.service.importer.support, - org.springframework.osgi.service.importer.support.internal.aop, - org.springframework.osgi.service.importer.support.internal.collection, - org.springframework.osgi.service.importer.support.internal.collection.comparator, - org.springframework.osgi.service.importer.support.internal.controller, - org.springframework.osgi.service.importer.support.internal.dependency, - org.springframework.osgi.service.importer.support.internal.support, - org.springframework.osgi.service.importer.support.internal.util, - org.springframework.osgi.service.util.internal.aop, - org.springframework.osgi.util, - org.springframework.osgi.util.internal -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: org.apache.commons.logging;bundle-version="1.1.1", - org.eclipse.osgi;bundle-version="3.6.1", - org.springframework;bundle-version="2.5.6" diff --git a/cots/org.springframework.dm/build.properties b/cots/org.springframework.dm/build.properties deleted file mode 100644 index 2aa1fa3db9..0000000000 --- a/cots/org.springframework.dm/build.properties +++ /dev/null @@ -1,4 +0,0 @@ -bin.includes = META-INF/,\ - org.springframework.osgi.core-1.2.0.jar,\ - org.springframework.osgi.extender-1.2.0.jar,\ - org.springframework.osgi.io-1.2.0.jar diff --git a/cots/org.springframework.dm/org.springframework.dm.ecl b/cots/org.springframework.dm/org.springframework.dm.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/cots/org.springframework.dm/org.springframework.osgi.core-1.2.0.jar b/cots/org.springframework.dm/org.springframework.osgi.core-1.2.0.jar deleted file mode 100644 index ece0eb4f5d..0000000000 Binary files a/cots/org.springframework.dm/org.springframework.osgi.core-1.2.0.jar and /dev/null differ diff --git a/cots/org.springframework.dm/org.springframework.osgi.core-sources-1.2.0.jar b/cots/org.springframework.dm/org.springframework.osgi.core-sources-1.2.0.jar deleted file mode 100644 index 437d516644..0000000000 Binary files a/cots/org.springframework.dm/org.springframework.osgi.core-sources-1.2.0.jar and /dev/null differ diff --git a/cots/org.springframework.dm/org.springframework.osgi.extender-1.2.0.jar b/cots/org.springframework.dm/org.springframework.osgi.extender-1.2.0.jar deleted file mode 100644 index 31ba0c7b45..0000000000 Binary files a/cots/org.springframework.dm/org.springframework.osgi.extender-1.2.0.jar and /dev/null differ diff --git a/cots/org.springframework.dm/org.springframework.osgi.extender-sources-1.2.0.jar b/cots/org.springframework.dm/org.springframework.osgi.extender-sources-1.2.0.jar deleted file mode 100644 index b0f78cd113..0000000000 Binary files a/cots/org.springframework.dm/org.springframework.osgi.extender-sources-1.2.0.jar and /dev/null differ diff --git a/cots/org.springframework.dm/org.springframework.osgi.io-1.2.0.jar b/cots/org.springframework.dm/org.springframework.osgi.io-1.2.0.jar deleted file mode 100644 index 420b97467b..0000000000 Binary files a/cots/org.springframework.dm/org.springframework.osgi.io-1.2.0.jar and /dev/null differ diff --git a/cots/org.springframework.dm/org.springframework.osgi.io-sources-1.2.0.jar b/cots/org.springframework.dm/org.springframework.osgi.io-sources-1.2.0.jar deleted file mode 100644 index e1a9ccd60c..0000000000 Binary files a/cots/org.springframework.dm/org.springframework.osgi.io-sources-1.2.0.jar and /dev/null differ diff --git a/cots/org.springframework/.classpath b/cots/org.springframework/.classpath index f9ddbf2477..69296e94fd 100644 --- a/cots/org.springframework/.classpath +++ b/cots/org.springframework/.classpath @@ -2,7 +2,7 @@ - + diff --git a/deltaScripts/12.12.1/reformatPurgeRules.sh b/deltaScripts/12.12.1/reformatPurgeRules.sh new file mode 100644 index 0000000000..1a0bafb75e --- /dev/null +++ b/deltaScripts/12.12.1/reformatPurgeRules.sh @@ -0,0 +1,193 @@ +#!/bin/sh + +# NOTE: UPGRADE SCRIPT IS SIMPLE. XML Purge Rule Cannot be condensed and have multiple tags on a line. Expects pretty print xml that is easily readable/parsable + +SITE_PATH="/awips2/edex/data/utility/common_static/site" + +if [ ! -d $SITE_PATH ]; then + echo "Cannot find site directory. $SITE_PATH does not exist" + usage + exit 1 +fi + +echo "This script should be run as user awips. Will back up purge rule directories to .bak" +echo "Press any key to continue or ^C to quit" +read + +for d in `find $SITE_PATH -type d -name "purge"`; do + newDir=$d.new + if [ -d "$newDir" ]; then + rm -rf $newDir + fi + mkdir -p $newDir + + echo "Processing directory $d" + + for f in `ls $d/*PurgeRules.xml`; do + fileName=${f##*/} + NEW_FILE=$newDir/${fileName} + if [ -f $f.modelPathKey ]; then + f="$f.modelPathKey" + elif [ -f $.radarPathKey ]; then + f="$f.radarPathKey" + fi + echo " Processing $f into $NEW_FILE" + + PIFS=$IFS + IFS=$'\n' + + # prescan to determine all key combinations + hasDefaultRule='0' + keys=() + keysIndex=0 + + for key in `grep key $f `; do + # strip tags + key=${key#*} + key=${key%*} + + if [ "$key" == "default" ]; then + hasDefaultRule='1' + else + # split on semicolon and equal + keyTokens=( $( echo "$key" | tr ';=' '\n' ) ) + size="${#keyTokens[@]}" + tokenIndex=0 + + while [ "$tokenIndex" -lt "$size" ]; do + curToken="${keyTokens[$tokenIndex]}" + addKey=1 + + # verify key hasn't already been added + if [ $keysIndex -gt 0 ]; then + tempIndex=0 + while [ $tempIndex -lt $keysIndex ]; do + if [ "${keys[$tempIndex]}" == "$curToken" ]; then + addKey=0 + break + fi + let tempIndex+=1 + done + fi + + if [ $addKey -eq 1 ]; then + keys[$keysIndex]="$curToken" + let keysIndex+=1 + fi + + let tokenIndex+=2 + done + fi + done + + keysSize=$keysIndex + keysIndex=0 + state='0' + rule=() + ruleIndex=0 + ruleTag="rule" + + for line in `cat $f`; do + case $state in + # looking for + 0) if [[ $line =~ "" ]]; then + # drop name space + echo "" >> $NEW_FILE + keyIndex=0 + while [ $keyIndex -lt $keysSize ]; do + echo " ${keys[$keyIndex]}" >> $NEW_FILE + let keyIndex+=1 + done + state='1' + else + # copy line to new file + echo $line >> $NEW_FILE + fi + ;; + # looking for + 1) if [[ $line =~ "" ]]; then + state='2' + else + # copy line to new file + echo $line >> $NEW_FILE + fi + ;; + # looking for + 2) if [[ $line =~ ".*" ]]; then + state='3' + + # strip tags + key=${line#*} + key=${key%*} + + if [ "$key" == "default" ]; then + # default rule, nothing to do besides set rule tag + ruleTag="defaultRule" + else + # normal rule, split into tokens, and order by keys + ruleTag="rule" + + # split on semicolon and equal + keyTokens=( $( echo "$key" | tr ';=' '\n' ) ) + tokenSize="${#keyTokens[@]}" + keyIndex=0 + + while [ $keyIndex -lt $keysSize ]; do + curKey="${keys[$keyIndex]}" + tokenIndex=0 + + while [ $tokenIndex -lt $tokenSize ]; do + if [ "$curKey" == "${keyTokens[$tokenIndex]}" ]; then + # found key, add value tag to rule + let tokenIndex+=1 + rule[$ruleIndex]=" ${keyTokens[$tokenIndex]}" + let ruleIndex+=1 + break + else + # advance tokenIndex to next key + let tokenIndex+=2 + fi + done + + let keyIndex+=1 + done + fi + elif [[ ! $line =~ "" ]] && [[ ! $line =~ "" ]]; then + # copy line to rule buffer, skipping and + rule[$ruleIndex]="$line" + let ruleIndex+=1 + fi + ;; + # looking for + 3) if [[ $line =~ "" ]]; then + state='1' + ruleSize=$ruleIndex + ruleIndex=0 + + echo " <$ruleTag>" >> $NEW_FILE + while [ $ruleIndex -lt $ruleSize ]; do + echo "${rule[$ruleIndex]}" >> $NEW_FILE + let ruleIndex+=1 + done + echo " " >> $NEW_FILE + + ruleIndex=0 + rule=() + elif [[ ! $line =~ "" ]] && [[ ! $line =~ "" ]]; then + # copy line to rule buffer + rule[$ruleIndex]="$line" + let ruleIndex+=1 + fi + ;; + esac + done + + IFS=$PIFS + done + + echo " Moving $d to $d.bak" + mv $d $d.bak + echo " Moving $newDir to $d" + mv $newDir $d +done + diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/exception/package-info.java b/deltaScripts/13.1.2/createEventsSchema.sql similarity index 88% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/exception/package-info.java rename to deltaScripts/13.1.2/createEventsSchema.sql index 06661defff..750b1d3499 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/exception/package-info.java +++ b/deltaScripts/13.1.2/createEventsSchema.sql @@ -17,7 +17,6 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -/** - * Exception classes for grib plugin - */ -package com.raytheon.uf.common.dataplugin.grib.exception; \ No newline at end of file +\set ON_ERROR_STOP 1 +\connect metadata; +CREATE SCHEMA events AUTHORIZATION awips; diff --git a/deltaScripts/13.1.2/eventsSchemaDelta.sh b/deltaScripts/13.1.2/eventsSchemaDelta.sh new file mode 100644 index 0000000000..ff45719f50 --- /dev/null +++ b/deltaScripts/13.1.2/eventsSchemaDelta.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +SQL_SCRIPT="createEventsSchema.sql" + +# ensure that the sql script is present +if [ ! -f ${SQL_SCRIPT} ]; then + echo "ERROR: the required sql script - ${SQL_SCRIPT} was not found." + echo "FATAL: the update has failed!" + exit 1 +fi + +echo "INFO: update started - adding the events schema to the metadata database" + +# run the update +/awips2/psql/bin/psql -U awips -d metadata -f ${SQL_SCRIPT} +if [ $? -ne 0 ]; then + echo "FATAL: the update has failed!" + exit 1 +fi + +echo "INFO: the update has completed successfully!" + +exit 0 diff --git a/deltaScripts/unified_grid/README.txt b/deltaScripts/unified_grid/README.txt new file mode 100644 index 0000000000..4c50d3f2ac --- /dev/null +++ b/deltaScripts/unified_grid/README.txt @@ -0,0 +1,38 @@ +This directory contains all the scripts needed to upgrade from grib to the new +"Unified" grid storage format. + +The following commands will need to run to upgrade postgres and hdf5 files: +bash register_grid_coverage.sh +bash create_grid_tables.sh +python convert_grib_data.py + +The following commands will need to run to upgrade localization files: +bash copy_grib_purge_rules.sh +bash update_D2D_bundles.sh +bash update_D2D_procedures.sh +bash update_FFMP_Source.sh + +convert_grib_data.py can take a significant amount of time, as much as 2 hours. +If you don't need your data and you want to upgrade faster you can purge all grib data. +If there is no grib data to convert there is no need to run convert_grib_data.py. + +After convert_grib_data.py has run, it may not convert all models(perhaps skipping +alaskan, hawaiin, or other models.) If this is the case there will be data left over +in /awips2/edex/data/hdf5/grib. This data can be used if you need to convert additional +models or if a rollback is necessary. The system is not set up to purge this data, so +after a successful upgrade when new data is arriving this directory will need to be deleted. + +The format of the data in /awips2/edex/data/hdf5/topo/modelStaticTopo.h5 has changed. When the +ingestGrib edex is started it will attempt to regenerate this file. This is a very time and +memory intensive process. To save time when upgrading an operational system it is recommended +that you copy a modelStaticTopo.h5 file from a testbed or other system that has already generated it. + +The update_saved_display.sh script can be used if there are any saved displays that are +saved outside of localization. + +If for some reason the upgrade fails or you want to roll back. Install an old +version of edex and run the scripts in the unified_grid_rollback directory. +The postgres and hdf5 scripts in that directory will need to be run in the opposite order: +python convert_grib_data.py +bash create_grid_tables.sh +bash register_grid_coverage.sh \ No newline at end of file diff --git a/deltaScripts/unified_grid/convert_grib_data.py b/deltaScripts/unified_grid/convert_grib_data.py new file mode 100644 index 0000000000..8f0df9e9a7 --- /dev/null +++ b/deltaScripts/unified_grid/convert_grib_data.py @@ -0,0 +1,351 @@ +#!/usr/bin/python +# This script will add register the gridcoverage plugin, which was previosly part of grib +# +# This needs to be performed with build ???? +# create_grid_tables.sh must be run before running this script. + +from shutil import copytree, move, copy +from subprocess import Popen, PIPE +from thread import start_new_thread, allocate_lock +import sys +from os.path import exists, isdir +from os import mkdir +from time import sleep, time +import h5py +import struct + +# this is generally a disk bound process so more threads won't help unless the disk is fast +numThreads = 1 +# setting too many records at once causes the exec to psql to fail because of the long arg list +maxRecords = 200 + +postgresCmd = "psql -U awips -d metadata -t -q -A -c " +hdf5loc = "/awips2/edex/data/hdf5/" + +quadrantGrids = ["ENSEMBLE37", "ENSEMBLE38", "ENSEMBLE39", "ENSEMBLE40", + "ECMF1", "ECMF2", "ECMF3", "ECMF4", "ECMF5", "ECMF6", "ECMF7", "ECMF8", + "UKMET40", "UKMET39", "UKMET38", "UKMET37"] + +akGrids = ["MOSGuide-AK", "AK-NamDNG5","AK-RTMA", "AKWAVE239", "AKwave10", "AKwave4", "HiResW-NMM-AK", "HiResW-ARW-AK", + "ETA242", "mesoEta217", "mesoEta216","ETA207", "AVN203", "MRF203", "GFS160"] + +prGrids = ["HiResW-NMM-SJU", "HiResW-ARW-SJU", "PR-NamDNG5", "PR-RTMA", "MRF205", "GFS161", "mesoEta237"] + +hiGrids = ["HI-NamDNG5", "HI-RTMA", "HiResW-NMM-HI", "HiResW-ARW-HI", "MRF204", "AVN225", "GFS254", "SREF243"] + +guGrids = ["HiResW-NMM-GU", "HiResW-ARW-GU"] + +blacklistGrids = {"quadrant grids which have already been converted in an assembled format":quadrantGrids, + "grids over Alaska":akGrids, "grids over Puerto Rico":prGrids, + "grids over Hawaii and the Pacific Region":hiGrids, "grids over Guam":guGrids} + + +parameters = {} +models = [] +gridinfo_seq = [] +models_lock = allocate_lock() + + +def queryPostgres(sql): + result = Popen(postgresCmd + "\"" + sql + "\"", stdout=PIPE, shell=True) + retVal = [] + for line in result.stdout: + retVal.append(line.strip().split("|")) + return retVal + +def convertModel(modelName): + sqlTime = 0 + hdfTime = 0 + totTime = 0 + totTime -= time() + print modelName, "Loading existing grid_info" + infoMap = loadGridInfo(modelName) + infoSql = None + print modelName, "Querying grib database" + rows = queryPostgres("select grib.forecasttime, grib.reftime, grib.utilityflags, grib.rangeend,grib.rangestart, grib.inserttime, grib.datauri, gridcoverage.id, grib_models.level_id, grib_models.location_id from grib, grib_models, gridcoverage, level where grib.modelinfo_id = grib_models.id and grib_models.location_id = gridcoverage.id and grib_models.level_id = level.id and grib_models.modelName = '%s' order by grib.forecasttime, grib.reftime, level.masterlevel_name" % modelName) + print modelName, "Converting %d records" % len(rows) + gridSql = None + lastFile = None + gribFiles = hdf5loc + "grib/" + modelName + "/" + gridFiles = hdf5loc + "grid/" + modelName + "/" + if not(isdir(hdf5loc + "grid/")): + mkdir(hdf5loc + "grid/") + if not(isdir(gridFiles)): + mkdir(gridFiles) + count = 0; + for row in rows: + gribforecasttime = row[0] + gribreftime = row[1] + gributilityflags = row[2] + gribrangeend = row[3] + gribrangestart = row[4] + gribinserttime = row[5] + gribdatauri = row[6] + gridcoverageid = row[7] + gribmodelslevelid = row[8] + gribmodelslocationid = row[9] + datauriparts = gribdatauri.split("/") + datatime = datauriparts[2] + paramabbrev = datauriparts[4] + masterlevel = datauriparts[5] + levelone = datauriparts[6] + leveltwo = datauriparts[7] + pert = datauriparts[9] + version = datauriparts[10] + secondaryId = "null" + if version != "0": + secondaryId = "Version" + version + ensembleId = convertPert(pert) + newdatauri = "/grid/" + datatime + "/" + modelName + "/" + secondaryId + "/" + ensembleId + "/" + gridcoverageid + "/" + paramabbrev + "/" + masterlevel + "/" + levelone + "/" + leveltwo + hdfTime -= time() + try: + forecast = int(gribforecasttime)/3600 + prevgrp = gribdatauri + newgrp = newdatauri + dataset="Data" + if paramabbrev.startswith("static"): + prevgrp = "/" + newgrp = "/" + gridcoverageid + dataset=paramabbrev + filebase = "/%s-%s-FH-%.3d.h5" % (modelName, gribreftime.split(":")[0].replace(" ", "-"), forecast) + hdf5file = gridFiles + masterlevel + filebase + if not(paramabbrev.startswith("static")) or forecast == 0: + if lastFile != None and lastFile.filename != hdf5file: + #print "Closing", lastFile.filename + lastFile.close() + lastFile = None + if lastFile == None: + if not(exists(hdf5file)): + t0 = time() + if not(isdir(gridFiles + masterlevel)): + mkdir(gridFiles + masterlevel) + move(gribFiles + masterlevel + filebase, gridFiles + masterlevel) + hdfTime -= (time() - t0) + #print "Opening", hdf5file + lastFile = h5py.File(hdf5file) + copyH5(lastFile, prevgrp, newgrp, dataset) + except: + print modelName, "Error", gribdatauri + print sys.exc_info()[1] + hdfTime += time() + continue + hdfTime += time() + infokey = modelName + ":::" + secondaryId + ":::" + ensembleId + ":::" + gribmodelslevelid + ":::" + gribmodelslocationid + ":::" + paramabbrev + infoid = infoMap.get(infokey) + if infoid == None: + infoid = nextGridInfoSeq() + infoMap[infokey] = infoid + if secondaryId == "null": + secondaryId = "NULL" + else: + secondaryId = "\'" + secondaryId + "\'" + if ensembleId == "null": + ensembleId = "NULL" + else: + ensembleId = "\'" + ensembleId + "\'" + if infoSql == None: + infoSql = "insert into grid_info (id, datasetid, secondaryid, ensembleid, level_id, location_id, parameter_abbreviation) values " + else: + infoSql = infoSql + ", " + infoSql = infoSql + ("(%d, '%s', %s, %s, %s, %s, '%s')" % (infoid, modelName, secondaryId, ensembleId, gribmodelslevelid, gribmodelslocationid, paramabbrev)) + if gridSql == None: + gridSql = "insert into grid (id, forecasttime, reftime, utilityflags, rangeend, rangestart, datauri, inserttime, info_id) values " + else: + gridSql = gridSql + ", " + gridSql = gridSql + ("(nextval(\'hibernate_sequence\'), %s, '%s', '%s', '%s', '%s', '%s', '%s', %d)" % (gribforecasttime, gribreftime, gributilityflags, gribrangeend, gribrangestart, newdatauri, gribinserttime, infoid)) + count += 1 + if count % maxRecords == 0: + print modelName, "Commiting %d grid records %d%%" % (maxRecords,100*count/len(rows)) + sqlTime -= time() + if infoSql != None: + #print infoSql + queryPostgres(infoSql) + infoSql = None + if gridSql != None: + #print gridSql + queryPostgres(gridSql) + gridSql = None + sqlTime += time() + print modelName, "Commiting remaining grid records" + sqlTime -= time() + if infoSql != None: + #print infoSql + queryPostgres(infoSql) + if gridSql != None: + #print gridSql + queryPostgres(gridSql) + if lastFile != None: + lastFile.close() + sqlTime += time() + totTime += time() + print modelName, "Time in sql commits = %ds" % (sqlTime) + print modelName, "Time in hdf5 links = %ds" % (hdfTime) + print modelName, "Total process Time = %ds" % (totTime) + +def loadGridInfo(modelName): + infoMap = {} + for row in queryPostgres("select distinct id, datasetid, secondaryid, ensembleid, level_id, location_id, parameter_abbreviation, id from grid_info where datasetid = '%s'" % (modelName)): + infokey = row[1] + ":::" + row[2] + ":::" + row[3] + ":::" + row[4] + ":::" + row[5] + ":::" + row[6] + infoMap[infokey] = int(row[0]) + return infoMap + +def nextGridInfoSeq(): + if len(gridinfo_seq) == 0: + # The number of ids we need per model varies wildly from 1 to 263, + # but on average 50 per model will grab enough ids that we don't + # ever need to go back to the db, although if we do it's not really + # a big deal, this is just trying to avoid excessive trips back + n = max(len(models),1)*50 + for row in queryPostgres("select nextval('gridinfo_seq') from generate_series(1,%d);" % (n)): + gridinfo_seq.append(int(row[0])) + return gridinfo_seq.pop() + +def convertPert(pert): + if pert == "1": + return "ctl1" + elif pert == "2": + return "ctl2" + elif pert == "3": + return "n1" + elif pert == "4": + return "p1" + elif pert == "5": + return "n2" + elif pert == "6": + return "p2" + elif pert == "7": + return "n3" + elif pert == "8": + return "p3" + elif pert == "9": + return "n4" + elif pert == "10": + return "p4" + elif pert == "11": + return "n5" + elif pert == "12": + return "p5" + return "null" + +def copyH5(h5, gribdatauri, griddatauri, dataset="Data"): + gribgrp = h5['/'] + gridgrp = gribgrp + for part in gribdatauri.split('/'): + if part: + gribgrp = gribgrp[part] + for part in griddatauri.split('/'): + if part: + gridgrp = gridgrp.require_group(part) + if not(dataset in gridgrp.keys()): + plists = {'lcpl': gribgrp[dataset]._lcpl, 'lapl': gribgrp[dataset]._lapl} + plists['lcpl'].set_create_intermediate_group(False) + h5py.h5o.link(gribgrp[dataset].id, gridgrp.id, dataset, **plists) + + +def processAllParameters(): + print "Populating parameter table from grib_models" + sql = None + c = 0 + for row in queryPostgres("select distinct abbreviation, name, unit from parameter"): + p = {"abbreviation":row[0], "name":row[1], "unit":row[2]} + parameters[row[0]] = p + for row in queryPostgres("select distinct parameterabbreviation, parametername, parameterunit from grib_models"): + if row[0] in parameters: + continue + p = {"abbreviation":row[0], "name":row[1], "unit":row[2]} + parameters[row[0]] = p + if sql == None: + sql = "insert into parameter (abbreviation, name, unit) values " + else: + sql = sql + ", " + c += 1 + sql = sql + ("('%s', '%s', '%s')" % (row[0], row[1], row[2])) + if sql != None: + queryPostgres(sql) + print "Done populating parameter table, %d new rows added" % (c) + +def processModels(): + while(True): + models_lock.acquire() + if len(models) == 0: + global numThreads + numThreads -= 1 + models_lock.release() + break + model = models.pop() + models_lock.release() + try: + convertModel(model) + except: + print model, "Error model aborted" + print sys.exc_info()[1] + +def loadAll(): + global models + print "This script will convert grib data in edex to use the new grid format" + print "You provided no arguments so this will convert almost all data." + print "To convert only specific models you can cancel and list models as arguments" + print "" + for row in queryPostgres("select distinct modelname from grib_models"): + models.append(row[0]) + print "To save time some grid models will be skipped, these grids will not be" + print "available until the next model run is ingested. If you would like to convert any" + print "of these models simply run the conversion script again with a list of models as arguments." + print "" + bad = [] + good = [] + for model in models: + if model.startswith("UnknownModel"): + bad.append(model) + else: + good.append(model) + if len(bad) > 0: + print "These Unknown Models will not be converted:", + for model in bad: + print "\"" + model + "\"", + print "" + print "" + models = good + for key in blacklistGrids: + blacklist = blacklistGrids[key] + bad = [] + good = [] + for model in models: + if model in blacklist: + bad.append(model) + else: + good.append(model) + if len(bad) > 0: + print "These " + key + " will not be converted:", + for model in bad: + print "\"" + model + "\"", + print "" + print "" + models = good + print "To continue converting the data Press Enter or Ctrl-C to cancel." + raw_input() + +def check_table(tablename): + rows = queryPostgres("SELECT count(*) FROM information_schema.tables WHERE table_name = '" + tablename + "';") + if(rows[0][0] != "1"): + print tablename, "table does not exist, please create tables" + sys.exit(1) + +if __name__ == '__main__': + t = time() + check_table("grid") + check_table("grid_info") + check_table("parameter") + if len(sys.argv) == 1: + loadAll() + else: + for i in range(1,len(sys.argv)): + models.append(sys.argv[i]) + processAllParameters() + print "Starting %d threads to process models" % (numThreads) + for i in range(numThreads-1): + start_new_thread(processModels, ()) + processModels() + while numThreads > 0: + sleep(5) + print "Total Conversion time %ds" % (time() - t) \ No newline at end of file diff --git a/deltaScripts/unified_grid/copy_grib_purge_rules.sh b/deltaScripts/unified_grid/copy_grib_purge_rules.sh new file mode 100644 index 0000000000..14972b33b0 --- /dev/null +++ b/deltaScripts/unified_grid/copy_grib_purge_rules.sh @@ -0,0 +1,35 @@ +#!/bin/bash +# This script will copy any grib purge rules to a equivalent grid purge rules file +# +# This update needs to be performed with build ???. + +echo "" +echo "Press Enter to perform the updates Ctrl-C to quit." +read done + +IFS=$'\n' +files=`find /awips2/edex/data/utility/common_static/site/*/purge/gribPurgeRules.xml` + +if [ $? -ne 0 ]; then +echo "No site level grib purge files found!" +exit 0 +fi + +for f in $files; do + nf=${f/grib/grid} + echo Copying $f to $nf + cp $f $nf + # level + sed -n 's/modelInfo\.level\.levelonevalue=/info.level.levelonevalue=/g;p;' -i $nf + sed -n 's/modelInfo\.level\.leveltwovalue=/info.level.leveltwovalue=/g;p;' -i $nf + sed -n 's/modelInfo\.level\.masterLevel.name=/info.level.masterLevel.name=/g;p;' -i $nf + # parameter + sed -n 's/modelInfo\.parameterAbbreviation=/info.parameter.abbreviation=/g;p;' -i $nf + # dataset + sed -n 's/modelInfo\.modelName=/info.datasetId=/g;p;' -i $nf +done + + + +echo "INFO: The update finished successfully." +exit 0 diff --git a/deltaScripts/unified_grid/create_grid_tables.sh b/deltaScripts/unified_grid/create_grid_tables.sh new file mode 100644 index 0000000000..f5f56c57af --- /dev/null +++ b/deltaScripts/unified_grid/create_grid_tables.sh @@ -0,0 +1,151 @@ +#!/bin/bash +# This script will add create tables for the grid plugin +# +# This needs to be performed with build ???? +# + +PSQL="/awips2/psql/bin/psql" +GRID_COMMAND="CREATE TABLE grid +( + id integer NOT NULL, + forecasttime integer, + reftime timestamp without time zone, + utilityflags character varying(255), + rangeend timestamp without time zone, + rangestart timestamp without time zone, + datauri character varying(255), + inserttime timestamp without time zone, + info_id integer, + CONSTRAINT grid_pkey PRIMARY KEY (id), + CONSTRAINT fk308b46a3c100e9 FOREIGN KEY (info_id) + REFERENCES grid_info (id) MATCH SIMPLE + ON UPDATE NO ACTION ON DELETE NO ACTION, + CONSTRAINT grid_datauri_key UNIQUE (datauri) +) +WITH (OIDS=FALSE); +ALTER TABLE grid OWNER TO awips; + +CREATE INDEX "gridDatasetReftime_idx" + ON grid + USING btree + (info_id, reftime, forecasttime); + +CREATE INDEX gridpersistableplugindataobjectdatauri_idx + ON grid + USING btree + (datauri); + +CREATE INDEX gridpersistableplugindataobjectfcsttimeindex + ON grid + USING btree + (forecasttime); + +CREATE INDEX gridpersistableplugindataobjectinserttimeindex + ON grid + USING btree + (inserttime); + +CREATE INDEX gridpersistableplugindataobjectreftimeindex + ON grid + USING btree + (reftime); +" + +INFO_SEQ_COMMAND="CREATE SEQUENCE gridinfo_seq + INCREMENT 1 + MINVALUE 1 + MAXVALUE 9223372036854775807 + START 91 + CACHE 1; +ALTER TABLE gridinfo_seq OWNER TO awips;" + +INFO_COMMAND="CREATE TABLE grid_info +( + id integer NOT NULL, + datasetid character varying(255), + ensembleid character varying(255), + secondaryid character varying(255), + level_id bigint, + location_id integer, + parameter_abbreviation character varying(255), + CONSTRAINT grid_info_pkey PRIMARY KEY (id), + CONSTRAINT fk4c4dae072d36f480 FOREIGN KEY (level_id) + REFERENCES "level" (id) MATCH SIMPLE + ON UPDATE NO ACTION ON DELETE NO ACTION, + CONSTRAINT fk4c4dae0746b2bf12 FOREIGN KEY (location_id) + REFERENCES gridcoverage (id) MATCH SIMPLE + ON UPDATE NO ACTION ON DELETE NO ACTION, + CONSTRAINT fk4c4dae076765a9e7 FOREIGN KEY (parameter_abbreviation) + REFERENCES parameter (abbreviation) MATCH SIMPLE + ON UPDATE NO ACTION ON DELETE NO ACTION +) +WITH (OIDS=FALSE); +ALTER TABLE grid_info OWNER TO awips; + +CREATE INDEX "gridinfoNameParamLevel_idx" + ON grid_info + USING btree + (datasetid, parameter_abbreviation, level_id); + +CREATE INDEX "gridinfoSecondryId_idx" + ON grid_info + USING btree + (secondaryid);" + +PARAM_COMMAND="CREATE TABLE parameter +( + abbreviation character varying(255) NOT NULL, + "name" character varying(255) NOT NULL, + unit character varying(255), + CONSTRAINT parameter_pkey PRIMARY KEY (abbreviation) +) +WITH (OIDS=FALSE); +ALTER TABLE parameter OWNER TO awips;" + +SQL_COMMAND_REGISTER="insert into plugin_info (name, database, initialized, tablename) VALUES('grid', 'metadata', TRUE, 'grid'), ('parameter', 'metadata', TRUE, 'parameter');" + + +if [ ! -f ${PSQL} ]; then +echo "ERROR: The PSQL executable does not exist - ${PSQL}." +echo "FATAL: Update Failed!" +exit 1 +fi + +echo "" +echo "Press Enter to perform the updates Ctrl-C to quit." +read done + +${PSQL} -U awips -d metadata -c "${PARAM_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${INFO_SEQ_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + + +${PSQL} -U awips -d metadata -c "${INFO_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${GRID_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_REGISTER}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +echo "INFO: The update was successfully applied." + +exit 0 \ No newline at end of file diff --git a/deltaScripts/unified_grid/register_grid_coverage.sh b/deltaScripts/unified_grid/register_grid_coverage.sh new file mode 100644 index 0000000000..11c55c029f --- /dev/null +++ b/deltaScripts/unified_grid/register_grid_coverage.sh @@ -0,0 +1,67 @@ +#!/bin/bash +# This script will add register the gridcoverage plugin, which was previously part of grib +# +# This needs to be performed with build ???? +# + +PSQL="/awips2/psql/bin/psql" +SQL_COMMAND_CHECK="select * FROM gridcoverage LIMIT 1;" +SQL_COMMAND_REGISTER="insert into plugin_info (name, database, initialized, tablename) VALUES('gridcoverage', 'metadata', TRUE, 'gridcoverage');" +SQL_COMMAND_SEQ="CREATE SEQUENCE gridcoverage_seq INCREMENT 1 MINVALUE 1 MAXVALUE 9223372036854775807 START 1 CACHE 1; ALTER TABLE gridcoverage_seq OWNER TO awips;" +SQL_COMMAND_UPDATE_ID="update gridcoverage set id=nextval('gridcoverage_seq');" +SQL_COMMAND_ALTER_NAME_DESC="ALTER TABLE gridcoverage DROP COLUMN description, ALTER COLUMN name TYPE character varying(255);" +SQL_COMMAND_UPDATE_NAME="update gridcoverage g1 set name = 'Subgrid-' || g2.id from gridcoverage g2 where g1.name like '%-SubGrid-%' and g2.name = split_part(g1.name, '-',1);" + +if [ ! -f ${PSQL} ]; then +echo "ERROR: The PSQL executable does not exist - ${PSQL}." +echo "FATAL: Update Failed!" +exit 1 +fi + +echo "" +echo "Press Enter to perform the updates Ctrl-C to quit." +read done + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_CHECK}" > /dev/null +if [ $? -ne 0 ]; then +echo "WARN: gridcoverage table does not exist so we are not registering the plugin" +exit 0 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_REGISTER}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_SEQ}" +if [ $? -ne 0 ]; then +echo "FATAL: unable to create gridcoverage_seq" +exit 1 +fi + +FK=`${PSQL} -U awips -d metadata -c "\d grib_models" | grep gridcoverage | awk -F"\"" '{print $2}'` +if [ -z "$FK" ]; then +echo "FATAL: unable to find foreign key constraint on grib_models" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "ALTER TABLE grib_models DROP CONSTRAINT ${FK}, ADD CONSTRAINT ${FK} FOREIGN KEY (location_id) REFERENCES gridcoverage (id) MATCH SIMPLE ON UPDATE CASCADE ON DELETE NO ACTION;" +if [ $? -ne 0 ]; then +echo "FATAL: unable to modify foreign key constraint on grib_models" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_UPDATE_ID}" +if [ $? -ne 0 ]; then +echo "FATAL: unable to update gridcoverage ids" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_ALTER_NAME_DESC}" +if [ $? -ne 0 ]; then +echo "WARN: unable to remove description column from gridcoverage table" +fi + +echo "INFO: The update was successfully applied." +exit 0 diff --git a/deltaScripts/unified_grid/update_D2D_bundles.sh b/deltaScripts/unified_grid/update_D2D_bundles.sh new file mode 100644 index 0000000000..a9b9f09d8d --- /dev/null +++ b/deltaScripts/unified_grid/update_D2D_bundles.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# This script will update any D2D bundle files +# to use grid data in place of grib +# +# This update needs to be performed with build ???. +# This update is only for edex servers which host the cave localization files + + +echo "" +echo "Press Enter to perform the updates Ctrl-C to quit." +read done + +IFS=$'\n' +files=`find /awips2/edex/data/utility/cave_static/*/*/bundles/ -iname '*.xml'` + +if [ $? -ne 0 ]; then +echo "No bundle files found." +exit 1 +fi + +MY_DIR=`dirname $0` + +for f in $files; do + bash $MY_DIR/update_saved_display.sh $f +done + + + +echo "INFO: The update finished successfully." +exit 0 diff --git a/deltaScripts/unified_grid/update_D2D_procedures.sh b/deltaScripts/unified_grid/update_D2D_procedures.sh new file mode 100644 index 0000000000..95070ec82d --- /dev/null +++ b/deltaScripts/unified_grid/update_D2D_procedures.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# This script will update any D2D procedures files +# to use grid data in place of grib +# +# This update needs to be performed with build ???. +# This update is only for edex servers which host the cave localization files + +echo "" +echo "Press Enter to perform the updates Ctrl-C to quit." +read done + +IFS=$'\n' +files=`ls /awips2/edex/data/utility/cave_static/*/*/procedures/*.xml` + +if [ $? -ne 0 ]; then +echo "No procedures found" +exit 1 +fi + +MY_DIR=`dirname $0` + +for f in $files; do + bash $MY_DIR/update_saved_display.sh $f +done + +echo "INFO: The update finished successfully." +exit 0 diff --git a/deltaScripts/unified_grid/update_FFMP_Source.sh b/deltaScripts/unified_grid/update_FFMP_Source.sh new file mode 100644 index 0000000000..d0d074e086 --- /dev/null +++ b/deltaScripts/unified_grid/update_FFMP_Source.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# This script will update any FFMPSourceConfig.xml files +# to use grid data in place of grib +# +# This update needs to be performed with build ???. +# This update is only for edex servers which host FFMPSourceConfig.xml files + +echo "" +echo "Press Enter to perform the updates Ctrl-C to quit." +read done + +files=`find /awips2/edex/data/utility/common_static -iname FFMPSourceConfig.xml` + +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +for f in $files; do + echo Updating $f + bf=$f.bak.`date +%m%d%y` + cp $f $bf + # reconstruct data uris from grib to grid + awk -F '/' ' + /\/grib/ {print $1 "/grid/" $3 "/" $4 "/.*/.*/.*/" $5 "/" $6 "/" $7 "/" $8 "/" $11 "/" $12; next;} + {gsub(/grib<\/plugin>/,"grid"); print; } + ' $bf > $f +done + + + +echo "INFO: The update finished successfully." +exit 0 diff --git a/deltaScripts/unified_grid/update_saved_display.sh b/deltaScripts/unified_grid/update_saved_display.sh new file mode 100644 index 0000000000..4519102b04 --- /dev/null +++ b/deltaScripts/unified_grid/update_saved_display.sh @@ -0,0 +1,55 @@ +#!/bin/bash +# This script will update any saved displays from the grib format to the grid format +# +# This update needs to be performed with build ???. +# This update only needs to be run if there are saved displays being stored outside of localization. + + +if [ $# -eq 0 ]; then + echo "Please provide a list of saved displays to update." +fi + +IFS=$'\n' + +for f in "$@"; do + echo Updating $f + #bf=$f.bak.`date +%m%d%y` + #cp $f $bf + # its probably not efficient to execute sed 20 times but its not slow... + # replace perturbationNumbers with ensmble ids + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)1\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2ctl1\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)2\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2ctl2\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)3\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2n1\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)4\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2p1\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)5\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2n2\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)6\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2p2\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)7\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2n3\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)8\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2p3\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)9\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2n4\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)10\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2p4\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)11\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2n5\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)12\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.ensembleId\2p5\3/g;p;}' -i $f + # handle grid version + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)\([0-9]\{1,2\}\)\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1info.secondaryId\2Version\3\4/g;p;}' -i $f + # level + sed -n 's/key="modelInfo\.level\.levelonevalue"/key="info.level.levelonevalue"/g;p;' -i $f + sed -n 's/key="modelInfo\.level\.leveltwovalue"/key="info.level.leveltwovalue"/g;p;' -i $f + sed -n 's/key="modelInfo\.level\.masterLevel.name"/key="info.level.masterLevel.name"/g;p;' -i $f + # parameter + sed -n 's/key="modelInfo\.parameterAbbreviation"/key="info.parameter.abbreviation"/g;p;' -i $f + # dataset + sed -n 's/key="modelInfo\.modelName"/key="info.datasetId"/g;p;' -i $f + #plugin name + sed -n 's/constraintValue="grib"/constraintValue="grid"/g;p;' -i $f + + #Also need to map the productIdentifierKey in best res resource data. + sed -n 's/productIdentifierKey="modelInfo\.level\.levelonevalue"/productIdentifierKey="info.level.levelonevalue"/g;p;' -i $f + sed -n 's/productIdentifierKey="modelInfo\.level\.leveltwovalue"/productIdentifierKey="info.level.leveltwovalue"/g;p;' -i $f + sed -n 's/productIdentifierKey="modelInfo\.level\.masterLevel.name"/productIdentifierKey="info.level.masterLevel.name"/g;p;' -i $f + sed -n 's/productIdentifierKey="modelInfo\.modelName"/productIdentifierKey="info.datasetId"/g;p;' -i $f + sed -n 's/productIdentifierKey="modelInfo\.parameterAbbreviation"/productIdentifierKey="info.parameter.abbreviation"/g;p;' -i $f + + + #diff $f $bf > /dev/null + #if [ $? -eq 0 ]; then rm $bf; echo "No Changes"; fi +done diff --git a/deltaScripts/unified_grid_rollback/convert_grib_data.py b/deltaScripts/unified_grid_rollback/convert_grib_data.py new file mode 100644 index 0000000000..afb14740d9 --- /dev/null +++ b/deltaScripts/unified_grid_rollback/convert_grib_data.py @@ -0,0 +1,252 @@ +#!/usr/bin/python +# This script will add register the gridcoverage plugin, which was previosly part of grib +# +# This needs to be performed with build ???? +# create_grid_tables.sh must be run before running this script. + +from shutil import copytree, move, copy +from subprocess import Popen, PIPE +from thread import start_new_thread, allocate_lock +import sys +from os.path import exists, isdir +from os import mkdir +from time import sleep, time +import h5py +import struct + +# this is generally a disk bound process so more threads won't help unless the disk is fast +numThreads = 1 +# setting too many records at once causes the exec to psql to fail because of the long arg list +maxRecords = 200 + +postgresCmd = "psql -U awips -d metadata -t -q -A -c " +hdf5loc = "/awips2/edex/data/hdf5/" + +quadrantGrids = ["ENSEMBLE37", "ENSEMBLE38", "ENSEMBLE39", "ENSEMBLE40", + "ECMF1", "ECMF2", "ECMF3", "ECMF4", "ECMF5", "ECMF6", "ECMF7", "ECMF8", + "UKMET40", "UKMET39", "UKMET38", "UKMET37"] + +akGrids = ["MOSGuide-AK", "AK-NamDNG5","AK-RTMA", "AKWAVE239", "AKwave10", "AKwave4", "HiResW-NMM-AK", "HiResW-ARW-AK", + "ETA242", "mesoEta217", "mesoEta216","ETA207", "AVN203", "MRF203", "GFS160"] + +prGrids = ["HiResW-NMM-SJU", "HiResW-ARW-SJU", "PR-NamDNG5", "PR-RTMA", "MRF205", "GFS161", "mesoEta237"] + +hiGrids = ["HI-NamDNG5", "HI-RTMA", "HiResW-NMM-HI", "HiResW-ARW-HI", "MRF204", "AVN225", "GFS254", "SREF243"] + +guGrids = ["HiResW-NMM-GU", "HiResW-ARW-GU"] + +blacklistGrids = {"quadrant grids which have already been converted in an assembled format":quadrantGrids, + "grids over Alaska":akGrids, "grids over Puerto Rico":prGrids, + "grids over Hawaii and the Pacific Region":hiGrids, "grids over Guam":guGrids} + + +parameters = {} +models = [] +models_lock = allocate_lock() + + +def queryPostgres(sql): + result = Popen(postgresCmd + "\"" + sql + "\"", stdout=PIPE, shell=True) + retVal = [] + for line in result.stdout: + retVal.append(line.strip().split("|")) + return retVal + +def convertModel(modelName): + hdfTime = 0 + totTime = 0 + totTime -= time() + print modelName, "Loading existing grid_info" + print modelName, "Querying grib database" + rows = queryPostgres("select grib.forecasttime, grib.reftime, grib.datauri, gridcoverage.id from grib, grib_models, gridcoverage, level where grib.modelinfo_id = grib_models.id and grib_models.location_id = gridcoverage.id and grib_models.level_id = level.id and grib_models.modelName = '%s' order by grib.forecasttime, grib.reftime, level.masterlevel_name" % modelName) + print modelName, "Converting %d records" % len(rows) + gridSql = None + lastFile = None + gribFiles = hdf5loc + "grib/" + modelName + "/" + gridFiles = hdf5loc + "grid/" + modelName + "/" + if not(isdir(hdf5loc + "grib/")): + mkdir(hdf5loc + "grib/") + if not(isdir(gribFiles)): + mkdir(gribFiles) + count = 0; + for row in rows: + gribforecasttime = row[0] + gribreftime = row[1] + gribdatauri = row[2] + gridcoverageid = row[3] + datauriparts = gribdatauri.split("/") + datatime = datauriparts[2] + paramabbrev = datauriparts[4] + masterlevel = datauriparts[5] + levelone = datauriparts[6] + leveltwo = datauriparts[7] + pert = datauriparts[9] + version = datauriparts[10] + secondaryId = "null" + if version != "0": + secondaryId = "Version" + version + ensembleId = convertPert(pert) + newdatauri = "/grid/" + datatime + "/" + modelName + "/" + secondaryId + "/" + ensembleId + "/" + gridcoverageid + "/" + paramabbrev + "/" + masterlevel + "/" + levelone + "/" + leveltwo + hdfTime -= time() + try: + forecast = int(gribforecasttime)/3600 + prevgrp = gribdatauri + newgrp = newdatauri + dataset="Data" + if paramabbrev.startswith("static"): + prevgrp = "/"+ gridcoverageid + newgrp = "/" + dataset=paramabbrev + if not(paramabbrev.startswith("static")) or forecast == 0: + filebase = "/%s-%s-FH-%.3d.h5" % (modelName, gribreftime.split(":")[0].replace(" ", "-"), forecast) + hdf5file = gribFiles + masterlevel + filebase + if lastFile != None and lastFile.filename != hdf5file: + #print "Closing", lastFile.filename + lastFile.close() + lastFile = None + if lastFile == None: + if not(exists(hdf5file)): + t0 = time() + if not(isdir(gribFiles + masterlevel)): + mkdir(gribFiles + masterlevel) + move(gridFiles + masterlevel + filebase, gribFiles + masterlevel) + hdfTime -= (time() - t0) + #print "Opening", hdf5file + lastFile = h5py.File(hdf5file) + copyH5(lastFile, newgrp, prevgrp, dataset) + except: + print modelName, "Error", gribdatauri + print sys.exc_info()[1] + hdfTime += time() + continue + hdfTime += time() + count += 1 + if count % maxRecords == 0: + print modelName, "Processed %d grid records %d%%" % (maxRecords,100*count/len(rows)) + totTime += time() + print modelName, "Time in hdf5 links = %ds" % (hdfTime) + print modelName, "Total process Time = %ds" % (totTime) + +def convertPert(pert): + if pert == "1": + return "ctl1" + elif pert == "2": + return "ctl2" + elif pert == "3": + return "n1" + elif pert == "4": + return "p1" + elif pert == "5": + return "n2" + elif pert == "6": + return "p2" + elif pert == "7": + return "n3" + elif pert == "8": + return "p3" + elif pert == "9": + return "n4" + elif pert == "10": + return "p4" + elif pert == "11": + return "n5" + elif pert == "12": + return "p5" + return "null" + +def copyH5(h5, gribdatauri, griddatauri, dataset="Data"): + gribgrp = h5['/'] + gridgrp = gribgrp + for part in gribdatauri.split('/'): + if part: + gribgrp = gribgrp[part] + for part in griddatauri.split('/'): + if part: + gridgrp = gridgrp.require_group(part) + if not(dataset in gridgrp.keys()): + plists = {'lcpl': gribgrp[dataset]._lcpl, 'lapl': gribgrp[dataset]._lapl} + plists['lcpl'].set_create_intermediate_group(False) + h5py.h5o.link(gribgrp[dataset].id, gridgrp.id, dataset, **plists) + +def processModels(): + while(True): + models_lock.acquire() + if len(models) == 0: + global numThreads + numThreads -= 1 + models_lock.release() + break + model = models.pop() + models_lock.release() + try: + convertModel(model) + except: + print model, "Error model aborted" + print sys.exc_info()[1] + +def loadAll(): + global models + print "This script will convert grid data in edex to use the old grib format" + print "You provided no arguments so this will convert almost all data." + print "To convert only specific models you can cancel and list models as arguments" + print "" + for row in queryPostgres("select distinct modelname from grib_models"): + models.append(row[0]) + print "To save time some grid models will be skipped, these grids will not be" + print "available until the next model run is ingested. If you would like to convert any" + print "of these models simply run the conversion script again with a list of models as arguments." + print "" + bad = [] + good = [] + for model in models: + if model.startswith("UnknownModel"): + bad.append(model) + else: + good.append(model) + if len(bad) > 0: + print "These Unknown Models will not be converted:", + for model in bad: + print "\"" + model + "\"", + print "" + print "" + models = good + for key in blacklistGrids: + blacklist = blacklistGrids[key] + bad = [] + good = [] + for model in models: + if model in blacklist: + bad.append(model) + else: + good.append(model) + if len(bad) > 0: + print "These " + key + " will not be converted:", + for model in bad: + print "\"" + model + "\"", + print "" + print "" + models = good + print "To continue converting the data Press Enter or Ctrl-C to cancel." + raw_input() + +def check_table(tablename): + rows = queryPostgres("SELECT count(*) FROM information_schema.tables WHERE table_name = '" + tablename + "';") + if(rows[0][0] != "1"): + print tablename, "table does not exist, please create tables" + sys.exit(1) + +if __name__ == '__main__': + t = time() + check_table("grib") + if len(sys.argv) == 1: + loadAll() + else: + for i in range(1,len(sys.argv)): + models.append(sys.argv[i]) + print "Starting %d threads to process models" % (numThreads) + for i in range(numThreads-1): + start_new_thread(processModels, ()) + processModels() + while numThreads > 0: + sleep(5) + print "Total Conversion time %ds" % (time() - t) \ No newline at end of file diff --git a/deltaScripts/unified_grid_rollback/copy_grib_purge_rules.sh b/deltaScripts/unified_grid_rollback/copy_grib_purge_rules.sh new file mode 100644 index 0000000000..29babfbc4d --- /dev/null +++ b/deltaScripts/unified_grid_rollback/copy_grib_purge_rules.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# This script will copy any grib purge rules to a equivalent grid purge rules file +# +# This update needs to be performed with build ???. + +echo "" +echo "Press Enter to undo the updates Ctrl-C to quit." +read done + +IFS=$'\n' +files=`find /awips2/edex/data/utility/common_static/site/*/purge/gridPurgeRules.xml` + +if [ $? -ne 0 ]; then +echo "No site level grid purge files found!" +exit 0 +fi + +for f in $files; do + echo Deleting $f + rm $f +done + +echo "INFO: The update was successfully removed." +exit 0 diff --git a/deltaScripts/unified_grid_rollback/create_grid_tables.sh b/deltaScripts/unified_grid_rollback/create_grid_tables.sh new file mode 100644 index 0000000000..9f4163c401 --- /dev/null +++ b/deltaScripts/unified_grid_rollback/create_grid_tables.sh @@ -0,0 +1,58 @@ +#!/bin/bash +# This script will add create tables for the grid plugin +# +# This needs to be performed with build ???? +# + +PSQL="/awips2/psql/bin/psql" +GRID_COMMAND="DROP TABLE grid;" +INFO_SEQ_COMMAND="DROP SEQUENCE gridinfo_seq;" +INFO_COMMAND="DROP TABLE grid_info;" +PARAM_COMMAND="DROP TABLE parameter;" +SQL_COMMAND_REGISTER="delete from plugin_info where name = 'grid' OR name = 'parameter';" + + +if [ ! -f ${PSQL} ]; then +echo "ERROR: The PSQL executable does not exist - ${PSQL}." +echo "FATAL: Update Failed!" +exit 1 +fi + +echo "" +echo "Press Enter to undo the updates Ctrl-C to quit." +read done + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_REGISTER}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${GRID_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${INFO_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${INFO_SEQ_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${PARAM_COMMAND}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + + +echo "INFO: The update was successfully applied." + +exit 0 \ No newline at end of file diff --git a/deltaScripts/unified_grid_rollback/register_grid_coverage.sh b/deltaScripts/unified_grid_rollback/register_grid_coverage.sh new file mode 100644 index 0000000000..aff1aa0e72 --- /dev/null +++ b/deltaScripts/unified_grid_rollback/register_grid_coverage.sh @@ -0,0 +1,54 @@ +#!/bin/bash +# This script will add register the gridcoverage plugin, which was previously part of grib +# +# This needs to be performed with build ???? +# + +PSQL="/awips2/psql/bin/psql" +SQL_COMMAND_CHECK="select * FROM gridcoverage LIMIT 1;" +SQL_COMMAND_REGISTER="delete from plugin_info where name = 'gridcoverage';" +SQL_COMMAND_SEQ="DROP SEQUENCE gridcoverage_seq;" +SQL_COMMAND_UPDATE_ID="update gridcoverage set id=id*10000;" +SQL_COMMAND_ALTER_NAME_DESC="ALTER TABLE gridcoverage ADD COLUMN description character varying(3071), ALTER COLUMN name TYPE character varying(2047);" + +if [ ! -f ${PSQL} ]; then +echo "ERROR: The PSQL executable does not exist - ${PSQL}." +echo "FATAL: Update Failed!" +exit 1 +fi + +echo "" +echo "Press Enter to undo the updates Ctrl-C to quit." +read done + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_CHECK}" > /dev/null +if [ $? -ne 0 ]; then +echo "WARN: gridcoverage table does not exist so we are not registering the plugin" +exit 0 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_REGISTER}" +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_SEQ}" +if [ $? -ne 0 ]; then +echo "FATAL: unable to delete gridcoverage_seq" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_UPDATE_ID}" +if [ $? -ne 0 ]; then +echo "FATAL: unable to update gridcoverage ids" +exit 1 +fi + +${PSQL} -U awips -d metadata -c "${SQL_COMMAND_ALTER_NAME_DESC}" +if [ $? -ne 0 ]; then +echo "WARN: unable to add description column to gridcoverage table" +fi + +echo "INFO: The update was successfully removed." +exit 0 diff --git a/deltaScripts/unified_grid_rollback/update_D2D_bundles.sh b/deltaScripts/unified_grid_rollback/update_D2D_bundles.sh new file mode 100644 index 0000000000..93ab28558c --- /dev/null +++ b/deltaScripts/unified_grid_rollback/update_D2D_bundles.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# This script will update any D2D bundle files +# to use grid data in place of grib +# +# This update needs to be performed with build ???. +# This update is only for edex servers which host the cave localization files + + +echo "" +echo "Press Enter to undo the updates Ctrl-C to quit." +read done + +IFS=$'\n' +files=`find /awips2/edex/data/utility/cave_static/*/*/bundles/ -iname '*.xml'` + +if [ $? -ne 0 ]; then +echo "No bundle files found." +exit 1 +fi + +MY_DIR=`dirname $0` + +for f in $files; do + bash $MY_DIR/update_saved_display.sh $f +done + + + +echo "INFO: The update was successfully removed." +exit 0 diff --git a/deltaScripts/unified_grid_rollback/update_D2D_procedures.sh b/deltaScripts/unified_grid_rollback/update_D2D_procedures.sh new file mode 100644 index 0000000000..36f170cc89 --- /dev/null +++ b/deltaScripts/unified_grid_rollback/update_D2D_procedures.sh @@ -0,0 +1,27 @@ +#!/bin/bash +# This script will update any D2D procedures files +# to use grid data in place of grib +# +# This update needs to be performed with build ???. +# This update is only for edex servers which host the cave localization files + +echo "" +echo "Press Enter to undo the updates Ctrl-C to quit." +read done + +IFS=$'\n' +files=`ls /awips2/edex/data/utility/cave_static/*/*/procedures/*.xml` + +if [ $? -ne 0 ]; then +echo "No procedures found" +exit 1 +fi + +MY_DIR=`dirname $0` + +for f in $files; do + bash $MY_DIR/update_saved_display.sh $f +done + +echo "INFO: The update was successfully removed." +exit 0 diff --git a/deltaScripts/unified_grid_rollback/update_FFMP_Source.sh b/deltaScripts/unified_grid_rollback/update_FFMP_Source.sh new file mode 100644 index 0000000000..addc57bc06 --- /dev/null +++ b/deltaScripts/unified_grid_rollback/update_FFMP_Source.sh @@ -0,0 +1,33 @@ +#!/bin/bash +# This script will update any FFMPSourceConfig.xml files +# to use grid data in place of grib +# +# This update needs to be performed with build ???. +# This update is only for edex servers which host FFMPSourceConfig.xml files + +echo "" +echo "Press Enter to undo the updates Ctrl-C to quit." +read done + +files=`find /awips2/edex/data/utility/common_static -iname FFMPSourceConfig.xml` + +if [ $? -ne 0 ]; then +echo "FATAL: Update Failed!" +exit 1 +fi + +for f in $files; do + echo Updating $f + bf=$f.bak.`date +%m%d%y` + cp $f $bf + # reconstruct data uris from grib to grid + awk -F '/' ' + /\/grid/ {print $1 "/grib/" $3 "/" $4 "/" $8 "/" $9 "/" $10 "/" $11 "/null/null/" $12 "/" $13; next;} + {gsub(/grid<\/plugin>/,"grib"); print; } + ' $bf > $f +done + + + +echo "INFO: The update was successfully removed." +exit 0 diff --git a/deltaScripts/unified_grid_rollback/update_saved_display.sh b/deltaScripts/unified_grid_rollback/update_saved_display.sh new file mode 100644 index 0000000000..2ff8753ed7 --- /dev/null +++ b/deltaScripts/unified_grid_rollback/update_saved_display.sh @@ -0,0 +1,46 @@ +#!/bin/bash +# This script will update any saved displays from the grib format to the grid format +# +# This update needs to be performed with build ???. +# This update only needs to be run if there are saved displays being stored outside of localization. + + +if [ $# -eq 0 ]; then + echo "Please provide a list of saved displays to update." +fi + +IFS=$'\n' + +for f in "$@"; do + echo Updating $f + #bf=$f.bak.`date +%m%d%y` + #cp $f $bf + # its probably not efficient to execute sed 20 times but its not slow... + # replace perturbationNumbers with ensmble ids + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)ctl1\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\21\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)ctl2\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\22\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)n1\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\23\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)p1\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\24\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)n2\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\25\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)p2\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\26\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)n3\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\27\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)p3\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\28\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)n4\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\29\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)p4\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\210\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)n5\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\211\3/g;p;}' -i $f + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)p5\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1modelInfo.perturbationNumber\212\3/g;p;}' -i $f + # handle grid version + sed -n '1h;1!H;${;g;s/\(\s*<\s*constraint\s\+constraintValue="\)Version\([0-9]\{1,2\}\)\("\s\+constraintType="EQUALS"\s*\/>\s*<\/mapping>\)/\1gridVersion\2\3\4/g;p;}' -i $f + # level + sed -n 's/key="info\.level\.levelonevalue"/key="modelInfo.level.levelonevalue"/g;p;' -i $f + sed -n 's/key="info\.level\.leveltwovalue"/key="modelInfo.level.leveltwovalue"/g;p;' -i $f + sed -n 's/key="info\.level\.masterLevel.name"/key="modelInfo.level.masterLevel.name"/g;p;' -i $f + # parameter + sed -n 's/key="info\.parameter.abbreviation"/key="modelInfo.parameterAbbreviation"/g;p;' -i $f + # dataset + sed -n 's/key="info\.datasetId"/key="modelInfo.modelName"/g;p;' -i $f + #plugin name + sed -n 's/constraintValue="grid"/constraintValue="grib"/g;p;' -i $f + #diff $f $bf > /dev/null + #if [ $? -eq 0 ]; then rm $bf; echo "No Changes"; fi +done diff --git a/edexOsgi/build.edex/.gitignore b/edexOsgi/build.edex/.gitignore new file mode 100644 index 0000000000..ceeb05b410 --- /dev/null +++ b/edexOsgi/build.edex/.gitignore @@ -0,0 +1 @@ +/tmp diff --git a/edexOsgi/build.edex/basebuilds/component_deploy_base.xml b/edexOsgi/build.edex/basebuilds/component_deploy_base.xml index f3c63463fb..cb10f40ded 100644 --- a/edexOsgi/build.edex/basebuilds/component_deploy_base.xml +++ b/edexOsgi/build.edex/basebuilds/component_deploy_base.xml @@ -34,9 +34,10 @@ - - - + + + + - + @@ -113,6 +113,19 @@ + + + + + + + + + + + + + &substitute-targets; diff --git a/edexOsgi/build.edex/build.xml b/edexOsgi/build.edex/build.xml index bceb17ab22..dc70ace7e7 100644 --- a/edexOsgi/build.edex/build.xml +++ b/edexOsgi/build.edex/build.xml @@ -26,6 +26,10 @@ + + + @@ -74,6 +78,10 @@ + + + diff --git a/edexOsgi/build.edex/deploy-common/deploy-esb-configuration.xml b/edexOsgi/build.edex/deploy-common/deploy-esb-configuration.xml index 6eb7c9897c..b4e273d6fa 100644 --- a/edexOsgi/build.edex/deploy-common/deploy-esb-configuration.xml +++ b/edexOsgi/build.edex/deploy-common/deploy-esb-configuration.xml @@ -7,5 +7,6 @@ overwrite="${esb.overwrite}"> + \ No newline at end of file diff --git a/edexOsgi/build.edex/deploy-common/deploy-esb.xml b/edexOsgi/build.edex/deploy-common/deploy-esb.xml index 2b980b2376..3f00bf3487 100644 --- a/edexOsgi/build.edex/deploy-common/deploy-esb.xml +++ b/edexOsgi/build.edex/deploy-common/deploy-esb.xml @@ -1,7 +1,7 @@ - - + + - + @@ -49,6 +49,7 @@ + diff --git a/edexOsgi/build.edex/deploy-common/deploy-setup.xml b/edexOsgi/build.edex/deploy-common/deploy-setup.xml index f2d6e9dc8d..4cc2068e6a 100644 --- a/edexOsgi/build.edex/deploy-common/deploy-setup.xml +++ b/edexOsgi/build.edex/deploy-common/deploy-setup.xml @@ -3,6 +3,9 @@ + + + @@ -49,23 +52,26 @@ - + - - - + - + + + - - - - - - + + + + + + + + diff --git a/edexOsgi/build.edex/deploy-common/external-rules.xml b/edexOsgi/build.edex/deploy-common/external-rules.xml new file mode 100644 index 0000000000..2b42ce321e --- /dev/null +++ b/edexOsgi/build.edex/deploy-common/external-rules.xml @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edexOsgi/build.edex/deploy-common/plugin-methods.xml b/edexOsgi/build.edex/deploy-common/plugin-methods.xml index e865ad5dae..cb78f8c732 100644 --- a/edexOsgi/build.edex/deploy-common/plugin-methods.xml +++ b/edexOsgi/build.edex/deploy-common/plugin-methods.xml @@ -115,31 +115,24 @@ - - - + + - - - - - - - - - - + + + + + - + - + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -42,88 +83,102 @@ + + + + + + + + + + + + + + + + + - - - - - - - - - - - - + + - - - - - - - - - - - - - - - - + + + + + + + + + + + + - - - - + + + + - - - + + + + - - - - - - - - - - + + + + + + + + + + + + + + + - - - - - - - + + + + + diff --git a/edexOsgi/build.edex/edex/customTargets.xml b/edexOsgi/build.edex/edex/customTargets.xml index 3c7f503824..af024f7a62 100644 --- a/edexOsgi/build.edex/edex/customTargets.xml +++ b/edexOsgi/build.edex/edex/customTargets.xml @@ -144,11 +144,18 @@ - + + + + + + + + diff --git a/edexOsgi/build.edex/edex/developer.properties b/edexOsgi/build.edex/edex/developer.properties index 8354087483..28ec5525e9 100644 --- a/edexOsgi/build.edex/edex/developer.properties +++ b/edexOsgi/build.edex/edex/developer.properties @@ -1,12 +1,9 @@ #-----------------------------------------------------------------------------# # developer configurable properties. -# the root directory of the work assignment repository when one -# exists. TODO: is this the only way??? -wa.root.directory= -# the edex feature to deploy; when working a work assignment, this -# will occasionally become: com.raytheon.edex.wa.feature/feature.xml -edex.feature=com.raytheon.edex.feature.uframe/feature.xml +# the root directories of the work assignment(s) to deploy. +# delimited by colon (:) +wa.to.deploy= # deploy the raytheon ufpy, dynamicserialize, and pypies site-packages deploy.python=true @@ -32,4 +29,10 @@ gfesuite.project=com.raytheon.uf.tools.gfesuite.servicebackup # static properties dependent on the current versions of the foss libraries # we are utilizing - should only be modified by CM. -python.version.dir=python2.7 \ No newline at end of file +python.version.dir=python2.7 + +# the Common Baseline EDEX feature +edex.feature=com.raytheon.edex.feature.uframe/feature.xml +# the name of the Work Assignment EDEX feature - +# this feature must exist in a Work Assignment to deploy it. +wa.edex.feature=com.raytheon.edex.wa.feature/feature.xml \ No newline at end of file diff --git a/edexOsgi/build.edex/esb/bin/linux-x86-32/wrapper.conf b/edexOsgi/build.edex/esb/bin/linux-x86-32/wrapper.conf index 5edfea661d..8a72330191 100644 --- a/edexOsgi/build.edex/esb/bin/linux-x86-32/wrapper.conf +++ b/edexOsgi/build.edex/esb/bin/linux-x86-32/wrapper.conf @@ -21,6 +21,7 @@ # Wrapper Properties #******************************************************************** +wrapper.java.classpath.6=%EDEX_HOME%/conf/resources/ # Java Library Path (location of Wrapper.DLL or libwrapper.so) wrapper.java.library.path.1=%EDEX_HOME%/bin/linux-x86-32/ wrapper.java.library.path.4=%EDEX_HOME%/lib/dependencies/org.jep.linux32/ diff --git a/edexOsgi/build.edex/esb/bin/setup.env b/edexOsgi/build.edex/esb/bin/setup.env index 35f7a55d63..5c23461186 100644 --- a/edexOsgi/build.edex/esb/bin/setup.env +++ b/edexOsgi/build.edex/esb/bin/setup.env @@ -22,12 +22,20 @@ export BROKER_ADDR=localhost # setup hdf5 connection if pypies is enabled export PYPIES_SERVER=http://localhost:9582 +# data delivery specific variables, used below in the localization section +export DATADELIVERY_HOST=localhost +export DATADELIVERY_PORT=9588 +export DATADELIVERY_SOAP_PORT=10144 + # moved here from environment.xml # these values are returned to clients that contact the localization service export HTTP_PORT=9581 export HTTP_SERVER=http://localhost:${HTTP_PORT}/services export JMS_SERVER=tcp://localhost:5672 export RADAR_SERVER=tcp://localhost:8813 +export DATADELIVERY_SERVER=http://${DATADELIVERY_HOST}:${DATADELIVERY_PORT}/services/thrift +export DATADELIVERY_LCM_SERVER=http://${DATADELIVERY_HOST}:${DATADELIVERY_SOAP_PORT}/lcm?WSDL +export DATADELIVERY_QUERY_SERVER=http://${DATADELIVERY_HOST}:${DATADELIVERY_SOAP_PORT}/query?WSDL # set the AWIPS II shared directory export SHARE_DIR=/awips2/edex/data/share @@ -42,4 +50,4 @@ export SITE_IDENTIFIER=${AW_SITE_IDENTIFIER} # set Fax environment variables pointing to ldad@ls1 export LDAD_EXTERNAL_HOME=/ldad -export LDAD_EXTERNAL_PUBLIC=/data/ldad/public \ No newline at end of file +export LDAD_EXTERNAL_PUBLIC=/data/ldad/public diff --git a/edexOsgi/build.edex/esb/bin/wrapper.conf b/edexOsgi/build.edex/esb/bin/wrapper.conf index 125d07fa05..2a62a5102f 100644 --- a/edexOsgi/build.edex/esb/bin/wrapper.conf +++ b/edexOsgi/build.edex/esb/bin/wrapper.conf @@ -46,6 +46,7 @@ wrapper.java.classpath.2=%EDEX_HOME%/lib/plugins/com.raytheon.uf.edex.esb.camel. wrapper.java.classpath.3=%EDEX_HOME%/conf/ wrapper.java.classpath.4=%EDEX_HOME%/conf/cache/ wrapper.java.classpath.5=%EDEX_HOME%/conf/spring/ +wrapper.java.classpath.6=%EDEX_HOME%/conf/resources/ # set the umask for file/directory creation by the Java process wrapper.java.umask=0002 @@ -114,16 +115,20 @@ wrapper.java.additional.36=-Dlog4j.configuration=%LOG4J_CONF% # moved these from environment.xml to setup.env wrapper.java.additional.37=-Dhttp.server=%HTTP_SERVER% wrapper.java.additional.38=-Djms.server=%JMS_SERVER% +wrapper.java.additional.39=-Ddatadelivery.server=%DATADELIVERY_SERVER% +wrapper.java.additional.40=-Ddatadelivery.lcm.server=%DATADELIVERY_LCM_SERVER% +wrapper.java.additional.41=-Ddatadelivery.query.server=%DATADELIVERY_QUERY_SERVER% -wrapper.java.additional.39=-DHighMem=%HIGH_MEM_FLAG% -wrapper.java.additional.40=-Dmanagement.port=%MGMT_PORT% +wrapper.java.additional.42=-DHighMem=%HIGH_MEM_FLAG% +wrapper.java.additional.43=-Dmanagement.port=%MGMT_PORT% -wrapper.java.additional.41=-Dqpid.dest_syntax=BURL -wrapper.java.additional.42=-Dweb.port=8080 -wrapper.java.additional.43=-Dconfidential.port=8443 -wrapper.java.additional.44=-Dhttp.port=%HTTP_PORT% -wrapper.java.additional.45=-Dedex.arch=%EDEX_ARCH% -wrapper.java.additional.46=-Dedex.tmp=%TEMP_DIR% +wrapper.java.additional.44=-Dqpid.dest_syntax=BURL +wrapper.java.additional.45=-Dweb.port=8080 +wrapper.java.additional.46=-Dconfidential.port=8443 +wrapper.java.additional.47=-Dhttp.port=%HTTP_PORT% +wrapper.java.additional.48=-Dedex.arch=%EDEX_ARCH% +wrapper.java.additional.49=-Dedex.tmp=%TEMP_DIR% +wrapper.java.additional.50=-Dawips.registrymanager.debug=%AWIPS_REGISTRYMANAGER_DEBUG% # Initial Java Heap Size (in MB) wrapper.java.initmemory=%INIT_MEM% diff --git a/edexOsgi/com.raytheon.edex.common/res/ehcache.xml b/edexOsgi/build.edex/esb/conf/cache/ebxmlRegistryCache.xml similarity index 51% rename from edexOsgi/com.raytheon.edex.common/res/ehcache.xml rename to edexOsgi/build.edex/esb/conf/cache/ebxmlRegistryCache.xml index fcb3dc0e84..9372c7a0f7 100644 --- a/edexOsgi/com.raytheon.edex.common/res/ehcache.xml +++ b/edexOsgi/build.edex/esb/conf/cache/ebxmlRegistryCache.xml @@ -1,54 +1,6 @@ - - - - - - - - - + - + + + \ No newline at end of file diff --git a/edexOsgi/build.edex/esb/conf/db/hibernateConfig/ebxml/hibernate.cfg.xml b/edexOsgi/build.edex/esb/conf/db/hibernateConfig/ebxml/hibernate.cfg.xml new file mode 100644 index 0000000000..91bbbf214d --- /dev/null +++ b/edexOsgi/build.edex/esb/conf/db/hibernateConfig/ebxml/hibernate.cfg.xml @@ -0,0 +1,79 @@ + + + + + + + + + + + org.postgresql.Driver + + + org.hibernate.dialect.PostgreSQLDialect + + + jdbc:postgresql://${db.addr}:${db.port}/ebxml + + awips + awips + + after_transaction + + 100 + + + + + false + + + false + + + false + + + org.hibernate.connection.C3P0ConnectionProvider + + + + 60 + 1800 + 10 + 5 + ${db.metadata.pool.min} + ${db.metadata.pool.max} + + true + org.hibernate.transaction.JDBCTransactionFactory + thread + ebxmlRegistryCache.xml + net.sf.ehcache.hibernate.EhCacheProvider + true + true + true + + + \ No newline at end of file diff --git a/edexOsgi/build.edex/esb/conf/db/hibernateConfig/metadata/hibernate.cfg.xml b/edexOsgi/build.edex/esb/conf/db/hibernateConfig/metadata/hibernate.cfg.xml index 3ba6bcbfc9..1c918cfac5 100644 --- a/edexOsgi/build.edex/esb/conf/db/hibernateConfig/metadata/hibernate.cfg.xml +++ b/edexOsgi/build.edex/esb/conf/db/hibernateConfig/metadata/hibernate.cfg.xml @@ -69,6 +69,7 @@ false false + false false diff --git a/edexOsgi/build.edex/esb/conf/log4j-datadelivery.xml b/edexOsgi/build.edex/esb/conf/log4j-datadelivery.xml new file mode 100644 index 0000000000..d2695ec92d --- /dev/null +++ b/edexOsgi/build.edex/esb/conf/log4j-datadelivery.xml @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edexOsgi/build.edex/esb/conf/log4j-dataprovideragent.xml b/edexOsgi/build.edex/esb/conf/log4j-dataprovideragent.xml new file mode 100644 index 0000000000..d716071732 --- /dev/null +++ b/edexOsgi/build.edex/esb/conf/log4j-dataprovideragent.xml @@ -0,0 +1,75 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edexOsgi/build.edex/esb/conf/log4j-registry.xml b/edexOsgi/build.edex/esb/conf/log4j-registry.xml new file mode 100644 index 0000000000..57a9087cf7 --- /dev/null +++ b/edexOsgi/build.edex/esb/conf/log4j-registry.xml @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edexOsgi/build.edex/esb/conf/modes.xml b/edexOsgi/build.edex/esb/conf/modes.xml index 1f53de9a6d..5d989596b3 100644 --- a/edexOsgi/build.edex/esb/conf/modes.xml +++ b/edexOsgi/build.edex/esb/conf/modes.xml @@ -32,33 +32,114 @@ are compatible with Java's Pattern class. If you provide no tag for a particular mode, the include defaults to .*. --> + .*request.* .*common.* - + excludeDpaAndOgc + purgeutil-request.xml - + + ebxml.*\.xml + statsTemplate + + + registry + datadeliverytemplate + + .*datadelivery-registry.* + + .*datadelivery-standalone.* + + + manualIngest* + time-common.xml + distribution-spring.xml + persist-ingest.xml + auth-common.xml + + grib-common.xml + grib-distribution.xml + grib-datadelivery.xml + level-common.xml + + pointdata-common.xml + obs-common.xml + obs-datadelivery.xml + + .*dpa.* + + .*ogc.* + + fssobs-common + + + ebxml.*\.xml .*request.* - grib-ingest.xml - ncgrib-ingest.xml - - aww-ingest.xml - ncairep-ingest.xml - ncccfp-ingest.xml - ncgrib-distribution.xml - ncep-util-on-edex-ingest - ncep-util-on-edex-ingestGrib - ncscd-ingest.xml - ncpafm-ingest.xml - ncpirep-ingest.xml - nctaf-ingest.xml - nctext-ingest.xml - ncuair-ingest.xml - + grib-ingest.xml + ncgrib-ingest.xml + .*datadelivery.* + .*bandwidth.* + excludeDpaAndOgc + + aww-ingest.xml + ncairep-ingest.xml + ncccfp-ingest.xml + ncgrib-distribution.xml + ncep-util-on-edex-ingest + ncep-util-on-edex-ingestGrib + ncscd-ingest.xml + ncpafm-ingest.xml + ncpirep-ingest.xml + nctaf-ingest.xml + nctext-ingest.xml + ncuair-ingest.xml + + ffmp-ingest.xml scan-ingest.xml cwat-ingest.xml @@ -70,25 +151,32 @@ cpgsrv-spring.xml - time-common.xml - grib-common.xml - grib-ingest.xml - level-common.xml - persist-ingest.xml - management-common.xml - auth-common.xml - - ncgrib-common.xml - ncgrib-ingest.xml - ncep-util-on-edex-ingestGrib - h5uair-ingest.xml - h5uair-common.xml - h5scd-ingest.xml - + time-common.xml + grib-common.xml + grib-ingest.xml + level-common.xml + grid-common.xml + gridcoverage-.*.xml + parameter-common.xml + persist-ingest.xml + management-common.xml + database-common.xml + auth-common.xml + event-ingest.xml + + ncgrib-common.xml + ncgrib-ingest.xml + ncep-util-on-edex-ingestGrib + h5uair-ingest.xml + h5uair-common.xml + h5scd-ingest.xml + + statsTemplate + excludeDpaAndOgc - time-common.xml + time-common.xml ffmp-ingest.xml ffmp-common.xml scan-ingest.xml @@ -104,9 +192,12 @@ qpf-ingest.xml qpf-common.xml cpgsrv-spring.xml - persist-ingest.xml + persist-ingest.xml binlightning-common.xml - grib-common.xml + parameter-common.xml + gridcoverage-.*.xml + grid-common.xml + database-common.xml radar-common.xml text-common.xml level-common.xml @@ -120,30 +211,33 @@ obs-common.xml fssobs-ingest.xml fssobs-common.xml - ldadmesonet-common.xml + ldadmesonet-common.xml ncgrib-common.xml - nctext-common.xml + nctext-common.xml + excludeDpaAndOgc + statsTemplate - - - grib-common.xml - grib-ingest.xml + + + + grib-common.xml + grib-ingest.xml grib-distribution.xml - level-common.xml - persist-ingest.xml + level-common.xml + persist-ingest.xml distribution-spring.xml manualIngest-spring.xml - - - text-.* - textdb-.* - textdbsrv-.* + + + text-.* + textdb-.* + textdbsrv-.* uengine-request.xml - auth-request.xml - distribution-spring.xml + auth-request.xml + distribution-spring.xml manualIngest-spring.xml - + .*gfe.* serialize-request.xml @@ -153,14 +247,15 @@ manualIngest-spring.xml + ebxml.*\.xml alarmWhfs-spring.xml arealffgGenerator-spring.xml - dpaDecoder-spring.xml + DPADecoder-spring.xml dqcPreprocessor-spring.xml floodArchiver-spring.xml hpeDHRDecoder-spring.xml ohd.*.xml - ihfsDbPurge-spring.xml + ihfsDbPurge-spring.xml logFilePurger-spring.xml mpeFieldgen-spring.xml mpeHpeFilePurge-spring.xml @@ -168,10 +263,45 @@ ohdSetupService-spring.xml pointDataRetrievel-spring.xml q2FileProcessor-spring.xml - satpre-spring.xml + satpre-spring.xml auth-request.xml utility-request.xml - \ No newline at end of file + + .*datadelivery-standalone.* + .*datadelivery-registry.* + datadeliverytemplate + + + event-common.xml + stats-common.xml + + + .*datadelivery.* + .*bandwidth.* + + .*bandwidth.*-inmemory.*.xml + time-common.xml + grib-common.xml + grid-common.xml + gridcoverage-.*.xml + parameter-common.xml + pointdata-common.xml + obs-common.xml + level-common.xml + persist-ingest.xml + management-common.xml + database-common.xml + auth-common.xml + event-ingest.xml + statsTemplate + + + + .*dpa.* + + .*ogc.* + + diff --git a/edexOsgi/build.edex/esb/conf/spring/cron.properties b/edexOsgi/build.edex/esb/conf/spring/cron.properties index 532cfac3a0..3acf3c2942 100644 --- a/edexOsgi/build.edex/esb/conf/spring/cron.properties +++ b/edexOsgi/build.edex/esb/conf/spring/cron.properties @@ -3,22 +3,12 @@ #crontab values -logfilepurger.cron=0+1+1,5,9,13,17,21+*+*+? -ihfsdbpurge.cron=0+45+7+*+*+? -floodarchiver.cron=0+30+6+*+*+? -mpehpefilepurge.cron=0+1+12+*+*+? -mpefieldgen.cron=0+25+*+*+*+? -pointdataretrieval.cron=0+2,17,32,47+*+*+*+? -alarmwhfs.cron=0+7,17,27,37,47,57+*+*+*+? -arealqpegen.cron=0+10,25,40,55+*+*+*+? subscription.cron=0+*+*+*+*+? -dqcpreprocessor.cron=0+20+0,6,12,18+*+*+? freezingLevel.cron=0+5+2,8,14,20+*+*+? rpggenvdata.envdata.cron=0+0+*+*+*+? rpggenvdata.biastable.cron=0+26,46+*+*+*+? metartohmdb.cron=0+14+*+*+*+? distribution.cron=0/5+*+*+*+*+? -mpelightningsrv.cron=0+0/30+*+*+*+? qc.cron=0+2,7,12,17,22,27,32,37,42,47,52,57+*+*+*+? acarssounding.cron=00+10,30,50+*+*+*+? gfe.cron=0+15+*+*+*+? diff --git a/edexOsgi/build.edex/esb/conf/spring/edex.xml b/edexOsgi/build.edex/esb/conf/spring/edex.xml index 20a61c50e9..f23ae9117a 100644 --- a/edexOsgi/build.edex/esb/conf/spring/edex.xml +++ b/edexOsgi/build.edex/esb/conf/spring/edex.xml @@ -174,16 +174,6 @@ - - - com.vividsolutions.jts.geom.Geometry - - - - - javax.measure.unit.Unit - - @@ -360,4 +350,36 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/edexOsgi/build.edex/esb/data/utility/common_static/base/ffmp/FFMPSourceConfig.xml b/edexOsgi/build.edex/esb/data/utility/common_static/base/ffmp/FFMPSourceConfig.xml index 9c6a3f87b5..3780f841e7 100644 --- a/edexOsgi/build.edex/esb/data/utility/common_static/base/ffmp/FFMPSourceConfig.xml +++ b/edexOsgi/build.edex/esb/data/utility/common_static/base/ffmp/FFMPSourceConfig.xml @@ -101,8 +101,8 @@ FFG0124hr RFCFFG 1 - /grib/%/%/FFG0124hr/SFC/0.0/-999999.0/null/null/ - grib + /grid/%/%/.*/.*/null/FFG0124hr/SFC/0.0/-999999.0/ + grid GRID GUIDANCE accum @@ -118,8 +118,8 @@ FFG0324hr RFCFFG 3 - /grib/%/%/FFG0324hr/SFC/0.0/-999999.0/null/null/ - grib + /grid/%/%/.*/.*/null/FFG0324hr/SFC/0.0/-999999.0/ + grid GRID GUIDANCE accum @@ -135,8 +135,8 @@ FFG0624hr RFCFFG 6 - /grib/%/%/FFG0624hr/SFC/0.0/-999999.0/null/null/ - grib + /grid/%/%/.*/.*/null/FFG0624hr/SFC/0.0/-999999.0/ + grid GRID GUIDANCE accum diff --git a/edexOsgi/build.edex/esb/data/utility/common_static/base/level/GroupDefinitions.xml b/edexOsgi/build.edex/esb/data/utility/common_static/base/level/GroupDefinitions.xml deleted file mode 100644 index f9317a5662..0000000000 --- a/edexOsgi/build.edex/esb/data/utility/common_static/base/level/GroupDefinitions.xml +++ /dev/null @@ -1,99 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/edexOsgi/build.edex/esb/data/utility/common_static/base/level/LevelAliases.xml b/edexOsgi/build.edex/esb/data/utility/common_static/base/level/LevelAliases.xml deleted file mode 100644 index d93a0336c5..0000000000 --- a/edexOsgi/build.edex/esb/data/utility/common_static/base/level/LevelAliases.xml +++ /dev/null @@ -1,82 +0,0 @@ - - - - - ISBL - - - THEL - - - TRO - - - 0DEG - - - MWSL - - - HTGL - ZAGL - - - SIGL - - - AMSL - ZZZZ - - - DBLL - - - EATM - - - SPDL - - - PVL - - - HYBL - - - ETAL - - - DBSL - - - MIXL - - - MTHE - - - EHLT - - - OSD - - - diff --git a/edexOsgi/build.edex/esb/data/utility/common_static/base/ncep/hold/NcInventoryDefinitions/NcGridSoundingInventory.xml b/edexOsgi/build.edex/esb/data/utility/common_static/base/ncep/hold/NcInventoryDefinitions/NcGridSoundingInventory.xml index d9eca31919..dde5030b14 100644 --- a/edexOsgi/build.edex/esb/data/utility/common_static/base/ncep/hold/NcInventoryDefinitions/NcGridSoundingInventory.xml +++ b/edexOsgi/build.edex/esb/data/utility/common_static/base/ncep/hold/NcInventoryDefinitions/NcGridSoundingInventory.xml @@ -6,7 +6,7 @@ pluginName,modelName,eventName,dataTime - + diff --git a/edexOsgi/com.raytheon.uf.common.sounding/utility/edex_static/base/python/RaobPyUtil.py b/edexOsgi/build.edex/esb/etc/datadelivery.sh similarity index 70% rename from edexOsgi/com.raytheon.uf.common.sounding/utility/edex_static/base/python/RaobPyUtil.py rename to edexOsgi/build.edex/esb/etc/datadelivery.sh index 00224794de..9259fd5029 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/utility/edex_static/base/python/RaobPyUtil.py +++ b/edexOsgi/build.edex/esb/etc/datadelivery.sh @@ -1,3 +1,4 @@ +#!/bin/bash ## # This software was developed and / or modified by Raytheon Company, # pursuant to Contract DG133W-05-CQ-1067 with the US Government. @@ -17,10 +18,17 @@ # See the AWIPS II Master Rights File ("Master Rights File.pdf") for # further licensing information. ## -# to recreate the menu files for radar and scan -def generateMenuFiles(): - from com.raytheon.uf.common.sounding.util import RaobMenuUtil - r = RaobMenuUtil() - from com.raytheon.uf.common.message.response import ResponseMessageGeneric - return ResponseMessageGeneric("Rebuilt upper air local menu files") \ No newline at end of file +export INIT_MEM=512 # in Meg + +if [ $HIGH_MEM_FLAG == "on" ]; then + export MAX_MEM=1536 # in Meg +else + export MAX_MEM=896 # in Meg +fi + +export METADATA_POOL_MIN=10 +export EDEX_DEBUG_PORT=5009 +export EDEX_JMX_PORT=1620 +export LOG4J_CONF=log4j-datadelivery.xml +export MGMT_PORT=9605 diff --git a/edexOsgi/build.edex/esb/etc/datadeliveryonly.sh b/edexOsgi/build.edex/esb/etc/datadeliveryonly.sh new file mode 100644 index 0000000000..9259fd5029 --- /dev/null +++ b/edexOsgi/build.edex/esb/etc/datadeliveryonly.sh @@ -0,0 +1,34 @@ +#!/bin/bash +## +# 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. +## + +export INIT_MEM=512 # in Meg + +if [ $HIGH_MEM_FLAG == "on" ]; then + export MAX_MEM=1536 # in Meg +else + export MAX_MEM=896 # in Meg +fi + +export METADATA_POOL_MIN=10 +export EDEX_DEBUG_PORT=5009 +export EDEX_JMX_PORT=1620 +export LOG4J_CONF=log4j-datadelivery.xml +export MGMT_PORT=9605 diff --git a/edexOsgi/build.edex/esb/etc/dataprovideragent.sh b/edexOsgi/build.edex/esb/etc/dataprovideragent.sh new file mode 100644 index 0000000000..5f1627d854 --- /dev/null +++ b/edexOsgi/build.edex/esb/etc/dataprovideragent.sh @@ -0,0 +1,34 @@ +#!/bin/bash +## +# 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. +## + +export INIT_MEM=512 # in Meg + +if [ $HIGH_MEM_FLAG == "on" ]; then + export MAX_MEM=1536 # in Meg +else + export MAX_MEM=896 # in Meg +fi +export METADATA_POOL_MIN=10 +export EDEX_DEBUG_PORT=5010 +export EDEX_JMX_PORT=1621 +export LOG4J_CONF=log4j-dataprovideragent.xml +export MGMT_PORT=9606 + diff --git a/edexOsgi/build.edex/esb/etc/registry.sh b/edexOsgi/build.edex/esb/etc/registry.sh new file mode 100644 index 0000000000..1f3a9a7d2a --- /dev/null +++ b/edexOsgi/build.edex/esb/etc/registry.sh @@ -0,0 +1,34 @@ +#!/bin/bash +## +# 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. +## + +export INIT_MEM=512 # in Meg + +if [ $HIGH_MEM_FLAG == "on" ]; then + export MAX_MEM=1536 # in Meg +else + export MAX_MEM=896 # in Meg +fi +export METADATA_POOL_MIN=10 +export EDEX_DEBUG_PORT=5011 +export EDEX_JMX_PORT=1622 +export LOG4J_CONF=log4j-registry.xml +export MGMT_PORT=9607 + diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/WebConsoleStarter.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/WebConsoleStarter.class deleted file mode 100644 index 607b30e0e7..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/WebConsoleStarter.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CopyMessage.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CopyMessage.class deleted file mode 100644 index cecd3d5461..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CopyMessage.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CreateDestination.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CreateDestination.class deleted file mode 100644 index dc8d92abeb..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CreateDestination.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CreateSubscriber.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CreateSubscriber.class deleted file mode 100644 index d6d03f6c9d..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/CreateSubscriber.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteDestination.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteDestination.class deleted file mode 100644 index a0c9a3c219..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteDestination.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteMessage.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteMessage.class deleted file mode 100644 index 17cc728253..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteMessage.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteSubscriber.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteSubscriber.class deleted file mode 100644 index 686b49dc20..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/DeleteSubscriber.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/MoveMessage.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/MoveMessage.class deleted file mode 100644 index bc60a24659..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/MoveMessage.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/PurgeDestination.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/PurgeDestination.class deleted file mode 100644 index 525f442ed6..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/PurgeDestination.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/SendMessage.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/SendMessage.class deleted file mode 100644 index feca1ffadc..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/controller/SendMessage.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter$1.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter$1.class deleted file mode 100644 index 7d4cbe9219..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter$1.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter$2.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter$2.class deleted file mode 100644 index 3cc7c96226..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter$2.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter.class deleted file mode 100644 index 6f9f1d10f4..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/filter/ApplicationContextFilter.class and /dev/null differ diff --git a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/handler/BindingBeanNameUrlHandlerMapping.class b/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/handler/BindingBeanNameUrlHandlerMapping.class deleted file mode 100644 index bde8039ac2..0000000000 Binary files a/edexOsgi/build.edex/esb/webapps/admin/WEB-INF/classes/org/apache/activemq/web/handler/BindingBeanNameUrlHandlerMapping.class and /dev/null differ diff --git a/edexOsgi/build.edex/opt/db/ddl/ebxml/createEbxml.sql b/edexOsgi/build.edex/opt/db/ddl/ebxml/createEbxml.sql new file mode 100644 index 0000000000..e0f673869b --- /dev/null +++ b/edexOsgi/build.edex/opt/db/ddl/ebxml/createEbxml.sql @@ -0,0 +1,25 @@ +/** + * 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. + **/ +\set ON_ERROR_STOP 1 +DROP DATABASE IF EXISTS ebxml; +DROP TABLESPACE IF EXISTS ebxml_data; +CREATE TABLESPACE ebxml_data OWNER awips LOCATION '%{database_files_home}%/ebxml'; +COMMENT ON TABLESPACE ebxml_data IS 'EBXML Registry Database tablespace'; +CREATE DATABASE ebxml OWNER awips TABLESPACE ebxml_data; diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/package-info.java b/edexOsgi/build.edex/opt/db/ddl/events/createEventsSchema.sql similarity index 87% rename from edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/package-info.java rename to edexOsgi/build.edex/opt/db/ddl/events/createEventsSchema.sql index e57d4c3c11..750b1d3499 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/package-info.java +++ b/edexOsgi/build.edex/opt/db/ddl/events/createEventsSchema.sql @@ -17,7 +17,6 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -/** - * Data access objects for accessing and manipulating grib data. - */ -package com.raytheon.edex.plugin.grib.dao; \ No newline at end of file +\set ON_ERROR_STOP 1 +\connect metadata; +CREATE SCHEMA events AUTHORIZATION awips; diff --git a/edexOsgi/build.edex/opt/db/ddl/setup/pg_hba.conf b/edexOsgi/build.edex/opt/db/ddl/setup/pg_hba.conf index 73e509c222..84b7146f88 100644 --- a/edexOsgi/build.edex/opt/db/ddl/setup/pg_hba.conf +++ b/edexOsgi/build.edex/opt/db/ddl/setup/pg_hba.conf @@ -72,6 +72,7 @@ local maps all trust local hmdb all trust local postgres all trust local ncep all trust +local ebxml all trust # IPv4 local connections: host fxatext all 127.0.0.1/32 trust host fxatext all 147.18.136.0/24 trust @@ -105,5 +106,9 @@ host ncep all 127.0.0.1/32 md5 host ncep all 147.18.136.0/24 md5 host ncep all 147.18.139.0/24 md5 host ncep all 162.0.0.0/8 md5 +host ebxml all 127.0.0.1/32 trust +host ebxml all 147.18.136.0/24 trust +host ebxml all 147.18.139.0/24 trust +host ebxml all 162.0.0.0/8 trust # IPv6 local connections: host all all ::1/128 md5 diff --git a/edexOsgi/com.raytheon.edex.autobldsrv/src/com/raytheon/edex/services/ScriptRunner.java b/edexOsgi/com.raytheon.edex.autobldsrv/src/com/raytheon/edex/services/ScriptRunner.java index 3ac8ef7566..078b137764 100644 --- a/edexOsgi/com.raytheon.edex.autobldsrv/src/com/raytheon/edex/services/ScriptRunner.java +++ b/edexOsgi/com.raytheon.edex.autobldsrv/src/com/raytheon/edex/services/ScriptRunner.java @@ -45,6 +45,7 @@ import com.raytheon.uf.common.message.Header; import com.raytheon.uf.common.message.Message; import com.raytheon.uf.common.message.Property; import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.util.ReflectionUtil; import com.raytheon.uf.edex.core.EdexException; /** @@ -182,8 +183,9 @@ public class ScriptRunner { PluginDataObject[] pdos = (PluginDataObject[]) event; for (PluginDataObject pdo : pdos) { try { - String prodID = (String) Util.getFieldValue(pdo, - pdo.getClass(), "productId"); + String prodID = ReflectionUtil.getter(String.class, + pdo, + "productId"); if (logger.isDebugEnabled()) { logger.debug("Processing trigger: " + prodID + ", class = " @@ -198,8 +200,8 @@ public class ScriptRunner { } else if (event instanceof PluginDataObject) { PluginDataObject pdo = (PluginDataObject) event; try { - String prodID = (String) Util.getFieldValue(pdo, - pdo.getClass(), "productId"); + String prodID = ReflectionUtil.getter(String.class, + pdo, "productId"); if (logger.isDebugEnabled()) { logger.debug("Processing trigger: " + prodID + ", class = " diff --git a/edexOsgi/com.raytheon.edex.common/component-deploy.xml b/edexOsgi/com.raytheon.edex.common/component-deploy.xml deleted file mode 100644 index 23afc06df6..0000000000 --- a/edexOsgi/com.raytheon.edex.common/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/exception/GribDecoderException.java b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/exception/GribDecoderException.java deleted file mode 100644 index 5033a59772..0000000000 --- a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/exception/GribDecoderException.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - - -package com.raytheon.edex.exception; - -import com.raytheon.uf.edex.core.EdexException; - - -/** - * GRIB decoder exception class - * - *
- *
- * SOFTWARE HISTORY
- *
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * 06/14/06                garmendariz Initial check-in 
- * 
- * 
- * - * @author garmendariz - * @version 1.0 - */ -public class GribDecoderException extends EdexException { - - /** - * Default serial version id - */ - private static final long serialVersionUID = 1L; - - /** - * Constructor that accepts only a string message - * - * @param aMsg The exception message - */ - public GribDecoderException(String aMsg) { - super(aMsg); - } - - /** - * Constructor that accepts a message and a cause - * @param aMsg An exception message - * @param e A message - */ - public GribDecoderException(String aMsg, Exception e) { - super(aMsg, e); - } - -} diff --git a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/msg/ResponseMessageASCII.java b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/msg/ResponseMessageASCII.java index 798820e801..fc218342ed 100644 --- a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/msg/ResponseMessageASCII.java +++ b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/msg/ResponseMessageASCII.java @@ -24,8 +24,8 @@ import java.util.Calendar; import java.util.Date; import com.raytheon.edex.util.Util; -import com.raytheon.uf.common.dataplugin.convert.ConvertUtil; import com.raytheon.uf.common.message.response.AbstractResponseMessage; +import com.raytheon.uf.common.util.ConvertUtil; /** * Represents an ASCII product response from EDEX. diff --git a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/util/Util.java b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/util/Util.java index ad9b10f493..6b888a9e71 100644 --- a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/util/Util.java +++ b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/util/Util.java @@ -51,26 +51,18 @@ import java.util.regex.Pattern; import java.util.zip.DataFormatException; import java.util.zip.ZipEntry; -import javax.measure.unit.Unit; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; -import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.lang.builder.HashCodeBuilder; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.springframework.context.ConfigurableApplicationContext; -import com.raytheon.uf.common.dataplugin.convert.ConvertUtil; -import com.raytheon.uf.common.dataplugin.convert.UnitConverter; -import com.raytheon.uf.common.geospatial.util.JtsGeometryConverter; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; -import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.common.time.util.CalendarConverter; -import com.raytheon.uf.common.time.util.DataTimeConverter; -import com.raytheon.uf.common.time.util.DateConverter; import com.raytheon.uf.common.time.util.TimeUtil; -import com.vividsolutions.jts.geom.Geometry; +import com.raytheon.uf.common.util.ConvertUtil; /** * Contains utility methods for use in common. @@ -85,6 +77,7 @@ import com.vividsolutions.jts.geom.Geometry; * 10Apr2008 1068 MW Fegan Remove redundant memory reporting. * 15Jul2008 1014 MW Fegan Improved logging of JiBX marshaling errors. * Aug 20, 2008 dglazesk Added functions for handling JaXB marshalling + * Nov 09, 2012 1322 djohnson Add close for Spring context. *
* * @author mfegan @@ -121,17 +114,6 @@ public final class Util { public static final float GRID_FILL_VALUE = -999999; - // TODO remove this static block - // this registration should occur in spring and edex is set up to - // do this but CAVE isn't yet - static { - ConvertUtils.register(new DataTimeConverter(), DataTime.class); - ConvertUtils.register(new CalendarConverter(), Calendar.class); - ConvertUtils.register(new UnitConverter(), Unit.class); - ConvertUtils.register(new DateConverter(), Date.class); - ConvertUtils.register(new JtsGeometryConverter(), Geometry.class); - } - private Util() { // No Instantiation } @@ -161,35 +143,6 @@ public final class Util { return "[" + (obj == null ? "null" : obj.toString()) + "]"; } - /** - * Obtains the value of the specified field from the object. - * - * @param object - * the object containing the field - * @param classObj - * the class of the object - * @param name - * the name of the field - * - * @return the value of the field - * - * @throws NoSuchMethodException - * @throws InvocationTargetException - * @throws IllegalAccessException - */ - @SuppressWarnings("unchecked") - public static Object getFieldValue(Object object, Class classObj, - String name) throws NoSuchMethodException, - InvocationTargetException, IllegalAccessException { - Object obj = null; - StringBuffer getter = new StringBuffer("get").append( - name.substring(0, 1).toUpperCase()).append(name.substring(1)); - Method worker = classObj.getMethod(getter.toString(), (Class[]) null); - obj = worker.invoke(object, (Object[]) null); - return obj; - - } - /** * Invokes the setter for the specified field on an object. *

@@ -971,8 +924,7 @@ public final class Util { * * @return the converted object */ - @SuppressWarnings("unchecked") - public static Object getObjForStr(String string, Class aClass) { + public static Object getObjForStr(String string, Class aClass) { Object retValue = null; @@ -1398,4 +1350,22 @@ public final class Util { } } + /** + * Performs a safe-close on a {@link ConfigurableApplicationContext}. + * + * @param ctx + * the context + */ + public static String close(final ConfigurableApplicationContext ctx) { + // Just adapt to a normal Java closeable + return close(new Closeable() { + @Override + public void close() throws IOException { + if (ctx != null) { + ctx.close(); + } + } + }); +} + } diff --git a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/utility/EDEXLocalizationAdapter.java b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/utility/EDEXLocalizationAdapter.java index 75684652dd..cfe47da18d 100644 --- a/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/utility/EDEXLocalizationAdapter.java +++ b/edexOsgi/com.raytheon.edex.common/src/com/raytheon/edex/utility/EDEXLocalizationAdapter.java @@ -33,6 +33,7 @@ import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.LocalizationFile.ModifiableLocalizationFile; import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException; import com.raytheon.uf.edex.core.props.EnvProperties; import com.raytheon.uf.edex.core.props.PropertiesFactory; @@ -73,23 +74,6 @@ public class EDEXLocalizationAdapter implements ILocalizationAdapter { this.contexts = new HashMap(); } - /* - * (non-Javadoc) - * - * @see - * com.raytheon.edex.utility.ILocalizationAdapter#getDirNameForType(com. - * raytheon.edex.utility.LocalizationContext.LocalizationType) - */ - @Override - public String getDirNameForType(LocalizationType type) { - - if (type == LocalizationType.UNKNOWN) { - throw new IllegalArgumentException("Unsupported type: " + type); - } else { - return type.toString().toLowerCase(); - } - } - /* * (non-Javadoc) * @@ -119,7 +103,7 @@ public class EDEXLocalizationAdapter implements ILocalizationAdapter { } } - private String getSiteName() { + protected String getSiteName() { String site = PropertiesFactory.getInstance().getEnvProperties() .getEnvValue("SITENAME"); @@ -176,12 +160,7 @@ public class EDEXLocalizationAdapter implements ILocalizationAdapter { @Override public File getPath(LocalizationContext context, String fileName) { - String baseDir = null; - - EnvProperties env = PropertiesFactory.getInstance().getEnvProperties(); - - String utilityDir = new File(env.getEnvValue("UTILITYDIR")) - .getAbsolutePath(); + File utilityDir = getUtilityDir(); if (context.getLocalizationLevel() == LocalizationLevel.UNKNOWN) { throw new IllegalArgumentException( @@ -191,11 +170,11 @@ public class EDEXLocalizationAdapter implements ILocalizationAdapter { // TODO: Check for invalid type / level combinations // Change the above condition and add invalid type / level checking // if needed - } else { - baseDir = utilityDir + File.separator + context.toPath(); } - return new File(baseDir + File.separator + fileName); + File baseDir = new File(utilityDir, context.toPath()); + + return new File(baseDir, fileName); } /* @@ -212,6 +191,17 @@ public class EDEXLocalizationAdapter implements ILocalizationAdapter { return type; } + /** + * Get the file reference to the utility directory. + * + * @return the file reference to the utility directory + */ + protected File getUtilityDir() { + EnvProperties env = PropertiesFactory.getInstance().getEnvProperties(); + + return new File(env.getEnvValue("UTILITYDIR")); + } + /** * Create ListResponse metadata *

@@ -288,43 +278,37 @@ public class EDEXLocalizationAdapter implements ILocalizationAdapter { // --- CRUD Operations --------------------------------------------------- - /** - * UNSUPPORTED Create a file - *

- * On EDEX all file operations are local and do not need to be created, - * read, updated, or deleted from a remote source. Instead of using the CRUD - * methods provided by the {@link ILocalizationAdapter} interface use - * {@link #getPath(LocalizationContext, String)} and appropriate File object - * methods. - *

+ /* + * (non-Javadoc) * - * @see com.raytheon.uf.common.localization.ILocalizationAdapter#save(java.io.File, - * com.raytheon.uf.common.localization.LocalizationContext, - * java.lang.String) + * @see com.raytheon.uf.common.localization.ILocalizationAdapter#save( + * com.raytheon.uf.common.localization.LocalizationFile. + * ModifiableLocalizationFile) */ @Override - public boolean save(File localFile, LocalizationContext context, - String fileName) throws LocalizationOpFailedException { - - if (context.getLocalizationLevel().equals(LocalizationLevel.BASE)) { + public boolean save(ModifiableLocalizationFile file) + throws LocalizationOpFailedException { + if (file.getContext().getLocalizationLevel() + .equals(LocalizationLevel.BASE)) { throw new UnsupportedOperationException( "Saving to the BASE context is not supported."); } return true; } - /** - * Delete a file. Deletes the local file. + /* + * (non-Javadoc) * - * @see com.raytheon.uf.common.localization.ILocalizationAdapter#delete(java.io.File, - * com.raytheon.uf.common.localization.LocalizationContext, - * java.lang.String) + * @see com.raytheon.uf.common.localization.ILocalizationAdapter#delete( + * com.raytheon.uf.common.localization.LocalizationFile. + * ModifiableLocalizationFile) */ @Override - public boolean delete(File file, LocalizationContext context, - String fileName) throws LocalizationOpFailedException { - if (file.exists()) { - return file.delete(); + public boolean delete(ModifiableLocalizationFile file) + throws LocalizationOpFailedException { + File localFile = file.getLocalFile(); + if (localFile.exists()) { + return localFile.delete(); } return true; } diff --git a/edexOsgi/com.raytheon.edex.common/unit-test/com/raytheon/edex/subscription/TestSubscriptionManager.java b/edexOsgi/com.raytheon.edex.common/unit-test/com/raytheon/edex/subscription/TestSubscriptionManager.java deleted file mode 100644 index 030daa352d..0000000000 --- a/edexOsgi/com.raytheon.edex.common/unit-test/com/raytheon/edex/subscription/TestSubscriptionManager.java +++ /dev/null @@ -1,157 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.edex.subscription; - -import static com.raytheon.edex.subscription.AddScriptAction.addScript; -import static com.raytheon.edex.subscription.DeleteScriptAction.deleteScript; -import static org.hamcrest.Matchers.instanceOf; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; - -import org.jmock.Expectations; -import org.jmock.Mockery; -import org.jmock.integration.junit4.JMock; -import org.jmock.integration.junit4.JUnit4Mockery; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; - -import com.raytheon.edex.db.dao.ISubscriber; -import com.raytheon.edex.exception.SubscriptionException; -import com.raytheon.uf.edex.database.DataAccessLayerException; - - - -/** - * - *
- *
- * SOFTWARE HISTORY
- *
- * Date       	Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * 	
- * 
- * 
- * - * @author mfegan - * @version 1 - */ -@RunWith(JMock.class) -public class TestSubscriptionManager { - Mockery context = new JUnit4Mockery(); - /* the test fixture */ - SubscriptionManager manager; - String goodKey = "/.+?/METAR/KDBN/.+"; - String badKey = "/.+?/METAR/KQKQ/.+"; - String scriptID1 = "TEST 1"; - String scriptID2 = "TEST 2"; - StringBuffer script1 = new StringBuffer("This is test script 1"); - StringBuffer script2 = new StringBuffer("This is test script 2"); - String subNotFound = "No subscriptions exist for requested URI"; - String[] subscriptions = {goodKey}; - Subscription goodScript; - - /** - * @throws java.lang.Exception - */ - @Before - public void setUp() throws Exception { - manager = new SubscriptionManager(); - final ISubscriber dataLayer = context.mock(ISubscriber.class); - goodScript = new Subscription(goodKey,scriptID1,script1); - // expections - context.checking(new Expectations() {{ - allowing (dataLayer).getSubscriptions(); - will(returnValue(subscriptions)); - allowing (dataLayer).getSubscription(goodKey); - will(returnValue(goodScript)); - allowing (dataLayer).getSubscription(badKey); - will(throwException(new DataAccessLayerException(subNotFound))); - allowing (dataLayer).manageSubscriptions(with(instanceOf(Subscription.class)), - with(equal(ISubscriber.SUBSCRIBE_MODE_SAVE))); - will(addScript(goodScript,scriptID2,script2)); - allowing (dataLayer).manageSubscriptions(with(instanceOf(Subscription.class)), - with(equal(ISubscriber.SUBSCRIBE_MODE_DELETE))); - will(deleteScript(goodScript,scriptID2)); - allowing (dataLayer).manageSubscriptions(with(instanceOf(Subscription.class)), - with(equal(ISubscriber.SUBSCRIBE_MODE_UPDATE))); - will(returnValue(null)); - }}); - // manager.setDataLayer(dataLayer); - - } - - /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception { - manager = null; - - - } - - /** - * Test method for {@link com.raytheon.edex.subscription.SubscriptionManager#subscribe(java.lang.String, java.lang.String, java.lang.Object)}. - */ - @Test - public void testSubscribe() throws SubscriptionException { - manager.subscribe(goodKey, scriptID2, script2); - Subscription s = manager.getSubscription(goodKey); - assertNotNull("Checking Subscription retrieval - good subscription",s); - assertEquals("Checking Subscription script count",2,s.getCount()); - Script t = s.getScript(scriptID1); - assertSame("Checkin script 1",script1,t.getScript()); - t = s.getScript(scriptID2); - assertSame("Checking script 2",script2,t.getScript()); - } - - /** - * Test method for {@link com.raytheon.edex.subscription.SubscriptionManager#subscribe(java.lang.String, java.lang.String, java.lang.Object)}. - */ - @Test(expected=SubscriptionException.class) - public void testSubscribe_bad() throws SubscriptionException { - manager.subscribe(goodKey, scriptID1, script1); - } - - /** - * Test method for {@link com.raytheon.edex.subscription.SubscriptionManager#getSubscription(java.lang.String)}. - */ - @Test - public void testGetSubscription() { - Subscription s = manager.getSubscription(goodKey); - assertNotNull("Checking Subscription retrieval - good subscription",s); - assertEquals("Checking Subscription script count",1,s.getCount()); - - - } - /** - * Test method for {@link com.raytheon.edex.subscription.SubscriptionManager#getSubscription(java.lang.String)}. - */ - @Test - public void testGetSubscription_error() { - Subscription s = manager.getSubscription(badKey); - assertNull("Checking Subscription retrieval - bad subscription",s); - } -} diff --git a/edexOsgi/com.raytheon.edex.feature.uframe/feature.xml b/edexOsgi/com.raytheon.edex.feature.uframe/feature.xml index 1a4376696c..aadba52a15 100644 --- a/edexOsgi/com.raytheon.edex.feature.uframe/feature.xml +++ b/edexOsgi/com.raytheon.edex.feature.uframe/feature.xml @@ -96,7 +96,12 @@ id="com.raytheon.uf.edex.ost.feature" version="0.0.0"/> + + + diff --git a/edexOsgi/com.raytheon.edex.ingestsrv/src/com/raytheon/edex/services/PersistSrv.java b/edexOsgi/com.raytheon.edex.ingestsrv/src/com/raytheon/edex/services/PersistSrv.java index 48d4218703..e8378306bf 100644 --- a/edexOsgi/com.raytheon.edex.ingestsrv/src/com/raytheon/edex/services/PersistSrv.java +++ b/edexOsgi/com.raytheon.edex.ingestsrv/src/com/raytheon/edex/services/PersistSrv.java @@ -46,6 +46,7 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory; * ------------ ---------- ----------- -------------------------- * Oct 31, 2008 chammack Initial creation * 02/06/09 1990 bphillip Refactored to use plugin specific daos + * Nov 02, 2012 1302 djohnson Remove unused method, fix formatting. *
* * @author chammack @@ -53,7 +54,7 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory; */ public class PersistSrv { - private Log logger = LogFactory.getLog(getClass()); + private final Log logger = LogFactory.getLog(getClass()); private static final PersistSrv instance = new PersistSrv(); @@ -64,7 +65,6 @@ public class PersistSrv { private PersistSrv() { } - @SuppressWarnings("unchecked") public PluginDataObject[] persist(PluginDataObject[] pdo) { if (pdo == null || pdo.length == 0) { diff --git a/edexOsgi/com.raytheon.edex.meteolib/unit-test/com/raytheon/edex/meteoLib/Test.class b/edexOsgi/com.raytheon.edex.meteolib/unit-test/com/raytheon/edex/meteoLib/Test.class deleted file mode 100644 index 63a5989344..0000000000 Binary files a/edexOsgi/com.raytheon.edex.meteolib/unit-test/com/raytheon/edex/meteoLib/Test.class and /dev/null differ diff --git a/edexOsgi/com.raytheon.edex.plugin.airep/unit-test/test/airep/TestAIREPParser.java b/edexOsgi/com.raytheon.edex.plugin.airep/unit-test/test/airep/TestAIREPParser.java index ecc7038967..c661c21a91 100644 --- a/edexOsgi/com.raytheon.edex.plugin.airep/unit-test/test/airep/TestAIREPParser.java +++ b/edexOsgi/com.raytheon.edex.plugin.airep/unit-test/test/airep/TestAIREPParser.java @@ -267,20 +267,20 @@ public class TestAIREPParser { // Winds with "KT" p = new AirepParser("ARP DAL278 3336N 165E 1543 F320 MS40 110/010KT TB LGT=", c); assertNotNull(p); - assertEquals(110, p.getWindDirection()); - assertEquals(10, p.getWindSpeed()); + assertEquals(110, p.getWindDirection().intValue()); + assertEquals(10, p.getWindSpeed().intValue()); // Winds with "KTS" p = new AirepParser("ARP DAL278 3336N 165E 1543 F320 MS40 265/010KTS TB LGT=", c); assertNotNull(p); - assertEquals(265, p.getWindDirection()); - assertEquals(10, p.getWindSpeed()); + assertEquals(265, p.getWindDirection().intValue()); + assertEquals(10, p.getWindSpeed().intValue()); // Winds with no units - assume knots p = new AirepParser("ARP DAL278 3336N 165E 1543 F320 MS40 265/010 TB LGT=", c); assertNotNull(p); - assertEquals(265, p.getWindDirection()); - assertEquals(10, p.getWindSpeed()); + assertEquals(265, p.getWindDirection().intValue()); + assertEquals(10, p.getWindSpeed().intValue()); } diff --git a/edexOsgi/com.raytheon.edex.plugin.binlightning/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.edex.plugin.binlightning/META-INF/MANIFEST.MF index 43a4213b56..799dd83d43 100644 --- a/edexOsgi/com.raytheon.edex.plugin.binlightning/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.edex.plugin.binlightning/META-INF/MANIFEST.MF @@ -8,8 +8,7 @@ Bundle-Vendor: RAYTHEON Require-Bundle: org.apache.commons.logging, com.raytheon.edex.common, com.raytheon.uf.edex.decodertools;bundle-version="1.0.0", - javax.persistence + javax.persistence, + com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.12.1174";visibility:=reexport Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: com.raytheon.uf.common.dataplugin.binlightning, - com.raytheon.uf.common.dataplugin.binlightning.dao, - com.raytheon.uf.common.dataplugin.binlightning.impl +Export-Package: com.raytheon.edex.plugin.binlightning.dao diff --git a/edexOsgi/com.raytheon.edex.plugin.binlightning/component-deploy.xml b/edexOsgi/com.raytheon.edex.plugin.binlightning/component-deploy.xml deleted file mode 100644 index df09595af9..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.binlightning/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/res/spring/binlightning-common.xml b/edexOsgi/com.raytheon.edex.plugin.binlightning/res/spring/binlightning-common.xml similarity index 90% rename from edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/res/spring/binlightning-common.xml rename to edexOsgi/com.raytheon.edex.plugin.binlightning/res/spring/binlightning-common.xml index 789a0b30c4..702667203e 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/res/spring/binlightning-common.xml +++ b/edexOsgi/com.raytheon.edex.plugin.binlightning/res/spring/binlightning-common.xml @@ -7,7 +7,7 @@ - + diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/src/com/raytheon/uf/common/dataplugin/binlightning/dao/BinLightningDao.java b/edexOsgi/com.raytheon.edex.plugin.binlightning/src/com/raytheon/edex/plugin/binlightning/dao/BinLightningDao.java similarity index 97% rename from edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/src/com/raytheon/uf/common/dataplugin/binlightning/dao/BinLightningDao.java rename to edexOsgi/com.raytheon.edex.plugin.binlightning/src/com/raytheon/edex/plugin/binlightning/dao/BinLightningDao.java index 2ba8a53427..70a9049e4c 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/src/com/raytheon/uf/common/dataplugin/binlightning/dao/BinLightningDao.java +++ b/edexOsgi/com.raytheon.edex.plugin.binlightning/src/com/raytheon/edex/plugin/binlightning/dao/BinLightningDao.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.binlightning.dao; +package com.raytheon.edex.plugin.binlightning.dao; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; import com.raytheon.uf.common.dataplugin.PluginException; diff --git a/edexOsgi/com.raytheon.edex.plugin.bufrmos/utility/common_static/base/path/bufrmosPathKeys.xml b/edexOsgi/com.raytheon.edex.plugin.bufrmos/utility/common_static/base/path/bufrmosPathKeys.xml deleted file mode 100644 index 20f5fba6f2..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.bufrmos/utility/common_static/base/path/bufrmosPathKeys.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - type - 0 - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.bufrua/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.edex.plugin.bufrua/META-INF/MANIFEST.MF index d98fea61d4..0ccbb69f2e 100644 --- a/edexOsgi/com.raytheon.edex.plugin.bufrua/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.edex.plugin.bufrua/META-INF/MANIFEST.MF @@ -14,7 +14,9 @@ Require-Bundle: com.raytheon.uf.common.dataplugin.bufrua;bundle-version="1.0.0", com.raytheon.uf.edex.pointdata;bundle-version="1.11.8", javax.measure, org.geotools, - javax.persistence + javax.persistence, + com.raytheon.uf.edex.menus;bundle-version="1.0.0", + com.raytheon.uf.common.localization;bundle-version="1.12.1174" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: com.raytheon.edex.plugin.bufrua.dao Import-Package: com.raytheon.uf.common.status diff --git a/edexOsgi/com.raytheon.edex.plugin.bufrua/component-deploy.xml b/edexOsgi/com.raytheon.edex.plugin.bufrua/component-deploy.xml deleted file mode 100644 index b25f1a9947..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.bufrua/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.sounding/res/spring/raob-request.xml b/edexOsgi/com.raytheon.edex.plugin.bufrua/res/spring/bufrua-request.xml similarity index 76% rename from edexOsgi/com.raytheon.uf.common.sounding/res/spring/raob-request.xml rename to edexOsgi/com.raytheon.edex.plugin.bufrua/res/spring/bufrua-request.xml index b9e87bffaa..d3c88b4737 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/res/spring/raob-request.xml +++ b/edexOsgi/com.raytheon.edex.plugin.bufrua/res/spring/bufrua-request.xml @@ -4,10 +4,10 @@ http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - - + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/RaobMenuUtil.java b/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/RaobMenuUtil.java similarity index 98% rename from edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/RaobMenuUtil.java rename to edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/RaobMenuUtil.java index a4404f02b1..aaad51be2b 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/RaobMenuUtil.java +++ b/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/RaobMenuUtil.java @@ -17,14 +17,13 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.sounding.util; +package com.raytheon.edex.plugin.bufrua.util; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; -import com.raytheon.uf.common.menus.AbstractMenuUtil; import com.raytheon.uf.common.menus.xml.CommonAbstractMenuContribution; import com.raytheon.uf.common.menus.xml.CommonBundleMenuContribution; import com.raytheon.uf.common.menus.xml.CommonPlaceholderMenuContribution; @@ -33,6 +32,7 @@ import com.raytheon.uf.common.menus.xml.MenuTemplateFile; import com.raytheon.uf.common.menus.xml.VariableSubstitution; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.menus.AbstractMenuUtil; /** * Builds the menus for raobs diff --git a/edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/RaobSitesInUseUtil.java b/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/RaobSitesInUseUtil.java similarity index 99% rename from edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/RaobSitesInUseUtil.java rename to edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/RaobSitesInUseUtil.java index 81b025645e..81c03e0573 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/RaobSitesInUseUtil.java +++ b/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/RaobSitesInUseUtil.java @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.sounding.util; +package com.raytheon.edex.plugin.bufrua.util; import java.io.BufferedReader; import java.io.File; diff --git a/edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/UpperAirSite.java b/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/UpperAirSite.java similarity index 97% rename from edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/UpperAirSite.java rename to edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/UpperAirSite.java index 815a781b48..3d4e4e8fff 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/src/com/raytheon/uf/common/sounding/util/UpperAirSite.java +++ b/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/plugin/bufrua/util/UpperAirSite.java @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.sounding.util; +package com.raytheon.edex.plugin.bufrua.util; /** * TODO Add Description diff --git a/edexOsgi/com.raytheon.edex.plugin.bufrua/utility/edex_static/base/distribution/bufrua.xml b/edexOsgi/com.raytheon.edex.plugin.bufrua/utility/edex_static/base/distribution/bufrua.xml index 6911ea7a87..c92a6d18ae 100644 --- a/edexOsgi/com.raytheon.edex.plugin.bufrua/utility/edex_static/base/distribution/bufrua.xml +++ b/edexOsgi/com.raytheon.edex.plugin.bufrua/utility/edex_static/base/distribution/bufrua.xml @@ -19,6 +19,6 @@ further_licensing_information. --> - ^IUSZ[0-9][123468].* + ^IUSZ[4-9][123468].* ^IUSY4[123468].* diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.edex.plugin.gfe/META-INF/MANIFEST.MF index 8743a0ec35..9c8d8a6e58 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/META-INF/MANIFEST.MF @@ -21,6 +21,7 @@ Require-Bundle: com.raytheon.uf.common.dataplugin.gfe;bundle-version="1.12.1174" org.springframework, org.junit;bundle-version="1.0.0", com.raytheon.edex.plugin.grib, + com.raytheon.uf.edex.plugin.grid, com.raytheon.messaging.mhs;bundle-version="1.0.0", com.raytheon.uf.common.datastorage.hdf5;bundle-version="1.11.24", ncsa.hdf5;bundle-version="2.4.0", @@ -31,9 +32,9 @@ Require-Bundle: com.raytheon.uf.common.dataplugin.gfe;bundle-version="1.12.1174" com.raytheon.edex.plugin.satellite;bundle-version="1.12.1174", com.raytheon.uf.edex.auth;bundle-version="1.12.1174", com.raytheon.uf.common.auth;bundle-version="1.12.1174", - com.raytheon.uf.common.plugin.nwsauth;bundle-version="1.12.1174", com.raytheon.uf.common.site;bundle-version="1.12.1174", - ucar.nc2;bundle-version="1.0.0" + ucar.nc2;bundle-version="1.0.0", + com.raytheon.uf.common.parameter;bundle-version="1.0.0" Export-Package: com.raytheon.edex.plugin.gfe, com.raytheon.edex.plugin.gfe.config, com.raytheon.edex.plugin.gfe.db.dao, @@ -51,24 +52,21 @@ Import-Package: com.raytheon.edex.db.dao, com.raytheon.edex.db.mapping, com.raytheon.edex.msg, com.raytheon.edex.plugin, - com.raytheon.edex.plugin.grib.dao, com.raytheon.edex.site, com.raytheon.edex.topo, com.raytheon.edex.util, - com.raytheon.edex.util.grib, com.raytheon.uf.common.activetable, com.raytheon.uf.common.comm, com.raytheon.uf.common.dataplugin, com.raytheon.uf.common.dataplugin.annotations, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.grib.util, + com.raytheon.uf.common.dataplugin.grid, com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.dataplugin.persist, com.raytheon.uf.common.dataplugin.warning, com.raytheon.uf.common.datastorage, com.raytheon.uf.common.datastorage.records, com.raytheon.uf.common.geospatial, + com.raytheon.uf.common.gridcoverage, com.raytheon.uf.common.message, com.raytheon.uf.common.pointdata, com.raytheon.uf.common.python, diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-common.xml b/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-common.xml index 79301ee876..fba4bf8bc1 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-common.xml +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-common.xml @@ -21,7 +21,7 @@ + depends-on="gridRegistered, textRegistered"> @@ -33,7 +33,7 @@ + factory-method="getInstance" depends-on="commonTimeRegistered"> @@ -83,5 +83,16 @@ + + + + + + + java.lang.Throwable + + + + diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-request.xml b/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-request.xml index 1520e2c58d..ecc5fa2616 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-request.xml +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/res/spring/gfe-request.xml @@ -349,14 +349,6 @@ value="com.raytheon.uf.common.dataplugin.gfe.request.CheckPermissionsRequest" /> - - - - - - diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/cache/d2dparms/D2DParmIdCache.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/cache/d2dparms/D2DParmIdCache.java index abaa6bb143..861f7acee2 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/cache/d2dparms/D2DParmIdCache.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/cache/d2dparms/D2DParmIdCache.java @@ -45,8 +45,6 @@ import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.gfe.db.objects.DatabaseID; import com.raytheon.uf.common.dataplugin.gfe.db.objects.ParmID; import com.raytheon.uf.common.dataplugin.gfe.exception.GfeException; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -60,7 +58,9 @@ import com.raytheon.uf.edex.site.SiteAwareRegistry; * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * 1/08/09 1674 bphillip Initial creation + * 01/08/09 1674 bphillip Initial creation + * 11/05/12 #1310 dgilling Modify cache to listen to plugin + * purged topic. * * * @author bphillip @@ -328,19 +328,17 @@ public class D2DParmIdCache { IFPServerConfig config = IFPServerConfigManager .getServerConfig(siteID); GFEDao dao = new GFEDao(); - GribModelLookup modelLookup = GribModelLookup.getInstance(); Set parmIds = new HashSet(); long start = System.currentTimeMillis(); List d2dModels = config.getD2dModels(); for (String d2dModelName : d2dModels) { - GridModel model = modelLookup.getModelByName(d2dModelName); String gfeModel = config.gfeModelNameMapping(d2dModelName); - if ((model != null) && (gfeModel != null)) { + if ((d2dModelName != null) && (gfeModel != null)) { List dbIds = null; try { - dbIds = dao.getD2DDatabaseIdsFromDb(model, gfeModel, - siteID); + dbIds = dao.getD2DDatabaseIdsFromDb(d2dModelName, + gfeModel, siteID); } catch (DataAccessLayerException e) { throw new PluginException( "Unable to get D2D Database Ids from database!", @@ -354,8 +352,8 @@ public class D2DParmIdCache { for (int i = 0; i < versions; i++) { try { - parmIds.addAll(dao.getD2DParmIdsFromDb(model, - dbIds.get(i))); + parmIds.addAll(dao.getD2DParmIdsFromDb( + d2dModelName, dbIds.get(i))); } catch (DataAccessLayerException e) { throw new PluginException( "Error adding parmIds to D2DParmIdCache!!", @@ -396,4 +394,11 @@ public class D2DParmIdCache { } return size; } + + public void pluginPurged(String pluginName) + throws GfeConfigurationException, PluginException { + if (pluginName.equals("grid")) { + buildCache(null); + } + } } diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/config/GFESiteActivation.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/config/GFESiteActivation.java index 8d4231b747..8cdb67e5c9 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/config/GFESiteActivation.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/config/GFESiteActivation.java @@ -46,8 +46,6 @@ import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.gfe.db.objects.DatabaseID; import com.raytheon.uf.common.dataplugin.gfe.db.objects.DatabaseID.DataType; import com.raytheon.uf.common.dataplugin.gfe.exception.GfeException; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; import com.raytheon.uf.common.site.notify.SendSiteActivationNotifications; import com.raytheon.uf.common.site.notify.SiteActivationNotification; import com.raytheon.uf.common.site.notify.SiteActivationNotification.ACTIVATIONSTATUS; @@ -408,25 +406,24 @@ public class GFESiteActivation implements ISiteActivationListener { boolean clearTime = false; try { GFEDao dao = new GFEDao(); - GribModelLookup modelLookup = GribModelLookup - .getInstance(); List d2dModels = configRef.getD2dModels(); List> idsByVersion = new ArrayList>( 5); for (String d2dModelName : d2dModels) { - GridModel model = modelLookup - .getModelByName(d2dModelName); + String gfeModel = configRef .gfeModelNameMapping(d2dModelName); - if ((model != null) && (gfeModel != null)) { + if ((d2dModelName != null) + && (gfeModel != null)) { int versions = configRef .desiredDbVersions(new DatabaseID( siteID, DataType.GRID, "", gfeModel)); List dbIds = dao - .getD2DDatabaseIdsFromDb(model, - gfeModel, siteID, versions); + .getD2DDatabaseIdsFromDb( + d2dModelName, gfeModel, + siteID, versions); while (versions > idsByVersion.size()) { idsByVersion.add(new ArrayList( @@ -593,4 +590,4 @@ public class GFESiteActivation implements ISiteActivationListener { return retVal; } -} +} \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/db/dao/GFEDao.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/db/dao/GFEDao.java index bc8129bee3..00d2e830cb 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/db/dao/GFEDao.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/db/dao/GFEDao.java @@ -72,9 +72,10 @@ import com.raytheon.uf.common.dataplugin.gfe.server.notify.GridUpdateNotificatio import com.raytheon.uf.common.dataplugin.gfe.server.notify.LockNotification; import com.raytheon.uf.common.dataplugin.gfe.type.Pair; import com.raytheon.uf.common.dataplugin.gfe.util.GfeUtil; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridInfoConstants; +import com.raytheon.uf.common.dataplugin.grid.GridInfoRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.dataplugin.persist.IPersistable; @@ -87,8 +88,6 @@ import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.common.time.TimeRange; import com.raytheon.uf.common.time.util.TimeUtil; import com.raytheon.uf.edex.database.DataAccessLayerException; -import com.raytheon.uf.edex.database.dao.CoreDao; -import com.raytheon.uf.edex.database.dao.DaoConfig; import com.raytheon.uf.edex.database.purge.PurgeLogger; import com.raytheon.uf.edex.database.query.DatabaseQuery; @@ -116,8 +115,6 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; */ public class GFEDao extends DefaultPluginDao { - private static String D2D_PARM_QUERY_STRING = "select model.id,model.parameterabbreviation, level.masterLevel_name, level.levelonevalue, level.leveltwovalue from awips.grib_models model, awips.level level where model.modelName = ':modelName' and model.id in (select distinct modelinfo_id from awips.grib where reftime=':reftime') and model.level_id = level.id"; - public GFEDao() throws PluginException { super("gfe"); } @@ -596,12 +593,12 @@ public class GFEDao extends DefaultPluginDao { @SuppressWarnings("unchecked") public List getD2DForecastTimes(DatabaseID dbId) throws DataAccessLayerException { - DatabaseQuery query = new DatabaseQuery(GribRecord.class.getName()); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); query.addDistinctParameter("dataTime.fcstTime"); try { IFPServerConfig config = IFPServerConfigManager .getServerConfig(dbId.getSiteId()); - query.addQueryParam("modelInfo.modelName", + query.addQueryParam(GridConstants.DATASET_ID, config.d2dModelNameMapping(dbId.getModelName())); } catch (GfeConfigurationException e) { throw new DataAccessLayerException( @@ -614,22 +611,22 @@ public class GFEDao extends DefaultPluginDao { } /** - * Retrieves a GribRecord from the grib metadata database based on a ParmID + * Retrieves a GridRecord from the grib metadata database based on a ParmID * and a TimeRange * * @param id - * The parmID of the desired GribRecord + * The parmID of the desired GridRecord * @param timeRange - * The timeRange of the desired GribRecord - * @return The GribRecord from the grib metadata database + * The timeRange of the desired GridRecord + * @return The GridRecord from the grib metadata database * @throws DataAccessLayerException * If errors occur while querying the metadata database */ - public GribRecord getD2DGrid(ParmID id, TimeRange timeRange, + public GridRecord getD2DGrid(ParmID id, TimeRange timeRange, GridParmInfo info) throws DataAccessLayerException { - List records = queryByD2DParmId(id); + List records = queryByD2DParmId(id); List gribTimes = new ArrayList(); - for (GribRecord record : records) { + for (GridRecord record : records) { gribTimes.add(record.getDataTime().getValidPeriod()); } @@ -641,15 +638,15 @@ public class GFEDao extends DefaultPluginDao { gribTime.getEnd()); if (timeRange.getEnd().equals(time.getEnd()) || !info.getTimeConstraints().anyConstraints()) { - GribRecord retVal = records.get(i); - retVal.setPluginName("grib"); + GridRecord retVal = records.get(i); + retVal.setPluginName(GridConstants.GRID); return retVal; } } else if (D2DGridDatabase.isNonAccumDuration(id, gribTimes)) { if (timeRange.getStart().equals(gribTime.getEnd()) || timeRange.equals(gribTime)) { - GribRecord retVal = records.get(i); - retVal.setPluginName("grib"); + GridRecord retVal = records.get(i); + retVal.setPluginName(GridConstants.GRID); return retVal; } @@ -658,8 +655,8 @@ public class GFEDao extends DefaultPluginDao { gribTime.getStart()); if ((timeRange.getStart().equals(time.getStart()) || !info .getTimeConstraints().anyConstraints())) { - GribRecord retVal = records.get(i); - retVal.setPluginName("grib"); + GridRecord retVal = records.get(i); + retVal.setPluginName(GridConstants.GRID); return retVal; } } @@ -674,18 +671,18 @@ public class GFEDao extends DefaultPluginDao { } /** - * Gets a list of GribRecords from the grib metadata database which match + * Gets a list of GridRecords from the grib metadata database which match * the given ParmID * * @param id * The ParmID to search with - * @return The list of GribRecords from the grib metadata database which + * @return The list of GridRecords from the grib metadata database which * match the given ParmID * @throws DataAccessLayerException * If errors occur while querying the metadata database */ @SuppressWarnings("unchecked") - public List queryByD2DParmId(ParmID id) + public List queryByD2DParmId(ParmID id) throws DataAccessLayerException { Session s = null; try { @@ -716,26 +713,26 @@ public class GFEDao extends DefaultPluginDao { if (level == null) { logger.warn("Unable to query D2D parms, ParmID " + id + " does not map to a level"); - return new ArrayList(); + return new ArrayList(); } s = getHibernateTemplate().getSessionFactory().openSession(); - Criteria modelCrit = s.createCriteria(GribModel.class); - Criterion baseCrit = Restrictions.eq("level", level); + Criteria modelCrit = s.createCriteria(GridInfoRecord.class); + Criterion baseCrit = Restrictions + .eq(GridInfoConstants.LEVEL, level); DatabaseID dbId = id.getDbId(); try { IFPServerConfig config = IFPServerConfigManager .getServerConfig(dbId.getSiteId()); baseCrit = Restrictions.and(baseCrit, Restrictions.eq( - "modelName", + GridInfoConstants.DATASET_ID, config.d2dModelNameMapping(dbId.getModelName()))); } catch (GfeConfigurationException e) { throw new DataAccessLayerException( "Error occurred looking up model name mapping", e); } - String abbreviation = DataFieldTableLookup.getInstance() .lookupDataName(id.getParmName()); if (abbreviation == null) { @@ -746,24 +743,25 @@ public class GFEDao extends DefaultPluginDao { .and(baseCrit, Restrictions.or( Restrictions - .sqlRestriction("lower(parameterAbbreviation) = '" + .sqlRestriction("lower(parameter_abbreviation) = '" + abbreviation + "'"), Restrictions - .sqlRestriction("lower(parameterAbbreviation) like '" + .sqlRestriction("lower(parameter_abbreviation) like '" + abbreviation + "%hr'"))); modelCrit.add(abbrevCrit); List results = modelCrit.list(); - GribModel model = null; + GridInfoRecord model = null; if (results.size() == 0) { - return new ArrayList(0); + return new ArrayList(0); } else if (results.size() > 1) { // hours matched, take hour with least number that matches exact // param Pattern p = Pattern.compile("^" + abbreviation + "(\\d+)hr$"); int lowestHr = -1; - for (GribModel m : (List) results) { - String param = m.getParameterAbbreviation().toLowerCase(); + for (GridInfoRecord m : (List) results) { + String param = m.getParameter().getAbbreviation() + .toLowerCase(); if (param.equals(abbreviation) && (lowestHr < 0)) { model = m; } else { @@ -779,11 +777,11 @@ public class GFEDao extends DefaultPluginDao { } } else { - model = (GribModel) results.get(0); + model = (GridInfoRecord) results.get(0); } - Criteria recordCrit = s.createCriteria(GribRecord.class); - baseCrit = Restrictions.eq("modelInfo", model); + Criteria recordCrit = s.createCriteria(GridRecord.class); + baseCrit = Restrictions.eq("info", model); baseCrit = Restrictions.and( baseCrit, Restrictions.eq("dataTime.refTime", @@ -849,7 +847,7 @@ public class GFEDao extends DefaultPluginDao { if (dTimeList.contains(tr)) { timeList.add(new TimeRange(tr.getStart(), tr.getStart())); } - } + } if (!timeList.isEmpty()) { return timeList; @@ -870,12 +868,11 @@ public class GFEDao extends DefaultPluginDao { return timeList; } - private List executeD2DParmQuery(ParmID id) throws DataAccessLayerException { List times = new ArrayList(); - List records = queryByD2DParmId(id); - for (GribRecord record : records) { + List records = queryByD2DParmId(id); + for (GridRecord record : records) { times.add(record.getDataTime()); } return times; @@ -902,36 +899,29 @@ public class GFEDao extends DefaultPluginDao { }); } - public List getD2DDatabaseIdsFromDb(GridModel d2dModel, + public List getD2DDatabaseIdsFromDb(String d2dModelName, String gfeModel, String siteID) throws DataAccessLayerException { - return getD2DDatabaseIdsFromDb(d2dModel, gfeModel, siteID, -1); + return getD2DDatabaseIdsFromDb(d2dModelName, gfeModel, siteID, -1); } - public List getD2DDatabaseIdsFromDb(GridModel d2dModel, + public List getD2DDatabaseIdsFromDb(String d2dModelName, String gfeModel, String siteID, int maxRecords) throws DataAccessLayerException { List dbInventory = new ArrayList(); - StringBuffer modelQueryString = new StringBuffer(); - modelQueryString.append("select id from awips.grib_models where "); - modelQueryString.append("modelName = '").append(d2dModel.getName()) - .append("'"); - - StringBuffer gribQueryString = new StringBuffer(); - gribQueryString - .append("select distinct refTime from awips.grib where modelinfo_id in (") - .append(modelQueryString).append(") order by refTime DESC "); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); + query.addDistinctParameter("dataTime.refTime"); + query.addQueryParam(GridConstants.DATASET_ID, d2dModelName); + query.addOrder("dataTime.refTime", false); if (maxRecords > 0) { - gribQueryString.append("limit ").append(maxRecords); + query.setMaxResults(maxRecords); } + List result = this.queryByCriteria(query); - QueryResult result = (QueryResult) new CoreDao(DaoConfig.DEFAULT) - .executeNativeSql(gribQueryString.toString()); - - for (int i = 0; i < result.getResultCount(); i++) { + for (Object obj : result) { DatabaseID dbId = null; dbId = new DatabaseID(siteID, DataType.GRID, "D2D", gfeModel, - (Date) result.getRowColumnValue(i, 0)); + (Date) obj); try { GridDatabase db = GridParmManager.getDb(dbId); if ((db != null) && !dbInventory.contains(dbId)) { @@ -959,10 +949,10 @@ public class GFEDao extends DefaultPluginDao { * be found. * @throws DataAccessLayerException */ - public DatabaseID getLatestD2DDatabaseIdsFromDb(GridModel d2dModel, + public DatabaseID getLatestD2DDatabaseIdsFromDb(String d2dModelName, String gfeModel, String siteID) throws DataAccessLayerException { - List dbIds = getD2DDatabaseIdsFromDb(d2dModel, gfeModel, - siteID, 1); + List dbIds = getD2DDatabaseIdsFromDb(d2dModelName, + gfeModel, siteID, 1); if (!dbIds.isEmpty()) { return dbIds.get(0); } else { @@ -970,28 +960,30 @@ public class GFEDao extends DefaultPluginDao { } } - public Set getD2DParmIdsFromDb(GridModel model, DatabaseID dbId) + public Set getD2DParmIdsFromDb(String d2dModelName, DatabaseID dbId) throws DataAccessLayerException { Set parmIds = new HashSet(); - String query = D2D_PARM_QUERY_STRING.replace(":modelName", - model.getName()); - query = query.replace( - ":reftime", + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); + query.addDistinctParameter(GridConstants.PARAMETER_ABBREVIATION); + query.addDistinctParameter(GridConstants.MASTER_LEVEL_NAME); + query.addDistinctParameter(GridConstants.LEVEL_ONE); + query.addDistinctParameter(GridConstants.LEVEL_TWO); + query.addQueryParam(GridConstants.DATASET_ID, d2dModelName); + query.addQueryParam( + "dataTime.refTime", TimeUtil.formatDate(dbId.getModelTimeAsDate()).replaceAll("_", " ")); - QueryResult result = (QueryResult) this.executeNativeSql(query); + List result = this.queryByCriteria(query); - for (int i = 0; i < result.getResultCount(); i++) { + for (Object obj : result) { + Object[] objArr = (Object[]) obj; String levelName = GridTranslator.getShortLevelName( - (String) result.getRowColumnValue(i, "masterlevel_name"), - (Double) result.getRowColumnValue(i, "levelonevalue"), - (Double) result.getRowColumnValue(i, "leveltwovalue")); + (String) objArr[1], (Double) objArr[2], (Double) objArr[3]); if (!levelName.equals(LevelFactory.UNKNOWN_LEVEL)) { - String abbrev = (String) result.getRowColumnValue(i, - "parameterabbreviation"); + String abbrev = (String) objArr[0]; abbrev = DataFieldTableLookup.getInstance().lookupCdlName( abbrev); ParmID newParmId = new ParmID(abbrev, dbId, levelName); diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/database/D2DGridDatabase.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/database/D2DGridDatabase.java index 7d5464987f..119b6fc728 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/database/D2DGridDatabase.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/database/D2DGridDatabase.java @@ -37,13 +37,10 @@ import java.util.TreeSet; import javax.measure.converter.UnitConverter; import javax.measure.unit.Unit; -import com.raytheon.edex.plugin.gfe.cache.gridlocations.GridLocationCache; import com.raytheon.edex.plugin.gfe.config.IFPServerConfig; import com.raytheon.edex.plugin.gfe.config.IFPServerConfigManager; import com.raytheon.edex.plugin.gfe.db.dao.GFEDao; import com.raytheon.edex.plugin.gfe.exception.GfeConfigurationException; -import com.raytheon.edex.plugin.grib.dao.GribDao; -import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; import com.raytheon.edex.plugin.grib.util.GribParamInfoLookup; import com.raytheon.edex.plugin.grib.util.ParameterInfo; import com.raytheon.edex.util.Util; @@ -62,14 +59,14 @@ import com.raytheon.uf.common.dataplugin.gfe.server.message.ServerResponse; import com.raytheon.uf.common.dataplugin.gfe.slice.IGridSlice; import com.raytheon.uf.common.dataplugin.gfe.slice.ScalarGridSlice; import com.raytheon.uf.common.dataplugin.gfe.slice.VectorGridSlice; -import com.raytheon.uf.common.dataplugin.grib.GribPathProvider; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; +import com.raytheon.uf.common.dataplugin.grid.GridPathProvider; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; 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.records.FloatDataRecord; import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.message.WsId; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; @@ -77,6 +74,7 @@ import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.TimeRange; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.plugin.PluginFactory; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * Singleton that assists with grid data @@ -110,10 +108,7 @@ public class D2DGridDatabase extends VGridDatabase { .getNamedHandler("GFEPerformanceLogger"); /** The remap object used for resampling grids */ - private RemapGrid remap; - - /** The source GridLocation (The D2D grid coverage) */ - private GridLocation inputLoc; + private Map remap = new HashMap(); /** The destination GridLocation (The local GFE grid coverage) */ private GridLocation outputLoc; @@ -137,35 +132,18 @@ public class D2DGridDatabase extends VGridDatabase { if (valid) { loadParms(); - - String siteId = dbId.getSiteId(); - GridLocationCache locCache = GridLocationCache.getInstance(dbId - .getSiteId()); - String gfeModelName = dbId.getModelName(); - inputLoc = locCache.getGridLocation(gfeModelName); - - if (inputLoc == null) { - String d2dModelName = this.config - .d2dModelNameMapping(gfeModelName); - GridCoverage awipsGrid = GribSpatialCache.getInstance() - .getGrid(d2dModelName); - - if (awipsGrid == null) { - throw new GfeException( - "Unable to lookup coverage for GFE Model [" - + gfeModelName + "] for site [" + siteId - + "]. GribSpatialCache for d2dModel [" - + d2dModelName + "] returned null"); - } - - inputLoc = new GridLocation(d2dModelName, awipsGrid); - inputLoc.setSiteId(d2dModelName); - locCache.addGridLocation(gfeModelName, inputLoc); - } - outputLoc = this.config.dbDomain(); + } + } - Rectangle subdomain = NetCDFUtils.getSubGridDims(this.inputLoc, + private RemapGrid getOrCreateRemap(GridCoverage awipsGrid) { + RemapGrid remap = this.remap.get(awipsGrid.getId()); + if (remap == null) { + String gfeModelName = dbId.getModelName(); + String d2dModelName = this.config.d2dModelNameMapping(gfeModelName); + GridLocation inputLoc = new GridLocation(d2dModelName, awipsGrid); + inputLoc.setSiteId(d2dModelName); + Rectangle subdomain = NetCDFUtils.getSubGridDims(inputLoc, this.outputLoc); // fix up coordinates for 0,0 in upper left in A2 @@ -175,14 +153,15 @@ public class D2DGridDatabase extends VGridDatabase { if (subdomain.isEmpty()) { statusHandler.warn(this.dbId + ": GFE domain does not overlap dataset domain."); - this.remap = null; } else { GridLocation subGloc = new GridLocation(dbId.toString(), - this.inputLoc, subdomain); - this.remap = new RemapGrid(subGloc, this.outputLoc); + inputLoc, subdomain); + remap = new RemapGrid(subGloc, this.outputLoc); + this.remap.put(awipsGrid.getId(), remap); } } + return remap; } @Override @@ -528,7 +507,7 @@ public class D2DGridDatabase extends VGridDatabase { GridParmInfo gpi, boolean convertUnit) throws GfeException { Grid2DFloat bdata = null; - GribRecord d2dRecord = null; + GridRecord d2dRecord = null; long t0 = System.currentTimeMillis(); GFEDao dao = null; @@ -568,7 +547,8 @@ public class D2DGridDatabase extends VGridDatabase { // Resample the data to fit desired region Grid2DFloat retVal; try { - retVal = this.remap.remap(bdata, fillV, gpi.getMaxValue(), + RemapGrid remap = getOrCreateRemap(d2dRecord.getLocation()); + retVal = remap.remap(bdata, fillV, gpi.getMaxValue(), gpi.getMinValue(), gpi.getMinValue()); if (convertUnit && d2dRecord != null) { convertUnits(d2dRecord, retVal, gpi.getUnitObject()); @@ -604,10 +584,10 @@ public class D2DGridDatabase extends VGridDatabase { * @throws GfeException * If the source and target units are incompatible */ - private void convertUnits(GribRecord d2dRecord, Grid2DFloat data, + private void convertUnits(GridRecord d2dRecord, Grid2DFloat data, Unit targetUnit) throws GfeException { - Unit sourceUnit = d2dRecord.getModelInfo().getParameterUnitObject(); + Unit sourceUnit = d2dRecord.getParameter().getUnit(); if (sourceUnit.equals(targetUnit)) { return; } @@ -651,10 +631,10 @@ public class D2DGridDatabase extends VGridDatabase { } catch (PluginException e1) { throw new GfeException("Unable to get GFE dao!!", e1); } - GribRecord uRecord = null; - GribRecord vRecord = null; - GribRecord sRecord = null; - GribRecord dRecord = null; + GridRecord uRecord = null; + GridRecord vRecord = null; + GridRecord sRecord = null; + GridRecord dRecord = null; try { // Get the metadata from the grib metadata database @@ -685,7 +665,8 @@ public class D2DGridDatabase extends VGridDatabase { } try { - this.remap.remapUV(uData, vData, fillV, gpi.getMaxValue(), + RemapGrid remap = getOrCreateRemap(uRecord.getLocation()); + remap.remapUV(uData, vData, fillV, gpi.getMaxValue(), gpi.getMinValue(), gpi.getMinValue(), true, true, mag, dir); } catch (Exception e) { @@ -721,7 +702,8 @@ public class D2DGridDatabase extends VGridDatabase { } try { - this.remap.remap(sData, dData, fillV, gpi.getMaxValue(), + RemapGrid remap = getOrCreateRemap(sRecord.getLocation()); + remap.remap(sData, dData, fillV, gpi.getMaxValue(), gpi.getMinValue(), gpi.getMinValue(), mag, dir); } catch (Exception e) { throw new GfeException("Unable to remap wind grids", e); @@ -756,21 +738,22 @@ public class D2DGridDatabase extends VGridDatabase { * @return The raw data * @throws GfeException */ - private Grid2DFloat getRawGridData(GribRecord d2dRecord) + private Grid2DFloat getRawGridData(GridRecord d2dRecord) throws GfeException { try { - GribDao dao = new GribDao(); + GridDao dao = new GridDao(); // reimplementing this call here with subgrid support // dao.getHDF5Data(d2dRecord, -1); // TODO should we add subgrid support to GribDao or PluginDao IDataStore dataStore = dao.getDataStore(d2dRecord); - GridLocation gloc = this.remap.getSourceGloc(); + GridLocation gloc = getOrCreateRemap(d2dRecord.getLocation()) + .getSourceGloc(); - String abbrev = d2dRecord.getModelInfo().getParameterAbbreviation(); + String abbrev = d2dRecord.getParameter().getAbbreviation(); String group, dataset; - if (GribPathProvider.STATIC_PARAMETERS.contains(abbrev)) { - group = "/"; + if (GridPathProvider.STATIC_PARAMETERS.contains(abbrev)) { + group = "/" + d2dRecord.getLocation().getId(); dataset = abbrev; } else { group = d2dRecord.getDataURI(); diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/SaveCombinationsFileHandler.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/SaveCombinationsFileHandler.java index 3661e9568e..e93084ab1a 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/SaveCombinationsFileHandler.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/SaveCombinationsFileHandler.java @@ -105,12 +105,11 @@ public class SaveCombinationsFileHandler implements if (isAdded) { changeType = FileChangeType.ADDED; } - EDEXUtil.getMessageProducer() - .sendAsync( - "utilityNotify", - new FileUpdatedMessage(localization, FileUtil.join( - COMBO_FILE_DIR, request.getFileName()), - changeType)); + EDEXUtil.getMessageProducer().sendAsync( + "utilityNotify", + new FileUpdatedMessage(localization, FileUtil.join( + COMBO_FILE_DIR, request.getFileName()), changeType, + localFile.lastModified())); } finally { if (file != null) { file.close(); diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/CheckPermissionsRequestHandler.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/CheckPermissionsRequestHandler.java index be73865352..603554ad48 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/CheckPermissionsRequestHandler.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/CheckPermissionsRequestHandler.java @@ -20,10 +20,11 @@ package com.raytheon.edex.plugin.gfe.server.handler.svcbu; import com.raytheon.edex.plugin.gfe.svcbackup.SvcBackupUtil; +import com.raytheon.uf.common.auth.exception.AuthorizationException; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.dataplugin.gfe.request.CheckPermissionsRequest; import com.raytheon.uf.common.dataplugin.gfe.server.message.ServerResponse; -import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.edex.auth.req.AbstractPrivilegedRequestHandler; import com.raytheon.uf.edex.auth.resp.AuthorizationResponse; /** @@ -43,11 +44,13 @@ import com.raytheon.uf.edex.auth.resp.AuthorizationResponse; * @version 1.0 */ -public class CheckPermissionsRequestHandler implements IRequestHandler{ +public class CheckPermissionsRequestHandler extends + AbstractPrivilegedRequestHandler { + @Override public Object handleRequest(CheckPermissionsRequest request) throws Exception { - AuthorizationResponse response = authorized(request.getUser()); + AuthorizationResponse response = authorized(request.getUser(), request); ServerResponse sr = new ServerResponse(); if (!response.isAuthorized()) { sr.addMessage(response.getResponseMessage()); @@ -55,7 +58,10 @@ public class CheckPermissionsRequestHandler implements IRequestHandler * @@ -68,7 +69,7 @@ public class ExportConfRequestHandler extends @Override public AuthorizationResponse authorized(IUser user, - ExportConfRequest request) { - return SvcBackupUtil.authorizeWithLocalization(user); + ExportConfRequest request) throws AuthorizationException { + return SvcBackupUtil.authorizeWithLocalization(user, request); } } diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/svcbackup/SvcBackupUtil.java b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/svcbackup/SvcBackupUtil.java index ef65e3272e..2bab561d3d 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/svcbackup/SvcBackupUtil.java +++ b/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/svcbackup/SvcBackupUtil.java @@ -29,8 +29,10 @@ import java.util.Properties; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import com.raytheon.uf.common.auth.exception.AuthorizationException; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.dataplugin.gfe.exception.GfeException; +import com.raytheon.uf.common.dataplugin.gfe.request.AbstractGfePrivilegedRequest; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -38,8 +40,8 @@ import com.raytheon.uf.common.util.RunProcess; import com.raytheon.uf.edex.auth.AuthManager; import com.raytheon.uf.edex.auth.AuthManagerFactory; import com.raytheon.uf.edex.auth.resp.AuthorizationResponse; -import com.raytheon.uf.edex.auth.roles.IRole; import com.raytheon.uf.edex.auth.roles.IRoleStorage; +import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.core.props.PropertiesFactory; /** @@ -51,9 +53,9 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory; * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Oct 9, 2009 bphillip Initial creation - * Sep 19,2011 10955 rferrel make sure process destroy is called. - * Nov 15,2012 15614 jdynina Added check for national center + * Oct 09, 2009 bphillip Initial creation + * Sep 19, 2011 10955 rferrel make sure process destroy is called. + * Jun 12, 2012 00609 djohnson Use EDEXUtil for EDEX_HOME. * * * @@ -64,9 +66,11 @@ public class SvcBackupUtil { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(SvcBackupUtil.class); - public static String OPERATION_FAIL = "Failure"; + private static final String LOCALIZATION = "Localization"; - public static String OPERATION_SUCCESS = "Success"; + public static final String OPERATION_FAIL = "Failure"; + + public static final String OPERATION_SUCCESS = "Success"; /** The logger instance */ protected static transient Log logger = LogFactory @@ -182,7 +186,7 @@ public class SvcBackupUtil { FileInputStream fis = null; try { fis = new FileInputStream( - System.getProperty("edex.home") + EDEXUtil.EDEX_HOME + "/../GFESuite/ServiceBackup/configuration/svcbu.properties"); svcbuProperties.load(fis); } catch (Exception e) { @@ -236,33 +240,27 @@ public class SvcBackupUtil { "LOCK_DIR") + File.separator; lockDir = lockDir.replace("${GFESUITE_HOME}", - System.getProperty("edex.home") + "/../GFESuite" + EDEXUtil.EDEX_HOME + "/../GFESuite" + File.separator); return lockDir; } - public static AuthorizationResponse authorizeWithLocalization(IUser user) { + public static AuthorizationResponse authorizeWithLocalization( +IUser user, + AbstractGfePrivilegedRequest request) + throws AuthorizationException { AuthManager manager = AuthManagerFactory.getInstance().getManager(); IRoleStorage roles = manager.getRoleStorage(); - String roleId = "com.raytheon.localization.site/common_static/gfe"; - IRole role = roles.lookupRole(roleId); - if (role != null && role.validForUser(user)) { + String roleId = request.getRoleId(); + if (roles + .isAuthorized(roleId, user.uniqueId().toString(), LOCALIZATION)) { return new AuthorizationResponse(true); } - return new AuthorizationResponse(false, "User, " + user.uniqueId() + return new AuthorizationResponse(false, "User, " + user + ", is not authorized to perform request needing role: " + roleId); } - - public static boolean ncCheck() { - String nationalCenter = SvcBackupUtil.getSvcBackupProperties() - .getProperty("NATIONAL_CENTER"); - if (nationalCenter.equals("1")) { - return true; - } - return false; - } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/GribDecoder.py b/edexOsgi/com.raytheon.edex.plugin.grib/GribDecoder.py index f6428c62c5..1c310ca965 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/GribDecoder.py +++ b/edexOsgi/com.raytheon.edex.plugin.grib/GribDecoder.py @@ -43,21 +43,22 @@ from com.raytheon.uf.common.time import TimeRange from com.raytheon.uf.common.geospatial import MapUtil from com.raytheon.uf.common.serialization import SerializationUtil -from com.raytheon.uf.common.dataplugin.grib import GribRecord -from com.raytheon.uf.common.dataplugin.grib import GribModel +from com.raytheon.uf.common.dataplugin.grid import GridRecord -from com.raytheon.uf.common.dataplugin.grib.spatial.projections import LambertConformalGridCoverage -from com.raytheon.uf.common.dataplugin.grib.spatial.projections import LatLonGridCoverage -from com.raytheon.uf.common.dataplugin.grib.spatial.projections import MercatorGridCoverage -from com.raytheon.uf.common.dataplugin.grib.spatial.projections import PolarStereoGridCoverage -from com.raytheon.uf.common.dataplugin.grib.spatial.projections import Corner -from com.raytheon.uf.common.dataplugin.grib.util import GribModelLookup +from com.raytheon.uf.common.gridcoverage import LambertConformalGridCoverage +from com.raytheon.uf.common.gridcoverage import LatLonGridCoverage +from com.raytheon.uf.common.gridcoverage import MercatorGridCoverage +from com.raytheon.uf.common.gridcoverage import PolarStereoGridCoverage +from com.raytheon.uf.common.gridcoverage.lookup import GridCoverageLookup +from com.raytheon.uf.common.gridcoverage import Corner +from com.raytheon.edex.plugin.grib.util import GribModelLookup + +from com.raytheon.uf.common.dataplugin.level.mapping import LevelMapper from com.raytheon.uf.common.dataplugin.level import Level from com.raytheon.uf.common.dataplugin.level import LevelFactory from com.raytheon.edex.plugin.grib.spatial import GribSpatialCache -from com.raytheon.edex.plugin.grib.util import GribModelCache from com.raytheon.edex.util.grib import GribTableLookup from com.raytheon.edex.util import Util @@ -65,7 +66,11 @@ from com.raytheon.edex.plugin.grib import Grib1Decoder from com.raytheon.edex.util.grib import GribParamTranslator -PLUGIN_NAME = "grib" +from com.raytheon.uf.common.parameter import Parameter; +from com.raytheon.uf.common.parameter.mapping import ParameterMapper; + + +PLUGIN_NAME = "grid" # Static values for accessing parameter lookup tables PARAMETER_TABLE = "4.2" @@ -196,8 +201,8 @@ class GribDecoder(): if record != None: records.append(record) - recordIndex = recordIndex + 1 - fieldIndex = 0 + recordIndex = recordIndex + 1 + fieldIndex = 0 except: LogStream.logProblem("Error processing file [", self.fileName, "]: ", LogStream.exc()) finally: @@ -355,23 +360,17 @@ class GribDecoder(): else: if not thinnedGrid: numpyDataArray = data - - - # - # Synchronizes model information with the database. - # - - pdsSectionValues['model'].setGridid(gdsSectionValues['coverage'].getName()) - self._createModelName(pdsSectionValues['model']) - - + + origCoverage = gdsSectionValues['coverage'] + # check sub gridding - modelName = pdsSectionValues['model'].getModelName() + modelName = self._createModelName(pdsSectionValues, origCoverage) spatialCache = GribSpatialCache.getInstance() - subCoverage = spatialCache.getSubGridCoverage(modelName) + gridCoverage = gdsSectionValues['coverage'] + subCoverage = spatialCache.getSubGridCoverage(modelName, gridCoverage) if subCoverage is not None: - subGrid = spatialCache.getSubGrid(modelName) + subGrid = spatialCache.getSubGrid(modelName, gridCoverage) # resize the data array numpyDataArray = numpy.resize(numpyDataArray, (ny, nx)) startx = subGrid.getUpperLeftX() @@ -399,49 +398,40 @@ class GribDecoder(): # set the new coverage gdsSectionValues['coverage'] = subCoverage - numpyDataArray = numpy.resize(numpyDataArray, (1, metadata[4])) - pdsSectionValues['model'].setLocation(gdsSectionValues['coverage']) + numpyDataArray = numpy.resize(numpyDataArray, (1, metadata[4])) - - newAbbr = GribParamTranslator.getInstance().translateParameter(2, pdsSectionValues['model'], dataTime) + newAbbr = GribParamTranslator.getInstance().translateParameter(2, pdsSectionValues['parameterAbbreviation'], pdsSectionValues['centerid'], pdsSectionValues['subcenterid'], pdsSectionValues['genprocess'], dataTime, gridCoverage) if newAbbr is None: - if pdsSectionValues['model'].getParameterName() != MISSING and dataTime.getValidPeriod().getDuration() > 0: - pdsSectionValues['model'].setParameterAbbreviation(pdsSectionValues['model'].getParameterAbbreviation() + str(dataTime.getValidPeriod().getDuration() / 3600000) + "hr") + if pdsSectionValues['parameterName'] != MISSING and dataTime.getValidPeriod().getDuration() > 0: + pdsSectionValues['parameterAbbreviation'] = pdsSectionValues['parameterAbbreviation'] + str(dataTime.getValidPeriod().getDuration() / 3600000) + "hr" else: - pdsSectionValues['model'].setParameterAbbreviation(newAbbr) - pdsSectionValues['model'].setParameterAbbreviation(pdsSectionValues['model'].getParameterAbbreviation().replace('_', '-')) - - pdsSectionValues['model'].setParameterName(GribParamTranslator.getInstance().getParameterNameAlias(pdsSectionValues['model'])) - pdsSectionValues['model'].generateId() - if pdsSectionValues['model'].getParameterName() == MISSING: - model = pdsSectionValues['model'] - else: - model = GribModelCache.getInstance().getModel(pdsSectionValues['model']) - - + pdsSectionValues['parameterAbbreviation'] = newAbbr + pdsSectionValues['parameterAbbreviation'] = pdsSectionValues['parameterAbbreviation'].replace('_', '-') # Construct the GribRecord - record = GribRecord() + record = GridRecord() record.setPluginName(PLUGIN_NAME) record.setDataTime(dataTime) - record.setMasterTableVersion(idSectionValues['masterTableVersion']) - record.setLocalTableVersion(idSectionValues['localTableVersion']) - record.setRefTimeSignificance(idSectionValues['sigRefTime']) - record.setProductionStatus(idSectionValues['productionStatus']) - record.setProcessedDataType(idSectionValues['typeProcessedData']) - record.setLocalSectionUsed(localSectionValues is not None) - record.setLocalSection(localSectionValues) - record.setHybridGrid(hybridCoordList is not None) - record.setHybridCoordList(hybridCoordList) - record.setThinnedGrid(False) - record.setThinnedPts(thinnedPts) record.setMessageData(numpyDataArray) - record.setModelInfo(model) - record.setResCompFlags(Integer(gdsSectionValues['resCompFlags'])) + record.setLocation(gdsSectionValues['coverage']) + record.setLevel(pdsSectionValues['level']) + record.setDatasetId(modelName) + record.addExtraAttribute("centerid", Integer(pdsSectionValues['centerid'])) + record.addExtraAttribute("subcenterid", Integer(pdsSectionValues['subcenterid'])) + record.addExtraAttribute("genprocess", Integer(pdsSectionValues['genprocess'])) + record.addExtraAttribute("backGenprocess", Integer(pdsSectionValues['backGenprocess'])) + record.addExtraAttribute("pdsTemplate", Integer(pdsSectionValues['pdsTemplateNumber'])) + record.addExtraAttribute("gridid", origCoverage.getName()) + if "numForecasts" in pdsSectionValues: + record.addExtraAttribute("numForecasts", pdsSectionValues['numForecasts']) + record.setEnsembleId(pdsSectionValues['ensembleId']) + param = Parameter(pdsSectionValues['parameterAbbreviation'], pdsSectionValues['parameterName'], pdsSectionValues['parameterUnit']) + GribParamTranslator.getInstance().getParameterNameAlias(modelName, param) + record.setParameter(param) # record.setResCompFlags(Integer(gdsSectionValues['resCompFlags'])) #check if forecast used flag needs to be removed - self._checkForecastFlag(pdsSectionValues['model'], record.getDataTime()) + self._checkForecastFlag(pdsSectionValues, origCoverage, record.getDataTime()) return record @@ -506,7 +496,6 @@ class GribDecoder(): # Dictionary to hold information extracted from PDS template pdsFields = {} - model = GribModel() endTime = None forecastTime = 0 duration = 0 @@ -516,10 +505,12 @@ class GribDecoder(): pdsTemplateNumber = metadata[10] - model.setPdsTemplate(pdsTemplateNumber) + # Default to null + pdsFields['ensembleId'] = None + pdsFields['pdsTemplateNumber'] = pdsTemplateNumber # default to UNKNOWN - model.setLevel(LevelFactory.getInstance().getLevel(LevelFactory.UNKNOWN_LEVEL, float(0))); + pdsFields['level'] = LevelFactory.getInstance().getLevel(LevelFactory.UNKNOWN_LEVEL, float(0)); # Templates 0-11 are ordered the same for the most part and can therefore be processed the same # Exception cases are handled accordingly @@ -544,7 +535,6 @@ class GribDecoder(): parameterAbbreviation = parameter.getD2dAbbrev() else: parameterAbbreviation = parameter.getAbbreviation() - parameterUnit = parameter.getUnit() else: LogStream.logEvent("No parameter information for center[" + str(centerID) + "], subcenter[" + @@ -602,9 +592,19 @@ class GribDecoder(): # Special case handling for specific PDS Templates if pdsTemplateNumber == 1 or pdsTemplateNumber == 11: - model.setTypeEnsemble(Integer(pdsTemplate[15])) - model.setPerturbationNumber(Integer(pdsTemplate[16])) - model.setNumForecasts(Integer(pdsTemplate[17])) + typeEnsemble = Integer(pdsTemplate[15]) + perturbationNumber = Integer(pdsTemplate[16]) + pdsFields['numForecasts'] = Integer(pdsTemplate[17]) + if(typeEnsemble == 0): + pdsFields['ensembleId'] = "ctlh" + perturbationNumber; + elif(typeEnsemble == 1): + pdsFields['ensembleId'] = "ctll" + perturbationNumber; + elif(typeEnsemble == 2): + pdsFields['ensembleId'] = "n" + perturbationNumber; + elif(typeEnsemble == 3): + pdsFields['ensembleId'] = "p" + perturbationNumber; + else: + pdsFields['ensembleId'] = typeEnsemble + "." + perturbationNumber; if pdsTemplateNumber == 11: endTime = GregorianCalendar(pdsTemplate[18], pdsTemplate[19] - 1, pdsTemplate[20], pdsTemplate[21], pdsTemplate[22], pdsTemplate[23]) @@ -620,9 +620,9 @@ class GribDecoder(): parameterAbbreviation= parameterAbbreviation+"mean" elif (derivedForecast == 2): parameterAbbreviation= parameterAbbreviation+"sprd" - - model.setTypeEnsemble(Integer(pdsTemplate[15])) - model.setNumForecasts(Integer(pdsTemplate[16])) + + pdsFields['typeEnsemble'] = Integer(pdsTemplate[15]) + pdsFields['numForecasts'] = Integer(pdsTemplate[16]) if(pdsTemplateNumber == 12): endTime = GregorianCalendar(pdsTemplate[17], pdsTemplate[18] - 1, pdsTemplate[19], pdsTemplate[20], pdsTemplate[21], pdsTemplate[22]) @@ -633,7 +633,7 @@ class GribDecoder(): elif pdsTemplateNumber == 5 or pdsTemplateNumber == 9: - + parameterUnit = "%" probabilityNumber = pdsTemplate[15] forecastProbabilities = pdsTemplate[16] probabilityType = pdsTemplate[17] @@ -675,18 +675,21 @@ class GribDecoder(): if(pdsTemplate[2] == 6 or pdsTemplate[2] == 7): parameterAbbreviation = parameterAbbreviation+"erranl" + + parameterAbbreviation = ParameterMapper.getInstance().lookupBaseName(parameterAbbreviation, "grib"); # Constructing the GribModel object - model.setCenterid(centerID) - model.setSubcenterid(subcenterID) - model.setBackGenprocess(pdsTemplate[3]) - model.setGenprocess(pdsTemplate[4]) - model.setParameterName(parameterName) - model.setParameterAbbreviation(parameterAbbreviation) - model.setParameterUnit(parameterUnit) + pdsFields['centerid'] = centerID + pdsFields['subcenterid'] = subcenterID + pdsFields['backGenprocess'] = pdsTemplate[3] + pdsFields['genprocess'] = pdsTemplate[4] + pdsFields['parameterName'] = parameterName + pdsFields['parameterAbbreviation'] = parameterAbbreviation + pdsFields['parameterUnit'] = parameterUnit # Constructing the Level object - level = LevelFactory.getInstance().getLevel(levelName, levelOneValue, levelTwoValue, levelUnit) - model.setLevel(level); + level = LevelMapper.getInstance().lookupLevel(levelName, 'grib', levelOneValue, levelTwoValue, levelUnit) + pdsFields['level'] = level + # Derived forecasts based on all ensemble members at a horizontal @@ -747,14 +750,13 @@ class GribDecoder(): #Temporary fix to prevent invalid values getting persisted #to the database until the grib decoder is fully implemented if pdsTemplateNumber >= 13: - model.setParameterName("Unknown") - model.setParameterAbbreviation("Unknown") - model.setParameterUnit("Unknown") + pdsFields['parameterName'] ="Unknown" + pdsFields['parameterAbbreviation'] ="Unknown" + pdsFields['parameterUnit'] ="Unknown" # endtime needs to be used to calculate forecastTime and forecastTime should be used for startTime of interval pdsFields['forecastTime'] = forecastTime pdsFields['endTime'] = endTime - pdsFields['model'] = model return pdsFields @@ -808,6 +810,18 @@ class GribDecoder(): dx = self._divideBy10e6(gdsTemplate[16]) dy = self._divideBy10e6(gdsTemplate[17]) + # According to the grib2 spec 65.535 is completely valid, however it + # is impossible to define anything larger than a 5x2 grid with this + # spacing so we assume it is invalid and try to calculate a better + # value. 65.535 was chosen because it is the value encoded in the + # GFS161 model and it is completely wrong. This value is probably + # an artifact of converting from grib1 to grib2 since in grib1 this + # value would be encoded as an unsigned short with all bits as 1 + # which is a special value in grib1, but in grib2 its just wrong + if dx >= 65.535: + dx = abs(lo1-lo2)/nx + if dy >= 65.535: + dy = abs(la1-la2)/ny coverage.setSpacingUnit(DEFAULT_SPACING_UNIT2) coverage.setNx(Integer(nx)) coverage.setNy(Integer(ny)) @@ -815,8 +829,8 @@ class GribDecoder(): coverage.setLo1(lo1) coverage.setDx(dx) coverage.setDy(dy) - coverage.determineFirstGridPointCorner(scanMode) - coverage.setId(coverage.hashCode()) + corner = GribSpatialCache.determineFirstGridPointCorner(scanMode) + coverage.setFirstGridPointCorner(corner) coverage = self._getGrid(coverage) @@ -859,8 +873,8 @@ class GribDecoder(): coverage.setLo1(lo1) coverage.setDx(dx) coverage.setDy(dy) - coverage.determineFirstGridPointCorner(scanMode) - coverage.setId(coverage.hashCode()) + corner = GribSpatialCache.determineFirstGridPointCorner(scanMode) + coverage.setFirstGridPointCorner(corner) coverage = self._getGrid(coverage) @@ -891,9 +905,8 @@ class GribDecoder(): coverage.setLo1(lo1) coverage.setDx(dx) coverage.setDy(dy) - coverage.determineFirstGridPointCorner(scanMode) - - coverage.setId(coverage.hashCode()) + corner = GribSpatialCache.determineFirstGridPointCorner(scanMode) + coverage.setFirstGridPointCorner(corner) coverage = self._getGrid(coverage) @@ -926,8 +939,8 @@ class GribDecoder(): coverage.setDy(dy) coverage.setLatin1(latin1) coverage.setLatin2(latin2) - coverage.determineFirstGridPointCorner(scanMode) - coverage.setId(coverage.hashCode()) + corner = GribSpatialCache.determineFirstGridPointCorner(scanMode) + coverage.setFirstGridPointCorner(corner) coverage = self._getGrid(coverage) @@ -1020,16 +1033,14 @@ class GribDecoder(): # @return: A GribCoverage object # @rtype: GribCoverage ## - def _getGrid(self, temp): - cache = GribSpatialCache.getInstance() - + def _getGrid(self, temp): # Check the cache first - grid = cache.getGrid(temp) + grid = GribSpatialCache.getInstance().getGrid(temp) # If not found, create a new GribCoverage and store in the cache if grid is None: - cache.putGrid(temp,True, True) - grid = cache.getGrid(temp.getId()) + grid = GridCoverageLookup.getInstance().getCoverage(temp, True) + return grid @@ -1249,25 +1260,23 @@ class GribDecoder(): return retVal - def _getGridModel(self, model): - center = model.getCenterid() - subcenter = model.getSubcenterid() + def _getGridModel(self, pdsSectionValues, grid): + center = pdsSectionValues['centerid'] + subcenter = pdsSectionValues['subcenterid'] - gridid = model.getGridid() - process = model.getGenprocess() - gridModel = GribModelLookup.getInstance().getModel(center, subcenter, gridid, process) + process = pdsSectionValues['genprocess'] + gridModel = GribModelLookup.getInstance().getModel(center, subcenter, grid, process) return gridModel - def _createModelName(self, model): - gridModel = self._getGridModel(model) - if gridModel is None: - name = "UnknownModel:" + str(model.getCenterid()) + ":" + str(model.getSubcenterid()) + ":" + str(model.getGenprocess()) + ":" + model.getGridid() - else: - name = gridModel.getName() - model.setModelName(name) + def _createModelName(self, pdsSectionValues, grid): + center = pdsSectionValues['centerid'] + subcenter = pdsSectionValues['subcenterid'] + + process = pdsSectionValues['genprocess'] + return GribModelLookup.getInstance().getModelName(center, subcenter, grid, process) - def _checkForecastFlag(self, model, dataTime): - gridModel = self._getGridModel(model) + def _checkForecastFlag(self, pdsSectionValues, grid, dataTime): + gridModel = self._getGridModel(pdsSectionValues, grid) if gridModel is None: return else: diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.edex.plugin.grib/META-INF/MANIFEST.MF index d199bd7e6f..47e774c5da 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.edex.plugin.grib/META-INF/MANIFEST.MF @@ -22,22 +22,29 @@ Require-Bundle: javax.measure, com.raytheon.uf.common.datastorage.hdf5;bundle-version="1.12.1174", com.raytheon.uf.edex.awipstools;bundle-version="1.12.1174", com.raytheon.uf.common.awipstools;bundle-version="1.12.1174", - ucar.nc2;bundle-version="1.0.0" + ucar.nc2;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin.level;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin.grid Import-Package: com.raytheon.edex.exception, com.raytheon.uf.common.comm, com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.exception, com.raytheon.uf.common.dataplugin.grib.request, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.grib.subgrid, - com.raytheon.uf.common.dataplugin.grib.util, - com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.derivparam.tree, + com.raytheon.uf.common.gridcoverage, + com.raytheon.uf.common.gridcoverage.exception, + com.raytheon.uf.common.gridcoverage.lookup, + com.raytheon.uf.common.gridcoverage.subgrid, + com.raytheon.uf.common.parameter, + com.raytheon.uf.common.parameter.mapping, com.raytheon.uf.common.status, + com.raytheon.uf.edex.parameter, + com.raytheon.uf.edex.plugin.grid.dao, + com.raytheon.uf.edex.plugin.grid.topo, org.apache.camel Export-Package: com.raytheon.edex.objects.hibernate.grib, com.raytheon.edex.plugin.grib, - com.raytheon.edex.plugin.grib.dao, + com.raytheon.edex.plugin.grib.exception, com.raytheon.edex.plugin.grib.notify, com.raytheon.edex.plugin.grib.spatial, com.raytheon.edex.plugin.grib.topo, diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-common.xml b/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-common.xml index 35707f8c54..487f256ded 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-common.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-common.xml @@ -10,11 +10,11 @@ - com.raytheon.uf.common.dataplugin.level + com.raytheon.uf.common.parameter + com.raytheon.uf.common.gridcoverage @@ -24,24 +24,9 @@ + depends-on="levelRegistered,parameterRegistered,gridcoverageRegistered"> - - - - - - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-ingest.xml b/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-ingest.xml index f8f3654fc5..d2292f5bfa 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-ingest.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-ingest.xml @@ -6,7 +6,7 @@ + factory-method="getInstance" depends-on="gridRegistered" /> @@ -15,6 +15,14 @@ + + + + @@ -37,6 +45,13 @@ + + + + + + + + + - - + + + + + + + + grid + + + + - grib + grid - - - - - - - - - - - - - - - - - java.lang.Throwable - - - - - - + + + + + + ${header.CamelSplitSize} == 1 + + + + + + + + + + + + + + + + + + + + java.lang.Throwable + + + + + + + + + + + + @@ -93,6 +134,12 @@ + + + + + + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-request.xml b/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-request.xml index 566c947ccd..24e5adf942 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-request.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/res/spring/grib-request.xml @@ -11,18 +11,6 @@ - - - - - - - - - - - - diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/Grib1Decoder.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/Grib1Decoder.java index 5eb3cf3799..cd29b44a75 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/Grib1Decoder.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/Grib1Decoder.java @@ -45,40 +45,43 @@ import ucar.grid.GridParameter; import ucar.unidata.io.RandomAccessFile; import com.raytheon.edex.plugin.AbstractDecoder; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; import com.raytheon.edex.plugin.grib.util.GribLevel; -import com.raytheon.edex.plugin.grib.util.GribModelCache; +import com.raytheon.edex.plugin.grib.util.GribModelLookup; import com.raytheon.edex.plugin.grib.util.GribParameter; +import com.raytheon.edex.plugin.grib.util.GridModel; import com.raytheon.edex.util.Util; import com.raytheon.edex.util.grib.Grib1TableMap; import com.raytheon.edex.util.grib.GribParamTranslator; import com.raytheon.edex.util.grib.GribTableLookup; import com.raytheon.uf.common.comm.CommunicationException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LambertConformalGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.MercatorGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.PolarStereoGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; +import com.raytheon.uf.common.dataplugin.level.mapping.LevelMapper; +import com.raytheon.uf.common.dataplugin.level.mapping.MultipleLevelMappingException; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.LambertConformalGridCoverage; +import com.raytheon.uf.common.gridcoverage.LatLonGridCoverage; +import com.raytheon.uf.common.gridcoverage.MercatorGridCoverage; +import com.raytheon.uf.common.gridcoverage.PolarStereoGridCoverage; +import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.parameter.mapping.ParameterMapper; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.common.time.DataTime.FLAG; import com.raytheon.uf.common.time.TimeRange; -import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.common.util.mapping.MultipleMappingException; /** * Grib decoder implementation for decoding grib version 1 files. @@ -97,7 +100,7 @@ import com.raytheon.uf.edex.database.DataAccessLayerException; * @version 1 */ public class Grib1Decoder extends AbstractDecoder { - private static final transient IUFStatusHandler statusHandler = UFStatus + private static final IUFStatusHandler statusHandler = UFStatus .getHandler(Grib1Decoder.class); /** Missing value string */ @@ -106,15 +109,6 @@ public class Grib1Decoder extends AbstractDecoder { /** Set of Time range types for accumulations and averages */ private static final Set AVG_ACCUM_LIST = new HashSet(); - private static final int[] fourtyOne = new int[] { 1, 1, 2, 3, 2, 3, 2, 3, - 2, 3, 2, 3 }; - - private static final int[] fourtyTwo = new int[] { 1, 2, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 5 }; - - private static final int[] perturbation = new int[] { 1, 2, 3, 4, 5, 6, 7, - 8, 9, 10, 11, 12 }; - static { AVG_ACCUM_LIST.add(3); AVG_ACCUM_LIST.add(4); @@ -148,11 +142,11 @@ public class Grib1Decoder extends AbstractDecoder { * * @param gribFileName * The name of the file to be decoded - * @return The decoded GribRecords + * @return The decoded GridRecords * @throws GribException * If decoding the file fails or encounters problems */ - public GribRecord[] decode(String gribFileName) throws GribException { + public GridRecord[] decode(String gribFileName) throws GribException { File gribFile = new File(gribFileName); RandomAccessFile raf = null; try { @@ -172,14 +166,14 @@ public class Grib1Decoder extends AbstractDecoder { + gribFile + "]"); } ArrayList records = g1i.getRecords(); - List gribRecords = new ArrayList(); + List gribRecords = new ArrayList(); for (int i = 0; i < records.size(); i++) { - GribRecord rec = decodeRecord((Grib1Record) records.get(i), raf); + GridRecord rec = decodeRecord(records.get(i), raf); if (rec != null) { gribRecords.add(rec); } } - return gribRecords.toArray(new GribRecord[] {}); + return gribRecords.toArray(new GridRecord[] {}); } finally { if (raf != null) { try { @@ -200,14 +194,14 @@ public class Grib1Decoder extends AbstractDecoder { * The record to decode * @param raf * The file object - * @return The decoded GribRecord + * @return The decoded GridRecord * @throws GribException * If the record cannot be decoded properly */ - private GribRecord decodeRecord(Grib1Record rec, RandomAccessFile raf) + private GridRecord decodeRecord(Grib1Record rec, RandomAccessFile raf) throws GribException { - GribRecord retVal = new GribRecord(); + GridRecord retVal = new GridRecord(); // Extract the sections from the grib record Grib1ProductDefinitionSection pds = rec.getPDS(); @@ -259,6 +253,7 @@ public class Grib1Decoder extends AbstractDecoder { parameterName = param.getDescription(); parameterAbbreviation = param.getName(); parameterUnit = param.getUnit(); + } catch (NotSupportedException e) { throw new GribException("Error getting grib 1 parameter", e); } @@ -287,51 +282,53 @@ public class Grib1Decoder extends AbstractDecoder { int nx = new Integer(gridCoverage.getNx()); int ny = new Integer(gridCoverage.getNy()); - // Create the GribModel object with the appropriate values from the grib - // record - GribModel model = new GribModel(); - model.setLocation(gridCoverage); - model.setCenterid(centerid); - model.setSubcenterid(subcenterid); - model.setBackGenprocess(0); - model.setGenprocess(pdsVars.getGenProcessId()); - model.setParameterName(parameterName); - model.setParameterAbbreviation(parameterAbbreviation); - model.setParameterUnit(parameterUnit); + retVal.setLocation(gridCoverage); + int genProcess = pdsVars.getGenProcessId(); + + retVal.addExtraAttribute("centerid", centerid); + retVal.addExtraAttribute("subcenterid", subcenterid); + retVal.addExtraAttribute("genprocess", pdsVars.getGenProcessId()); + retVal.addExtraAttribute("backGenprocess", 0); // unidata does not handle isEnsemble call when // octet size is less than 40. if (pdsVars.getLength() > 40 && pdsVars.isEnsemble()) { - model.setNumForecasts(10); - model.setTypeEnsemble(pdsVars.getType()); // rcg: added code to get perturbation - int pos41 = pdsVars.getOctet(42); - int pos42 = pdsVars.getOctet(43); - int pert = pdsVars.getID(); - for (int i = 0; i < perturbation.length; i++) { - if (pos41 == fourtyOne[i] && pos42 == fourtyTwo[i]) { - pert = perturbation[i]; - break; - } + int pos42 = pdsVars.getOctet(42); + int pos43 = pdsVars.getOctet(43); + switch (pos42) { + case 1: + retVal.setEnsembleId("ctl" + pos43); + break; + case 2: + retVal.setEnsembleId("n" + pos43); + break; + case 3: + retVal.setEnsembleId("p" + pos43); + break; + case 4: + retVal.setEnsembleId("cls" + pos43); + break; + default: + retVal.setEnsembleId(pos42 + "." + pos43); } - model.setPerturbationNumber(pert); } else { - model.setNumForecasts(null); - model.setTypeEnsemble(null); - model.setPerturbationNumber(null); + retVal.setEnsembleId(null); } - model.setGridid(gridCoverage.getName()); - createModelName(model); + retVal.addExtraAttribute("gridid", gridCoverage.getName()); + + retVal.setDatasetId(createModelName(centerid, subcenterid, genProcess, + gridCoverage)); // Get the level information float[] levelMetadata = this.convertGrib1LevelInfo( pdsVars.getLevelType1(), (float) pdsVars.getLevelValue1(), pdsVars.getLevelType2(), (float) pdsVars.getLevelValue2()); - getLevelInfo(model, centerid, subcenterid, levelMetadata[0], + retVal.setLevel(getLevelInfo(centerid, subcenterid, levelMetadata[0], levelMetadata[1], levelMetadata[2], levelMetadata[3], - levelMetadata[4], levelMetadata[5]); + levelMetadata[4], levelMetadata[5])); // Construct the DataTime GregorianCalendar refTime = new GregorianCalendar(); @@ -344,7 +341,7 @@ public class Grib1Decoder extends AbstractDecoder { refTime, forecastTime, getTimeInformation(refTime, pdsVars.getTimeRangeIndicator(), - p1, p2), model); + p1, p2)); /* * Extract the data values from the file. The AVG_ACCUM_LIST is checked @@ -446,13 +443,13 @@ public class Grib1Decoder extends AbstractDecoder { } // Check for subgridding - String modelName = model.getModelName(); + String modelName = retVal.getDatasetId(); GridCoverage subCoverage = GribSpatialCache.getInstance() - .getSubGridCoverage(modelName); + .getSubGridCoverage(modelName, gridCoverage); if (subCoverage != null) { SubGrid subGrid = GribSpatialCache.getInstance().getSubGrid( - modelName); + modelName, gridCoverage); // resize the data array float[][] dataArray = this.resizeDataTo2D(data, gridCoverage.getNx(), gridCoverage.getNy()); @@ -461,46 +458,46 @@ public class Grib1Decoder extends AbstractDecoder { data = this.resizeDataTo1D(dataArray, subGrid.getNY(), subGrid.getNX()); retVal.setMessageData(data); - model.setLocation(subCoverage); + retVal.setLocation(subCoverage); } String newAbbr = GribParamTranslator.getInstance().translateParameter( - 1, model, dataTime); + 1, parameterAbbreviation, centerid, subcenterid, genProcess, + dataTime, gridCoverage); if (newAbbr == null) { - if (!model.getParameterName().equals(MISSING) + if (!parameterName.equals(MISSING) && dataTime.getValidPeriod().getDuration() > 0) { - model.setParameterAbbreviation(model.getParameterAbbreviation() + parameterAbbreviation = parameterAbbreviation + String.valueOf(dataTime.getValidPeriod() - .getDuration() / 3600000) + "hr"); + .getDuration() / 3600000) + "hr"; } } else { - model.setParameterAbbreviation(newAbbr); + parameterAbbreviation = newAbbr; } - model.setParameterAbbreviation(model.getParameterAbbreviation() - .replaceAll("_", "-")); - - model.setParameterName(GribParamTranslator.getInstance() - .getParameterNameAlias(model)); - - if (!model.getParameterName().equals(MISSING)) { - try { - model = GribModelCache.getInstance().getModel(model); - } catch (DataAccessLayerException e) { - throw new GribException( - "Unable to get model info from the cache!", e); - } + parameterAbbreviation = parameterAbbreviation.replaceAll("_", "-"); + try { + parameterAbbreviation = ParameterMapper.getInstance() + .lookupBaseName(parameterAbbreviation, "grib"); + } catch (MultipleMappingException e) { + statusHandler.handle(Priority.WARN, e.getLocalizedMessage(), e); + parameterAbbreviation = e.getArbitraryMapping(); } - retVal.setModelInfo(model); - retVal.setPluginName("grib"); + retVal.setPluginName("grid"); + Parameter param = new Parameter(parameterAbbreviation, parameterName, + parameterUnit); + GribParamTranslator.getInstance().getParameterNameAlias(modelName, + param); + retVal.setParameter(param); + retVal.setPersistenceTime(new Date()); retVal.setDataTime(dataTime); - if (gdsVars != null) { - retVal.setResCompFlags(gdsVars.getResolution()); - } else { - retVal.setResCompFlags(gridCoverage.getResolution()); - } + // if (gdsVars != null) { + // retVal.setResCompFlags(gdsVars.getResolution()); + // } else { + // retVal.setResCompFlags(gridCoverage.getResolution()); + // } try { retVal.constructDataURI(); @@ -509,7 +506,8 @@ public class Grib1Decoder extends AbstractDecoder { } // check if FLAG.FCST_USED needs to be removed - checkForecastFlag(model, retVal.getDataTime()); + checkForecastFlag(retVal.getDataTime(), centerid, subcenterid, + genProcess, gridCoverage); return retVal; } @@ -767,8 +765,8 @@ public class Grib1Decoder extends AbstractDecoder { if (latLonCoverage.getDy() == -9999) { latLonCoverage.setDy(latLonCoverage.getDx()); } - latLonCoverage.determineFirstGridPointCorner(gdsVars.getScanMode()); - latLonCoverage.setId(latLonCoverage.hashCode()); + latLonCoverage.setFirstGridPointCorner(GribSpatialCache + .determineFirstGridPointCorner(gdsVars.getScanMode())); coverage = getGridFromCache(latLonCoverage, gridNumber); break; } @@ -796,8 +794,8 @@ public class Grib1Decoder extends AbstractDecoder { mercator.setDx(gdsVars.getDx() / 1000); mercator.setDy(gdsVars.getDy() / 1000); } - mercator.determineFirstGridPointCorner(gdsVars.getScanMode()); - mercator.setId(mercator.hashCode()); + mercator.setFirstGridPointCorner(GribSpatialCache + .determineFirstGridPointCorner(gdsVars.getScanMode())); coverage = getGridFromCache(mercator, gridNumber); break; } @@ -824,8 +822,8 @@ public class Grib1Decoder extends AbstractDecoder { lambert.setDx(gdsVars.getDx() / 1000); lambert.setDy(gdsVars.getDy() / 1000); } - lambert.determineFirstGridPointCorner(gdsVars.getScanMode()); - lambert.setId(lambert.hashCode()); + lambert.setFirstGridPointCorner(GribSpatialCache + .determineFirstGridPointCorner(gdsVars.getScanMode())); coverage = getGridFromCache(lambert, gridNumber); break; @@ -857,8 +855,8 @@ public class Grib1Decoder extends AbstractDecoder { polar.setDx(gdsVars.getDx() / 1000); polar.setDy(gdsVars.getDy() / 1000); } - polar.determineFirstGridPointCorner(gdsVars.getScanMode()); - polar.setId(polar.hashCode()); + polar.setFirstGridPointCorner(GribSpatialCache + .determineFirstGridPointCorner(gdsVars.getScanMode())); coverage = getGridFromCache(polar, gridNumber); break; } @@ -896,64 +894,45 @@ public class Grib1Decoder extends AbstractDecoder { String.valueOf(gridNumber)); } if (grid == null) { - GribSpatialCache.getInstance().putGrid(coverage, true, true); - grid = GribSpatialCache.getInstance().getGrid(coverage.getId()); + grid = GridCoverageLookup.getInstance().getCoverage(coverage, true); } return grid; } /** - * Creates a model name from a GribModel object + * Look up a model name based off the grib numbers * - * @param model - * The GribModel object to determine the name for + * @param centerId + * @param subcenterId + * @param process + * @param gridId + * @return */ - private void createModelName(GribModel model) { - GridModel gridModel = getGridModel(model); - String name = null; - if (gridModel == null || gridModel.getName() == null) { - name = "UnknownModel:" + String.valueOf(model.getCenterid()) + ":" - + String.valueOf(model.getSubcenterid()) + ":" - + String.valueOf(model.getGenprocess()) + ":" - + model.getGridid(); - } else { - name = gridModel.getName(); - } - model.setModelName(name); + private String createModelName(int centerId, int subcenterId, int process, + GridCoverage grid) { + return GribModelLookup.getInstance().getModelName(centerId, + subcenterId, grid, process); } /** * Check if the forecast flag should be removed * - * @param model - * The GribModel object to check * @param time - * the datatime to remove forecast flag if needed + * he datatime to remove forecast flag if needed + * @param centerId + * @param subcenterId + * @param process + * @param gridId */ - private void checkForecastFlag(GribModel model, DataTime time) { - GridModel gridModel = getGridModel(model); + private void checkForecastFlag(DataTime time, int centerId, + int subcenterId, int process, GridCoverage grid) { + GridModel gridModel = GribModelLookup.getInstance().getModel(centerId, + subcenterId, grid, process); if (gridModel != null && gridModel.getAnalysisOnly()) { time.getUtilityFlags().remove(FLAG.FCST_USED); } } - /** - * Return the GridModel object - * - * @param model - * The GribModel object to find the GridModel - */ - private GridModel getGridModel(GribModel model) { - int center = model.getCenterid(); - int subcenter = model.getSubcenterid(); - - String gridid = model.getGridid(); - int process = model.getGenprocess(); - GridModel gridModel = GribModelLookup.getInstance().getModel(center, - subcenter, gridid, process); - return gridModel; - } - /** * Constructs a data time object from the time information extracted from * the grib record @@ -962,14 +941,12 @@ public class Grib1Decoder extends AbstractDecoder { * The reference time * @param forecastTime * The forecast time - * @param times - * The start and end time of the data if applicable * @param model * The GribModel object * @return The resulting DataTime object */ private DataTime constructDataTime(Calendar refTime, int forecastTime, - Calendar[] times, GribModel model) { + Calendar[] times) { DataTime dataTime = null; // Construct the DataTime object Calendar startTime = times[0]; @@ -1211,8 +1188,6 @@ public class Grib1Decoder extends AbstractDecoder { /** * Gets the level information * - * @param model - * The GribModel object * @param centerID * The center * @param subcenterID @@ -1231,7 +1206,7 @@ public class Grib1Decoder extends AbstractDecoder { * The level two value * @throws GribException */ - private void getLevelInfo(GribModel model, int centerID, int subcenterID, + private Level getLevelInfo(int centerID, int subcenterID, float levelOneNumber, float scaleFactor1, float value1, float levelTwoNumber, float scaleFactor2, float value2) throws GribException { @@ -1276,8 +1251,7 @@ public class Grib1Decoder extends AbstractDecoder { if (scaleFactor2 == 0 || value2 == 0) { levelTwoValue = value2; } else { - levelTwoValue = (double) (value2 * Math.pow(10, scaleFactor2 - * -1)); + levelTwoValue = (value2 * Math.pow(10, scaleFactor2 * -1)); } } if (levelName.equals("SFC") && levelOneValue != 0) { @@ -1288,11 +1262,13 @@ public class Grib1Decoder extends AbstractDecoder { levelTwoValue = Level.getInvalidLevelValue(); } try { - Level level = LevelFactory.getInstance().getLevel(levelName, + return LevelMapper.getInstance().lookupLevel(levelName, "grib", levelOneValue, levelTwoValue, levelUnit); - model.setLevel(level); } catch (CommunicationException e) { throw new GribException("Error requesting levels", e); + } catch (MultipleLevelMappingException e) { + statusHandler.handle(Priority.WARN, e.getLocalizedMessage(), e); + return e.getArbitraryLevelMapping(); } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribDecoder.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribDecoder.java index 1741cc7f11..76c46e1bd9 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribDecoder.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribDecoder.java @@ -20,24 +20,19 @@ package com.raytheon.edex.plugin.grib; import java.io.File; -import java.io.FileOutputStream; import java.io.IOException; -import java.util.ArrayList; -import java.util.List; import ucar.grib.GribChecker; -import ucar.grib.grib1.Grib1Input; -import ucar.grib.grib1.Grib1Record; -import ucar.grib.grib2.Grib2Input; -import ucar.grib.grib2.Grib2Record; import ucar.unidata.io.RandomAccessFile; +import com.raytheon.edex.esb.Headers; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.python.decoder.PythonDecoder; /** @@ -48,8 +43,6 @@ import com.raytheon.uf.edex.python.decoder.PythonDecoder; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 3/12/10 4758 bphillip Initial creation - * 8/15/12 1064 bphillip Added code to ensure the destination folders for large file splits are - * present * * * @author njensen @@ -60,88 +53,19 @@ public class GribDecoder { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(GribDecoder.class); - /** The size limit for grib files before an attempt is made to split them */ - private static final long TEN_MEGABYTES = 10485760; - - /** The directory which split grib 1 files are written to */ - private static final File LARGE_GRIB1_DIR = new File( - System.getProperty("edex.home") - + "/data/manual/grib/grib1LargeSplit/"); - - /** The directory which split grib2 files are written to */ - private static final File LARGE_GRIB2_DIR = new File( - System.getProperty("edex.home") - + "/data/manual/grib/grib2LargeSplit/"); - - static { - /* - * Ensure the grib1 split output directory exists - */ - if (!LARGE_GRIB1_DIR.exists()) { - LARGE_GRIB1_DIR.mkdirs(); - } - - /* - * Ensure the grib2 split output directory exists - */ - if (!LARGE_GRIB2_DIR.exists()) { - LARGE_GRIB2_DIR.mkdirs(); - } - } - public GribDecoder() { } - public GribRecord[] decode(File file) { - - GribRecord[] records = null; + public GridRecord[] decode(File file, Headers headers) { + GridRecord[] records = null; RandomAccessFile raf = null; int edition = 0; - List recordLengths = new ArrayList(); try { raf = new RandomAccessFile(file.getAbsolutePath(), "r"); raf.order(RandomAccessFile.BIG_ENDIAN); edition = GribChecker.getEdition(raf); - // If the file is greater than ten megs, split it - if (file.length() > TEN_MEGABYTES) { - raf.seek(0); - if (edition == 1) { - Grib1Input g1i = new Grib1Input(raf); - g1i.scan(false, false); - List gribRecords = g1i.getRecords(); - for (int i = 0; i < gribRecords.size(); i++) { - recordLengths.add(gribRecords.get(i).getIs() - .getGribLength()); - } - } else if (edition == 2) { - Grib2Input g2i = new Grib2Input(raf); - try { - g2i.scan(false, false); - } catch (Exception e) { - throw new Exception( - "Error determining grib record count.", e); - } - List gribRecords = g2i.getRecords(); - - for (int i = 0; i < gribRecords.size(); i++) { - recordLengths.add(gribRecords.get(i).getIs() - .getGribLength()); - } - } - - // If there was more than one grib record in this file, we split - // the - // file up into individual records and send them back through - // the - // manual ingest endpoint - if (recordLengths.size() > 1) { - raf.seek(0); - splitFile(file.getName(), raf, recordLengths, edition); - return new GribRecord[] {}; - } - } if (edition == 1) { records = new Grib1Decoder().decode(file.getAbsolutePath()); } else if (edition == 2) { @@ -149,13 +73,13 @@ public class GribDecoder { pythonDecoder.setPluginName("grib"); pythonDecoder.setPluginFQN("com.raytheon.edex.plugin.grib"); pythonDecoder.setModuleName("GribDecoder"); - pythonDecoder.setRecordClassname(GribRecord.class.toString()); + pythonDecoder.setRecordClassname(GridRecord.class.toString()); pythonDecoder.setCache(true); try { PluginDataObject[] pdos = pythonDecoder.decode(file); - records = new GribRecord[pdos.length]; + records = new GridRecord[pdos.length]; for (int i = 0; i < pdos.length; i++) { - records[i] = (GribRecord) pdos[i]; + records[i] = (GridRecord) pdos[i]; } } catch (Exception e) { throw new GribException("Error decoding grib file!", e); @@ -164,10 +88,28 @@ public class GribDecoder { throw new GribException("Unknown grib version detected [" + edition + "]"); } + String datasetId = (String) headers.get("datasetid"); + String secondaryId = (String) headers.get("secondaryid"); + String ensembleId = (String) headers.get("ensembleid"); + if (secondaryId != null || datasetId != null || ensembleId != null) { + for (GridRecord record : records) { + if (datasetId != null) { + record.setDatasetId(datasetId); + } + if (secondaryId != null) { + record.setSecondaryId(secondaryId); + } + if (ensembleId != null) { + record.setEnsembleId(ensembleId); + } + record.setDataURI(null); + record.constructDataURI(); + } + } } catch (Exception e) { statusHandler.handle(Priority.ERROR, "Failed to decode file: [" + file.getAbsolutePath() + "]", e); - records = new GribRecord[0]; + records = new GridRecord[0]; } finally { try { if (raf != null) { @@ -178,74 +120,6 @@ public class GribDecoder { "Unable to close RandomAccessFile!", e); } } - return records; } - - /** - * Splits a collective file into individual records. - * - * @param fileName - * The name of the file being split - * @param raf - * The Random Access File object - * @param sizes - * The sizes of the individual records inside the collection - * @throws IOException - */ - private void splitFile(String fileName, RandomAccessFile raf, - List sizes, int edition) throws IOException { - FileOutputStream out = null; - byte[] transfer = null; - for (int i = 0; i < sizes.size(); i++) { - transfer = new byte[(int) sizes.get(i).longValue()]; - raf.seek(seekRecordStart(raf, raf.length())); - raf.read(transfer); - - try { - out = new FileOutputStream(System.getProperty("edex.home") - + "/data/manual/grib/grib" + edition + "LargeSplit/" + fileName + "_record_" + (i + 1)); - out.write(transfer); - } finally { - if (out != null) { - out.close(); - } - } - } - } - - /** - * Moves the filepointer on the random access file to the beginning of the - * next grib record in the file - * - * @param raf - * The random access file - * @param fileLength - * The total length of the file - * @return The index to the next grib record in the collection. -1 is - * returned if there are no more records in the file - * @throws IOException - */ - private long seekRecordStart(RandomAccessFile raf, long fileLength) - throws IOException { - int matches = 0; - while (raf.getFilePointer() < fileLength) { - char c = (char) raf.readByte(); - if (c == 'G') { - matches = 1; - } else if ((c == 'R') && (matches == 1)) { - matches = 2; - } else if ((c == 'I') && (matches == 2)) { - matches = 3; - } else if ((c == 'B') && (matches == 3)) { - matches = 4; - // Subtract 4 because we want the absolute beginning of the grib - // file - return raf.getFilePointer() - 4; - } else { - matches = 0; - } - } - return -1; - } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribInitializer.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribInitializer.java deleted file mode 100644 index 1bb247a0bb..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribInitializer.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.edex.plugin.grib; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.raytheon.edex.plugin.DefaultPluginInitializer; -import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; - -/** - * Initializer implementation for the grib plugin - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class GribInitializer extends DefaultPluginInitializer { - - /** The logger */ - protected transient Log logger = LogFactory.getLog(getClass()); - - /** - * Creates a new GribInitializer instance - * - * @param pluginName - * "grib" - */ - public GribInitializer(String pluginName) { - super(pluginName); - } - - @Override - public void initializePlugin() throws Exception { - super.initializePlugin(); - logger.info("Initializing grib plugin"); - GribModelLookup.getInstance(); - GribSpatialCache.getInstance(); - logger.info("Grib plugin initialized"); - } - -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLargeFileChecker.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLargeFileChecker.java index b36236ea2a..fc7b8cd651 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLargeFileChecker.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLargeFileChecker.java @@ -27,7 +27,7 @@ import java.net.UnknownHostException; import org.apache.camel.Exchange; import org.apache.camel.Processor; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.PathManagerFactory; diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLockRelease.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLockRelease.java index 154cb627a4..f59e2c8d02 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLockRelease.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribLockRelease.java @@ -22,7 +22,6 @@ package com.raytheon.edex.plugin.grib; import org.apache.camel.Exchange; import org.apache.camel.Processor; -import com.raytheon.uf.common.dataplugin.grib.StatusConstants; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -47,7 +46,8 @@ import com.raytheon.uf.edex.database.cluster.ClusterLockUtils; * @see com.raytheon.edex.plugin.grib.GribLargeFileChecker */ public class GribLockRelease implements Processor { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(GribLockRelease.class); + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GribLockRelease.class); @Override public void process(Exchange exchange) throws Exception { diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribSplitter.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribSplitter.java new file mode 100644 index 0000000000..fde36580e2 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GribSplitter.java @@ -0,0 +1,223 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.edex.plugin.grib; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Pattern; + +import ucar.grib.GribChecker; +import ucar.grib.grib1.Grib1Input; +import ucar.grib.grib1.Grib1Record; +import ucar.grib.grib2.Grib2IndicatorSection; +import ucar.grib.grib2.Grib2Input; +import ucar.grib.grib2.Grib2Record; +import ucar.unidata.io.RandomAccessFile; + +import com.raytheon.edex.esb.Headers; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.edex.core.EdexException; + +/** + * TODO Add Description + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 7, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GribSplitter { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GribSplitter.class); + + private static final long TEN_MEGABYTES = 10485760; + + private static final String suffixFormat = "%s_record_%d"; + + private static final Pattern suffixPattern = Pattern + .compile(".*_record_\\d+$"); + + private final File tmpFileDirectory; + + public GribSplitter(String tmpFileLocation) { + this.tmpFileDirectory = new File(tmpFileLocation); + if (!tmpFileDirectory.exists()) { + tmpFileDirectory.mkdirs(); + } + } + + public void clean(Headers headers) { + String ingestFileName = (String) headers.get("ingestfilename"); + File file = new File(ingestFileName); + if (tmpFileDirectory.equals(file.getParentFile()) + && suffixPattern.matcher(file.getName()).find()) { + file.delete(); + } + } + + public List split(String fileName) { + File file = new File(fileName); + if (file.length() > TEN_MEGABYTES) { + RandomAccessFile raf = null; + try { + raf = new RandomAccessFile(file.getAbsolutePath(), "r"); + raf.order(RandomAccessFile.BIG_ENDIAN); + int edition = GribChecker.getEdition(raf); + raf.seek(0); + List recordLengths = new ArrayList(); + if (edition == 1) { + Grib1Input g1i = new Grib1Input(raf); + g1i.scan(false, false); + List gribRecords = g1i.getRecords(); + for (int i = 0; i < gribRecords.size(); i++) { + recordLengths.add(gribRecords.get(i).getIs() + .getGribLength()); + } + } else if (edition == 2) { + Grib2Input g2i = new Grib2Input(raf); + + g2i.scan(false, false); + List gribRecords = g2i.getRecords(); + + Grib2IndicatorSection lastIs = null; + for (int i = 0; i < gribRecords.size(); i++) { + // 2 records with the same indicator section cannot be + // split, this occurs with uW and vW that are encoded + // together. + Grib2IndicatorSection is = gribRecords.get(i).getIs(); + if (lastIs != is) { + lastIs = is; + recordLengths.add(is.getGribLength()); + } + } + // If there was more than one grib record in this file, we + // split the file up into individual records and send them + // back through the manual ingest endpoint + if (recordLengths.size() > 1) { + raf.seek(0); + return splitFile(file.getName(), raf, recordLengths); + } + } + } catch (Exception e) { + statusHandler.handle(Priority.ERROR, + "Error splitting grib file", e); + } finally { + try { + if (raf != null) { + raf.close(); + } + } catch (IOException e) { + statusHandler.handle(Priority.ERROR, + "Unable to close RandomAccessFile!", e); + } + } + } + return Arrays.asList(file.getAbsolutePath()); + } + + /** + * Splits a collective file into individual records. + * + * @param fileName + * The name of the file being split + * @param raf + * The Random Access File object + * @param sizes + * The sizes of the individual records inside the collection + * @throws IOException + * @throws EdexException + */ + private List splitFile(String fileName, RandomAccessFile raf, + List sizes) throws IOException, EdexException { + FileOutputStream out = null; + byte[] transfer = null; + List result = new ArrayList(sizes.size()); + for (int i = 0; i < sizes.size(); i++) { + transfer = new byte[(int) sizes.get(i).longValue()]; + raf.seek(seekRecordStart(raf, raf.length())); + raf.read(transfer); + + try { + + File tmpFile = new File(tmpFileDirectory, String.format( + suffixFormat, fileName, i)); + out = new FileOutputStream(tmpFile); + out.write(transfer); + out.close(); + result.add(tmpFile.getPath()); + } finally { + if (out != null) { + out.close(); + } + } + } + return result; + } + + /** + * Moves the filepointer on the random access file to the beginning of the + * next grib record in the file + * + * @param raf + * The random access file + * @param fileLength + * The total length of the file + * @return The index to the next grib record in the collection. -1 is + * returned if there are no more records in the file + * @throws IOException + */ + private long seekRecordStart(RandomAccessFile raf, long fileLength) + throws IOException { + int matches = 0; + while (raf.getFilePointer() < fileLength) { + char c = (char) raf.readByte(); + if (c == 'G') { + matches = 1; + } else if ((c == 'R') && (matches == 1)) { + matches = 2; + } else if ((c == 'I') && (matches == 2)) { + matches = 3; + } else if ((c == 'B') && (matches == 3)) { + matches = 4; + // Subtract 4 because we want the absolute beginning of the grib + // file + return raf.getFilePointer() - 4; + } else { + matches = 0; + } + } + return -1; + } +} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GridToGribConverter.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GridToGribConverter.java new file mode 100644 index 0000000000..f5a6dcad2e --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/GridToGribConverter.java @@ -0,0 +1,151 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.edex.plugin.grib; + +import com.raytheon.edex.plugin.grib.util.GribModelCache; +import com.raytheon.uf.common.dataplugin.PluginException; +import com.raytheon.uf.common.dataplugin.grib.GribModel; +import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.edex.database.DataAccessLayerException; + +/** + * TODO Add Description + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 4, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridToGribConverter { + + private static GridToGribConverter instance = new GridToGribConverter(); + + public static GridToGribConverter getInstance() { + return instance; + } + + private GridToGribConverter() { + + } + + public GribRecord[] convert(GridRecord[] records) throws PluginException, + DataAccessLayerException { + GribRecord[] result = new GribRecord[records.length]; + for (int i = 0; i < records.length; i += 1) { + GridRecord grid = records[i]; + GribRecord grib = new GribRecord(); + GribModel model = new GribModel(); + grib.setPluginName("grib"); + grib.setDataTime(grid.getDataTime()); + model.setModelName(grid.getDatasetId()); + if (grid.getSecondaryId() != null + && grid.getSecondaryId().startsWith("Version")) { + grib.setGridVersion(Integer.parseInt(grid.getSecondaryId() + .replace("Version", ""))); + } + if ("ctl1".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(1); + model.setTypeEnsemble(1); + } else if ("ctl2".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(2); + model.setTypeEnsemble(1); + } else if ("n1".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(3); + model.setTypeEnsemble(2); + } else if ("p1".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(4); + model.setTypeEnsemble(3); + } else if ("n2".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(5); + model.setTypeEnsemble(2); + } else if ("p2".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(6); + model.setTypeEnsemble(3); + } else if ("n3".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(7); + model.setTypeEnsemble(2); + } else if ("p3".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(8); + model.setTypeEnsemble(3); + } else if ("n4".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(9); + model.setTypeEnsemble(2); + } else if ("p4".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(10); + model.setTypeEnsemble(3); + } else if ("n5".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(11); + model.setTypeEnsemble(2); + } else if ("p5".equals(grid.getEnsembleId())) { + model.setPerturbationNumber(12); + model.setTypeEnsemble(3); + } + Object centerid = grid.getExtraAttribute("centerid"); + if (centerid != null && centerid instanceof Integer) { + model.setCenterid((Integer) centerid); + } + Object subcenterid = grid.getExtraAttribute("subcenterid"); + if (subcenterid != null && subcenterid instanceof Integer) { + model.setSubcenterid((Integer) subcenterid); + } + Object genprocess = grid.getExtraAttribute("genprocess"); + if (genprocess != null && genprocess instanceof Integer) { + model.setGenprocess((Integer) genprocess); + } + Object backGenprocess = grid.getExtraAttribute("backGenprocess"); + if (backGenprocess != null && backGenprocess instanceof Integer) { + model.setBackGenprocess((Integer) backGenprocess); + } + Object pdsTemplate = grid.getExtraAttribute("pdsTemplate"); + if (pdsTemplate != null && pdsTemplate instanceof Integer) { + model.setPdsTemplate((Integer) pdsTemplate); + } + Object gridid = grid.getExtraAttribute("gridid"); + if (gridid != null && gridid instanceof String) { + model.setGridid((String) gridid); + } + Object numForecasts = grid.getExtraAttribute("numForecasts"); + if (numForecasts != null && numForecasts instanceof Integer) { + model.setNumForecasts((Integer) numForecasts); + } + model.setLevel(grid.getLevel()); + model.setLocation(grid.getLocation()); + model.setParameterAbbreviation(grid.getParameter() + .getAbbreviation()); + model.setParameterName(grid.getParameter().getName()); + model.setParameterUnit(grid.getParameter().getUnitString()); + model = GribModelCache.getInstance().getModel(model); + grib.setModelInfo(model); + grib.constructDataURI(); + result[i] = grib; + } + return result; + } +} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribDao.java index a828854996..ca47b43192 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribDao.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribDao.java @@ -68,7 +68,7 @@ import com.raytheon.uf.edex.database.plugin.PluginDao; import com.raytheon.uf.edex.database.query.DatabaseQuery; /** - * Data access object for accessing Grib records from the database + * Deprecated, use grid * *
  * 
@@ -79,12 +79,15 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery;
  * 4/7/09       1994        bphillip    Initial Creation
  * 5/31/12      #674        dgilling    Re-factor so all purge methods
  *                                      call updateCaches().
+ * 11/05/12     #1310       dgilling    Remove code from updateCatches()
+ *                                      that sent notification to D2DParmIdCache.
  * 
  * 
* * @author bphillip * @version 1 */ +@Deprecated public class GribDao extends PluginDao { private static final transient IUFStatusHandler statusHandler = UFStatus @@ -96,8 +99,6 @@ public class GribDao extends PluginDao { private static final String THINNED_PTS = "thinnedPts"; - private static final String REBUILD_CACHE_TOPIC = "jms-generic:topic:rebuildD2DCache"; - private static final String PURGE_MODEL_CACHE_TOPIC = "jms-generic:topic:purgeGribModelCache"; /** @@ -148,7 +149,6 @@ public class GribDao extends PluginDao { * @throws PluginException */ private void updateCaches() throws PluginException { - Exception rethrow = null; try { List orphanedIds = purgeGribModelOrphans(); @@ -156,24 +156,11 @@ public class GribDao extends PluginDao { orphanedIds); } catch (DataAccessLayerException e) { statusHandler.error("Error purging orphaned grib model entries", e); - rethrow = e; + throw new PluginException("Error updating GribModelCache", e); } catch (EdexException e1) { statusHandler.error( "Error sending message to purge grib model topic", e1); - rethrow = e1; - } - try { - EDEXUtil.getMessageProducer().sendAsyncUri(REBUILD_CACHE_TOPIC, - null); - } catch (EdexException e) { - statusHandler.error( - "Error sending message to rebuild D2D Cache topic", e); - rethrow = e; - } - - if (rethrow != null) { - throw new PluginException( - "Error updating GribModelCache or D2DParmIDCache", rethrow); + throw new PluginException("Error updating GribModelCache", e1); } } @@ -260,6 +247,23 @@ public class GribDao extends PluginDao { return dataStore; } + @Override + public IDataStore getDataStore(IPersistable obj) { + String persistDir = PLUGIN_HDF5_DIR.replace("grib", "grid") + + pathProvider.getHDFPath(this.pluginName, obj) + + File.separator; + String archive = pathProvider.getHDFFileName(this.pluginName, obj); + + File persistFile = new File(persistDir, archive); + /* connect to the data store and retrieve the data */ + return DataStoreFactory.getDataStore(persistFile); + } + + @Override + protected String getHDF5Path(String productKey) { + return super.getHDF5Path(productKey).replace("grib", "grid"); + } + @Override public List getHDF5Data(List objects, int tileSet) throws PluginException { @@ -284,23 +288,11 @@ public class GribDao extends PluginDao { } else { /* connect to the data store and retrieve the data */ - record = new IDataRecord[4]; + record = new IDataRecord[1]; - record[0] = dataStore.retrieve(obj.getDataURI(), - "Data", Request.ALL); - - if (obj.isLocalSectionUsed()) { - record[1] = dataStore.retrieve(obj.getDataURI(), - LOCAL_SECTION, Request.ALL); - } - if (obj.isHybridGrid()) { - record[2] = dataStore.retrieve(obj.getDataURI(), - HYBRID_LEVELS, Request.ALL); - } - if (obj.isThinnedGrid()) { - record[3] = dataStore.retrieve(obj.getDataURI(), - THINNED_PTS, Request.ALL); - } + record[0] = dataStore.retrieve(GribPathProvider + .getInstance().getGroup(obj), "Data", + Request.ALL); retVal.add(record); } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribModelDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribModelDao.java index ad04e1b7c3..321f291c15 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribModelDao.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GribModelDao.java @@ -42,7 +42,7 @@ import com.raytheon.uf.edex.database.dao.CoreDao; import com.raytheon.uf.edex.database.dao.DaoConfig; /** - * Data access object for retrieving GribModel objects from the database + * Deprecated, use grid * *
  * 
@@ -57,10 +57,11 @@ import com.raytheon.uf.edex.database.dao.DaoConfig;
  * @author bphillip
  * @version 1
  */
+@Deprecated
 public class GribModelDao extends CoreDao {
 
     private static final IUFStatusHandler handler = UFStatus
-            .getHandler(GridCoverageDao.class);
+            .getHandler(GribModelDao.class);
 
     /**
      * Creates a new GribModelDao
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GridCoverageDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GridCoverageDao.java
deleted file mode 100644
index fce8a813e9..0000000000
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/GridCoverageDao.java
+++ /dev/null
@@ -1,197 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-
-package com.raytheon.edex.plugin.grib.dao;
-
-import java.util.List;
-
-import org.hibernate.Criteria;
-import org.hibernate.Session;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Restrictions;
-import org.springframework.orm.hibernate3.HibernateTemplate;
-import org.springframework.transaction.TransactionStatus;
-import org.springframework.transaction.support.TransactionCallback;
-
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-import com.raytheon.uf.common.dataquery.db.QueryParam;
-import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand;
-import com.raytheon.uf.common.status.IUFStatusHandler;
-import com.raytheon.uf.common.status.UFStatus;
-import com.raytheon.uf.edex.database.DataAccessLayerException;
-import com.raytheon.uf.edex.database.dao.CoreDao;
-import com.raytheon.uf.edex.database.dao.DaoConfig;
-
-/**
- * Data access object for retrieving GridCoverage objects
- * 
- * 
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class GridCoverageDao extends CoreDao { - - protected static final float QUERY_TOLERANCE = 0.1f; - - private static final IUFStatusHandler handler = UFStatus - .getHandler(GridCoverageDao.class); - - public GridCoverageDao() { - super(DaoConfig.forClass(GridCoverage.class)); - } - - public GridCoverageDao(DaoConfig config) { - super(config); - } - - protected QueryParam addQueryTolerance(String field, double value) { - String between = String.valueOf(value - QUERY_TOLERANCE) + "--" - + String.valueOf(value + QUERY_TOLERANCE); - return new QueryParam(field, between, QueryOperand.BETWEEN); - } - - @SuppressWarnings("unchecked") - public GridCoverage queryByGridNumber(Integer number) - throws DataAccessLayerException { - List coverages = (List) this - .queryBySingleCriteria("name", String.valueOf(number)); - if (coverages.isEmpty()) { - return null; - } else { - return coverages.get(0); - } - } - - /** - * Method used by subclasses to pick the known grid if multiple results from - * the query are returned and the results include generated unknown grib - * coverage objects - * - * @param coverages - * The grib coverages to examine - * @return The 'known' coverage object if one is contained in the list - */ - protected GridCoverage selectKnownGrid( - List coverages) { - if (coverages.isEmpty()) { - return null; - } else if (coverages.size() == 1) { - return coverages.get(0); - } else { - for (GridCoverage coverage : coverages) { - if (!coverage.getDescription().startsWith("Unknown")) { - return coverage; - } - } - return coverages.get(0); - } - } - - @SuppressWarnings("unchecked") - public List loadBaseGrids() { - return (List) txTemplate - .execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - HibernateTemplate ht = getHibernateTemplate(); - Session sess = ht.getSessionFactory() - .getCurrentSession(); - Criteria crit = sess.createCriteria(GridCoverage.class); - Criterion where = Restrictions.not(Restrictions.like( - "name", "Unknown%")); - where = Restrictions.and(where, Restrictions - .not(Restrictions.like("name", "%SubGrid%"))); - crit.add(where); - return crit.list(); - } - }); - } - - @SuppressWarnings("unchecked") - public List loadSubGrids() { - return (List) txTemplate - .execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - HibernateTemplate ht = getHibernateTemplate(); - Session sess = ht.getSessionFactory() - .getCurrentSession(); - Criteria crit = sess.createCriteria(GridCoverage.class); - Criterion where = Restrictions - .like("name", "%SubGrid%"); - crit.add(where); - return crit.list(); - } - }); - } - - @SuppressWarnings("unchecked") - public List loadUnknownGrids() { - return (List) txTemplate - .execute(new TransactionCallback() { - @Override - public Object doInTransaction(TransactionStatus status) { - HibernateTemplate ht = getHibernateTemplate(); - Session sess = ht.getSessionFactory() - .getCurrentSession(); - Criteria crit = sess.createCriteria(GridCoverage.class); - Criterion where = Restrictions.like("name", "Unknown%"); - crit.add(where); - return crit.list(); - } - }); - } - - public boolean deleteCoverageAssociatedData(GridCoverage cov, - boolean deleteCoverage) { - boolean rval = false; - try { - GribModelDao modelDao = new GribModelDao(); - // query for models to delete - List modelNames = modelDao.getModelNamesForCoverage(cov - .getId()); - for (String modelName : modelNames) { - handler.info("Coverage for model " + modelName - + " has changed. Deleting prior records"); - - modelDao.deleteModelAndAssociatedData(modelName); - } - - // delete coverage - if (deleteCoverage) { - this.delete(cov); - } - - rval = true; - } catch (Exception e) { - handler.error("Error occurred deleting coverage associated data", e); - } - return rval; - } -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/IGridCoverageDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/IGridCoverageDao.java deleted file mode 100644 index cc1710b0a1..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/IGridCoverageDao.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.edex.plugin.grib.dao; - -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.edex.database.DataAccessLayerException; - -/** - * Interface implemented by grid coverage data access objects - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public interface IGridCoverageDao { - - public GridCoverage checkGrid(GridCoverage grid) - throws DataAccessLayerException; -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/LambertConformalDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/LambertConformalDao.java deleted file mode 100644 index f1fb2d94cf..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/LambertConformalDao.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.edex.plugin.grib.dao; - -import java.util.List; - -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LambertConformalGridCoverage; -import com.raytheon.uf.edex.database.DataAccessLayerException; -import com.raytheon.uf.edex.database.dao.DaoConfig; -import com.raytheon.uf.edex.database.query.DatabaseQuery; - -/** - * Data Access Object for retrieving LambertConforamlGridCoverage objects - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class LambertConformalDao extends GridCoverageDao implements - IGridCoverageDao { - - /** - * Creates new MercatorDao - */ - public LambertConformalDao() { - super(DaoConfig.forClass(LambertConformalGridCoverage.class)); - } - - /** - * Checks that database to see if a grid exists in the database which very - * closely resembles the provided coverage - * - * @param coverage - * The PolarStereoGridCoverage to check against - * @return The Grid from the database or null if not found - * @throws DataAccessLayerException - * If problems during query - */ - @SuppressWarnings("unchecked") - public GridCoverage checkGrid(GridCoverage grid) - throws DataAccessLayerException { - - LambertConformalGridCoverage coverage = (LambertConformalGridCoverage) grid; - DatabaseQuery query = new DatabaseQuery(this.daoClass); - query.addQueryParam(addQueryTolerance("dx", coverage.getDx())); - query.addQueryParam(addQueryTolerance("dy", coverage.getDy())); - query.addQueryParam(addQueryTolerance("la1", coverage.getLa1())); - query.addQueryParam(addQueryTolerance("lo1", coverage.getLo1())); - query.addQueryParam(addQueryTolerance("latin1", coverage.getLatin1())); - query.addQueryParam(addQueryTolerance("latin2", coverage.getLatin2())); - query.addQueryParam(addQueryTolerance("lov", coverage.getLov())); - query.addQueryParam("nx", coverage.getNx()); - query.addQueryParam("ny", coverage.getNy()); - List result = (List) queryByCriteria(query); - return selectKnownGrid(result); - } -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/LatLonDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/LatLonDao.java deleted file mode 100644 index 7d070a1707..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/LatLonDao.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.edex.plugin.grib.dao; - -import java.util.ArrayList; -import java.util.List; - -import com.raytheon.edex.plugin.grib.Grib1Decoder; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage; -import com.raytheon.uf.edex.database.DataAccessLayerException; -import com.raytheon.uf.edex.database.dao.DaoConfig; -import com.raytheon.uf.edex.database.query.DatabaseQuery; - -/** - * Data Access Object for retrieving LatLonGridCoverage objects - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class LatLonDao extends GridCoverageDao implements IGridCoverageDao { - - /** - * Creates a new LatLonDao - */ - public LatLonDao() { - super(DaoConfig.forClass(LatLonGridCoverage.class)); - } - - /** - * Checks that database to see if a grid exists in the database which very - * closely resembles the provided coverage - * - * @param coverage - * The LatLonGridCoverage to check against - * @return The Grid from the database or null if not found - * @throws DataAccessLayerException - * If problems during query - */ - @SuppressWarnings("unchecked") - public GridCoverage checkGrid(GridCoverage grid) - throws DataAccessLayerException { - - LatLonGridCoverage coverage = (LatLonGridCoverage) grid; - DatabaseQuery query = new DatabaseQuery(this.daoClass); - - // If dx and dy are present, use them - if (coverage.getDx() != 65.535) { - query.addQueryParam(addQueryTolerance("dx", coverage.getDx())); - } - if (coverage.getDy() != 65.535) { - query.addQueryParam(addQueryTolerance("dy", coverage.getDy())); - } - query.addQueryParam(addQueryTolerance("la1", coverage.getLa1())); - query.addQueryParam(addQueryTolerance("lo1", coverage.getLo1())); - query.addQueryParam("nx", coverage.getNx()); - query.addQueryParam("ny", coverage.getNy()); - query.addQueryParam("firstGridPointCorner",coverage.getFirstGridPointCorner()); - List result = (List) queryByCriteria(query); - - if (result.isEmpty()) { - return manualCheck(coverage); - } else { - return selectKnownGrid(result); - } - } - - @SuppressWarnings("unchecked") - private GridCoverage manualCheck(LatLonGridCoverage coverage) - throws DataAccessLayerException { - - DatabaseQuery query = new DatabaseQuery(this.daoClass); - query.addQueryParam("nx", coverage.getNx()); - query.addQueryParam("ny", coverage.getNy()); - query.addQueryParam(addQueryTolerance("dx", coverage.getDx())); - query.addQueryParam(addQueryTolerance("dy", coverage.getDy())); - List result = (List) queryByCriteria(query); - - List matchingCoverages = new ArrayList(); - for (LatLonGridCoverage gridToCheck : result) { - if (checkLat(coverage.getLa1(), gridToCheck.getLa1()) - && checkLon(coverage.getLo1(), gridToCheck.getLo1())) { - matchingCoverages.add(gridToCheck); - } - - } - - return selectKnownGrid(matchingCoverages); - } - - private boolean checkLat(double reference, double latToCheck) { - double correctedRef = Grib1Decoder.correctLat((float) reference); - double correctedLat = Grib1Decoder.correctLat((float) latToCheck); - - if (Math.abs(correctedRef - correctedLat) < QUERY_TOLERANCE - || Math.abs(correctedLat - correctedRef) < QUERY_TOLERANCE) { - return true; - } - return false; - } - - private boolean checkLon(double reference, double lonToCheck) { - double correctedRef = Grib1Decoder.correctLon((float) reference); - double correctedLon = Grib1Decoder.correctLon((float) lonToCheck); - - if (Math.abs(correctedRef - correctedLon) < QUERY_TOLERANCE - || Math.abs(correctedLon - correctedRef) < QUERY_TOLERANCE) { - return true; - } - return false; - } -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/MercatorDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/MercatorDao.java deleted file mode 100644 index 7bc9728bdf..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/MercatorDao.java +++ /dev/null @@ -1,83 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.edex.plugin.grib.dao; - -import java.util.List; - -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.MercatorGridCoverage; -import com.raytheon.uf.edex.database.DataAccessLayerException; -import com.raytheon.uf.edex.database.dao.DaoConfig; -import com.raytheon.uf.edex.database.query.DatabaseQuery; - -/** - * Data Access Object for retrieving MercatorCoverage objects - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class MercatorDao extends GridCoverageDao implements IGridCoverageDao { - - /** - * Creates new MercatorDao - */ - public MercatorDao() { - super(DaoConfig.forClass(MercatorGridCoverage.class)); - } - - /** - * Checks that database to see if a grid exists in the database which very - * closely resembles the provided coverage - * - * @param coverage - * The MercatorCoverage to check against - * @return The Grid from the database or null if not found - * @throws DataAccessLayerException - * If problems during query - */ - @SuppressWarnings("unchecked") - public GridCoverage checkGrid(GridCoverage grid) - throws DataAccessLayerException { - - MercatorGridCoverage coverage = (MercatorGridCoverage) grid; - - DatabaseQuery query = new DatabaseQuery(this.daoClass); - query.addQueryParam(addQueryTolerance("dx", coverage.getDx())); - query.addQueryParam(addQueryTolerance("dy", coverage.getDy())); - query.addQueryParam(addQueryTolerance("la1", coverage.getLa1())); - query.addQueryParam(addQueryTolerance("lo1", coverage.getLo1())); - query.addQueryParam(addQueryTolerance("latin", coverage.getLatin())); - query.addQueryParam("nx", coverage.getNx()); - query.addQueryParam("ny", coverage.getNy()); - List result = (List) queryByCriteria(query); - return selectKnownGrid(result); - } -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/PolarStereoDao.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/PolarStereoDao.java deleted file mode 100644 index 51e8e870f3..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/dao/PolarStereoDao.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ - -package com.raytheon.edex.plugin.grib.dao; - -import java.util.List; - -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.PolarStereoGridCoverage; -import com.raytheon.uf.edex.database.DataAccessLayerException; -import com.raytheon.uf.edex.database.dao.DaoConfig; -import com.raytheon.uf.edex.database.query.DatabaseQuery; - -/** - * Data Access Object for retrieving PolarStereoGridCoverage objects - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#     Engineer    Description
- * ------------ ----------  ----------- --------------------------
- * 4/7/09       1994        bphillip    Initial Creation
- * 
- * 
- * - * @author bphillip - * @version 1 - */ -public class PolarStereoDao extends GridCoverageDao implements IGridCoverageDao { - - /** - * Creates new MercatorDao - */ - public PolarStereoDao() { - super(DaoConfig.forClass(PolarStereoGridCoverage.class)); - } - - /** - * Checks that database to see if a grid exists in the database which very - * closely resembles the provided coverage - * - * @param coverage - * The PolarStereoGridCoverage to check against - * @return The Grid from the database or null if not found - * @throws DataAccessLayerException - * If problems during query - */ - @SuppressWarnings("unchecked") - public GridCoverage checkGrid(GridCoverage grid) - throws DataAccessLayerException { - - PolarStereoGridCoverage coverage = (PolarStereoGridCoverage) grid; - - DatabaseQuery query = new DatabaseQuery(this.daoClass); - query.addQueryParam(addQueryTolerance("dx", coverage.getDx())); - query.addQueryParam(addQueryTolerance("dy", coverage.getDy())); - query.addQueryParam(addQueryTolerance("la1", coverage.getLa1())); - query.addQueryParam(addQueryTolerance("lo1", coverage.getLo1())); - query.addQueryParam(addQueryTolerance("lov", coverage.getLov())); - query.addQueryParam(addQueryTolerance("lad", coverage.getLad())); - query.addQueryParam("nx", coverage.getNx()); - query.addQueryParam("ny", coverage.getNy()); - List result = (List) queryByCriteria(query); - return selectKnownGrid(result); - } -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CPCoutlookGribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CPCoutlookGribPostProcessor.java index b0e3a07991..68b69a2195 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CPCoutlookGribPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CPCoutlookGribPostProcessor.java @@ -21,10 +21,11 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors; import java.util.Calendar; + +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.StatusConstants; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -33,19 +34,16 @@ import com.raytheon.uf.common.time.DataTime; /** * Grib post processor implementation to decode monthly CPC outlook grids * - * CPC long-range outlook grids (forecast projections of 30 days, 90-450 - * days at 30-day intervals) do not contain the forecast periods within - * the data in the usual way, and this must be calculated from the time - * information. - * The reftime of each grid in the same run/delivery (which occurs - * monthly) contains a subsequent hour (00:00:00 through 13:00:00). - * These hours are used to determine the forecast period. - * E.g. for a reftime of 2008-10-15 01:00:00 the '01' tells us that this - * grid is for the second forecast increment. - * Since there is no 60-day forecast, an hour of '00' represents the - * 30-day outlook and then there is a shift so that an hour of '01' - * represents the 90-day outlook, hence the two calculations below, - * taken from the AWIPS I code. + * CPC long-range outlook grids (forecast projections of 30 days, 90-450 days at + * 30-day intervals) do not contain the forecast periods within the data in the + * usual way, and this must be calculated from the time information. The reftime + * of each grid in the same run/delivery (which occurs monthly) contains a + * subsequent hour (00:00:00 through 13:00:00). These hours are used to + * determine the forecast period. E.g. for a reftime of 2008-10-15 01:00:00 the + * '01' tells us that this grid is for the second forecast increment. Since + * there is no 60-day forecast, an hour of '00' represents the 30-day outlook + * and then there is a shift so that an hour of '01' represents the 90-day + * outlook, hence the two calculations below, taken from the AWIPS I code. * *
  * 
@@ -57,40 +55,41 @@ import com.raytheon.uf.common.time.DataTime;
  * 
  * 
* - * @author + * @author * @version */ public class CPCoutlookGribPostProcessor implements IDecoderPostProcessor { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(CPCoutlookGribPostProcessor.class); + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(CPCoutlookGribPostProcessor.class); @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { + + Calendar refTime = record.getDataTime().getRefTimeAsCalendar(); + + int hour = refTime.get(Calendar.HOUR_OF_DAY); + int time1, time2; + if (hour == 0) { + time1 = 0; + time2 = (hour + 1) * 30 * 86400; + } else { + time1 = 0; + time2 = (hour + 2) * 30 * 86400; + } + int fcstTime = time2 - time1; + refTime.set(Calendar.HOUR_OF_DAY, 0); - Calendar refTime = record.getDataTime().getRefTimeAsCalendar(); - - int hour = refTime.get(Calendar.HOUR_OF_DAY); - int time1,time2; - if (hour == 0) { - time1 = 0; - time2 = (hour + 1) * 30 * 86400; - } else { - time1 = 0; - time2 = (hour + 2) * 30 * 86400; - } - int fcstTime = time2 - time1; - refTime.set(Calendar.HOUR_OF_DAY, 0); - DataTime newDataTime = new DataTime(refTime, fcstTime); record.setDataTime(newDataTime); record.setDataURI(null); - - try { - record.setPluginName("grib"); - record.constructDataURI(); - } catch (PluginException e) { - statusHandler.handle(Priority.PROBLEM, - "Error constructing dataURI!", e); - } - return new GribRecord[] { record }; + + try { + record.setPluginName(GridConstants.GRID); + record.constructDataURI(); + } catch (PluginException e) { + statusHandler.handle(Priority.PROBLEM, + "Error constructing dataURI!", e); + } + return new GridRecord[] { record }; } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianNHPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianNHPostProcessor.java index 4a7a50b210..054102dc29 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianNHPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianNHPostProcessor.java @@ -24,12 +24,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import com.raytheon.edex.plugin.grib.dao.GribDao; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * Grib post processor implementation to generate 6-hr precipitation grids from @@ -51,33 +52,33 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; public class CanadianNHPostProcessor extends SixHrPrecipGridProcessor { @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { // Post process the data if this is a Total Precipitation grid - if (record.getModelInfo().getParameterAbbreviation().equals("TPrun")) { + if (record.getParameter().getAbbreviation().equals("TPrun")) { return super.process(record); } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") - protected List getPrecipInventory(Date refTime) + protected List getPrecipInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TPrun"); - query.addQueryParam("modelInfo.modelName", "Canadian-NH"); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TPrun"); + query.addQueryParam(GridConstants.DATASET_ID, "Canadian-NH"); query.addQueryParam("dataTime.refTime", refTime); query.addOrder("dataTime.fcstTime", true); try { - return (List) dao.queryByCriteria(query); + return (List) dao.queryByCriteria(query); } catch (DataAccessLayerException e) { throw new GribException( "Error getting Precip inventory for Canadian-NH!", e); @@ -90,15 +91,15 @@ public class CanadianNHPostProcessor extends SixHrPrecipGridProcessor { @SuppressWarnings("unchecked") protected List getPrecip6hrInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TP6hr"); - query.addQueryParam("modelInfo.modelName", "Canadian-NH"); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TP6hr"); + query.addQueryParam(GridConstants.DATASET_ID, "Canadian-NH"); query.addQueryParam("dataTime.refTime", refTime); query.addReturnedField("dataTime.fcstTime"); try { @@ -120,12 +121,12 @@ public class CanadianNHPostProcessor extends SixHrPrecipGridProcessor { * @return The generated 6-hr precipitation grids * @throws GribException */ - protected synchronized GribRecord[] generate6hrPrecipGrids(GribRecord record) + protected synchronized GridRecord[] generate6hrPrecipGrids(GridRecord record) throws GribException { // The current run accumulated precipitation grid inventory in the // database - List precipInventory = getPrecipInventory(record + List precipInventory = getPrecipInventory(record .getDataTime().getRefTime()); // The current 6-hr precipitation grid inventory in the database @@ -139,16 +140,16 @@ public class CanadianNHPostProcessor extends SixHrPrecipGridProcessor { // Examine each grid in the inventory and generate the 6hr precipitation // grid if possible - List generatedRecords = new ArrayList(); + List generatedRecords = new ArrayList(); for (int i = 0; i < precipInventory.size(); i++) { // Check if the 6hr precipitation grid has already been produced if (!precip6hrInventory.contains(precipInventory.get(i) .getDataTime().getFcstTime())) { // If the precipitation grid has not been produced, generate it - List generated6hrPrecips = generate6hrPrecip( + List generated6hrPrecips = generate6hrPrecip( precipInventory.get(i), precipInventory, precip6hrInventory); - for (GribRecord newRecord : generated6hrPrecips) { + for (GridRecord newRecord : generated6hrPrecips) { // Add the generated grid to the current inventory if (newRecord != null) { precip6hrInventory.add(newRecord.getDataTime() @@ -159,7 +160,7 @@ public class CanadianNHPostProcessor extends SixHrPrecipGridProcessor { } } - return generatedRecords.toArray(new GribRecord[] {}); + return generatedRecords.toArray(new GridRecord[] {}); } /** diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianRegPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianRegPostProcessor.java index 7d1db0db4e..75766b3422 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianRegPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/CanadianRegPostProcessor.java @@ -24,12 +24,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import com.raytheon.edex.plugin.grib.dao.GribDao; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * Grib post processor implementation to generate 3-hr precipitation grids from @@ -51,33 +52,33 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; public class CanadianRegPostProcessor extends ThreeHrPrecipGridProcessor { @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { // Post process the data if this is a Total Precipitation grid - if (record.getModelInfo().getParameterAbbreviation().equals("TPrun")) { + if (record.getParameter().getAbbreviation().equals("TPrun")) { return super.process(record); } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") - protected List getPrecipInventory(Date refTime) + protected List getPrecipInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TPrun"); - query.addQueryParam("modelInfo.modelName", "Canadian-Reg"); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TPrun"); + query.addQueryParam(GridConstants.DATASET_ID, "Canadian-Reg"); query.addQueryParam("dataTime.refTime", refTime); query.addOrder("dataTime.fcstTime", true); try { - return (List) dao.queryByCriteria(query); + return (List) dao.queryByCriteria(query); } catch (DataAccessLayerException e) { throw new GribException( "Error getting Precip inventory for Canadian-Reg!", e); @@ -90,15 +91,15 @@ public class CanadianRegPostProcessor extends ThreeHrPrecipGridProcessor { @SuppressWarnings("unchecked") protected List getPrecip3hrInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TP3hr"); - query.addQueryParam("modelInfo.modelName", "Canadian-Reg"); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TP3hr"); + query.addQueryParam(GridConstants.DATASET_ID, "Canadian-Reg"); query.addQueryParam("dataTime.refTime", refTime); query.addReturnedField("dataTime.fcstTime"); try { @@ -120,12 +121,12 @@ public class CanadianRegPostProcessor extends ThreeHrPrecipGridProcessor { * @return The generated 3-hr precipitation grids * @throws GribException */ - protected synchronized GribRecord[] generate3hrPrecipGrids(GribRecord record) + protected synchronized GridRecord[] generate3hrPrecipGrids(GridRecord record) throws GribException { // The current run accumulated precipitation grid inventory in the // database - List precipInventory = getPrecipInventory(record + List precipInventory = getPrecipInventory(record .getDataTime().getRefTime()); // The current 3-hr precipitation grid inventory in the database @@ -139,16 +140,16 @@ public class CanadianRegPostProcessor extends ThreeHrPrecipGridProcessor { // Examine each grid in the inventory and generate the 3hr precipitation // grid if possible - List generatedRecords = new ArrayList(); + List generatedRecords = new ArrayList(); for (int i = 0; i < precipInventory.size(); i++) { // Check if the 3hr precipitation grid has already been produced if (!precip3hrInventory.contains(precipInventory.get(i) .getDataTime().getFcstTime())) { // If the precipitation grid has not been produced, generate it - List generated3hrPrecips = generate3hrPrecip( + List generated3hrPrecips = generate3hrPrecip( precipInventory.get(i), precipInventory, precip3hrInventory); - for (GribRecord newRecord : generated3hrPrecips) { + for (GridRecord newRecord : generated3hrPrecips) { // Add the generated grid to the current inventory if (newRecord != null) { precip3hrInventory.add(newRecord.getDataTime() @@ -159,7 +160,7 @@ public class CanadianRegPostProcessor extends ThreeHrPrecipGridProcessor { } } - return generatedRecords.toArray(new GribRecord[] {}); + return generatedRecords.toArray(new GridRecord[] {}); } /** diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ECMWFHiResProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ECMWFHiResProcessor.java index 0affb3e893..1b02eff56a 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ECMWFHiResProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ECMWFHiResProcessor.java @@ -24,12 +24,13 @@ import java.util.ArrayList; import java.util.Date; import java.util.List; -import com.raytheon.edex.plugin.grib.dao.GribDao; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * Grib post processor implementation to generate 6-hr precipitation grids from @@ -51,33 +52,33 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; public class ECMWFHiResProcessor extends SixHrPrecipGridProcessor { @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { // Post process the data if this is a Total Precipitation grid - if (record.getModelInfo().getParameterAbbreviation().equals("TP-ECMWF")) { + if (record.getParameter().getAbbreviation().equals("TP-ECMWF")) { return super.process(record); } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } /** * {@inheritDoc} */ @SuppressWarnings("unchecked") - protected List getPrecipInventory(Date refTime) + protected List getPrecipInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TP-ECMWF"); - query.addQueryParam("modelInfo.modelName", "ECMWF-HiRes"); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TP-ECMWF"); + query.addQueryParam(GridConstants.DATASET_ID, "ECMWF-HiRes"); query.addQueryParam("dataTime.refTime", refTime); query.addOrder("dataTime.fcstTime", true); try { - return (List) dao.queryByCriteria(query); + return (List) dao.queryByCriteria(query); } catch (DataAccessLayerException e) { throw new GribException( "Error getting Precip inventory for ECMWF!", e); @@ -90,15 +91,15 @@ public class ECMWFHiResProcessor extends SixHrPrecipGridProcessor { @SuppressWarnings("unchecked") protected List getPrecip6hrInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TP6hr"); - query.addQueryParam("modelInfo.modelName", "ECMWF-HiRes"); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TP6hr"); + query.addQueryParam(GridConstants.DATASET_ID, "ECMWF-HiRes"); query.addQueryParam("dataTime.refTime", refTime); query.addReturnedField("dataTime.fcstTime"); try { @@ -120,12 +121,12 @@ public class ECMWFHiResProcessor extends SixHrPrecipGridProcessor { * @return The generated 6-hr precipitation grids * @throws GribException */ - protected synchronized GribRecord[] generate6hrPrecipGrids(GribRecord record) + protected synchronized GridRecord[] generate6hrPrecipGrids(GridRecord record) throws GribException { // The current run accumulated precipitation grid inventory in the // database - List precipInventory = getPrecipInventory(record + List precipInventory = getPrecipInventory(record .getDataTime().getRefTime()); // The current 6-hr precipitation grid inventory in the database @@ -142,16 +143,16 @@ public class ECMWFHiResProcessor extends SixHrPrecipGridProcessor { // Examine each grid in the inventory and generate the 6hr precipitation // grid if possible - List generatedRecords = new ArrayList(); + List generatedRecords = new ArrayList(); for (int i = 0; i < precipInventory.size(); i++) { // Check if the 6hr precipitation grid has already been produced if (!precip6hrInventory.contains(precipInventory.get(i) .getDataTime().getFcstTime())) { // If the precipitation grid has not been produced, generate it - List generated6hrPrecips = generate6hrPrecip( + List generated6hrPrecips = generate6hrPrecip( precipInventory.get(i), precipInventory, precip6hrInventory); - for (GribRecord newRecord : generated6hrPrecips) { + for (GridRecord newRecord : generated6hrPrecips) { // Add the generated grid to the current inventory if (newRecord != null) { precip6hrInventory.add(newRecord.getDataTime() @@ -162,7 +163,7 @@ public class ECMWFHiResProcessor extends SixHrPrecipGridProcessor { } } - return generatedRecords.toArray(new GribRecord[] {}); + return generatedRecords.toArray(new GridRecord[] {}); } /** diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/EnsembleGridAssembler.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/EnsembleGridAssembler.java index 49d5bc9272..1a6dbd2aea 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/EnsembleGridAssembler.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/EnsembleGridAssembler.java @@ -28,21 +28,18 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import com.raytheon.edex.plugin.grib.dao.GribDao; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; -import com.raytheon.edex.plugin.grib.util.GribModelCache; import com.raytheon.edex.util.Util; import com.raytheon.edex.util.grib.CompositeModel; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.StatusConstants; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.StorageException; import com.raytheon.uf.common.datastorage.StorageStatus; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.LatLonGridCoverage; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; @@ -53,11 +50,11 @@ import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.util.FileUtil; -import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.cluster.ClusterLockUtils; -import com.raytheon.uf.edex.database.cluster.ClusterTask; import com.raytheon.uf.edex.database.cluster.ClusterLockUtils.LockState; +import com.raytheon.uf.edex.database.cluster.ClusterTask; import com.raytheon.uf.edex.database.plugin.PluginFactory; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * The EnsembleGridAssembler class is part of the ingest process for grib data. @@ -78,7 +75,8 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory; * @version 1 */ public class EnsembleGridAssembler implements IDecoderPostProcessor { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(EnsembleGridAssembler.class); + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(EnsembleGridAssembler.class); /** The map of the models that come in sections */ private static Map thinnedModels; @@ -125,15 +123,14 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { } } - public GribRecord[] process(GribRecord rec) throws GribException { - Map newRecords = new HashMap(); - String compositeModel = getCompositeModel(rec.getModelInfo() - .getModelName()); + public GridRecord[] process(GridRecord rec) throws GribException { + Map newRecords = new HashMap(); + String compositeModel = getCompositeModel(rec.getDatasetId()); if (compositeModel != null) { - GribRecord newRec = null; + GridRecord newRec = null; String lockName = compositeModel + "_" - + rec.getModelInfo().getParameterAbbreviation() + "_" - + rec.getModelInfo().getLevel().toString(); + + rec.getParameter().getAbbreviation() + "_" + + rec.getLevel().toString(); ClusterTask ct = ClusterLockUtils.lock(CLUSTER_TASK_NAME, lockName, 120000, true); boolean clearTime = false; @@ -157,9 +154,9 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { ClusterLockUtils.unlock(ct, clearTime); } - return new GribRecord[] { rec, newRec }; + return new GridRecord[] { rec }; } - return new GribRecord[] { rec }; + return new GridRecord[] { rec }; } /** @@ -191,35 +188,38 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { } /** - * Processes a single GribRecord + * Processes a single GridRecord * * @param record - * The GribRecord to process + * The GridRecord to process * @param thinned - * The composite model for which the GribRecord is a part of + * The composite model for which the GridRecord is a part of * @return The new grib record * @throws Exception */ - private GribRecord processGrid(GribRecord record, CompositeModel thinned) + private GridRecord processGrid(GridRecord record, CompositeModel thinned) throws Exception { - GribDao dao = (GribDao) PluginFactory.getInstance() - .getPluginDao("grib"); - String modelName = record.getModelInfo().getModelName(); + GridDao dao = (GridDao) PluginFactory.getInstance().getPluginDao( + GridConstants.GRID); + String modelName = record.getDatasetId(); + String oldGrid = record.getLocation().getId().toString(); + String newGrid = GribSpatialCache.getInstance() + .getGridByName(thinned.getGrid()).getId().toString(); String dataURI = record.getDataURI(); String assembledDataURI = dataURI.replace(modelName, - thinned.getModelName()); + thinned.getModelName()).replace(oldGrid, newGrid); List result = dao.queryBySingleCriteria("dataURI", assembledDataURI); - GribRecord assembledRecord = null; + GridRecord assembledRecord = null; if (result.isEmpty()) { assembledRecord = createRecord(record, dao, thinned); } else { - assembledRecord = (GribRecord) result.get(0); + assembledRecord = (GridRecord) result.get(0); FloatDataRecord rec = (FloatDataRecord) dao.getHDF5Data( - assembledRecord, 0)[0]; + assembledRecord, -1)[0]; assembledRecord.setMessageData(rec); - assembledRecord.setPluginName("grib"); + assembledRecord.setPluginName(GridConstants.GRID); } mergeData(record, assembledRecord, dao, thinned); @@ -228,24 +228,24 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { } /** - * Merges the data from a GribRecord into the composite GribRecord + * Merges the data from a GridRecord into the composite GridRecord * * @param record - * The GribRecord containing the data to add + * The GridRecord containing the data to add * @param assembledRecord - * The composite GribRecord + * The composite GridRecord * @param dao * An instance of the grib data access object * @param thinned * The composite model definition - * @return The composite GribRecord + * @return The composite GridRecord * @throws Exception */ - private GribRecord mergeData(GribRecord record, GribRecord assembledRecord, - GribDao dao, CompositeModel thinned) throws Exception { + private GridRecord mergeData(GridRecord record, GridRecord assembledRecord, + GridDao dao, CompositeModel thinned) throws Exception { - String modelName = record.getModelInfo().getModelName(); - GridCoverage coverage = record.getModelInfo().getLocation(); + String modelName = record.getDatasetId(); + GridCoverage coverage = record.getLocation(); long[] sizes = ((FloatDataRecord) assembledRecord.getMessageData()) .getSizes(); @@ -292,7 +292,7 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { * Creates the composite grib record and stores it to the HDF5 repository * * @param record - * The recieved GribRecord used to initialize the composite grid + * The recieved GridRecord used to initialize the composite grid * with * @param dao * An instance of the grib data access object @@ -301,7 +301,7 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { * @return The composite record * @throws GribException */ - private GribRecord createRecord(GribRecord record, GribDao dao, + private GridRecord createRecord(GridRecord record, GridDao dao, CompositeModel thinned) throws GribException { LatLonGridCoverage coverage = (LatLonGridCoverage) GribSpatialCache .getInstance().getGridByName(thinned.getGrid()); @@ -310,27 +310,19 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { for (int i = 0; i < data.length; i++) { data[i] = Util.GRID_FILL_VALUE; } - GribRecord newRecord = new GribRecord(); - GribModel newModel = new GribModel(record.getModelInfo()); - newModel.setGridid(coverage.getName()); - newModel.setGridNumber(Integer.parseInt(coverage.getName())); - newModel.setModelName(thinned.getModelName()); - newModel.setLocation(coverage); - newModel.generateId(); + GridRecord newRecord = new GridRecord(); - try { - newModel = GribModelCache.getInstance().getModel(newModel); - } catch (DataAccessLayerException e) { - throw new GribException("Unable to get model info from the cache!", - e); - } - newRecord.setModelInfo(newModel); + newRecord.setLocation(coverage); + newRecord.setDatasetId(thinned.getModelName()); + newRecord.setLevel(record.getLevel()); + newRecord.setParameter(record.getParameter()); + newRecord.setEnsembleId(record.getEnsembleId()); newRecord.setMessageData(data); newRecord.setDataTime(record.getDataTime()); newRecord.setDataURI(null); - newRecord.setPluginName("grib"); + newRecord.setPluginName(GridConstants.GRID); newRecord.setInsertTime(Calendar.getInstance()); - + newRecord.getInfo().setId(null); try { newRecord.constructDataURI(); } catch (PluginException e) { @@ -347,11 +339,11 @@ public class EnsembleGridAssembler implements IDecoderPostProcessor { exceptions[0]); } dao.persistToDatabase(newRecord); - newRecord = (GribRecord) dao.getMetadata(newRecord.getDataURI()); + newRecord = (GridRecord) dao.getMetadata(newRecord.getDataURI()); FloatDataRecord rec = (FloatDataRecord) dao.getHDF5Data(newRecord, - 0)[0]; + -1)[0]; newRecord.setMessageData(rec); - newRecord.setPluginName("grib"); + newRecord.setPluginName(GridConstants.GRID); } catch (PluginException e) { throw new GribException("Error storing new record to HDF5", e); } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/FFGGribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/FFGGribPostProcessor.java index c74545f865..a9a8b1e13b 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/FFGGribPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/FFGGribPostProcessor.java @@ -20,11 +20,15 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors; -import com.raytheon.edex.plugin.grib.dao.GribDao; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataquery.db.QueryResult; +import java.util.List; + +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; import com.raytheon.uf.edex.database.plugin.PluginFactory; +import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * The FFGGribPostProcessor is a grib post processor implementation to update @@ -46,27 +50,41 @@ import com.raytheon.uf.edex.database.plugin.PluginFactory; public class FFGGribPostProcessor implements IDecoderPostProcessor { @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { try { - GribDao gribDao = (GribDao) PluginFactory.getInstance() - .getPluginDao("grib"); + GridDao gribDao = (GridDao) PluginFactory.getInstance() + .getPluginDao(GridConstants.GRID); + record.setSecondaryId("%"); + record.setDataURI(null); record.constructDataURI(); - QueryResult result = (QueryResult) gribDao - .executeNativeSql("select max(gridVersion) from awips.grib where datauri like '" - + record.getDataURI().substring(0, - record.getDataURI().lastIndexOf("/")) - + "%'"); - int resultCount = result.getResultCount(); - if (resultCount == 1 && result.getRowColumnValue(0, 0) != null) { - int newVersion = ((Integer) result.getRowColumnValue(0, 0)) + 1; - record.setGridVersion(newVersion); + + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addReturnedField(GridConstants.SECONDARY_ID); + query.addQueryParam("dataURI", record.getDataURI(), + QueryOperand.LIKE); + List result = gribDao.queryByCriteria(query); + int maxVersion = -1; + for (Object row : result) { + String secondaryId = (String) row; + if (secondaryId == null) { + continue; + } + secondaryId = secondaryId.replace("Version", ""); + try { + int version = Integer.parseInt(secondaryId); + maxVersion = Math.max(version, maxVersion); + } catch (NumberFormatException e) { + ;// Just move on + } } + record.setSecondaryId("Version" + (maxVersion + 1)); + record.getInfo().setId(null); record.setDataURI(null); record.constructDataURI(); } catch (Exception e) { throw new GribException("Error decoding FFG grid", e); } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GFSProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GFSProcessor.java index f38130b772..39bb547b18 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GFSProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GFSProcessor.java @@ -27,14 +27,13 @@ import java.util.Comparator; import java.util.Date; import java.util.List; -import com.raytheon.edex.plugin.grib.dao.GribDao; -import com.raytheon.edex.plugin.grib.util.GribModelCache; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -42,6 +41,7 @@ import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.common.time.TimeRange; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * Used to generate 6hr record from 12hr intervals. @@ -66,13 +66,13 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { .getHandler(GFSProcessor.class); @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { // Post process the data if this is a Total Precipitation grid - if (record.getModelInfo().getParameterAbbreviation().equals("TP12hr") + if (record.getParameter().getAbbreviation().equals("TP12hr") && record.getDataTime().getFcstTime() / 3600 > 180) { return super.process(record); } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } /** @@ -86,20 +86,20 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { * @return The generated 6-hr precipitation grids * @throws GribException */ - protected synchronized GribRecord[] generate6hrPrecipGrids(GribRecord record) + protected synchronized GridRecord[] generate6hrPrecipGrids(GridRecord record) throws GribException { - List generated6hrPrecips = new ArrayList(); + List generated6hrPrecips = new ArrayList(); // Get all 6hr records 180Hrs and greater - List precipInventory = getPrecipInventory(record + List precipInventory = getPrecipInventory(record .getDataTime().getRefTime()); - List generatedRecords = new ArrayList(); + List generatedRecords = new ArrayList(); // convert current record to 6hr and add it - GribRecord transformed = transForm12to6(record); + GridRecord transformed = transForm12to6(record); generated6hrPrecips.add(transformed); precipInventory.add(transformed); - Comparator comparator = new Comparator() { + Comparator comparator = new Comparator() { @Override - public int compare(GribRecord o1, GribRecord o2) { + public int compare(GridRecord o1, GridRecord o2) { int retValue = 0; if (o1 != o2) { retValue = Double.compare(o1.getDataTime().getFcstTime(), @@ -112,8 +112,8 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { Collections.sort(precipInventory, comparator); // loop through set, find twelve hour gaps and create new 6hr records. for (int i = 0; i < precipInventory.size() - 1; i++) { - GribRecord sequence1Record = precipInventory.get(i); - GribRecord sequence2Record = precipInventory.get(i + 1); + GridRecord sequence1Record = precipInventory.get(i); + GridRecord sequence2Record = precipInventory.get(i + 1); if (sequence1Record.getDataTime().getFcstTime() == sequence2Record .getDataTime().getFcstTime() - SECONDS_IN_12_HRS) { // we have a 12Hr gap @@ -121,53 +121,53 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { sequence2Record)); } } - for (GribRecord newRecord : generated6hrPrecips) { + for (GridRecord newRecord : generated6hrPrecips) { // Add the generated grid to the current inventory if (newRecord != null) { generatedRecords.add(newRecord); } } - return generatedRecords.toArray(new GribRecord[] {}); + return generatedRecords.toArray(new GridRecord[] {}); } @SuppressWarnings("unchecked") - protected List getPrecipInventory(Date refTime) + protected List getPrecipInventory(Date refTime) throws GribException { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating grib dao!", e); } - DatabaseQuery query = new DatabaseQuery(GribRecord.class); - query.addQueryParam("modelInfo.parameterAbbreviation", "TP6hr", + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "TP6hr", QueryOperand.IN); - query.addQueryParam("modelInfo.modelName", "GFS213"); + query.addQueryParam(GridConstants.DATASET_ID, "GFS213"); query.addQueryParam("dataTime.refTime", refTime); query.addQueryParam("dataTime.fcstTime", 648000, QueryOperand.GREATERTHANEQUALS); query.addOrder("dataTime.fcstTime", true); try { - return (List) dao.queryByCriteria(query); + return (List) dao.queryByCriteria(query); } catch (DataAccessLayerException e) { throw new GribException( "Error getting Precip inventory for ECMWF!", e); } } - private GribRecord transForm12to6(GribRecord currentRecord) + private GridRecord transForm12to6(GridRecord currentRecord) throws GribException { // Clone the current record and set the ID to 0 so Hibernate will // recognize it as a new record - GribRecord tp6hrRecord = new GribRecord(currentRecord); + GridRecord tp6hrRecord = new GridRecord(currentRecord); tp6hrRecord.setId(0); if (currentRecord.getMessageData() == null) { - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); currentRecord.setMessageData(((FloatDataRecord) dao - .getHDF5Data(currentRecord, 0)[0]).getFloatData()); + .getHDF5Data(currentRecord, -1)[0]).getFloatData()); } catch (PluginException e) { throw new GribException("Error populating grib data!", e); } @@ -182,16 +182,10 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { tp6hrRecord.setMessageData(newData); // Assign the new parameter abbreviation and cache it if necessary - tp6hrRecord.getModelInfo().setParameterAbbreviation("TP6hr"); - tp6hrRecord.getModelInfo().generateId(); - try { - GribModel model = GribModelCache.getInstance().getModel( - tp6hrRecord.getModelInfo()); - tp6hrRecord.setModelInfo(model); - } catch (DataAccessLayerException e) { - throw new GribException("Unable to get model info from the cache!", - e); - } + Parameter param = new Parameter("TP6hr", "Precip Accum 6 hr", + currentRecord.getParameter().getUnit()); + tp6hrRecord.setParameter(param); + tp6hrRecord.getInfo().setId(null); // Change the data time to include the 6-hr time range super.modifyDataTime(tp6hrRecord); return tp6hrRecord; @@ -211,7 +205,7 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { } @Override - protected void modifyDataTime(GribRecord record) { + protected void modifyDataTime(GridRecord record) { Calendar refTime = record.getDataTime().getRefTimeAsCalendar(); int fcstTime = record.getDataTime().getFcstTime(); @@ -232,7 +226,7 @@ public class GFSProcessor extends SixHrPrecipGridProcessor { record.setDataTime(newDataTime); record.setDataURI(null); try { - record.setPluginName("grib"); + record.setPluginName(GridConstants.GRID); record.constructDataURI(); } catch (PluginException e) { statusHandler.handle(Priority.PROBLEM, diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GribPostProcessor.java index 03d9dd03e1..20b4551ef9 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GribPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/GribPostProcessor.java @@ -26,9 +26,9 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.util.GribModelLookup; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; @@ -53,164 +53,183 @@ import com.raytheon.uf.common.status.UFStatus; * @version 1 */ public class GribPostProcessor { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(GribPostProcessor.class); + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GribPostProcessor.class); - /** The singleton instance */ - private static GribPostProcessor instance; + /** The singleton instance */ + private static GribPostProcessor instance; - /** The map containing the currently registered grib post processors */ - private static Map> processorMap = new HashMap>(); + /** The map containing the currently registered grib post processors */ + private static Map> processorMap = new HashMap>(); - private static final String CLASS_PREFIX = "com.raytheon.edex.plugin.grib.decoderpostprocessors."; + private static final String CLASS_PREFIX = "com.raytheon.edex.plugin.grib.decoderpostprocessors."; - /** - * Gets the singleton instance of GribPostProcessor - * - * @return The singleton instance of GribPostProcessor - */ - public static synchronized GribPostProcessor getInstance() { - if (instance == null) { - instance = new GribPostProcessor(); - } - return instance; - } + /** + * Gets the singleton instance of GribPostProcessor + * + * @return The singleton instance of GribPostProcessor + */ + public static synchronized GribPostProcessor getInstance() { + if (instance == null) { + instance = new GribPostProcessor(); + } + return instance; + } - /** - * Creates a new GribPostProcessor instance - */ - private GribPostProcessor() { - String processorFile = PathManagerFactory - .getPathManager() - .getStaticFile( - "/grib/postProcessModels/postProcessedModels.xml") - .getPath(); + /** + * Creates a new GribPostProcessor instance + */ + private GribPostProcessor() { + String processorFile = PathManagerFactory + .getPathManager() + .getStaticFile( + "/grib/postProcessModels/postProcessedModels.xml") + .getPath(); - try { - // Get the list of available model names - Set modelNames = GribModelLookup.getInstance() - .getModelNames(); + try { + // Get the list of available model names + Set modelNames = GribModelLookup.getInstance() + .getModelNames(); - // Unmarshal the post processed model file - PostProcessedModelSet ppModelSet = (PostProcessedModelSet) SerializationUtil - .jaxbUnmarshalFromXmlFile(processorFile); + // Unmarshal the post processed model file + PostProcessedModelSet ppModelSet = (PostProcessedModelSet) SerializationUtil + .jaxbUnmarshalFromXmlFile(processorFile); statusHandler.info(String.format("Using postProcessorFile [%s]", processorFile)); - /* - * Iterate over post processed models. Determine which models apply - * to each post processor if a regex is present - */ - for (PostProcessedModel ppModel : ppModelSet.getModels()) { - for (String modelName : modelNames) { - if (modelName.matches(ppModel.getModelName())) { - List processorInstances = processorMap - .get(modelName); - if (processorInstances == null) { - processorMap.put(modelName, - new ArrayList()); - processorInstances = processorMap.get(modelName); - } + /* + * Iterate over post processed models. Determine which models apply + * to each post processor if a regex is present + */ + for (PostProcessedModel ppModel : ppModelSet.getModels()) { + for (String modelName : modelNames) { + if (modelName.matches(ppModel.getModelName())) { + List processorInstances = processorMap + .get(modelName); + if (processorInstances == null) { + processorMap.put(modelName, + new ArrayList()); + processorInstances = processorMap.get(modelName); + } - for (String processor : ppModel.getProcessors()) { - try { - processorInstances - .add((IDecoderPostProcessor) Class - .forName( - CLASS_PREFIX - + processor) - .newInstance()); - } catch (InstantiationException e) { - statusHandler - .fatal("Error instantiating grib post processor!", - e); - } catch (IllegalAccessException e) { - statusHandler - .fatal("Error instantiating grib post processor!", - e); - } catch (ClassNotFoundException e) { - statusHandler - .info("Class [" - + CLASS_PREFIX - + processor - + "] not found. Trying to load class: [" - + processor + "]"); - try { - processorInstances - .add((IDecoderPostProcessor) Class - .forName(processor) - .newInstance()); - } catch (Exception e1) { - statusHandler - .fatal("Error instantiating grib post processor!", - e1); - } - } + for (String processor : ppModel.getProcessors()) { + try { + processorInstances + .add((IDecoderPostProcessor) Class + .forName( + CLASS_PREFIX + + processor) + .newInstance()); + } catch (InstantiationException e) { + statusHandler + .fatal("Error instantiating grib post processor!", + e); + } catch (IllegalAccessException e) { + statusHandler + .fatal("Error instantiating grib post processor!", + e); + } catch (ClassNotFoundException e) { + statusHandler + .info("Class [" + + CLASS_PREFIX + + processor + + "] not found. Trying to load class: [" + + processor + "]"); + try { + processorInstances + .add((IDecoderPostProcessor) Class + .forName(processor) + .newInstance()); + } catch (Exception e1) { + statusHandler + .fatal("Error instantiating grib post processor!", + e1); + } + } - } + } - } - } - } - } catch (SerializationException e) { - statusHandler.fatal( - "Error unmarshalling post processed model list: "+processorFile, e); - } + } + } + } + } catch (SerializationException e) { + statusHandler.fatal( + "Error unmarshalling post processed model list: " + + processorFile, e); + } - } + } - /** - * Processes the GribRecords to determine if they need post processing - * - * @param records - * The records to examine - * @return The GribRecords including any new records created during the post - * processing - * @throws GribException - */ - public GribRecord[] process(GribRecord[] records) throws GribException { - List processors; - GribRecord[] results = null; - List additionalGrids = null; - for (int i = 0; i < records.length; i++) { - // Check the map to see if this grib record is part of a model for - // which post processing is necessary - processors = processorMap.get(records[i].getModelInfo() - .getModelName()); - if (processors != null) { - for (IDecoderPostProcessor processor : processors) { - // Post processing is not necessary, so we continue - if (processor == null) { - continue; - } - // Post processing is necessary - else { - results = processor.process(records[i]); - if (results.length == 0) { - continue; - } - records[i] = results[0]; - if (results.length > 1) { - if (additionalGrids == null) { - additionalGrids = new ArrayList(); - } - for (int j = 1; j < results.length; j++) { - additionalGrids.add(results[j]); - } - } - } - } - } - } - if (additionalGrids == null) { - return records; - } else { - GribRecord[] returnArray = new GribRecord[records.length+additionalGrids.size()]; - System.arraycopy(records, 0, returnArray, 0, records.length); - for (int i = records.length; i < returnArray.length; i++) { - returnArray[i] = additionalGrids.get(i-records.length); - } - return returnArray; - } - } + /** + * Processes the GribRecords to determine if they need post processing + * + * @param records + * The records to examine + * @return The GribRecords including any new records created during the post + * processing + * @throws GribException + */ + public GridRecord[] process(GridRecord[] records) throws GribException { + List processors; + GridRecord[] results = null; + List additionalGrids = null; + for (int i = 0; i < records.length; i++) { + // Check the map to see if this grib record is part of a model for + // which post processing is necessary + processors = processorMap.get(records[i].getDatasetId()); + if (processors != null) { + for (IDecoderPostProcessor processor : processors) { + // Post processing is not necessary, so we continue + if (processor == null) { + continue; + } + // Post processing is necessary + else { + results = processor.process(records[i]); + if (results.length == 0) { + return results; + } + records[i] = results[0]; + if (results.length > 1) { + if (additionalGrids == null) { + additionalGrids = new ArrayList(); + } + for (int j = 1; j < results.length; j++) { + additionalGrids.add(results[j]); + } + } + } + } + } + } + if (additionalGrids == null) { + return records; + } else { + for (int i = 0; i < records.length; i++) { + additionalGrids.add(records[i]); + } + return additionalGrids.toArray(new GridRecord[] {}); + } + } + + private IDecoderPostProcessor getPostProcessor(String modelName, + String processorClassName) throws GribException { + + for (List processors : processorMap.values()) { + for (IDecoderPostProcessor processor : processors) { + if (processor.getClass().getCanonicalName() + .equals(processorClassName)) { + return processor; + } + } + } + try { + return (IDecoderPostProcessor) Class.forName(processorClassName) + .newInstance(); + } catch (Exception e) { + throw new GribException( + "Error instantiating decoder post processor for " + + modelName + " model.", e); + } + } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/IDecoderPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/IDecoderPostProcessor.java index 2ebb29f633..d1c254b6f6 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/IDecoderPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/IDecoderPostProcessor.java @@ -20,8 +20,8 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; /** * Grib decoder post processor interface @@ -51,5 +51,5 @@ public interface IDecoderPostProcessor { * processing * @throws GribException */ - public GribRecord[] process(GribRecord record) throws GribException; + public GridRecord[] process(GridRecord record) throws GribException; } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LapsPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LapsPostProcessor.java index e7b7056919..e55043c555 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LapsPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LapsPostProcessor.java @@ -20,14 +20,12 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors; -import com.raytheon.edex.plugin.grib.util.GribModelCache; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.comm.CommunicationException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.level.LevelFactory; -import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.common.parameter.Parameter; /** * Adjusts the LAPS Grib data to have to correct level information @@ -56,46 +54,39 @@ public class LapsPostProcessor implements IDecoderPostProcessor { private static final String MSLP = "MSLP"; @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { - String levelName = record.getModelInfo().getLevel().getMasterLevel() - .getName(); - GribModel gribModel = record.getModelInfo(); + String levelName = record.getLevel().getMasterLevel().getName(); boolean modelInfoModified = false; if (levelName.equals(FHAG)) { try { Level sfcLevel = LevelFactory.getInstance().getLevel(SFC, 0); - gribModel.setLevel(sfcLevel); + record.setLevel(sfcLevel); modelInfoModified = true; } catch (CommunicationException e) { throw new GribException("Error modifying LAPS records.", e); } } - if (gribModel.getParameterAbbreviation().equals(PMSL)) { - gribModel.setParameterAbbreviation(MSLP); + if (record.getParameter().getAbbreviation().equals(PMSL)) { + Parameter param = new Parameter(MSLP, "Mean Sea Level Pressure", + record.getParameter().getUnit()); + record.setParameter(param); modelInfoModified = true; } if (modelInfoModified) { + record.getInfo().setId(null); + record.setDataURI(null); try { - gribModel.generateId(); - GribModel cachedModel = GribModelCache.getInstance().getModel( - gribModel); - record.setModelInfo(cachedModel); - record.setDataURI(null); - try { - record.constructDataURI(); - } catch (Exception e) { - throw new GribException( - "Error creating new dataURI for LAPS data!", e); - } - } catch (DataAccessLayerException e) { - throw new GribException("Error modifying LAPS levels!", e); + record.constructDataURI(); + } catch (Exception e) { + throw new GribException( + "Error creating new dataURI for LAPS data!", e); } } record.setOverwriteAllowed(true); - return new GribRecord[] { record }; + return new GridRecord[] { record }; } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LiftedIndexPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LiftedIndexPostProcessor.java index 1ed7ab5a6a..9095d96197 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LiftedIndexPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/LiftedIndexPostProcessor.java @@ -6,9 +6,8 @@ import java.util.List; import javax.measure.converter.UnitConverter; import javax.measure.unit.SI; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; /** * @@ -43,12 +42,12 @@ public class LiftedIndexPostProcessor implements IDecoderPostProcessor { .getConverterTo(SI.CELSIUS); @Override - public GribRecord[] process(GribRecord record) throws GribException { - GribModel modelInfo = record.getModelInfo(); + public GridRecord[] process(GridRecord record) throws GribException { // Change units of Lifted Index to match the data - if (LIFTED_INDEX_PARAMETERS.contains(modelInfo - .getParameterAbbreviation()) - && KELVIN_UNIT_STRING.equals(modelInfo.getParameterUnit())) { + if (LIFTED_INDEX_PARAMETERS.contains(record.getParameter() + .getAbbreviation()) + && KELVIN_UNIT_STRING.equals(record.getParameter() + .getUnitString())) { float[] data = (float[]) record.getMessageData(); for (int i = 0; i < data.length; i++) { if (data[i] > MAX_VALID) { @@ -56,7 +55,7 @@ public class LiftedIndexPostProcessor implements IDecoderPostProcessor { } } } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/MSASPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/MSASPostProcessor.java index e6318b1058..e75a6bd24f 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/MSASPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/MSASPostProcessor.java @@ -19,13 +19,12 @@ **/ package com.raytheon.edex.plugin.grib.decoderpostprocessors; -import com.raytheon.edex.plugin.grib.dao.GribModelDao; -import com.raytheon.edex.plugin.grib.util.GribModelCache; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; -import com.raytheon.uf.edex.database.DataAccessLayerException; +import javax.measure.unit.NonSI; +import javax.measure.unit.SI; + +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.parameter.Parameter; /** * TODO Add Description @@ -67,63 +66,49 @@ public class MSASPostProcessor implements IDecoderPostProcessor { * * @see * com.raytheon.edex.plugin.grib.decoderpostprocessors.IDecoderPostProcessor - * #process(com.raytheon.uf.common.dataplugin.grib.GribRecord) + * #process(com.raytheon.uf.common.dataplugin.grib.GridRecord) */ @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { boolean modelInfoModified = false; - GribModel gribModel = record.getModelInfo(); - String currentAbbr = gribModel.getParameterAbbreviation(); - String levelName = gribModel.getLevel().getMasterLevel().getName(); + String currentAbbr = record.getParameter().getAbbreviation(); + String levelName = record.getLevel().getMasterLevel().getName(); // Reassign PMSL at the SFC to Altimeter if (currentAbbr.equals(PMSL) && levelName.equals(SFC)) { - gribModel.setParameterAbbreviation(ALTI_ABBR); - gribModel.setParameterName(ALTI_DESC); + Parameter param = new Parameter(ALTI_ABBR, ALTI_DESC, record + .getParameter().getUnit()); + record.setParameter(param); modelInfoModified = true; } else if (currentAbbr.equals(PMSL)) { - gribModel.setParameterAbbreviation(MSLP_ABBR); - gribModel.setParameterName(MSLP_DESC); + Parameter param = new Parameter(MSLP_ABBR, MSLP_DESC, record + .getParameter().getUnit()); + record.setParameter(param); modelInfoModified = true; } // Reassigns 3-hr pressure tendency to abbreviation used by MSAS else if (currentAbbr.equals(TSLSA)) { - gribModel.setParameterAbbreviation(PT3_ABBR); - gribModel.setParameterUnit("mb*100"); + Parameter param = new Parameter(PT3_ABBR, record.getParameter() + .getName(), SI.MILLI(NonSI.BAR).times(100)); + record.setParameter(param); modelInfoModified = true; } if (modelInfoModified) { - GribModelDao dao = new GribModelDao(); - PersistableDataObject obj = dao.queryById(gribModel.getId()); - if (obj != null) { - try{ - dao.delete(obj); - }catch(Throwable e){ - e.printStackTrace(); - } - } + record.getInfo().setId(null); + record.setDataURI(null); try { - gribModel.generateId(); - GribModel cachedModel = GribModelCache.getInstance().getModel( - gribModel); - record.setModelInfo(cachedModel); - record.setDataURI(null); - try { - record.constructDataURI(); - } catch (Exception e) { - throw new GribException( - "Error creating new dataURI for MSAS data!", e); - } - } catch (DataAccessLayerException e) { - throw new GribException("Error modifying MSAS levels!", e); + record.constructDataURI(); + } catch (Exception e) { + throw new GribException( + "Error creating new dataURI for MSAS data!", e); } } record.setOverwriteAllowed(true); - return new GribRecord[] { record }; + return new GridRecord[] { record }; } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/Nam80PostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/Nam80PostProcessor.java index 839a162982..8e1ccf307c 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/Nam80PostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/Nam80PostProcessor.java @@ -25,17 +25,17 @@ import java.util.HashSet; import java.util.List; import java.util.Set; -import com.raytheon.edex.plugin.grib.dao.GribDao; -import com.raytheon.edex.plugin.grib.util.GribModelCache; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.common.time.TimeRange; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * Post processor for the NAM80 (ETA) model. This post processor generates the @@ -77,44 +77,41 @@ public class Nam80PostProcessor implements IDecoderPostProcessor { * * @see * com.raytheon.edex.plugin.grib.decoderpostprocessors.IDecoderPostProcessor - * #process(com.raytheon.uf.common.dataplugin.grib.GribRecord) + * #process(com.raytheon.uf.common.dataplugin.grib.GridRecord) */ @Override - public GribRecord[] process(GribRecord record) throws GribException { + public GridRecord[] process(GridRecord record) throws GribException { /* * Determine if this record is a 6 or 12 hour total precipitation * accumulation grid */ - if (record.getModelInfo().getParameterAbbreviation().equals(TP_12HR)) { + if (record.getParameter().getAbbreviation().equals(TP_12HR)) { return generate6HrGrids(record, false, TP_6HR, TP_12HR); - } else if (record.getModelInfo().getParameterAbbreviation() - .equals(TP_6HR)) { + } else if (record.getParameter().getAbbreviation().equals(TP_6HR)) { return generate6HrGrids(record, true, TP_6HR, TP_12HR); - } else if (record.getModelInfo().getParameterAbbreviation() - .equals(CP_12HR)) { + } else if (record.getParameter().getAbbreviation().equals(CP_12HR)) { return generate6HrGrids(record, false, CP_6HR, CP_12HR); - } else if (record.getModelInfo().getParameterAbbreviation() - .equals(CP_6HR)) { + } else if (record.getParameter().getAbbreviation().equals(CP_6HR)) { return generate6HrGrids(record, true, CP_6HR, CP_12HR); } - return new GribRecord[] { record }; + return new GridRecord[] { record }; } @SuppressWarnings("unchecked") - private GribRecord[] generate6HrGrids(GribRecord currentRecord, + private GridRecord[] generate6HrGrids(GridRecord currentRecord, boolean sixHr, String parameter6hr, String parameter12hr) throws GribException { // The 12 hr accumulation grid to use in the calculations - GribRecord tp12record = null; + GridRecord tp12record = null; // The 6 hr accumulation grid to use in the calculations - GribRecord tp6record = null; + GridRecord tp6record = null; Date refTime = currentRecord.getDataTime().getRefTime(); - GribDao dao = null; + GridDao dao = null; try { - dao = new GribDao(); + dao = new GridDao(); } catch (PluginException e) { throw new GribException("Error instantiating Grib Dao!", e); } @@ -123,27 +120,27 @@ public class Nam80PostProcessor implements IDecoderPostProcessor { * If the current record is a 6 hr accumulation grid, get the 12 hr grid * and vice versa */ - DatabaseQuery dbQuery = new DatabaseQuery(GribRecord.class); - dbQuery.addQueryParam("modelInfo.modelName", "ETA"); + DatabaseQuery dbQuery = new DatabaseQuery(GridRecord.class); + dbQuery.addQueryParam(GridConstants.DATASET_ID, "ETA"); dbQuery.addQueryParam("dataTime.refTime", refTime); if (sixHr) { tp6record = currentRecord; - dbQuery.addQueryParam("modelInfo.parameterAbbreviation", + dbQuery.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, parameter12hr); dbQuery.addQueryParam("dataTime.fcstTime", currentRecord .getDataTime().getFcstTime() + SECONDS_IN_6_HRS); } else { tp12record = currentRecord; - dbQuery.addQueryParam("modelInfo.parameterAbbreviation", + dbQuery.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, parameter6hr); dbQuery.addQueryParam("dataTime.fcstTime", currentRecord .getDataTime().getFcstTime() - SECONDS_IN_6_HRS); } try { - List results = (List) dao + List results = (List) dao .queryByCriteria(dbQuery); if (results.isEmpty()) { - return new GribRecord[] { currentRecord }; + return new GridRecord[] { currentRecord }; } if (sixHr) { tp12record = results.get(0); @@ -156,30 +153,30 @@ public class Nam80PostProcessor implements IDecoderPostProcessor { e); } - Set retVal = new HashSet(); + Set retVal = new HashSet(); retVal.add(currentRecord); retVal.add(generateGrid(tp12record, tp6record, dao, parameter6hr)); - return retVal.toArray(new GribRecord[] {}); + return retVal.toArray(new GridRecord[] {}); } - private GribRecord generateGrid(GribRecord tp12HrRecord, - GribRecord tp6HrRecord, GribDao dao, String parameter) + private GridRecord generateGrid(GridRecord tp12HrRecord, + GridRecord tp6HrRecord, GridDao dao, String parameter) throws GribException { - GribRecord newRecord = new GribRecord(); + GridRecord newRecord = new GridRecord(); try { float[] newData = null; float[] tp6Data = null; if (tp12HrRecord.getMessageData() == null) { newData = (float[]) ((FloatDataRecord) dao.getHDF5Data( - tp12HrRecord, 0)[0]).getFloatData(); + tp12HrRecord, -1)[0]).getFloatData(); } else { newData = (float[]) tp12HrRecord.getMessageData(); } if (tp6HrRecord.getMessageData() == null) { tp6Data = (float[]) ((FloatDataRecord) dao.getHDF5Data( - tp6HrRecord, 0)[0]).getFloatData(); + tp6HrRecord, -1)[0]).getFloatData(); } else { tp6Data = (float[]) tp6HrRecord.getMessageData(); } @@ -191,18 +188,12 @@ public class Nam80PostProcessor implements IDecoderPostProcessor { throw new GribException("Error retrieving precipitation data", e); } - newRecord.setModelInfo(tp6HrRecord.getModelInfo()); - newRecord.getModelInfo().setParameterAbbreviation(parameter); - newRecord.getModelInfo().generateId(); - try { - GribModel model = GribModelCache.getInstance().getModel( - newRecord.getModelInfo()); - newRecord.setModelInfo(model); - } catch (DataAccessLayerException e) { - throw new GribException("Unable to get model info from the cache!", - e); - } - + newRecord.setLocation(tp6HrRecord.getLocation()); + newRecord.setDatasetId(tp6HrRecord.getDatasetId()); + newRecord.setLevel(tp6HrRecord.getLevel()); + Parameter param = new Parameter(parameter, tp6HrRecord.getParameter() + .getUnit()); + newRecord.setParameter(param); Calendar refTime = tp12HrRecord.getDataTime().getRefTimeAsCalendar(); Date start = new Date(tp12HrRecord.getDataTime().getValidPeriod() .getEnd().getTime() @@ -214,9 +205,10 @@ public class Nam80PostProcessor implements IDecoderPostProcessor { // Reset the datauri since the datauri contains the DataTime newRecord.setDataTime(newDataTime); + newRecord.getInfo().setId(null); newRecord.setDataURI(null); try { - newRecord.setPluginName("grib"); + newRecord.setPluginName(GridConstants.GRID); newRecord.constructDataURI(); } catch (PluginException e) { throw new GribException("Error constructing dataURI!", e); diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/OverwriteGribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/OverwriteGribPostProcessor.java index f8cd76deb8..ca9c82a6a7 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/OverwriteGribPostProcessor.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/OverwriteGribPostProcessor.java @@ -20,11 +20,12 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; /** - * Grib decode post processor implementation for setting the record to allow overwrites + * Grib decode post processor implementation for setting the record to allow + * overwrites * *
  * 
@@ -42,9 +43,9 @@ import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
 public class OverwriteGribPostProcessor implements IDecoderPostProcessor {
 
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
+    public GridRecord[] process(GridRecord record) throws GribException {
         record.setOverwriteAllowed(true);
-        return new GribRecord[] { record };
+        return new GridRecord[] { record };
     }
 
 }
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RTMAGribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RTMAGribPostProcessor.java
index 4b0afca147..8deb7e32eb 100644
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RTMAGribPostProcessor.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RTMAGribPostProcessor.java
@@ -22,8 +22,8 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors;
 
 import java.util.Calendar;
 
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
+import com.raytheon.edex.plugin.grib.exception.GribException;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.time.DataTime;
 import com.raytheon.uf.common.time.TimeRange;
 
@@ -47,10 +47,10 @@ import com.raytheon.uf.common.time.TimeRange;
 public class RTMAGribPostProcessor implements IDecoderPostProcessor {
 
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
+    public GridRecord[] process(GridRecord record) throws GribException {
 
         Calendar time = record.getDataTime().getRefTimeAsCalendar();
-        if (record.getModelInfo().getParameterAbbreviation().equals("TCC")
+        if (record.getParameter().getAbbreviation().equals("TCC")
                 && time.get(Calendar.MINUTE) > 0) {
 
             time.set(Calendar.MINUTE, 0);
@@ -66,6 +66,6 @@ public class RTMAGribPostProcessor implements IDecoderPostProcessor {
                         "Error creating new dataURI for RTMA data!", e);
             }
         }
-        return new GribRecord[] { record };
+        return new GridRecord[] { record };
     }
 }
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC130GribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC130GribPostProcessor.java
index 0e69819c54..b8de53253b 100644
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC130GribPostProcessor.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC130GribPostProcessor.java
@@ -20,8 +20,8 @@
 
 package com.raytheon.edex.plugin.grib.decoderpostprocessors;
 
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
+import com.raytheon.edex.plugin.grib.exception.GribException;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 
 /**
  * Grib post processor implementation to eliminate 2-3hr duration grids from the
@@ -43,14 +43,13 @@ import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
 public class RUC130GribPostProcessor implements IDecoderPostProcessor {
 
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
+    public GridRecord[] process(GridRecord record) throws GribException {
 
         // Toss out all 2-3hr duration grids
-        if (record.getModelInfo().getParameterAbbreviation().endsWith("hr")
-                && !record.getModelInfo().getParameterAbbreviation().endsWith(
-                        "1hr")) {
-            return new GribRecord[] {};
+        if (record.getParameter().getAbbreviation().endsWith("hr")
+                && !record.getParameter().getAbbreviation().endsWith("1hr")) {
+            return new GridRecord[] {};
         }
-        return new GribRecord[] { record };
+        return new GridRecord[] { record };
     }
 }
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC236GribPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC236GribPostProcessor.java
index 105b0cdb5f..74c8e65164 100644
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC236GribPostProcessor.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/RUC236GribPostProcessor.java
@@ -20,11 +20,11 @@
 
 package com.raytheon.edex.plugin.grib.decoderpostprocessors;
 
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
+import com.raytheon.edex.plugin.grib.exception.GribException;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 
 /**
- * Grib post processor implementation to eliminate invalid 7HR and 8HR forecast 
+ * Grib post processor implementation to eliminate invalid 7HR and 8HR forecast
  * grids from the RUC236 model
  * 
  * 
@@ -43,14 +43,14 @@ import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
 public class RUC236GribPostProcessor implements IDecoderPostProcessor {
 
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
+    public GridRecord[] process(GridRecord record) throws GribException {
 
         // Toss out all 7HR and 8HR forecast grids
-    	if(record.getDataTime().getFcstTime() == 25200 
-    			|| record.getDataTime().getFcstTime() == 28800) {
-    			
-            return new GribRecord[] {};
+        if (record.getDataTime().getFcstTime() == 25200
+                || record.getDataTime().getFcstTime() == 28800) {
+
+            return new GridRecord[] {};
         }
-        return new GribRecord[] { record };
+        return new GridRecord[] { record };
     }
 }
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/SixHrPrecipGridProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/SixHrPrecipGridProcessor.java
index e36465fdcb..ba46ff2b56 100644
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/SixHrPrecipGridProcessor.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/SixHrPrecipGridProcessor.java
@@ -24,19 +24,18 @@ import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.List;
 
-import com.raytheon.edex.plugin.grib.dao.GribDao;
-import com.raytheon.edex.plugin.grib.util.GribModelCache;
+import com.raytheon.edex.plugin.grib.exception.GribException;
 import com.raytheon.uf.common.dataplugin.PluginException;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
+import com.raytheon.uf.common.parameter.Parameter;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
 import com.raytheon.uf.common.time.DataTime;
 import com.raytheon.uf.common.time.TimeRange;
-import com.raytheon.uf.edex.database.DataAccessLayerException;
+import com.raytheon.uf.edex.plugin.grid.dao.GridDao;
 
 /**
  * Abstract class to generate 6hr records
@@ -63,12 +62,12 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
     protected static final int SECONDS_IN_6_HRS = 21600;
 
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
+    public GridRecord[] process(GridRecord record) throws GribException {
 
         // Post process the data if this is a Total Precipitation grid
 
-        GribRecord[] newRecords = generate6hrPrecipGrids(record);
-        GribRecord[] retVal = new GribRecord[newRecords.length + 1];
+        GridRecord[] newRecords = generate6hrPrecipGrids(record);
+        GridRecord[] retVal = new GridRecord[newRecords.length + 1];
         retVal[0] = record;
         for (int i = 1; i < retVal.length; i++) {
             retVal[i] = newRecords[i - 1];
@@ -77,7 +76,7 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
 
     }
 
-    protected abstract GribRecord[] generate6hrPrecipGrids(GribRecord record)
+    protected abstract GridRecord[] generate6hrPrecipGrids(GridRecord record)
             throws GribException;
 
     /**
@@ -93,10 +92,10 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
      * @return The generated 6hr precipitation grid
      * @throws GribException
      */
-    protected List generate6hrPrecip(GribRecord record,
-            List precipInventory, List precip6hrInventory)
+    protected List generate6hrPrecip(GridRecord record,
+            List precipInventory, List precip6hrInventory)
             throws GribException {
-        List tp6hrRecords = new ArrayList();
+        List tp6hrRecords = new ArrayList();
         int currentFcstTime = record.getDataTime().getFcstTime();
 
         // If this is the first grid (the 6 hr grid), the 6hr precip
@@ -107,7 +106,7 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
         // If this is not the first grid, generate the new grid using the
         // previous grid
         else {
-            for (GribRecord rec : precipInventory) {
+            for (GridRecord rec : precipInventory) {
                 if (rec.getDataTime().getFcstTime() == currentFcstTime
                         - SECONDS_IN_6_HRS) {
                     tp6hrRecords.add(calculate6hrPrecip(rec, record));
@@ -128,19 +127,19 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
      * @return The generated 6hr precipitation grid
      * @throws GribException
      */
-    protected GribRecord calculate6hrPrecip(GribRecord inventoryRecord,
-            GribRecord currentRecord) throws GribException {
+    protected GridRecord calculate6hrPrecip(GridRecord inventoryRecord,
+            GridRecord currentRecord) throws GribException {
 
         // Clone the current record and set the ID to 0 so Hibernate will
         // recognize it as a new record
-        GribRecord tp6hrRecord = new GribRecord(currentRecord);
+        GridRecord tp6hrRecord = new GridRecord(currentRecord);
         tp6hrRecord.setId(0);
         if (currentRecord.getMessageData() == null) {
-            GribDao dao = null;
+            GridDao dao = null;
             try {
-                dao = new GribDao();
+                dao = new GridDao();
                 currentRecord.setMessageData(((FloatDataRecord) dao
-                        .getHDF5Data(currentRecord, 0)[0]).getFloatData());
+                        .getHDF5Data(currentRecord, -1)[0]).getFloatData());
             } catch (PluginException e) {
                 throw new GribException("Error populating grib data!", e);
             }
@@ -155,26 +154,19 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
         tp6hrRecord.setMessageData(newData);
 
         // Assign the new parameter abbreviation and cache it if necessary
-        tp6hrRecord.getModelInfo().setParameterAbbreviation("TP6hr");
-        tp6hrRecord.getModelInfo().generateId();
-        try {
-            GribModel model = GribModelCache.getInstance().getModel(
-                    tp6hrRecord.getModelInfo());
-            tp6hrRecord.setModelInfo(model);
-        } catch (DataAccessLayerException e) {
-            throw new GribException("Unable to get model info from the cache!",
-                    e);
-        }
-
+        Parameter param = new Parameter("TP6hr", "Precip Accum 6 hr",
+                currentRecord.getParameter().getUnit());
+        tp6hrRecord.setParameter(param);
+        tp6hrRecord.getInfo().setId(null);
         // Change the data time to include the 6-hr time range
         modifyDataTime(tp6hrRecord);
 
         // Calculate the new data values
         if (inventoryRecord != null) {
             if (inventoryRecord.getMessageData() == null) {
-                GribDao dao = null;
+                GridDao dao = null;
                 try {
-                    dao = new GribDao();
+                    dao = new GridDao();
                     inventoryRecord
                             .setMessageData(((FloatDataRecord) dao.getHDF5Data(
                                     inventoryRecord, 0)[0]).getFloatData());
@@ -206,7 +198,7 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
      * @param record
      *            The record to modify the datatime for
      */
-    protected void modifyDataTime(GribRecord record) {
+    protected void modifyDataTime(GridRecord record) {
 
         Calendar refTime = record.getDataTime().getRefTimeAsCalendar();
         int fcstTime = record.getDataTime().getFcstTime();
@@ -226,7 +218,7 @@ public abstract class SixHrPrecipGridProcessor implements IDecoderPostProcessor
         record.setDataTime(newDataTime);
         record.setDataURI(null);
         try {
-            record.setPluginName("grib");
+            record.setPluginName(GridConstants.GRID);
             record.constructDataURI();
         } catch (PluginException e) {
             statusHandler.handle(Priority.PROBLEM,
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/TPCSurgeProbPostProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/TPCSurgeProbPostProcessor.java
index 4ce6ad1055..36a16f9939 100644
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/TPCSurgeProbPostProcessor.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/TPCSurgeProbPostProcessor.java
@@ -22,13 +22,9 @@ package com.raytheon.edex.plugin.grib.decoderpostprocessors;
 import java.util.HashMap;
 import java.util.Map;
 
-import com.raytheon.edex.plugin.grib.dao.GribModelDao;
-import com.raytheon.edex.plugin.grib.util.GribModelCache;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
-import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject;
-import com.raytheon.uf.edex.database.DataAccessLayerException;
+import com.raytheon.edex.plugin.grib.exception.GribException;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
+import com.raytheon.uf.common.parameter.Parameter;
 
 /**
  * TODO Add Description
@@ -85,57 +81,47 @@ public class TPCSurgeProbPostProcessor implements IDecoderPostProcessor {
      * 
      * @see
      * com.raytheon.edex.plugin.grib.decoderpostprocessors.IDecoderPostProcessor
-     * #process(com.raytheon.uf.common.dataplugin.grib.GribRecord)
+     * #process(com.raytheon.uf.common.dataplugin.grib.GridRecord)
      */
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
-        GribModel gribModel = record.getModelInfo();
+    public GridRecord[] process(GridRecord record) throws GribException {
         boolean modified = false;
-        if (gribModel.getParameterAbbreviation().startsWith("PSurge")) {
-            String surge = gribModel.getParameterAbbreviation().toLowerCase()
+        Parameter param = record.getParameter();
+        if (param.getAbbreviation().startsWith("PSurge")) {
+            String surge = param.getAbbreviation().toLowerCase()
                     .replace("psurge", "").replace("ft", "");
-            gribModel.setParameterName(TPCSG_MAP.get(surge));
+            param = new Parameter(param.getAbbreviation(),
+                    TPCSG_MAP.get(surge), param.getUnitString());
             modified = true;
-        }else if(gribModel.getParameterAbbreviation().equals("TPCSG_SLOSH")){
-            gribModel.setParameterName("Real Time Slosh MEOW");
+        } else if (param.getAbbreviation().equals("TPCSG_SLOSH")) {
+            param = new Parameter(param.getAbbreviation(),
+                    "Real Time Slosh MEOW", param.getUnitString());
             modified = true;
-        }else if(gribModel.getParameterAbbreviation().startsWith("TPCSG-")){
-            gribModel.setParameterAbbreviation(gribModel.getParameterAbbreviation().substring(0,8).replace("-", "_"));
+        } else if (param.getAbbreviation().startsWith("TPCSG-")) {
+            String abbr = param.getAbbreviation().substring(0, 8)
+                    .replace("-", "_");
+            param = new Parameter(abbr, param.getName(), param.getUnitString());
             modified = true;
-        }else if (gribModel.getParameterAbbreviation().endsWith("10Pct")){
-            gribModel.setParameterAbbreviation(gribModel.getParameterAbbreviation().replace("10Pct", ""));
+        } else if (param.getAbbreviation().endsWith("10Pct")) {
+            String abbr = param.getAbbreviation().replace("10Pct", "");
+            param = new Parameter(abbr, param.getName(), param.getUnitString());
             modified = true;
         }
-        if(!modified){
-            return new GribRecord[] { record };
+        if (!modified) {
+            return new GridRecord[] { record };
         }
-        GribModelDao dao = new GribModelDao();
-        PersistableDataObject obj = dao.queryById(gribModel.getId());
-        if (obj != null) {
-            try {
-                dao.delete(obj);
-            } catch (Throwable e) {
 
-            }
-        }
+        record.setParameter(param);
+        record.getInfo().setId(null);
+        record.setDataURI(null);
         try {
-            gribModel.generateId();
-            GribModel cachedModel = GribModelCache.getInstance().getModel(
-                    gribModel);
-            record.setModelInfo(cachedModel);
-            record.setDataURI(null);
-            try {
-                record.constructDataURI();
-            } catch (Exception e) {
-                throw new GribException(
-                        "Error creating new dataURI for TPCSurgeProb data!", e);
-            }
-        } catch (DataAccessLayerException e) {
+            record.constructDataURI();
+        } catch (Exception e) {
             throw new GribException(
-                    "Error getting cached data for TPCSurgeProb!", e);
+                    "Error creating new dataURI for TPCSurgeProb data!", e);
         }
 
         record.setOverwriteAllowed(true);
-        return new GribRecord[] { record };
+        return new GridRecord[] { record };
     }
 }
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ThreeHrPrecipGridProcessor.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ThreeHrPrecipGridProcessor.java
index d918004d47..fb3dd3c854 100644
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ThreeHrPrecipGridProcessor.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/decoderpostprocessors/ThreeHrPrecipGridProcessor.java
@@ -24,19 +24,18 @@ import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.List;
 
-import com.raytheon.edex.plugin.grib.dao.GribDao;
-import com.raytheon.edex.plugin.grib.util.GribModelCache;
+import com.raytheon.edex.plugin.grib.exception.GribException;
 import com.raytheon.uf.common.dataplugin.PluginException;
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.datastorage.records.FloatDataRecord;
+import com.raytheon.uf.common.parameter.Parameter;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
 import com.raytheon.uf.common.time.DataTime;
 import com.raytheon.uf.common.time.TimeRange;
-import com.raytheon.uf.edex.database.DataAccessLayerException;
+import com.raytheon.uf.edex.plugin.grid.dao.GridDao;
 
 /**
  * Abstract class to generate 3hr records
@@ -55,7 +54,8 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
  * @author porricel
  * @version 1.0
  */
-public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcessor {
+public abstract class ThreeHrPrecipGridProcessor implements
+        IDecoderPostProcessor {
     private static final transient IUFStatusHandler statusHandler = UFStatus
             .getHandler(ThreeHrPrecipGridProcessor.class);
 
@@ -63,12 +63,12 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
     protected static final int SECONDS_IN_3_HRS = 10800;
 
     @Override
-    public GribRecord[] process(GribRecord record) throws GribException {
+    public GridRecord[] process(GridRecord record) throws GribException {
 
         // Post process the data if this is a Total Precipitation grid
 
-        GribRecord[] newRecords = generate3hrPrecipGrids(record);
-        GribRecord[] retVal = new GribRecord[newRecords.length + 1];
+        GridRecord[] newRecords = generate3hrPrecipGrids(record);
+        GridRecord[] retVal = new GridRecord[newRecords.length + 1];
         retVal[0] = record;
         for (int i = 1; i < retVal.length; i++) {
             retVal[i] = newRecords[i - 1];
@@ -77,7 +77,7 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
 
     }
 
-    protected abstract GribRecord[] generate3hrPrecipGrids(GribRecord record)
+    protected abstract GridRecord[] generate3hrPrecipGrids(GridRecord record)
             throws GribException;
 
     /**
@@ -93,10 +93,10 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
      * @return The generated 3hr precipitation grid
      * @throws GribException
      */
-    protected List generate3hrPrecip(GribRecord record,
-            List precipInventory, List precip3hrInventory)
+    protected List generate3hrPrecip(GridRecord record,
+            List precipInventory, List precip3hrInventory)
             throws GribException {
-        List tp3hrRecords = new ArrayList();
+        List tp3hrRecords = new ArrayList();
         int currentFcstTime = record.getDataTime().getFcstTime();
 
         // If this is the first grid (the 3 hr grid), the 3hr precip
@@ -107,7 +107,7 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
         // If this is not the first grid, generate the new grid using the
         // previous grid
         else {
-            for (GribRecord rec : precipInventory) {
+            for (GridRecord rec : precipInventory) {
                 if (rec.getDataTime().getFcstTime() == currentFcstTime
                         - SECONDS_IN_3_HRS) {
                     tp3hrRecords.add(calculate3hrPrecip(rec, record));
@@ -128,19 +128,19 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
      * @return The generated 3hr precipitation grid
      * @throws GribException
      */
-    protected GribRecord calculate3hrPrecip(GribRecord inventoryRecord,
-            GribRecord currentRecord) throws GribException {
+    protected GridRecord calculate3hrPrecip(GridRecord inventoryRecord,
+            GridRecord currentRecord) throws GribException {
 
         // Clone the current record and set the ID to 0 so Hibernate will
         // recognize it as a new record
-        GribRecord tp3hrRecord = new GribRecord(currentRecord);
+        GridRecord tp3hrRecord = new GridRecord(currentRecord);
         tp3hrRecord.setId(0);
         if (currentRecord.getMessageData() == null) {
-            GribDao dao = null;
+            GridDao dao = null;
             try {
-                dao = new GribDao();
+                dao = new GridDao();
                 currentRecord.setMessageData(((FloatDataRecord) dao
-                        .getHDF5Data(currentRecord, 0)[0]).getFloatData());
+                        .getHDF5Data(currentRecord, -1)[0]).getFloatData());
             } catch (PluginException e) {
                 throw new GribException("Error populating grib data!", e);
             }
@@ -155,26 +155,20 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
         tp3hrRecord.setMessageData(newData);
 
         // Assign the new parameter abbreviation and cache it if necessary
-        tp3hrRecord.getModelInfo().setParameterAbbreviation("TP3hr");
-        tp3hrRecord.getModelInfo().generateId();
-        try {
-            GribModel model = GribModelCache.getInstance().getModel(
-                    tp3hrRecord.getModelInfo());
-            tp3hrRecord.setModelInfo(model);
-        } catch (DataAccessLayerException e) {
-            throw new GribException("Unable to get model info from the cache!",
-                    e);
-        }
 
+        Parameter param = new Parameter("TP3hr", "Precip Accum 3 hr",
+                currentRecord.getParameter().getUnit());
+        tp3hrRecord.setParameter(param);
+        tp3hrRecord.getInfo().setId(null);
         // Change the data time to include the 3-hr time range
         modifyDataTime(tp3hrRecord);
 
         // Calculate the new data values
         if (inventoryRecord != null) {
             if (inventoryRecord.getMessageData() == null) {
-                GribDao dao = null;
+                GridDao dao = null;
                 try {
-                    dao = new GribDao();
+                    dao = new GridDao();
                     inventoryRecord
                             .setMessageData(((FloatDataRecord) dao.getHDF5Data(
                                     inventoryRecord, 0)[0]).getFloatData());
@@ -206,7 +200,7 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
      * @param record
      *            The record to modify the datatime for
      */
-    protected void modifyDataTime(GribRecord record) {
+    protected void modifyDataTime(GridRecord record) {
 
         Calendar refTime = record.getDataTime().getRefTimeAsCalendar();
         int fcstTime = record.getDataTime().getFcstTime();
@@ -226,7 +220,7 @@ public abstract class ThreeHrPrecipGridProcessor implements IDecoderPostProcesso
         record.setDataTime(newDataTime);
         record.setDataURI(null);
         try {
-            record.setPluginName("grib");
+            record.setPluginName(GridConstants.GRID);
             record.constructDataURI();
         } catch (PluginException e) {
             statusHandler.handle(Priority.PROBLEM,
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/exception/GribException.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/exception/GribException.java
similarity index 97%
rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/exception/GribException.java
rename to edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/exception/GribException.java
index 8b577a71cf..833b1f9d97 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/exception/GribException.java
+++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/exception/GribException.java
@@ -18,7 +18,7 @@
  * further licensing information.
  **/
 
-package com.raytheon.uf.common.dataplugin.grib.exception;
+package com.raytheon.edex.plugin.grib.exception;
 
 import com.raytheon.uf.common.dataplugin.PluginException;
 
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GetCoveragesHandler.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GetCoveragesHandler.java
deleted file mode 100644
index 4778a56a99..0000000000
--- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GetCoveragesHandler.java
+++ /dev/null
@@ -1,58 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.edex.plugin.grib.handler;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache;
-import com.raytheon.uf.common.dataplugin.grib.request.GetCoveragesRequest;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage;
-import com.raytheon.uf.common.serialization.comm.IRequestHandler;
-
-/**
- * 
- * TODO Add Description
- * 
- * 
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Dec 20, 2011            bsteffen     Initial creation
- * 
- * 
- * - * @author bsteffen - * @version 1.0 - */ -public class GetCoveragesHandler implements - IRequestHandler { - - @Override - public List handleRequest(GetCoveragesRequest request) { - List result = new ArrayList(); - for (String modelName : request.getModelNames()) { - result.add(GribSpatialCache.getInstance().getGrid(modelName)); - } - return result; - } -} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GridDataHandler.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GridDataHandler.java index 979e715397..3aab10ef03 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GridDataHandler.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GridDataHandler.java @@ -23,18 +23,19 @@ import java.sql.Timestamp; import java.util.Arrays; import java.util.List; -import com.raytheon.edex.plugin.grib.dao.GribDao; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; import com.raytheon.uf.common.dataplugin.grib.GribThriftContainer; import com.raytheon.uf.common.dataplugin.grib.GribThriftRecord; import com.raytheon.uf.common.dataplugin.grib.request.GridDataRequestMessage; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.common.serialization.comm.IRequestHandler; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; /** * TODO Add Description @@ -57,29 +58,29 @@ public class GridDataHandler implements IRequestHandler public Object handleRequest(GridDataRequestMessage request) throws Exception { - GribDao dao = new GribDao(); - DatabaseQuery query = new DatabaseQuery(GribRecord.class); + GridDao dao = new GridDao(); + DatabaseQuery query = new DatabaseQuery(GridRecord.class); if (request.getModelName() != null && !"".equals(request.getModelName())) { - query.addQueryParam("modelInfo.modelName", request.getModelName(), - QueryOperand.EQUALS); + query.addQueryParam(GridConstants.DATASET_ID, + request.getModelName(), QueryOperand.EQUALS); } if (request.getLevelOne() != Level.INVALID_VALUE) { - query.addQueryParam("modelInfo.level.levelonevalue", - request.getLevelOne(), QueryOperand.EQUALS); + query.addQueryParam(GridConstants.LEVEL_ONE, request.getLevelOne(), + QueryOperand.EQUALS); if (request.getLevelType() != null) { - query.addQueryParam("modelInfo.level.masterLevel.name", + query.addQueryParam(GridConstants.MASTER_LEVEL_NAME, request.getLevelType(), QueryOperand.EQUALS); } - query.addQueryParam("modelInfo.level.leveltwovalue", - request.getLevelTwo(), QueryOperand.EQUALS); + query.addQueryParam(GridConstants.LEVEL_TWO, request.getLevelTwo(), + QueryOperand.EQUALS); } if (request.getParameterAbbreviation() != null && !"".equals(request.getParameterAbbreviation())) { - query.addQueryParam("modelInfo.parameterAbbreviation", + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, request.getParameterAbbreviation(), QueryOperand.EQUALS); } @@ -105,7 +106,7 @@ public class GridDataHandler implements IRequestHandler for (int i = 0; i < records.length; i++) { thriftRecords[i] = new GribThriftRecord(); IDataRecord[] data = hdfRecords.get(i); - GribRecord thisGribRecord = (GribRecord) records[i]; + GridRecord thisGribRecord = (GridRecord) records[i]; GridDataRequestMessage thisGribInfo = new GridDataRequestMessage(); thisGribInfo.setInfoFromRecord(thisGribRecord); thriftRecords[i].setMessage(thisGribInfo); diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyMessage.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyMessage.java index 7b3825402c..d6cdde7e67 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyMessage.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyMessage.java @@ -21,8 +21,7 @@ package com.raytheon.edex.plugin.grib.notify; import java.util.Date; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; @@ -84,17 +83,15 @@ public class GribNotifyMessage implements ISerializableObject { } - public GribNotifyMessage(GribRecord grib) { - GribModel modelInfo = grib.getModelInfo(); + public GribNotifyMessage(GridRecord grib) { this.setInsertTime(grib.getInsertTime().getTime()); this.setDataTime(grib.getDataTime()); - this.setModel(modelInfo.getModelName()); - this.setLevelName(modelInfo.getLevelName()); - this.setLevelOne(modelInfo.getLevelOneValue()); - this.setLevelTwo(modelInfo.getLevelTwoValue()); - this.setParamAbbreviation(grib.getModelInfo() - .getParameterAbbreviation()); + this.setModel(grib.getDatasetId()); + this.setLevelName(grib.getLevel().getMasterLevel().getName()); + this.setLevelOne(grib.getLevel().getLevelonevalue()); + this.setLevelTwo(grib.getLevel().getLeveltwovalue()); + this.setParamAbbreviation(grib.getParameter().getAbbreviation()); this.setDataURI(grib.getDataURI()); } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyQueue.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyQueue.java index 082308283d..115d7dea88 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyQueue.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/notify/GribNotifyQueue.java @@ -23,7 +23,7 @@ import java.util.ArrayList; import java.util.List; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -68,7 +68,7 @@ public class GribNotifyQueue { if (gribs != null && gribs.length > 0) { synchronized (syncObj) { for (PluginDataObject grib : gribs) { - queuedMsgs.add(new GribNotifyMessage((GribRecord) grib)); + queuedMsgs.add(new GribNotifyMessage((GridRecord) grib)); } syncObj.notifyAll(); } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/GribSpatialCache.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/GribSpatialCache.java index 2b7bb6d8e0..9935b65395 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/GribSpatialCache.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/GribSpatialCache.java @@ -21,52 +21,51 @@ package com.raytheon.edex.plugin.grib.spatial; import java.io.File; +import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Set; + +import javax.xml.bind.JAXBException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opengis.metadata.spatial.PixelOrientation; -import com.raytheon.edex.plugin.grib.dao.GribModelDao; -import com.raytheon.edex.plugin.grib.dao.GridCoverageDao; -import com.raytheon.edex.plugin.grib.dao.IGridCoverageDao; +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.util.GribModelLookup; +import com.raytheon.edex.plugin.grib.util.GridModel; import com.raytheon.edex.site.SiteUtil; import com.raytheon.uf.common.awipstools.GetWfoCenterPoint; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.Corner; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext; -import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; -import com.raytheon.uf.common.localization.LocalizationFile; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.serialization.JAXBManager; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; import com.raytheon.uf.edex.awipstools.GetWfoCenterHandler; -import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.cluster.ClusterLockUtils; import com.raytheon.uf.edex.database.cluster.ClusterLockUtils.LockState; import com.raytheon.uf.edex.database.cluster.ClusterTask; -import com.raytheon.uf.edex.database.dao.CoreDao; -import com.raytheon.uf.edex.database.dao.DaoConfig; import com.vividsolutions.jts.geom.Coordinate; /** - * Cache used for holding GridCoverage objects. Since creating geometries and - * CRS objects are expensive operations, this cache is used to store - * GridCoverages as they are produced. + * Cache used for holding GridCoverage objects. This cache is responsible for + * managing the grids and subgrids stored on the filesystem for grib data. The + * functions in this class have some overlap with the GridCoverageLookup, + * methods in this class have some extra functionality for trying to resolve + * grids off the filesystem. * *
  * 
@@ -75,7 +74,7 @@ import com.vividsolutions.jts.geom.Coordinate;
  * Date         Ticket#     Engineer    Description
  * ------------ ----------  ----------- --------------------------
  * 4/7/09       1994        bphillip    Initial Creation
- * Jul 25, 2012 977         rjpeter     Add ability for sub grids to have a defined center point.
+ * 
  * 
* * @author bphillip @@ -84,17 +83,10 @@ import com.vividsolutions.jts.geom.Coordinate; public class GribSpatialCache { /** The logger */ - protected Log logger = LogFactory.getLog(getClass()); + protected transient Log logger = LogFactory.getLog(getClass()); /** The singleton instance */ - private static GribSpatialCache instance = new GribSpatialCache(); - - /** - * Map containing the GridCoverages
- * The key for this map is the id field of the GridCoverage object stored as - * the value of the map - */ - private final Map spatialMap; + private static GribSpatialCache instance; /** * Map containing the GridCoverages
@@ -102,24 +94,46 @@ public class GribSpatialCache { * as the value of the map. This is only used internally for lookup of a * coverage by name aka gridId. */ - private final Map spatialNameMap; + private Map spatialNameMap; /** - * Map containing the subGrid coverage based on a model name. + * Maps a GridCoverage id to a set of grid names. The id should come from a + * coverage in the database but the names are not necessarily in the + * database. If a grid file spatially matches a grid in the database it will + * not be added to the db to avoid confusion, this map can be used to look + * up those names. */ - private final Map subGridCoverageMap; + private Map> gridNameMap; /** - * Map containing the subGrid definition based on a model name. + * Map containing the subGrid coverage based on a subGridKey */ - private final Map definedSubGridMap; + private Map subGridCoverageMap; + + /** + * Map containing the subGrid based on a the subGridKey + */ + private Map definedSubGridMap; + + /** + * Map containing the subGrid definition based on a model name and the base + * coverage name + */ + private Map subGridDefMap; + + private FileDataList fileDataList; + + private long fileScanTime = 0; /** * Gets the singleton instance of GribSpatialCache * * @return The singleton instance of the GribSpatialCache */ - public static GribSpatialCache getInstance() { + public static synchronized GribSpatialCache getInstance() { + if (instance == null) { + instance = new GribSpatialCache(); + } return instance; } @@ -127,485 +141,242 @@ public class GribSpatialCache { * Creates a new GribSpatialCache */ private GribSpatialCache() { - spatialMap = new HashMap(); + gridNameMap = new HashMap>(); spatialNameMap = new HashMap(); definedSubGridMap = new HashMap(); - subGridCoverageMap = new HashMap(); - initializeGrids(); + subGridCoverageMap = new HashMap(); + subGridDefMap = new HashMap(); + scanFiles(); } /** - * Retrieves a grid from the map. If the grid does not exist, null is - * returned + * Retrieves a grid from the map. If the grid does not exist, the + * localization files are scanned for newly defined grids, if it still + * doesn't exist null is returned * - * @param id - * The id of the GridCoverage to retrieve + * @param coverage + * a grid coverage * @return The GridCoverage object, null if not present * @throws GribException * @throws DataAccessLayerException */ - public GridCoverage getGrid(final GridCoverage coverage) - throws GribException { - GridCoverage retVal = spatialMap.get(coverage.getId()); - - if (retVal == null) { - /* - * Coverage not found in cache, but the values provided in the GDS - * may be slightly different than those for the grid in the cache. - * Check the database to be sure. - */ - try { - retVal = ((IGridCoverageDao) EDEXUtil.getESBComponent(coverage - .getProjectionType().replaceAll(" ", "") + "Dao")) - .checkGrid(coverage); - } catch (DataAccessLayerException e) { - throw new GribException("Error querying for grib coverage!", e); - } - - if (retVal != null) { - spatialMap.put(coverage.getId(), retVal); - spatialNameMap.put(coverage.getName(), retVal); - } - + public GridCoverage getGrid(GridCoverage coverage) { + GridCoverage rval = GridCoverageLookup.getInstance().getCoverage( + coverage, false); + if (rval == null) { + scanFiles(); + rval = GridCoverageLookup.getInstance() + .getCoverage(coverage, false); } - - return retVal; + return rval; } - public GridCoverage getGrid(final int id) { - return spatialMap.get(id); - } - - public GridCoverage getGrid(final String modelName) { - GridCoverage rval = null; - + /** + * For a grib model name return all GridCoverages that are defined in the + * gribModels file for that model. For models which use subgrids this will + * return the subgridded coverages. For models that are not defined or + * models that do not specify a specific grid this will return an empty + * list. + * + * @param modelName + * @return + */ + public List getGridsForModel(String modelName) { + List rval = new ArrayList(); if (modelName != null) { - if (subGridCoverageMap.containsKey(modelName)) { - rval = spatialMap.get(subGridCoverageMap.get(modelName)); - } else { - GridModel model = GribModelLookup.getInstance().getModelByName( - modelName); - if (model != null) { - rval = spatialNameMap.get(model.getGrid().toString()); - } - } - } - - return rval; - } - - public GridCoverage getGridByName(final String name) { - return spatialNameMap.get(name); - } - - /** - * Puts a grid into the GribSpatialCache. - * - * @param grid - * The grid to store - * @param persistToDb - * True if this GridCoverage object is to be persisted to the - * database - * @throws GribException - * If problems occur while initializing the grid - */ - public void putGrid(final GridCoverage grid, final boolean initializeGrid, - final boolean persistToDb) throws GribException { - if (initializeGrid) { - /* - * Prepare the grid to be stored into the cache. Initializes the - * geometry and crs objects and generates the id field - */ - grid.initialize(); - if (grid.getName() == null) { - grid.generateName(); - } - } - - // Persist to the database if desired - if (persistToDb) { - new CoreDao(DaoConfig.DEFAULT).saveOrUpdate(grid); - } - - spatialMap.put(grid.getId(), grid); - spatialNameMap.put(grid.getName(), grid); - } - - public SubGrid getSubGrid(final String modelName) { - return definedSubGridMap.get(modelName); - } - - public GridCoverage getSubGridCoverage(final String modelName) { - GridCoverage rval = null; - - if (subGridCoverageMap.containsKey(modelName)) { - rval = spatialMap.get(subGridCoverageMap.get(modelName)); - } - - return rval; - } - - /** - * Initializes the predefined set of grids. The grids are stored in xml - * format in the utility folder so the localization service has access to - * them.
- * GridCoverage are created from the xml via JaxB and placed in the cache - */ - private void initializeGrids() { - ClusterTask ct = null; - - do { - ct = ClusterLockUtils.lock("grib", "spatialCache", 120000, true); - } while (!LockState.SUCCESSFUL.equals(ct.getLockState())); - - try { - // pull all the coverage from the database - GridCoverageDao dao = new GridCoverageDao(); - FileDataList previousFdl = getPreviousFileDataList(); - FileDataList currentFdl = generateFileDataList(); - - if (isDefintionChanged(previousFdl, currentFdl)) { - processBaseGridsChanged(dao, currentFdl); - saveFileDataList(currentFdl); - } else { - List baseCoverages = dao - .loadBaseGrids(); - - if ((baseCoverages != null) && (baseCoverages.size() > 0)) { - for (Object obj : baseCoverages) { - try { - putGrid((GridCoverage) obj, false, false); - } catch (Exception e) { - // Log error but do not throw exception, technically - // is - // only from initialize which isn't being called - logger.error( - "Unable to load grid coverage into cache " - + obj, e); - } + GridModel model = GribModelLookup.getInstance().getModelByName( + modelName); + if (model != null) { + for (String coverageName : model.getAllGrids()) { + GridCoverage coverage = getGridByName(coverageName); + if (coverage != null) { + rval.add(coverage); } - } else { - // database wiped/plugin re-initialized need to repopulate - processBaseGridsChanged(dao, currentFdl); - saveFileDataList(currentFdl); } } - - processUnknownGrids(dao); - processSubGrids(dao, currentFdl); - } finally { - ClusterLockUtils.unlock(ct, false); } + for (int i = 0; i < rval.size(); i++) { + GridCoverage subGrid = getSubGridCoverage(modelName, rval.get(i)); + if (subGrid != null) { + rval.remove(i); + rval.add(i, subGrid); + } + } + + return rval; } /** - * A non subgridded definition has been added, deleted, or changed. - * Changed/delete both delete all records, models, and coverage defintion. - * Then Change/Add put in a new coverage definition. + * Get a grib by name, first all grid files are searched to find one with a + * matching name, if none is found the database is checked. The returned + * coverage may not have the name you are looking for but it will be + * spatially equivalent to that named grid. * - * TODO: Post process Unknown definitions to see if they are now known. If - * now known delete definitions of unknown. - * - * @param dao - * @param currentFdl + * @param name + * @return */ - private void processBaseGridsChanged(final GridCoverageDao dao, - final FileDataList currentFdl) { - List baseCoverages = dao.loadBaseGrids(); - Map fileCoverageMap = loadGridDefinitionsFromDisk(currentFdl); - - // update needs to delete all hdf5 same as delete, so update is - // a delete and then an add to simplify logic and handle primary - // key changes. - List coveragesToDelete = new LinkedList(); - HashSet validDbCoverageNames = new HashSet( - (int) (baseCoverages.size() * 1.25) + 1); - - Iterator iter = baseCoverages.iterator(); - while (iter.hasNext()) { - GridCoverage dbCov = iter.next(); - GridCoverage fileCoverage = fileCoverageMap.get(dbCov.getName()); - if (!dbCov.equals(fileCoverage)) { - // coverage not in flat file or coverage has changed, - // delete coverage old coverage - coveragesToDelete.add(dbCov); - iter.remove(); - } else { - // current coverage still valid - validDbCoverageNames.add(dbCov.getName()); - } - } - - // delete grids, models, coverages, and hdf5 for namesToDelete. - for (GridCoverage cov : coveragesToDelete) { - logger.info("GridCoverage " + cov.getName() - + " has changed. Deleting out of date data"); - if (!dao.deleteCoverageAssociatedData(cov, true)) { - logger.warn("Failed to delete GridCoverage " + cov.getName() - + ". Manual intervention required."); - } else { - logger.info("GridCoverage successfully deleted"); - } - } - - // remove the valid db coverages from the map - fileCoverageMap.keySet().removeAll(validDbCoverageNames); - - // add new grids in bulk - for (GridCoverage cov : fileCoverageMap.values()) { - try { - putGrid(cov, true, false); - } catch (Exception e) { - logger.error( - "Failed to initialize grid definition " + cov.getName(), - e); - } - } - - // bulk persist the spatial maps - if (spatialMap.size() > 0) { - dao.persistAll(spatialMap.values()); - } - - for (GridCoverage cov : baseCoverages) { - try { - putGrid(cov, false, false); - } catch (Exception e) { - logger.error( - "Failed to initialize grid definition " + cov.getName(), - e); - } + public GridCoverage getGridByName(String name) { + GridCoverage coverage = spatialNameMap.get(name); + if (coverage == null) { + // rescan and hopefully the coverage shows up + scanFiles(); + coverage = spatialNameMap.get(name); } + return coverage; } /** - * A non subGridd definition has been added, deleted, or changed. - * Changed/delete both delete all records, models, and coverage defintion. - * Then Change/Add put in a new coverage definition, and also delete any - * data associated with base model definition. + * This method provides a way to get the names from the definiton files for + * looking up a grib model. It will return all the names of any coverages + * defined in the grid definition files that are spatially equivalent to the + * passed in coverage. This is useful when there are multiple grid + * definition files with the same spatial attributes but different names or + * for cases where the name in the definition file does not match what is + * currently in the db. * - * @param dao - * @param currentFdl + * @param coverage + * @return */ - private void processSubGrids(final GridCoverageDao dao, - final FileDataList currentFdl) { - List oldSubGridCoverages = dao.loadSubGrids(); - Map fileSubGridCoverageMap = loadSubGridDefinitionsFromDisk(currentFdl); - - // update needs to delete all hdf5 same as delete, so update is - // a delete and then an add to simplify logic and handle primary - // key changes. - List coveragesToDelete = new LinkedList(); - HashSet validDbCoverageNames = new HashSet( - (int) (oldSubGridCoverages.size() * 1.25) + 1); - - Iterator iter = oldSubGridCoverages.iterator(); - while (iter.hasNext()) { - GridCoverage dbCov = iter.next(); - GridCoverage fileCoverage = fileSubGridCoverageMap.get(dbCov - .getName()); - if (!dbCov.equals(fileCoverage)) { - // coverage not in flat file or coverage has changed, - // delete coverage - coveragesToDelete.add(dbCov); - iter.remove(); - } else { - // current coverage still valid - validDbCoverageNames.add(dbCov.getName()); - } - } - - // delete grids, models, coverages, and hdf5 for namesToDelete. - for (GridCoverage cov : coveragesToDelete) { - logger.info("Model " - + cov.getSubGridModel() - + " has changed subGrid definition, deleting out of date data"); - if (!dao.deleteCoverageAssociatedData(cov, true)) { - logger.warn("Failed to delete GridCoverage " + cov.getName() - + ". Manual intervention required."); - } else { - logger.info("GridModel successfully deleted"); - } - } - - // remove the valid db coverages from the map - fileSubGridCoverageMap.keySet().removeAll(validDbCoverageNames); - - // need to delete model information for new adds, as old grid may not - // have been subgridded - GribModelDao modelDao = new GribModelDao(); - for (GridCoverage cov : fileSubGridCoverageMap.values()) { - logger.info("Model " - + cov.getSubGridModel() - + " has changed subGrid definition, deleting out of date data"); - // look up parent - if (modelDao.deleteModelAndAssociatedData(cov.getSubGridModel()) < 0) { - logger.warn("Failed to delete SubGrid Model " - + cov.getSubGridModel() - + ". Manual intervention required."); - } else { - logger.info("GridModel successfully deleted"); - } - } - - // add new grids, persisting individually - for (GridCoverage cov : fileSubGridCoverageMap.values()) { - try { - putGrid(cov, true, true); - subGridCoverageMap.put(cov.getSubGridModel(), cov.getId()); - } catch (Exception e) { - logger.error( - "Failed to initialize grid definition " + cov.getName(), - e); - } - } - - // put database grids into map - for (GridCoverage cov : oldSubGridCoverages) { - try { - putGrid(cov, true, true); - subGridCoverageMap.put(cov.getSubGridModel(), cov.getId()); - } catch (Exception e) { - logger.error( - "Failed to initialize grid definition " + cov.getName(), - e); + public Set getGribCoverageNames(GridCoverage coverage) { + Set rval = gridNameMap.get(coverage.getId()); + if (rval == null) { + scanFiles(); + rval = gridNameMap.get(coverage.getId()); + if (rval == null) { + rval = Collections.emptySet(); } } + return rval; } - private void processUnknownGrids(final GridCoverageDao dao) { - List unknownGrids = dao.loadUnknownGrids(); - for (GridCoverage cov : unknownGrids) { - try { - GridCoverage dbCov = getGrid(cov); - if (!cov.getName().equals(dbCov.getName())) { - logger.info("Unknown grid " + cov.getName() - + " is now mapped by " + dbCov.getName() - + ". Deleting unknown grid"); - dao.deleteCoverageAssociatedData(cov, true); + /** + * For a given modelName and coverage this will return the SubGrid used for + * slicing data if there is a subGrid file for this model. If this model + * does not require subgridding this method will return null. + * + * @param modelName + * @param coverage + * @return + */ + public SubGrid getSubGrid(String modelName, GridCoverage coverage) { + SubGrid subGrid = definedSubGridMap + .get(subGridKey(modelName, coverage)); + if (subGrid == null) { + if (loadSubGrid(modelName, coverage)) { + subGrid = definedSubGridMap + .get(subGridKey(modelName, coverage)); + } + } + return subGrid; + } + + /** + * For a given modelName and coverage this will return the sub-GridCoverage + * which should be used for this data. If this model does not require + * subgridding this method will return null. + * + * @param modelName + * @param coverage + * @return + */ + public GridCoverage getSubGridCoverage(String modelName, + GridCoverage coverage) { + GridCoverage subGrid = subGridCoverageMap.get(subGridKey(modelName, + coverage)); + if (subGrid == null) { + if (loadSubGrid(modelName, coverage)) { + subGrid = subGridCoverageMap + .get(subGridKey(modelName, coverage)); + } + } + return subGrid; + } + + /** + * If a sub grid area is defined for this model than this will process that + * defintion and piopulate the subGridCoverageMap and definedSubGridMap. + * + * @param modelName + * @param coverage + * @return true if this model is subgridded, false otherwise + */ + private boolean loadSubGrid(String modelName, GridCoverage coverage) { + SubGridDef subGridDef = subGridDefMap.get(modelName); + if (subGridDef != null) { + String referenceGrid = subGridDef.getReferenceGrid(); + if (referenceGrid == null) { + referenceGrid = GribModelLookup.getInstance() + .getModelByName(subGridDef.getReferenceModel()) + .getGrid(); + if (referenceGrid == null) { + logger.error("Failed to generate sub grid, Unable to determine coverage for referenceModel [" + + subGridDef.getReferenceModel() + "]"); + return false; } - } catch (Exception e) { - logger.error("Erro occurred scanning unknown grids", e); - } - } - } - - private Map loadSubGridDefinitionsFromDisk( - final FileDataList currentFdl) { - GribModelLookup gribModelLUT = GribModelLookup.getInstance(); - List subGridDefs = currentFdl.getSubGridFileList(); - Map subGrids = null; - - if ((subGridDefs != null) && (subGridDefs.size() > 0)) { - subGrids = new HashMap(subGridDefs.size() * 3); - - Coordinate defaultCenterPoint = null; - - try { - defaultCenterPoint = getDefaultSubGridCenterPoint(); - } catch (Exception e) { - logger.error( - "Failed to generate sub grid definitions. Unable to lookup WFO Center Point", - e); - return new HashMap(0); } - for (FileData fd : subGridDefs) { + GridCoverage referenceCoverage = getGridByName(referenceGrid + .toString()); + if (referenceCoverage == null) { + logger.error("Failed to generate sub grid, Unable to determine coverage for referenceGrid [" + + referenceGrid + "]"); + return false; + } + + Coordinate subGridCenterLatLon = new Coordinate( + subGridDef.getCenterLongitude(), + subGridDef.getCenterLatitude()); + + Coordinate subGridCenterGridCoord = MapUtil.latLonToGridCoordinate( + subGridCenterLatLon, PixelOrientation.CENTER, + referenceCoverage); + + double xCenterPoint = subGridCenterGridCoord.x; + double yCenterPoint = subGridCenterGridCoord.y; + + double xDistance = subGridDef.getNx() / 2; + double yDistance = subGridDef.getNy() / 2; + Coordinate lowerLeftPosition = new Coordinate(xCenterPoint + - xDistance, yCenterPoint + yDistance); + Coordinate upperRightPosition = new Coordinate(xCenterPoint + + xDistance, yCenterPoint - yDistance); + + lowerLeftPosition = MapUtil.gridCoordinateToLatLon( + lowerLeftPosition, PixelOrientation.CENTER, + referenceCoverage); + upperRightPosition = MapUtil.gridCoordinateToLatLon( + upperRightPosition, PixelOrientation.CENTER, + referenceCoverage); + + SubGrid subGrid = new SubGrid(); + subGrid.setLowerLeftLon(lowerLeftPosition.x); + subGrid.setLowerLeftLat(lowerLeftPosition.y); + subGrid.setUpperRightLon(upperRightPosition.x); + subGrid.setUpperRightLat(upperRightPosition.y); + + // verify numbers in -180 -> 180 range + subGrid.setLowerLeftLon(MapUtil.correctLon(subGrid + .getLowerLeftLon())); + subGrid.setUpperRightLon(MapUtil.correctLon(subGrid + .getUpperRightLon())); + + GridCoverage subGridCoverage = coverage.trim(subGrid); + + if (subGridCoverage != null) { try { - SubGridDef subGridDef = loadSubGridDef(fd.getFilePath(), - defaultCenterPoint); - - if (subGridDef != null) { - String referenceModel = subGridDef.getReferenceModel(); - - GridCoverage gridCoverage = getGrid(referenceModel); - - if (gridCoverage != null) { - Coordinate subGridCenterLatLon = new Coordinate( - subGridDef.getCenterLongitude(), - subGridDef.getCenterLatitude()); - - Coordinate subGridCenterGridCoord = MapUtil - .latLonToGridCoordinate( - subGridCenterLatLon, - PixelOrientation.CENTER, - gridCoverage); - - double xCenterPoint = subGridCenterGridCoord.x; - double yCenterPoint = subGridCenterGridCoord.y; - - double xDistance = subGridDef.getNx() / 2; - double yDistance = subGridDef.getNy() / 2; - Coordinate lowerLeftPosition = new Coordinate( - xCenterPoint - xDistance, yCenterPoint - + yDistance); - Coordinate upperRightPosition = new Coordinate( - xCenterPoint + xDistance, yCenterPoint - - yDistance); - - lowerLeftPosition = MapUtil.gridCoordinateToLatLon( - lowerLeftPosition, PixelOrientation.CENTER, - gridCoverage); - upperRightPosition = MapUtil - .gridCoordinateToLatLon(upperRightPosition, - PixelOrientation.CENTER, - gridCoverage); - - subGridDef.setLowerLeftLon(lowerLeftPosition.x); - subGridDef.setLowerLeftLat(lowerLeftPosition.y); - subGridDef.setUpperRightLon(upperRightPosition.x); - subGridDef.setUpperRightLat(upperRightPosition.y); - - // verify numbers in -180 -> 180 range - subGridDef.setLowerLeftLon(MapUtil - .correctLon(subGridDef.getLowerLeftLon())); - subGridDef.setUpperRightLon(MapUtil - .correctLon(subGridDef.getUpperRightLon())); - - // do a reverse lookup of the model name to get its - // associated grid id - - for (String modelName : subGridDef.getModelNames()) { - GridModel model = gribModelLUT - .getModelByName(modelName); - if (model != null) { - GridCoverage baseCoverage = spatialNameMap - .get(model.getGrid().toString()); - - if (baseCoverage != null) { - SubGrid subGrid = new SubGrid(); - subGrid.setModelName(modelName); - GridCoverage subGridCoverage = baseCoverage - .trim(subGridDef, subGrid); - if (subGridCoverage != null) { - subGrids.put( - subGridCoverage.getName(), - subGridCoverage); - definedSubGridMap.put(modelName, - subGrid); - } - } - } - } - } else { - logger.error("Failed to generate sub grid for " - + fd.getFilePath() - + ". Unable to determine coverage for referenceModel [" - + referenceModel + "]"); - } - } + subGridCoverage = insert(subGridCoverage); } catch (Exception e) { - // Log error but do not throw exception - logger.error( - "Failed processing sub grid file: " - + fd.getFilePath(), e); + logger.error(e.getLocalizedMessage(), e); + return false; } + subGridCoverageMap.put(subGridKey(modelName, coverage), + subGridCoverage); + definedSubGridMap.put(subGridKey(modelName, coverage), subGrid); } + return true; } else { - subGrids = new HashMap(0); + return false; } - - return subGrids; } /** @@ -622,9 +393,10 @@ public class GribSpatialCache { if (f.length() > 0) { try { - rval = (SubGridDef) SerializationUtil - .jaxbUnmarshalFromXmlFile(f); - if ((rval.getReferenceModel() == null) + JAXBManager manager = new JAXBManager(SubGridDef.class); + rval = (SubGridDef) manager.jaxbUnmarshalFromXmlFile(f); + if ((rval.getReferenceModel() == null && rval + .getReferenceGrid() == null) || (rval.getModelNames() == null) || (rval.getModelNames().size() == 0)) { // sub grid didn't have required definitions @@ -632,28 +404,127 @@ public class GribSpatialCache { } else { if ((rval.getCenterLatitude() == null) || (rval.getCenterLongitude() == null)) { - rval.setCenterLatitude(defaultCenter.y); - rval.setCenterLongitude(defaultCenter.x); + if (defaultCenter == null) { + rval = null; + } else { + rval.setCenterLatitude(defaultCenter.y); + rval.setCenterLongitude(defaultCenter.x); + } } } } catch (SerializationException e) { logger.error("Failed reading sub grid file: " + filePath, e); + } catch (JAXBException e) { + logger.error("Failed reading sub grid file: " + filePath, e); } } return rval; } - private static boolean isDefintionChanged(final FileDataList previousFdl, - final FileDataList currentFdl) { - boolean rval = true; - if (currentFdl != null) { - rval = !currentFdl.equals(previousFdl); - } else { - rval = previousFdl != null; - } + private String subGridKey(String modelName, GridCoverage coverage) { + return modelName + "&" + coverage.getId(); + } - return rval; + /** + * scan the grib grid definition for changes, when force is false this will + * only scan if we have not scanne din the last 60 seconds. + * + * @param force + * @return + */ + private synchronized void scanFiles() { + if (fileScanTime + 60000 > System.currentTimeMillis()) { + return; + } + FileDataList currentFDL = generateFileDataList(); + fileScanTime = System.currentTimeMillis(); + if (!currentFDL.equals(this.fileDataList)) { + initializeGrids(currentFDL); + return; + } else { + return; + } + } + + private void initializeGrids(FileDataList fdl) { + logger.info("Initializing grib grid coverages"); + long startTime = System.currentTimeMillis(); + ClusterTask ct = null; + Map> gridNameMap = new HashMap>(); + Map spatialNameMap = new HashMap(); + Map subGridDefMap = new HashMap(); + do { + ct = ClusterLockUtils.lock("grib", "spatialCache", 120000, true); + } while (!LockState.SUCCESSFUL.equals(ct.getLockState())); + + try { + for (FileData fd : fdl.getCoverageFileList()) { + try { + GridCoverage grid = (GridCoverage) SerializationUtil + .jaxbUnmarshalFromXmlFile(fd.getFilePath()); + String name = grid.getName(); + grid = insert(grid); + spatialNameMap.put(name, grid); + Set names = gridNameMap.get(grid.getId()); + if (names == null) { + names = new HashSet(); + gridNameMap.put(grid.getId(), names); + } + names.add(name); + } catch (Exception e) { + // Log error but do not throw exception + logger.error( + "Unable to read default grids file: " + + fd.getFilePath(), e); + } + } + Coordinate defaultCenterPoint = null; + + try { + defaultCenterPoint = getDefaultSubGridCenterPoint(); + } catch (Exception e) { + logger.error( + "Failed to generate sub grid definitions. Unable to lookup WFO Center Point", + e); + } + for (FileData fd : fdl.getSubGridFileList()) { + try { + SubGridDef subGridDef = loadSubGridDef(fd.getFilePath(), + defaultCenterPoint); + if (subGridDef == null) { + continue; + } + for (String modelName : subGridDef.getModelNames()) { + subGridDefMap.put(modelName, subGridDef); + } + } catch (Exception e) { + // Log error but do not throw exception + logger.error( + "Unable to read default grids file: " + + fd.getFilePath(), e); + } + } + this.gridNameMap = gridNameMap; + this.spatialNameMap = spatialNameMap; + this.subGridDefMap = subGridDefMap; + this.subGridCoverageMap.clear(); + this.definedSubGridMap.clear(); + this.fileDataList = fdl; + } finally { + ClusterLockUtils.unlock(ct, false); + } + long endTime = System.currentTimeMillis(); + logger.info("Grib grid coverages initialized: " + (endTime - startTime) + + "ms"); + } + + private GridCoverage insert(GridCoverage coverage) + throws GridCoverageException { + coverage.initialize(); + GridCoverageLookup gcl = GridCoverageLookup.getInstance(); + GridCoverage dbCoverage = gcl.getCoverage(coverage, true); + return dbCoverage; } private FileDataList generateFileDataList() { @@ -672,92 +543,6 @@ public class GribSpatialCache { return fileList; } - private FileDataList getPreviousFileDataList() { - IPathManager pm = PathManagerFactory.getPathManager(); - File previousFileData = pm.getFile(pm.getContext( - LocalizationType.EDEX_STATIC, LocalizationLevel.CONFIGURED), - "/grib/gridDefFileListing.xml"); - FileDataList rval = null; - - if (previousFileData.exists() && (previousFileData.length() > 0)) { - try { - Object obj = SerializationUtil - .jaxbUnmarshalFromXmlFile(previousFileData); - if (obj instanceof FileDataList) { - rval = (FileDataList) obj; - } else { - logger.error("Error occurred deserializing " - + previousFileData.getAbsolutePath() - + ", expected type " + FileDataList.class - + " received " + obj.getClass()); - } - } catch (Exception e) { - logger.error( - "Error occurred deserializing " - + previousFileData.getAbsolutePath(), e); - } - } - return rval; - } - - private Map loadGridDefinitionsFromDisk( - final FileDataList currentFdl) { - List coverageFiles = currentFdl.getCoverageFileList(); - Map fileCoverageMap = new HashMap( - (int) (coverageFiles.size() * 1.25) + 1); - - /* - * Iterate over file list. Unmarshal to GridCoverage object - */ - for (FileData fd : coverageFiles) { - try { - GridCoverage grid = (GridCoverage) SerializationUtil - .jaxbUnmarshalFromXmlFile(fd.getFilePath()); - GridCoverage previousGrid = fileCoverageMap.put(grid.getName(), - grid); - if (previousGrid != null) { - for (FileData fd2 : coverageFiles) { - GridCoverage grid2 = (GridCoverage) SerializationUtil - .jaxbUnmarshalFromXmlFile(fd2.getFilePath()); - if (grid.getName().equals(grid2.getName())) { - logger.error("Grid " + grid.getName() - + " has already been defined. " - + fd.getFilePath() + " and " - + fd2.getFilePath() - + " have same name. Using " - + fd2.getFilePath()); - break; - } - } - } - } catch (Exception e) { - // Log error but do not throw exception - logger.error( - "Unable to read default grids file: " - + fd.getFilePath(), e); - } - } - - return fileCoverageMap; - } - - private void saveFileDataList(final FileDataList fdl) { - try { - IPathManager pm = PathManagerFactory.getPathManager(); - LocalizationFile lf = pm.getLocalizationFile( - pm.getContext(LocalizationType.EDEX_STATIC, - LocalizationLevel.CONFIGURED), - "/grib/gridDefFileListing.xml"); - SerializationUtil.jaxbMarshalToXmlFile(fdl, lf.getFile() - .getAbsolutePath()); - lf.save(); - } catch (Exception e) { - logger.error( - "Failed to save coverage file data list, coverages may be reloaded on next restart", - e); - } - } - public static void reinitialize() { GribSpatialCache newInstance = new GribSpatialCache(); instance = newInstance; @@ -806,4 +591,27 @@ public class GribSpatialCache { return defaultCenterPoint; } + + public static Corner determineFirstGridPointCorner(int scanMode) { + if ((scanMode & 128) > 0) { + // -i + if ((scanMode & 64) > 0) { + // +j + return Corner.LowerRight; + } else { + // -j + return Corner.UpperRight; + } + } else { + // +i + if ((scanMode & 64) > 0) { + // +j + return Corner.LowerLeft; + } else { + // -j + return Corner.UpperLeft; + } + } + } + } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/subgrid/SubGridDef.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/SubGridDef.java similarity index 69% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/subgrid/SubGridDef.java rename to edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/SubGridDef.java index 989fd6bf9e..cc19677b94 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/subgrid/SubGridDef.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/spatial/SubGridDef.java @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.subgrid; +package com.raytheon.edex.plugin.grib.spatial; import java.util.List; @@ -39,7 +39,7 @@ import com.raytheon.uf.common.serialization.ISerializableObject; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Jun 25, 2010 rjpeter Initial creation - * Jul 25, 2012 977 rjpeter Add optional centerLatitude/centerLongitude + * *
* * @author rjpeter @@ -53,14 +53,18 @@ public class SubGridDef implements ISerializableObject { @XmlList private List modelNames; - @XmlElement(required = true) + @XmlElement private String referenceModel; + @XmlElement + private String referenceGrid; + @XmlElement(required = true) private double nx; @XmlElement(required = true) private double ny; + // annotation on setter to enforce data constraints private Double centerLatitude; @@ -68,63 +72,19 @@ public class SubGridDef implements ISerializableObject { // annotation on setter to enforce data constraints private Double centerLongitude; - /** the lower left latitude */ - private double lowerLeftLat; - - /** the lower left longitude */ - private double lowerLeftLon; - - /** the upper right latitude */ - private double upperRightLat; - - /** the upper right longitude */ - private double upperRightLon; - public List getModelNames() { return modelNames; } - public void setModelNames(final List modelNames) { + public void setModelNames(List modelNames) { this.modelNames = modelNames; } - public double getLowerLeftLat() { - return lowerLeftLat; - } - - public void setLowerLeftLat(final double lowerLeftLat) { - this.lowerLeftLat = lowerLeftLat; - } - - public double getLowerLeftLon() { - return lowerLeftLon; - } - - public void setLowerLeftLon(final double lowerLeftLon) { - this.lowerLeftLon = lowerLeftLon; - } - - public double getUpperRightLat() { - return upperRightLat; - } - - public void setUpperRightLat(final double upperRightLat) { - this.upperRightLat = upperRightLat; - } - - public double getUpperRightLon() { - return upperRightLon; - } - - public void setUpperRightLon(final double upperRightLon) { - this.upperRightLon = upperRightLon; - } - public double getNx() { return nx; } - public void setNx(final double nx) { + public void setNx(double nx) { this.nx = nx; } @@ -132,18 +92,38 @@ public class SubGridDef implements ISerializableObject { return ny; } - public void setNy(final double ny) { + public void setNy(double ny) { this.ny = ny; } + /** + * a model may have more than one grid so use reference grid instead. + * + * @return + */ + @Deprecated public String getReferenceModel() { return referenceModel; } - public void setReferenceModel(final String referenceModel) { + /** + * a model may have more than one grid so use reference grid instead. + * + * @param referenceModel + */ + @Deprecated + public void setReferenceModel(String referenceModel) { this.referenceModel = referenceModel; } + public String getReferenceGrid() { + return referenceGrid; + } + + public void setReferenceGrid(String referenceGrid) { + this.referenceGrid = referenceGrid; + } + public Double getCenterLatitude() { return centerLatitude; } @@ -169,4 +149,5 @@ public class SubGridDef implements ISerializableObject { MapUtil.correctLon(centerLongitude.doubleValue())); } } -} + +} \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticDataGenerator.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticDataGenerator.java index 59abae4d6a..29c5924c31 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticDataGenerator.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticDataGenerator.java @@ -25,38 +25,48 @@ import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; +import java.util.Iterator; +import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; +import javax.measure.unit.SI; + import org.apache.camel.Exchange; import org.apache.camel.Processor; -import com.raytheon.edex.plugin.grib.dao.GribDao; -import com.raytheon.edex.plugin.grib.util.GribModelCache; +import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; +import com.raytheon.edex.plugin.grib.util.GribModelLookup; import com.raytheon.edex.plugin.grib.util.GribParamInfoLookup; +import com.raytheon.edex.plugin.grib.util.GridModel; import com.raytheon.edex.plugin.grib.util.ParameterInfo; import com.raytheon.uf.common.dataplugin.PluginDataObject; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.util.StaticGridData; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataplugin.grid.util.StaticGridData; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.datastorage.IDataStore; import com.raytheon.uf.common.datastorage.IDataStore.StoreOp; import com.raytheon.uf.common.datastorage.StorageException; import com.raytheon.uf.common.datastorage.StorageStatus; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.edex.core.EdexException; +import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.cluster.ClusterLockUtils; import com.raytheon.uf.edex.database.cluster.ClusterLockUtils.LockState; import com.raytheon.uf.edex.database.cluster.ClusterTask; import com.raytheon.uf.edex.decodertools.time.TimeTools; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; +import com.raytheon.uf.edex.plugin.grid.topo.StaticTopoData; /** * Populates the data store with static data which includes topo,spacing, and @@ -105,14 +115,62 @@ public class StaticDataGenerator implements Processor { } private StaticDataGenerator() { - // Force initialization of static topo data - StaticTopoData.getInstance(); + checkModelTopo(); + } + + /** + * Private method used by the initialization code to see if the static topo + * data for a coverage has been initialized + */ + private void checkModelTopo() { + Map models = GribModelLookup.getInstance() + .getModelByNameMap(); + + List modelsToProcess = new LinkedList(models.keySet()); + int size = modelsToProcess.size(); + while (size > 0) { + Iterator iter = modelsToProcess.iterator(); + while (iter.hasNext()) { + String name = iter.next(); + boolean processed = false; + if (GribParamInfoLookup.getInstance().getParameterInfo(name, + "staticTopo") != null) { + processed = true; + for (GridCoverage coverage : GribSpatialCache.getInstance() + .getGridsForModel(name)) { + processed &= StaticTopoData.getInstance() + .checkModelTopo(coverage); + } + } else { + processed = true; + } + + // remove the item from the queue + if (processed) { + iter.remove(); + } + } + + int curSize = modelsToProcess.size(); + if (curSize > 0 && curSize == size) { + // we still have items to process and we didn't process any then + // they are in process by another server and we need to sleep + // and try again + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // ignore + } + } + + size = curSize; + } } @Override public void process(Exchange exchange) throws Exception { Object payload = exchange.getIn().getBody(); - List stopoRecords = null; + List stopoRecords = null; if (payload instanceof PluginDataObject[]) { PluginDataObject[] records = (PluginDataObject[]) payload; @@ -121,10 +179,10 @@ public class StaticDataGenerator implements Processor { exchange.getOut().setFault(true); } - stopoRecords = new ArrayList(records.length); + stopoRecords = new ArrayList(records.length); for (PluginDataObject pdo : records) { try { - List staticRecords = checkForStaticTopo((GribRecord) pdo); + List staticRecords = checkForStaticTopo((GridRecord) pdo); if (staticRecords != null && !staticRecords.isEmpty()) { stopoRecords.addAll(staticRecords); } @@ -136,7 +194,7 @@ public class StaticDataGenerator implements Processor { } else { statusHandler.handle(Priority.ERROR, "StaticTopoGenerator received unhandled message type. Expected: " - + (new GribRecord[0].getClass().toString()) + + (new GridRecord[0].getClass().toString()) + " received: " + payload.getClass()); } @@ -145,37 +203,36 @@ public class StaticDataGenerator implements Processor { exchange.getOut().setFault(true); } else { exchange.getOut().setBody( - stopoRecords.toArray(new GribRecord[stopoRecords.size()])); + stopoRecords.toArray(new GridRecord[stopoRecords.size()])); } } - private List checkForStaticTopo(GribRecord record) + private List checkForStaticTopo(GridRecord record) throws Exception { - GribDao dao = new GribDao(); - GribModel model = record.getModelInfo(); + GridDao dao = new GridDao(); ParameterInfo topoParamInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), STATIC_TOPO); + .getParameterInfo(record.getDatasetId(), STATIC_TOPO); ParameterInfo spacingParamInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), STATIC_SPACING); + .getParameterInfo(record.getDatasetId(), STATIC_SPACING); ParameterInfo coriolisParamInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), STATIC_CORIOLIS); + .getParameterInfo(record.getDatasetId(), STATIC_CORIOLIS); if (topoParamInfo == null && spacingParamInfo == null && coriolisParamInfo == null) { return Collections.emptyList(); } - GribRecord staticTopoGribRecord = null; - GribRecord staticXSpacingRecord = null; - GribRecord staticYSpacingRecord = null; - GribRecord staticCoriolisRecord = null; + GridRecord staticTopoGridRecord = null; + GridRecord staticXSpacingRecord = null; + GridRecord staticYSpacingRecord = null; + GridRecord staticCoriolisRecord = null; ConcurrentMap> stModelCache = staticTopoTimeCache - .get(model.getModelName()); + .get(record.getDatasetId()); if (stModelCache == null) { // should only ever have 1 refTime in it stModelCache = new ConcurrentHashMap>( 4); - staticTopoTimeCache.put(model.getModelName(), stModelCache); + staticTopoTimeCache.put(record.getDatasetId(), stModelCache); } DataTime dataTime = record.getDataTime(); @@ -199,26 +256,27 @@ public class StaticDataGenerator implements Processor { * If it is Geopotential Height at Surface and this model contains * staticTop, then store a staticTopoRecord */ - if ((model.getParameterAbbreviation().equals( - GEOPOTENTIAL_HEIGHT_PARAM) || model - .getParameterAbbreviation().equals(GEOMETRIC_HEIGHT_PARAM)) - && model.getLevelName().equals(SURFACE_LEVEL)) { + if ((record.getParameter().getAbbreviation() + .equals(GEOPOTENTIAL_HEIGHT_PARAM) || record.getParameter() + .getAbbreviation().equals(GEOMETRIC_HEIGHT_PARAM)) + && record.getLevel().getMasterLevel().getName() + .equals(SURFACE_LEVEL)) { if (ct == null) { ct = getStaticTopoClusterLock(record); } float[] rawData = (float[]) record.getMessageData(); FloatDataRecord staticTopoData = new FloatDataRecord( - STATIC_TOPO, "/", rawData, 2, new long[] { - record.getModelInfo().getLocation().getNx(), - record.getModelInfo().getLocation().getNy() }); - staticTopoGribRecord = createTopoRecord(record); + STATIC_TOPO, "/" + record.getLocation().getId(), + rawData, 2, new long[] { record.getLocation().getNx(), + record.getLocation().getNy() }); + staticTopoGridRecord = createTopoRecord(record); staticXSpacingRecord = createXSpacing(record); staticYSpacingRecord = createYSpacing(record); staticCoriolisRecord = createCoriolis(record); IDataStore dataStore = null; - if (staticTopoGribRecord != null) { - dataStore = dao.getDataStore(staticTopoGribRecord); + if (staticTopoGridRecord != null) { + dataStore = dao.getDataStore(staticTopoGridRecord); } else if (staticXSpacingRecord != null) { dataStore = dao.getDataStore(staticXSpacingRecord); } else if (staticYSpacingRecord != null) { @@ -232,25 +290,25 @@ public class StaticDataGenerator implements Processor { StorageStatus status = dataStore.store(StoreOp.REPLACE); StorageException[] se = status.getExceptions(); if (se == null || se.length == 0) { - persistStaticDataToDatabase(dao, staticTopoGribRecord, + persistStaticDataToDatabase(dao, staticTopoGridRecord, staticXSpacingRecord, staticYSpacingRecord, staticCoriolisRecord); stRefTimeCache.put(dataTime.getFcstTime(), ""); } else { statusHandler.handle(Priority.ERROR, "Error persisting staticTopo data to hdf5", se[0]); - staticTopoGribRecord = null; + staticTopoGridRecord = null; } } else if (!stRefTimeCache.containsKey(dataTime.getFcstTime())) { // double check cache in case lock had to wait for running to // finish - staticTopoGribRecord = createTopoRecord(record); + staticTopoGridRecord = createTopoRecord(record); staticXSpacingRecord = createXSpacing(record); staticYSpacingRecord = createYSpacing(record); staticCoriolisRecord = createCoriolis(record); IDataStore dataStore = null; - if (staticTopoGribRecord != null) { - dataStore = dao.getDataStore(staticTopoGribRecord); + if (staticTopoGridRecord != null) { + dataStore = dao.getDataStore(staticTopoGridRecord); } else if (staticXSpacingRecord != null) { dataStore = dao.getDataStore(staticXSpacingRecord); } else if (staticYSpacingRecord != null) { @@ -262,18 +320,20 @@ public class StaticDataGenerator implements Processor { try { // check if its already been stored - dataSets = dataStore.getDatasets("/"); + dataSets = dataStore.getDatasets("/" + + record.getLocation().getId()); } catch (Exception e) { // Ignore } if (dataSets == null || (dataSets != null && !Arrays.asList(dataSets) .contains(STATIC_TOPO))) { - if (staticTopoGribRecord != null) { + if (staticTopoGridRecord != null) { FloatDataRecord staticTopoRecord = StaticTopoData .getInstance().getStopoData( - record.getModelInfo().getModelName()); - staticTopoRecord.setGroup("/"); + record.getLocation()); + staticTopoRecord.setGroup("/" + + record.getLocation().getId()); staticTopoRecord.setName(STATIC_TOPO); dataStore.addDataRecord(staticTopoRecord); } @@ -283,7 +343,7 @@ public class StaticDataGenerator implements Processor { StorageException[] se = status.getExceptions(); if (se == null || se.length == 0) { // store to database - persistStaticDataToDatabase(dao, staticTopoGribRecord, + persistStaticDataToDatabase(dao, staticTopoGridRecord, staticXSpacingRecord, staticYSpacingRecord, staticCoriolisRecord); stRefTimeCache.put(dataTime.getFcstTime(), ""); @@ -292,11 +352,11 @@ public class StaticDataGenerator implements Processor { statusHandler.handle(Priority.ERROR, "Error persisting staticTopo data to hdf5", se[0]); - staticTopoGribRecord = null; + staticTopoGridRecord = null; } } else { // dataset existed verify in database - persistStaticDataToDatabase(dao, staticTopoGribRecord, + persistStaticDataToDatabase(dao, staticTopoGridRecord, staticXSpacingRecord, staticYSpacingRecord, staticCoriolisRecord); stRefTimeCache.put(dataTime.getFcstTime(), ""); @@ -308,9 +368,9 @@ public class StaticDataGenerator implements Processor { .getDetails()); } } - List staticRecords = new ArrayList(); - if (staticTopoGribRecord != null) { - staticRecords.add(staticTopoGribRecord); + List staticRecords = new ArrayList(); + if (staticTopoGridRecord != null) { + staticRecords.add(staticTopoGridRecord); } if (staticXSpacingRecord != null) { staticRecords.add(staticXSpacingRecord); @@ -324,8 +384,8 @@ public class StaticDataGenerator implements Processor { return staticRecords; } - private ClusterTask getStaticTopoClusterLock(GribRecord record) { - String taskDetails = record.getModelInfo().getModelName() + private ClusterTask getStaticTopoClusterLock(GridRecord record) { + String taskDetails = record.getDatasetId() + record.getDataTime().getRefTime(); ClusterTask rval = null; do { @@ -334,17 +394,16 @@ public class StaticDataGenerator implements Processor { return rval; } - private GribRecord createTopoRecord(GribRecord record) throws Exception { - GribRecord staticTopoRecord = null; - GribModel model = record.getModelInfo(); + private GridRecord createTopoRecord(GridRecord record) throws Exception { + GridRecord staticTopoRecord = null; ParameterInfo paramInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), STATIC_TOPO); + .getParameterInfo(record.getDatasetId(), STATIC_TOPO); if (paramInfo == null) { return null; } - staticTopoRecord = new GribRecord(record); + staticTopoRecord = new GridRecord(record); staticTopoRecord.setId(0); staticTopoRecord.setDataURI(null); staticTopoRecord.setDataTime(null); @@ -355,65 +414,59 @@ public class StaticDataGenerator implements Processor { DataTime dataTime = new DataTime(refTime, record.getDataTime() .getFcstTime()); - GribModel staticTopoModelInfo = new GribModel(model); - staticTopoModelInfo.setId(null); - staticTopoModelInfo.setParameterAbbreviation(paramInfo.getShort_name()); - staticTopoModelInfo.setParameterName(paramInfo.getLong_name()); - staticTopoModelInfo.setParameterUnit("m"); - staticTopoModelInfo.setLevel(LevelFactory.getInstance().getLevel( - "Dflt", 0, "m")); + Parameter param = new Parameter(paramInfo.getShort_name(), + paramInfo.getLong_name(), SI.METER); + staticTopoRecord.setParameter(param); + staticTopoRecord.setLevel(LevelFactory.getInstance().getLevel("Dflt", + 0, "m")); staticTopoRecord.setDataTime(dataTime); - staticTopoModelInfo = (GribModelCache.getInstance() - .getModel(staticTopoModelInfo)); - staticTopoRecord.setModelInfo(staticTopoModelInfo); + staticTopoRecord.getInfo().setId(null); staticTopoRecord.setMessageData(null); staticTopoRecord.setOverwriteAllowed(true); staticTopoRecord.constructDataURI(); return staticTopoRecord; } - private void getStaticData(GribRecord staticXRecord, - GribRecord staticYRecord, GribRecord staticCoriolisRecord, + private void getStaticData(GridRecord staticXRecord, + GridRecord staticYRecord, GridRecord staticCoriolisRecord, IDataStore dataStore) throws Exception { if (staticXRecord != null) { FloatDataRecord dxRecord = StaticGridData.getInstance( - staticXRecord.getModelInfo().getLocation()).getDx(); + staticXRecord.getLocation()).getDx(); if (staticYRecord == null) { dxRecord.setName("staticSpacing"); } else { dxRecord.setName("staticXspacing"); } - dxRecord.setGroup("/"); + dxRecord.setGroup("/" + staticXRecord.getLocation().getId()); dataStore.addDataRecord(dxRecord); } if (staticYRecord != null) { FloatDataRecord dyRecord = StaticGridData.getInstance( - staticYRecord.getModelInfo().getLocation()).getDy(); + staticYRecord.getLocation()).getDy(); dyRecord.setName("staticYspacing"); - dyRecord.setGroup("/"); + dyRecord.setGroup("/" + staticXRecord.getLocation().getId()); dataStore.addDataRecord(dyRecord); } if (staticCoriolisRecord != null) { FloatDataRecord coriolisRecord = StaticGridData.getInstance( - staticCoriolisRecord.getModelInfo().getLocation()) - .getCoriolis(); + staticCoriolisRecord.getLocation()).getCoriolis(); coriolisRecord.setName("staticCoriolis"); - coriolisRecord.setGroup("/"); + coriolisRecord.setGroup("/" + staticXRecord.getLocation().getId()); dataStore.addDataRecord(coriolisRecord); } } - private GribRecord createXSpacing(GribRecord record) throws Exception { - GribModel model = record.getModelInfo(); + private GridRecord createXSpacing(GridRecord record) throws Exception { ParameterInfo paramInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), STATIC_SPACING); + .getParameterInfo(record.getDatasetId(), STATIC_SPACING); if (paramInfo == null) { paramInfo = GribParamInfoLookup.getInstance().getParameterInfo( - model.getModelName(), "staticXspacing"); + record.getDatasetId(), "staticXspacing"); if (paramInfo == null) { return null; } else { @@ -425,10 +478,9 @@ public class StaticDataGenerator implements Processor { } - private GribRecord createYSpacing(GribRecord record) throws Exception { - GribModel model = record.getModelInfo(); + private GridRecord createYSpacing(GridRecord record) throws Exception { ParameterInfo paramInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), "staticYspacing"); + .getParameterInfo(record.getDatasetId(), "staticYspacing"); if (paramInfo == null) { return null; } else { @@ -436,19 +488,17 @@ public class StaticDataGenerator implements Processor { } } - private GribRecord createCoriolis(GribRecord record) throws Exception { - GribModel model = record.getModelInfo(); + private GridRecord createCoriolis(GridRecord record) throws Exception { ParameterInfo paramInfo = GribParamInfoLookup.getInstance() - .getParameterInfo(model.getModelName(), "staticCoriolis"); + .getParameterInfo(record.getDatasetId(), "staticCoriolis"); return createStaticRecord(record, "staticCoriolis", paramInfo); } - private GribRecord createStaticRecord(GribRecord record, String name, + private GridRecord createStaticRecord(GridRecord record, String name, ParameterInfo paramInfo) throws Exception { - GribRecord staticRecord = null; - GribModel model = record.getModelInfo(); + GridRecord staticRecord = null; - staticRecord = new GribRecord(record); + staticRecord = new GridRecord(record); staticRecord.setId(0); staticRecord.setDataURI(null); staticRecord.setDataTime(null); @@ -459,18 +509,14 @@ public class StaticDataGenerator implements Processor { DataTime dataTime = new DataTime(refTime, record.getDataTime() .getFcstTime()); - GribModel staticModelInfo = new GribModel(model); - staticModelInfo.setId(null); - staticModelInfo.setParameterAbbreviation(name); - staticModelInfo.setParameterName(paramInfo.getLong_name()); - staticModelInfo.setParameterUnit(paramInfo.getUnits()); - staticModelInfo.setLevel(LevelFactory.getInstance().getLevel("Dflt", 0, + Parameter param = new Parameter(name, paramInfo.getLong_name(), + paramInfo.getUnits()); + staticRecord.setParameter(param); + staticRecord.setLevel(LevelFactory.getInstance().getLevel("Dflt", 0, "m")); - + staticRecord.getInfo().setId(null); staticRecord.setDataTime(dataTime); - staticModelInfo = (GribModelCache.getInstance() - .getModel(staticModelInfo)); - staticRecord.setModelInfo(staticModelInfo); + staticRecord.setMessageData(null); staticRecord.setOverwriteAllowed(true); staticRecord.constructDataURI(); @@ -483,32 +529,40 @@ public class StaticDataGenerator implements Processor { * * @param topo */ - private void persistStaticDataToDatabase(GribDao dao, GribRecord topo, - GribRecord staticXSpacing, GribRecord staticYSpacing, - GribRecord staticCoriolis) throws SerializationException, + private void persistStaticDataToDatabase(GridDao dao, GridRecord topo, + GridRecord staticXSpacing, GridRecord staticYSpacing, + GridRecord staticCoriolis) throws SerializationException, EdexException { - if (topo != null && !dao.isSTopoInDb(topo)) { + if (topo != null && !isSTopoInDb(dao, topo)) { statusHandler.handle(Priority.DEBUG, "Persisting static topo record to the database!!!"); dao.persistToDatabase(topo); } - if (staticXSpacing != null && !dao.isSTopoInDb(staticXSpacing)) { + if (staticXSpacing != null && !isSTopoInDb(dao, staticXSpacing)) { statusHandler.handle(Priority.DEBUG, "Persisting static " - + staticXSpacing.getModelInfo().getParameterAbbreviation() + + staticXSpacing.getParameter().getAbbreviation() + " record to the database!!!"); dao.persistToDatabase(staticXSpacing); } - if (staticYSpacing != null && !dao.isSTopoInDb(staticYSpacing)) { + if (staticYSpacing != null && !isSTopoInDb(dao, staticYSpacing)) { statusHandler.handle(Priority.DEBUG, "Persisting static " - + staticYSpacing.getModelInfo().getParameterAbbreviation() + + staticYSpacing.getParameter().getAbbreviation() + " record to the database!!!"); dao.persistToDatabase(staticYSpacing); } - if (staticCoriolis != null && !dao.isSTopoInDb(staticCoriolis)) { + if (staticCoriolis != null && !isSTopoInDb(dao, staticCoriolis)) { statusHandler.handle(Priority.DEBUG, "Persisting static " - + staticCoriolis.getModelInfo().getParameterAbbreviation() + + staticCoriolis.getParameter().getAbbreviation() + " record to the database!!!"); dao.persistToDatabase(staticCoriolis); } } + + private boolean isSTopoInDb(GridDao dao, GridRecord record) + throws DataAccessLayerException { + List fields = Arrays.asList("dataURI"); + List values = Arrays.asList((Object) record.getDataURI()); + List list = dao.queryByCriteria(fields, values); + return !list.isEmpty(); + } } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/Grib1ParameterLookup.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/Grib1ParameterLookup.java index e142cd5776..b39dc2cebd 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/Grib1ParameterLookup.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/Grib1ParameterLookup.java @@ -27,7 +27,7 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.PathManagerFactory; diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribModelLookup.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribModelLookup.java new file mode 100644 index 0000000000..f127541400 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribModelLookup.java @@ -0,0 +1,306 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.edex.plugin.grib.util; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.bind.JAXB; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.raytheon.edex.plugin.grib.exception.GribException; +import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoSet; +import com.raytheon.uf.common.dataplugin.grid.mapping.DatasetIdMapper; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.util.mapping.MultipleMappingException; + +public class GribModelLookup { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GribModelLookup.class); + + /** The logger */ + protected transient Log logger = LogFactory.getLog(getClass()); + + /** The singleton instance of GribModelLookup **/ + private static GribModelLookup instance; + + /** + * A map of the models. The key is a hash of the center, grid, and process + * id rcg: changed key to a string, too many identical key were generated + * with the hash. + */ + private final Map models; + + /** A map of the models. The key is the title of the model */ + private final Map modelsByName; + + public static synchronized GribModelLookup getInstance() { + if (instance == null) { + instance = new GribModelLookup(); + } + return instance; + } + + private GribModelLookup() { + models = new HashMap(); + modelsByName = new HashMap(); + try { + initModelList(); + } catch (GribException e) { + logger.error("Unable to initialize model list!", e); + } + } + + public GridModel getModel(int center, int subcenter, String grid, + int process) { + GridModel model = models.get(toKey(center, subcenter, grid, process)); + if (model == null) { + // See if there is a version for all grids. + model = models.get(toKey(center, subcenter, null, process)); + } + return model; + } + + public GridModel getModel(int center, int subcenter, GridCoverage grid, + int process) { + GridModel model = null; + if (grid.getName() != null) { + models.get(toKey(center, subcenter, grid.getName(), process)); + } + if (model == null) { + for (String gribGridName : GribSpatialCache.getInstance() + .getGribCoverageNames(grid)) { + model = models.get(toKey(center, subcenter, gribGridName, + process)); + if (model != null) { + break; + } + } + if (model == null) { + // last step is to look for a matching center, subcenter, and + // process with no grid. + model = models.get(toKey(center, subcenter, null, process)); + } + } + return model; + } + + public GridModel getModel(int center, int subcenter, int gridid, int process) { + return getModel(center, subcenter, String.valueOf(gridid), process); + } + + public GridModel getModelByName(String name) { + return modelsByName.get(name); + } + + public Map getModelByNameMap() { + return modelsByName; + } + + public Set getModelNames() { + return modelsByName.keySet(); + } + + public String getModelName(int center, int subcenter, GridCoverage grid, + int process) { + GridModel model = getModel(center, subcenter, grid, process); + if (model == null || model.getName() == null) { + String cenSubProc = "GribModel:" + String.valueOf(center) + ":" + + String.valueOf(subcenter) + ":" + String.valueOf(process); + String cenSubProcLoc = null; + DatasetIdMapper mapper = DatasetIdMapper.getInstance(); + try { + if (grid.getName() != null) { + cenSubProcLoc = cenSubProc + ":" + grid.getName(); + String name = mapper.lookupBaseName(cenSubProcLoc, "grib"); + if (!name.equals(cenSubProcLoc)) { + return name; + } + } + for (String gribGridName : GribSpatialCache.getInstance() + .getGribCoverageNames(grid)) { + cenSubProcLoc = cenSubProc + ":" + gribGridName; + String name = mapper.lookupBaseName(cenSubProcLoc, "grib"); + if (!name.equals(cenSubProcLoc)) { + return name; + } + } + String name = mapper.lookupBaseName(cenSubProc, "grib"); + if (!name.equals(cenSubProcLoc)) { + return name; + } + return cenSubProcLoc; + } catch (MultipleMappingException e) { + statusHandler.handle(Priority.WARN, e.getLocalizedMessage(), e); + + return e.getArbitraryMapping(); + } + } else { + return model.getName(); + } + } + + private void initModelList() throws GribException { + logger.info("Initializing grib models"); + long startTime = System.currentTimeMillis(); + LocalizationContext edexStaticBase = PathManagerFactory + .getPathManager().getContext( + LocalizationContext.LocalizationType.EDEX_STATIC, + LocalizationContext.LocalizationLevel.BASE); + + LocalizationContext edexStaticSite = PathManagerFactory + .getPathManager().getContext( + LocalizationContext.LocalizationType.EDEX_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + LocalizationFile[] modelFiles = PathManagerFactory.getPathManager() + .listFiles( + new LocalizationContext[] { edexStaticSite, + edexStaticBase }, + "grib" + IPathManager.SEPARATOR + "models", // Win32 + new String[] { ".xml" }, false, true); + + GridModelSet modelSet = new GridModelSet(); + + for (LocalizationFile modelFile : modelFiles) { + try { + GridModelSet fileSet = JAXB.unmarshal(modelFile.getFile(), + GridModelSet.class); + modelSet.addModels(fileSet.getModels()); + } catch (Exception e) { + throw new GribException("Unable to unmarshal grib models file:" + + modelFile); + } + } + + modelSet.addModels(initCommonStaticModels()); + + for (GridModel model : modelSet.getModels()) { + modelsByName.put(model.getName(), model); + for (int process : model.getProcess()) { + if (model.getAllGrids().isEmpty()) { + models.put( + toKey(model.getCenter(), + Integer.parseInt(model.getSubCenter()), + null, process), model); + } + for (String grid : model.getAllGrids()) { + models.put( + toKey(model.getCenter(), + Integer.parseInt(model.getSubCenter()), + grid, process), model); + } + } + } + long endTime = System.currentTimeMillis(); + logger.info("Grib models initialized: " + (endTime - startTime) + "ms"); + } + + /** + * GribModels files used to be in common and contained information used on + * viz. This information has been moved to datasetInfo files and now the + * gribModel files should only be used on edex. To ease this transition this + * method will search for any old common files and generate datasetInfo + * files. At some point in the future all files should be converted and this + * method can be removed. + * + * + * @return + * @throws GribException + */ + private List initCommonStaticModels() throws GribException { + List modelSet = new ArrayList(); + LocalizationContext commonStaticSite = PathManagerFactory + .getPathManager().getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + LocalizationFile[] legacyFiles = PathManagerFactory.getPathManager() + .listFiles(new LocalizationContext[] { commonStaticSite }, + "grid" + IPathManager.SEPARATOR + "models", // Win32 + new String[] { ".xml" }, false, true); + + for (LocalizationFile modelFile : legacyFiles) { + try { + GridModelSet fileSet = JAXB.unmarshal(modelFile.getFile(), + GridModelSet.class); + modelSet.addAll(fileSet.getModels()); + ArrayList infoList = new ArrayList( + fileSet.getModels().size()); + for (GridModel model : fileSet.getModels()) { + DatasetInfo info = new DatasetInfo(); + info.setDatasetId(model.getName()); + info.setTitle(model.getTitle()); + info.setDt(model.getDt()); + info.setAlias(model.getAlias()); + infoList.add(info); + } + DatasetInfoSet infoSet = new DatasetInfoSet(); + infoSet.setInfos(infoList); + LocalizationFile file = PathManagerFactory.getPathManager() + .getLocalizationFile( + commonStaticSite, + "/grid/datasetInfo/imported-" + + modelFile.getFile().getName()); + if (!file.exists()) { + JAXB.marshal(infoSet, file.getFile()); + file.save(); + } + } catch (Exception e) { + throw new GribException("Unable to unmarshal grib models file:" + + modelFile); + } + } + return modelSet; + } + + private String toKey(Integer center, Integer subcenter, String grid, + Integer process) { + StringBuilder builder = new StringBuilder(); + builder.append(center); + builder.append(subcenter); + builder.append(grid); + builder.append(process); + return builder.toString(); + // final int PRIME = 31; + // int result = 1; + // result = PRIME * result + ((center == null) ? 0 : center.hashCode()); + // result = PRIME * result + // + ((subcenter == null) ? 0 : subcenter.hashCode()); + // result = PRIME * result + ((grid == null) ? 0 : grid.hashCode()); + // result = PRIME * result + ((process == null) ? 0 : + // process.hashCode()); + // return result; + } +} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribParamInfoLookup.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribParamInfoLookup.java index 28aa36c529..1093f9b9f3 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribParamInfoLookup.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GribParamInfoLookup.java @@ -29,8 +29,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GridModel.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GridModel.java similarity index 73% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GridModel.java rename to edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GridModel.java index bbf8ab2eab..53a8e126ae 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GridModel.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GridModel.java @@ -17,9 +17,10 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.util; +package com.raytheon.edex.plugin.grib.util; import java.util.ArrayList; +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -45,7 +46,11 @@ public class GridModel implements ISerializableObject { /** The NCEP grid associated with this model */ @XmlElement - private Integer grid; + private String grid; + + @XmlElementWrapper(name = "grids") + @XmlElement(name = "id") + private ArrayList grids; @XmlElement private String subcenter; @@ -70,10 +75,18 @@ public class GridModel implements ISerializableObject { @XmlElement private boolean analysisOnly; + /** + * use datasetInfo instead + */ + @Deprecated public String getTitle() { return title; } + /** + * use datasetInfo instead + */ + @Deprecated public void setTitle(String title) { this.title = title; } @@ -86,11 +99,11 @@ public class GridModel implements ISerializableObject { this.name = name; } - public Integer getGrid() { + public String getGrid() { return grid; } - public void setGrid(Integer grid) { + public void setGrid(String grid) { this.grid = grid; } @@ -118,18 +131,34 @@ public class GridModel implements ISerializableObject { this.subcenter = subcenter; } + /** + * use datasetInfo instead + */ + @Deprecated public void setAlias(String alias) { this.alias = alias; } + /** + * use datasetInfo instead + */ + @Deprecated public String getAlias() { return alias; } + /** + * use datasetInfo instead + */ + @Deprecated public Integer getDt() { return dt; } + /** + * use datasetInfo instead + */ + @Deprecated public void setDt(Integer dt) { this.dt = dt; } @@ -152,4 +181,29 @@ public class GridModel implements ISerializableObject { public boolean getAnalysisOnly() { return analysisOnly; } + + public ArrayList getGrids() { + return grids; + } + + public void setGrids(ArrayList grids) { + this.grids = grids; + } + + /** + * Returns a list containing both the grid element if present and the grids + * element if present + * + * @return + */ + public List getAllGrids() { + List grids = new ArrayList(); + if (this.grids != null) { + grids.addAll(this.grids); + } + if (this.grid != null) { + grids.add(this.grid); + } + return grids; + } } \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GridModelSet.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GridModelSet.java similarity index 97% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GridModelSet.java rename to edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GridModelSet.java index cb31519475..21d98677c6 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GridModelSet.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/util/GridModelSet.java @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.util; +package com.raytheon.edex.plugin.grib.util; import java.util.ArrayList; import java.util.Collection; diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribParamTranslator.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribParamTranslator.java index 341f72a36e..640f053afc 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribParamTranslator.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribParamTranslator.java @@ -27,15 +27,14 @@ import java.io.IOException; import java.util.HashMap; import java.util.Map; -import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.edex.plugin.grib.util.DataFieldTableLookup; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.LocalizationFile; import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.parameter.Parameter; import com.raytheon.uf.common.time.DataTime; /** @@ -103,21 +102,20 @@ public class GribParamTranslator { } } - public String getParameterNameAlias(GribModel model) { - Map modelMap = parameterNameMap.get(model - .getModelName()); + public void getParameterNameAlias(String modelName, Parameter parameter) { + Map modelMap = parameterNameMap.get(modelName); if (modelMap != null) { - String newName = modelMap.get(model.getParameterAbbreviation()); + String newName = modelMap.get(parameter.getAbbreviation()); if (newName != null) { - return newName; + parameter.setName(newName); + return; } } String newName = DataFieldTableLookup.getInstance().lookupName( - model.getParameterAbbreviation()); + parameter.getAbbreviation()); if (newName != null) { - return newName; + parameter.setName(newName); } - return model.getParameterName(); } /** @@ -126,19 +124,28 @@ public class GribParamTranslator { * @param gribVersion * The version of the grib. Necessary so the correct table is * used for translations - * @param model - * The grib model object from the record + * @param parName + * the original parameter abbreviation from the grib file + * @param center + * the center from the grib data + * @param subcenter + * the subcenter from the grib data + * @param genProcess + * the genProcess of the grib data. * @param dataTime - * The datatime of the grib data + * The datatime of the grib data the geospatial location of the + * grib data, if this model is being subgridded then this expects + * the full coverage, not the subgridded coverage. * @return The translated grib parameter */ - public String translateParameter(int gribVersion, GribModel model, - DataTime dataTime) { + public String translateParameter(int gribVersion, String parName, + int center, int subcenter, int genProcess, DataTime dataTime, + GridCoverage location) { - String parName = model.getParameterAbbreviation(); - String pcs = parName + "_" + getGenProcess(model); - String centerName = getCenterName(model); - String subcenterName = getSubcenterName(model); + String pcs = parName + "_" + + getGenProcess(center, subcenter, genProcess); + String centerName = getCenterName(center, subcenter); + String subcenterName = getSubcenterName(center, subcenter); if (centerName != null && !centerName.equals("NONE")) { pcs += "-" + centerName; } @@ -147,15 +154,7 @@ public class GribParamTranslator { pcs += "-" + subcenterName; } - String dimstr = ""; - GridCoverage location = model.getLocation(); - if (location.isSubGridded()) { - GridCoverage fullCoverage = GribSpatialCache.getInstance() - .getGridByName(location.getParentGridName()); - dimstr = "_" + fullCoverage.getNx() + "x" + fullCoverage.getNy(); - } else { - dimstr = "_" + location.getNx() + "x" + location.getNy(); - } + String dimstr = "_" + location.getNx() + "x" + location.getNy(); long duration = dataTime.getValidPeriod().getDuration() / 1000; @@ -205,49 +204,42 @@ public class GribParamTranslator { /** * Gets the name of the center for the parameter contained in the provided - * grib model object + * center and subcenter * - * @param model - * The grib model object + * @param center + * @param subcenter * @return The center name */ - private String getCenterName(GribModel model) { - int center = model.getCenterid(); - int subcenter = model.getSubcenterid(); + private String getCenterName(int center, int subcenter) { return (String) GribTableLookup.getInstance().getTableValue(center, subcenter, "0", center); } /** * Gets the name of the sub-center for the parameter contained in the - * provided grib model object + * provided center and subcenter * - * @param model - * The grib model object + * @param center + * @param subcenter * @return The sub-center name */ - private String getSubcenterName(GribModel model) { - int center = model.getCenterid(); - int subcenter = model.getSubcenterid(); - + private String getSubcenterName(int center, int subcenter) { return (String) GribTableLookup.getInstance().getTableValue(center, subcenter, "C-center" + center, subcenter); } /** * Gets the name of the generating process contained in the provided grib - * model object + * center and subcenter * - * @param model - * The grib model object + * @param center + * @param subcenter * @return The generating process name */ - private String getGenProcess(GribModel model) { - int center = model.getCenterid(); - int subcenter = model.getSubcenterid(); + private String getGenProcess(int center, int subcenter, int genProcess) { return (String) GribTableLookup.getInstance().getTableValue(center, - subcenter, "A-center" + center, model.getGenprocess()); + subcenter, "A-center" + center, genProcess); } /** diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribTableLookup.java b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribTableLookup.java index 4a6884ccd3..fb4cf4b765 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribTableLookup.java +++ b/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/util/grib/GribTableLookup.java @@ -32,18 +32,18 @@ import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import com.raytheon.edex.plugin.grib.exception.GribException; import com.raytheon.edex.plugin.grib.util.GenProcess; import com.raytheon.edex.plugin.grib.util.Grib1Parameter; import com.raytheon.edex.plugin.grib.util.Grib1ParameterLookup; import com.raytheon.edex.plugin.grib.util.GribLevel; import com.raytheon.edex.plugin.grib.util.GribParameter; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; import com.raytheon.uf.common.dataplugin.level.LevelFactory; import com.raytheon.uf.common.dataplugin.level.MasterLevel; import com.raytheon.uf.common.localization.IPathManager; -import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; +import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.util.FileUtil; /** @@ -325,9 +325,9 @@ public class GribTableLookup { GribParameter param = null; int number = Integer.parseInt(tokens[0]); - param = new GribParameter(center, subcenter, Integer - .parseInt(tableTokens[2]), Integer - .parseInt(tableTokens[3]), number, name, + param = new GribParameter(center, subcenter, + Integer.parseInt(tableTokens[2]), + Integer.parseInt(tableTokens[3]), number, name, abbreviation, unit, d2dAbbrev); table.addEntry(Integer.valueOf(tokens[0]), param); diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/GribModels_FNMO-58.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/dataset/alias/grib.xml similarity index 60% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/GribModels_FNMO-58.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/dataset/alias/grib.xml index 08cd7cd38d..7bad99d4ee 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/GribModels_FNMO-58.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/dataset/alias/grib.xml @@ -1,4 +1,4 @@ - + - - - - - - - - NOGAPS - NOGAPS -
58
- 20 - 218 - - 120 - - nogaps -
1
-
- - - AK-NOGAPS - AK-NOGAPS -
58
- 20 - 242 - - 120 - - nogaps -
1
-
- - - - -
\ No newline at end of file + + GribModel:7:0:96:212 + GribModel:7:0:81:212 + GribModel:7:0:77:212 + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_ECMWF-98.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_ECMWF-98.xml new file mode 100644 index 0000000000..2433405053 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_ECMWF-98.xml @@ -0,0 +1,78 @@ + + + + ECMWF-HiRes + ECMWF-HiRes +
12
+
+ + ECMWF-LowRes + ECMF-NorthernHemisphere +
24
+
+ + ECMWF-LowRes + ECMF1 +
24
+
+ + ECMWF-LowRes + ECMF2 +
24
+
+ + ECMWF-LowRes + ECMF3 +
24
+
+ + ECMWF-LowRes + ECMF4 +
24
+
+ + ECMWF-LowRes + ECMF5 +
24
+
+ + ECMWF-LowRes + ECMF6 +
24
+
+ + ECMWF-LowRes + ECMF7 +
24
+
+ + ECMWF-LowRes + ECMF8 +
24
+
+ + ECMWF-LowRes + ECMF9 +
24
+
+ + ECMWF-LowRes + ECMF10 +
24
+
+ + ECMWF-LowRes + ECMF11 +
24
+
+ + ECMWF-LowRes + ECMF12 +
24
+
+ + ECMWF-MODEL0 + ECMF-MODEL0 +
24
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_FNMO-58.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_FNMO-58.xml new file mode 100644 index 0000000000..e51f74121b --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_FNMO-58.xml @@ -0,0 +1,13 @@ + + + + NOGAPS + NOGAPS +
1
+
+ + AK-NOGAPS + AK-NOGAPS +
1
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_FSL-59.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_FSL-59.xml new file mode 100644 index 0000000000..c10736ced4 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_FSL-59.xml @@ -0,0 +1,8 @@ + + + + LAPS + LAPS +
1
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NCEP-7.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NCEP-7.xml new file mode 100644 index 0000000000..516afb5ee1 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NCEP-7.xml @@ -0,0 +1,904 @@ + + + + GFSLAMP-Stn + GFSLAMP +
1
+
+ + NAM80 + ETA +
6
+
+ + GFS180 + AVN +
6
+
+ + NGM80 + NGM +
6
+
+ + gfsLR + MRF +
12
+
+ + gfsLR21 + MRF21 +
12
+
+ + gfsLR22 + MRF22 +
12
+
+ + gfsLR23 + MRF23 +
12
+
+ + gfsLR24 + MRF24 +
12
+
+ + gfsLR25 + MRF25 +
12
+
+ + gfsLR26 + MRF26 +
12
+
+ + GFS360 + GFS201 +
6
+
+ + gfsLR + mrfNH +
12
+
+ + GFS90 + GFS213 +
6
+
+ + NGM90 + NGM213 +
6
+
+ + NGM180 + NGM202 +
6
+
+ + GFS80 + AVN211 +
6
+
+ + NAM40 + mesoEta212 +
3
+
+ + NAM20 + mesoEta215 + mesoEta212 +
3
+
+ + WAFS + WAFS +
6
+
+ + NAMWX + ETA212 +
3
+
+ + GFS190 + AVN203 +
12
+
+ + gfs190 + MRF203 +
12
+
+ + GFS150 + MRF204 +
12
+
+ + GFS150 + MRF205 +
12
+
+ + NGM95 + NGM207 +
6
+
+ + NAM95 + ETA207 +
6
+
+ + GFSGbl + AVN-NorthernHemisphere +
6
+
+ + GFSGbl + AVN37 +
6
+
+ + GFSGbl + AVN38 +
6
+
+ + GFSGbl + AVN39 +
6
+
+ + GFSGbl + AVN40 +
6
+
+ + GFSGbl + AVN41 +
6
+
+ + GFSGbl + AVN42 +
6
+
+ + GFSGbl + AVN43 +
6
+
+ + GFSGbl + AVN44 +
6
+
+ + GWW + GWW233 +
6
+
+ + GWW21 + GWW21 +
6
+
+ + GWW22 + GWW22 +
6
+
+ + GWW23 + GWW23 +
6
+
+ + GWW24 + GWW24 +
6
+
+ + SeaIce + SeaIce +
1
+
+ + SeaIce220 + SeaIce220 +
1
+
+ + SeaIce173 + SeaIce173 +
1
+
+ + SeaIce235 + SeaIce235 +
1
+
+ + RAP40 + RUC236 +
1
+
+ + GFS75 + AVN225 +
6
+
+ + AKWAVE + AKWAVE239 +
6
+
+ + WNAwave + WNAWAVE238 +
6
+
+ + AK-NAM40 + mesoEta216 +
6
+
+ + AK-NAM20 + mesoEta217 +
6
+
+ + NAM12 + ETA218 +
3
+
+ + AK-NAM12 + ETA242 +
3
+
+ + NAM over the contiguous US 16X Resolution(5Km) Lambert Conformal + NAM227 +
3
+
+ + ENPwave + ENPWAVE253 +
6
+
+ + HurWave238 + HurWave238 +
6
+
+ + HurWave253 + HurWave253 +
6
+
+ + TPC-HurWind + HurWind226 +
6
+
+ + GuamHurWind + HurWind175 +
6
+
+ + HawHurWind + HurWind250 +
6
+
+ + NICICE + NICICE +
1
+
+ + AK-NICICE + AK-NICICE +
1
+
+ + DGEX + DGEX185 +
6
+
+ + DGEX + DGEX186 +
6
+
+ + GFS40 + GFS212 +
6
+
+ + AK-GFS + GFS160 +
6
+
+ + PR-GFS + GFS254 +
6
+
+ + SJU-GFS + GFS161 +
6
+
+ + Guam-GFS + GFS199 +
6
+
+ + RAP13 + RUC130 +
1
+
+ + RTMA + RTMA +
1
+
+ + RTMA-Mosaic + RTMA-Mosaic +
1
+
+ + AK-RTMA + AK-RTMA +
1
+
+ + NamDNG5 + NamDNG5 +
3
+
+ + RaobOA + RaobOA +
12
+
+ + MetarOA + MetarOA +
1
+
+ + GlobalWave + GlobalWave +
3
+
+ + AKwave10 + AKwave10 +
3
+
+ + AKwave4 + AKwave4 +
3
+
+ + EPwave10 + EPwave10 +
3
+
+ + WCwave10 + WCwave10 +
3
+
+ + WCwave4 + WCwave4 +
3
+
+ + WNAwave10 + WNAwave10 +
3
+
+ + WNAwave4 + WNAwave4 +
3
+
+ + Aviation + Aviation +
1
+
+ + Aviation + Aviation +
1
+
+ + Aviation + Aviation +
1
+
+ + AK-NamDNG5 + AK-NamDNG5 +
3
+
+ + HI-NamDNG5 + HI-NamDNG5 +
3
+
+ + PR-NamDNG5 + PR-NamDNG5 +
3
+
+ + HiResW-ARW-East + HiResW-ARW-East +
3
+
+ + HiResW-ARW-West + HiResW-ARW-West +
3
+
+ + HiResW-ARW-AK + HiResW-ARW-AK +
3
+
+ + HiResW-ARW-SJU + HiResW-ARW-SJU +
3
+
+ + HiResW-ARW-HI + HiResW-ARW-HI +
3
+
+ + HiResW-ARW-GU + HiResW-ARW-GU +
3
+
+ + HiResW-NMM-East + HiResW-NMM-East +
3
+
+ + HiResW-NMM-West + HiResW-NMM-West +
3
+
+ + HiResW-NMM-AK + HiResW-NMM-AK +
3
+
+ + HiResW-NMM-SJU + HiResW-NMM-SJU +
3
+
+ + HiResW-NMM-HI + HiResW-NMM-HI +
3
+
+ + HiResW-NMM-GU + HiResW-NMM-GU +
3
+
+ + GRLKwave + GRLKwave +
1
+
+ + MSAS + MSAS +
1
+
+ + GFSBufr + GfsBufr +
1
+
+ + GFSSouthernHemisphere + GFSSouthernHemisphere +
1
+
+ + GoesBufr + GoesBufr +
1
+
+ + Metar + Metar +
1
+
+ + Ldad + Ldad +
1
+
+ + DMD + DMD +
-10
+
+ + MDCRS + MDCRS +
1
+
+ + NAM Bufr + EtaBufr +
1
+
+ + PoesBufr + PoesBufr +
1
+
+ + Profiler + Profiler +
1
+
+ + Raob + Raob +
12
+
+ + VWP + VWP +
-6
+
+ + PR-NAM12 + mesoEta237 +
3
+
+ + GFSensemble + ENSEMBLE +
6
+
+ + GFSensemble + ENSEMBLE37 +
6
+
+ + GFSensemble + ENSEMBLE38 +
6
+
+ + GFSensemble + ENSEMBLE39 +
6
+
+ + GFSensemble + ENSEMBLE40 +
6
+
+ + GFSensemble + ENSEMBLE41 +
6
+
+ + GFSensemble + ENSEMBLE42 +
6
+
+ + GFSensemble + ENSEMBLE43 +
6
+
+ + GFSensemble + ENSEMBLE44 +
6
+
+ + SREF + SREF212 +
3
+
+ + AK-SREF + SREF216 +
3
+
+ + PR-SREF + SREF243 +
3
+
+ + RTG-SST-Analysis + RTGSST +
1
+
+ + GFSGuide + GFSGuide +
6
+
+ + RTMA + RTMA +
1
+
+ + RTMA-Mosaic + RTMA-Mosaic +
1
+
+ + AK-RTMA + AK-RTMA +
1
+
+ + HI-RTMA + HI-RTMA +
1
+
+ + PR-RTMA + PR-RTMA +
1
+
+ + Guam-RTMA + Guam-RTMA +
1
+
+ + RTG-SST-HR-Analysis + RTGSSTHR +
1
+
+ + QPE + QPE +
1
+
+ + SeaSfcAnalysis21 + SeaSfcAnalysis21 +
1
+
+ + SeaSfcAnalysis22 + SeaSfcAnalysis22 +
1
+
+ + SeaSfcAnalysis23 + SeaSfcAnalysis23 +
1
+
+ + SeaSfcAnalysis24 + SeaSfcAnalysis24 +
1
+
+ + SeaSfcAnalysis37 + SeaSfcAnalysis37 +
1
+
+ + SeaSfcAnalysis38 + SeaSfcAnalysis38 +
1
+
+ + SeaSfcAnalysis39 + SeaSfcAnalysis39 +
1
+
+ + SeaSfcAnalysis40 + SeaSfcAnalysis40 +
1
+
+ + SeaSfcAnalysis41 + SeaSfcAnalysis41 +
1
+
+ + SeaSfcAnalysis42 + SeaSfcAnalysis42 +
1
+
+ + SeaSfcAnalysis43 + SeaSfcAnalysis43 +
1
+
+ + SeaSfcAnalysis44 + SeaSfcAnalysis44 +
1
+
+ + SeaSfcAnalysis61 + SeaSfcAnalysis61 +
1
+
+ + SeaSfcAnalysis62 + SeaSfcAnalysis62 +
1
+
+ + SeaSfcAnalysis63 + SeaSfcAnalysis63 +
1
+
+ + SeaSfcAnalysis64 + SeaSfcAnalysis64 +
1
+
+ + RFCqpf + RFCqpf +
6
+
+ + HPCqpf + HPCqpf +
6
+
+ + HPCGuide + HPCGuide +
6
+
+ + HPCGuide-AK + HPCGuide-AK +
6
+
+ + HPC + HPCqpfNDFD +
6
+
+ + HPC-MODEL0 + HPC-MODEL0 +
6
+
+ + OPCWave-W-ATL + OPCWave180 +
24
+
+ + OPCWave-NE-PAC + OPCWave181 +
24
+
+ + CPCoutlook-Short + CPCoutlook-Short +
24
+
+ + CPCoutlook-Medium + CPCoutlook-Medium +
24
+
+ + CPCoutlook-Short-AK + CPCoutlook-Short-AK +
3
+
+ + CPCoutlook-Medium-AK + CPCoutlook-Medium-AK +
3
+
+ + CPCoutlook-Long + CPCoutlook211 +
720
+
+ + Aviation + Aviation +
1
+
+ + NCWF + NCWF +
1
+
+ + SPCGuide + SPCGuide +
1
+
+ + TPCWindProb + TPCWindProb +
6
+
+ + OPCWave-TE-PAC + OPCWave182 +
24
+
+ + GriddedMOS + MOSGuide +
6
+
+ + AK-GriddedMOS + MOSGuide-AK +
3
+
+ + GFSLAMP-Grid + GFSLAMPTstorm +
1
+
+ + TPCSurgeProb + TPCSurgeProb +
6
+
+ + TPCSurgeProb197 + TPCSurgeProb197 +
6
+
+ + TPCSurgeProb-AK + TPCSurgeProb-AK +
6
+
+ + PROB3HR + PROB3HR +
3
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NOAA-161.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NOAA-161.xml new file mode 100644 index 0000000000..78cfe82a5a --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NOAA-161.xml @@ -0,0 +1,8 @@ + + + + GLERL + GLERL +
12
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NWSTG-8.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NWSTG-8.xml new file mode 100644 index 0000000000..327a8b5f94 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_NWSTG-8.xml @@ -0,0 +1,8 @@ + + + + RCM + RCM +
1
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_RFC-9.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_RFC-9.xml new file mode 100644 index 0000000000..9f7bf13420 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_RFC-9.xml @@ -0,0 +1,668 @@ + + + + MPE + MPE-Local +
1
+
+ + MPE + MPE-Mosaic +
1
+
+ + HPE + HPE +
300
+
+ + BiasHPE + BHPE +
300
+
+ + QPE-SJU + QPE-SJU +
1
+
+ + QPE-Manual-SJU + QPE-Manual-SJU +
1
+
+ + QPE-Auto-SJU + QPE-Auto-SJU +
1
+
+ + MPE-Local-SJU + MPE-Local-SJU +
1
+
+ + MPE-Mosaic-SJU + MPE-Mosaic-SJU +
1
+
+ + QPE-XNAV-SJU + QPE-XNAV-SJU +
1
+
+ + QPE-RFC-SJU + QPE-RFC-SJU +
1
+
+ + QPF-TUA + RFCqpf +
6
+
+ + FFG-TUA + FFG-TUA +
1
+
+ + QPE-TUA + QPE-TUA +
1
+
+ + QPE-Manual-TUA + QPE-Manual-TUA +
1
+
+ + QPE-Auto-TUA + QPE-Auto-TUA +
1
+
+ + MPE-Local-TUA + MPE-Local-TUA +
1
+
+ + MPE-Mosaic-TUA + MPE-Mosaic-TUA +
1
+
+ + QPE-XNAV-TUA + QPE-XNAV-TUA +
1
+
+ + QPE-RFC-TUA + QPE-RFC-TUA +
1
+
+ + QPF-ACR + RFCqpf +
6
+
+ + FFG-ACR + FFG-ACR +
1
+
+ + QPE-ACR + QPE-ACR +
1
+
+ + QPE-Manual-ACR + QPE-Manual-ACR +
1
+
+ + QPE-Auto-ACR + QPE-Auto-ACR +
1
+
+ + MPE-Local-ACR + MPE-Local-ACR +
1
+
+ + MPE-Mosaic-ACR + MPE-Mosaic-ACR +
1
+
+ + QPE-XNAV-ACR + QPE-XNAV-ACR +
1
+
+ + QPE-RFC-ACR + QPE-RFC-ACR +
1
+
+ + QPF-STR + RFCqpf +
6
+
+ + FFG-STR + FFG-STR +
1
+
+ + QPE-STR + QPE-STR +
1
+
+ + QPE-Manual-STR + QPE-Manual-STR +
1
+
+ + QPE-Auto-STR + QPE-Auto-STR +
1
+
+ + MPE-Local-STR + MPE-Local-STR +
1
+
+ + MPE-Mosaic-STR + MPE-Mosaic-STR +
1
+
+ + QPE-XNAV-STR + QPE-XNAV-STR +
1
+
+ + QPE-RFC-STR + QPE-RFC-STR +
1
+
+ + QPF-RSA + RFCqpf +
6
+
+ + FFG-RSA + FFG-RSA +
1
+
+ + QPE-RSA + QPE-RSA +
1
+
+ + QPE-Manual-RSA + QPE-Manual-RSA +
1
+
+ + QPE-Auto-RSA + QPE-Auto-RSA +
1
+
+ + MPE-Local-RSA + MPE-Local-RSA +
1
+
+ + MPE-Mosaic-RSA + MPE-Mosaic-RSA +
1
+
+ + QPE-XNAV-RSA + QPE-XNAV-RSA +
1
+
+ + QPE-RFC-RSA + QPE-RFC-RSA +
1
+
+ + QPF-ORN + RFCqpf +
6
+
+ + FFG-ORN + FFG-ORN +
1
+
+ + QPE-ORN + QPE-ORN +
1
+
+ + QPE-Manual-ORN + QPE-Manual-ORN +
1
+
+ + QPE-Auto-ORN + QPE-Auto-ORN +
1
+
+ + MPE-Local-ORN + MPE-Local-ORN +
1
+
+ + MPE-Mosaic-ORN + MPE-Mosaic-ORN +
1
+
+ + QPE-XNAV-ORN + QPE-XNAV-ORN +
1
+
+ + QPE-RFC-ORN + QPE-RFC-ORN +
1
+
+ + QPF-RHA + RFCqpf +
6
+
+ + FFG-RHA + FFG-RHA +
1
+
+ + QPE-RHA + QPE-RHA +
1
+
+ + QPE-Manual-RHA + QPE-Manual-RHA +
1
+
+ + QPE-Auto-RHA + QPE-Auto-RHA +
1
+
+ + MPE-Local-RHA + MPE-Local-RHA +
1
+
+ + MPE-Mosaic-RHA + MPE-Mosaic-RHA +
1
+
+ + QPE-XNAV-RHA + QPE-XNAV-RHA +
1
+
+ + QPE-RFC-RHA + QPE-RFC-RHA +
1
+
+ + QPF-KRF + RFCqpf +
6
+
+ + FFG-KRF + FFG-KRF +
1
+
+ + QPE-KRF + QPE-KRF +
1
+
+ + QPE-Manual-KRF + QPE-Manual-KRF +
1
+
+ + QPE-Auto-KRF + QPE-Auto-KRF +
1
+
+ + MPE-Local-KRF + MPE-Local-KRF +
1
+
+ + MPE-Mosaic-KRF + MPE-Mosaic-KRF +
1
+
+ + QPE-XNAV-KRF + QPE-XNAV-KRF +
1
+
+ + QPE-RFC-KRF + QPE-RFC-KRF +
1
+
+ + QPF-MSR + RFCqpf +
6
+
+ + FFG-MSR + FFG-MSR +
1
+
+ + QPE-MSR + QPE-MSR +
1
+
+ + QPE-Manual-MSR + QPE-Manual-MSR +
1
+
+ + QPE-Auto-MSR + QPE-Auto-MSR +
1
+
+ + MPE-Local-MSR + MPE-Local-MSR +
1
+
+ + MPE-Mosaic-MSR + MPE-Mosaic-MSR +
1
+
+ + QPE-XNAV-MSR + QPE-XNAV-MSR +
1
+
+ + QPE-RFC-MSR + QPE-RFC-MSR +
1
+
+ + QPF-TAR + RFCqpf +
6
+
+ + FFG-TAR + FFG-TAR +
1
+
+ + QPE-TAR + QPE-TAR +
1
+
+ + QPE-Manual-TAR + QPE-Manual-TAR +
1
+
+ + QPE-Auto-TAR + QPE-Auto-TAR +
1
+
+ + MPE-Local-TAR + MPE-Local-TAR +
1
+
+ + MPE-Mosaic-TAR + MPE-Mosaic-TAR +
1
+
+ + QPE-XNAV-TAR + QPE-XNAV-TAR +
1
+
+ + QPE-RFC-TAR + QPE-RFC-TAR +
1
+
+ + QPF-PTR + RFCqpf +
6
+
+ + FFG-PTR + FFG-PTR +
1
+
+ + QPE-PTR + QPE-PTR +
1
+
+ + QPE-Manual-PTR + QPE-Manual-PTR +
1
+
+ + QPE-Auto-PTR + QPE-Auto-PTR +
1
+
+ + MPE-Local-PTR + MPE-Local-PTR +
1
+
+ + MPE-Mosaic-PTR + MPE-Mosaic-PTR +
1
+
+ + QPE-XNAV-PTR + QPE-XNAV-PTR +
1
+
+ + QPE-RFC-PTR + QPE-RFC-PTR +
1
+
+ + QPF-TIR + RFCqpf +
6
+
+ + FFG-TIR + FFG-TIR +
1
+
+ + FFG-TIR-HiRes + FFG-TIR-HiRes +
1
+
+ + QPE-TIR + QPE-TIR +
1
+
+ + QPE-Manual-TIR + QPE-Manual-TIR +
1
+
+ + QPE-Auto-TIR + QPE-Auto-TIR +
1
+
+ + MPE-Local-TIR + MPE-Local-TIR +
1
+
+ + MPE-Mosaic-TIR + MPE-Mosaic-TIR +
1
+
+ + QPE-XNAV-TIR + QPE-XNAV-TIR +
1
+
+ + QPE-RFC-TIR + QPE-RFC-TIR +
1
+
+ + QPF-ALR + RFCqpf +
6
+
+ + FFG-ALR + FFG-ALR +
1
+
+ + QPE-ALR + QPE-ALR +
1
+
+ + QPE-Manual-ALR + QPE-Manual-ALR +
1
+
+ + QPE-Auto-ALR + QPE-Auto-ALR +
1
+
+ + MPE-Local-ALR + MPE-Local-ALR +
1
+
+ + MPE-Mosaic-ALR + MPE-Mosaic-ALR +
1
+
+ + QPE-XNAV-ALR + QPE-XNAV-ALR +
1
+
+ + QPE-RFC-ALR + QPE-RFC-ALR +
1
+
+ + QPF-FWR + RFCqpf +
6
+
+ + FFG-FWR + FFG-FWR +
1
+
+ + QPE-FWR + QPE-FWR +
1
+
+ + QPE-Manual-FWR + QPE-Manual-FWR +
1
+
+ + QPE-Auto-FWR + QPE-Auto-FWR +
1
+
+ + MPE-Local-FWR + MPE-Local-FWR +
1
+
+ + MPE-Mosaic-FWR + MPE-Mosaic-FWR +
1
+
+ + QPE-XNAV-FWR + QPE-XNAV-FWR +
1
+
+ + QPE-RFC-FWR + QPE-RFC-FWR +
1
+
+ + NOHRSC-SNOW + NOHRSC-SNOW +
1
+
+ + NOHRSC-SNOW + NOHRSC-SNOW +
24
+
+ + SPE + AUTOSPE +
1
+
+ + SPE + MANSPE +
1
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_RSMC-54.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_RSMC-54.xml new file mode 100644 index 0000000000..e2a93e0e8a --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_RSMC-54.xml @@ -0,0 +1,13 @@ + + + + CanadianModel + CanadianModel +
1
+
+ + CanadianModel + CanadianModel +
1
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_UKMET-74.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_UKMET-74.xml new file mode 100644 index 0000000000..9d7c5ded04 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/datasetInfo/gribDatasets_UKMET-74.xml @@ -0,0 +1,53 @@ + + + + UKMET-MODEL1 + UKMET-MODEL1 +
6
+
+ + UKMET + UKMET-NorthernHemisphere +
6
+
+ + UKMET + UKMET37 +
6
+
+ + UKMET + UKMET38 +
6
+
+ + UKMET + UKMET39 +
6
+
+ + UKMET + UKMET40 +
6
+
+ + UKMET + UKMET41 +
6
+
+ + UKMET + UKMET42 +
6
+
+ + UKMET + UKMET43 +
6
+
+ + UKMET + UKMET44 +
6
+
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/grib1ParameterConvTable.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/grib1ParameterConvTable.xml index dca4246047..41bc4ae4a1 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/grib1ParameterConvTable.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/grib1ParameterConvTable.xml @@ -3199,6 +3199,15 @@ 12 + +
7
+ 129 + 230 + 0 + 1 + 242 +
+
7
130 @@ -4000,6 +4009,15 @@ 10
+ +
7
+ 133 + 191 + 0 + 6 + 201 +
+
7
133 @@ -6776,9 +6794,9 @@
98
128 31 - 255 - 255 - 255 + 10 + 2 + 192
@@ -6938,9 +6956,9 @@
98
128 49 - 255 - 255 - 255 + 0 + 2 + 22
@@ -6988,6 +7006,15 @@ 255 + +
98
+ 128 + 59 + 0 + 7 + 6 +
+
98
128 @@ -7064,36 +7091,36 @@
98
128 134 - 255 - 255 - 255 + 0 + 3 + 0
98
128 135 - 255 - 255 - 255 + 0 + 2 + 8
98
128 136 - 255 - 255 - 255 + 0 + 1 + 51
98
128 137 - 255 - 255 - 255 + 0 + 1 + 64
@@ -7132,13 +7159,31 @@ 255 + +
98
+ 128 + 142 + 0 + 1 + 9 +
+ + +
98
+ 128 + 143 + 0 + 1 + 10 +
+
98
128 144 - 255 - 255 - 255 + 0 + 1 + 29
@@ -7271,9 +7316,9 @@
98
128 159 - 255 - 255 - 255 + 0 + 3 + 18
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_RSMC-54.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_RSMC-54.xml deleted file mode 100644 index 833ee469dc..0000000000 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_RSMC-54.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - - - - CanadianModel - CanadianModel -
54
- 0 - 999001 - - 41 - - localMPE -
1
-
- - - CanadianModel - CanadianModel -
54
- 0 - 21 - - 41 - - localMPE -
1
-
- - - -
\ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/level/alias/grib.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/level/alias/grib.xml new file mode 100644 index 0000000000..257ec30570 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/level/alias/grib.xml @@ -0,0 +1,43 @@ + + + + ISBL + THEL + TRO + 0DEG + MWSL + HTGL + ZAGL + SIGL + AMSL + ZZZZ + DBLL + EATM + SPDL + PVL + HYBL + ETAL + DBSL + MIXL + MTHE + EHLT + OSD + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/parameter/alias/grib.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/parameter/alias/grib.xml new file mode 100644 index 0000000000..44fa99c118 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/parameter/alias/grib.xml @@ -0,0 +1,104 @@ + + + + 5WAVH + ABSV + CRAIN + CFRZR + CICEP + CSNOW + CWAT + CAPE + CIN + CDCON + ACPCP + CPRAT + DPT + DEPR + WVDIR + SWDIR + EPOT + EVP + HGT + DIST + HTX + HCDC + ICETK + MIXR + LAPR + LCDC + NCPCP + LHTFL + TMIN + WVPER + SWPER + MCDC + TMXK + PLI + PRES + PRMSL + MSLET + MSLPM + POT + PRATE + PRESA + DIRPW + PERPW + CPOFP + CPOZP + PV + PEVAP + PEVPR + PWAT + RH + SATD + DIRSW + PERSW + SWELL + WVHGT + SNOWC + SNOD + SPFH + SHTFL + TSOIL + HLCY + SLI + TMP + TMPA + TSTM + TCDC + APCP + USTM + VSTM + UGRD + VGRD + VAPP + VWSH + VVEL + VIS + VPTMP + VTMP + WEASD + WMIXE + WDIR + WIND + WGS + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/purge/gribPurgeRules.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/purge/gribPurgeRules.xml index 665a5faeeb..ca03820ffc 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/purge/gribPurgeRules.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/purge/gribPurgeRules.xml @@ -4,6 +4,7 @@ 2 + 02-00:00:00 diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid104.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid104.xml new file mode 100644 index 0000000000..111beff391 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid104.xml @@ -0,0 +1,35 @@ + + + + 104 + NAM model (Polar Stereographic) + -0.268 + -139.475 + LowerLeft + 147 + 110 + 90.755 + 90.755 + km + 6371229.0 + 6371229.0 + -105.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid1153576001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid1153576001.xml new file mode 100644 index 0000000000..ebbe02e6c9 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid1153576001.xml @@ -0,0 +1,34 @@ + + + + 1153576001 + Global Gaussian Lon/Lat T382 Resolution-Add on column + 89.761 + 0 + UpperLeft + 1153 + 576 + 0.313 + 0 + degree + -89.761 + 360.00 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid126.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid126.xml new file mode 100644 index 0000000000..4f9e245b60 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid126.xml @@ -0,0 +1,34 @@ + + + + 126 + Global Gaussian Lon/Lat T126 Resolution + 89.277 + 0 + UpperLeft + 384 + 190 + 0.9375 + 0 + degree + -89.277 + 359.0625 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid127.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid127.xml new file mode 100644 index 0000000000..b6fd0a1a59 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid127.xml @@ -0,0 +1,34 @@ + + + + 127 + Global Gaussian Lon/Lat T254 Resolution + 89.624 + 0 + UpperLeft + 768 + 384 + 0.469 + 0 + degree + -89.624 + 359.531 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid128.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid128.xml new file mode 100644 index 0000000000..615f6caaba --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid128.xml @@ -0,0 +1,34 @@ + + + + 128 + Global Gaussian Lon/Lat T382 Resolution + 89.761 + 0 + UpperLeft + 1152 + 576 + 0.313 + 0 + degree + -89.761 + 359.687 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid129.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid129.xml new file mode 100644 index 0000000000..711093dff3 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid129.xml @@ -0,0 +1,34 @@ + + + + 129 + Global Gaussian Lon/Lat T574 Resolution + 89.844 + 0 + UpperLeft + 1760 + 880 + 0.205 + 0 + degree + -89.844 + 359.795 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145029001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145029001.xml new file mode 100644 index 0000000000..0ee8e24a04 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145029001.xml @@ -0,0 +1,34 @@ + + + + 145029001 + World wide ECMWF 2.5 degree WAVE + 35.0 + 0.0 + UpperLeft + 145 + 29 + 2.5 + 2.5 + degree + -35.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145029002.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145029002.xml new file mode 100644 index 0000000000..1ef3a2b68a --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145029002.xml @@ -0,0 +1,34 @@ + + + + 145029002 + World wide ECMWF 2.5 degree WAVE -Add one column + 35.0 + 0.0 + UpperLeft + 146 + 29 + 2.5 + 2.5 + degree + -35.0 + 362.5 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145073001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145073001.xml new file mode 100644 index 0000000000..90650634aa --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid145073001.xml @@ -0,0 +1,34 @@ + + + + 145073001 + Global (longitude/latitude grid)-Add one column + 90.0 + 0.0 + UpperLeft + 145 + 73 + 2.5 + 2.5 + degree + -90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid170.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid170.xml new file mode 100644 index 0000000000..9205411c55 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid170.xml @@ -0,0 +1,34 @@ + + + + 170 + Global Gaussian Lon/Lat T170 Resolution + 89.463 + 0 + UpperLeft + 512 + 256 + 0.7025 + 0 + degree + -89.463 + 359.2975 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid1761880001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid1761880001.xml new file mode 100644 index 0000000000..5e6865d89a --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid1761880001.xml @@ -0,0 +1,34 @@ + + + + 1761880001 + Global Gaussian Lon/Lat T574 Resolution -Add one column + 89.844 + 0 + UpperLeft + 1761 + 880 + 0.205 + 0 + degree + -89.844 + 360.00 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid181139001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid181139001.xml new file mode 100644 index 0000000000..d3b0565edd --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid181139001.xml @@ -0,0 +1,34 @@ + + + + 181139001 + Latitude/Longitude Ocean grid with (1,1) at (1E,64E) and (180,139) at (1W,74S) I increasing Eastward, Equator at J=65 -Add one column + 64.0 + 1.0 + UpperLeft + 181 + 139 + 2.0 + 1.0 + degree + -74.0 + 361.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid193094001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid193094001.xml new file mode 100644 index 0000000000..d04730a227 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid193094001.xml @@ -0,0 +1,34 @@ + + + + 193094001 + Global Gaussian Lon/Lat T62 Resolution -Add one column + 88.542 + 0 + UpperLeft + 193 + 94 + 1.875 + 0 + degree + -88.542 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid196.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid196.xml index 4c68ad3ea9..94a494cb83 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid196.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid196.xml @@ -32,6 +32,6 @@ 6371229.0 6371229.0 20.0 - 18.0778 - -161.517 + 23.082 + -153.969 diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid22829.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid22829.xml new file mode 100644 index 0000000000..03a2ebdc6e --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid22829.xml @@ -0,0 +1,34 @@ + + + + 22829 + Global (longitude/latitude grid) + 35.0 + 0.0 + UpperLeft + 144 + 29 + 2.5 + 2.5 + degree + -35.0 + 357.5 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid229L.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid229L.xml new file mode 100644 index 0000000000..1dacaaa609 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid229L.xml @@ -0,0 +1,34 @@ + + + + 2291 + Global (longitude/latitude grid) + -90.0 + 0.0 + LowerLeft + 360 + 181 + 1.0 + 1.0 + degree + 90.0 + 359.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid2881144001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid2881144001.xml new file mode 100644 index 0000000000..15923a91f8 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid2881144001.xml @@ -0,0 +1,35 @@ + + + + 2881144001 + Global High Resolution Sea Ice grid + (longitude/latitude grid)-Add one column + 89.9375 + 0.0625 + UpperLeft + 2881 + 1440 + 0.125 + 0.125 + degree + -89.9375 + 360.0625 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid289145001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid289145001.xml new file mode 100644 index 0000000000..c5c4868507 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid289145001.xml @@ -0,0 +1,34 @@ + + + + 289145001 + Global Latitude/Longitude 1.25 deg Resolution + 90.0 + 0.0 + UpperLeft + 289 + 145 + 1.25 + 1.25 + degree + -90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid289157001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid289157001.xml new file mode 100644 index 0000000000..5d6d4a2ea3 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid289157001.xml @@ -0,0 +1,34 @@ + + + + 289157001 + Regional (longitude/latitude grid) - Add one column + 78.0 + 0.0 + UpperLeft + 289 + 157 + 1.25 + 1.0 + degree + -78.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361091001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361091001.xml new file mode 100644 index 0000000000..5ca333ddbe --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361091001.xml @@ -0,0 +1,34 @@ + + + + 361091001 + Northern Hemisphere (longitude/latitude grid)-Add one column + 0.0 + 0.0 + LowerLeft + 361 + 91 + 1.0 + 1.0 + degree + 90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361181001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361181001.xml new file mode 100644 index 0000000000..7cd1add776 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361181001.xml @@ -0,0 +1,34 @@ + + + + 361181001 + Global (longitude/latitude grid) - Add one column + 90.0 + 0.0 + UpperLeft + 361 + 181 + 1.0 + 1.0 + degree + -90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361181002.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361181002.xml new file mode 100644 index 0000000000..dfad9f53c8 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid361181002.xml @@ -0,0 +1,34 @@ + + + + 361181002 + Global (longitude/latitude grid) - Add one column + -90.0 + 0.0 + LowerLeft + 361 + 181 + 1.0 + 1.0 + degree + 90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid362181001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid362181001.xml new file mode 100644 index 0000000000..11caec5b0f --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid362181001.xml @@ -0,0 +1,34 @@ + + + + 362181001 + Global (longitude/latitude grid) - Add one column + -90.0 + 0.0 + LowerLeft + 362 + 181 + 1.0 + 1.0 + degree + 90.0 + 361.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid362181002.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid362181002.xml new file mode 100644 index 0000000000..0afd029b70 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid362181002.xml @@ -0,0 +1,34 @@ + + + + 362181002 + Global (longitude/latitude grid) - Add one column + 90.0 + 0.0 + UpperLeft + 362 + 181 + 1.0 + 1.0 + degree + -90.0 + 361.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid363181001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid363181001.xml new file mode 100644 index 0000000000..c58962d2b6 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid363181001.xml @@ -0,0 +1,35 @@ + + + + 363181001 + Global (longitude/latitude grid) - Add one column + -90.0 + 0.0 + LowerLeft + 363 + 181 + 1.0 + 1.0 + degree + 90.0 + 362.0 + + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid363181002.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid363181002.xml new file mode 100644 index 0000000000..8b3c3513b7 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid363181002.xml @@ -0,0 +1,34 @@ + + + + 363181002 + Global (longitude/latitude grid) - Add one column + 90.0 + 0.0 + UpperLeft + 363 + 181 + 1.0 + 1.0 + degree + -90.0 + 362.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid385190001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid385190001.xml new file mode 100644 index 0000000000..cf9a1c0795 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid385190001.xml @@ -0,0 +1,34 @@ + + + + 385190001 + Global Gaussian Lon/Lat T126 Resolution - Add one column + 89.277 + 0 + UpperLeft + 385 + 190 + 0.9375 + 0 + degree + -89.277 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid4321216001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid4321216001.xml new file mode 100644 index 0000000000..a811db673a --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid4321216001.xml @@ -0,0 +1,34 @@ + + + + 4321216001 + Global 1/12 degree Lat/Lon grid - Add one column + 89.958333 + 0.041667 + UpperLeft + 4321 + 2160 + 0.083333 + 0.083333 + degree + -89.958333 + 360.041666 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid448087001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid448087001.xml new file mode 100644 index 0000000000..056faaaff2 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid448087001.xml @@ -0,0 +1,34 @@ + + + + 448087001 + 38976-point (448x87) global Lon/Lat grid + 47.478 + 160.486999 + LowerLeft + 448 + 87 + 0.09999999 + 0.09999999 + degree + 56.178 + 205.286999 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid500400001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid500400001.xml new file mode 100644 index 0000000000..c396e14536 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid500400001.xml @@ -0,0 +1,34 @@ + + + + 500400001 + 200000-point (500x400) global Lon/Lat grid + -26.5 + 254.97 + LowerLeft + 500 + 400 + 0.255 + 0.255 + degree + 26.5 + -22.47 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid500500001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid500500001.xml new file mode 100644 index 0000000000..4f491b65e0 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid500500001.xml @@ -0,0 +1,34 @@ + + + + 500500001 + 250000-point (500x500) global Lon/Lat grid + 15 + 262 + LowerLeft + 500 + 500 + 0.056 + 0.034 + degree + 32 + 280 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid512256001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid512256001.xml new file mode 100644 index 0000000000..075f2e4138 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid512256001.xml @@ -0,0 +1,34 @@ + + + + 513256001 + Global Gaussian Lon/Lat T170 Resolution -Add one column + 89.463 + 0 + UpperLeft + 513 + 256 + 0.7025 + 0 + degree + -89.463 + 360.00 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid602151001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid602151001.xml new file mode 100644 index 0000000000..126461a705 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid602151001.xml @@ -0,0 +1,35 @@ + + + + 602151001 + 90902-point (602x151) Lon/Lat grid + 0.0 + 180.0 + LowerLeft + 601 + 151 + 0.6 + 0.6 + degree + 90.0 + 180.0 + + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720051001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720051001.xml new file mode 100644 index 0000000000..73a1d3c27c --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720051001.xml @@ -0,0 +1,34 @@ + + + + 720051001 + 36720-point (720x51) global Lon/Lat grid + 90.0 + 0.0 + UpperLeft + 720 + 51 + 0.5 + 0.5 + degree + 75.0 + 359.5 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720311001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720311001.xml new file mode 100644 index 0000000000..ffba3e4d7e --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720311001.xml @@ -0,0 +1,34 @@ + + + + 720311001 + 223920-point (720x311) global Lon/Lat grid + 77.5 + 0.0 + UpperLeft + 720 + 311 + 0.5 + 0.5 + degree + -77.5 + 359.5 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720361001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720361001.xml new file mode 100644 index 0000000000..0a17b1bf50 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid720361001.xml @@ -0,0 +1,34 @@ + + + + 720361001 + 259920-point (720x361) global Lon/Lat grid + -90.0 + 0.0 + LowerLeft + 720 + 361 + 0.5 + 0.5 + degree + 90.0 + 359.5 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721051001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721051001.xml new file mode 100644 index 0000000000..4220d2c0e6 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721051001.xml @@ -0,0 +1,34 @@ + + + + 721051001 + 36720-point (721x51) global Lon/Lat grid + 90.0 + 0.0 + UpperLeft + 721 + 51 + 0.5 + 0.5 + degree + 75.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721181001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721181001.xml new file mode 100644 index 0000000000..1d541dd3b8 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721181001.xml @@ -0,0 +1,34 @@ + + + + 721181001 + Northern Hemisphere (longitude/latitude grid)-Add one column + 0.0 + 0.0 + LowerLeft + 721 + 181 + 0.5 + 0.5 + degree + 90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721311001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721311001.xml new file mode 100644 index 0000000000..cbc7cb6b2e --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721311001.xml @@ -0,0 +1,34 @@ + + + + 721311001 + 223920-point (720x311) global Lon/Lat grid - add one column + 77.5 + 0.0 + UpperLeft + 721 + 311 + 0.5 + 0.5 + degree + -77.5 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721336001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721336001.xml new file mode 100644 index 0000000000..10a0975c29 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721336001.xml @@ -0,0 +1,34 @@ + + + + 721336001 + Global 0.5 degree Latitude/Longitude grid - Add one column + 90.0 + 0.0 + UpperLeft + 721 + 336 + 0.5 + 0.5 + degree + -77.5 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721360001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721360001.xml new file mode 100644 index 0000000000..96ec3044c0 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721360001.xml @@ -0,0 +1,34 @@ + + + + 721360001 + Global (longitude/latitude grid)-Add one column + 89.75 + 0.25 + UpperLeft + 721 + 360 + 0.5 + 0.5 + degree + -89.75 + 360.25 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721361001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721361001.xml new file mode 100644 index 0000000000..feb9d0a1bb --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721361001.xml @@ -0,0 +1,34 @@ + + + + 721361001 + 259920-point (721x361) global Lon/Lat grid + -90.0 + 0.0 + LowerLeft + 721 + 361 + 0.5 + 0.5 + degree + 90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721361002.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721361002.xml new file mode 100644 index 0000000000..a11c81e4d0 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid721361002.xml @@ -0,0 +1,34 @@ + + + + 721361002 + Global (longitude/latitude grid) - Add one column + 90.0 + 0.0 + UpperLeft + 721 + 361 + 0.5 + 0.5 + degree + -90.0 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid722051001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid722051001.xml new file mode 100644 index 0000000000..6214374f97 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid722051001.xml @@ -0,0 +1,34 @@ + + + + 722051001 + 36822-point (722x51) global Lon/Lat grid -Add one column + 90.0 + 0.0 + UpperLeft + 722 + 51 + 0.5 + 0.5 + degree + 75.0 + 360.5 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid722361001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid722361001.xml new file mode 100644 index 0000000000..522e8bd2e0 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid722361001.xml @@ -0,0 +1,34 @@ + + + + 722361001 + 260642-point (722x361) global Lon/Lat grid + -90.0 + 0.0 + LowerLeft + 722 + 361 + 0.5 + 0.5 + degree + 90.0 + 361 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid769384001.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid769384001.xml new file mode 100644 index 0000000000..7bc3df3b6e --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid769384001.xml @@ -0,0 +1,34 @@ + + + + 769384001 + Global Gaussian Lon/Lat T254 Resolution - Add one column + 89.624 + 0 + UpperLeft + 769 + 384 + 0.469 + 0 + degree + -89.624 + 360.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid98.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid98.xml new file mode 100644 index 0000000000..943673b529 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/grid98.xml @@ -0,0 +1,34 @@ + + + + 98 + Global Gaussian Lon/Lat T254 Resolution + 88.542 + 0 + UpperLeft + 192 + 94 + 1.875 + 0 + degree + -88.542 + 358.125 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/seaice_south1_grid.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/seaice_south1_grid.xml new file mode 100644 index 0000000000..5e0826769a --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/seaice_south1_grid.xml @@ -0,0 +1,35 @@ + + + + 405 + Sea Ice south 690X710 13km grid + -36.866 + 139.806 + LowerLeft + 690 + 710 + 12.7 + 12.7 + km + 6371229.0 + 6371229.0 + 100.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/seaice_south_grid.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/seaice_south_grid.xml new file mode 100644 index 0000000000..9558aa4c4c --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/grids/seaice_south_grid.xml @@ -0,0 +1,35 @@ + + + + 400 + Sea Ice south 345X355 25km grid + -36.866 + 139.806 + LowerLeft + 345 + 355 + 25.4 + 25.4 + km + 6371229.0 + 6371229.0 + 100.0 + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/GribModels_FNMO-58.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/GribModels_FNMO-58.xml new file mode 100644 index 0000000000..da51fe45b0 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/GribModels_FNMO-58.xml @@ -0,0 +1,147 @@ + + + + + + + + + + nogaps +
58
+ 0 + 401 + + 58 + + nogaps +
+ + + nogaps +
58
+ 0 + 362181001 + + 58 + + nogaps +
+ + + nogaps +
58
+ 0 + 362181002 + + 58 + + nogaps +
+ + + nogaps +
58
+ 0 + 2291 + + 50 + 58 + + nogaps +
+ + + nogaps +
58
+ 0 + 361181002 + + 50 + 58 + + nogaps +
+ + + fnmocWave +
58
+ 0 + 401 + + 110 + +
+ + + fnmocWave +
58
+ 0 + 362181001 + + 110 + +
+ + + fnmocWave +
58
+ 0 + 362181002 + + 110 + +
+ + + fnmocWave +
58
+ 0 + 2291 + + 110 + +
+ + + fnmocWave +
58
+ 0 + 361181002 + + 110 + +
+ + + NOGAPS +
58
+ 20 + 218 + + 120 + + nogaps +
+ + + AK-NOGAPS +
58
+ 20 + 242 + + 120 + + nogaps +
+ + + + +
\ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_ECMWF-98.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_ECMWF-98.xml similarity index 81% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_ECMWF-98.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_ECMWF-98.xml index b448a6b401..55a423fc88 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_ECMWF-98.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_ECMWF-98.xml @@ -12,7 +12,545 @@ - ECMWF-HiRes + ecmwf +
98
+ 0 + 3 + + 141 + 142 + 143 + 144 + 145 + + ecmwf +
+ + + ecmwf +
98
+ 0 + 361181001 + + 141 + 142 + 143 + 144 + 145 + + ecmwf +
+ + + ecmwf +
98
+ 0 + 229 + + 141 + 142 + 143 + 144 + 145 + + ecmwf +
+ + + ecmwfg +
98
+ 0 + 228 + + 141 + 142 + 143 + 144 + 145 + +
+ + + ecmwfg +
98
+ 0 + 145073001 + + 141 + 142 + 143 + 144 + 145 + +
+ + + ecmwfg +
98
+ 0 + 22829 + + 141 + 142 + 143 + 144 + 145 + +
+ + + ecmwfg +
98
+ 0 + 145029001 + + 141 + 142 + 143 + 144 + 145 + +
+ + + ecmwfg +
98
+ 0 + 145029002 + + 141 + 142 + 143 + 144 + 145 + +
+ + + ecmwft +
98
+ 0 + 14529 + + 141 + 142 + 143 + 144 + 145 + +
+ + + narr +
98
+ 0 + 14529 + + 140 + +
+ + + narr +
98
+ 0 + 2 + + 140 + +
+ + + narr +
98
+ 0 + 228 + + 140 + +
+ + + narr +
98
+ 0 + 145073001 + + 140 + +
+ + + ecmwfWave +
98
+ 0 + 403 + + 108 + 109 + 110 + 111 + 112 + +
+ + + ecmwfWave +
98
+ 0 + 361181001 + + 109 + +
+ + + ecmwfWave +
98
+ 0 + 361181002 + + 109 + +
+ + + ecmwfWave +
98
+ 0 + 362181001 + + 109 + +
+ + + ecmwfWave +
98
+ 0 + 362181002 + + 109 + +
+ + + ecmwfWave +
98
+ 0 + 363181001 + + 109 + +
+ + + ecmwfWave +
98
+ 0 + 363181002 + + 109 + +
+ + + ecmwfg +
98
+ 0 + 2 + + 137 + +
+ + + ECMWFWAVE +
98
+ 0 + 374 + + 255 + +
+ + + ECMWFWAVE +
98
+ 0 + 375 + + 104 + 255 + +
+ + + ECMWFHiRes +
98
+ 0 + 361091001 + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20 + 21 + 22 + 23 + 24 + 25 + 26 + 27 + 28 + 29 + 30 + 31 + 32 + 33 + 34 + 35 + 36 + 37 + 38 + 39 + 40 + 41 + 42 + 43 + 44 + 45 + 46 + 47 + 48 + 49 + 50 + 51 + 52 + 53 + 54 + 55 + 56 + 57 + 58 + 59 + 60 + 61 + 62 + 63 + 64 + 65 + 66 + 67 + 68 + 69 + 70 + 71 + 72 + 73 + 74 + 75 + 76 + 77 + 78 + 79 + 80 + 81 + 82 + 83 + 84 + 85 + 86 + 87 + 88 + 89 + 90 + 91 + 92 + 93 + 94 + 95 + 96 + 97 + 98 + 99 + 100 + 101 + 102 + 103 + 104 + 105 + 106 + 107 + 108 + 109 + 110 + 111 + 112 + 113 + 114 + 115 + 116 + 117 + 118 + 119 + 120 + 121 + 122 + 123 + 124 + 125 + 126 + 127 + 128 + 129 + 130 + 131 + 132 + 133 + 134 + 135 + 136 + 137 + 138 + 139 + 140 + 141 + 142 + 143 + 144 + 145 + 146 + 147 + 148 + 149 + 150 + 151 + 152 + 153 + 154 + 155 + 156 + 157 + 158 + 159 + 160 + 161 + 162 + 163 + 164 + 165 + 166 + 167 + 168 + 169 + 170 + 171 + 172 + 173 + 174 + 175 + 176 + 177 + 178 + 179 + 180 + 181 + 182 + 183 + 184 + 185 + 186 + 187 + 188 + 189 + 190 + 191 + 192 + 193 + 194 + 195 + 196 + 197 + 198 + 199 + 200 + 201 + 202 + 203 + 204 + 205 + 206 + 207 + 208 + 209 + 210 + 211 + 212 + 213 + 214 + 215 + 216 + 217 + 218 + 219 + 220 + 221 + 222 + 223 + 224 + 225 + 226 + 227 + 228 + 229 + 230 + 231 + 232 + 233 + 234 + 235 + 236 + 237 + 238 + 239 + 240 + 241 + 242 + 243 + 244 + 245 + 246 + 247 + 248 + 249 + 250 + 251 + 252 + 253 + 254 + 255 + + ecmwf +
+ ECMWF-HiRes
98
0 @@ -276,11 +814,9 @@ 255 ecmwf -
12
- ECMWF-LowRes ECMF-NorthernHemisphere
98
0 @@ -424,10 +960,8 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF1
98
0 @@ -571,11 +1105,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF2
98
0 @@ -719,11 +1251,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF3
98
0 @@ -867,11 +1397,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF4
98
0 @@ -1015,11 +1543,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF5
98
0 @@ -1163,11 +1689,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF6
98
0 @@ -1311,11 +1835,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF7
98
0 @@ -1459,11 +1981,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF8
98
0 @@ -1607,11 +2127,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF9
98
0 @@ -1755,11 +2273,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF10
98
0 @@ -1903,11 +2419,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF11
98
0 @@ -2051,11 +2565,9 @@ 255 ecmfNH -
24
- ECMWF-LowRes ECMF12
98
0 @@ -2199,11 +2711,9 @@ 255 ecmfNH -
24
- + - ECMWF-MODEL0 ECMF-MODEL0
98
0 @@ -2347,8 +2857,7 @@ 255 ecmfNH -
24
- + - \ No newline at end of file + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_FSL-59.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_FSL-59.xml similarity index 97% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_FSL-59.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_FSL-59.xml index 996e1a03f0..53fe18802f 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_FSL-59.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_FSL-59.xml @@ -25,7 +25,6 @@ - LAPS LAPS
59
0 @@ -34,7 +33,6 @@ 103 laps -
1
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NCEP-7.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NCEP-7.xml similarity index 68% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NCEP-7.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NCEP-7.xml index cf9b89d206..d9c1c7c0ad 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NCEP-7.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NCEP-7.xml @@ -12,7 +12,6 @@ - GFSLAMP-Stn GFSLAMP
7
0 @@ -21,11 +20,9 @@ 999 -
1
- NAM80 ETA
7
0 @@ -34,11 +31,9 @@ 84 eta211 -
6
- GFS180 AVN
7
0 @@ -49,11 +44,9 @@ 81 avn202 -
6
- NGM80 NGM
7
0 @@ -62,11 +55,9 @@ 39 ngm211 -
6
- gfsLR MRF
7
0 @@ -78,11 +69,9 @@ 94 mrf202 -
12
- gfsLR21 MRF21
7
0 @@ -94,11 +83,9 @@ 94 mrf202 -
12
- gfsLR22 MRF22
7
0 @@ -110,11 +97,9 @@ 94 mrf202 -
12
- gfsLR23 MRF23
7
0 @@ -126,11 +111,9 @@ 94 mrf202 -
12
- gfsLR24 MRF24
7
0 @@ -142,11 +125,9 @@ 94 mrf202 -
12
- gfsLR25 MRF25
7
0 @@ -158,11 +139,9 @@ 94 mrf202 -
12
- gfsLR26 MRF26
7
0 @@ -174,11 +153,9 @@ 94 mrf202 -
12
- GFS360 GFS201
7
0 @@ -188,11 +165,9 @@ 81 gfs201 -
6
- gfsLR mrfNH
7
0 @@ -204,11 +179,9 @@ 94 mrf201 -
12
- GFS90 GFS213
7
0 @@ -219,11 +192,9 @@ 96 gfs213 -
6
- NGM90 NGM213
7
0 @@ -232,11 +203,9 @@ 39 ngm213 -
6
- NGM180 NGM202
7
0 @@ -245,12 +214,10 @@ 39 ngm202 -
6
- GFS80 AVN211
7
0 @@ -261,11 +228,9 @@ 96 avn211 -
6
- NAM40 mesoEta212
7
0 @@ -274,13 +239,10 @@ 84 mesoEta212 -
3
- NAM20 mesoEta215 - mesoEta212
7
0 215 @@ -288,11 +250,9 @@ 84 mesoEta215 -
3
- WAFS WAFS
7
0 @@ -305,11 +265,23 @@ 96 -
6
- NAMWX + WAFS +
7
+ 0 + 289145001 + + 80 + 81 + 82 + 94 + 96 + +
+ + ETA212
7
0 @@ -318,11 +290,9 @@ 89 eta212 -
3
- GFS190 AVN203
7
0 @@ -333,11 +303,9 @@ 96 avn203 -
12
- gfs190 MRF203
7
0 @@ -349,11 +317,9 @@ 94 mrf203 -
12
- GFS150 MRF204
7
0 @@ -365,11 +331,9 @@ 94 mrf204 -
12
- GFS150 MRF205
7
0 @@ -381,11 +345,9 @@ 94 mrf205 -
12
- NGM95 NGM207
7
0 @@ -394,11 +356,9 @@ 39 ngm207 -
6
- NAM95 ETA207
7
0 @@ -407,11 +367,29 @@ 84 eta207 -
6
- GFSGbl + ofsGmex +
7
+ 0 + 15058391 + + 45 + +
+ + + ofsWatl +
7
+ 0 + -26535243 + + 45 + +
+ + AVN-NorthernHemisphere
7
0 @@ -423,11 +401,9 @@ 94 avnNH -
6
- GFSGbl AVN37
7
0 @@ -439,11 +415,9 @@ 94 avnNH -
6
- GFSGbl AVN38
7
0 @@ -455,11 +429,9 @@ 94 avnNH -
6
- GFSGbl AVN39
7
0 @@ -471,11 +443,9 @@ 94 avnNH -
6
- GFSGbl AVN40
7
0 @@ -487,11 +457,9 @@ 94 avnNH -
6
- GFSGbl AVN41
7
0 @@ -503,11 +471,9 @@ 94 avnNH -
6
- GFSGbl AVN42
7
0 @@ -519,11 +485,9 @@ 94 avnNH -
6
- GFSGbl AVN43
7
0 @@ -535,11 +499,9 @@ 94 avnNH -
6
- GFSGbl AVN44
7
0 @@ -551,11 +513,49 @@ 94 avnNH -
6
- GWW + gww +
7
+ 0 + 3 + + 10 + +
+ + + gww +
7
+ 0 + 361181001 + + 10 + +
+ + + gww2 +
7
+ 0 + 77528250 + + 11 + +
+ + + gww3 +
7
+ 0 + 408 + + 11 + +
+ + GWW233
7
0 @@ -564,11 +564,29 @@ 10 gww233 -
6
- GWW21 + gww4 +
7
+ 0 + 289157001 + + 10 + +
+ + + gww5 +
7
+ 0 + 372 + + 10 + +
+ + GWW21
7
0 @@ -577,11 +595,9 @@ 10 gww233 -
6
- GWW22 GWW22
7
0 @@ -590,11 +606,9 @@ 10 gww233 -
6
- GWW23 GWW23
7
0 @@ -603,11 +617,9 @@ 10 gww233 -
6
- GWW24 GWW24
7
0 @@ -616,11 +628,9 @@ 10 gww233 -
6
- SeaIce SeaIce
7
0 @@ -629,11 +639,9 @@ 120 seaIce219 -
1
- SeaIce220 SeaIce220
7
0 @@ -642,11 +650,9 @@ 120 seaIce219 -
1
- SeaIce173 SeaIce173
7
0 @@ -655,11 +661,9 @@ 120 seaIce219 -
1
- SeaIce235 SeaIce235
7
0 @@ -668,12 +672,10 @@ 120 seaIce219 -
1
- RAP40 RUC236
7
0 @@ -682,11 +684,19 @@ 105 ruc236 -
1
- GFS75 + rapIcing +
7
+ 0 + 236 + + 191 + +
+ + AVN225
7
0 @@ -697,11 +707,9 @@ 81 avn225 -
6
- AKWAVE AKWAVE239
7
0 @@ -710,11 +718,9 @@ 122 akWave239 -
6
- WNAwave WNAWAVE238
7
0 @@ -723,11 +729,9 @@ 121 wnaWave238 -
6
- AK-NAM40 mesoEta216
7
0 @@ -736,11 +740,9 @@ 84 mesoEta216 -
6
- AK-NAM20 mesoEta217
7
0 @@ -749,11 +751,9 @@ 84 mesoEta217 -
6
- NAM12 ETA218
7
0 @@ -762,11 +762,9 @@ 84 eta218 -
3
- AK-NAM12 ETA242
7
0 @@ -775,11 +773,60 @@ 84 eta242 +
+ + + NAM227 +
7
+ 0 + 227 + + 84 +
3
- ENPwave + namNestHI +
7
+ 0 + 406 + + 84 + +
+ + + namNestHI +
7
+ 0 + 196 + + 84 + +
+ + + NAMAK +
7
+ 0 + 198 + + 84 + +
+ + + namPR +
7
+ 0 + 407 + + 84 + +
+ + ENPWAVE253
7
0 @@ -788,11 +835,9 @@ 124 enpWave253 -
6
- HurWave238 HurWave238
7
0 @@ -801,11 +846,9 @@ 123 -
6
- HurWave253 HurWave253
7
0 @@ -814,11 +857,19 @@ 125 -
6
- TPC-HurWind + HPCdelta +
7
+ 0 + 215 + + 183 + +
+ + HurWind226
7
0 @@ -827,11 +878,9 @@ 30 TPCtcm226 -
6
- GuamHurWind HurWind175
7
0 @@ -840,11 +889,9 @@ 30 TCPtcm175 -
6
- HawHurWind HurWind250
7
0 @@ -853,11 +900,9 @@ 30 TPCtpm250 -
6
- NICICE NICICE
7
0 @@ -866,11 +911,9 @@ 120 nic218 -
1
- AK-NICICE AK-NICICE
7
0 @@ -879,11 +922,9 @@ 120 nic242 -
1
- DGEX DGEX185
7
0 @@ -892,11 +933,9 @@ 115 dgex185 -
6
- DGEX DGEX186
7
0 @@ -905,11 +944,9 @@ 115 dgex186 -
6
- GFS40 GFS212
7
0 @@ -920,11 +957,9 @@ 77 gfs212 -
6
- AK-GFS GFS160
7
0 @@ -935,11 +970,9 @@ 77 gfs160 -
6
- PR-GFS GFS254
7
0 @@ -950,11 +983,9 @@ 77 gfs254 -
6
- SJU-GFS GFS161
7
0 @@ -965,11 +996,9 @@ 77 gfs161 -
6
- Guam-GFS GFS199
7
0 @@ -980,11 +1009,21 @@ 77 gfs161 -
6
- RAP13 + GFS230 +
7
+ 0 + 230 + + 96 + 77 + 81 + +
+ + RUC130
7
0 @@ -993,11 +1032,9 @@ 105 ruc130 -
1
- RTMA RTMA
7
0 @@ -1006,11 +1043,9 @@ 109 rtmaNDFD -
1
- + - RTMA-Mosaic RTMA-Mosaic
7
0 @@ -1019,11 +1054,9 @@ 109 rtmaNDFD -
1
- AK-RTMA AK-RTMA
7
0 @@ -1032,11 +1065,9 @@ 109 aKrtmaNDFD -
1
- NamDNG5 NamDNG5
7
0 @@ -1045,11 +1076,9 @@ 89 NamDNG5 -
3
- RaobOA RaobOA
7
0 @@ -1058,11 +1087,9 @@ 999 -
12
- MetarOA MetarOA
7
0 @@ -1071,24 +1098,30 @@ 999 -
1
- GlobalWave GlobalWave
7
0 - 011 + 11 11 GlobalWave -
3
- AKwave10 + wave30mAO +
7
+ 0 + 90042500 + + 11 + +
+ + AKwave10
7
0 @@ -1097,11 +1130,9 @@ 11 AKwave10 -
3
- AKwave4 AKwave4
7
0 @@ -1110,11 +1141,9 @@ 11 AKwave4 -
3
- EPwave10 EPwave10
7
0 @@ -1123,11 +1152,9 @@ 11 EPwave10 -
3
- WCwave10 WCwave10
7
0 @@ -1136,11 +1163,9 @@ 11 WCwave10 -
3
- WCwave4 WCwave4
7
0 @@ -1149,11 +1174,9 @@ 11 WCwave4 -
3
- WNAwave10 WNAwave10
7
0 @@ -1162,11 +1185,9 @@ 11 WNAwave10 -
3
- WNAwave4 WNAwave4
7
0 @@ -1175,11 +1196,9 @@ 11 WNAwave4 -
3
- Aviation Aviation
7
0 @@ -1189,51 +1208,9 @@ 105 -
1
- Aviation - Aviation -
7
- 0 - 252 - - 191 - 105 - - -
1
-
- - - Aviation - Aviation -
7
- 0 - 252 - - 191 - - -
1
-
- - - Aviation - Aviation -
7
- 8 - 130 - - 105 - - -
1
-
- - - AK-NamDNG5 AK-NamDNG5
7
0 @@ -1242,11 +1219,9 @@ 89 AkNamDNG5 -
3
- HI-NamDNG5 HI-NamDNG5
7
0 @@ -1255,11 +1230,9 @@ 89 HiNamDNG5 -
3
- PR-NamDNG5 PR-NamDNG5
7
0 @@ -1268,11 +1241,9 @@ 89 PrNamDNG5 -
3
- HiResW-ARW-East HiResW-ARW-East
7
0 @@ -1281,11 +1252,9 @@ 116 HiResW-arwEast -
3
- HiResW-ARW-West HiResW-ARW-West
7
0 @@ -1294,11 +1263,9 @@ 116 HiResW-arwWest -
3
- HiResW-ARW-AK HiResW-ARW-AK
7
0 @@ -1307,11 +1274,9 @@ 116 HiResW-arwAK -
3
- + - HiResW-ARW-SJU HiResW-ARW-SJU
7
0 @@ -1320,11 +1285,9 @@ 116 HiResW-arwSJU -
3
- HiResW-ARW-HI HiResW-ARW-HI
7
0 @@ -1333,12 +1296,10 @@ 116 HiResW-arwHI -
3
- HiResW-ARW-GU HiResW-ARW-GU
7
0 @@ -1347,11 +1308,29 @@ 116 HiResW-arwGU -
3
- HiResW-NMM-East + hireswArwGuam +
7
+ 0 + 11731129 + + 116 + +
+ + + hireswArwPR +
7
+ 0 + 13560489 + + 116 + +
+ + HiResW-NMM-East
7
0 @@ -1360,12 +1339,10 @@ 112 HiResW-nmmEast -
3
- HiResW-NMM-West HiResW-NMM-West
7
0 @@ -1374,11 +1351,9 @@ 112 HiResW-nmmWest -
3
- HiResW-NMM-AK HiResW-NMM-AK
7
0 @@ -1387,11 +1362,9 @@ 112 HiResW-nmmAK -
3
- HiResW-NMM-SJU HiResW-NMM-SJU
7
0 @@ -1400,11 +1373,9 @@ 112 HiResW-nmmSJU -
3
- HiResW-NMM-HI HiResW-NMM-HI
7
0 @@ -1413,11 +1384,9 @@ 112 HiResW-nmmHI -
3
- HiResW-NMM-GU HiResW-NMM-GU
7
0 @@ -1426,11 +1395,29 @@ 112 HiResW-nmmGU -
3
- GRLKwave + hireswNmmGuam +
7
+ 0 + 11731129 + + 112 + +
+ + + hireswNmmPR +
7
+ 0 + 13560489 + + 112 + +
+ + GRLKwave
7
0 @@ -1439,11 +1426,9 @@ 131 GRLKwave -
1
- MSAS MSAS
7
0 @@ -1452,11 +1437,9 @@ 100 msas -
1
- GFSBufr GfsBufr
7
0 @@ -1465,11 +1448,9 @@ 999 -
1
- GFSSouthernHemisphere GFSSouthernHemisphere
7
0 @@ -1479,11 +1460,9 @@ 96 gfs201 -
1
- GoesBufr GoesBufr
7
0 @@ -1492,11 +1471,9 @@ 999 -
1
- Metar Metar
7
0 @@ -1505,11 +1482,9 @@ 999 -
1
- Ldad Ldad
7
0 @@ -1518,11 +1493,9 @@ 999 -
1
- DMD DMD
7
0 @@ -1531,11 +1504,9 @@ 999 -
-10
- MDCRS MDCRS
7
0 @@ -1544,11 +1515,9 @@ 999 -
1
- NAM Bufr EtaBufr
7
0 @@ -1557,11 +1526,9 @@ 999 -
1
- PoesBufr PoesBufr
7
0 @@ -1570,11 +1537,9 @@ 999 -
1
- Profiler Profiler
7
0 @@ -1583,11 +1548,9 @@ 999 -
1
- Raob Raob
7
0 @@ -1596,11 +1559,9 @@ 999 -
12
- VWP VWP
7
0 @@ -1609,11 +1570,9 @@ 999 -
-6
- PR-NAM12 mesoEta237
7
0 @@ -1622,7 +1581,556 @@ 84 eta218 -
3
+
+ + + GFS0.5 +
7
+ 0 + 4 + + 96 + 77 + 81 + +
+ + + gfsP5 +
7
+ 0 + 721361002 + + 96 + 77 + 81 + +
+ + gfsP5 +
7
+ 0 + 408 + + 255 + +
+ + + gfs +
7
+ 0 + 229 + + 96 + 77 + 81 + 225 + 255 + +
+ + + gfs +
7
+ 0 + 228 + + 96 + 77 + 81 + +
+ + + gfs +
7
+ 0 + 361181001 + + 96 + 77 + 81 + 225 + 255 + +
+ + + gfs +
7
+ 0 + 372 + + 96 + +
+ + + gdas +
7
+ 0 + 375 + + 86 + +
+ + + gfs +
7
+ 0 + 372 + + 81 + +
+ + + gdas +
7
+ 0 + 3 + + 82 + +
+ + + gdas +
7
+ 0 + 361181001 + + 82 + +
+ + + gdas +
7
+ 0 + 372 + + 82 + +
+ + + gfs +
7
+ 0 + 145073001 + + 96 + 77 + 81 + +
+ + + nam12E +
7
+ 0 + 99 + + 89 + +
+ + + nam +
7
+ 0 + 104 + + 84 + +
+ + + nam91 +
7
+ 0 + 101 + + 84 + +
+ + + nam32E +
7
+ 0 + 151 + + 84 + +
+ + + nam32 +
7
+ 0 + 221 + + 84 + +
+ + + namP5ENP +
7
+ 0 + 243 + + 84 + +
+ + + lfm +
7
+ 0 + 5 + + 84 + +
+ + + lfm +
7
+ 0 + 6 + + 84 + +
+ + + rap40 +
7
+ 0 + 212 + + 100 + +
+ + + rap15 +
7
+ 0 + 88 + + 100 + +
+ + + gefsNdgd +
7
+ 0 + 197 + + 107 + +
+ + + rap +
7
+ 0 + 888 + + 105 + +
+ + + rap80 +
7
+ 0 + 211 + + 86 + 100 + +
+ + + gfs32 +
7
+ 0 + 221 + + 96 + 81 + +
+ + + gfs +
7
+ 0 + 375 + + 96 + 81 + +
+ + + gww375 +
7
+ 0 + 375 + + 10 + 255 + +
+ + + nww3 +
7
+ 0 + 233 + + 88 + +
+ + + nww3 +
7
+ 0 + 289157001 + + 88 + +
+ + + iceSouth +
7
+ 0 + 400 + + 120 + +
+ + + iceSHP5 +
7
+ 0 + 405 + + 120 + +
+ + + iceSH12 +
7
+ 0 + 172 + + 120 + +
+ + + iceNH12 +
7
+ 0 + 171 + + 120 + +
+ + + ice12th +
7
+ 0 + 4321216001 + + 120 + +
+ + + iceP5 +
7
+ 0 + 721360001 + + 120 + +
+ + + RTGSST +
7
+ 0 + 235 + + 44 + +
+ + + RTGSST +
7
+ 0 + 721360001 + + 44 + +
+ + + RTGSSTHR +
7
+ 0 + 173 + + 44 + +
+ + + RTGSSTHR +
7
+ 0 + 4321216001 + + 44 + +
+ + + AVIATION +
7
+ 0 + 255202 + + 191 + 105 + +
+ + + AVIATION +
7
+ 0 + 255203 + + 191 + +
+ + + AQM196 +
7
+ 0 + 196 + + 211 + +
+ + + AQM227 +
7
+ 0 + 227 + + 211 + +
+ + + wave30mAO +
7
+ 0 + 720051001 + + 11 + +
+ + + wave30mAO +
7
+ 0 + 721051001 + + 11 + +
+ + + wave30mAO +
7
+ 0 + 722051001 + + 11 + +
+ + + wave30mGlobal +
7
+ 0 + 720311001 + + 11 + +
+ + + wave30mGlobal +
7
+ 0 + 721311001 + + 11 + +
+ + + wave30mGlobal +
7
+ 0 + 721336001 + + 11 + +
+ + + ofsWatl +
7
+ 0 + 500400001 + + 45 + +
+ + + ofsGmex +
7
+ 0 + 500500001 + + 45 +
@@ -1630,7 +2138,6 @@ - GFSensemble ENSEMBLE
7
2 @@ -1643,11 +2150,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE37
7
2 @@ -1660,11 +2165,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE38
7
2 @@ -1677,11 +2180,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE39
7
2 @@ -1694,11 +2195,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE40
7
2 @@ -1711,11 +2210,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE41
7
2 @@ -1728,11 +2225,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE42
7
2 @@ -1745,11 +2240,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE43
7
2 @@ -1762,11 +2255,9 @@ 96 ensembleNH -
6
- GFSensemble ENSEMBLE44
7
2 @@ -1779,11 +2270,59 @@ 96 ensembleNH -
6
- SREF + gefs +
7
+ 2 + 2 + + 107 + +
+ + + gefs +
7
+ 2 + 3 + + 107 + +
+ + + gefs +
7
+ 2 + 361181001 + + 107 + +
+ + + gefs +
7
+ 2 + 372 + + 107 + +
+ + + gefs +
7
+ 2 + 375 + + 107 + +
+ + SREF212
7
2 @@ -1792,11 +2331,9 @@ 113 sref212 -
3
- AK-SREF SREF216
7
2 @@ -1805,11 +2342,9 @@ 113 sref216 -
3
- PR-SREF SREF243
7
2 @@ -1818,15 +2353,93 @@ 113 sref243 -
3
+
+ + + naefsBC +
7
+ 2 + 375 + + 114 + +
+ + + naefsBC +
7
+ 2 + 372 + + 114 + +
+ + + naefsBC +
7
+ 2 + 3 + + 114 + +
+ + + naefsBC +
7
+ 2 + 361181001 + + 114 + +
+ + + naefsUS +
7
+ 2 + 197 + + 114 + +
+ + + naefsAK +
7
+ 2 + 198 + + 114 + +
+ + + rtmaDV +
7
+ 2 + 198 + + 107 +
+ + hysplit +
7
+ 3 + 36928220 + + 3 + +
+ - RTG-SST-Analysis RTGSST
7
4 @@ -1835,11 +2448,19 @@ 44 RTGSST235 -
1
- GFSGuide + sstP5 +
7
+ 4 + 721360001 + + 44 + +
+ + GFSGuide
7
4 @@ -1850,11 +2471,21 @@ 77 gfsGuide232 -
6
- RTMA + GFSGuide +
7
+ 4 + 361091001 + + 96 + 81 + 77 + +
+ + RTMA
7
4 @@ -1863,11 +2494,19 @@ 109 rtmaNDFD -
1
- + + + RTMA2P5KM +
7
+ 4 + 1971 + + 109 + +
+ - RTMA-Mosaic RTMA-Mosaic
7
4 @@ -1876,11 +2515,9 @@ 109 rtmaNDFD -
1
- AK-RTMA AK-RTMA
7
4 @@ -1889,11 +2526,9 @@ 109 aKrtmaNDFD -
1
- HI-RTMA HI-RTMA
7
4 @@ -1902,11 +2537,9 @@ 109 HIrtmaNDFD -
1
- PR-RTMA PR-RTMA
7
4 @@ -1915,11 +2548,9 @@ 109 PRrtmaNDFD -
1
- + - Guam-RTMA Guam-RTMA
7
4 @@ -1928,11 +2559,9 @@ 109 rtmaNDFD -
1
- RTG-SST-HR-Analysis RTGSSTHR
7
4 @@ -1941,11 +2570,19 @@ 44 rtgssthr173 -
1
- QPE + sst12th +
7
+ 4 + 4321216001 + + 44 + +
+ + QPE
7
4 @@ -1954,11 +2591,59 @@ 182 -
1
- SeaSfcAnalysis21 + ccpaUS +
7
+ 4 + 240 + + 184 + +
+ + + ccpaP5 +
7
+ 4 + 720361001 + + 184 + +
+ + + ccpaP5 +
7
+ 4 + 721361001 + + 184 + +
+ + + ccpaP5 +
7
+ 4 + 722361001 + + 184 + +
+ + + ccpa2 +
7
+ 4 + 375 + + 184 + +
+ + SeaSfcAnalysis21
7
4 @@ -1967,11 +2652,9 @@ 44 -
1
- SeaSfcAnalysis22 SeaSfcAnalysis22
7
4 @@ -1980,10 +2663,8 @@ 44 -
1
- SeaSfcAnalysis23 SeaSfcAnalysis23
7
4 @@ -1992,10 +2673,8 @@ 44 -
1
- SeaSfcAnalysis24 SeaSfcAnalysis24
7
4 @@ -2004,10 +2683,8 @@ 44 -
1
- SeaSfcAnalysis37 SeaSfcAnalysis37
7
4 @@ -2016,10 +2693,8 @@ 44 -
1
- SeaSfcAnalysis38 SeaSfcAnalysis38
7
4 @@ -2028,10 +2703,8 @@ 44 -
1
- SeaSfcAnalysis39 SeaSfcAnalysis39
7
4 @@ -2040,10 +2713,8 @@ 44 -
1
- SeaSfcAnalysis40 SeaSfcAnalysis40
7
4 @@ -2052,10 +2723,8 @@ 44 -
1
- SeaSfcAnalysis41 SeaSfcAnalysis41
7
4 @@ -2064,10 +2733,8 @@ 44 -
1
- SeaSfcAnalysis42 SeaSfcAnalysis42
7
4 @@ -2076,10 +2743,8 @@ 44 -
1
- SeaSfcAnalysis43 SeaSfcAnalysis43
7
4 @@ -2088,10 +2753,8 @@ 44 -
1
- SeaSfcAnalysis44 SeaSfcAnalysis44
7
4 @@ -2100,10 +2763,8 @@ 44 -
1
- SeaSfcAnalysis61 SeaSfcAnalysis61
7
4 @@ -2112,10 +2773,8 @@ 44 -
1
- SeaSfcAnalysis62 SeaSfcAnalysis62
7
4 @@ -2124,10 +2783,8 @@ 44 -
1
- SeaSfcAnalysis63 SeaSfcAnalysis63
7
4 @@ -2136,10 +2793,8 @@ 44 -
1
- SeaSfcAnalysis64 SeaSfcAnalysis64
7
4 @@ -2148,14 +2803,72 @@ 44 -
1
+
+ + + ccpa +
7
+ 4 + 3 + + 184 + +
+ + + ccpa +
7
+ 4 + 361181001 + + 184 + +
+ + + ccpa2P5 +
7
+ 4 + 110 + + 184 + +
+ + + ccpa5K +
7
+ 4 + 197 + + 184 + +
+ + + estofsUS +
7
+ 4 + 1971 + + 14 + +
+ + + estofsPR +
7
+ 4 + 339227-95 + + 14 +
- RFCqpf RFCqpf
7
5 @@ -2164,11 +2877,9 @@ 181 qpf218 -
6
- HPCqpf HPCqpf
7
5 @@ -2177,11 +2888,9 @@ 180 hpc_qpf218 -
6
- HPCGuide HPCGuide
7
5 @@ -2190,12 +2899,10 @@ 183 hpcGuideNDFD -
6
- AK-HPCGuide - AK-HPCGuide + HPCGuide-AK
7
5 198 @@ -2203,25 +2910,9 @@ 183 hpcGuideNDFD -
6
- AK-HPCGuide - AK-HPCGuide -
7
- 5 - 198 - - 0 - - hpcGuideNDFD -
6
-
- - - - HPC HPCqpfNDFD
7
5 @@ -2230,16 +2921,24 @@ 180 HPCqpfNDFD -
6
- + + + HPC-MODEL0 +
7
+ 5 + 198 + + 0 + + +
- OPCWave-W-ATL OPCWave180
7
6 @@ -2248,11 +2947,9 @@ 30 opcWave180 -
24
- OPCWave-NE-PAC OPCWave181
7
6 @@ -2261,7 +2958,6 @@ 30 opcWave181 -
24
@@ -2269,7 +2965,6 @@ - CPCoutlook-Short CPCoutlook-Short
7
7 @@ -2278,11 +2973,9 @@ 201 CPCoutlookShort -
24
- CPCoutlook-Medium CPCoutlook-Medium
7
7 @@ -2291,11 +2984,9 @@ 200 CPCoutlookMedium -
24
- CPCoutlook-Short-AK CPCoutlook-Short-AK
7
7 @@ -2304,11 +2995,9 @@ 201 CPCoutlookShort_AK -
3
- CPCoutlook-Medium-AK CPCoutlook-Medium-AK
7
7 @@ -2317,11 +3006,9 @@ 200 CPCoutlookMedium_AK -
3
- CPCoutlook-Long CPCoutlook211
7
7 @@ -2330,7 +3017,6 @@ 30 CPCoutlook211 -
720
@@ -2338,7 +3024,16 @@ - Aviation + Aviation +
7
+ 8 + 130 + + 105 + +
+ + Aviation
7
8 @@ -2348,11 +3043,9 @@ 105 -
1
- NCWF NCWF
7
8 @@ -2361,16 +3054,45 @@ 190 -
1
true
+ + AWCICING +
7
+ 8 + 255202 + + 191 + +
+ + + AWCTURB +
7
+ 8 + 255202 + + 105 + +
+ + + AVIATION +
7
+ 8 + 255203 + + 191 + 105 + +
+ - + - SPCGuide SPCGuide
7
9 @@ -2379,15 +3101,13 @@ 0 spcGuideNDFD -
1
- + - TPCWindProb TPCWindProb
7
10 @@ -2396,11 +3116,19 @@ 30 tpcWind231 -
6
- OPCWave-TE-PAC + TPCWindProb +
7
+ 10 + 721181001 + + 30 + +
+ + OPCWave182
7
10 @@ -2409,7 +3137,6 @@ 30 opcWave182 -
24
@@ -2417,7 +3144,6 @@ - GriddedMOS MOSGuide
7
14 @@ -2426,11 +3152,9 @@ 96 mosGuideNDFD -
6
- AK-GriddedMOS MOSGuide-AK
7
14 @@ -2439,11 +3163,9 @@ 96 mosGuideNDFD_AK -
3
- GFSLAMP-Grid GFSLAMPTstorm
7
14 @@ -2452,11 +3174,9 @@ 108 lampNDFD -
1
- TPCSurgeProb TPCSurgeProb
7
14 @@ -2466,11 +3186,9 @@ 0 TPCSurgeProb -
6
- TPCSurgeProb197 TPCSurgeProb197
7
14 @@ -2479,11 +3197,9 @@ 12 TPCSurgeProb -
6
- TPCSurgeProb-AK TPCSurgeProb-AK
7
14 @@ -2492,11 +3208,9 @@ 12 TPCSurgeProb -
6
- PROB3HR PROB3HR
7
14 @@ -2505,9 +3219,8 @@ 0 -
3
- \ No newline at end of file + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NOAA-161.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NOAA-161.xml similarity index 85% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NOAA-161.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NOAA-161.xml index 60dd729713..8d93936b18 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NOAA-161.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NOAA-161.xml @@ -13,7 +13,6 @@ - GLERL GLERL
161
1 @@ -22,7 +21,17 @@ 99 glerl -
12
+
+ + + GLERL +
161
+ 1 + 176 + + 99 + + glerl
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NWSTG-8.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NWSTG-8.xml similarity index 96% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NWSTG-8.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NWSTG-8.xml index c5b6a490cf..512872ddf1 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_NWSTG-8.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_NWSTG-8.xml @@ -13,7 +13,6 @@ - RCM RCM
8
0 @@ -22,7 +21,6 @@ 0 -
1
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_RFC-9.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_RFC-9.xml similarity index 83% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_RFC-9.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_RFC-9.xml index 9b08d6e316..d02fd64208 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_RFC-9.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_RFC-9.xml @@ -13,7 +13,6 @@ - MPE MPE-Local
9
0 @@ -22,11 +21,9 @@ 160 localMPE -
1
- MPE MPE-Mosaic
9
0 @@ -35,11 +32,9 @@ 161 mosaicMPE -
1
- HPE HPE
9
0 @@ -48,11 +43,9 @@ 165 localHPE -
300
- BiasHPE BHPE
9
0 @@ -61,7 +54,6 @@ 166 localBHPE -
300
@@ -69,7 +61,6 @@ - QPE-SJU QPE-SJU
9
105 @@ -78,11 +69,9 @@ 152 -
1
- QPE-Manual-SJU QPE-Manual-SJU
9
105 @@ -91,11 +80,9 @@ 158 -
1
- QPE-Auto-SJU QPE-Auto-SJU
9
105 @@ -104,11 +91,9 @@ 159 -
1
- MPE-Local-SJU MPE-Local-SJU
9
105 @@ -117,11 +102,9 @@ 160 -
1
- MPE-Mosaic-SJU MPE-Mosaic-SJU
9
105 @@ -130,11 +113,9 @@ 161 -
1
- QPE-XNAV-SJU QPE-XNAV-SJU
9
105 @@ -143,11 +124,9 @@ 171 -
1
- QPE-RFC-SJU QPE-RFC-SJU
9
105 @@ -156,7 +135,6 @@ 172 -
1
@@ -164,7 +142,6 @@ - QPF-TUA RFCqpf
9
150 @@ -173,11 +150,9 @@ 180 qpf218 -
6
- FFG-TUA FFG-TUA
9
150 @@ -186,11 +161,9 @@ 151 -
1
- QPE-TUA QPE-TUA
9
150 @@ -199,11 +172,9 @@ 152 -
1
- QPE-Manual-TUA QPE-Manual-TUA
9
150 @@ -212,11 +183,9 @@ 158 -
1
- QPE-Auto-TUA QPE-Auto-TUA
9
150 @@ -225,11 +194,9 @@ 159 -
1
- MPE-Local-TUA MPE-Local-TUA
9
150 @@ -238,11 +205,9 @@ 160 -
1
- MPE-Mosaic-TUA MPE-Mosaic-TUA
9
150 @@ -251,11 +216,9 @@ 161 -
1
- QPE-XNAV-TUA QPE-XNAV-TUA
9
150 @@ -264,11 +227,9 @@ 171 -
1
- QPE-RFC-TUA QPE-RFC-TUA
9
150 @@ -277,7 +238,6 @@ 172 -
1
@@ -285,7 +245,6 @@ - QPF-ACR RFCqpf
9
151 @@ -294,11 +253,9 @@ 180 qpf218 -
6
- FFG-ACR FFG-ACR
9
151 @@ -307,11 +264,9 @@ 151 -
1
- QPE-ACR QPE-ACR
9
151 @@ -320,11 +275,9 @@ 152 -
1
- QPE-Manual-ACR QPE-Manual-ACR
9
151 @@ -333,11 +286,9 @@ 158 -
1
- QPE-Auto-ACR QPE-Auto-ACR
9
151 @@ -346,11 +297,9 @@ 159 -
1
- MPE-Local-ACR MPE-Local-ACR
9
151 @@ -359,11 +308,9 @@ 160 -
1
- MPE-Mosaic-ACR MPE-Mosaic-ACR
9
151 @@ -372,11 +319,9 @@ 161 -
1
- QPE-XNAV-ACR QPE-XNAV-ACR
9
151 @@ -385,11 +330,9 @@ 171 -
1
- QPE-RFC-ACR QPE-RFC-ACR
9
151 @@ -398,7 +341,6 @@ 172 -
1
@@ -406,7 +348,6 @@ - QPF-STR RFCqpf
9
152 @@ -415,11 +356,9 @@ 180 qpf218 -
6
- FFG-STR FFG-STR
9
152 @@ -428,11 +367,9 @@ 151 -
1
- QPE-STR QPE-STR
9
152 @@ -441,11 +378,9 @@ 152 -
1
- QPE-Manual-STR QPE-Manual-STR
9
152 @@ -454,11 +389,9 @@ 158 -
1
- QPE-Auto-STR QPE-Auto-STR
9
152 @@ -467,11 +400,9 @@ 159 -
1
- MPE-Local-STR MPE-Local-STR
9
152 @@ -480,11 +411,9 @@ 160 -
1
- MPE-Mosaic-STR MPE-Mosaic-STR
9
152 @@ -493,11 +422,9 @@ 161 -
1
- QPE-XNAV-STR QPE-XNAV-STR
9
152 @@ -506,11 +433,9 @@ 171 -
1
- QPE-RFC-STR QPE-RFC-STR
9
152 @@ -519,7 +444,6 @@ 172 -
1
@@ -527,7 +451,6 @@ - QPF-RSA RFCqpf
9
153 @@ -536,11 +459,9 @@ 180 qpf218 -
6
- FFG-RSA FFG-RSA
9
153 @@ -549,11 +470,9 @@ 151 -
1
- QPE-RSA QPE-RSA
9
153 @@ -562,11 +481,9 @@ 152 -
1
- QPE-Manual-RSA QPE-Manual-RSA
9
153 @@ -575,11 +492,9 @@ 158 -
1
- QPE-Auto-RSA QPE-Auto-RSA
9
153 @@ -588,11 +503,9 @@ 159 -
1
- MPE-Local-RSA MPE-Local-RSA
9
153 @@ -601,11 +514,9 @@ 160 -
1
- MPE-Mosaic-RSA MPE-Mosaic-RSA
9
153 @@ -614,11 +525,9 @@ 161 -
1
- QPE-XNAV-RSA QPE-XNAV-RSA
9
153 @@ -627,11 +536,9 @@ 171 -
1
- QPE-RFC-RSA QPE-RFC-RSA
9
153 @@ -640,7 +547,6 @@ 172 -
1
@@ -648,7 +554,6 @@ - QPF-ORN RFCqpf
9
154 @@ -657,11 +562,9 @@ 180 qpf218 -
6
- FFG-ORN FFG-ORN
9
154 @@ -670,11 +573,9 @@ 151 -
1
- QPE-ORN QPE-ORN
9
154 @@ -683,11 +584,9 @@ 152 -
1
- QPE-Manual-ORN QPE-Manual-ORN
9
154 @@ -696,11 +595,9 @@ 158 -
1
- QPE-Auto-ORN QPE-Auto-ORN
9
154 @@ -709,11 +606,9 @@ 159 -
1
- MPE-Local-ORN MPE-Local-ORN
9
154 @@ -722,11 +617,9 @@ 160 -
1
- MPE-Mosaic-ORN MPE-Mosaic-ORN
9
154 @@ -735,11 +628,9 @@ 161 -
1
- QPE-XNAV-ORN QPE-XNAV-ORN
9
154 @@ -748,11 +639,9 @@ 171 -
1
- QPE-RFC-ORN QPE-RFC-ORN
9
154 @@ -761,7 +650,6 @@ 172 -
1
@@ -769,7 +657,6 @@ - QPF-RHA RFCqpf
9
155 @@ -778,11 +665,9 @@ 180 qpf218 -
6
- FFG-RHA FFG-RHA
9
155 @@ -791,11 +676,9 @@ 151 -
1
- QPE-RHA QPE-RHA
9
155 @@ -804,11 +687,9 @@ 152 -
1
- QPE-Manual-RHA QPE-Manual-RHA
9
155 @@ -817,11 +698,9 @@ 158 -
1
- QPE-Auto-RHA QPE-Auto-RHA
9
155 @@ -830,11 +709,9 @@ 159 -
1
- MPE-Local-RHA MPE-Local-RHA
9
155 @@ -843,11 +720,9 @@ 160 -
1
- MPE-Mosaic-RHA MPE-Mosaic-RHA
9
155 @@ -856,11 +731,9 @@ 161 -
1
- QPE-XNAV-RHA QPE-XNAV-RHA
9
155 @@ -869,11 +742,9 @@ 171 -
1
- QPE-RFC-RHA QPE-RFC-RHA
9
155 @@ -882,7 +753,6 @@ 172 -
1
@@ -890,7 +760,6 @@ - QPF-KRF RFCqpf
9
156 @@ -899,11 +768,9 @@ 180 qpf218 -
6
- FFG-KRF FFG-KRF
9
156 @@ -912,11 +779,9 @@ 151 -
1
- QPE-KRF QPE-KRF
9
156 @@ -925,11 +790,9 @@ 152 -
1
- QPE-Manual-KRF QPE-Manual-KRF
9
156 @@ -938,11 +801,9 @@ 158 -
1
- QPE-Auto-KRF QPE-Auto-KRF
9
156 @@ -951,11 +812,9 @@ 159 -
1
- MPE-Local-KRF MPE-Local-KRF
9
156 @@ -964,11 +823,9 @@ 160 -
1
- MPE-Mosaic-KRF MPE-Mosaic-KRF
9
156 @@ -977,11 +834,9 @@ 161 -
1
- QPE-XNAV-KRF QPE-XNAV-KRF
9
156 @@ -990,11 +845,9 @@ 171 -
1
- QPE-RFC-KRF QPE-RFC-KRF
9
156 @@ -1003,7 +856,6 @@ 172 -
1
@@ -1011,7 +863,6 @@ - QPF-MSR RFCqpf
9
157 @@ -1020,11 +871,9 @@ 180 qpf218 -
6
- FFG-MSR FFG-MSR
9
157 @@ -1033,11 +882,9 @@ 151 -
1
- QPE-MSR QPE-MSR
9
157 @@ -1046,11 +893,9 @@ 152 -
1
- QPE-Manual-MSR QPE-Manual-MSR
9
157 @@ -1059,11 +904,9 @@ 158 -
1
- QPE-Auto-MSR QPE-Auto-MSR
9
157 @@ -1072,11 +915,9 @@ 159 -
1
- MPE-Local-MSR MPE-Local-MSR
9
157 @@ -1085,11 +926,9 @@ 160 -
1
- MPE-Mosaic-MSR MPE-Mosaic-MSR
9
157 @@ -1098,11 +937,9 @@ 161 -
1
- QPE-XNAV-MSR QPE-XNAV-MSR
9
157 @@ -1111,11 +948,9 @@ 171 -
1
- QPE-RFC-MSR QPE-RFC-MSR
9
157 @@ -1124,7 +959,6 @@ 172 -
1
@@ -1132,7 +966,6 @@ - QPF-TAR RFCqpf
9
158 @@ -1141,11 +974,9 @@ 180 qpf218 -
6
- FFG-TAR FFG-TAR
9
158 @@ -1154,11 +985,9 @@ 151 -
1
- QPE-TAR QPE-TAR
9
158 @@ -1167,11 +996,9 @@ 152 -
1
- QPE-Manual-TAR QPE-Manual-TAR
9
158 @@ -1180,11 +1007,9 @@ 158 -
1
- QPE-Auto-TAR QPE-Auto-TAR
9
158 @@ -1193,11 +1018,9 @@ 159 -
1
- MPE-Local-TAR MPE-Local-TAR
9
158 @@ -1206,11 +1029,9 @@ 160 -
1
- MPE-Mosaic-TAR MPE-Mosaic-TAR
9
158 @@ -1219,11 +1040,9 @@ 161 -
1
- QPE-XNAV-TAR QPE-XNAV-TAR
9
158 @@ -1232,11 +1051,9 @@ 171 -
1
- QPE-RFC-TAR QPE-RFC-TAR
9
158 @@ -1245,7 +1062,6 @@ 172 -
1
@@ -1253,7 +1069,6 @@ - QPF-PTR RFCqpf
9
159 @@ -1262,11 +1077,9 @@ 180 qpf218 -
6
- FFG-PTR FFG-PTR
9
159 @@ -1275,11 +1088,9 @@ 151 -
1
- QPE-PTR QPE-PTR
9
159 @@ -1288,11 +1099,9 @@ 152 -
1
- QPE-Manual-PTR QPE-Manual-PTR
9
159 @@ -1301,11 +1110,9 @@ 158 -
1
- QPE-Auto-PTR QPE-Auto-PTR
9
159 @@ -1314,11 +1121,9 @@ 159 -
1
- MPE-Local-PTR MPE-Local-PTR
9
159 @@ -1327,11 +1132,9 @@ 160 -
1
- MPE-Mosaic-PTR MPE-Mosaic-PTR
9
159 @@ -1340,11 +1143,9 @@ 161 -
1
- QPE-XNAV-PTR QPE-XNAV-PTR
9
159 @@ -1353,11 +1154,9 @@ 171 -
1
- QPE-RFC-PTR QPE-RFC-PTR
9
159 @@ -1366,7 +1165,6 @@ 172 -
1
@@ -1374,7 +1172,6 @@ - QPF-TIR RFCqpf
9
160 @@ -1383,11 +1180,9 @@ 180 qpf218 -
6
- FFG-TIR FFG-TIR
9
160 @@ -1396,11 +1191,9 @@ 151 -
1
- FFG-TIR-HiRes FFG-TIR-HiRes
9
160 @@ -1409,11 +1202,9 @@ 151 -
1
- QPE-TIR QPE-TIR
9
160 @@ -1422,11 +1213,9 @@ 152 -
1
- QPE-Manual-TIR QPE-Manual-TIR
9
160 @@ -1435,11 +1224,9 @@ 158 -
1
- QPE-Auto-TIR QPE-Auto-TIR
9
160 @@ -1448,11 +1235,9 @@ 159 -
1
- MPE-Local-TIR MPE-Local-TIR
9
160 @@ -1461,11 +1246,9 @@ 160 -
1
- MPE-Mosaic-TIR MPE-Mosaic-TIR
9
160 @@ -1474,11 +1257,9 @@ 161 -
1
- QPE-XNAV-TIR QPE-XNAV-TIR
9
160 @@ -1487,11 +1268,9 @@ 171 -
1
- QPE-RFC-TIR QPE-RFC-TIR
9
160 @@ -1500,7 +1279,6 @@ 172 -
1
@@ -1508,7 +1286,6 @@ - QPF-ALR RFCqpf
9
161 @@ -1517,11 +1294,9 @@ 180 qpf218 -
6
- FFG-ALR FFG-ALR
9
161 @@ -1530,11 +1305,9 @@ 151 -
1
- QPE-ALR QPE-ALR
9
161 @@ -1543,11 +1316,9 @@ 152 -
1
- QPE-Manual-ALR QPE-Manual-ALR
9
161 @@ -1556,11 +1327,9 @@ 158 -
1
- QPE-Auto-ALR QPE-Auto-ALR
9
161 @@ -1569,11 +1338,9 @@ 159 -
1
- MPE-Local-ALR MPE-Local-ALR
9
161 @@ -1582,11 +1349,9 @@ 160 -
1
- MPE-Mosaic-ALR MPE-Mosaic-ALR
9
161 @@ -1595,11 +1360,9 @@ 161 -
1
- QPE-XNAV-ALR QPE-XNAV-ALR
9
161 @@ -1608,11 +1371,9 @@ 171 -
1
- QPE-RFC-ALR QPE-RFC-ALR
9
161 @@ -1621,7 +1382,6 @@ 172 -
1
@@ -1629,7 +1389,6 @@ - QPF-FWR RFCqpf
9
162 @@ -1638,11 +1397,9 @@ 180 qpf218 -
6
- FFG-FWR FFG-FWR
9
162 @@ -1651,11 +1408,9 @@ 151 -
1
- QPE-FWR QPE-FWR
9
162 @@ -1664,11 +1419,9 @@ 152 -
1
- QPE-Manual-FWR QPE-Manual-FWR
9
162 @@ -1677,11 +1430,9 @@ 158 -
1
- QPE-Auto-FWR QPE-Auto-FWR
9
162 @@ -1690,11 +1441,9 @@ 159 -
1
- MPE-Local-FWR MPE-Local-FWR
9
162 @@ -1703,11 +1452,9 @@ 160 -
1
- MPE-Mosaic-FWR MPE-Mosaic-FWR
9
162 @@ -1716,11 +1463,9 @@ 161 -
1
- QPE-XNAV-FWR QPE-XNAV-FWR
9
162 @@ -1729,11 +1474,9 @@ 171 -
1
- QPE-RFC-FWR QPE-RFC-FWR
9
162 @@ -1742,7 +1485,6 @@ 172 -
1
@@ -1750,7 +1492,6 @@ - NOHRSC-SNOW NOHRSC-SNOW
9
163 @@ -1760,11 +1501,9 @@ 255 -
1
- NOHRSC-SNOW NOHRSC-SNOW
9
163 @@ -1773,7 +1512,6 @@ 185 -
24
true
@@ -1782,7 +1520,6 @@ - SPE AUTOSPE
9
170 @@ -1791,11 +1528,9 @@ 190 -
1
- SPE MANSPE
9
170 @@ -1804,7 +1539,6 @@ 191 -
1
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_RSMC-54.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_RSMC-54.xml new file mode 100644 index 0000000000..a61ffe83a7 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_RSMC-54.xml @@ -0,0 +1,167 @@ + + + + + + + + + + CanadianModel +
54
+ 0 + 999001 + + 41 + + localMPE +
+ + + CanadianModel +
54
+ 0 + 21 + + 41 + + localMPE +
+ + + + cmce +
54
+ 2 + 401 + + 70 + +
+ + + cmce +
54
+ 2 + 362181001 + + 70 + +
+ + + cmce +
54
+ 2 + 362181002 + + 70 + +
+ + + cmce +
54
+ 2 + 2291 + + 70 + +
+ + + cmce +
54
+ 2 + 361181002 + + 70 + +
+ + + cmc +
54
+ 0 + 2291 + + 47 + +
+ + + cmc +
54
+ 0 + 361181002 + + 47 + +
+ + + cmc +
54
+ 0 + 374 + + 47 + +
+ + + cmc +
54
+ 0 + 401 + + 47 + +
+ + + cmc +
54
+ 0 + 362181001 + + 47 + +
+ + + cmc +
54
+ 0 + 362181002 + + 47 + +
+ + + cmcP6 +
53
+ 0 + 602151001 + + 47 + +
+ + + CMCQLM +
54
+ 2 + -90045000 + + 70 + +
+
diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_UKMET-74.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_UKMET-74.xml similarity index 77% rename from edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_UKMET-74.xml rename to edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_UKMET-74.xml index 78220029c0..12ea989bb2 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/common_static/base/grid/models/gribModels_UKMET-74.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/models/gribModels_UKMET-74.xml @@ -11,9 +11,8 @@ - + - UKMET-MODEL1 UKMET-MODEL1
74
0 @@ -24,12 +23,10 @@ 89 ukmetNH -
6
- + - UKMET UKMET-NorthernHemisphere
74
0 @@ -40,11 +37,9 @@ 45 ukmetNH -
6
- UKMET UKMET37
74
0 @@ -55,11 +50,9 @@ 45 ukmetNH -
6
- UKMET UKMET38
74
0 @@ -70,11 +63,9 @@ 45 ukmetNH -
6
- UKMET UKMET39
74
0 @@ -85,11 +76,9 @@ 45 ukmetNH -
6
- UKMET UKMET40
74
0 @@ -100,11 +89,9 @@ 45 ukmetNH -
6
- UKMET UKMET41
74
0 @@ -115,11 +102,9 @@ 45 ukmetNH -
6
- UKMET UKMET42
74
0 @@ -130,11 +115,9 @@ 45 ukmetNH -
6
- UKMET UKMET43
74
0 @@ -145,11 +128,9 @@ 45 ukmetNH -
6
- UKMET UKMET44
74
0 @@ -160,9 +141,61 @@ 45 ukmetNH -
6
- + + + ukmet +
74
+ 0 + 45 + + 15 + 44 + 45 + + ukmetNH +
+ + + ukmet2 +
74
+ 0 + 289145001 + + 15 + 44 + 45 + + ukmetNH + +
+ + + ukmet228 +
74
+ 0 + 228 + + 15 + 44 + 45 + + ukmetNH +
+ + + ukmet228 +
74
+ 0 + 145073001 + + 15 + 44 + 45 + + ukmetNH +
+ - -
\ No newline at end of file + + diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/ecmwf.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/ecmwf.xml index bf1cd78b0a..86e431ec4d 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/ecmwf.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/ecmwf.xml @@ -2,46 +2,26 @@ 0 - 21600 43200 - 64800 86400 - 108000 129600 - 151200 172800 - 194400 216000 - 237600 259200 - 280800 302400 - 324000 345600 - 367200 388800 - 410400 432000 - 453600 475200 - 496800 518400 - 540000 561600 - 583200 604800 - 626400 648000 - 669600 691200 - 712800 734400 - 756000 777600 - 799200 820800 - 842400 - 864000 + 864000 staticXspacing @@ -110,7 +90,7 @@ - tp6hr + tp_ecmwf total precipitation mm millimeter diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpcGuideNDFD.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpcGuideNDFD.xml index f013c5ed1b..afb2131a42 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpcGuideNDFD.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpcGuideNDFD.xml @@ -1,160 +1,165 @@ - + - - 302400 - 324000 - 345600 - 367200 - 388800 - 410400 - 432000 - 453600 - 475200 - 496800 - 518400 - 540000 - 561600 - 583200 - 604800 - 626400 - 648000 - - - mnt - Minimum Temperature - K - degree_Kelvin - minT - 180.0 - 330.0 - -99999.0 - 1 - FHAG 2 - - FHAG2 - - - - pop - Probability of precip Delta - % - percent - PcpProb - 0.0 - 100.0 - -99999.0 - 0 - SFC - - SFC - - - - staticSpacing - Grid spacing - meters - -99999.0 - - - tcc - Total Cloud Cover - % - percent - totalCldCvr - 0.0 - 100.0 - -99999.0 - 0 - EA - - EA - - - - wd - Wind Direction - degreeTrue - degree_True - windDir - 0.0 - 360.0 - -99999.0 - 1 - FHAG 10 - - FHAG10 - - - - mxt - Maximum Temperature - K - degree_Kelvin - maxT - 180.0 - 330.0 - -99999.0 - 1 - FHAG 2 - - FHAG2 - - - - staticCoriolis - Coriolis parameter - /second - -99999.0 - - - ws - Wind Speed - m/s - meter/sec - windSpeed - -150.0 - 150.0 - -99999.0 - 1 - FHAG 10 - - FHAG10 - - - - wxType - Weather - - - Weather - 0.0 - 12.0 - -99999.0 - 0 - SFC - - SFC - - - - dpt - Dewpoint Temperature - K - degree_Kelvin - Td - 180.0 - 330.0 - -99999.0 - 1 - FHAG 2 - - FHAG2 - - - - staticTopo - Topography - meters - -99999.0 - - + + 302400 + 324000 + 345600 + 367200 + 388800 + 410400 + 432000 + 453600 + 475200 + 496800 + 518400 + 540000 + 561600 + 583200 + 604800 + 626400 + 648000 + + + mxt + Maximum Temperature + K + degree_Kelvin + maxT + 180.0 + 330.0 + -99999.0 + 1 + FHAG 2 + + + staticSpacing + Grid spacing + m + -99999.0 + 0 + + + mnt + Minimum Temperature + K + degree_Kelvin + minT + 180.0 + 330.0 + -99999.0 + 1 + FHAG 2 + + + pop + Probability of precip Delta + % + percent + PcpProb + 0.0 + 100.0 + -99999.0 + 0 + SFC + + + staticTopo + Topography + m + -99999.0 + 0 + + + ws + Wind Speed + m/s + meter/sec + windSpeed + -150.0 + 150.0 + -99999.0 + 1 + FHAG 10 + + + tcc + Total Cloud Cover + % + percent + totalCldCvr + 0.0 + 100.0 + -99999.0 + 0 + EA + + + dpt + Dewpoint Temperature + K + degree_Kelvin + Td + 180.0 + 330.0 + -99999.0 + 1 + FHAG 2 + + + wx + Weather + + + Weather + 0.0 + 10.0 + -99999.0 + 0 + SFC + + + reftime + reference time + seconds since (1970-1-1 00:00:00.0) + 0.0 + 0 + + + staticCoriolis + Coriolis parameter + s^-1 + -99999.0 + 0 + + + valtimeMINUSreftime + seconds + 0.0 + 0 + + + wd + Wind Direction + degreeTrue + degree_True + windDir + 0.0 + 360.0 + -99999.0 + 1 + FHAG 10 + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpc_qpf218.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpc_qpf218.xml index db70a0b28c..e3f2de13d0 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpc_qpf218.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/parameterInfo/hpc_qpf218.xml @@ -16,7 +16,7 @@ 259200 - tpHPC + tp_HPC 6 hr Total Precip mm millimeter diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/postProcessModels/postProcessedModels.txt b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/postProcessModels/postProcessedModels.txt new file mode 100644 index 0000000000..ae96f585d8 --- /dev/null +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/postProcessModels/postProcessedModels.txt @@ -0,0 +1,80 @@ +# RUC130 PostProcessor +RUC130:com.raytheon.edex.plugin.grib.decoderpostprocessors.RUC130GribPostProcessor + +# Generate 6Hr Records Post Processor +ECMWF-HiRes:com.raytheon.edex.plugin.grib.decoderpostprocessors.ECMWFHiResProcessor +GFS213:com.raytheon.edex.plugin.grib.decoderpostprocessors.GFSProcessor + +# Post Processor For Lifted Index, if the ability to limit post processing to specific +# parameters is ever added this would be better done there +ETA:com.raytheon.edex.plugin.grib.decoderpostprocessors.Nam80PostProcessor +ETA218:com.raytheon.edex.plugin.grib.decoderpostprocessors.LiftedIndexPostProcessor +ETA242:com.raytheon.edex.plugin.grib.decoderpostprocessors.LiftedIndexPostProcessor +GFS212:com.raytheon.edex.plugin.grib.decoderpostprocessors.LiftedIndexPostProcessor +GFS213:com.raytheon.edex.plugin.grib.decoderpostprocessors.LiftedIndexPostProcessor + +# Ensemble Grids that need to be stitched together +AVN37:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +AVN38:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +AVN39:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +AVN40:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF1:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF2:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF3:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF4:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF5:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF6:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF7:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ECMF8:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ENSEMBLE37:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ENSEMBLE38:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ENSEMBLE39:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +ENSEMBLE40:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +UKMET37:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +UKMET38:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +UKMET39:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler +UKMET40:com.raytheon.edex.plugin.grib.decoderpostprocessors.EnsembleGridAssembler + +# FFG grids +FFG-TIR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-RSA:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-ORN:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-FWR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-MSR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-TUA:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-ALR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-RHA:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-STR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-KRF:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-ACR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-PTR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor +FFG-TAR:com.raytheon.edex.plugin.grib.decoderpostprocessors.FFGGribPostProcessor + +#RFCqpf grids +RFCqpf:com.raytheon.edex.plugin.grib.decoderpostprocessors.OverwriteGribPostProcessor +#MPE-Local grids +MPE-Local:com.raytheon.edex.plugin.grib.decoderpostprocessors.OverwriteGribPostProcessor +MPE-Mosaic:com.raytheon.edex.plugin.grib.decoderpostprocessors.OverwriteGribPostProcessor + +#RTMA grids +RTMA:com.raytheon.edex.plugin.grib.decoderpostprocessors.RTMAGribPostProcessor + +#LAPS grids +LAPS:com.raytheon.edex.plugin.grib.decoderpostprocessors.LapsPostProcessor + +#TPC grids +CPCoutlook211:com.raytheon.edex.plugin.grib.decoderpostprocessors.CPCoutlookGribPostProcessor + +#MSAS grids +MSAS:com.raytheon.edex.plugin.grib.decoderpostprocessors.MSASPostProcessor + +#HPCqpf grids +HPCqpf:com.raytheon.edex.plugin.grib.decoderpostprocessors.OverwriteGribPostProcessor +HPCqpfNDFD:com.raytheon.edex.plugin.grib.decoderpostprocessors.OverwriteGribPostProcessor + +#Canadian GEM grids +Canadian-Reg:com.raytheon.edex.plugin.grib.decoderpostprocessors.CanadianRegPostProcessor +Canadian-NH:com.raytheon.edex.plugin.grib.decoderpostprocessors.CanadianNHPostProcessor + +# RUC236 PostProcessor +RUC236:com.raytheon.edex.plugin.grib.decoderpostprocessors.RUC236GribPostProcessor \ No newline at end of file diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/subgrids/HPCGuideClip.xml b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/subgrids/HPCGuideClip.xml index ab94f7dc86..322118d976 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/subgrids/HPCGuideClip.xml +++ b/edexOsgi/com.raytheon.edex.plugin.grib/utility/edex_static/base/grib/subgrids/HPCGuideClip.xml @@ -20,7 +20,7 @@ --> HPCGuide - HPCGuide + 197 1000 689 HiResW-ARW-East HiResW-NMM-East - HiResW-ARW-East + 255001 350 350 HiResW-ARW-West HiResW-NMM-West - HiResW-ARW-West + 255002 350 350 NamDNG5 - NamDNG5 + 197 1000 689 RTMA - RTMA + 197 1000 689 TPCSurgeProb - TPCSurgeProb + 374 1300 1200 ETA218 - ETA218 + 218 175 175 GFSLAMPTstorm - GFSLAMPTstorm + 197 1000 689 mesoEta212 mesoEta215 ETA212 - mesoEta215 + 215 175 173 MOSGuide - MOSGuide + 197 350 350 MOSGuide-AK - MOSGuide-AK + 1023 1649 1105 HPCqpf - RFCqpf + 226 175 175 RUC130 - RUC130 + 130 175 175 + @@ -22,7 +23,7 @@ - + diff --git a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/AbstractPrivilegedLocalizationRequestHandler.java b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/AbstractPrivilegedLocalizationRequestHandler.java index 4e7e1659db..e5709ca09a 100644 --- a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/AbstractPrivilegedLocalizationRequestHandler.java +++ b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/AbstractPrivilegedLocalizationRequestHandler.java @@ -19,6 +19,9 @@ **/ package com.raytheon.edex.services; +import java.io.File; + +import com.raytheon.uf.common.auth.exception.AuthorizationException; import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.localization.LocalizationContext; @@ -27,7 +30,6 @@ import com.raytheon.uf.edex.auth.AuthManager; import com.raytheon.uf.edex.auth.AuthManagerFactory; import com.raytheon.uf.edex.auth.req.AbstractPrivilegedRequestHandler; import com.raytheon.uf.edex.auth.resp.AuthorizationResponse; -import com.raytheon.uf.edex.auth.roles.IRole; import com.raytheon.uf.edex.auth.roles.IRoleStorage; /** @@ -39,8 +41,8 @@ import com.raytheon.uf.edex.auth.roles.IRoleStorage; * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Jul 6, 2011 mschenke Initial creation - * + * Jul 6, 2011 mschenke Initial creation + * Jul 8, 2012 719 mpduff Fix order of checks * * * @author mschenke @@ -49,10 +51,13 @@ import com.raytheon.uf.edex.auth.roles.IRoleStorage; */ public abstract class AbstractPrivilegedLocalizationRequestHandler extends AbstractPrivilegedRequestHandler { + + private static final String APPLICATION = "Localization"; protected AuthorizationResponse getAuthorizationResponse(IUser user, LocalizationContext context, LocalizationLevel level, - String fileName, String myContextName) { + String fileName, String myContextName) + throws AuthorizationException { String contextName = context.getContextName(); if (level.isSystemLevel()) { @@ -68,15 +73,15 @@ public abstract class AbstractPrivilegedLocalizationRequestHandler 0) { if (contextName != null) { roleId += "." + contextName; @@ -85,43 +90,50 @@ public abstract class AbstractPrivilegedLocalizationRequestHandler.(.)/type/path/name/ + int minIndex = roleId.length(); + roleId += File.separator + fileName; + int index = roleId.length(); + + while (index > minIndex) { + roleId = roleId.substring(0, index); + + if (roleStorage.isAuthorized(roleId, user.uniqueId().toString(), APPLICATION)) { + return new AuthorizationResponse(true); + } + + index = roleId.lastIndexOf(File.separator, index - 1); + } + + roleId = "com.raytheon.localization." + + context.getLocalizationLevel().name(); + if (i > 0) { + if (contextName != null) { + roleId += "." + contextName; + } else { + // We already checked this case + break; + } + } + // com.raytheon.localization..() - if (checkRole(roles, roleId, user)) { + if (roleStorage.isAuthorized(roleId, user.uniqueId().toString(), APPLICATION)) { return new AuthorizationResponse(true); } // com.raytheon.localization..(.)/type roleId += "/" + context.getLocalizationType().name(); - if (checkRole(roles, roleId, user)) { + + if (roleStorage.isAuthorized(roleId, user.uniqueId().toString(), APPLICATION)) { return new AuthorizationResponse(true); } - - // check most specific to least specific - // com.raytheon.localization..(.)/type/path/name/ - int minIndex = roleId.length(); - roleId += "/" + fileName; - int index = roleId.length(); - while (index > minIndex && isValid) { - roleId = roleId.substring(0, index); - IRole role = roles.lookupRole(roleId); - index = roleId.lastIndexOf("/", index - 1); - if (role.validForUser(user)) { - return new AuthorizationResponse(true); - } else if (!roles.isDefaultRole(role)) { - // if not valid for user and is not default role then not - // authorized. - isValid = false; - } - } + } - + return new AuthorizationResponse(false, "User, " + user.uniqueId() + ", is not authorized to perform request needing role: " + roleId); } - - private boolean checkRole(IRoleStorage roles, String roleId, IUser user) { - IRole role = roles.lookupRole(roleId); - return (role != null && role.validForUser(user)); - } } diff --git a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/GetServersHandler.java b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/GetServersHandler.java index ce5d246eb6..fe95dbbd70 100644 --- a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/GetServersHandler.java +++ b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/GetServersHandler.java @@ -19,12 +19,15 @@ **/ package com.raytheon.edex.services; +import java.util.Collections; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.raytheon.uf.common.localization.msgs.GetServersRequest; import com.raytheon.uf.common.localization.msgs.GetServersResponse; import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.util.registry.GenericRegistry; import com.raytheon.uf.edex.core.props.PropertiesFactory; /** @@ -37,6 +40,7 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 6, 2009 mschenke Initial creation + * Sep 12, 2012 1167 djohnson Add datadelivery servers. * * * @@ -44,7 +48,8 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory; * @version 1.0 */ -public class GetServersHandler implements IRequestHandler { +public class GetServersHandler extends GenericRegistry + implements IRequestHandler { private static final Log logger = LogFactory.getLog(UtilityManager.class); @@ -59,6 +64,7 @@ public class GetServersHandler implements IRequestHandler { logger.info("http.server=" + httpServer); logger.info("jms.server=" + jmsServer); logger.info("pypies.server=" + pypiesServer); + logger.info("server locations=" + registry); String hdf5DataDir = PropertiesFactory.getInstance().getEnvProperties() .getEnvValue("HDF5DIR"); @@ -67,7 +73,8 @@ public class GetServersHandler implements IRequestHandler { response.setJmsServer(jmsServer); response.setPypiesServer(pypiesServer); response.setServerDataDir(hdf5DataDir); + response.setServerLocations(Collections.unmodifiableMap(this.registry)); + return response; } - } diff --git a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/LocalizationStreamHandler.java b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/LocalizationStreamHandler.java index 07432fde50..08d8319ffa 100644 --- a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/LocalizationStreamHandler.java +++ b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/LocalizationStreamHandler.java @@ -27,7 +27,10 @@ import java.util.HashMap; import java.util.Map; import com.raytheon.edex.utility.ProtectedFiles; +import com.raytheon.uf.common.auth.exception.AuthorizationException; import com.raytheon.uf.common.auth.user.IUser; +import com.raytheon.uf.common.localization.FileLocker; +import com.raytheon.uf.common.localization.FileLocker.Type; import com.raytheon.uf.common.localization.FileUpdatedMessage; import com.raytheon.uf.common.localization.FileUpdatedMessage.FileChangeType; import com.raytheon.uf.common.localization.LocalizationContext; @@ -168,6 +171,8 @@ public class LocalizationStreamHandler private Object handleStreamingGet(LocalizationStreamGetRequest request, File file) throws Exception { + // TODO: Copy file to tmp location named from request unique id and + // stream that file for the request to avoid put/delete/read issues FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); @@ -213,8 +218,8 @@ public class LocalizationStreamHandler if (file.getParentFile().exists() == false) { file.getParentFile().mkdirs(); } - File tmpFile = new File(file.getParentFile(), file.getName() + "." - + request.getId()); + File tmpFile = new File(file.getParentFile(), "." + file.getName() + + "." + request.getId()); if ((tmpFile.exists() == false) && (request.getOffset() != 0)) { throw new LocalizationException( "Illegal state, request has offset set but file " @@ -237,12 +242,10 @@ public class LocalizationStreamHandler tmpFile.createNewFile(); } FileOutputStream outputStream = null; - Integer bytesWritten = 0; try { outputStream = new FileOutputStream(tmpFile, true); byte[] bytes = request.getBytes(); - bytesWritten += bytes.length; outputStream.write(bytes); } finally { if (outputStream != null) { @@ -251,26 +254,41 @@ public class LocalizationStreamHandler } } if (request.isEnd()) { - FileChangeType changeType = FileChangeType.UPDATED; - if (!file.exists()) { - changeType = FileChangeType.ADDED; + try { + FileLocker.lock(this, file, Type.WRITE); + FileChangeType changeType = FileChangeType.UPDATED; + if (!file.exists()) { + changeType = FileChangeType.ADDED; + } + + tmpFile.renameTo(file); + + try { + // attempt to generate checksum after change + UtilityManager.writeChecksum(file); + } catch (Exception e) { + // ignore, will be generated next time requested + } + + long timeStamp = file.lastModified(); + + EDEXUtil.getMessageProducer().sendAsync( + UtilityManager.NOTIFY_ID, + new FileUpdatedMessage(request.getContext(), request + .getFileName(), changeType, timeStamp)); + return timeStamp; + } finally { + FileLocker.unlock(this, file); } - - tmpFile.renameTo(file); - // tmpFile.delete(); - - EDEXUtil.getMessageProducer().sendAsync( - UtilityManager.NOTIFY_ID, - new FileUpdatedMessage(request.getContext(), request - .getFileName(), changeType)); } - return bytesWritten; + return tmpFile.lastModified(); } @Override public AuthorizationResponse authorized(IUser user, - AbstractLocalizationStreamRequest request) { + AbstractLocalizationStreamRequest request) + throws AuthorizationException { if (request instanceof LocalizationStreamGetRequest) { // All gets are authorized return new AuthorizationResponse(true); diff --git a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/PrivilegedUtilityHandler.java b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/PrivilegedUtilityHandler.java index 414130fc8f..a4b9df6d99 100644 --- a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/PrivilegedUtilityHandler.java +++ b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/PrivilegedUtilityHandler.java @@ -3,6 +3,7 @@ package com.raytheon.edex.services; import java.util.ArrayList; import java.util.List; +import com.raytheon.uf.common.auth.exception.AuthorizationException; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; @@ -66,7 +67,8 @@ public class PrivilegedUtilityHandler @Override public AuthorizationResponse authorized(IUser user, - PrivilegedUtilityRequestMessage request) { + PrivilegedUtilityRequestMessage request) + throws AuthorizationException { AbstractPrivilegedUtilityCommand[] commands = request.getCommands(); for (AbstractPrivilegedUtilityCommand abstractUtilityCommand : commands) { diff --git a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/UtilityManager.java b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/UtilityManager.java index ad6352841a..115429bf90 100644 --- a/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/UtilityManager.java +++ b/edexOsgi/com.raytheon.edex.utilitysrv/src/com/raytheon/edex/services/UtilityManager.java @@ -21,10 +21,11 @@ package com.raytheon.edex.services; import java.io.BufferedReader; +import java.io.BufferedWriter; import java.io.File; import java.io.FileFilter; import java.io.FileReader; -import java.io.IOException; +import java.io.FileWriter; import java.util.ArrayList; import java.util.Date; @@ -41,7 +42,6 @@ import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.msgs.DeleteUtilityResponse; import com.raytheon.uf.common.localization.msgs.ListResponseEntry; import com.raytheon.uf.common.localization.msgs.ListUtilityResponse; -import com.raytheon.uf.common.util.FileUtil; import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.core.EdexException; @@ -121,35 +121,46 @@ public class UtilityManager { * @throws EdexException */ private static String getFileChecksum(File file) throws EdexException { - File checksumFile = new File(file.toString() + CHECKSUM_FILE_EXTENSION); - + // TODO: Fix FileLocker so it never times out in test driver + File checksumFile = getChecksumFile(file); String chksum = null; - if (!checksumFile.exists() - || (checksumFile.lastModified() < file.lastModified())) { - // Create a checksum - try { - chksum = Checksum.getMD5Checksum(file); - FileUtil.bytes2File(chksum.getBytes(), checksumFile); - } catch (Exception e) { - // ignore, no checksum will be provided - } - } else { - BufferedReader br = null; - try { - br = new BufferedReader(new FileReader(checksumFile)); - chksum = br.readLine(); - } catch (Exception e) { - // ignore, no checksum will be provided - } finally { - if (br != null) { - try { - br.close(); - } catch (IOException e) { - // ignore - can't do anything anyway... - } + try { + if (checksumFile.exists() + && checksumFile.lastModified() >= file.lastModified()) { + + BufferedReader reader = new BufferedReader(new FileReader( + checksumFile)); + try { + chksum = reader.readLine(); + } finally { + reader.close(); } } + if (chksum == null) { + chksum = writeChecksum(file); + } + } catch (Exception e) { + // log, no checksum will be provided + logger.error("Error determing file checksum for: " + file, e); + } + return chksum; + } + + private static File getChecksumFile(File utilityFile) { + return new File(utilityFile.getParentFile(), utilityFile.getName() + + CHECKSUM_FILE_EXTENSION); + } + + public static String writeChecksum(File file) throws Exception { + String chksum = null; + File checksumFile = getChecksumFile(file); + BufferedWriter bw = new BufferedWriter(new FileWriter(checksumFile)); + try { + chksum = Checksum.getMD5Checksum(file); + bw.write(chksum); + } finally { + bw.close(); } return chksum; } @@ -176,7 +187,20 @@ public class UtilityManager { File delFile = new File(fullPath); if (delFile.exists()) { - delFile.delete(); + if (!delFile.delete()) { + // Failed to delete file... + msg = "File could not be deleted: "; + if (delFile.isDirectory() && delFile.list().length > 0) { + msg += "Non-empty directory"; + } else if (delFile.canWrite() == false) { + msg += "Do not have write permission to file"; + } else if (delFile.getParentFile() != null + && delFile.getParentFile().canWrite() == false) { + msg += "Do not have write permission to file's parent directory"; + } else { + msg += "Reason unknown"; + } + } String md5Path = fullPath + ".md5"; File md5File = new File(md5Path); if (md5File.exists()) { @@ -184,20 +208,22 @@ public class UtilityManager { } } } catch (Exception e) { - return new DeleteUtilityResponse(context, e.getMessage(), fileName); + return new DeleteUtilityResponse(context, e.getMessage(), fileName, + System.currentTimeMillis()); } + long timeStamp = System.currentTimeMillis(); // send notification try { EDEXUtil.getMessageProducer().sendAsync( NOTIFY_ID, new FileUpdatedMessage(context, fileName, - FileChangeType.DELETED)); + FileChangeType.DELETED, timeStamp)); } catch (Exception e) { logger.error("Error sending file updated message", e); } - return new DeleteUtilityResponse(context, msg, fileName); + return new DeleteUtilityResponse(context, msg, fileName, timeStamp); } /** diff --git a/edexOsgi/com.raytheon.uf.common.auth/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.auth/META-INF/MANIFEST.MF index 559952c970..ccb292c23b 100644 --- a/edexOsgi/com.raytheon.uf.common.auth/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.auth/META-INF/MANIFEST.MF @@ -10,6 +10,7 @@ Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.11.31", com.raytheon.uf.common.serialization.comm;bundle-version="1.11.31", org.apache.commons.lang;bundle-version="2.3.0" Export-Package: com.raytheon.uf.common.auth, + com.raytheon.uf.common.auth.exception, com.raytheon.uf.common.auth.req, com.raytheon.uf.common.auth.resp, com.raytheon.uf.common.auth.user diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/ParameterNode.java b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/exception/AuthorizationException.java similarity index 58% rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/ParameterNode.java rename to edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/exception/AuthorizationException.java index f0a3ec89c0..ae3b8ea948 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/ParameterNode.java +++ b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/exception/AuthorizationException.java @@ -17,51 +17,55 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.viz.grid.gridcache; - -import java.util.ArrayList; +package com.raytheon.uf.common.auth.exception; /** - * The parameter node of the cache tree. + * Base exception for access authorization. * *
  * 
  * SOFTWARE HISTORY
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Nov 13, 2009 3579       mpduff      Initial creation
+ * Sep 19, 2012            bgonzale     Initial creation
  * 
  * 
* - * @author mpduff + * @author bgonzale * @version 1.0 */ -public class ParameterNode extends CacheNode { +public class AuthorizationException extends Exception { - private String parameter = null; - - private ArrayList levelTypeList = new ArrayList(); + private static final long serialVersionUID = 1L; /** - * @return the parameter + * */ - public String getParameter() { - return parameter; + public AuthorizationException() { } /** - * @param parameter the parameter to set + * @param message */ - public void setParameter(String parameter) { - this.parameter = parameter; + public AuthorizationException(String message) { + super(message); } - - public void addLevelNode(LevelNode lnode) { - levelTypeList.add(lnode); + + /** + * @param cause + */ + public AuthorizationException(Throwable cause) { + super(cause); } - - public ArrayList getLevelTypeList() { - return levelTypeList; + + /** + * @param message + * @param cause + */ + public AuthorizationException(String message, Throwable cause) { + super(message, cause); } + } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/CacheNode.java b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IPermission.java similarity index 67% rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/CacheNode.java rename to edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IPermission.java index 4cc737b5be..f0eb6c8509 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/CacheNode.java +++ b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IPermission.java @@ -17,39 +17,39 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.viz.grid.gridcache; +package com.raytheon.uf.common.auth.user; /** - * Base class for the cache nodes. + * A permission. * *
  * 
  * SOFTWARE HISTORY
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Nov 13, 2009 3579       mpduff      Initial creation
+ * Nov 5, 2012  1302      djohnson     Initial creation
  * 
  * 
* - * @author mpduff + * @author djohnson * @version 1.0 */ -public abstract class CacheNode { - private String modelName = null; - - /** - * @return the modelName - */ - public String getModelName() { - return modelName; - } +public interface IPermission { /** - * @param modelName - * the modelName to set + * Get the description. + * + * @return the description */ - public void setModelName(String modelName) { - this.modelName = modelName; - } + String getDescription(); + + /** + * The display name of the permission. + * + * @return the name + */ + @Override + String toString(); } diff --git a/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IRole.java b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IRole.java new file mode 100644 index 0000000000..5534b08485 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IRole.java @@ -0,0 +1,65 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.auth.user; + +import java.util.List; + +/** + * Interface for representing a role. A role should be able to determine if it + * is valid for a specific user + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 18, 2010            mschenke     Initial creation
+ * Nov 06, 2012 1302       djohnson     Move back to API plugin, add getter for permissions.
+ * 
+ * 
+ * + * @author mschenke + * @version 1.0 + */ + +public interface IRole { + + /** + * Get the list of permissions. + * + * @return the list of permissions + */ + List getPermissions(); + + /** + * Get the description of the role. + * + * @return the description + */ + String getDescription(); + + /** + * The representation of the role as a string. + * + * @return + */ + @Override + String toString(); +} diff --git a/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IUser.java b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IUser.java index 2f598794ab..eedeea6f25 100644 --- a/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IUser.java +++ b/edexOsgi/com.raytheon.uf.common.auth/src/com/raytheon/uf/common/auth/user/IUser.java @@ -45,13 +45,20 @@ public interface IUser extends ISerializableObject { * * @return the user identifier object */ - public IUserId uniqueId(); + IUserId uniqueId(); + + // /** + // * Retrieve the roles assigned to the user. + // * + // * @return the roles + // */ + // IRole[] getUserRoles(); /** * Get the authentication data used to identify the user * * @return data needed to authenticate the user */ - public IAuthenticationData authenticationData(); + IAuthenticationData authenticationData(); } diff --git a/edexOsgi/com.raytheon.uf.common.comm/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.comm/META-INF/MANIFEST.MF index 1ef9ad2fd9..2075fcc963 100644 --- a/edexOsgi/com.raytheon.uf.common.comm/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.comm/META-INF/MANIFEST.MF @@ -7,5 +7,8 @@ Bundle-Vendor: RAYTHEON Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: org.apache.http, com.raytheon.uf.common.status, - com.raytheon.uf.common.util + com.raytheon.uf.common.util, + com.raytheon.uf.common.auth;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174" Export-Package: com.raytheon.uf.common.comm diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/.classpath b/edexOsgi/com.raytheon.uf.common.dataaccess/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/.project b/edexOsgi/com.raytheon.uf.common.dataaccess/.project new file mode 100644 index 0000000000..07d8ab1b31 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.dataaccess + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.dataaccess/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..e23a1c7d0c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Sep 18 14:46:02 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataaccess/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..7982f9fe8f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/META-INF/MANIFEST.MF @@ -0,0 +1,17 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Dataaccess +Bundle-SymbolicName: com.raytheon.uf.common.dataaccess +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: com.raytheon.uf.common.time;visibility:=reexport, + com.raytheon.uf.common.datastorage, + com.raytheon.uf.common.geospatial;visibility:=reexport, + javax.measure;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin.level;visibility:=reexport +Export-Package: com.raytheon.uf.common.dataaccess, + com.raytheon.uf.common.dataaccess.exception, + com.raytheon.uf.common.dataaccess.geom, + com.raytheon.uf.common.dataaccess.grid, + com.raytheon.uf.common.dataaccess.impl diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/build.properties b/edexOsgi/com.raytheon.uf.common.dataaccess/build.properties similarity index 100% rename from edexOsgi/com.raytheon.uf.common.datastorage.remote/build.properties rename to edexOsgi/com.raytheon.uf.common.dataaccess/build.properties diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/res/spring/dataaccess-common.xml b/edexOsgi/com.raytheon.uf.common.dataaccess/res/spring/dataaccess-common.xml new file mode 100644 index 0000000000..1a7c87f3e0 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/res/spring/dataaccess-common.xml @@ -0,0 +1,8 @@ + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/DataAccessLayer.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/DataAccessLayer.java new file mode 100644 index 0000000000..bb52712bfc --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/DataAccessLayer.java @@ -0,0 +1,165 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess; + +import org.geotools.coverage.grid.GridGeometry2D; + +import com.raytheon.uf.common.dataaccess.exception.DataFactoryNotFoundException; +import com.raytheon.uf.common.dataaccess.exception.TimeAgnosticDataException; +import com.raytheon.uf.common.dataaccess.geom.IGeometryDataFactory; +import com.raytheon.uf.common.dataaccess.geom.IGeometryRequest; +import com.raytheon.uf.common.dataaccess.grid.IGridDataFactory; +import com.raytheon.uf.common.dataaccess.grid.IGridRequest; +import com.raytheon.uf.common.time.BinOffset; +import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.common.time.TimeRange; + +/** + * The Data Access Layer is the published API for getting data through the Data + * Access Framework. Code from other components should go through these methods + * to retrieve the data. All methods may potentially throw + * UnsupportedOperationException or IllegalArgumentException dependent on how + * much support has been provided per datatype. + * + * The implementation of this class is a retrieval of the corresponding factory + * and then delegating the processing to that factory. All the generics that + * exist in this implementation are to save the caller from the hassle of + * casting what is returned. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 24, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class DataAccessLayer { + + /** + * Gets the times of available data to the request + * + * @param request + * the request to find available times for + * @return the available times that match the request + * @throws TimeAgnosticDataException + */ + public static , D extends IData> DataTime[] getAvailableTimes( + R request) { + IDataFactory factory = getFactory(request); + return factory.getAvailableTimes(request); + } + + /** + * Gets the times of available data to the request with a BinOffset applied + * + * @param request + * the request to find available times for + * @param binOffset + * the BinOffset to apply + * @return the available times with the bin offset applied that match the + * request + * @throws TimeAgnosticDataException + */ + public static , D extends IData> DataTime[] getAvailableTimes( + R request, BinOffset binOffset) { + IDataFactory factory = getFactory(request); + return factory.getAvailableTimes(request, binOffset); + } + + /** + * Gets the data that matches the request at the specified times. If data is + * time agnostic then simply don't pass in any DataTimes, for example + * DataAccessLayer.getData(R) + * + * @param request + * the request to get data for + * @param times + * the times to get data for + * @return the data that matches the request and times + */ + public static , D extends IData> D[] getData( + R request, DataTime... times) { + IDataFactory factory = getFactory(request); + return factory.getData(request, times); + } + + /** + * Gets the data that matches the request within the time range + * + * @param request + * the request to get data for + * @param timeRange + * the time range to get data for + * @return the data that matches the request and time range + */ + public static , D extends IData> D[] getData( + R request, TimeRange timeRange) { + IDataFactory factory = getFactory(request); + return factory.getData(request, timeRange); + } + + /** + * Gets the grid geometry of the data matching the request without actually + * requesting the data. Useful for then making slab/subgrid/line requests by + * setting the storage request parameter on an IGridRequest. + * + * @param request + * the request to get the grid geometry of the data for + * @return the geometry of the data if the data was requested + */ + public static GridGeometry2D getGridGeometry(IGridRequest request) { + IGridDataFactory factory = (IGridDataFactory) getFactory(request); + return factory.getGeometry(request); + } + + /** + * Gets the available location names that match the request without actually + * requesting the data. + * + * @param request + * @return the available location names if the data was requested + */ + public static String[] getAvailableLocationNames(IGeometryRequest request) { + IGeometryDataFactory factory = (IGeometryDataFactory) getFactory(request); + return factory.getAvailableLocationNames(request); + } + + /** + * TODO: contemplate making this public to allow for special case handling + * Returns the factory that should process the request. Will never return + * null, will instead throw exceptions. + * + * @param request + * @return the factory that matches the request + * @throws DataFactoryNotFoundException + */ + private static , D extends IData> IDataFactory getFactory( + R request) { + return DataFactoryRegistry.getInstance().getFactory(request); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/DataFactoryRegistry.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/DataFactoryRegistry.java new file mode 100644 index 0000000000..cc23dd2f2e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/DataFactoryRegistry.java @@ -0,0 +1,144 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess; + +import java.util.HashMap; +import java.util.Map; +import java.util.Map.Entry; + +import com.raytheon.uf.common.dataaccess.exception.DataFactoryNotFoundException; + +/** + * Registry containing the support for different datatypes in the Data Access + * Framework. The registry maps a datatype name/key to a request type + * (IGridRequest vs IGeometryRequest) and the corresponding factory to support + * that request type. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class DataFactoryRegistry { + + private Map>, IDataFactory>> datatypeMap; + + private static DataFactoryRegistry instance; + + /** + * Constructor + */ + private DataFactoryRegistry() { + datatypeMap = new HashMap>, IDataFactory>>(); + } + + /** + * Returns the instance of the DataFactoryRegistry + * + * @return + */ + public static DataFactoryRegistry getInstance() { + if (instance == null) { + instance = new DataFactoryRegistry(); + } + return instance; + } + + /** + * Registers a datatype name with a request type and the supporting factory. + * Should only be called from spring. + * + * @param datatype + * the datatype name that will become the key for requests' + * datatypes + * @param requestType + * IGridRequest vs IGeometryRequest + * @param factory + * the factory that will support requests of this datatype and + * type + */ + public IDataFactory register(String datatype, + Class> requestType, IDataFactory factory) { + Map>, IDataFactory> requestTypeMap = datatypeMap + .get(datatype); + if (requestTypeMap == null) { + requestTypeMap = new HashMap>, IDataFactory>(); + datatypeMap.put(datatype, requestTypeMap); + } + requestTypeMap.put(requestType, factory); + return factory; + } + + /** + * Returns the factory that should process the request. Will never return + * null and will instead throw an exception if no registered factories + * match. + * + * @param request + * the request to find a matching factory for + * @return the factory that is registered to process the request + * @throws DataFactoryNotFoundException + * @throws IllegalArgumentException + */ + @SuppressWarnings("unchecked") + public , D extends IData> IDataFactory getFactory( + R request) { + String datatype = request.getDatatype(); + if (datatype != null) { + Map>, IDataFactory> requestTypeMap = datatypeMap + .get(datatype); + if (requestTypeMap != null) { + IDataFactory factory = null; + for (Entry>, IDataFactory> entry : requestTypeMap + .entrySet()) { + if (entry.getKey().isInstance(request)) { + factory = entry.getValue(); + break; + } + } + if (factory != null) { + return (IDataFactory) factory; + } else { + throw new DataFactoryNotFoundException( + "No data access support for requests of datatype " + + datatype + " and type " + + request.getClass()); + } + } else { + throw new DataFactoryNotFoundException( + "No data access support registered to datatype key: " + + datatype); + } + } else { + throw new IllegalArgumentException( + "Request must have a datatype set"); + } + + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IData.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IData.java new file mode 100644 index 0000000000..65279f2bab --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IData.java @@ -0,0 +1,67 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess; + +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.time.DataTime; + +/** + * An IData represents the bare minimum of any piece of data, namely that it can + * have attributes, a time, and a level. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IData { + + /** + * Gets an attribute of the data based on the key. + * + * @param key + * @return the attribute + */ + public Object getAttribute(String key); + + /** + * Gets the DataTime of the data. May be null if the data is time agnostic. + * + * @return the time of the data, possibly null for some data types + */ + public DataTime getDataTime(); + + /** + * Gets the level of the data. May be null depending on the datatype. + * + * @return the level of the data, possibly null for some data types + */ + public Level getLevel(); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IDataFactory.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IDataFactory.java new file mode 100644 index 0000000000..7e77767f7a --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IDataFactory.java @@ -0,0 +1,116 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess; + +import com.raytheon.uf.common.dataaccess.exception.TimeAgnosticDataException; +import com.raytheon.uf.common.time.BinOffset; +import com.raytheon.uf.common.time.DataTime; +import com.raytheon.uf.common.time.TimeRange; + +/** + * Factory interface for producing data objects that implement IData, hiding the + * details of the underlying data implementation object and how it was + * retrieved. + * + * Implementations of IDataFactory should strive to handle all their processing + * based on the request interface that was received. If at all possible, they + * should not cast the request to a specific request implementation, ensuring + * that they will work with multiple request implementations. + * + * The return types of the getData() methods should be geared towards returning + * what a caller of the API would expect. For example, a request for county + * polygons may not explicitly request that it wants the US state name as an + * attribute on the returned object. However, a caller could reasonably expect + * when requesting counties that the returned object includes state name. This + * must be balanced carefully since a caller of the API does not see the factory + * implementation but has expectations about what will be returned. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + * @param + */ + +public interface IDataFactory, D extends IData> { + + /** + * Gets the available times that match the request. Implementations should + * throw TimeAgnosticDataException if the datatype is time agnostic. + * + * @param request + * the request to find matching times for + * @return the times that have data available for this request + * @throws TimeAgnosticDataException + */ + public DataTime[] getAvailableTimes(R request) + throws TimeAgnosticDataException; + + /** + * Gets the available times that match the request within the BinOffset. + * Implementations should throw TimeAgnosticDataException if the datatype is + * time agnostic. + * + * @param request + * the request to find matching times for + * @param binOffset + * the bin offset to limit the returned times + * @return the times with the bin offset applied that have data available + * for this request + * @throws TimeAgnosticDataException + */ + public DataTime[] getAvailableTimes(R request, BinOffset binOffset) + throws TimeAgnosticDataException; + + /** + * Gets the available data that matches the request at the specified times. + * If data is time agnostic, use getData(R). + * + * @param request + * the request to get matching data for + * @param times + * the times to get data for. If data is time agnostic, use + * getData(R) + * @return the data that matches the request at the specified times + */ + public D[] getData(R request, DataTime... times); + + /** + * Gets the available data that matches the request and is within the time + * range. If data is time agnostic, use getData(R). + * + * @param request + * the request to get matching data for + * @param timeRange + * the time range to return data for. If data is time agnostic, + * use getData(R). + * @return the data that matches the request within the time range + */ + public D[] getData(R request, TimeRange timeRange); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IDataRequest.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IDataRequest.java new file mode 100644 index 0000000000..99eaee65a8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/IDataRequest.java @@ -0,0 +1,113 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess; + +import java.util.Map; + +import com.raytheon.uf.common.dataplugin.level.Level; + +/** + * A generic request for geospatial data to the Data Access Framework. All + * requests must have a datatype set. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IDataRequest { + + /** + * The datatype of the data, usually the pluginName. This value will be used + * as a key to determine the corresponding IDataFactory that should process + * the request. This is required to be non-null. + * + * @param datatype + * the datatype of the data to request + */ + public void setDatatype(String datatype); + + /** + * Adds an identifier the factory can use to determine exactly what data is + * desired. Note that sub-interfaces may add methods for specific + * identifying characteristics. + * + * @param key + * the name of the identifier + * @param value + * the value desired on all the return data + */ + public void addIdentifier(String key, Object value); + + /** + * Sets the parameters to request of the data. + * + * @param params + * the parameters to request + */ + public void setParameters(String... params); + + /** + * Sets the levels to request of the data. Some factories may ignore this or + * throw an exception if all data is at one level. + * + * @param levels + * the levels to request + */ + public void setLevels(Level... levels); + + /** + * Returns the datatype set on the request. + * + * @return the datatype of the request + */ + public String getDatatype(); + + /** + * Returns the identifiers added to the request. + * + * @return the identifiers of the request + */ + public Map getIdentifiers(); + + /** + * Returns the parameters set on the request. + * + * @return the parameters of the request + */ + public String[] getParameters(); + + /** + * Returns the levels set on the request. + * + * @return the levels of the request + */ + public Level[] getLevels(); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataAccessException.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataAccessException.java new file mode 100644 index 0000000000..231cc03273 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataAccessException.java @@ -0,0 +1,82 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.exception; + +/** + * An exception that comes out of the Data Access Framework. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 12, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public abstract class DataAccessException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor + */ + public DataAccessException() { + super(); + } + + /** + * Constructor + * + * @param message + * the error message + */ + public DataAccessException(String message) { + super(message); + } + + /** + * Constructor + * + * @param message + * the error message + * @param cause + * the cause of the error + */ + public DataAccessException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor + * + * @param cause + * the cause of the error + */ + public DataAccessException(Throwable cause) { + super(cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataFactoryNotFoundException.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataFactoryNotFoundException.java new file mode 100644 index 0000000000..2d243eaf46 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataFactoryNotFoundException.java @@ -0,0 +1,82 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.exception; + +/** + * An exception for when a data factory is not found to fulfill a request. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 12, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class DataFactoryNotFoundException extends DataAccessException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor + */ + public DataFactoryNotFoundException() { + super(); + } + + /** + * Constructor + * + * @param message + * the error message + */ + public DataFactoryNotFoundException(String message) { + super(message); + } + + /** + * Constructor + * + * @param message + * the error message + * @param cause + * the cause of the error + */ + public DataFactoryNotFoundException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor + * + * @param cause + * the cause of the error + */ + public DataFactoryNotFoundException(Throwable cause) { + super(cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataRetrievalException.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataRetrievalException.java new file mode 100644 index 0000000000..3f21f3ed15 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/DataRetrievalException.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.exception; + +/** + * An exception for when there is an error performing the underlying factory + * specific retrieval for data. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 14, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class DataRetrievalException extends DataAccessException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor + */ + public DataRetrievalException() { + super(); + } + + /** + * Constructor + * + * @param message + * the error message + */ + public DataRetrievalException(String message) { + super(message); + } + + /** + * Constructor + * + * @param message + * the error message + * @param cause + * the cause of the error + */ + public DataRetrievalException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor + * + * @param cause + * the cause of the error + */ + public DataRetrievalException(Throwable cause) { + super(cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/IncompatibleRequestException.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/IncompatibleRequestException.java new file mode 100644 index 0000000000..ea8a6d601e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/IncompatibleRequestException.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.exception; + +/** + * An exception for when an IDataFactory cannot handle a request due to specific + * values on the request. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 13, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class IncompatibleRequestException extends DataAccessException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor + */ + public IncompatibleRequestException() { + super(); + } + + /** + * Constructor + * + * @param message + * the error message + */ + public IncompatibleRequestException(String message) { + super(message); + } + + /** + * Constructor + * + * @param message + * the error message + * @param cause + * the cause of the error + */ + public IncompatibleRequestException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor + * + * @param cause + * the cause of the error + */ + public IncompatibleRequestException(Throwable cause) { + super(cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/MissingRequiredIdentifierException.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/MissingRequiredIdentifierException.java new file mode 100644 index 0000000000..fef908fb59 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/MissingRequiredIdentifierException.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.exception; + +/** + * An exception for when a request is sent that a factory cannot process without + * one or more specific identifiers. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 13, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class MissingRequiredIdentifierException extends DataAccessException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor + */ + public MissingRequiredIdentifierException() { + super(); + } + + /** + * Constructor + * + * @param message + * the error message + */ + public MissingRequiredIdentifierException(String message) { + super(message); + } + + /** + * Constructor + * + * @param message + * the error message + * @param cause + * the cause of the error + */ + public MissingRequiredIdentifierException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor + * + * @param cause + * the cause of the error + */ + public MissingRequiredIdentifierException(Throwable cause) { + super(cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/TimeAgnosticDataException.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/TimeAgnosticDataException.java new file mode 100644 index 0000000000..0fc6155dc6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/exception/TimeAgnosticDataException.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.exception; + +/** + * An exception for when the data is time agnostic and time requests are not + * supported. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 12, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class TimeAgnosticDataException extends DataAccessException { + + private static final long serialVersionUID = 1L; + + /** + * Constructor + */ + public TimeAgnosticDataException() { + super(); + } + + /** + * Constructor + * + * @param message + * the error message + */ + public TimeAgnosticDataException(String message) { + super(message); + } + + /** + * Constructor + * + * @param message + * the error message + * @param cause + * the cause of the error + */ + public TimeAgnosticDataException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Constructor + * + * @param cause + * the cause of the error + */ + public TimeAgnosticDataException(Throwable cause) { + super(cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryData.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryData.java new file mode 100644 index 0000000000..440813bd54 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryData.java @@ -0,0 +1,129 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.geom; + +import java.util.Set; + +import javax.measure.converter.ConversionException; +import javax.measure.unit.Unit; + +import com.raytheon.uf.common.dataaccess.IData; +import com.vividsolutions.jts.geom.Geometry; + +/** + * An IGeometryData represents data of potentially multiple parameters + * associated with a single geometry, typically a point or polygon, at a single + * level. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IGeometryData extends IData { + + public static enum Type { + STRING, INT, LONG, FLOAT, DOUBLE; + }; + + /** + * Gets the geometry associated with this instance of data. The geometry + * coordinates are in Lat/Lon space. + * + * @return the geometry of the data + */ + public Geometry getGeometry(); + + /** + * Gets the list of parameters associated with this instance of data + * + * @return the parameters on this instance of data + */ + public Set getParameters(); + + /** + * Gets the string value of a particular parameter. + * + * @param param + * the parameter to get the value of + * @return the string value of the parameter + */ + public String getString(String param); + + /** + * Gets the number value of a particular parameter + * + * @param param + * the parameter to get the value of + * @return the number value of the parameter + */ + public Number getNumber(String param); + + /** + * Gets the number value of a particular parameter converted to the + * specified unit. Will throw ConversionException if the units are + * incompatible or the data has no unit. + * + * @param param + * the parameter to get the value of + * @param unit + * the unit to get the value as + * @return the number value of a parameter, converted to the specified unit + * @throws ConversionException + */ + public Number getNumber(String param, Unit unit) + throws ConversionException; + + /** + * Gets the unit associated with a particular parameter. May be null. + * + * @param param + * the parameter to get the unit of + * @return the unit of the parameter + */ + public Unit getUnit(String param); + + /** + * Gets the type of a particular parameter. + * + * @param param + * the parameter to get the type of + * @return the type as specified in IGeometryData.type + */ + public Type getType(String param); + + /** + * Gets the location name associated with this instance of IData. May be + * null. + * + * @return the location name or null + */ + public String getLocationName(); + +} diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/LevelComparator.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryDataFactory.java similarity index 55% rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/LevelComparator.java rename to edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryDataFactory.java index 33e3d4132a..27258e5885 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/LevelComparator.java +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryDataFactory.java @@ -17,45 +17,40 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.viz.grid.gridcache; +package com.raytheon.uf.common.dataaccess.geom; -import java.util.Comparator; - -import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.level.CompareType; +import com.raytheon.uf.common.dataaccess.IDataFactory; /** - * Grib layer comparator. + * IDataFactory for any data that is non-gridded, for example points or + * polygons. * *
  * 
  * SOFTWARE HISTORY
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Nov 12, 2009 3579       mpduff      Initial creation
+ * Oct 10, 2012            njensen     Initial creation
  * 
  * 
* - * @author mpduff + * @author njensen * @version 1.0 */ -public class LevelComparator implements Comparator { - /** - * Compare the two objects. - * - * @return 1 if above, -1 if below, 0 if equal - */ - public int compare(GribRecord record, GribRecord otherRecord) { - CompareType ct = record.getModelInfo().getLevel().compare( - otherRecord.getModelInfo().getLevel()); +public interface IGeometryDataFactory extends + IDataFactory { + + /** + * Gets the available location names that match the request. Implementations + * should throw LocationNameUnsupportedException if location names do not + * apply to their datatype. + * + * @param request + * the request to find matching location names for + * @return the available location names that match the request + */ + public String[] getAvailableLocationNames(IGeometryRequest request); - if (ct == CompareType.ABOVE) { - return 1; - } else if (ct == CompareType.BELOW) { - return -1; - } else { - return 0; - } - } } diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryRequest.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryRequest.java new file mode 100644 index 0000000000..aaf9331001 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/geom/IGeometryRequest.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.geom; + +import com.raytheon.uf.common.dataaccess.IDataRequest; +import com.vividsolutions.jts.geom.Envelope; + +/** + * A request for any data type that is non-gridded and can be represented by a + * geometry. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IGeometryRequest extends IDataRequest { + + /** + * Sets a bounding box on the request to limit the area of the request. The + * envelope coordinates should be in Lat/Lon space. Note that not all + * factories may support the envelope and instead may throw an + * EnvelopeUnsupportedException or ignore the envelope. + * + * @param env + * the envelope to constrain the request + */ + public void setEnvelope(Envelope env); + + /** + * Returns the envelope set on the request. + * + * @return the envelope set on the request + */ + public Envelope getEnvelope(); + + /** + * Sets a list of location names to limit what is returned. Each datatype + * may have its own mapping of what a location is (e.g. ICAO vs stationId vs + * radar name, etc). Possible location names can be retrieved by using the + * method getAvailableLocationNames(IGeometryRequest) on the DataAccessLayer + * or IGeometryDataFactory. Note that not all factories may support requests + * by location names and instead may throw a + * LocationNameUnsupportedException or ignore the location names. + * + * @param locationNames + */ + public void setLocationNames(String... locationNames); + + /** + * Returns the location names set on the request. + * + * @return + */ + public String[] getLocationNames(); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridData.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridData.java new file mode 100644 index 0000000000..fe8d210094 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridData.java @@ -0,0 +1,93 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.grid; + +import javax.measure.unit.Unit; + +import org.geotools.coverage.grid.GridGeometry2D; + +import com.raytheon.uf.common.dataaccess.IData; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.geospatial.interpolation.data.DataDestination; +import com.raytheon.uf.common.geospatial.interpolation.data.UnitConvertingDataDestination; + +/** + * An IGridData represents data that is gridded, ie rectangular (when not + * projected) with a set x and y size. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 9, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IGridData extends IData { + + /** + * Gets the parameter of the data + * + * @return the parameter of the data + */ + public String getParameter(); + + /** + * Gets the level of the data + * + * @return the level of the data + */ + public Level getLevel(); + + /** + * Gets the GridGeometry of the data + * + * @return the grid geometry of the data + */ + public GridGeometry2D getGridGeometry(); + + /** + * Gets the unit of the raw data. This may differ from the unit of a data + * destination. + * + * @return the unit of the data + */ + public Unit getUnit(); + + /** + * Populates the DataDestination argument with the raw data converted to the + * type to match the DataDestination. The destination must not be null. If + * unit conversions are desired, use the + * {@link UnitConvertingDataDestination} to specify what unit conversion + * should be applied to the data. + * + * @param destination + * the destination to fill with data + * @return the data destination that was passed in, with the data populated + */ + public
DD populateData(DD destination); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridDataFactory.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridDataFactory.java new file mode 100644 index 0000000000..2dd85c13c8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridDataFactory.java @@ -0,0 +1,60 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.grid; + +import org.geotools.coverage.grid.GridGeometry2D; + +import com.raytheon.uf.common.dataaccess.IDataFactory; + +/** + * IDataFactory interface for two dimensional gridded data. Note that IGridData + * has the populateData() methods, therefore the implementations of this + * interface can choose to either retrieve the raw data when factory.getData() + * is called, or have the implementation of IGridData retrieve the raw data when + * populateData() is called. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 9, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IGridDataFactory extends IDataFactory { + + /** + * Gets the GridGeometry2D that matches the request. Useful for determining + * the area before requesting the data. + * + * @param request + * the request to get the geometry for + * @return the grid geometry of the data that would be returned from this + * request + */ + public GridGeometry2D getGeometry(IGridRequest request); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridRequest.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridRequest.java new file mode 100644 index 0000000000..f52931ee47 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/grid/IGridRequest.java @@ -0,0 +1,61 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.grid; + +import com.raytheon.uf.common.dataaccess.IDataRequest; +import com.raytheon.uf.common.datastorage.Request; + +/** + * A request for gridded data. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 9, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public interface IGridRequest extends IDataRequest { + + /** + * Sets a storage request as part of the request. If null, the entire + * dataset will be retrieved. Useful for slab requests to avoid retrieving + * the entire dataset and boost performance in some scenarios. + * + * @param request + * the {@link Request} to limit the data returned + */ + public void setStorageRequest(Request request); + + /** + * Gets the storage request set on the request. + * + * @return the {@link Request} set on the IGridRequest + */ + public Request getStorageRequest(); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/AbstractDataFactory.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/AbstractDataFactory.java new file mode 100644 index 0000000000..308f5ff2c7 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/AbstractDataFactory.java @@ -0,0 +1,100 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.raytheon.uf.common.dataaccess.IDataRequest; +import com.raytheon.uf.common.dataaccess.exception.MissingRequiredIdentifierException; + +/** + * + * An abstract data factory that can be used by implementing IGridDataFactories + * or IGeometryDataFactories. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 13, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public abstract class AbstractDataFactory { + + /** + * Returns the identifiers that must be set on a request for the request to + * be processed + * + * @return the required identifiers + */ + public abstract String[] getRequiredIdentifiers(); + + /** + * Validates that a request is compatible with the factory + * + * @param request + * the request to validate + */ + public void validateRequest(IDataRequest request) { + String[] required = getRequiredIdentifiers(); + List missing = null; + if (required != null && required.length > 0) { + Map identifiers = request.getIdentifiers(); + if (identifiers != null) { + for (String s : required) { + if (!identifiers.containsKey(s)) { + if (missing == null) { + missing = new ArrayList(required.length); + } + missing.add(s); + } + } + } else { + missing = Arrays.asList(required); + } + } + + if (missing != null) { + StringBuilder sb = new StringBuilder(); + sb.append("Request of "); + sb.append(request.getDatatype()); + sb.append(" data is missing identifiers: "); + Iterator itr = missing.iterator(); + while (itr.hasNext()) { + sb.append(itr.next()); + if (itr.hasNext()) { + sb.append(", "); + } + } + throw new MissingRequiredIdentifierException(sb.toString()); + } + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/AbstractDataRequest.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/AbstractDataRequest.java new file mode 100644 index 0000000000..e5cc5eacc0 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/AbstractDataRequest.java @@ -0,0 +1,90 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.impl; + +import java.util.HashMap; +import java.util.Map; + +import com.raytheon.uf.common.dataplugin.level.Level; + +/** + * + * An abstract request for requesting data through the Data Access Framework. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 6, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public abstract class AbstractDataRequest { + + protected String datatype; + + protected Map identifiers; + + protected String[] parameters; + + protected Level[] levels; + + public void setDatatype(String datatype) { + this.datatype = datatype; + } + + public void addIdentifier(String key, Object value) { + if (identifiers == null) { + identifiers = new HashMap(); + } + identifiers.put(key, value); + } + + public void setParameters(String... params) { + this.parameters = params; + } + + public void setLevels(Level... levels) { + this.levels = levels; + } + + public String getDatatype() { + return datatype; + } + + public Map getIdentifiers() { + return identifiers; + } + + public String[] getParameters() { + return parameters; + } + + public Level[] getLevels() { + return levels; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGeometryData.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGeometryData.java new file mode 100644 index 0000000000..603c4b7d07 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGeometryData.java @@ -0,0 +1,294 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.impl; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import javax.measure.converter.ConversionException; +import javax.measure.unit.Unit; + +import com.raytheon.uf.common.dataaccess.geom.IGeometryData; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.time.DataTime; +import com.vividsolutions.jts.geom.Geometry; + +/** + * A default geometry data object if factory developers do not wish to create + * their own IGeometryData implementations. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 9, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class DefaultGeometryData implements IGeometryData { + + /** + * A simple object to hold a value, type, and unit of a parameter + */ + private class GeomData { + private Object value; + + private Type type; + + private Unit unit; + } + + protected Map dataMap = new HashMap(); + + protected DataTime time; + + protected Level level; + + protected Geometry geometry; + + protected String locationName; + + protected Map attributes; + + @Override + public Object getAttribute(String key) { + Object result = null; + if (attributes != null) { + result = attributes.get(key); + } + return result; + } + + @Override + public DataTime getDataTime() { + return time; + } + + @Override + public Level getLevel() { + return level; + } + + @Override + public Geometry getGeometry() { + return geometry; + } + + @Override + public Set getParameters() { + return dataMap.keySet(); + } + + @Override + public String getString(String param) { + String result = null; + GeomData data = dataMap.get(param); + if (data != null) { + result = data.value.toString(); + } + return result; + } + + @Override + public Number getNumber(String param) { + Number result = null; + GeomData data = dataMap.get(param); + if (data != null) { + switch (data.type) { + case STRING: + result = Double.valueOf((String) data.value); + break; + case INT: + result = (Integer) data.value; + break; + case LONG: + result = (Long) data.value; + break; + case FLOAT: + result = (Float) data.value; + break; + case DOUBLE: + result = (Double) data.value; + break; + default: + throw new UnsupportedOperationException( + "Unable to handle data of type " + + data.value.getClass()); + } + } + return result; + } + + @Override + public Number getNumber(String param, Unit unit) { + Number result = null; + if (unit == null) { + throw new IllegalArgumentException( + "Unable to convert data to null unit"); + } + GeomData data = dataMap.get(param); + if (data != null) { + if (data.unit != null) { + if (data.unit.isCompatible(unit)) { + Number orig = getNumber(param); + result = data.unit.getConverterTo(unit).convert( + orig.doubleValue()); + } else { + throw new ConversionException("Requested unit " + unit + + " is incompatible with " + param + + " data's unit " + data.unit); + } + } else { + throw new ConversionException( + "Unable to convert data due to no unit associated with " + + param); + } + } + return result; + } + + @Override + public Unit getUnit(String param) { + Unit result = null; + GeomData data = dataMap.get(param); + if (data != null) { + result = data.unit; + } + return result; + } + + @Override + public Type getType(String param) { + Type result = null; + GeomData data = dataMap.get(param); + if (data != null) { + result = data.type; + } + return result; + } + + @Override + public String getLocationName() { + return locationName; + } + + /** + * Adds data for this IGeometryData + * + * @param parameter + * the parameter name + * @param value + * the value of the parameter + */ + public void addData(String parameter, Object value) { + addData(parameter, value, null, null); + } + + /** + * Adds data for this IGeometryData + * + * @param parameter + * the parameter name + * @param value + * the value of the parameter + * @param type + * the type of the value + */ + public void addData(String parameter, Object value, Type type) { + addData(parameter, value, type, null); + } + + /** + * Adds data for this IGeometryData + * + * @param parameter + * the parameter name + * @param value + * the value of the parameter + * @param unit + * the unit of the value + */ + public void addData(String parameter, Object value, Unit unit) { + addData(parameter, value, null, unit); + } + + /** + * Adds data for this IGeometryData + * + * @param parameter + * the parameter name + * @param value + * the value of the parameter + * @param type + * the type of the value + * @param unit + * the unit of the value + */ + public void addData(String parameter, Object value, Type type, Unit unit) { + GeomData data = new GeomData(); + data.value = value; + data.unit = unit; + data.type = type; + if (data.type == null) { + if (data.value instanceof String) { + data.type = Type.STRING; + } else if (data.value instanceof Double) { + // TODO do these ifs work or will any number fall into + // the first one? + data.type = Type.DOUBLE; + } else if (data.value instanceof Integer) { + data.type = Type.INT; + } else if (data.value instanceof Long) { + data.type = Type.LONG; + } else if (data.value instanceof Float) { + data.type = Type.FLOAT; + } + } + this.dataMap.put(parameter, data); + } + + public void setGeometry(Geometry geom) { + this.geometry = geom; + } + + public void setLevel(Level level) { + this.level = level; + } + + public void setDataTime(DataTime time) { + this.time = time; + } + + public void setLocationName(String locationName) { + this.locationName = locationName; + } + + public void setAttributes(Map attrs) { + this.attributes = attrs; + } + +} diff --git a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/NcCheckRequestHandler.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGeometryRequest.java similarity index 53% rename from edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/NcCheckRequestHandler.java rename to edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGeometryRequest.java index 4e91db9024..b67d782180 100644 --- a/edexOsgi/com.raytheon.edex.plugin.gfe/src/com/raytheon/edex/plugin/gfe/server/handler/svcbu/NcCheckRequestHandler.java +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGeometryRequest.java @@ -17,15 +17,13 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.edex.plugin.gfe.server.handler.svcbu; +package com.raytheon.uf.common.dataaccess.impl; -import com.raytheon.edex.plugin.gfe.svcbackup.SvcBackupUtil; -import com.raytheon.uf.common.dataplugin.gfe.request.NcCheckRequest; -import com.raytheon.uf.common.dataplugin.gfe.server.message.ServerResponse; -import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.dataaccess.geom.IGeometryRequest; +import com.vividsolutions.jts.geom.Envelope; /** - * TODO Add Description + * A default IGeometryRequest that can be used for most IGeometryRequests. * *
  * 
@@ -33,26 +31,40 @@ import com.raytheon.uf.common.serialization.comm.IRequestHandler;
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Nov 14, 2012            jdynina     Initial creation
+ * Nov 5, 2012            njensen     Initial creation
  * 
  * 
* - * @author jdynina + * @author njensen * @version 1.0 */ -public class NcCheckRequestHandler implements IRequestHandler{ +public class DefaultGeometryRequest extends AbstractDataRequest implements + IGeometryRequest { - public Object handleRequest(NcCheckRequest request) - throws Exception { - ServerResponse sr = new ServerResponse(); - if (!isNationalCenter()) { - sr.addMessage("Site is not a national center."); - } - return sr; + protected Envelope envelope; + + protected String[] locationNames; + + @Override + public void setEnvelope(Envelope env) { + this.envelope = env; } - public boolean isNationalCenter() { - return SvcBackupUtil.ncCheck(); + @Override + public Envelope getEnvelope() { + return envelope; } + + @Override + public void setLocationNames(String... locationNames) { + this.locationNames = locationNames; + + } + + @Override + public String[] getLocationNames() { + return locationNames; + } + } diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGridData.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGridData.java new file mode 100644 index 0000000000..654f1df779 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGridData.java @@ -0,0 +1,142 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.impl; + +import java.util.Map; + +import javax.measure.unit.Unit; + +import org.geotools.coverage.grid.GridGeometry2D; + +import com.raytheon.uf.common.dataaccess.grid.IGridData; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.geospatial.interpolation.data.DataDestination; +import com.raytheon.uf.common.geospatial.interpolation.data.DataSource; +import com.raytheon.uf.common.time.DataTime; + +/** + * A default grid data object if factory developers do not wish to create their + * own IGridData implementations. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 5, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class DefaultGridData implements IGridData { + + protected DataSource data; + + protected DataTime time; + + protected String parameter; + + protected Level level; + + protected Unit unit; + + protected GridGeometry2D gridGeometry; + + protected Map attributes; + + public DefaultGridData(DataSource data, GridGeometry2D gridGeometry) { + this.data = data; + this.gridGeometry = gridGeometry; + } + + @Override + public Object getAttribute(String key) { + Object result = null; + if (attributes != null) { + result = attributes.get(key); + } + return result; + } + + @Override + public DataTime getDataTime() { + return time; + } + + @Override + public String getParameter() { + return parameter; + } + + @Override + public Level getLevel() { + return level; + } + + @Override + public GridGeometry2D getGridGeometry() { + return gridGeometry; + } + + @Override + public Unit getUnit() { + return unit; + } + + @Override + public DataDestination populateData(DataDestination destination) { + if (destination == null) { + throw new IllegalArgumentException( + "Data destination must not be null"); + } + + for (int x = 0; x < gridGeometry.axisDimensionX; x++) { + for (int y = 0; y < gridGeometry.axisDimensionY; y++) { + destination.setDataValue(data.getDataValue(x, y), x, y); + } + } + return destination; + } + + public void setDataTime(DataTime time) { + this.time = time; + } + + public void setParameter(String parameter) { + this.parameter = parameter; + } + + public void setLevel(Level level) { + this.level = level; + } + + public void setUnit(Unit unit) { + this.unit = unit; + } + + public void setAttributes(Map attrs) { + this.attributes = attrs; + } + +} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GetCoverageHandler.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGridRequest.java similarity index 60% rename from edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GetCoverageHandler.java rename to edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGridRequest.java index 02e18bb35c..ef497d32c6 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/handler/GetCoverageHandler.java +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/DefaultGridRequest.java @@ -17,33 +17,41 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.edex.plugin.grib.handler; +package com.raytheon.uf.common.dataaccess.impl; -import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; -import com.raytheon.uf.common.dataplugin.grib.request.GetCoverageRequest; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.dataaccess.grid.IGridRequest; +import com.raytheon.uf.common.datastorage.Request; /** - * TODO Add Description + * A default IGridRequest that can be used for most IGridRequests. * *
  * 
  * SOFTWARE HISTORY
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Jan 8, 2010            rjpeter     Initial creation
+ * Nov 5, 2012            njensen     Initial creation
  * 
  * 
* - * @author rjpeter + * @author njensen * @version 1.0 */ -public class GetCoverageHandler implements IRequestHandler { +public class DefaultGridRequest extends AbstractDataRequest implements + IGridRequest { + + protected Request storageRequest; @Override - public GridCoverage handleRequest(GetCoverageRequest request) { - return GribSpatialCache.getInstance().getGrid(request.getModelName()); + public void setStorageRequest(Request request) { + this.storageRequest = request; } + + @Override + public Request getStorageRequest() { + return this.storageRequest; + } + } diff --git a/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/FactoryUtil.java b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/FactoryUtil.java new file mode 100644 index 0000000000..cf5b96f83e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataaccess/src/com/raytheon/uf/common/dataaccess/impl/FactoryUtil.java @@ -0,0 +1,74 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataaccess.impl; + +import java.util.Set; + +import com.raytheon.uf.common.dataaccess.IData; +import com.raytheon.uf.common.dataaccess.IDataFactory; +import com.raytheon.uf.common.dataaccess.IDataRequest; +import com.raytheon.uf.common.time.BinOffset; +import com.raytheon.uf.common.time.DataTime; + +/** + * Utilities for working with data factories + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 14, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class FactoryUtil { + + /** + * Convenience method that provides the getAvailableTimes(R, BinOffset) + * functionality by calling getAvailableTimes(R) and then applying the + * BinOffset to normalize the available times. + * + * @param factory + * the factory to retrieve times through + * @param request + * the request to find available times for + * @param binOffset + * the bin offset to apply + * @return the binned times + */ + public static , D extends IData> DataTime[] getAvailableTimes( + IDataFactory factory, R request, BinOffset binOffset) { + DataTime[] actualTimes = factory.getAvailableTimes(request); + if (binOffset != null) { + Set normalized = binOffset + .getNormalizedTimes(actualTimes); + return normalized.toArray(new DataTime[0]); + } else { + return actualTimes; + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/build.properties b/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/build.properties index 5791d48d5f..34d2e4d2da 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/build.properties +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/build.properties @@ -1,5 +1,4 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ - res/ + . diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/component-deploy.xml deleted file mode 100644 index b7006af084..0000000000 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/META-INF/MANIFEST.MF index 49c0c711f7..c487d8fef5 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/META-INF/MANIFEST.MF @@ -7,7 +7,6 @@ Bundle-Vendor: RAYTHEON Eclipse-RegisterBuddy: com.raytheon.edex.common, com.raytheon.uf.common.serialization Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: com.raytheon.uf.common.dataplugin.binlightning, - com.raytheon.uf.common.dataplugin.binlightning.dao, com.raytheon.uf.common.dataplugin.binlightning.impl Require-Bundle: com.raytheon.edex.common, org.geotools, diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/build.properties b/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/build.properties index 5791d48d5f..34d2e4d2da 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/build.properties +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/build.properties @@ -1,5 +1,4 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ - res/ + . diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/component-deploy.xml deleted file mode 100644 index 433bb481bd..0000000000 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.binlightning/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.cwat/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.cwat/META-INF/MANIFEST.MF index 9299b596be..c2b57e97dc 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.cwat/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.cwat/META-INF/MANIFEST.MF @@ -15,4 +15,3 @@ Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.common.dataplugin.cwat, com.raytheon.uf.common.dataplugin.cwat.dao -Import-Package: com.raytheon.uf.common.dataplugin.grib diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/META-INF/MANIFEST.MF index e7d07c71be..ff5ebc10f8 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/META-INF/MANIFEST.MF @@ -10,18 +10,13 @@ Export-Package: com.raytheon.uf.common.dataplugin.ffmp, com.raytheon.uf.common.dataplugin.ffmp.dao Require-Bundle: javax.persistence;bundle-version="1.0.0", com.raytheon.edex.common;bundle-version="1.11.1", - org.apache.commons.logging;bundle-version="1.0.4", - org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.monitor;bundle-version="1.11.5", - com.raytheon.uf.common.dataplugin, - com.raytheon.uf.common.dataplugin.qpf;bundle-version="1.11.9", com.raytheon.uf.common.hydro;bundle-version="1.11.11", com.raytheon.uf.common.mpe;bundle-version="1.11.11", com.raytheon.uf.common.localization;bundle-version="1.11.13", com.raytheon.uf.common.status;bundle-version="1.12.1174", com.raytheon.uf.common.site, - com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", com.raytheon.uf.common.dataplugin.shef;bundle-version="1.12.1174", - com.raytheon.uf.common.cache;bundle-version="1.12.1174" -Import-Package: com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.datastorage.hdf5 + com.raytheon.uf.common.cache;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0" diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPGuidanceBasin.java b/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPGuidanceBasin.java index c08bf448ea..3366acac1c 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPGuidanceBasin.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPGuidanceBasin.java @@ -100,7 +100,7 @@ public class FFMPGuidanceBasin extends FFMPBasin implements ISerializableObject return Float.NaN; } } - + /** * purge out old entries * @@ -178,14 +178,14 @@ public class FFMPGuidanceBasin extends FFMPBasin implements ISerializableObject return val; } - + /** * Gets a Value for a FFG source * * @param date * @return */ - public Float getValue(String sourceName, + public Float getValue(String sourceName, FFMPGuidanceInterpolation interpolation, long expiration) { Float dvalue = Float.NaN; @@ -209,23 +209,23 @@ public class FFMPGuidanceBasin extends FFMPBasin implements ISerializableObject */ public Float getValue(String sourceName, Date date, FFMPGuidanceInterpolation interpolation, long expiration) { - + Float dvalue = Float.NaN; Float value = Float.NaN; Date closestDate = getClosest(sourceName, date, expiration); - + if (closestDate != null) { value = getValue(closestDate, sourceName); } - + if (!value.isNaN()) { FFFGDataMgr dman = FFFGDataMgr.getInstance(); if (dman.isExpired() == false) { - dvalue = dman.adjustValue(dvalue, sourceName, this.pfaf, + dvalue = dman.adjustValue(value, sourceName, this.pfaf, this.countyFips); } else { - dvalue = value; + dvalue = value; } } @@ -244,30 +244,30 @@ public class FFMPGuidanceBasin extends FFMPBasin implements ISerializableObject Date rdate = null; if (guidValues != null && guidValues.size() > 0) { - - Date markerDate = guidValues.firstKey(); - - for (Date checkDate : guidValues.keySet()) { - - if (guidValues.get(checkDate).containsKey(sourceName)) { - float val = guidValues.get(checkDate).get(sourceName); - if (val != FFMPUtils.MISSING) { - - long time1 = markerDate.getTime(); - long time2 = checkDate.getTime(); - - if ((time1 - time2) < expiration) { - rdate = checkDate; - } - break; - } - } - } + + Date markerDate = guidValues.firstKey(); + + for (Date checkDate : guidValues.keySet()) { + + if (guidValues.get(checkDate).containsKey(sourceName)) { + float val = guidValues.get(checkDate).get(sourceName); + if (val != FFMPUtils.MISSING) { + + long time1 = markerDate.getTime(); + long time2 = checkDate.getTime(); + + if ((time1 - time2) < expiration) { + rdate = checkDate; + } + break; + } + } + } } return rdate; } - + /** * Get Closest Key * @@ -284,14 +284,14 @@ public class FFMPGuidanceBasin extends FFMPBasin implements ISerializableObject if (guidValues.containsKey(date)) { if (guidValues.get(date).containsKey(sourceName)) { - + float val = guidValues.get(date).get(sourceName); - + if (val != FFMPUtils.MISSING) { rdate = date; } } - } + } if (rdate == null) { diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPUtils.java b/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPUtils.java index d8197bc1a8..a7d3fb4e02 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPUtils.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.ffmp/src/com/raytheon/uf/common/dataplugin/ffmp/FFMPUtils.java @@ -31,11 +31,18 @@ import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.Map; +import java.util.Set; import org.geotools.coverage.grid.GridGeometry2D; import org.geotools.referencing.GeodeticCalculator; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.shef.util.ShefConstants; +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.responses.DbQueryResponse; import com.raytheon.uf.common.geospatial.ISpatialQuery; import com.raytheon.uf.common.geospatial.MapUtil; import com.raytheon.uf.common.geospatial.SpatialException; @@ -44,6 +51,7 @@ import com.raytheon.uf.common.hydro.spatial.HRAPCoordinates; import com.raytheon.uf.common.hydro.spatial.HRAPSubGrid; import com.raytheon.uf.common.monitor.scan.ScanUtils; import com.raytheon.uf.common.mpe.util.XmrgFile; +import com.raytheon.uf.common.serialization.comm.RequestRouter; import com.raytheon.uf.common.site.SiteMap; import com.raytheon.uf.edex.database.dao.CoreDao; import com.raytheon.uf.edex.database.dao.DaoConfig; @@ -71,7 +79,6 @@ import com.vividsolutions.jts.io.WKTWriter; * ------------ ---------- ----------- -------------------------- * 06/22/09 2152 D. Hladky Initial release * 06/18/12 DR 15108 G. Zhang Fix County FIPS 4-digit issue - * 09/05/12 DR 15164 G. Zhang Fix FFMP Table county/state name null issue * * * @author dhladky @@ -468,11 +475,12 @@ public class FFMPUtils { * @return */ public static FFMPCounty getCounty(Long pfaf, String mode) { - - String ftxt = (pfaf>=10000 ? ""+pfaf : "0"+pfaf);// DR 15164 - + + String ftxt = (pfaf >= 10000 ? "" + pfaf : "0" + pfaf);// DR 15164 + String sql = "SELECT county.countyname, county.state FROM " - + " mapdata.county WHERE county.fips = '" + ftxt/*pfaf*/ + "'";// DR 15164 + + " mapdata.county WHERE county.fips = '" + ftxt/* pfaf */+ "'";// DR + // 15164 ISpatialQuery sq = null; FFMPCounty county = new FFMPCounty(); @@ -620,10 +628,23 @@ public class FFMPUtils { */ @SuppressWarnings("unchecked") public static ArrayList getCountyInfo(Long fips, String mode) { - String ftxt = (fips>=10000 ? ""+fips : "0"+fips);// DR 15108: add a leading 0 to 4-digit FIPS. + String ftxt = (fips >= 10000 ? "" + fips : "0" + fips);// DR 15108: add + // a leading 0 to + // 4-digit FIPS. String sql1 = "SELECT county.gid from " + FFMPUtils.COUNTY_TABLE - + " WHERE county.fips = '" + ftxt/*fips*/ + "'";// DR 15108: use the 5-digit FIPS string. - System.out.println("___FFMPUtils.getCountyInfo(): county FIPS: "+ftxt);//Not a debug statement but for Template generation. + + " WHERE county.fips = '" + ftxt/* fips */+ "'";// DR 15108: + // use the + // 5-digit FIPS + // string. + System.out + .println("___FFMPUtils.getCountyInfo(): county FIPS: " + ftxt);// Not + // a + // debug + // statement + // but + // for + // Template + // generation. ISpatialQuery sq1 = null; ArrayList gids = new ArrayList(); @@ -873,31 +894,28 @@ public class FFMPUtils { * @param rfc * @return */ - public static HashMap getFFGModelInfo(String rfc) { + public static Set getFFGParameters(String rfc) { + Set ffgHash = new HashSet(); /** * Had to add this bit of code for ncgrib models */ - String sql = "select id, parameterabbreviation from awips.grib_models where modelname = 'FFG-" - + rfc.substring(1) + "\'"; - - ISpatialQuery sq = null; - HashMap ffgHash = new HashMap(); - + DbQueryRequest request = new DbQueryRequest(); + request.setEntityClass(GridRecord.class.getName()); + request.setDistinct(true); + request.addRequestField(GridConstants.PARAMETER_ABBREVIATION); + request.addConstraint(GridConstants.DATASET_ID, new RequestConstraint( + "FFG-" + rfc.substring(1))); try { - sq = SpatialQueryFactory.create(); - Object[] results = sq.dbRequest(sql, META_DB); - if (results.length > 0) { - for (int i = 0; i < results.length; i++) { - Object[] results2 = (Object[]) results[i]; - if (results2.length > 0) { - Integer id = (Integer) results2[0]; - String key = (String) results2[1]; - ffgHash.put(key, id); - } - } + DbQueryResponse response = (DbQueryResponse) RequestRouter + .route(request); + + for (Map map : response.getResults()) { + String key = (String) map + .get(GridConstants.PARAMETER_ABBREVIATION); + ffgHash.add(key); } - } catch (SpatialException e) { + } catch (Exception e) { e.printStackTrace(); } @@ -910,24 +928,29 @@ public class FFMPUtils { * @param id * @return */ - public static String getFFGDataURI(int id, String plugin) { - String sql = "select datauri from awips." + plugin - + " where modelinfo_id = " + id + " order by reftime desc"; - - ISpatialQuery sq = null; - String uri = null; + public static String getFFGDataURI(String rfc, String parameter, + String plugin) { + DbQueryRequest request = new DbQueryRequest(); + request.setEntityClass(GridRecord.class.getName()); + request.addRequestField("dataURI"); + request.addConstraint(GridConstants.PARAMETER_ABBREVIATION, + new RequestConstraint(parameter)); + request.addConstraint(GridConstants.DATASET_ID, new RequestConstraint( + "FFG-" + rfc.substring(1))); + request.setOrderByField("dataTime.refTime", OrderMode.DESC); try { - sq = SpatialQueryFactory.create(); - Object[] results = sq.dbRequest(sql, META_DB); - if (results.length > 0) { - uri = (String) results[0]; + DbQueryResponse response = (DbQueryResponse) RequestRouter + .route(request); + + for (Map map : response.getResults()) { + return (String) map.get("dataURI"); } - } catch (SpatialException e) { + } catch (Exception e) { e.printStackTrace(); } - return uri; + return null; } /** diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/META-INF/MANIFEST.MF index 7d033ebbf3..a794447395 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/META-INF/MANIFEST.MF @@ -45,12 +45,11 @@ Import-Package: com.raytheon.edex.exception, com.raytheon.uf.common.activetable, com.raytheon.uf.common.dataplugin, com.raytheon.uf.common.dataplugin.annotations, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.grib.util, com.raytheon.uf.common.dataplugin.persist, com.raytheon.uf.common.geospatial, com.raytheon.uf.common.geospatial.interpolation, com.raytheon.uf.common.geospatial.interpolation.data, + com.raytheon.uf.common.gridcoverage, com.raytheon.uf.common.localization, com.raytheon.uf.common.localization.exception, com.raytheon.uf.common.message, diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GFERecord.java b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GFERecord.java index 61c13dad69..14c17a2ce5 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GFERecord.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GFERecord.java @@ -97,7 +97,7 @@ public class GFERecord extends PluginDataObject { }; /** The name of the parm parameter */ - @Column(length = 100) + @Column(length = 32) @XmlAttribute @DynamicSerializeElement private String parmName; diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GridLocation.java b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GridLocation.java index 2e3cea2aa1..46a79b6376 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GridLocation.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/db/objects/GridLocation.java @@ -57,11 +57,11 @@ import com.raytheon.uf.common.dataplugin.gfe.grid.Grid2DBit; import com.raytheon.uf.common.dataplugin.gfe.reference.ReferenceData; import com.raytheon.uf.common.dataplugin.gfe.reference.ReferenceData.CoordinateType; import com.raytheon.uf.common.dataplugin.gfe.reference.ReferenceID; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.geospatial.CRSCache; import com.raytheon.uf.common.geospatial.ISpatialObject; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.adapters.CoordAdapter; import com.raytheon.uf.common.serialization.adapters.GeometryAdapter; diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/AbstractGfePrivilegedRequest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/AbstractGfePrivilegedRequest.java new file mode 100644 index 0000000000..685679e75e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/AbstractGfePrivilegedRequest.java @@ -0,0 +1,70 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.gfe.request; + +import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Privilege request for GFE for a given role Id. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 19, 2012            bgonzale     Initial creation
+ * 
+ * 
+ * + * @author bgonzale + * @version 1.0 + */ + +public class AbstractGfePrivilegedRequest extends AbstractPrivilegedRequest { + private final static String DEFAULT_ROLEID = "com.raytheon.localization.site/common_static/gfe"; + + @DynamicSerializeElement + private String roleId; + + /** + * + */ + public AbstractGfePrivilegedRequest() { + roleId = DEFAULT_ROLEID; + } + + /** + * @return the roleId + */ + public String getRoleId() { + return roleId; + } + + /** + * @param roleId + * the roleId to set + */ + public void setRoleId(String roleId) { + this.roleId = roleId; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/CheckPermissionsRequest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/CheckPermissionsRequest.java index 53a110b3e7..bc93c7a4f0 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/CheckPermissionsRequest.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/CheckPermissionsRequest.java @@ -19,9 +19,7 @@ **/ package com.raytheon.uf.common.dataplugin.gfe.request; -import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; -import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** * TODO Add Description @@ -41,31 +39,9 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; */ @DynamicSerialize -public class CheckPermissionsRequest extends AbstractGfeRequest { - - @DynamicSerializeElement - private IUser user; +public class CheckPermissionsRequest extends AbstractGfePrivilegedRequest { public CheckPermissionsRequest() { } - public CheckPermissionsRequest(IUser user) { - this.user = user; - } - - /** - * @return the user - */ - public IUser getUser() { - return user; - } - - /** - * @param user - * the user to set - */ - public void setUser(IUser user) { - this.user = user; - } - } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/ExportConfRequest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/ExportConfRequest.java index 339e341ba4..2530314a07 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/ExportConfRequest.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/ExportConfRequest.java @@ -19,7 +19,6 @@ **/ package com.raytheon.uf.common.dataplugin.gfe.request; -import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; @@ -42,7 +41,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; */ @DynamicSerialize -public class ExportConfRequest extends AbstractPrivilegedRequest { +public class ExportConfRequest extends AbstractGfePrivilegedRequest { @DynamicSerializeElement private String site; @@ -71,5 +70,4 @@ public class ExportConfRequest extends AbstractPrivilegedRequest { this.site = site; } - } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/MANIFEST.MF index 2e7785b508..004ced58e9 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/MANIFEST.MF @@ -17,13 +17,14 @@ Require-Bundle: javax.measure, com.raytheon.uf.common.serialization, com.raytheon.uf.common.serialization.comm, com.raytheon.uf.common.status, - com.raytheon.uf.common.localization -Import-Package: com.raytheon.uf.common.dataplugin.level, - com.raytheon.uf.common.geospatial + com.raytheon.uf.common.localization, + com.raytheon.uf.common.dataplugin.grid;bundle-version="1.0.0" +Import-Package: com.raytheon.uf.common.dataplugin.grid, + com.raytheon.uf.common.dataplugin.level, + com.raytheon.uf.common.geospatial, + com.raytheon.uf.common.gridcoverage, + com.raytheon.uf.common.gridcoverage.exception, + com.raytheon.uf.common.parameter Export-Package: com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.exception, - com.raytheon.uf.common.dataplugin.grib.request, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.grib.subgrid, - com.raytheon.uf.common.dataplugin.grib.util + com.raytheon.uf.common.dataplugin.grib.request Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject index 4eac3bc3e0..dd830b0b9e 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject @@ -1,9 +1,2 @@ com.raytheon.uf.common.dataplugin.grib.GribModel -com.raytheon.uf.common.dataplugin.grib.GribRecord -com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage -com.raytheon.uf.common.dataplugin.grib.spatial.projections.MercatorGridCoverage -com.raytheon.uf.common.dataplugin.grib.spatial.projections.PolarStereoGridCoverage -com.raytheon.uf.common.dataplugin.grib.spatial.projections.LambertConformalGridCoverage -com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef -com.raytheon.uf.common.dataplugin.grib.util.GridModel -com.raytheon.uf.common.dataplugin.grib.util.GridModelSet \ No newline at end of file +com.raytheon.uf.common.dataplugin.grib.GribRecord \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/CombinedGribRecord.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/CombinedGribRecord.java deleted file mode 100644 index fb988dbaa8..0000000000 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/CombinedGribRecord.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.raytheon.uf.common.dataplugin.grib; - -/** - * TODO Add Description - * - *
- * 
- * SOFTWARE HISTORY
- * 
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Mar 16, 2011            rgeorge     Initial creation
- * 
- * 
- * - * @author rgeorge - * @version 1.0 - */ -public class CombinedGribRecord extends GribRecord { - - private static final long serialVersionUID = 1L; - - GribRecord secondaryGribRecord; - - GribRecord primaryGribRecord; - - /** - * Default Constructor - * - * @param recordToCopy - * @param secondaryGribRecord - */ - public CombinedGribRecord(GribRecord recordToCopy, - GribRecord secondaryGribRecord) { - super(recordToCopy); - this.primaryGribRecord = recordToCopy; - this.secondaryGribRecord = secondaryGribRecord; - } - - public GribRecord getPrimaryGribRecord() { - return primaryGribRecord; - } - - public GribRecord getSecondaryGribRecord() { - return secondaryGribRecord; - } - -} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribModel.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribModel.java index ee1accc13f..f6b273a853 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribModel.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribModel.java @@ -40,17 +40,16 @@ import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang.builder.HashCodeBuilder; import com.raytheon.uf.common.dataplugin.annotations.DataURI; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** - * Class encapsulating parameter, level, and spatial information of the grib - * record. + * Deprecated, use grid * *
  * 
@@ -70,811 +69,812 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 @DynamicSerialize
+@Deprecated
 public class GribModel extends PersistableDataObject {
 
-	private static final long serialVersionUID = 4417959632479879335L;
-
-	/** The id */
-	@Id
-	@DynamicSerializeElement
-	private Integer id;
-
-	/** The originating center ID */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private int centerid;
-
-	/** The national subcenter ID */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private int subcenterid;
-
-	/** The generating process number */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private int genprocess;
-
-	/** The backgenprocess number */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private int backGenprocess;
-
-	/** The name of the grib parameter */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private String parameterName;
-
-	/**
-	 * The abbreviation for the grib parameter. For accumulation and probability
-	 * parameters, the duration is appended
-	 */
-	@Column
-	@DataURI(position = 1)
-	@XmlAttribute
-	@DynamicSerializeElement
-	private String parameterAbbreviation;
-
-	/** The unit for this grib parameter */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private String parameterUnit;
-
-	/** The grid number */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private String gridid;
-
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private int gridNumber;
-
-	/**
-	 * The pds template number (grib 2) from which this information was
-	 * extracted
-	 */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private int pdsTemplate;
-
-	/** The type of ensemble forecast (See Code table 4.6) */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	@DataURI(position = 3)
-	private Integer typeEnsemble;
-
-	/** The perturbation number of the ensemble */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	@DataURI(position = 4)
-	private Integer perturbationNumber;
-
-	/** The number of forecasts in the ensemble */
-	@Column
-	@XmlAttribute
-	@DynamicSerializeElement
-	private Integer numForecasts;
-
-	/** The unique model name (i.e.NAM212) */
-	@Column
-	@DataURI(position = 0)
-	@XmlAttribute
-	@DynamicSerializeElement
-	private String modelName;
-
-	/** The database insert time of the object */
-	@Column(columnDefinition = "timestamp without time zone default now()", insertable = false, updatable = true)
-	private Calendar insertTime;
-
-	/** The spatial information */
-	@ManyToOne
-	@PrimaryKeyJoinColumn
-	@XmlElement
-	@DynamicSerializeElement
-	private GridCoverage location;
-
-	@ManyToOne
-	@PrimaryKeyJoinColumn
-	@XmlElement
-	@DynamicSerializeElement
-	@DataURI(position = 2, embedded = true)
-	private Level level;
-
-	/**
-	 * Creates and empty GribModel object
-	 */
-	public GribModel() {
-
-	}
-
-	/**
-	 * Copy constructor
-	 */
-	public GribModel(GribModel copy) {
-		this.backGenprocess = copy.backGenprocess;
-		this.centerid = copy.centerid;
-		this.genprocess = copy.genprocess;
-		this.gridid = copy.gridid;
-		this.gridNumber = copy.gridNumber;
-		this.id = copy.id;
-		if (copy.insertTime != null) {
-			this.insertTime = (Calendar) copy.insertTime.clone();
-		}
-		this.level = copy.level;
-		this.location = copy.location;
-		this.modelName = copy.modelName;
-		this.numForecasts = copy.numForecasts;
-		this.parameterAbbreviation = copy.parameterAbbreviation;
-		this.parameterName = copy.parameterName;
-		this.parameterUnit = copy.parameterUnit;
-		this.pdsTemplate = copy.pdsTemplate;
-		this.perturbationNumber = copy.perturbationNumber;
-		this.subcenterid = copy.subcenterid;
-		this.typeEnsemble = copy.typeEnsemble;
-	}
-
-	public String toString() {
-		StringBuffer buffer = new StringBuffer();
-
-		buffer.append("                    Id: ").append(id).append("\n");
-		buffer.append("          PDS Template: ").append(pdsTemplate)
-				.append("\n");
-		buffer.append("                Center: ").append(centerid).append("\n");
-		buffer.append("             Subcenter: ").append(subcenterid)
-				.append("\n");
-		buffer.append("            Model Name: ").append(modelName)
-				.append("\n");
-		buffer.append("    Generating Process: ").append(genprocess)
-				.append("\n");
-		buffer.append("        Parameter Name: ").append(parameterName)
-				.append("\n");
-		buffer.append("Parameter Abbreviation: ").append(parameterAbbreviation)
-				.append("\n");
-		buffer.append("        Parameter Unit: ")
-				.append(getParamterUnitPrettyString()).append("\n");
-
-		if (level != null) {
-			buffer.append("            Level Name: ")
-					.append(level.getMasterLevel().getName()).append("\n");
-			buffer.append("       Level One Value: ")
-					.append(level.getLevelonevalue()).append("\n");
-			buffer.append("       Level Two Value: ")
-					.append(level.getLeveltwovalue()).append("\n");
-			buffer.append("            Level Unit: ")
-					.append(getLevelUnitPrettyString()).append("\n");
-		} else {
-
-		}
-		buffer.append("         Type Ensemble: ").append(typeEnsemble)
-				.append("\n");
-		buffer.append("   Perturbation Number: ").append(perturbationNumber)
-				.append("\n");
-		buffer.append("         Num Forecasts: ").append(numForecasts)
-				.append("\n");
-		if (location == null) {
-			buffer.append("Location is NULL").append("\n");
-		} else {
-			buffer.append(location.toString()).append("\n");
-		}
-
-		return buffer.toString();
-	}
-
-	public int hashCode() {
-		HashCodeBuilder builder = new HashCodeBuilder();
-		builder.append(modelName);
-		builder.append(parameterName);
-		builder.append(parameterAbbreviation);
-		builder.append(level);
-		builder.append(typeEnsemble);
-		builder.append(perturbationNumber);
-		return builder.toHashCode();
-	}
-
-	/**
-	 * Generates a unique id from the hashcode of this object
-	 */
-	public void generateId() {
-		this.id = hashCode();
-	}
-
-	/**
-	 * Gets the level unit as a javax.measure.Unit object. If the level unit
-	 * string cannot be successfully converted to a javax.measure.Unit
-	 * object, Unit.ONE is returned
-	 * 
-	 * @return The level unit as a javax.measure.Unit object
-	 */
-	public Unit getLevelUnitObject() {
-		Unit retVal = Unit.ONE;
-
-		if (level != null) {
-			Unit tmp = level.getMasterLevel().getUnit();
-			if (tmp != null) {
-				retVal = tmp;
-			}
-		}
-		return retVal;
-	}
-
-	/**
-	 * Gets the level unit as a pretty string meaning superscripts and
-	 * subscripts are printed accordingly
-	 * 
-	 * @return The level unit as a pretty string
-	 */
-	public String getLevelUnitPrettyString() {
-		Unit unitObj = getLevelUnitObject();
-		if (unitObj.equals(Unit.ONE)) {
-			return "";
-		} else {
-			return unitObj.toString();
-		}
-	}
-
-	/**
-	 * Gets the parameter unit as a javax.measure.Unit object. If the
-	 * parameter unit string cannot be successfully converted to a
-	 * javax.measure.Unit object, Unit.ONE is returned
-	 * 
-	 * @return The parameter unit as a javax.measure.Unit object
-	 */
-	public Unit getParameterUnitObject() {
-		Unit retVal = Unit.ONE;
-
-		if (this.parameterUnit != null) {
-			try {
-				retVal = UnitFormat.getUCUMInstance().parseProductUnit(
-						this.parameterUnit, new ParsePosition(0));
-			} catch (Exception e) {
-				// Unable to parse
-				retVal = Unit.ONE;
-			}
-		}
-		return retVal;
-	}
-
-	/**
-	 * Gets the parameter unit as a pretty string meaning superscripts and
-	 * subscripts are printed accordingly
-	 * 
-	 * @return The parameter unit as a pretty string
-	 */
-	public String getParamterUnitPrettyString() {
-		Unit unitObj = getParameterUnitObject();
-		if (unitObj.equals(Unit.ONE)) {
-			return this.parameterUnit;
-		} else {
-			return unitObj.toString();
-		}
-	}
-
-	/**
-	 * Gets the id
-	 * 
-	 * @return The id
-	 */
-	public Integer getId() {
-		return id;
-	}
-
-	/**
-	 * Sets the id
-	 * 
-	 * @param id
-	 *            The id
-	 */
-	public void setId(Integer id) {
-		this.id = id;
-	}
-
-	/**
-	 * Gets the center id
-	 * 
-	 * @return The center id
-	 */
-	public int getCenterid() {
-		return centerid;
-	}
-
-	/**
-	 * Sets the subcenter id
-	 * 
-	 * @param centerid
-	 *            The subcenter id
-	 */
-	public void setCenterid(int centerid) {
-		this.centerid = centerid;
-	}
-
-	/**
-	 * Gets the subcenter id
-	 * 
-	 * @return The subcenter id
-	 */
-	public int getSubcenterid() {
-		return subcenterid;
-	}
-
-	/**
-	 * Sets the subcenter id
-	 * 
-	 * @param subcenterid
-	 *            The subcenter id
-	 */
-	public void setSubcenterid(int subcenterid) {
-		this.subcenterid = subcenterid;
-	}
-
-	/**
-	 * Gets the genprocess
-	 * 
-	 * @return The genprocess
-	 */
-	public int getGenprocess() {
-		return genprocess;
-	}
-
-	/**
-	 * Sets the genproces
-	 * 
-	 * @param genprocess
-	 *            The genprocess
-	 */
-	public void setGenprocess(int genprocess) {
-		this.genprocess = genprocess;
-	}
-
-	/**
-	 * Gets the parameter name
-	 * 
-	 * @return parameterName
-	 */
-	public String getParameterName() {
-		return parameterName;
-	}
-
-	/**
-	 * Sets the parameter name
-	 * 
-	 * @param parameterName
-	 *            The parameter nam
-	 */
-	public void setParameterName(String parameterName) {
-		this.parameterName = parameterName;
-	}
-
-	/**
-	 * Gets the parameter abbreviation
-	 * 
-	 * @return The parameter abbreviation
-	 */
-	public String getParameterAbbreviation() {
-		return parameterAbbreviation;
-	}
-
-	/**
-	 * Sets the parameter abbreviation
-	 * 
-	 * @param parameterAbbreviation
-	 *            The parameter abbreviation
-	 */
-	public void setParameterAbbreviation(String parameterAbbreviation) {
-		this.parameterAbbreviation = parameterAbbreviation;
-	}
-
-	/**
-	 * Gets the parameter unit
-	 * 
-	 * @return The parameter unit
-	 */
-	public String getParameterUnit() {
-		return parameterUnit;
-	}
-
-	/**
-	 * Sets the parameter unit
-	 * 
-	 * @param parameterUnit
-	 *            The parameter unit
-	 */
-	public void setParameterUnit(String parameterUnit) {
-		this.parameterUnit = parameterUnit;
-	}
-
-	/**
-	 * Gets the level name
-	 * 
-	 * @return The level name
-	 */
-	public String getLevelName() {
-		String rval = null;
-		if (level != null) {
-			rval = level.getMasterLevel().getName();
-		}
-		return rval;
-	}
-
-	/**
-	 * Gets the level one value
-	 * 
-	 * @return The level one value
-	 */
-	public Double getLevelOneValue() {
-		Double rval = null;
-		if (level != null) {
-			rval = level.getLevelonevalue();
-		}
-		return rval;
-	}
-
-	/**
-	 * Gets the level two value
-	 * 
-	 * @return The level two value
-	 */
-	public Double getLevelTwoValue() {
-		Double rval = null;
-		if (level != null) {
-			rval = level.getLeveltwovalue();
-		}
-		return rval;
-	}
-
-	/**
-	 * Gets the level unit
-	 * 
-	 * @return The level unit
-	 */
-	public String getLevelUnit() {
-		String rval = null;
-		if (level != null) {
-			rval = level.getMasterLevel().getUnitString();
-		}
-		return rval;
-	}
-
-	/**
-	 * Gets the level info
-	 * 
-	 * @return The level info
-	 */
-	public String getLevelInfo() {
-		String rval = null;
-		if (level != null) {
-			rval = level.getLevelInfo();
-		}
-		return rval;
-	}
-
-	/**
-	 * Gets the grid id
-	 * 
-	 * @return The grid id
-	 */
-	public String getGridid() {
-		return gridid;
-	}
-
-	/**
-	 * Sets the grid id
-	 * 
-	 * @param gridid
-	 *            The grid id
-	 */
-	public void setGridid(String gridid) {
-		this.gridid = gridid;
-		try {
-			gridNumber = Integer.parseInt(gridid);
-		} catch (NumberFormatException e) {
-			gridNumber = -1;
-		}
-	}
-
-	/**
-	 * Gets the database insert time
-	 * 
-	 * @return The database insert time
-	 */
-	public Calendar getInsertTime() {
-		return insertTime;
-	}
-
-	/**
-	 * Sets the database insert time
-	 * 
-	 * @param insertTime
-	 *            The database insert time
-	 */
-	public void setInsertTime(Calendar insertTime) {
-		this.insertTime = insertTime;
-	}
-
-	/**
-	 * Gets the spatial information
-	 * 
-	 * @return The spatial information
-	 */
-	public GridCoverage getLocation() {
-		return location;
-	}
-
-	/**
-	 * Sets the spatial information
-	 * 
-	 * @param location
-	 *            The spatial information
-	 */
-	public void setLocation(GridCoverage location) {
-		this.location = location;
-	}
-
-	/**
-	 * Gets the level information
-	 * 
-	 * @return The level information
-	 */
-	public Level getLevel() {
-		return level;
-	}
-
-	/**
-	 * Sets the level information
-	 * 
-	 * @param level
-	 *            The level information
-	 */
-	public void setLevel(Level level) {
-		this.level = level;
-	}
-
-	/**
-	 * Gets the ensemble type
-	 * 
-	 * @return The ensemble type
-	 */
-	public Integer getTypeEnsemble() {
-		return typeEnsemble;
-	}
-
-	/**
-	 * Sets the ensemble type
-	 * 
-	 * @param typeEnsemble
-	 *            The ensemble type
-	 */
-	public void setTypeEnsemble(Integer typeEnsemble) {
-		this.typeEnsemble = typeEnsemble;
-	}
-
-	/**
-	 * Gets the perturbation number
-	 * 
-	 * @return The perturbation number
-	 */
-	public Integer getPerturbationNumber() {
-		return perturbationNumber;
-	}
-
-	/**
-	 * Sets the perturbation number
-	 * 
-	 * @param perturbationNumber
-	 *            The perturbation number
-	 */
-	public void setPerturbationNumber(Integer perturbationNumber) {
-		this.perturbationNumber = perturbationNumber;
-	}
-
-	/**
-	 * Gets the number of ensemble forecasts
-	 * 
-	 * @return The number of ensemble forecasts
-	 */
-	public Integer getNumForecasts() {
-		return numForecasts;
-	}
-
-	/**
-	 * Sets the number of ensemble forecasts
-	 * 
-	 * @param numForecasts
-	 *            The number of ensemble forecasts
-	 */
-	public void setNumForecasts(Integer numForecasts) {
-		this.numForecasts = numForecasts;
-	}
-
-	/**
-	 * Gets the background generating process
-	 * 
-	 * @return The background generating process
-	 */
-	public int getBackGenprocess() {
-		return backGenprocess;
-	}
-
-	/**
-	 * Sets the background generating process
-	 * 
-	 * @param backGenprocess
-	 *            The background generating process
-	 */
-	public void setBackGenprocess(int backGenprocess) {
-		this.backGenprocess = backGenprocess;
-	}
-
-	/**
-	 * Gets the pds template number
-	 * 
-	 * @return The pds template number
-	 */
-	public int getPdsTemplate() {
-		return pdsTemplate;
-	}
-
-	/**
-	 * Sets the pds template number
-	 * 
-	 * @param pdsTemplate
-	 *            The pds template number
-	 */
-	public void setPdsTemplate(int pdsTemplate) {
-		this.pdsTemplate = pdsTemplate;
-	}
-
-	public String getModelName() {
-		return modelName;
-	}
-
-	public String getModelTitle() {
-		String rval = null;
-
-		if (modelName != null) {
-			GridModel model = GribModelLookup.getInstance().getModelByName(
-					modelName);
-
-			if (model != null) {
-				rval = model.getTitle();
-			} else {
-				rval = modelName;
-			}
-		}
-
-		return rval;
-	}
-
-	public void setModelName(String modelName) {
-		this.modelName = modelName;
-	}
-
-	public int getGridNumber() {
-		return gridNumber;
-	}
-
-	public void setGridNumber(int gridNumber) {
-		this.gridNumber = gridNumber;
-	}
-
-	@Override
-	public boolean equals(Object obj) {
-		if (obj == null) {
-			return false;
-		} else if (!obj.getClass().equals(this.getClass())) {
-			return false;
-		}
-		GribModel rhs = (GribModel) obj;
-		if (centerid != rhs.centerid) {
-			return false;
-		} else if (genprocess != rhs.genprocess) {
-			return false;
-		} else if (gridNumber != rhs.gridNumber) {
-			return false;
-		} else if (pdsTemplate != rhs.pdsTemplate) {
-			return false;
-		} else if (subcenterid != rhs.subcenterid) {
-			return false;
-		} else if (backGenprocess != rhs.backGenprocess) {
-			return false;
-		}
-
-		if (gridid == null) {
-			if (rhs.gridid != null) {
-				return false;
-			}
-		} else if (!gridid.equals(rhs.gridid)) {
-			return false;
-		}
-
-		if (insertTime == null) {
-			if (rhs.insertTime != null) {
-				return false;
-			}
-		} else if (!insertTime.equals(rhs.insertTime)) {
-			return false;
-		}
-
-		if (level == null) {
-			if (rhs.level != null) {
-				return false;
-			}
-		} else if (!level.equals(rhs.level)) {
-			return false;
-		}
-
-		if (location == null) {
-			if (rhs.location != null) {
-				return false;
-			}
-		} else if (!location.equals(rhs.location)) {
-			return false;
-		}
-
-		if (modelName == null) {
-			if (rhs.modelName != null) {
-				return false;
-			}
-		} else if (!modelName.equals(rhs.modelName)) {
-			return false;
-		}
-
-		if (numForecasts == null) {
-			if (rhs.numForecasts != null) {
-				return false;
-			}
-		} else if (!numForecasts.equals(rhs.numForecasts)) {
-			return false;
-		}
-
-		if (parameterAbbreviation == null) {
-			if (rhs.parameterAbbreviation != null) {
-				return false;
-			}
-		} else if (!parameterAbbreviation.equals(rhs.parameterAbbreviation)) {
-			return false;
-		}
-
-		if (parameterName == null) {
-			if (rhs.parameterName != null) {
-				return false;
-			}
-		} else if (!parameterName.equals(rhs.parameterName)) {
-			return false;
-		}
-
-		if (parameterUnit == null) {
-			if (rhs.parameterUnit != null) {
-				return false;
-			}
-		} else if (!parameterUnit.equals(rhs.parameterUnit)) {
-			return false;
-		}
-
-		if (perturbationNumber == null) {
-			if (rhs.perturbationNumber != null) {
-				return false;
-			}
-		} else if (!perturbationNumber.equals(rhs.perturbationNumber)) {
-			return false;
-		}
-
-		if (typeEnsemble == null) {
-			if (rhs.typeEnsemble != null) {
-				return false;
-			}
-		} else if (!typeEnsemble.equals(rhs.typeEnsemble)) {
-			return false;
-		}
-		return true;
-	}
+    private static final long serialVersionUID = 4417959632479879335L;
+
+    /** The id */
+    @Id
+    @DynamicSerializeElement
+    private Integer id;
+
+    /** The originating center ID */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private int centerid;
+
+    /** The national subcenter ID */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private int subcenterid;
+
+    /** The generating process number */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private int genprocess;
+
+    /** The backgenprocess number */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private int backGenprocess;
+
+    /** The name of the grib parameter */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private String parameterName;
+
+    /**
+     * The abbreviation for the grib parameter. For accumulation and probability
+     * parameters, the duration is appended
+     */
+    @Column
+    @DataURI(position = 1)
+    @XmlAttribute
+    @DynamicSerializeElement
+    private String parameterAbbreviation;
+
+    /** The unit for this grib parameter */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private String parameterUnit;
+
+    /** The grid number */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private String gridid;
+
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private int gridNumber;
+
+    /**
+     * The pds template number (grib 2) from which this information was
+     * extracted
+     */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private int pdsTemplate;
+
+    /** The type of ensemble forecast (See Code table 4.6) */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    @DataURI(position = 3)
+    private Integer typeEnsemble;
+
+    /** The perturbation number of the ensemble */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    @DataURI(position = 4)
+    private Integer perturbationNumber;
+
+    /** The number of forecasts in the ensemble */
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private Integer numForecasts;
+
+    /** The unique model name (i.e.NAM212) */
+    @Column
+    @DataURI(position = 0)
+    @XmlAttribute
+    @DynamicSerializeElement
+    private String modelName;
+
+    /** The database insert time of the object */
+    @Column(columnDefinition = "timestamp without time zone default now()", insertable = false, updatable = true)
+    private Calendar insertTime;
+
+    /** The spatial information */
+    @ManyToOne
+    @PrimaryKeyJoinColumn
+    @XmlElement
+    @DynamicSerializeElement
+    private GridCoverage location;
+
+    @ManyToOne
+    @PrimaryKeyJoinColumn
+    @XmlElement
+    @DynamicSerializeElement
+    @DataURI(position = 2, embedded = true)
+    private Level level;
+
+    /**
+     * Creates and empty GribModel object
+     */
+    public GribModel() {
+
+    }
+
+    /**
+     * Copy constructor
+     */
+    public GribModel(GribModel copy) {
+        this.backGenprocess = copy.backGenprocess;
+        this.centerid = copy.centerid;
+        this.genprocess = copy.genprocess;
+        this.gridid = copy.gridid;
+        this.gridNumber = copy.gridNumber;
+        this.id = copy.id;
+        if (copy.insertTime != null) {
+            this.insertTime = (Calendar) copy.insertTime.clone();
+        }
+        this.level = copy.level;
+        this.location = copy.location;
+        this.modelName = copy.modelName;
+        this.numForecasts = copy.numForecasts;
+        this.parameterAbbreviation = copy.parameterAbbreviation;
+        this.parameterName = copy.parameterName;
+        this.parameterUnit = copy.parameterUnit;
+        this.pdsTemplate = copy.pdsTemplate;
+        this.perturbationNumber = copy.perturbationNumber;
+        this.subcenterid = copy.subcenterid;
+        this.typeEnsemble = copy.typeEnsemble;
+    }
+
+    public String toString() {
+        StringBuffer buffer = new StringBuffer();
+
+        buffer.append("                    Id: ").append(id).append("\n");
+        buffer.append("          PDS Template: ").append(pdsTemplate)
+                .append("\n");
+        buffer.append("                Center: ").append(centerid).append("\n");
+        buffer.append("             Subcenter: ").append(subcenterid)
+                .append("\n");
+        buffer.append("            Model Name: ").append(modelName)
+                .append("\n");
+        buffer.append("    Generating Process: ").append(genprocess)
+                .append("\n");
+        buffer.append("        Parameter Name: ").append(parameterName)
+                .append("\n");
+        buffer.append("Parameter Abbreviation: ").append(parameterAbbreviation)
+                .append("\n");
+        buffer.append("        Parameter Unit: ")
+                .append(getParamterUnitPrettyString()).append("\n");
+
+        if (level != null) {
+            buffer.append("            Level Name: ")
+                    .append(level.getMasterLevel().getName()).append("\n");
+            buffer.append("       Level One Value: ")
+                    .append(level.getLevelonevalue()).append("\n");
+            buffer.append("       Level Two Value: ")
+                    .append(level.getLeveltwovalue()).append("\n");
+            buffer.append("            Level Unit: ")
+                    .append(getLevelUnitPrettyString()).append("\n");
+        } else {
+
+        }
+        buffer.append("         Type Ensemble: ").append(typeEnsemble)
+                .append("\n");
+        buffer.append("   Perturbation Number: ").append(perturbationNumber)
+                .append("\n");
+        buffer.append("         Num Forecasts: ").append(numForecasts)
+                .append("\n");
+        if (location == null) {
+            buffer.append("Location is NULL").append("\n");
+        } else {
+            buffer.append(location.toString()).append("\n");
+        }
+
+        return buffer.toString();
+    }
+
+    public int hashCode() {
+        HashCodeBuilder builder = new HashCodeBuilder();
+        builder.append(modelName);
+        builder.append(parameterName);
+        builder.append(parameterAbbreviation);
+        builder.append(level);
+        builder.append(typeEnsemble);
+        builder.append(perturbationNumber);
+        return builder.toHashCode();
+    }
+
+    /**
+     * Generates a unique id from the hashcode of this object
+     */
+    public void generateId() {
+        this.id = hashCode();
+    }
+
+    /**
+     * Gets the level unit as a javax.measure.Unit object. If the level unit
+     * string cannot be successfully converted to a javax.measure.Unit
+     * object, Unit.ONE is returned
+     * 
+     * @return The level unit as a javax.measure.Unit object
+     */
+    public Unit getLevelUnitObject() {
+        Unit retVal = Unit.ONE;
+
+        if (level != null) {
+            Unit tmp = level.getMasterLevel().getUnit();
+            if (tmp != null) {
+                retVal = tmp;
+            }
+        }
+        return retVal;
+    }
+
+    /**
+     * Gets the level unit as a pretty string meaning superscripts and
+     * subscripts are printed accordingly
+     * 
+     * @return The level unit as a pretty string
+     */
+    public String getLevelUnitPrettyString() {
+        Unit unitObj = getLevelUnitObject();
+        if (unitObj.equals(Unit.ONE)) {
+            return "";
+        } else {
+            return unitObj.toString();
+        }
+    }
+
+    /**
+     * Gets the parameter unit as a javax.measure.Unit object. If the
+     * parameter unit string cannot be successfully converted to a
+     * javax.measure.Unit object, Unit.ONE is returned
+     * 
+     * @return The parameter unit as a javax.measure.Unit object
+     */
+    public Unit getParameterUnitObject() {
+        Unit retVal = Unit.ONE;
+
+        if (this.parameterUnit != null) {
+            try {
+                retVal = UnitFormat.getUCUMInstance().parseProductUnit(
+                        this.parameterUnit, new ParsePosition(0));
+            } catch (Exception e) {
+                // Unable to parse
+                retVal = Unit.ONE;
+            }
+        }
+        return retVal;
+    }
+
+    /**
+     * Gets the parameter unit as a pretty string meaning superscripts and
+     * subscripts are printed accordingly
+     * 
+     * @return The parameter unit as a pretty string
+     */
+    public String getParamterUnitPrettyString() {
+        Unit unitObj = getParameterUnitObject();
+        if (unitObj.equals(Unit.ONE)) {
+            return this.parameterUnit;
+        } else {
+            return unitObj.toString();
+        }
+    }
+
+    /**
+     * Gets the id
+     * 
+     * @return The id
+     */
+    public Integer getId() {
+        return id;
+    }
+
+    /**
+     * Sets the id
+     * 
+     * @param id
+     *            The id
+     */
+    public void setId(Integer id) {
+        this.id = id;
+    }
+
+    /**
+     * Gets the center id
+     * 
+     * @return The center id
+     */
+    public int getCenterid() {
+        return centerid;
+    }
+
+    /**
+     * Sets the subcenter id
+     * 
+     * @param centerid
+     *            The subcenter id
+     */
+    public void setCenterid(int centerid) {
+        this.centerid = centerid;
+    }
+
+    /**
+     * Gets the subcenter id
+     * 
+     * @return The subcenter id
+     */
+    public int getSubcenterid() {
+        return subcenterid;
+    }
+
+    /**
+     * Sets the subcenter id
+     * 
+     * @param subcenterid
+     *            The subcenter id
+     */
+    public void setSubcenterid(int subcenterid) {
+        this.subcenterid = subcenterid;
+    }
+
+    /**
+     * Gets the genprocess
+     * 
+     * @return The genprocess
+     */
+    public int getGenprocess() {
+        return genprocess;
+    }
+
+    /**
+     * Sets the genproces
+     * 
+     * @param genprocess
+     *            The genprocess
+     */
+    public void setGenprocess(int genprocess) {
+        this.genprocess = genprocess;
+    }
+
+    /**
+     * Gets the parameter name
+     * 
+     * @return parameterName
+     */
+    public String getParameterName() {
+        return parameterName;
+    }
+
+    /**
+     * Sets the parameter name
+     * 
+     * @param parameterName
+     *            The parameter nam
+     */
+    public void setParameterName(String parameterName) {
+        this.parameterName = parameterName;
+    }
+
+    /**
+     * Gets the parameter abbreviation
+     * 
+     * @return The parameter abbreviation
+     */
+    public String getParameterAbbreviation() {
+        return parameterAbbreviation;
+    }
+
+    /**
+     * Sets the parameter abbreviation
+     * 
+     * @param parameterAbbreviation
+     *            The parameter abbreviation
+     */
+    public void setParameterAbbreviation(String parameterAbbreviation) {
+        this.parameterAbbreviation = parameterAbbreviation;
+    }
+
+    /**
+     * Gets the parameter unit
+     * 
+     * @return The parameter unit
+     */
+    public String getParameterUnit() {
+        return parameterUnit;
+    }
+
+    /**
+     * Sets the parameter unit
+     * 
+     * @param parameterUnit
+     *            The parameter unit
+     */
+    public void setParameterUnit(String parameterUnit) {
+        this.parameterUnit = parameterUnit;
+    }
+
+    /**
+     * Gets the level name
+     * 
+     * @return The level name
+     */
+    public String getLevelName() {
+        String rval = null;
+        if (level != null) {
+            rval = level.getMasterLevel().getName();
+        }
+        return rval;
+    }
+
+    /**
+     * Gets the level one value
+     * 
+     * @return The level one value
+     */
+    public Double getLevelOneValue() {
+        Double rval = null;
+        if (level != null) {
+            rval = level.getLevelonevalue();
+        }
+        return rval;
+    }
+
+    /**
+     * Gets the level two value
+     * 
+     * @return The level two value
+     */
+    public Double getLevelTwoValue() {
+        Double rval = null;
+        if (level != null) {
+            rval = level.getLeveltwovalue();
+        }
+        return rval;
+    }
+
+    /**
+     * Gets the level unit
+     * 
+     * @return The level unit
+     */
+    public String getLevelUnit() {
+        String rval = null;
+        if (level != null) {
+            rval = level.getMasterLevel().getUnitString();
+        }
+        return rval;
+    }
+
+    /**
+     * Gets the level info
+     * 
+     * @return The level info
+     */
+    public String getLevelInfo() {
+        String rval = null;
+        if (level != null) {
+            rval = level.getLevelInfo();
+        }
+        return rval;
+    }
+
+    /**
+     * Gets the grid id
+     * 
+     * @return The grid id
+     */
+    public String getGridid() {
+        return gridid;
+    }
+
+    /**
+     * Sets the grid id
+     * 
+     * @param gridid
+     *            The grid id
+     */
+    public void setGridid(String gridid) {
+        this.gridid = gridid;
+        try {
+            gridNumber = Integer.parseInt(gridid);
+        } catch (NumberFormatException e) {
+            gridNumber = -1;
+        }
+    }
+
+    /**
+     * Gets the database insert time
+     * 
+     * @return The database insert time
+     */
+    public Calendar getInsertTime() {
+        return insertTime;
+    }
+
+    /**
+     * Sets the database insert time
+     * 
+     * @param insertTime
+     *            The database insert time
+     */
+    public void setInsertTime(Calendar insertTime) {
+        this.insertTime = insertTime;
+    }
+
+    /**
+     * Gets the spatial information
+     * 
+     * @return The spatial information
+     */
+    public GridCoverage getLocation() {
+        return location;
+    }
+
+    /**
+     * Sets the spatial information
+     * 
+     * @param location
+     *            The spatial information
+     */
+    public void setLocation(GridCoverage location) {
+        this.location = location;
+    }
+
+    /**
+     * Gets the level information
+     * 
+     * @return The level information
+     */
+    public Level getLevel() {
+        return level;
+    }
+
+    /**
+     * Sets the level information
+     * 
+     * @param level
+     *            The level information
+     */
+    public void setLevel(Level level) {
+        this.level = level;
+    }
+
+    /**
+     * Gets the ensemble type
+     * 
+     * @return The ensemble type
+     */
+    public Integer getTypeEnsemble() {
+        return typeEnsemble;
+    }
+
+    /**
+     * Sets the ensemble type
+     * 
+     * @param typeEnsemble
+     *            The ensemble type
+     */
+    public void setTypeEnsemble(Integer typeEnsemble) {
+        this.typeEnsemble = typeEnsemble;
+    }
+
+    /**
+     * Gets the perturbation number
+     * 
+     * @return The perturbation number
+     */
+    public Integer getPerturbationNumber() {
+        return perturbationNumber;
+    }
+
+    /**
+     * Sets the perturbation number
+     * 
+     * @param perturbationNumber
+     *            The perturbation number
+     */
+    public void setPerturbationNumber(Integer perturbationNumber) {
+        this.perturbationNumber = perturbationNumber;
+    }
+
+    /**
+     * Gets the number of ensemble forecasts
+     * 
+     * @return The number of ensemble forecasts
+     */
+    public Integer getNumForecasts() {
+        return numForecasts;
+    }
+
+    /**
+     * Sets the number of ensemble forecasts
+     * 
+     * @param numForecasts
+     *            The number of ensemble forecasts
+     */
+    public void setNumForecasts(Integer numForecasts) {
+        this.numForecasts = numForecasts;
+    }
+
+    /**
+     * Gets the background generating process
+     * 
+     * @return The background generating process
+     */
+    public int getBackGenprocess() {
+        return backGenprocess;
+    }
+
+    /**
+     * Sets the background generating process
+     * 
+     * @param backGenprocess
+     *            The background generating process
+     */
+    public void setBackGenprocess(int backGenprocess) {
+        this.backGenprocess = backGenprocess;
+    }
+
+    /**
+     * Gets the pds template number
+     * 
+     * @return The pds template number
+     */
+    public int getPdsTemplate() {
+        return pdsTemplate;
+    }
+
+    /**
+     * Sets the pds template number
+     * 
+     * @param pdsTemplate
+     *            The pds template number
+     */
+    public void setPdsTemplate(int pdsTemplate) {
+        this.pdsTemplate = pdsTemplate;
+    }
+
+    public String getModelName() {
+        return modelName;
+    }
+
+    public String getModelTitle() {
+        String rval = null;
+
+        if (modelName != null) {
+            DatasetInfo model = DatasetInfoLookup.getInstance().getInfo(
+                    modelName);
+
+            if (model != null) {
+                rval = model.getTitle();
+            } else {
+                rval = modelName;
+            }
+        }
+
+        return rval;
+    }
+
+    public void setModelName(String modelName) {
+        this.modelName = modelName;
+    }
+
+    public int getGridNumber() {
+        return gridNumber;
+    }
+
+    public void setGridNumber(int gridNumber) {
+        this.gridNumber = gridNumber;
+    }
+
+    @Override
+    public boolean equals(Object obj) {
+        if (obj == null) {
+            return false;
+        } else if (!obj.getClass().equals(this.getClass())) {
+            return false;
+        }
+        GribModel rhs = (GribModel) obj;
+        if (centerid != rhs.centerid) {
+            return false;
+        } else if (genprocess != rhs.genprocess) {
+            return false;
+        } else if (gridNumber != rhs.gridNumber) {
+            return false;
+        } else if (pdsTemplate != rhs.pdsTemplate) {
+            return false;
+        } else if (subcenterid != rhs.subcenterid) {
+            return false;
+        } else if (backGenprocess != rhs.backGenprocess) {
+            return false;
+        }
+
+        if (gridid == null) {
+            if (rhs.gridid != null) {
+                return false;
+            }
+        } else if (!gridid.equals(rhs.gridid)) {
+            return false;
+        }
+
+        if (insertTime == null) {
+            if (rhs.insertTime != null) {
+                return false;
+            }
+        } else if (!insertTime.equals(rhs.insertTime)) {
+            return false;
+        }
+
+        if (level == null) {
+            if (rhs.level != null) {
+                return false;
+            }
+        } else if (!level.equals(rhs.level)) {
+            return false;
+        }
+
+        if (location == null) {
+            if (rhs.location != null) {
+                return false;
+            }
+        } else if (!location.equals(rhs.location)) {
+            return false;
+        }
+
+        if (modelName == null) {
+            if (rhs.modelName != null) {
+                return false;
+            }
+        } else if (!modelName.equals(rhs.modelName)) {
+            return false;
+        }
+
+        if (numForecasts == null) {
+            if (rhs.numForecasts != null) {
+                return false;
+            }
+        } else if (!numForecasts.equals(rhs.numForecasts)) {
+            return false;
+        }
+
+        if (parameterAbbreviation == null) {
+            if (rhs.parameterAbbreviation != null) {
+                return false;
+            }
+        } else if (!parameterAbbreviation.equals(rhs.parameterAbbreviation)) {
+            return false;
+        }
+
+        if (parameterName == null) {
+            if (rhs.parameterName != null) {
+                return false;
+            }
+        } else if (!parameterName.equals(rhs.parameterName)) {
+            return false;
+        }
+
+        if (parameterUnit == null) {
+            if (rhs.parameterUnit != null) {
+                return false;
+            }
+        } else if (!parameterUnit.equals(rhs.parameterUnit)) {
+            return false;
+        }
+
+        if (perturbationNumber == null) {
+            if (rhs.perturbationNumber != null) {
+                return false;
+            }
+        } else if (!perturbationNumber.equals(rhs.perturbationNumber)) {
+            return false;
+        }
+
+        if (typeEnsemble == null) {
+            if (rhs.typeEnsemble != null) {
+                return false;
+            }
+        } else if (!typeEnsemble.equals(rhs.typeEnsemble)) {
+            return false;
+        }
+        return true;
+    }
 }
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribPathProvider.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribPathProvider.java
index 8895b11105..c2a5cc78b9 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribPathProvider.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribPathProvider.java
@@ -25,11 +25,12 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;
 
+import com.raytheon.uf.common.dataplugin.grid.GridConstants;
 import com.raytheon.uf.common.dataplugin.persist.DefaultPathProvider;
 import com.raytheon.uf.common.dataplugin.persist.IPersistable;
 
 /**
- * Path provider for storing grib data to HDF5
+ * Deprecated, use grid
  * 
  * 
  * 
@@ -44,6 +45,7 @@ import com.raytheon.uf.common.dataplugin.persist.IPersistable;
  * @author bphillip
  * @version 1
  */
+@Deprecated
 public class GribPathProvider extends DefaultPathProvider {
 
     private static final DecimalFormat forecastHourFormat = new DecimalFormat(
@@ -118,4 +120,102 @@ public class GribPathProvider extends DefaultPathProvider {
     public String formatTime(Date date) {
         return fileNameFormat.get().format(date);
     }
+
+    @Override
+    public String getHDFPath(String pluginName, IPersistable persistable) {
+        return super.getHDFPath(GridConstants.GRID, persistable);
+    }
+
+    @Override
+    public List getKeyNames(String pluginName) {
+        List keys = super.getKeyNames(GridConstants.GRID);
+        List newKeys = new ArrayList(keys.size());
+        for (String key : keys) {
+            if (key.equals(GridConstants.DATASET_ID)) {
+                newKeys.add("modelInfo.modelName");
+            } else if (key.equals(GridConstants.MASTER_LEVEL_NAME)) {
+                newKeys.add("modelInfo.level.masterLevel.name");
+            } else if (key.equals(GridConstants.PARAMETER_ABBREVIATION)) {
+                newKeys.add("modelInfo.parameterAbbreviation");
+            } else if (key.equals(GridConstants.LEVEL_ONE)) {
+                newKeys.add("modelInfo.level.levelonevalue");
+            } else if (key.equals(GridConstants.LEVEL_TWO)) {
+                newKeys.add("modelInfo.level.leveltwovalue");
+            } else {
+                newKeys.add(key);
+            }
+        }
+        return newKeys;
+    }
+
+    public String getGroup(GribRecord record) {
+        StringBuilder datauri = new StringBuilder("/grid/");
+        datauri.append(record.getDataTime().toString().replace(" ", "_"));
+        datauri.append("/");
+        datauri.append(record.getModelInfo().getModelName());
+        // secondaryid
+        datauri.append("/");
+        if (record.getGridVersion() != 0) {
+            datauri.append("Version");
+            datauri.append(record.getGridVersion());
+        } else {
+            datauri.append("null");
+        }
+        datauri.append("/");
+        if (record.getModelInfo().getPerturbationNumber() != null) {
+            switch (record.getModelInfo().getPerturbationNumber()) {
+            case 1:
+                datauri.append("ctl1");
+                break;
+            case 2:
+                datauri.append("ctl2");
+                break;
+            case 3:
+                datauri.append("n1");
+                break;
+            case 4:
+                datauri.append("p1");
+                break;
+            case 5:
+                datauri.append("n2");
+                break;
+            case 6:
+                datauri.append("p2");
+                break;
+            case 7:
+                datauri.append("n3");
+                break;
+            case 8:
+                datauri.append("p3");
+                break;
+            case 9:
+                datauri.append("n4");
+                break;
+            case 10:
+                datauri.append("p4");
+                break;
+            case 11:
+                datauri.append("n5");
+                break;
+            case 12:
+                datauri.append("p5");
+                break;
+            default:
+                datauri.append("null");
+            }
+        } else {
+            datauri.append("null");
+        }
+        datauri.append("/");
+        datauri.append(record.getModelInfo().getLocation().getId());
+        datauri.append("/");
+        datauri.append(record.getModelInfo().getParameterAbbreviation());
+        datauri.append("/");
+        datauri.append(record.getModelInfo().getLevelName());
+        datauri.append("/");
+        datauri.append(record.getModelInfo().getLevelOneValue());
+        datauri.append("/");
+        datauri.append(record.getModelInfo().getLevelTwoValue());
+        return datauri.toString();
+    }
 }
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribRecord.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribRecord.java
index dc13c6cad0..2ca402a1ca 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribRecord.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/GribRecord.java
@@ -22,6 +22,8 @@ package com.raytheon.uf.common.dataplugin.grib;
 
 import java.util.Arrays;
 import java.util.Calendar;
+import java.util.Date;
+import java.util.TimeZone;
 
 import javax.persistence.CascadeType;
 import javax.persistence.Column;
@@ -38,6 +40,7 @@ import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlRootElement;
 
 import com.raytheon.uf.common.dataplugin.IDecoderGettable;
+import com.raytheon.uf.common.dataplugin.IPrecomputedRange;
 import com.raytheon.uf.common.dataplugin.annotations.DataURI;
 import com.raytheon.uf.common.dataplugin.persist.IHDFFilePathProvider;
 import com.raytheon.uf.common.dataplugin.persist.IPersistable;
@@ -48,7 +51,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
 import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
 
 /**
- * Record class for the grib plugin.
+ * Deprecated, use grid
  * 
  * 
  * 
@@ -68,8 +71,9 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 @DynamicSerialize
+@Deprecated
 public class GribRecord extends PersistablePluginDataObject implements
-        IPersistable, ISpatialEnabled {
+        IPersistable, ISpatialEnabled, IPrecomputedRange {
 
     private static final long serialVersionUID = 1L;
 
@@ -171,6 +175,16 @@ public class GribRecord extends PersistablePluginDataObject implements
     @DynamicSerializeElement
     private Integer resCompFlags;
 
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private double dataMin;
+
+    @Column
+    @XmlAttribute
+    @DynamicSerializeElement
+    private double dataMax;
+
     /**
      * Creates an empty GribRecord
      */
@@ -240,6 +254,22 @@ public class GribRecord extends PersistablePluginDataObject implements
         return null;
     }
 
+    @Override
+    public Date getPersistenceTime() {
+        Calendar c = getInsertTime();
+        if (c == null)
+            return null;
+
+        return c.getTime();
+    }
+
+    @Override
+    public void setPersistenceTime(Date persistTime) {
+        Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
+        c.setTime(persistTime);
+        setInsertTime(c);
+    }
+
     @Override
     public ISpatialObject getSpatialObject() {
         return modelInfo.getLocation();
@@ -475,11 +505,42 @@ public class GribRecord extends PersistablePluginDataObject implements
         this.resCompFlags = resCompFlags;
     }
 
-    @Override
     public void setId(int id) {
         this.id = id;
     }
 
+    /**
+     * @return the dataMin
+     */
+    @Override
+    public double getDataMin() {
+        return dataMin;
+    }
+
+    /**
+     * @param dataMin
+     *            the dataMin to set
+     */
+    public void setDataMin(double dataMin) {
+        this.dataMin = dataMin;
+    }
+
+    /**
+     * @return the dataMax
+     */
+    @Override
+    public double getDataMax() {
+        return dataMax;
+    }
+
+    /**
+     * @param dataMax
+     *            the dataMax to set
+     */
+    public void setDataMax(double dataMax) {
+        this.dataMax = dataMax;
+    }
+
     @Override
     public int hashCode() {
         final int prime = 31;
@@ -506,15 +567,12 @@ public class GribRecord extends PersistablePluginDataObject implements
 
     @Override
     public boolean equals(Object obj) {
-        if (this == obj) {
+        if (this == obj)
             return true;
-        }
-        if (obj == null) {
+        if (obj == null)
             return false;
-        }
-        if (getClass() != obj.getClass()) {
+        if (getClass() != obj.getClass())
             return false;
-        }
         GribRecord other = (GribRecord) obj;
         if (!this.dataTime.getRefTimeAsCalendar().equals(
                 other.getDataTime().getRefTimeAsCalendar())) {
@@ -527,59 +585,42 @@ public class GribRecord extends PersistablePluginDataObject implements
             return false;
         }
 
-        if (gridVersion != other.gridVersion) {
+        if (gridVersion != other.gridVersion)
             return false;
-        }
-        if (!Arrays.equals(hybridCoordList, other.hybridCoordList)) {
+        if (!Arrays.equals(hybridCoordList, other.hybridCoordList))
             return false;
-        }
-        if (hybridGrid != other.hybridGrid) {
+        if (hybridGrid != other.hybridGrid)
             return false;
-        }
-        if (isVector != other.isVector) {
+        if (isVector != other.isVector)
             return false;
-        }
-        if (!Arrays.equals(localSection, other.localSection)) {
+        if (!Arrays.equals(localSection, other.localSection))
             return false;
-        }
-        if (localSectionUsed != other.localSectionUsed) {
+        if (localSectionUsed != other.localSectionUsed)
             return false;
-        }
-        if (localTableVersion != other.localTableVersion) {
+        if (localTableVersion != other.localTableVersion)
             return false;
-        }
-        if (masterTableVersion != other.masterTableVersion) {
+        if (masterTableVersion != other.masterTableVersion)
             return false;
-        }
         if (modelInfo == null) {
-            if (other.modelInfo != null) {
+            if (other.modelInfo != null)
                 return false;
-            }
-        } else if (!modelInfo.equals(other.modelInfo)) {
+        } else if (!modelInfo.equals(other.modelInfo))
             return false;
-        }
-        if (processedDataType != other.processedDataType) {
+        if (processedDataType != other.processedDataType)
             return false;
-        }
-        if (productionStatus != other.productionStatus) {
+        if (productionStatus != other.productionStatus)
             return false;
-        }
-        if (refTimeSignificance != other.refTimeSignificance) {
+        if (refTimeSignificance != other.refTimeSignificance)
             return false;
-        }
         if (resCompFlags == null) {
-            if (other.resCompFlags != null) {
+            if (other.resCompFlags != null)
                 return false;
-            }
-        } else if (!resCompFlags.equals(other.resCompFlags)) {
+        } else if (!resCompFlags.equals(other.resCompFlags))
             return false;
-        }
-        if (thinnedGrid != other.thinnedGrid) {
+        if (thinnedGrid != other.thinnedGrid)
             return false;
-        }
-        if (!Arrays.equals(thinnedPts, other.thinnedPts)) {
+        if (!Arrays.equals(thinnedPts, other.thinnedPts))
             return false;
-        }
         return true;
     }
 
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoveragesRequest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoveragesRequest.java
index 5d538a3118..9e49b88000 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoveragesRequest.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoveragesRequest.java
@@ -27,7 +27,7 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest;
 
 /**
  * 
- * TODO Add Description
+ * Deprecated, use grid
  * 
  * 
  * 
@@ -43,6 +43,7 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest;
  * @version 1.0
  */
 @DynamicSerialize
+@Deprecated
 public class GetCoveragesRequest implements IServerRequest {
     @DynamicSerializeElement
     private List modelNames;
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GridDataRequestMessage.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GridDataRequestMessage.java
index 3102be7538..12f6aedfb7 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GridDataRequestMessage.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GridDataRequestMessage.java
@@ -19,8 +19,7 @@
  **/
 package com.raytheon.uf.common.dataplugin.grib.request;
 
-import com.raytheon.uf.common.dataplugin.grib.GribModel;
-import com.raytheon.uf.common.dataplugin.grib.GribRecord;
+import com.raytheon.uf.common.dataplugin.grid.GridRecord;
 import com.raytheon.uf.common.dataplugin.level.Level;
 import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
 import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
@@ -69,7 +68,7 @@ public class GridDataRequestMessage implements IServerRequest {
     private String parameterAbbreviation;
 
     @DynamicSerializeElement
-    private int pert = -999;
+    private String ensemble;
 
     @DynamicSerializeElement
     private int version = -999;
@@ -130,12 +129,12 @@ public class GridDataRequestMessage implements IServerRequest {
         this.parameterAbbreviation = parameterAbbreviation;
     }
 
-    public int getPert() {
-        return pert;
+    public String getEnsemble() {
+        return ensemble;
     }
 
-    public void setPert(int pert) {
-        this.pert = pert;
+    public void setEnsemble(String ensemble) {
+        this.ensemble = ensemble;
     }
 
     public int getVersion() {
@@ -146,18 +145,16 @@ public class GridDataRequestMessage implements IServerRequest {
         this.version = version;
     }
 
-    public void setInfoFromRecord(GribRecord record) {
-        GribModel info = record.getModelInfo();
+    public void setInfoFromRecord(GridRecord record) {
         DataTime time = record.getDataTime();
-        this.modelName = info.getModelName();
-        this.levelOne = info.getLevel().getLevelonevalue();
-        this.levelTwo = info.getLevel().getLeveltwovalue();
-        this.levelType = info.getLevel().getMasterLevel().getName();
-        this.parameterAbbreviation = info.getParameterAbbreviation();
-        if (info.getPerturbationNumber() != null) {
-            this.pert = info.getPerturbationNumber();
+        this.modelName = record.getDatasetId();
+        this.levelOne = record.getLevel().getLevelonevalue();
+        this.levelTwo = record.getLevel().getLeveltwovalue();
+        this.levelType = record.getLevel().getMasterLevel().getName();
+        this.parameterAbbreviation = record.getParameter().getAbbreviation();
+        if (record.getEnsembleId() != null) {
+            this.ensemble = record.getEnsembleId();
         }
-        this.version = record.getGridVersion();
         this.startTime = time.getRefTime().getTime();
         this.forecastTime = time.getFcstTime();
     }
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GribModelLookup.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GribModelLookup.java
deleted file mode 100644
index c664b6a207..0000000000
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/GribModelLookup.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/**
- * This software was developed and / or modified by Raytheon Company,
- * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
- * 
- * U.S. EXPORT CONTROLLED TECHNICAL DATA
- * This software product contains export-restricted data whose
- * export/transfer/disclosure is restricted by U.S. law. Dissemination
- * to non-U.S. persons whether in the United States or abroad requires
- * an export license or other authorization.
- * 
- * Contractor Name:        Raytheon Company
- * Contractor Address:     6825 Pine Street, Suite 340
- *                         Mail Stop B8
- *                         Omaha, NE 68106
- *                         402.291.0100
- * 
- * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
- * further licensing information.
- **/
-package com.raytheon.uf.common.dataplugin.grib.util;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
-import com.raytheon.uf.common.localization.IPathManager;
-import com.raytheon.uf.common.localization.LocalizationContext;
-import com.raytheon.uf.common.localization.LocalizationFile;
-import com.raytheon.uf.common.localization.PathManagerFactory;
-import com.raytheon.uf.common.serialization.SerializationUtil;
-
-public class GribModelLookup {
-
-    /** The logger */
-    protected transient Log logger = LogFactory.getLog(getClass());
-
-    /** The singleton instance of GribModelLookup **/
-    private static GribModelLookup instance;
-
-    /**
-     * A map of the models. The key is a hash of the center, grid, and process
-     * id rcg: changed key to a string, too many identical key were generated
-     * with the hash.
-     */
-    private final Map models;
-
-    /** A map of the models. The key is the title of the model */
-    private final Map modelsByName;
-
-    public static synchronized GribModelLookup getInstance() {
-        if (instance == null) {
-            instance = new GribModelLookup();
-        }
-        return instance;
-    }
-
-    private GribModelLookup() {
-        models = new HashMap();
-        modelsByName = new HashMap();
-        try {
-            initModelList();
-        } catch (GribException e) {
-            logger.error("Unable to initialize model list!", e);
-        }
-    }
-
-    public GridModel getModel(int center, int subcenter, String grid,
-            int process) {
-        return models.get(toKey(center, subcenter, grid, process));
-    }
-
-    public GridModel getModel(int center, int subcenter, int gridid, int process) {
-        return getModel(center, subcenter, String.valueOf(gridid), process);
-    }
-
-    public GridModel getModelByName(String name) {
-        return modelsByName.get(name);
-    }
-
-    public Map getModelByNameMap() {
-        return modelsByName;
-    }
-
-    private void initModelList() throws GribException {
-
-        LocalizationContext commonStaticBase = PathManagerFactory
-                .getPathManager().getContext(
-                        LocalizationContext.LocalizationType.COMMON_STATIC,
-                        LocalizationContext.LocalizationLevel.BASE);
-
-        LocalizationContext commonStaticSite = PathManagerFactory
-                .getPathManager().getContext(
-                        LocalizationContext.LocalizationType.COMMON_STATIC,
-                        LocalizationContext.LocalizationLevel.SITE);
-
-        LocalizationFile[] modelFiles = PathManagerFactory.getPathManager()
-                .listFiles(
-                        new LocalizationContext[] { commonStaticSite,
-                                commonStaticBase },
-                        "grid" + IPathManager.SEPARATOR + "models", // Win32
-                        new String[] { ".xml" }, false, true);
-        GridModelSet modelSet = new GridModelSet();
-
-        for (LocalizationFile modelFile : modelFiles) {
-            try {
-                modelSet.addModels(((GridModelSet) SerializationUtil
-                        .jaxbUnmarshalFromXmlFile(modelFile.getFile().getPath()))
-                        .getModels());
-            } catch (Exception e) {
-                throw new GribException("Unable to unmarshal grib models file:"
-                        + modelFile);
-            }
-        }
-
-        for (GridModel model : modelSet.getModels()) {
-            modelsByName.put(model.getName(), model);
-            for (int process : model.getProcess()) {
-                models.put(
-                        toKey(model.getCenter(),
-                                Integer.parseInt(model.getSubCenter()),
-                                String.valueOf(model.getGrid()), process),
-                        model);
-            }
-        }
-    }
-    
-    public Set getModelNames(){
-    	return modelsByName.keySet();
-    }
-
-    private String toKey(Integer center, Integer subcenter, String grid,
-            Integer process) {
-        StringBuilder builder = new StringBuilder();
-        builder.append(center);
-        builder.append(subcenter);
-        builder.append(grid);
-        builder.append(process);
-        return builder.toString();
-        // final int PRIME = 31;
-        // int result = 1;
-        // result = PRIME * result + ((center == null) ? 0 : center.hashCode());
-        // result = PRIME * result
-        // + ((subcenter == null) ? 0 : subcenter.hashCode());
-        // result = PRIME * result + ((grid == null) ? 0 : grid.hashCode());
-        // result = PRIME * result + ((process == null) ? 0 :
-        // process.hashCode());
-        // return result;
-    }
-}
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/test/com/raytheon/uf/common/dataplugin/grib/CoverageTest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/test/com/raytheon/uf/common/dataplugin/grib/CoverageTest.java
index f4e781e2a9..4cc4121c99 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/test/com/raytheon/uf/common/dataplugin/grib/CoverageTest.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grib/test/com/raytheon/uf/common/dataplugin/grib/CoverageTest.java
@@ -21,10 +21,10 @@ package com.raytheon.uf.common.dataplugin.grib;
 
 import org.opengis.metadata.spatial.PixelOrientation;
 
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.Corner;
-import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LambertConformalGridCoverage;
 import com.raytheon.uf.common.geospatial.MapUtil;
+import com.raytheon.uf.common.gridcoverage.Corner;
+import com.raytheon.uf.common.gridcoverage.LambertConformalGridCoverage;
+import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException;
 import com.vividsolutions.jts.geom.Coordinate;
 
 /**
@@ -103,7 +103,7 @@ public class CoverageTest {
             ll = MapUtil.gridCoordinateToLatLon(c, orient, cov);
             System.out.println("grid cell: " + c + " lonLat: " + ll);
 
-        } catch (GribException e) {
+        } catch (GridCoverageException e) {
             e.printStackTrace();
         }
     }
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.classpath b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.classpath
new file mode 100644
index 0000000000..ad32c83a78
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.classpath
@@ -0,0 +1,7 @@
+
+
+	
+	
+	
+	
+
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.project b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.project
new file mode 100644
index 0000000000..aae180a2b7
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.project
@@ -0,0 +1,28 @@
+
+
+	com.raytheon.uf.common.dataplugin.grid
+	
+	
+	
+	
+		
+			org.eclipse.jdt.core.javabuilder
+			
+			
+		
+		
+			org.eclipse.pde.ManifestBuilder
+			
+			
+		
+		
+			org.eclipse.pde.SchemaBuilder
+			
+			
+		
+	
+	
+		org.eclipse.pde.PluginNature
+		org.eclipse.jdt.core.javanature
+	
+
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.settings/org.eclipse.jdt.core.prefs
new file mode 100644
index 0000000000..3f00c1463d
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/.settings/org.eclipse.jdt.core.prefs
@@ -0,0 +1,8 @@
+#Fri Feb 03 13:18:16 CST 2012
+eclipse.preferences.version=1
+org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6
+org.eclipse.jdt.core.compiler.compliance=1.6
+org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
+org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.source=1.6
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/META-INF/MANIFEST.MF
new file mode 100644
index 0000000000..d562304799
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/META-INF/MANIFEST.MF
@@ -0,0 +1,42 @@
+Manifest-Version: 1.0
+Bundle-ManifestVersion: 2
+Bundle-Name: Grid
+Bundle-SymbolicName: com.raytheon.uf.common.dataplugin.grid
+Bundle-Version: 1.0.0.qualifier
+Bundle-Vendor: RAYTHEON
+Bundle-RequiredExecutionEnvironment: JavaSE-1.6
+Eclipse-RegisterBuddy:  com.raytheon.uf.common.serialization
+Eclipse-BuddyPolicy: registered, ext, global
+Import-Package: com.raytheon.uf.common.dataplugin,
+ com.raytheon.uf.common.dataplugin.annotations,
+ com.raytheon.uf.common.dataplugin.persist,
+ com.raytheon.uf.common.geospatial,
+ com.raytheon.uf.common.localization,
+ com.raytheon.uf.common.serialization,
+ com.raytheon.uf.common.serialization.annotations,
+ com.raytheon.uf.common.serialization.comm,
+ com.raytheon.uf.common.status,
+ com.raytheon.uf.common.time,
+ com.vividsolutions.jts.geom,
+ javax.persistence,
+ org.hibernate.annotations,
+ org.opengis.metadata.spatial
+Export-Package: com.raytheon.uf.common.dataplugin.grid,
+ com.raytheon.uf.common.dataplugin.grid.dataquery,
+ com.raytheon.uf.common.dataplugin.grid.dataset,
+ com.raytheon.uf.common.dataplugin.grid.datastorage,
+ com.raytheon.uf.common.dataplugin.grid.mapping,
+ com.raytheon.uf.common.dataplugin.grid.request,
+ com.raytheon.uf.common.dataplugin.grid.units,
+ com.raytheon.uf.common.dataplugin.grid.util
+Require-Bundle: javax.measure,
+ com.raytheon.uf.common.geospatial,
+ org.geotools,
+ com.raytheon.uf.common.localization,
+ com.raytheon.uf.common.datastorage,
+ com.raytheon.uf.common.gridcoverage;bundle-version="1.0.0",
+ com.raytheon.uf.common.parameter;bundle-version="1.0.0",
+ com.raytheon.uf.common.comm;bundle-version="1.12.1174",
+ com.raytheon.uf.common.dataquery;bundle-version="1.0.0",
+ com.raytheon.uf.common.dataplugin.level;bundle-version="1.12.1174",
+ com.raytheon.uf.common.util;bundle-version="1.12.1174"
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject
new file mode 100644
index 0000000000..bdc0a8ab06
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject
@@ -0,0 +1,4 @@
+com.raytheon.uf.common.dataplugin.grid.GridRecord
+com.raytheon.uf.common.dataplugin.grid.GridInfoRecord
+com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo
+com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoSet
\ No newline at end of file
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/build.properties b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/build.properties
new file mode 100644
index 0000000000..5791d48d5f
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/build.properties
@@ -0,0 +1,5 @@
+source.. = src/
+output.. = bin/
+bin.includes = META-INF/,\
+               .,\
+               res/
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/res/scripts/grid_indices.sql b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/res/scripts/grid_indices.sql
new file mode 100644
index 0000000000..a7a86e8478
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/res/scripts/grid_indices.sql
@@ -0,0 +1,41 @@
+/**
+ * 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.
+ **/
+
+CREATE INDEX "gridDatasetReftime_idx"
+  ON grid
+  USING btree
+  (info_id, reftime, forecasttime);
+
+CREATE INDEX "gridinfoNameParamLevel_idx"
+  ON grid_info
+  USING btree
+  (datasetid, parameter_abbreviation, level_id);
+  
+CREATE INDEX "gridinfoSecondryId_idx"
+  ON grid_info
+  USING btree
+  (secondaryid)
+  WHERE secondaryid IS NOT NULL;
+  
+CREATE INDEX "gridinfoEnsembleId_idx"
+  ON grid_info
+  USING btree
+  (ensembleid)
+  WHERE ensembleid IS NOT NULL;
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridConstants.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridConstants.java
new file mode 100644
index 0000000000..55ff4ae309
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridConstants.java
@@ -0,0 +1,91 @@
+/**
+ * This software was developed and / or modified by Raytheon Company,
+ * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
+ * 
+ * U.S. EXPORT CONTROLLED TECHNICAL DATA
+ * This software product contains export-restricted data whose
+ * export/transfer/disclosure is restricted by U.S. law. Dissemination
+ * to non-U.S. persons whether in the United States or abroad requires
+ * an export license or other authorization.
+ * 
+ * Contractor Name:        Raytheon Company
+ * Contractor Address:     6825 Pine Street, Suite 340
+ *                         Mail Stop B8
+ *                         Omaha, NE 68106
+ *                         402.291.0100
+ * 
+ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
+ * further licensing information.
+ **/
+package com.raytheon.uf.common.dataplugin.grid;
+
+/**
+ * 
+ * Contains some useful constants for dealing with grid data, mostly just
+ * hibernate names of attributes.
+ * 
+ * 
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 11, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class GridConstants { + + public static final String GRID = "grid"; + + public static final String PLUGIN_NAME = "pluginName"; + + public static final String INFO = "info"; + + public static final String INFO_ID = INFO + "." + GridInfoConstants.ID; + + public static final String DATASET_ID = INFO + "." + + GridInfoConstants.DATASET_ID; + + public static final String SECONDARY_ID = INFO + "." + + GridInfoConstants.SECONDARY_ID; + + public static final String ENSEMBLE_ID = INFO + "." + + GridInfoConstants.ENSEMBLE_ID; + + public static final String LOCATION = INFO + "." + + GridInfoConstants.LOCATION; + + public static final String LOCATION_ID = INFO + "." + + GridInfoConstants.LOCATION_ID; + + public static final String PARAMETER = INFO + "." + + GridInfoConstants.PARAMETER; + + public static final String PARAMETER_ABBREVIATION = INFO + "." + + GridInfoConstants.PARAMETER_ABBREVIATION; + + public static final String PARAMETER_NAME = INFO + "." + + GridInfoConstants.PARAMETER_NAME; + + public static final String PARAMETER_UNIT = INFO + "." + + GridInfoConstants.PARAMETER_UNIT; + + public static final String LEVEL = INFO + "." + GridInfoConstants.LEVEL; + + public static final String LEVEL_ID = INFO + "." + + GridInfoConstants.LEVEL_ID; + + public static final String MASTER_LEVEL_NAME = INFO + "." + + GridInfoConstants.MASTER_LEVEL_NAME; + + public static final String LEVEL_ONE = INFO + "." + + GridInfoConstants.LEVEL_ONE; + + public static final String LEVEL_TWO = INFO + "." + + GridInfoConstants.LEVEL_TWO; + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridInfoConstants.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridInfoConstants.java new file mode 100644 index 0000000000..8f0f9d6b2a --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridInfoConstants.java @@ -0,0 +1,73 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid; + +/** + * + * Contains some useful constants for dealing with grid info objects, mostly + * just hibernate names of attributes. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 11, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class GridInfoConstants { + + public static final String ID = "id"; + + public static final String DATASET_ID = "datasetId"; + + public static final String SECONDARY_ID = "secondaryId"; + + public static final String ENSEMBLE_ID = "ensembleId"; + + public static final String LOCATION = "location"; + + public static final String LOCATION_ID = LOCATION + ".id"; + + public static final String PARAMETER = "parameter"; + + public static final String PARAMETER_ABBREVIATION = PARAMETER + + ".abbreviation"; + + public static final String PARAMETER_NAME = PARAMETER + ".name"; + + public static final String PARAMETER_UNIT = PARAMETER + ".unitString"; + + public static final String LEVEL = "level"; + + public static final String LEVEL_ID = LEVEL + ".id"; + + public static final String MASTER_LEVEL_NAME = LEVEL + ".masterLevel.name"; + + public static final String LEVEL_ONE = LEVEL + ".levelonevalue"; + + public static final String LEVEL_TWO = LEVEL + ".leveltwovalue"; + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridInfoRecord.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridInfoRecord.java new file mode 100644 index 0000000000..70457c8047 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridInfoRecord.java @@ -0,0 +1,248 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.ManyToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.SequenceGenerator; +import javax.persistence.Table; + +import com.raytheon.uf.common.dataplugin.annotations.DataURI; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Contains all attributes of a grid record except time. This is done to save + * space in the db since across time most grid data has the same + * level/parameter/etc so having all other information in a separate table saves + * space and improves theoretical performance. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 21, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@Entity +@Table(name = "grid_info") +@SequenceGenerator(name = "GRIDINFO_GENERATOR", sequenceName = "gridinfo_seq", allocationSize = 1) +@DynamicSerialize +public class GridInfoRecord extends PersistableDataObject { + + private static final long serialVersionUID = 1L; + + /** The id */ + @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GRIDINFO_GENERATOR") + @DynamicSerializeElement + private Integer id; + + @Column + @DataURI(position = 0) + @DynamicSerializeElement + private String datasetId; + + /** + * Any string which can differentiate this record from other records with + * the same datasetId, examples of this would be for different versions of + * the same grid or for different events from the same model. + */ + @Column + @DataURI(position = 1) + @DynamicSerializeElement + private String secondaryId; + + @Column + @DynamicSerializeElement + @DataURI(position = 2) + private String ensembleId; + + /** The spatial information */ + @ManyToOne + @PrimaryKeyJoinColumn + @DataURI(position = 3) + @DynamicSerializeElement + private GridCoverage location; + + @ManyToOne + @PrimaryKeyJoinColumn + @DataURI(position = 4, embedded = true) + @DynamicSerializeElement + private Parameter parameter; + + @ManyToOne + @PrimaryKeyJoinColumn + @DynamicSerializeElement + @DataURI(position = 5, embedded = true) + private Level level; + + public GridInfoRecord() { + + } + + public GridInfoRecord(GridInfoRecord record) { + this.datasetId = record.getDatasetId(); + this.level = record.getLevel(); + this.location = record.getLocation(); + this.parameter = record.getParameter(); + this.ensembleId = record.getEnsembleId(); + this.secondaryId = record.getSecondaryId(); + this.id = record.getId(); + } + + public Integer getId() { + return id; + } + + public void setId(Integer id) { + this.id = id; + } + + public String getDatasetId() { + return datasetId; + } + + public void setDatasetId(String datasetId) { + this.datasetId = datasetId; + } + + public String getSecondaryId() { + return secondaryId; + } + + public void setSecondaryId(String secondaryId) { + this.secondaryId = secondaryId; + } + + public String getEnsembleId() { + return ensembleId; + } + + public void setEnsembleId(String ensembleId) { + this.ensembleId = ensembleId; + } + + public GridCoverage getLocation() { + return location; + } + + public void setLocation(GridCoverage location) { + this.location = location; + } + + public Parameter getParameter() { + return parameter; + } + + public void setParameter(Parameter parameter) { + this.parameter = parameter; + } + + public Level getLevel() { + return level; + } + + public void setLevel(Level level) { + this.level = level; + } + + @Override + public String toString() { + return "/" + datasetId + "/" + secondaryId + "/" + ensembleId + "/" + + location + "/" + parameter + "/" + level; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((datasetId == null) ? 0 : datasetId.hashCode()); + result = prime * result + + ((ensembleId == null) ? 0 : ensembleId.hashCode()); + result = prime * result + ((level == null) ? 0 : level.hashCode()); + result = prime * result + + ((location == null) ? 0 : location.hashCode()); + result = prime * result + + ((parameter == null) ? 0 : parameter.hashCode()); + result = prime * result + + ((secondaryId == null) ? 0 : secondaryId.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + GridInfoRecord other = (GridInfoRecord) obj; + if (datasetId == null) { + if (other.datasetId != null) + return false; + } else if (!datasetId.equals(other.datasetId)) + return false; + if (ensembleId == null) { + if (other.ensembleId != null) + return false; + } else if (!ensembleId.equals(other.ensembleId)) + return false; + if (level == null) { + if (other.level != null) + return false; + } else if (!level.equals(other.level)) + return false; + if (location == null) { + if (other.location != null) + return false; + } else if (!location.equals(other.location)) + return false; + if (parameter == null) { + if (other.parameter != null) + return false; + } else if (!parameter.equals(other.parameter)) + return false; + if (secondaryId == null) { + if (other.secondaryId != null) + return false; + } else if (!secondaryId.equals(other.secondaryId)) + return false; + return true; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridPathProvider.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridPathProvider.java new file mode 100644 index 0000000000..26573c7dc4 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridPathProvider.java @@ -0,0 +1,127 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ + +package com.raytheon.uf.common.dataplugin.grid; + +import java.text.DecimalFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import com.raytheon.uf.common.dataplugin.persist.DefaultPathProvider; +import com.raytheon.uf.common.dataplugin.persist.IPersistable; + +/** + * Path provider for storing gridded data to HDF5 + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * 4/24/09       1994        bphillip    Initial Creation
+ * 
+ * 
+ * + * @author bphillip + * @version 1 + */ +public class GridPathProvider extends DefaultPathProvider { + + private static final ThreadLocal forecastHourFormat = new ThreadLocal() { + + @Override + protected DecimalFormat initialValue() { + return new DecimalFormat("000"); + } + + }; + + private static final int SECONDS_PER_HOUR = 3600; + + public static final String FORECAST_HR_TOKEN = "-FH-"; + + private static GridPathProvider instance = new GridPathProvider(); + + public static final List STATIC_PARAMETERS; + + static { + STATIC_PARAMETERS = new ArrayList(); + STATIC_PARAMETERS.add("staticTopo"); + STATIC_PARAMETERS.add("staticXspacing"); + STATIC_PARAMETERS.add("staticYspacing"); + STATIC_PARAMETERS.add("staticCoriolis"); + STATIC_PARAMETERS.add("staticSpacing"); + } + + public static GridPathProvider getInstance() { + return instance; + } + + protected GridPathProvider() { + + } + + @Override + public String getHDFFileName(String pluginName, IPersistable persistable) { + + if (persistable == null) { + throw new IllegalArgumentException( + "Expected argument persistable is null"); + } + + if (!(persistable instanceof GridRecord)) { + throw new IllegalArgumentException( + "Argument persistable is of wrong type. Expected " + + GridRecord.class + " but got " + + persistable.getClass()); + } else if (pluginName == null) { + throw new IllegalArgumentException( + "Expected argument pluginName not set on object " + + persistable.toString()); + } + + GridRecord pdo = (GridRecord) persistable; + StringBuffer sb = new StringBuffer(64); + sb.append(pdo.getDatasetId()); + Date refTime = pdo.getDataTime().getRefTime(); + String refTimeString = null; + refTimeString = fileNameFormat.get().format(refTime); + sb.append(refTimeString); + sb.append(FORECAST_HR_TOKEN); + if (STATIC_PARAMETERS.contains(pdo.getParameter().getAbbreviation())) { + sb.append("000"); + } else { + long number = pdo.getDataTime().getFcstTime() / SECONDS_PER_HOUR; + String numberString = forecastHourFormat.get().format(number); + sb.append(numberString); + } + sb.append(".h5"); + + return sb.toString(); + } + + public String formatTime(Date date) { + String retVal = null; + retVal = fileNameFormat.get().format(date); + return retVal; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridRecord.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridRecord.java new file mode 100644 index 0000000000..df57ea4455 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/GridRecord.java @@ -0,0 +1,238 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid; + +import java.util.HashMap; +import java.util.Map; + +import javax.persistence.Entity; +import javax.persistence.ManyToOne; +import javax.persistence.PrimaryKeyJoinColumn; +import javax.persistence.Table; +import javax.persistence.Transient; +import javax.persistence.UniqueConstraint; + +import com.raytheon.uf.common.dataplugin.IDecoderGettable; +import com.raytheon.uf.common.dataplugin.annotations.DataURI; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.dataplugin.persist.IHDFFilePathProvider; +import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; +import com.raytheon.uf.common.geospatial.ISpatialEnabled; +import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * + * Record for storing generic gridded data. Everything interesting is stored in + * the info object since it allows us to reuse the info object for identical + * records at different times which saves db and improves theoretical + * performance. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 21, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@Entity +@Table(name = "grid", uniqueConstraints = { @UniqueConstraint(columnNames = { "dataURI" }) }) +@DynamicSerialize +public class GridRecord extends PersistablePluginDataObject implements + ISpatialEnabled { + + private static final long serialVersionUID = 1L; + + @ManyToOne + @PrimaryKeyJoinColumn + @DataURI(position = 1, embedded = true) + @DynamicSerializeElement + private GridInfoRecord info; + + /** + * Holds any extra attributes which may be specific to this data. These are + * not stored to the database or to hdf5 but they can be useful for passing + * additional parameters from a decoder to a post processor. + */ + @Transient + private Map extraAttributes; + + public GridRecord() { + super(); + } + + public GridRecord(GridRecord record) { + this.pluginName = record.getPluginName(); + this.dataTime = record.getDataTime(); + this.info = new GridInfoRecord(record.getInfoNotNull()); + if (record.getExtraAttributes() != null) { + this.extraAttributes = new HashMap( + record.getExtraAttributes()); + } + } + + public GridRecord(String uri) { + super(uri); + } + + public GridInfoRecord getInfo() { + + return info; + } + + public void setInfo(GridInfoRecord info) { + this.info = info; + } + + protected GridInfoRecord getInfoNotNull() { + if (info == null) { + info = new GridInfoRecord(); + } + return info; + } + + public String getDatasetId() { + return getInfoNotNull().getDatasetId(); + } + + public void setDatasetId(String datasetId) { + getInfoNotNull().setDatasetId(datasetId); + } + + public String getSecondaryId() { + return getInfoNotNull().getSecondaryId(); + } + + public void setSecondaryId(String secondaryId) { + getInfoNotNull().setSecondaryId(secondaryId); + } + + public GridCoverage getLocation() { + return getInfoNotNull().getLocation(); + } + + public void setLocation(GridCoverage location) { + getInfoNotNull().setLocation(location); + } + + public Parameter getParameter() { + return getInfoNotNull().getParameter(); + } + + public void setParameter(Parameter parameter) { + getInfoNotNull().setParameter(parameter); + } + + public Level getLevel() { + return getInfoNotNull().getLevel(); + } + + public void setLevel(Level level) { + getInfoNotNull().setLevel(level); + } + + public String getEnsembleId() { + return getInfoNotNull().getEnsembleId(); + } + + public void setEnsembleId(String ensembleId) { + getInfoNotNull().setEnsembleId(ensembleId); + } + + @Override + public IDecoderGettable getDecoderGettable() { + return null; + } + + @Override + public ISpatialObject getSpatialObject() { + return getLocation(); + } + + @Override + public IHDFFilePathProvider getHDFPathProvider() { + return GridPathProvider.getInstance(); + } + + public Map getExtraAttributes() { + return extraAttributes; + } + + public void setExtraAttributes(Map extraAttributes) { + this.extraAttributes = extraAttributes; + } + + /** + * Add an attribute to the data, if there are no attributes then the + * attribute map is created. + * + * @param key + * @param value + * @return the previous value of the attribute or null if there was none. + */ + public Object addExtraAttribute(String key, Object value) { + if (extraAttributes == null) { + extraAttributes = new HashMap(); + } + return extraAttributes.put(key, value); + } + + public Object getExtraAttribute(String key) { + if (extraAttributes == null) { + return null; + } + return extraAttributes.get(key); + } + + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + result = prime * result + ((info == null) ? 0 : info.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + GridRecord other = (GridRecord) obj; + if (info == null) { + if (other.info != null) + return false; + } else if (!info.equals(other.info)) + return false; + return true; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataquery/GridQueryAssembler.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataquery/GridQueryAssembler.java new file mode 100644 index 0000000000..dd1264a764 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataquery/GridQueryAssembler.java @@ -0,0 +1,308 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.dataquery; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +import com.raytheon.uf.common.comm.CommunicationException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.mapping.DatasetIdMapper; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.dataplugin.level.mapping.LevelMapper; +import com.raytheon.uf.common.dataquery.db.QueryParam; +import com.raytheon.uf.common.dataquery.requests.RequestConstraint; +import com.raytheon.uf.common.dataquery.requests.RequestConstraint.ConstraintType; +import com.raytheon.uf.common.parameter.mapping.ParameterMapper; +import com.raytheon.uf.common.util.mapping.Mapper; + +/** + * Assemble a query to use when requesting grid data. To use populate query + * fields using the various setters, then use getConstraintMap to get the + * constraints to use in a DbQueryRequest or other query type. This + * implementation uses the ParameterMapper, LevelMapper, and DatasetIdMapper so + * it can accept fields using namespaces that aren't in the database and + * transform them to valid database requests. Even if no custom namespace is + * being used the assembler should still be used to check for deprecated names. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 9, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridQueryAssembler { + + private String datasetIdNamespace; + + private String datasetId; + + private String secondaryId; + + private String ensembleId; + + private String parameterNamespace; + + private String parameterAbbreviation; + + private String levelNamespace; + + private String masterLevelName; + + private Double levelOneValue; + + private Double levelTwoValue; + + private String levelUnits; + + /** + * Construct an assembler that only checks for deprecated names. + */ + public GridQueryAssembler() { + this(Mapper.DEPRECATED); + } + + /** + * Construct an assembler that uses the provided namespace for all mappings. + */ + public GridQueryAssembler(String namespace) { + this(namespace, namespace, namespace); + } + + /** + * Construct an assembler that will use three separate namespaces for each + * type of mapping. + */ + public GridQueryAssembler(String datasetIdNamespace, + String parameterNamespace, String levelNamespace) { + this.datasetIdNamespace = datasetIdNamespace; + this.parameterNamespace = parameterNamespace; + this.levelNamespace = levelNamespace; + } + + private RequestConstraint buildEqualOrInRC(Set names) { + if (names.size() == 1) { + return new RequestConstraint(names.iterator().next()); + } else { + RequestConstraint rc = new RequestConstraint(null, + ConstraintType.IN); + rc.setConstraintValueList(names); + return rc; + } + } + + /** + * Get the constraints that can be used for querying whatever parameters + * were specified. + * + * @return + * @throws CommunicationException + */ + public Map getConstraintMap() + throws CommunicationException { + Map constraintMap = new HashMap(); + constraintMap.put(GridConstants.PLUGIN_NAME, new RequestConstraint( + GridConstants.GRID)); + if (datasetId != null) { + Set names = DatasetIdMapper.getInstance().lookupBaseNames( + datasetId, datasetIdNamespace); + constraintMap + .put(GridConstants.DATASET_ID, buildEqualOrInRC(names)); + } + if (secondaryId != null) { + constraintMap.put(GridConstants.SECONDARY_ID, + new RequestConstraint(secondaryId)); + } + if (ensembleId != null) { + constraintMap.put(GridConstants.ENSEMBLE_ID, new RequestConstraint( + ensembleId)); + } + if (parameterAbbreviation != null) { + Set names = ParameterMapper.getInstance().lookupBaseNames( + parameterAbbreviation, parameterNamespace); + constraintMap.put(GridConstants.PARAMETER_ABBREVIATION, + buildEqualOrInRC(names)); + } + if (masterLevelName != null) { + if (levelOneValue != null) { + Set levels = null; + if (levelTwoValue != null) { + levels = LevelMapper.getInstance().lookupLevels( + masterLevelName, levelNamespace, levelOneValue, + levelTwoValue, levelUnits); + } else { + levels = LevelMapper.getInstance().lookupLevels( + masterLevelName, levelNamespace, levelOneValue, + levelUnits); + } + Set masterLevels = new HashSet( + (int) (levels.size() / 0.75) + 1, 0.75f); + Set levelOnes = new HashSet( + (int) (levels.size() / 0.75) + 1, 0.75f); + Set levelTwos = new HashSet( + (int) (levels.size() / 0.75) + 1, 0.75f); + for (Level level : levels) { + masterLevels.add(level.getMasterLevel().getName()); + levelOnes.add(level.getLevelOneValueAsString()); + levelTwos.add(level.getLevelTwoValueAsString()); + } + constraintMap.put(GridConstants.MASTER_LEVEL_NAME, + buildEqualOrInRC(masterLevels)); + constraintMap.put(GridConstants.LEVEL_ONE, + buildEqualOrInRC(levelOnes)); + if (levelTwoValue != null) { + constraintMap.put(GridConstants.LEVEL_TWO, + buildEqualOrInRC(levelTwos)); + } + } else { + Set names = LevelMapper.getInstance().lookupBaseNames( + masterLevelName, levelNamespace); + constraintMap.put(GridConstants.MASTER_LEVEL_NAME, + buildEqualOrInRC(names)); + } + } + return new HashMap(constraintMap); + } + + /** + * Same idea as getConstraintMap but return QueryParams instead. + * + * @return + * @throws CommunicationException + */ + public List getQueryParams() throws CommunicationException { + Map map = getConstraintMap(); + List result = new ArrayList(map.size()); + for (Entry entry : getConstraintMap() + .entrySet()) { + String field = entry.getKey(); + String value = entry.getValue().getConstraintValue(); + String operand = entry.getValue().getConstraintType().getOperand(); + result.add(new QueryParam(field, value, operand)); + } + return result; + } + + /** + * Namespace to se when looking up dataset mappings, by default deprecated + * is used to replace deprecated names with new names. + * + * @param datasetIdNamespace + */ + public void setDatasetIdNamespace(String datasetIdNamespace) { + this.datasetIdNamespace = datasetIdNamespace; + } + + public void setDatasetId(String datasetId) { + this.datasetId = datasetId; + } + + public void setSecondaryId(String secondaryId) { + this.secondaryId = secondaryId; + } + + public void setEnsembleId(String ensembleId) { + this.ensembleId = ensembleId; + } + + /** + * Namespace to se when looking up parameter mappings, by default deprecated + * is used to replace deprecated names with new names. + * + * @param parameterNamespace + */ + public void setParameterNamespace(String parameterNamespace) { + this.parameterNamespace = parameterNamespace; + } + + public void setParameterAbbreviation(String parameterAbbreviation) { + this.parameterAbbreviation = parameterAbbreviation; + } + + /** + * Namespace to se when looking up level mappings, by default deprecated is + * used to replace deprecated names with new names. + * + * @param levelNamespace + */ + public void setLevelNamespace(String levelNamespace) { + this.levelNamespace = levelNamespace; + } + + public void setMasterLevelName(String masterLevelName) { + this.masterLevelName = masterLevelName; + } + + /** + * set the level one value, be sure to set level units if the units might + * differ from the db. + * + * @param levelOneValue + */ + public void setLevelOneValue(Double levelOneValue) { + this.levelOneValue = levelOneValue; + } + + /** + * set the level two value, only valid if levelonevalue is also set. + * + * @param levelOneValue + */ + public void setLevelTwoValue(Double levelTwoValue) { + this.levelTwoValue = levelTwoValue; + } + + /** + * set the unit of the numerical values passed in for the level values. The + * level units aren't used directly in the request constraints, but if the + * units are different then what is in the database then the values will + * automatically be converted to build proper constraints. + * + * @param levelUnits + */ + public void setLevelUnits(String levelUnits) { + this.levelUnits = levelUnits; + } + + /** + * Convenience method to set all three namespaces to the same thing. + * + * @param namespace + */ + public void setNamespace(String namespace) { + setParameterNamespace(namespace); + setDatasetIdNamespace(namespace); + setLevelNamespace(namespace); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfo.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfo.java new file mode 100644 index 0000000000..669c916f84 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfo.java @@ -0,0 +1,95 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.dataset; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +/** + * + * Contains static information about a grid dataset. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Feb 27, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.NONE) +public class DatasetInfo { + + /** The title of the model */ + @XmlElement + private String title; + + /** The model name */ + @XmlElement + private String datasetId; + + @XmlElement + private String alias; + + /** + * The intrinsic temporal resolution of the data. + */ + @XmlElement + private Integer dt; + + public String getTitle() { + return title; + } + + public void setTitle(String title) { + this.title = title; + } + + public String getDatasetId() { + return datasetId; + } + + public void setDatasetId(String datasetId) { + this.datasetId = datasetId; + } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + + public Integer getDt() { + return dt; + } + + public void setDt(Integer dt) { + this.dt = dt; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfoLookup.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfoLookup.java new file mode 100644 index 0000000000..cb7721df58 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfoLookup.java @@ -0,0 +1,117 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.dataset; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.JAXBException; + +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.serialization.JAXBManager; +import com.raytheon.uf.common.serialization.SerializationException; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; + +/** + * + * Provides logic to read datasetInfo files from localization and provide lookup + * by datasetId. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Feb 27, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class DatasetInfoLookup { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(DatasetInfoLookup.class); + + private static DatasetInfoLookup instance; + + public static DatasetInfoLookup getInstance() { + if (instance == null) { + instance = new DatasetInfoLookup(); + } + return instance; + } + + private Map infoMap = new HashMap(); + + private DatasetInfoLookup() { + init(); + } + + private void init() { + JAXBManager manager = null; + try { + manager = new JAXBManager(DatasetInfoSet.class); + } catch (JAXBException e) { + statusHandler + .error("Error loading context for DatasetInfo, no datasetInfo will be loaded.", + e); + } + IPathManager pathMgr = PathManagerFactory.getPathManager(); + LocalizationContext commonStaticBase = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.BASE); + + LocalizationContext commonStaticSite = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + LocalizationFile[] files = pathMgr.listFiles(new LocalizationContext[] { + commonStaticSite, commonStaticBase }, "grid" + + IPathManager.SEPARATOR + "datasetInfo", + new String[] { ".xml" }, true, true); + for (LocalizationFile file : files) { + if (file == null || !file.exists()) { + return; + } + try { + Object obj = manager.jaxbUnmarshalFromXmlFile(file.getFile()); + DatasetInfoSet set = (DatasetInfoSet) obj; + for (DatasetInfo info : set.getInfos()) { + infoMap.put(info.getDatasetId(), info); + } + } catch (SerializationException e) { + statusHandler.error( + "Error reading dataset info: " + file.getName() + + " has been ignored.", e); + } + } + + } + + public DatasetInfo getInfo(String datasetId) { + return infoMap.get(datasetId); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelAlias.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfoSet.java similarity index 63% rename from edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelAlias.java rename to edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfoSet.java index eb332791bc..f7559b7bb3 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelAlias.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/dataset/DatasetInfoSet.java @@ -17,52 +17,46 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.level.xml; +package com.raytheon.uf.common.dataplugin.grid.dataset; + +import java.util.ArrayList; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; -import com.raytheon.uf.common.serialization.ISerializableObject; - /** - * Level + * + * JAXB compatible root element for a list of datasetInfo objects * *
+ * 
  * SOFTWARE HISTORY
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Sep 03, 2009            rjpeter     Initial creation.
+ * Feb 27, 2012            bsteffen     Initial creation
+ * 
  * 
* - * @author rjpeter + * @author bsteffen * @version 1.0 */ @XmlRootElement @XmlAccessorType(XmlAccessType.NONE) -public class LevelAlias implements ISerializableObject { - @XmlAttribute(required = true) - private String name; +public class DatasetInfoSet { - @XmlElement(name = "alias") - private String[] aliases; + @XmlElements({ @XmlElement(name = "info", type = DatasetInfo.class) }) + private ArrayList infos; - public String getName() { - return name; + public ArrayList getInfos() { + return infos; } - public void setName(String name) { - this.name = name; + public void setInfos(ArrayList infos) { + this.infos = infos; } - public String[] getAliases() { - return aliases; - } - - public void setAliases(String[] aliases) { - this.aliases = aliases; - } } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/datastorage/GridDataRetriever.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/datastorage/GridDataRetriever.java new file mode 100644 index 0000000000..cd99edc7ef --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/datastorage/GridDataRetriever.java @@ -0,0 +1,358 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.datastorage; + +import java.io.File; +import java.io.FileNotFoundException; + +import javax.measure.converter.ConversionException; +import javax.measure.converter.UnitConverter; +import javax.measure.unit.Unit; + +import org.geotools.coverage.grid.GridGeometry2D; +import org.opengis.metadata.spatial.PixelOrientation; + +import com.raytheon.uf.common.dataplugin.annotations.DataURI; +import com.raytheon.uf.common.dataplugin.grid.GridPathProvider; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataplugin.persist.IHDFFilePathProvider; +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.MapUtil; +import com.raytheon.uf.common.geospatial.util.GridGeometryWrapChecker; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.LambertConformalGridCoverage; +import com.raytheon.uf.common.gridcoverage.LatLonGridCoverage; +import com.raytheon.uf.common.gridcoverage.MercatorGridCoverage; +import com.raytheon.uf.common.gridcoverage.PolarStereoGridCoverage; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.msgs.GetServersRequest; +import com.raytheon.uf.common.localization.msgs.GetServersResponse; +import com.raytheon.uf.common.parameter.lookup.ParameterLookup; +import com.raytheon.uf.common.serialization.comm.RequestRouter; +import com.vividsolutions.jts.geom.Coordinate; + +/** + * Convenience class for requesting grid data. This class provides automatic + * unit conversion and also the ability to allow worldwide data to overlap. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 14, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridDataRetriever { + + protected static String serverDataDir; + + protected GridRecord record; + + protected GridCoverage requestCoverage; + + protected Request request = Request.ALL; + + protected int worldWrapColumns = -1; + + protected Unit unit; + + protected UnitConverter converter; + + /** + * Construct a GridDataRetriever that will retrieve data for the provided + * GridRecord. + * + * @param record + * GridRecord for which data is retrieved. + */ + public GridDataRetriever(GridRecord record) { + this.record = record; + } + + /** + * Construct a GridDataRetriever that will retrieve data for the provided + * dataURI. The dataURI must be a valid dataURI for a grid record. + * + * @param dataUri + * dataURI for grid data to retrieve. + */ + public GridDataRetriever(String dataUri) { + this.record = new GridRecord(dataUri); + this.record.setParameter(ParameterLookup.getInstance().getParameter( + record.getParameter().getAbbreviation())); + } + + /** + * For data that wraps around the world, specify the number of redundant + * columns to add. For data that does not wrap around the world this method + * call has no affect and the full data set will be retrieved. + * + * @param worldWrapColumns + * The number of redundant columns to include in the x direction + * for wrapping grids. + * @return a boolean true if the data is world wrapping, false if not(in + * which case this method call has no affect). + * @throws GridCoverageException + * thrown when there are errors constructing a wrapping + * GridCoverage + */ + public boolean setWorldWrapColumns(int worldWrapColumns) + throws GridCoverageException { + GridCoverage dataLoc = record.getLocation(); + GridGeometry2D dataGeom = dataLoc.getGridGeometry(); + int wrapX = GridGeometryWrapChecker.checkForWrapping(dataGeom); + if (wrapX != -1) { + int newX = wrapX + worldWrapColumns; + if (newX == dataLoc.getNx()) { + this.request = Request.ALL; + } else if (newX < dataLoc.getNx()) { + Coordinate upperRight = new Coordinate(newX - 1, 0); + upperRight = MapUtil.gridCoordinateToLatLon(upperRight, + PixelOrientation.CENTER, dataLoc); + setRequestArea(dataLoc.getLowerLeftLon(), + dataLoc.getLowerLeftLat(), upperRight.x, upperRight.y); + } else { + this.request = Request.ALL; + if (dataLoc instanceof LatLonGridCoverage) { + LatLonGridCoverage newLoc = new LatLonGridCoverage( + (LatLonGridCoverage) dataLoc); + newLoc.setLa2(0); + newLoc.setLo2(0); + requestCoverage = newLoc; + } else if (dataLoc instanceof MercatorGridCoverage) { + MercatorGridCoverage newLoc = new MercatorGridCoverage( + (MercatorGridCoverage) dataLoc); + newLoc.setLa2(null); + newLoc.setLo2(null); + requestCoverage = newLoc; + } else if (dataLoc instanceof LambertConformalGridCoverage) { + requestCoverage = new LambertConformalGridCoverage( + (LambertConformalGridCoverage) dataLoc); + } else if (dataLoc instanceof PolarStereoGridCoverage) { + // I really doubt it is possible to world wrap a + // PolarStereoCoverage, but just in case... + requestCoverage = new PolarStereoGridCoverage( + (PolarStereoGridCoverage) dataLoc); + } else { + throw new GridCoverageException( + "Cannot wrap data for projection of type " + + dataLoc.getClass().getName()); + } + requestCoverage.setNx(newX); + requestCoverage.setGridGeometry(null); + requestCoverage.initialize(); + this.worldWrapColumns = newX - dataLoc.getNx(); + } + return true; + } else { + return false; + } + } + + /** + * Set the requested area to be a subgrid of the total area. This uses the + * trim functionality of GridCoverage to generate an area which has corners + * at the provided latitude and longitude. + * + * @param lon1 + * @param lat1 + * @param lon2 + * @param lat2 + * @throws GridDataRetrievalException + * @throws GridCoverageException + */ + protected void setRequestArea(double lon1, double lat1, double lon2, + double lat2) throws GridCoverageException { + SubGrid subGrid = new SubGrid(); + subGrid.setLowerLeftLat(Math.min(lat1, lat2)); + subGrid.setLowerLeftLon(Math.min(lat1, lat2)); + subGrid.setUpperRightLat(Math.min(lat1, lat2)); + subGrid.setUpperRightLon(Math.min(lat1, lat2)); + requestCoverage = record.getLocation().trim(subGrid); + int[] minIndex = { subGrid.getUpperLeftX(), subGrid.getUpperLeftY() }; + int[] maxIndex = { subGrid.getUpperLeftX() + subGrid.getNX(), + subGrid.getUpperLeftY() + subGrid.getNY() }; + request = Request.buildSlab(minIndex, maxIndex); + requestCoverage.initialize(); + } + + /** + * Set the desired unit for the data being retrieved. If this method is + * successful the data will automatically be converted when it is retrieved. + * + * @param unit + * the desired unit for the data. + * @throws ConversionException + * occurs when the provided unit is incompatible with the + * storage unit of the data. + */ + public void setUnit(Unit unit) throws ConversionException { + this.converter = record.getParameter().getUnit().getConverterTo(unit); + this.unit = unit; + } + + /** + * retrieve the grid data. This method will automatically perform any + * requested unit conversion or world wrap adjustments. + * + * @return FloatDataRecord containing the raw values for this grid. + * @throws StorageException + * if anything goes wrong while retrieving the data, for example + * if the data cannot be found in the datastore or if there are + * problems communicating with the servers. + */ + public FloatDataRecord getDataRecord() throws StorageException { + IDataStore ds = DataStoreFactory.getDataStore(findStorageLocation()); + IDataRecord dataRecord; + try { + dataRecord = ds.retrieve(getGroup(), "Data", request); + } catch (FileNotFoundException e) { + throw new StorageException(e.getLocalizedMessage(), null, e); + } + FloatDataRecord floatRecord = (FloatDataRecord) dataRecord; + boolean cloned = false; + if (converter != null) { + if (!cloned) { + floatRecord = (FloatDataRecord) floatRecord.clone(); + cloned = true; + } + float[] data = floatRecord.getFloatData(); + for (int i = 0; i < data.length; i += 1) { + if (data[i] <= -9999) { + // -9999 and -999999 are both commonly used no data values, + // and rarely are such extremes valid. No Data Value. + data[i] = data[i]; + } else { + data[i] = (float) converter.convert(data[i]); + } + } + } + if (worldWrapColumns > 0) { + if (!cloned) { + floatRecord = (FloatDataRecord) floatRecord.clone(); + cloned = true; + } + int nx = (int) floatRecord.getSizes()[0]; + int newNx = nx + worldWrapColumns; + int ny = (int) floatRecord.getSizes()[1]; + float[] oldData = floatRecord.getFloatData(); + float[] newData = new float[newNx * ny]; + for (int y = 0; y < ny; y += 1) { + // this is in a loop so it works correctly when extraColumns > + // nx + for (int numCopied = 0; numCopied < newNx; numCopied += nx) { + System.arraycopy(oldData, y * nx, newData, y * newNx + + numCopied, Math.min(nx, newNx - numCopied)); + } + } + floatRecord.setSizes(new long[] { newNx, ny }); + floatRecord.setFloatData(newData); + + } + return floatRecord; + } + + /** + * Get a GridCoverage describing the spatial area covered by the retrieved + * data. If setWorldWrapColumns or setRequestArea was used then this will + * return a coverage describing the modified area, otherwise this is the + * same as the coverage in the GridRecord. + * + * @return grid coverage of the data record. + */ + public GridCoverage getCoverage() { + if (requestCoverage == null) { + return record.getLocation(); + } else { + return requestCoverage; + } + } + + /** + * Get a unit object describing the retrieved data. If setUnit was + * successfully used then this will return the same unit, otherwise it + * returns the storage unit of the data. + * + * @return unit of the data record + */ + public Unit getUnit() { + if (unit == null) { + return record.getParameter().getUnit(); + } + return unit; + } + + private String getGroup() { + if (GridPathProvider.STATIC_PARAMETERS.contains(record.getParameter() + .getAbbreviation())) { + return DataURI.SEPARATOR + record.getLocation().getId() + + DataURI.SEPARATOR + + record.getParameter().getAbbreviation(); + } else { + return record.getDataURI(); + } + } + + private File findStorageLocation() throws StorageException { + IHDFFilePathProvider pathProvider = record.getHDFPathProvider(); + + String path = pathProvider.getHDFPath(record.getPluginName(), record); + String fileName = pathProvider.getHDFFileName(record.getPluginName(), + record); + + return new File(getServerDataDir() + IPathManager.SEPARATOR + + record.getPluginName() + IPathManager.SEPARATOR + path + + IPathManager.SEPARATOR + fileName); + } + + private static synchronized String getServerDataDir() + throws StorageException { + if (serverDataDir == null) { + // TODO cave already knows the server data dir in VizApp, and edex + // has it in system properties but we can't access either because + // this is common code, architecturally we need some way around + // this. For now this will send it's own request which is slightly + // wasteful but not terribly harmful. + try { + GetServersResponse response = (GetServersResponse) RequestRouter + .route(new GetServersRequest()); + serverDataDir = response.getServerDataDir(); + } catch (Exception e) { + throw new StorageException("Error communicating with server.", + null, e); + } + } + return serverDataDir; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/mapping/DatasetIdMapper.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/mapping/DatasetIdMapper.java new file mode 100644 index 0000000000..9249757d46 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/mapping/DatasetIdMapper.java @@ -0,0 +1,90 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.mapping; + +import javax.xml.bind.JAXBException; + +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManager; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.util.mapping.Mapper; + +/** + * Provide mappings of grid datasetId. The "base" namespace is not formally + * defined and can be considered as whatever the decoders are storing in the + * database. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 30, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class DatasetIdMapper extends Mapper { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(DatasetIdMapper.class); + + private DatasetIdMapper() { + IPathManager pathMgr = PathManagerFactory.getPathManager(); + LocalizationContext commonStaticBase = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.BASE); + + LocalizationContext commonStaticSite = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + // read in the namespace map + LocalizationFile[] files = pathMgr.listFiles(new LocalizationContext[] { + commonStaticSite, commonStaticBase }, "grid" + + PathManager.SEPARATOR + "dataset" + IPathManager.SEPARATOR + + "alias", new String[] { ".xml" }, true, true); + for (LocalizationFile file : files) { + try { + addAliasList(file.getFile()); + } catch (JAXBException e) { + statusHandler.error( + "Error reading datasetid aliases: " + file.getName() + + " has been ignored.", e); + } + } + } + + private static DatasetIdMapper instance; + + public static synchronized DatasetIdMapper getInstance() { + if (instance == null) { + instance = new DatasetIdMapper(); + } + return instance; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/request/DeleteAllGridDataRequest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/request/DeleteAllGridDataRequest.java new file mode 100644 index 0000000000..24c3d67d12 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/request/DeleteAllGridDataRequest.java @@ -0,0 +1,78 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.request; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.serialization.comm.IServerRequest; + +/** + * Request object used to delete all stored data for the specified model name. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 2, 2012            dgilling     Initial creation
+ * 
+ * 
+ * + * @author dgilling + * @version 1.0 + */ + +@DynamicSerialize +public class DeleteAllGridDataRequest implements IServerRequest { + + @DynamicSerializeElement + private String modelName; + + public DeleteAllGridDataRequest() { + this(null); + } + + public DeleteAllGridDataRequest(String modelName) { + this.modelName = modelName; + } + + public String getModelName() { + return modelName; + } + + public void setModelName(String modelName) { + this.modelName = modelName; + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder builder = new StringBuilder(); + builder.append("DeleteAllGridDataRequest [modelName="); + builder.append(modelName); + builder.append("]"); + return builder.toString(); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/NcCheckRequest.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/request/GetGridTreeRequest.java similarity index 78% rename from edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/NcCheckRequest.java rename to edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/request/GetGridTreeRequest.java index d3a6bf38af..235fb8504b 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.gfe/src/com/raytheon/uf/common/dataplugin/gfe/request/NcCheckRequest.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/request/GetGridTreeRequest.java @@ -17,12 +17,14 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.gfe.request; +package com.raytheon.uf.common.dataplugin.grid.request; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.comm.IServerRequest; /** - * TODO Add Description + * + * Request for the Grid DataTree. * *
  * 
@@ -30,18 +32,14 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Nov 14, 2012            jdynina     Initial creation
+ * Mar 5, 2012            bsteffen     Initial creation
  * 
  * 
* - * @author jdynina + * @author bsteffen * @version 1.0 */ - @DynamicSerialize -public class NcCheckRequest extends AbstractGfeRequest { - - public NcCheckRequest() { - } +public class GetGridTreeRequest implements IServerRequest { } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/units/GridUnits.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/units/GridUnits.java new file mode 100644 index 0000000000..6b2e05e6fd --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/units/GridUnits.java @@ -0,0 +1,66 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.grid.units; + +import javax.measure.unit.NonSI; +import javax.measure.unit.SI; +import javax.measure.unit.UnitFormat; + +/** + * Provide alias for common units used in grid. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 20, 2009            mschenke     Initial creation
+ * 
+ * 
+ * + * @author mschenke + * @version 1.0 + */ + +public class GridUnits { + + public static boolean register() { + UnitFormat.getInstance().alias(SI.METER, "gpm"); + UnitFormat.getUCUMInstance().alias(SI.METER, "gpm"); + UnitFormat.getInstance().alias(SI.MILLI(NonSI.BAR), "mb"); + UnitFormat.getUCUMInstance().alias(SI.MILLI(NonSI.BAR), "mb"); + UnitFormat.getInstance().alias(SI.CELSIUS, "C"); + UnitFormat.getUCUMInstance().alias(SI.CELSIUS, "C"); + UnitFormat.getInstance().alias(NonSI.FAHRENHEIT, "F"); + UnitFormat.getUCUMInstance().alias(NonSI.FAHRENHEIT, "F"); + UnitFormat.getInstance().alias(NonSI.DEGREE_ANGLE, "deg"); + UnitFormat.getUCUMInstance().alias(NonSI.DEGREE_ANGLE, "deg"); + UnitFormat.getInstance().alias(NonSI.DEGREE_ANGLE, "Degree"); + UnitFormat.getUCUMInstance().alias(NonSI.DEGREE_ANGLE, "Degree"); + UnitFormat.getInstance().alias(NonSI.KNOT, "kt"); + UnitFormat.getUCUMInstance().alias(NonSI.KNOT, "kt"); + UnitFormat.getInstance().alias(SI.SECOND, "sec"); + UnitFormat.getUCUMInstance().alias(SI.SECOND, "sec"); + UnitFormat.getInstance().alias(SI.METER, "meters"); + UnitFormat.getUCUMInstance().alias(SI.METER, "meters"); + return true; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/StaticGridData.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/util/StaticGridData.java similarity index 96% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/StaticGridData.java rename to edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/util/StaticGridData.java index cd90812820..fb4d813f72 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/StaticGridData.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/util/StaticGridData.java @@ -17,20 +17,20 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.util; +package com.raytheon.uf.common.dataplugin.grid.util; import java.util.HashMap; import java.util.Map; import org.opengis.metadata.spatial.PixelOrientation; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.vividsolutions.jts.geom.Coordinate; /** - * TODO Add Description + * A class for calculating and caching static data for grids. * *
  * SOFTWARE HISTORY
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/StaticGridDataType.java b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/util/StaticGridDataType.java
similarity index 89%
rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/StaticGridDataType.java
rename to edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/util/StaticGridDataType.java
index 41573e9387..9259e3e57c 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/util/StaticGridDataType.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/src/com/raytheon/uf/common/dataplugin/grid/util/StaticGridDataType.java
@@ -17,13 +17,14 @@
  * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
  * further licensing information.
  **/
-package com.raytheon.uf.common.dataplugin.grib.util;
+package com.raytheon.uf.common.dataplugin.grid.util;
 
 import java.util.ArrayList;
 import java.util.List;
 
 /**
- * TODO Add Description
+ * The static grid data types are the same values for a coverage and can be
+ * calculated based off the coverage/model.
  * 
  * 
  * 
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grid/utility/common_static/base/grid/dataset/alias/d2d-title.xml b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/utility/common_static/base/grid/dataset/alias/d2d-title.xml
new file mode 100644
index 0000000000..4affe5f5fe
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.grid/utility/common_static/base/grid/dataset/alias/d2d-title.xml
@@ -0,0 +1,131 @@
+
+    
+
+	AKWAVE
+	SPE
+	GFS190
+	GFS80
+	GFS75
+	GFSGbl
+	GFSGbl
+	GFSGbl
+	GFSGbl
+	GFSGbl
+	GFSGbl
+	GFSGbl
+	GFSGbl
+	GFS180
+	GFSGbl
+	BiasHPE
+	CPCoutlook-Long
+	DGEX
+	DGEX
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-LowRes
+	ECMWF-MODEL0
+	ECMWF-LowRes
+	ENPwave
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	GFSensemble
+	NAM95
+	NAMWX
+	NAM12
+	AK-NAM12
+	NAM Bufr
+	NAM80
+	AK-GFS
+	SJU-GFS
+	Guam-GFS
+	GFS360
+	GFS40
+	GFS90
+	PR-GFS
+	GFSBufr
+	GFSLAMP-Stn
+	GFSLAMP-Grid
+	GWW
+	HPC
+	GuamHurWind
+	TPC-HurWind
+	HawHurWind
+	SPE
+	NAM40
+	NAM20
+	AK-NAM40
+	AK-NAM20
+	PR-NAM12
+	AK-GriddedMOS
+	GriddedMOS
+	MPE
+	MPE
+	gfs190
+	GFS150
+	GFS150
+	gfsLR21
+	gfsLR22
+	gfsLR23
+	gfsLR24
+	gfsLR25
+	gfsLR26
+	gfsLR
+	gfsLR
+	NGM180
+	NGM95
+	NGM90
+	NGM80
+	OPCWave-W-ATL
+	OPCWave-NE-PAC
+	OPCWave-TE-PAC
+	RTG-SST-HR-Analysis
+	RTG-SST-Analysis
+	RAP13
+	RAP40
+	SREF
+	AK-SREF
+	PR-SREF
+	UKMET
+	UKMET
+	UKMET
+	UKMET
+	UKMET
+	UKMET
+	UKMET
+	UKMET
+	UKMET
+	WNAwave
+
\ No newline at end of file
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/MANIFEST.MF
index 062600939d..d367f82e13 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/MANIFEST.MF
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/MANIFEST.MF
@@ -6,7 +6,7 @@ Bundle-Version: 1.12.1174.qualifier
 Eclipse-BuddyPolicy: registered, ext, global
 Eclipse-RegisterBuddy:  com.raytheon.uf.common.serialization
 Bundle-Vendor: Raytheon
-Require-Bundle: javax.measure, 
+Require-Bundle: javax.measure,
  javax.persistence,
  org.apache.commons.lang,
  org.apache.commons.logging,
@@ -14,10 +14,11 @@ Require-Bundle: javax.measure,
  com.raytheon.uf.common.localization,
  com.raytheon.uf.common.serialization,
  com.raytheon.uf.common.serialization.comm,
- com.raytheon.uf.common.status
+ com.raytheon.uf.common.status,
+ com.raytheon.uf.common.util;bundle-version="1.12.1174"
 Export-Package: com.raytheon.uf.common.dataplugin.level,
- com.raytheon.uf.common.dataplugin.level.request,
- com.raytheon.uf.common.dataplugin.level.xml
+ com.raytheon.uf.common.dataplugin.level.mapping,
+ com.raytheon.uf.common.dataplugin.level.request
 Bundle-RequiredExecutionEnvironment: JavaSE-1.6
 Import-Package: com.raytheon.uf.common.comm,
  org.hibernate.annotations
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject
index 7331203598..29c6f3acce 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.level/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject
@@ -1,8 +1,2 @@
 com.raytheon.uf.common.dataplugin.level.Level
-com.raytheon.uf.common.dataplugin.level.MasterLevel
-com.raytheon.uf.common.dataplugin.level.xml.Group
-com.raytheon.uf.common.dataplugin.level.xml.GroupList
-com.raytheon.uf.common.dataplugin.level.xml.Level
-com.raytheon.uf.common.dataplugin.level.xml.LevelAlias
-com.raytheon.uf.common.dataplugin.level.xml.LevelAliasList
-com.raytheon.uf.common.dataplugin.level.xml.LevelValue
\ No newline at end of file
+com.raytheon.uf.common.dataplugin.level.MasterLevel
\ No newline at end of file
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/LevelFactory.java b/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/LevelFactory.java
index 0ccc5759c5..3749289c0e 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/LevelFactory.java
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/LevelFactory.java
@@ -42,14 +42,11 @@ import com.raytheon.uf.common.dataplugin.level.request.GetLevelByIdRequest;
 import com.raytheon.uf.common.dataplugin.level.request.GetLevelRequest;
 import com.raytheon.uf.common.dataplugin.level.request.GetMasterLevelRequest;
 import com.raytheon.uf.common.dataplugin.level.request.ILevelRetrievalAdapter;
-import com.raytheon.uf.common.dataplugin.level.xml.LevelAlias;
-import com.raytheon.uf.common.dataplugin.level.xml.LevelAliasList;
 import com.raytheon.uf.common.localization.IPathManager;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
 import com.raytheon.uf.common.localization.LocalizationFile;
 import com.raytheon.uf.common.localization.PathManagerFactory;
-import com.raytheon.uf.common.serialization.SerializationUtil;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
@@ -94,9 +91,6 @@ public class LevelFactory {
     // level id String to its full level
     private Map levelCacheByIdAsString = new HashMap();
 
-    // lists all aliases and their associated master level name
-    private Map levelAliasMap = new HashMap();
-
     private ILevelRetrievalAdapter retrievalAdapter = null;
 
     private boolean hasRequestedAllLevels = false;
@@ -123,7 +117,6 @@ public class LevelFactory {
             e.printStackTrace();
         }
 
-        loadLevelAliases();
         try {
             loadAllMasterLevels();
         } catch (CommunicationException e) {
@@ -229,11 +222,6 @@ public class LevelFactory {
         MasterLevel rval = null;
         String levelName = level.getName();
 
-        // check aliasing
-        if (levelAliasMap.containsKey(levelName)) {
-            levelName = levelAliasMap.get(levelName);
-        }
-
         if (!hasRequestedAllMasterLevels) {
             loadAllMasterLevels();
         }
@@ -366,59 +354,6 @@ public class LevelFactory {
         levelCacheByIdAsString.put("" + levelToCache.getId(), levelToCache);
     }
 
-    private void loadLevelAliases() {
-        Map aliasMap = new HashMap();
-
-        IPathManager pathMgr = PathManagerFactory.getPathManager();
-        Map tieredMap = pathMgr
-                .getTieredLocalizationFile(LocalizationType.COMMON_STATIC,
-                        LEVEL_FILENAME);
-
-        LocalizationLevel[] levels = pathMgr.getAvailableLevels();
-        for (LocalizationLevel level : levels) {
-            LocalizationFile file = tieredMap.get(level);
-            if (file != null) {
-                loadLevelAliasFile(file.getFile(), aliasMap);
-            }
-        }
-
-        // set to master file
-        levelAliasMap = aliasMap;
-    }
-
-    private void loadLevelAliasFile(File file, Map aliasMap) {
-        if ((file != null) && file.exists()) {
-            LevelAliasList defList = null;
-
-            // use jaxb to deserialize file
-            try {
-                Object xmlObj = SerializationUtil.jaxbUnmarshalFromXmlFile(file
-                        .getAbsolutePath());
-
-                if (xmlObj instanceof LevelAliasList) {
-                    defList = (LevelAliasList) xmlObj;
-                } else {
-                    logger.error("Malformed alias file, expected ["
-                            + LevelAliasList.class.getName() + "], received ["
-                            + xmlObj.getClass().getName() + "]");
-                }
-            } catch (Exception e) {
-                logger.error("Caught exception parsing level alias file", e);
-            }
-
-            if ((defList != null) && (defList.getLevels() != null)) {
-                for (LevelAlias level : defList.getLevels()) {
-                    String[] aliases = level.getAliases();
-                    if (aliases != null) {
-                        for (String alias : aliases) {
-                            aliasMap.put(alias, level.getName());
-                        }
-                    }
-                }
-            }
-        }
-    }
-
     private void loadAllLevels() throws CommunicationException {
         if (retrievalAdapter != null) {
             LevelContainer container = retrievalAdapter.getAllLevels();
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/mapping/LevelMapper.java b/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/mapping/LevelMapper.java
new file mode 100644
index 0000000000..cabd2a6ac6
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/mapping/LevelMapper.java
@@ -0,0 +1,205 @@
+/**
+ * This software was developed and / or modified by Raytheon Company,
+ * pursuant to Contract DG133W-05-CQ-1067 with the US Government.
+ * 
+ * U.S. EXPORT CONTROLLED TECHNICAL DATA
+ * This software product contains export-restricted data whose
+ * export/transfer/disclosure is restricted by U.S. law. Dissemination
+ * to non-U.S. persons whether in the United States or abroad requires
+ * an export license or other authorization.
+ * 
+ * Contractor Name:        Raytheon Company
+ * Contractor Address:     6825 Pine Street, Suite 340
+ *                         Mail Stop B8
+ *                         Omaha, NE 68106
+ *                         402.291.0100
+ * 
+ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
+ * further licensing information.
+ **/
+package com.raytheon.uf.common.dataplugin.level.mapping;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.measure.unit.Unit;
+import javax.measure.unit.UnitFormat;
+import javax.xml.bind.JAXBException;
+
+import com.raytheon.uf.common.comm.CommunicationException;
+import com.raytheon.uf.common.dataplugin.level.Level;
+import com.raytheon.uf.common.dataplugin.level.LevelFactory;
+import com.raytheon.uf.common.dataplugin.level.MasterLevel;
+import com.raytheon.uf.common.localization.IPathManager;
+import com.raytheon.uf.common.localization.LocalizationContext;
+import com.raytheon.uf.common.localization.LocalizationFile;
+import com.raytheon.uf.common.localization.PathManagerFactory;
+import com.raytheon.uf.common.status.IUFStatusHandler;
+import com.raytheon.uf.common.status.UFStatus;
+import com.raytheon.uf.common.util.mapping.Mapper;
+import com.raytheon.uf.common.util.mapping.MultipleMappingException;
+
+/**
+ * Provide mapping of master level names. The base set is defined by what is in
+ * the masterlevel database, which is initially populated from masterLevels. As
+ * well as providing name mapping it is also possible to map level objects with
+ * unit conversion.
+ * 
+ * 
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 29, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class LevelMapper extends Mapper { + + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(LevelMapper.class); + + private transient LevelFactory factory = LevelFactory.getInstance(); + + private LevelMapper() { + IPathManager pathMgr = PathManagerFactory.getPathManager(); + LocalizationContext commonStaticBase = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.BASE); + + LocalizationContext commonStaticSite = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + // read in the namespace map + LocalizationFile[] files = pathMgr.listFiles(new LocalizationContext[] { + commonStaticSite, commonStaticBase }, "level" + + IPathManager.SEPARATOR + "alias", new String[] { ".xml" }, + true, true); + for (LocalizationFile file : files) { + try { + addAliasList(file.getFile()); + } catch (JAXBException e) { + statusHandler.error( + "Error reading level aliases: " + file.getName() + + " has been ignored.", e); + } + } + } + + /** + * same functionality as lookupBaseNames but also maps those baseNames to + * MasterLevel objects. + * + * @param alias + * @param namespace + * @return + * @throws CommunicationException + */ + public Set lookupMasterLevels(String alias, String namespace) + throws CommunicationException { + Set baseNames = super.lookupBaseNames(alias, namespace); + Set result = new HashSet( + (int) (baseNames.size() / 0.75) + 1, 0.75f); + for (String baseName : baseNames) { + result.add(factory.getMasterLevel(baseName)); + } + return result; + } + + /** + * same functionality as lookupBaseName but also maps the baseName to a + * MasterLevel object. + * + * @param alias + * @param namespace + * @return + */ + public MasterLevel lookupMasterLevel(String alias, String namespace) + throws MultipleMappingException, CommunicationException { + String baseName = super.lookupBaseName(alias, namespace); + return factory.getMasterLevel(baseName); + } + + public Level lookupLevel(String masterLevelAlias, String namespace, + double levelone, double leveltwo, Unit unit) + throws MultipleLevelMappingException, CommunicationException { + return lookupLevel(masterLevelAlias, namespace, levelone, leveltwo, + UnitFormat.getUCUMInstance().format(unit)); + } + + public Level lookupLevel(String masterLevelAlias, String namespace, + double levelone, Unit unit) + throws MultipleLevelMappingException, CommunicationException { + return lookupLevel(masterLevelAlias, namespace, levelone, UnitFormat + .getUCUMInstance().format(unit)); + } + + public Level lookupLevel(String masterLevelAlias, String namespace, + double levelone, String unit) throws MultipleLevelMappingException, + CommunicationException { + return lookupLevel(masterLevelAlias, namespace, levelone, + Level.INVALID_VALUE, unit); + } + + public Level lookupLevel(String masterLevelAlias, String namespace, + double levelone, double leveltwo, String unit) + throws MultipleLevelMappingException, CommunicationException { + Set levels = lookupLevels(masterLevelAlias, namespace, levelone, + leveltwo, unit); + if (levels.size() == 1) { + return levels.iterator().next(); + } else { + throw new MultipleLevelMappingException(masterLevelAlias, + namespace, lookupBaseNames(masterLevelAlias, namespace), + levels); + } + } + + public Set lookupLevels(String masterLevelAlias, String namespace, + double levelone, double leveltwo, Unit unit) + throws CommunicationException { + return lookupLevels(masterLevelAlias, namespace, levelone, leveltwo, + UnitFormat.getUCUMInstance().format(unit)); + } + + public Set lookupLevels(String masterLevelAlias, String namespace, + double levelone, Unit unit) throws CommunicationException { + return lookupLevels(masterLevelAlias, namespace, levelone, UnitFormat + .getUCUMInstance().format(unit)); + } + + public Set lookupLevels(String masterLevelAlias, String namespace, + double levelone, String unit) throws CommunicationException { + return lookupLevels(masterLevelAlias, namespace, levelone, + Level.INVALID_VALUE, unit); + } + + public Set lookupLevels(String masterLevelAlias, String namespace, + double levelone, double leveltwo, String unit) + throws CommunicationException { + Set baseNames = super.lookupBaseNames(masterLevelAlias, + namespace); + Set result = new HashSet( + (int) (baseNames.size() / 0.75) + 1, 0.75f); + for (String baseName : baseNames) { + result.add(factory.getLevel(baseName, levelone, leveltwo, unit)); + } + return result; + } + + private static LevelMapper instance; + + public static synchronized LevelMapper getInstance() { + if (instance == null) { + instance = new LevelMapper(); + } + return instance; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/mapping/MultipleLevelMappingException.java b/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/mapping/MultipleLevelMappingException.java new file mode 100644 index 0000000000..16749c3e87 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/mapping/MultipleLevelMappingException.java @@ -0,0 +1,78 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.dataplugin.level.mapping; + +import java.util.Set; + +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.util.mapping.MultipleMappingException; + +/** + * Exception indicating that multiple mappings are defined when the LevelMapper + * is used to alias to a single level. Catching this exception gives a decoder + * the ability to easily grab all the levels or an arbitrary level so it can + * store the data while logging an exception. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 30, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class MultipleLevelMappingException extends MultipleMappingException { + + private static final long serialVersionUID = -2542711470181578302L; + + private final Set levelMappings; + + public MultipleLevelMappingException(String name, String namespace, + Set mappings, Set levelMappings) { + super(true, name, namespace, mappings); + this.levelMappings = levelMappings; + } + + /** + * Get all the matching levels, same as if LevelMapper.lookupLevels was + * called to begin with. + * + * @return + */ + public Set getLevelMappings() { + return levelMappings; + } + + /** + * Get one level that was mapped by the alias, which level specifically is + * not well defined. + * + * @return + */ + public Level getArbitraryLevelMapping() { + return levelMappings.iterator().next(); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/utility/common_static/base/level/alias/deprecated.xml b/edexOsgi/com.raytheon.uf.common.dataplugin.level/utility/common_static/base/level/alias/deprecated.xml new file mode 100644 index 0000000000..0e1b02deff --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.level/utility/common_static/base/level/alias/deprecated.xml @@ -0,0 +1,23 @@ + + + + ZAGL + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.qpf/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.qpf/META-INF/MANIFEST.MF index e64f3b6ac1..9a43df454f 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.qpf/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.qpf/META-INF/MANIFEST.MF @@ -14,4 +14,3 @@ Require-Bundle: javax.persistence;bundle-version="1.0.0", org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.monitor;bundle-version="1.11.5", com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0" -Import-Package: com.raytheon.uf.common.dataplugin.grib diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.radar/.classpath b/edexOsgi/com.raytheon.uf.common.dataplugin.radar/.classpath index ad32c83a78..1fa3e6803d 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.radar/.classpath +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.radar/.classpath @@ -1,6 +1,6 @@ - + diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.scan/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.scan/META-INF/MANIFEST.MF index fbed137140..38f08d641e 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.scan/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.scan/META-INF/MANIFEST.MF @@ -12,12 +12,9 @@ Export-Package: com.raytheon.uf.common.dataplugin.scan, Require-Bundle: javax.persistence;bundle-version="1.0.0", com.raytheon.edex.common;bundle-version="1.11.1", org.apache.commons.logging;bundle-version="1.0.4", - org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.monitor;bundle-version="1.11.5", com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.11.26", - com.raytheon.uf.common.dataplugin.bufrua;bundle-version="1.11.26", - com.raytheon.uf.common.dataplugin.ffmp;bundle-version="1.11.31", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.31", + com.raytheon.uf.common.dataplugin.grid, com.raytheon.uf.common.sounding;bundle-version="1.12.1112", com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0" diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.scan/src/com/raytheon/uf/common/dataplugin/scan/data/ModelData.java b/edexOsgi/com.raytheon.uf.common.dataplugin.scan/src/com/raytheon/uf/common/dataplugin/scan/data/ModelData.java index ce28c26353..006f955220 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.scan/src/com/raytheon/uf/common/dataplugin/scan/data/ModelData.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.scan/src/com/raytheon/uf/common/dataplugin/scan/data/ModelData.java @@ -31,7 +31,7 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.geotools.coverage.grid.GridGeometry2D; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.geospatial.ISpatialObject; import com.raytheon.uf.common.geospatial.MapUtil; @@ -46,7 +46,7 @@ import com.vividsolutions.jts.geom.Coordinate; @DynamicSerialize public class ModelData implements ISerializableObject { - private final Map> gribMap; + private final Map> gribMap; private transient final Log logger = LogFactory.getLog(getClass()); @@ -54,7 +54,7 @@ public class ModelData implements ISerializableObject { * Public constructor */ public ModelData() { - gribMap = new HashMap>(); + gribMap = new HashMap>(); } /** @@ -80,7 +80,7 @@ public class ModelData implements ISerializableObject { * @return * @throws Exception */ - private synchronized GribRecord getRecord(String modelName, String prodType) + private synchronized GridRecord getRecord(String modelName, String prodType) throws Exception { return gribMap.get(modelName).get(prodType); } @@ -90,8 +90,8 @@ public class ModelData implements ISerializableObject { * * @param gr */ - public synchronized void setGribRecord(String modelName, String prodType, - GribRecord gr) { + public synchronized void setGridRecord(String modelName, String prodType, + GridRecord gr) { if (gribMap.get(modelName) != null) { if (gribMap.get(modelName).get(prodType) != null) { if (!gribMap.get(modelName).get(prodType).getDataURI() @@ -103,7 +103,7 @@ public class ModelData implements ISerializableObject { gribMap.get(modelName).put(prodType, gr); } } else { - HashMap modelHash = new HashMap(); + HashMap modelHash = new HashMap(); modelHash.put(prodType, gr); // add new gribMap.put(modelName, modelHash); @@ -115,7 +115,7 @@ public class ModelData implements ISerializableObject { * * @param gr */ - public synchronized GribRecord getGribRecord(String modelName, + public synchronized GridRecord getGridRecord(String modelName, String prodType) { return gribMap.get(modelName).get(prodType); } @@ -160,7 +160,7 @@ public class ModelData implements ISerializableObject { double value = -99999.0; try { Point point = getPoint(modelName, prodType, coor); - GribRecord gribRec = getRecord(modelName, prodType); + GridRecord gribRec = getRecord(modelName, prodType); FloatDataRecord rec = (FloatDataRecord) getRecord(modelName, prodType).getMessageData(); value = rec.getFloatData()[(gribRec.getSpatialObject().getNx() * point.x) diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.vil/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin.vil/META-INF/MANIFEST.MF index e28313148d..89122debf6 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.vil/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin.vil/META-INF/MANIFEST.MF @@ -10,8 +10,7 @@ Require-Bundle: javax.persistence;bundle-version="1.0.0", org.apache.commons.logging;bundle-version="1.0.4", org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.monitor;bundle-version="1.11.5" -Import-Package: com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.radar +Import-Package: com.raytheon.uf.common.dataplugin.radar Export-Package: com.raytheon.uf.common.dataplugin.vil, com.raytheon.uf.common.dataplugin.vil.dao Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.dataplugin/META-INF/MANIFEST.MF index 2ad7deddef..13c9207b94 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.dataplugin/META-INF/MANIFEST.MF @@ -14,11 +14,11 @@ Import-Package: com.raytheon.uf.common.time, org.hibernate.annotations Export-Package: com.raytheon.uf.common.dataplugin, com.raytheon.uf.common.dataplugin.annotations, - com.raytheon.uf.common.dataplugin.convert, com.raytheon.uf.common.dataplugin.defaults, com.raytheon.uf.common.dataplugin.persist, com.raytheon.uf.common.dataplugin.request Require-Bundle: com.raytheon.uf.common.localization;bundle-version="1.12.1174", com.raytheon.uf.common.status, com.raytheon.uf.common.serialization, - com.raytheon.uf.common.serialization.comm + com.raytheon.uf.common.serialization.comm, + com.raytheon.uf.common.util;bundle-version="1.12.1174" diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.dataplugin/component-deploy.xml deleted file mode 100644 index b539470dc5..0000000000 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/IPrecomputedRange.java b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/IPrecomputedRange.java new file mode 100644 index 0000000000..edea697211 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/IPrecomputedRange.java @@ -0,0 +1,39 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + */ +package com.raytheon.uf.common.dataplugin; + +/** + * This interface can be implemented to indicate that a particular + * PluginDataObject has a pre-computed data range + * + * @author ekladstrup + * + */ +public interface IPrecomputedRange { + + public double getDataMin(); + + public double getDataMax(); + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/PluginDataObject.java b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/PluginDataObject.java index c36e85ebbf..89c059618c 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/PluginDataObject.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/PluginDataObject.java @@ -44,7 +44,6 @@ import org.hibernate.annotations.Index; import com.raytheon.uf.common.dataplugin.annotations.DataURI; import com.raytheon.uf.common.dataplugin.annotations.DataURIUtil; -import com.raytheon.uf.common.dataplugin.convert.ConvertUtil; import com.raytheon.uf.common.dataplugin.persist.DefaultPathProvider; import com.raytheon.uf.common.dataplugin.persist.IHDFFilePathProvider; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; @@ -54,6 +53,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; import com.raytheon.uf.common.time.DataTime; import com.raytheon.uf.common.time.util.TimeUtil; +import com.raytheon.uf.common.util.ConvertUtil; /** * Abstract class from which all plugin specific data types inherit. A plugin diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/IPersistableDataObject.java b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/IPersistableDataObject.java index 8751913ce4..17bb9f2503 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/IPersistableDataObject.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/IPersistableDataObject.java @@ -35,17 +35,19 @@ package com.raytheon.uf.common.dataplugin.persist; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * 20Aug2007 393 MW Fegan Initial creation - * + * Oct 10, 2012 1261 djohnson Add generic for identifier. + * *
+ * * @author mfegan * @version 1 - * + * */ -public interface IPersistableDataObject { +public interface IPersistableDataObject { /** * Returns an object representing the identifier. * * @return the identifier */ - public Object getIdentifier(); + IDENTIFIER_TYPE getIdentifier(); } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/PersistableDataObject.java b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/PersistableDataObject.java index 435d79492c..eb55100ec0 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/PersistableDataObject.java +++ b/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/persist/PersistableDataObject.java @@ -49,6 +49,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; * ------------ ---------- ----------- -------------------------- * 7/24/07 353 bphillip Initial Check in * 20080408 1039 jkorman Added traceId for tracing data. + * Oct 10, 2012 1261 djohnson Add generic for identifier. * *
* @@ -57,16 +58,19 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; */ @XmlAccessorType(XmlAccessType.NONE) @DynamicSerialize -public abstract class PersistableDataObject implements IPersistableDataObject, +public abstract class PersistableDataObject implements + IPersistableDataObject, Serializable, ISerializableObject { + private static final long serialVersionUID = -6747395152869923909L; + /** * Object used as the unique identifier. Intended to be used as the primary * key for the associated database table. */ @XmlElement @DynamicSerializeElement - protected Object identifier; + protected IDENTIFIER_TYPE identifier; private String traceId = ""; @@ -96,7 +100,8 @@ public abstract class PersistableDataObject implements IPersistableDataObject, * * @return The identifier */ - public Object getIdentifier() { + @Override + public IDENTIFIER_TYPE getIdentifier() { return identifier; } @@ -106,7 +111,7 @@ public abstract class PersistableDataObject implements IPersistableDataObject, * @param identifier * The identifier */ - public void setIdentifier(Object identifier) { + public void setIdentifier(IDENTIFIER_TYPE identifier) { this.identifier = identifier; } diff --git a/edexOsgi/com.raytheon.uf.common.dataquery/src/com/raytheon/uf/common/dataquery/requests/RequestConstraint.java b/edexOsgi/com.raytheon.uf.common.dataquery/src/com/raytheon/uf/common/dataquery/requests/RequestConstraint.java index 017e9c476c..7a5317f83d 100644 --- a/edexOsgi/com.raytheon.uf.common.dataquery/src/com/raytheon/uf/common/dataquery/requests/RequestConstraint.java +++ b/edexOsgi/com.raytheon.uf.common.dataquery/src/com/raytheon/uf/common/dataquery/requests/RequestConstraint.java @@ -23,6 +23,7 @@ import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.Collection; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; @@ -194,10 +195,17 @@ public class RequestConstraint implements ISerializableObject, Cloneable { * the constraintValues to set */ public void setConstraintValueList(String[] constraintValues) { - int size = (constraintValues != null && constraintValues.length > 1 ? constraintValues.length - * constraintValues[0].length() - : 16); - StringBuffer sb = new StringBuffer(size); + setConstraintValueList(Arrays.asList(constraintValues)); + } + + /** + * Set a list of possible value for a request constraint, used for IN + * ConstraintType. + * + * @param constraintValues + */ + public void setConstraintValueList(Collection constraintValues) { + StringBuffer sb = new StringBuffer(constraintValues.size() * 16); boolean first = true; for (String v : constraintValues) { if (!first) { diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.datastorage.remote/META-INF/MANIFEST.MF deleted file mode 100644 index 2e0d0983b2..0000000000 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/META-INF/MANIFEST.MF +++ /dev/null @@ -1,16 +0,0 @@ -Manifest-Version: 1.0 -Bundle-ManifestVersion: 2 -Bundle-Name: Thrift Plug-in -Bundle-SymbolicName: com.raytheon.uf.common.datastorage.remote -Bundle-Version: 1.12.1174.qualifier -Bundle-Vendor: RAYTHEON -Eclipse-RegisterBuddy: com.raytheon.uf.common.serialization -Require-Bundle: com.raytheon.uf.common.datastorage;bundle-version="1.11.11", - com.raytheon.uf.common.message;bundle-version="1.11.11", - com.raytheon.uf.common.serialization.comm;bundle-version="1.0.0", - com.raytheon.uf.common.serialization;bundle-version="1.11.12", - net.sf.cglib;bundle-version="2.1.3" -Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Bundle-ActivationPolicy: lazy -Export-Package: com.raytheon.uf.common.datastorage.remote.handlers, - com.raytheon.uf.common.datastorage.remote.requests diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/com.raytheon.uf.common.datastorage.remote.ecl b/edexOsgi/com.raytheon.uf.common.datastorage.remote/com.raytheon.uf.common.datastorage.remote.ecl deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.datastorage.remote/component-deploy.xml deleted file mode 100644 index 1d97dc7e9a..0000000000 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/res/spring/rdatastorage-request.xml b/edexOsgi/com.raytheon.uf.common.datastorage.remote/res/spring/rdatastorage-request.xml deleted file mode 100644 index fadb69b369..0000000000 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/res/spring/rdatastorage-request.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/handlers/RetrieveDataHandler.java b/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/handlers/RetrieveDataHandler.java deleted file mode 100644 index 2bcc6dc9a6..0000000000 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/handlers/RetrieveDataHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.common.datastorage.remote.handlers; - -import java.io.File; -import java.lang.reflect.Method; - -import com.raytheon.uf.common.datastorage.DataStoreFactory; -import com.raytheon.uf.common.datastorage.IDataStore; -import com.raytheon.uf.common.datastorage.records.IDataRecord; -import com.raytheon.uf.common.datastorage.remote.requests.ThriftDataRequest; -import com.raytheon.uf.common.datastorage.remote.requests.ThriftDataResponse; -import com.raytheon.uf.common.serialization.comm.IRequestHandler; - -/** - * Uses reflection to invoke an IDataStore method instead of creating a Handler - * for each method - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Aug 3, 2009            mschenke     Initial creation
- * 
- * 
- * - * @author mschenke - * @version 1.0 - */ - -public class RetrieveDataHandler implements IRequestHandler { - - /* - * (non-Javadoc) - * - * @see - * com.raytheon.uf.common.thrift.IRequestHandler#handleRequest(com.raytheon - * .uf.common.thrift.IServerRequest) - */ - @Override - public Object handleRequest(ThriftDataRequest req) throws Exception { - File file = new File(req.getFile()); - if (file.getParentFile().exists() == false) { - file = new File(new File(System.getProperty("edex.home") - + File.separator + "data" + File.separator + "hdf5"), file - .getAbsolutePath()); - } - IDataStore store = DataStoreFactory.getDataStore(file); - Class[] classes = new Class[req.getParameterTypes().length]; - int i = 0; - for (String clazz : req.getParameterTypes()) { - classes[i++] = Class.forName(clazz); - } - Method m = store.getClass().getMethod(req.getMethod(), classes); - Object obj = m.invoke(store, req.getParameters()); - if (obj == null) { - throw new Exception("datastore returned null"); - } else if (obj instanceof IDataRecord) { - return new ThriftDataResponse((IDataRecord) obj); - } else if (obj instanceof IDataRecord[]) { - return new ThriftDataResponse((IDataRecord[]) obj); - } else if (obj instanceof String[]) { - return new ThriftDataResponse((String[]) obj); - } else { - throw new Exception("datastore returned invalid response object: " - + obj.getClass().getName()); - } - } -} diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/requests/ThriftDataRequest.java b/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/requests/ThriftDataRequest.java deleted file mode 100644 index 880473b5f4..0000000000 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/requests/ThriftDataRequest.java +++ /dev/null @@ -1,107 +0,0 @@ -/** - * This software was developed and / or modified by Raytheon Company, - * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * - * U.S. EXPORT CONTROLLED TECHNICAL DATA - * This software product contains export-restricted data whose - * export/transfer/disclosure is restricted by U.S. law. Dissemination - * to non-U.S. persons whether in the United States or abroad requires - * an export license or other authorization. - * - * Contractor Name: Raytheon Company - * Contractor Address: 6825 Pine Street, Suite 340 - * Mail Stop B8 - * Omaha, NE 68106 - * 402.291.0100 - * - * See the AWIPS II Master Rights File ("Master Rights File.pdf") for - * further licensing information. - **/ -package com.raytheon.uf.common.datastorage.remote.requests; - -import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; -import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; -import com.raytheon.uf.common.serialization.comm.IServerRequest; - -/** - * Request for invoking a method on IDataStore using thrift. This class uses - * reflection heavily - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * Aug 3, 2009            mschenke     Initial creation
- * 
- * 
- * - * @author mschenke - * @version 1.0 - */ -@DynamicSerialize -public class ThriftDataRequest implements IServerRequest { - - @DynamicSerializeElement - private Object[] parameters; - - @DynamicSerializeElement - private String[] parameterTypes; - - @DynamicSerializeElement - private String file; - - @DynamicSerializeElement - private String method; - - @DynamicSerializeElement - private boolean useLocking; - - public Object[] getParameters() { - return parameters; - } - - public void setParameters(Object[] parameters) { - this.parameters = parameters; - } - - public String getFile() { - return file; - } - - public void setFile(String file) { - this.file = file; - } - - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - - public boolean isUseLocking() { - return useLocking; - } - - public void setUseLocking(boolean useLocking) { - this.useLocking = useLocking; - } - - public String[] getParameterTypes() { - return parameterTypes; - } - - /** - * Sets the parameter types, these types are turned into classes using - * Class.forName on the server side. Needed for reflective method invocation - * - * @param parameterTypes - * should match up 1-1 with parameters - */ - public void setParameterTypes(String[] parameterTypes) { - this.parameterTypes = parameterTypes; - } - -} diff --git a/edexOsgi/com.raytheon.uf.common.event/.classpath b/edexOsgi/com.raytheon.uf.common.event/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.event/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.event/.project b/edexOsgi/com.raytheon.uf.common.event/.project new file mode 100644 index 0000000000..a5e31e2ffb --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.event/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.event + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.event/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.event/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..6231358f5d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.event/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Thu Jun 14 10:58:39 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.event/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.event/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..364617af80 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.event/META-INF/MANIFEST.MF @@ -0,0 +1,12 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Event +Bundle-SymbolicName: com.raytheon.uf.common.event +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + javax.persistence;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin;bundle-version="1.12.1174" +Export-Package: com.raytheon.uf.common.event diff --git a/cave/com.raytheon.uf.viz.datastorage.remote/build.properties b/edexOsgi/com.raytheon.uf.common.event/build.properties similarity index 100% rename from cave/com.raytheon.uf.viz.datastorage.remote/build.properties rename to edexOsgi/com.raytheon.uf.common.event/build.properties diff --git a/edexOsgi/com.raytheon.uf.common.time/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.event/component-deploy.xml similarity index 96% rename from edexOsgi/com.raytheon.uf.common.time/component-deploy.xml rename to edexOsgi/com.raytheon.uf.common.event/component-deploy.xml index 37f87ff5e2..a4b7d8c4f6 100644 --- a/edexOsgi/com.raytheon.uf.common.time/component-deploy.xml +++ b/edexOsgi/com.raytheon.uf.common.event/component-deploy.xml @@ -1,4 +1,5 @@ - + + diff --git a/edexOsgi/com.raytheon.uf.common.event/src/com/raytheon/uf/common/event/Event.java b/edexOsgi/com.raytheon.uf.common.event/src/com/raytheon/uf/common/event/Event.java new file mode 100644 index 0000000000..4e3aa07e16 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.event/src/com/raytheon/uf/common/event/Event.java @@ -0,0 +1,91 @@ +package com.raytheon.uf.common.event; + +import java.io.Serializable; +import java.text.SimpleDateFormat; +import java.util.Calendar; + +import javax.persistence.Column; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Provides logging and deletion services for camel + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 5, 2012  #1305      bgonzale    Added LogLevel enum and transient attribute.
+ * 
+ * 
+ * + * @author jsanchez + * @version 1.0 + */ +public abstract class Event implements Serializable, ISerializableObject { + + private static final long serialVersionUID = 1L; + + public enum LogLevel { + DEBUG, INFO, WARN, ERROR, FATAL, ALL, OFF, TRACE + } + + @Column + @DynamicSerializeElement + protected Calendar date; + + @Column + @DynamicSerializeElement + protected String id; + + @DynamicSerializeElement + protected LogLevel logLevel; + + public Event() { + this(LogLevel.DEBUG); + } + + public Event(LogLevel logLevel) { + date = Calendar.getInstance(); + this.logLevel = logLevel; + } + + public Calendar getDate() { + return date; + } + + public void setDate(Calendar date) { + this.date = date; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String toString() { + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-d hh:mm:ss"); + return formatter.format(date.getTime()) + " Id: " + id; + } + + /** + * @return the logLevel + */ + public LogLevel getLogLevel() { + return logLevel; + } + + /** + * @param logLevel + * the logLevel to set + */ + public void setLogLevel(LogLevel logLevel) { + this.logLevel = logLevel; + } + +} \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.geospatial/META-INF/MANIFEST.MF index 8f6a0bee35..6728fad0a0 100644 --- a/edexOsgi/com.raytheon.uf.common.geospatial/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.geospatial/META-INF/MANIFEST.MF @@ -14,11 +14,12 @@ Require-Bundle: org.geotools;bundle-version="2.5.2";visibility:=reexport, org.apache.commons.beanutils;bundle-version="1.8.3", com.raytheon.uf.common.serialization;bundle-version="1.12.1174", com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", - com.raytheon.uf.common.dataquery;bundle-version="1.0.0" + com.raytheon.uf.common.dataquery;bundle-version="1.0.0", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.common.util;bundle-version="1.12.1174" Export-Package: com.raytheon.uf.common.geospatial, com.raytheon.uf.common.geospatial.interpolation, com.raytheon.uf.common.geospatial.interpolation.data, com.raytheon.uf.common.geospatial.request, com.raytheon.uf.common.geospatial.spi, com.raytheon.uf.common.geospatial.util -Import-Package: com.raytheon.uf.common.status diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/build.properties b/edexOsgi/com.raytheon.uf.common.geospatial/build.properties index 34d2e4d2da..5791d48d5f 100644 --- a/edexOsgi/com.raytheon.uf.common.geospatial/build.properties +++ b/edexOsgi/com.raytheon.uf.common.geospatial/build.properties @@ -1,4 +1,5 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - . + .,\ + res/ diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.geospatial/component-deploy.xml deleted file mode 100644 index b75ce2262e..0000000000 --- a/edexOsgi/com.raytheon.uf.common.geospatial/component-deploy.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/res/spring/geo-common.xml b/edexOsgi/com.raytheon.uf.common.geospatial/res/spring/geo-common.xml new file mode 100644 index 0000000000..d720e0b4e1 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.geospatial/res/spring/geo-common.xml @@ -0,0 +1,10 @@ + + + + + com.vividsolutions.jts.geom.Geometry + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/MapUtil.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/MapUtil.java index a7d02af7b7..cae2d27ec7 100644 --- a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/MapUtil.java +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/MapUtil.java @@ -595,6 +595,33 @@ public class MapUtil { return LATLON_PROJECTION; } + public static ProjectedCRS contructLambertAzimuthalEqualArea( + double majorAxis, double minorAxis, double latOfOrigin, + double centralMeridian, double falseEasting, double falseNorthing) { + + try { + ParameterValueGroup parameters = dmtFactory + .getDefaultParameters("Lambert_Azimuthal_Equal_Area"); + + parameters.parameter("semi_major").setValue(majorAxis); + parameters.parameter("semi_minor").setValue(minorAxis); + parameters.parameter("latitude_of_center").setValue(latOfOrigin); + parameters.parameter("longitude_of_center").setValue( + centralMeridian); + parameters.parameter("false_easting").setValue(falseEasting); + parameters.parameter("false_northing").setValue(falseNorthing); + + String name = "Equidistant_Cylindrical (LO: " + latOfOrigin + + ", CM: " + centralMeridian + ")"; + + return constructProjection(name, parameters); + } catch (Exception e) { + statusHandler.handle(Priority.WARN, e.getLocalizedMessage(), e); + return null; + } + + } + /** * Construct a lambert conformal crs * @@ -1552,4 +1579,42 @@ public class MapUtil { (int) (sizes[1]) }), newEnv); return newTarget; } + + public static ReferencedEnvelope getBoundingEnvelope( + CoordinateReferenceSystem crs, Polygon crs84Shape) { + try { + // the polygons aren't truly projected, they are just the projected + // points + Coordinate[] coords = crs84Shape.getExteriorRing().getCoordinates(); + MathTransform mt = CRS.findMathTransform(MapUtil.LATLON_PROJECTION, + crs); + // here we project the points back to the native crs + + double maxX = Double.NEGATIVE_INFINITY; + double maxY = Double.NEGATIVE_INFINITY; + double minX = Double.POSITIVE_INFINITY; + double minY = Double.POSITIVE_INFINITY; + for (int i = 0; i < coords.length; ++i) { + DirectPosition2D to = new DirectPosition2D(); + mt.transform(new DirectPosition2D(coords[i].x, coords[i].y), to); + maxX = Math.max(maxX, to.x); + maxY = Math.max(maxY, to.y); + minX = Math.min(minX, to.x); + minY = Math.min(minY, to.y); + } + + return new ReferencedEnvelope(minX, maxX, minY, maxY, crs); + } catch (Exception e) { + statusHandler.handle(Priority.ERROR, e.getLocalizedMessage(), e); + // FIXME actually handle error + throw new RuntimeException(e); + } + } + + public static ReferencedEnvelope getNativeEnvelope(ISpatialObject spatial) + throws FactoryException { + CoordinateReferenceSystem crs = spatial.getCrs(); + Geometry geom = spatial.getGeometry(); + return MapUtil.getBoundingEnvelope(crs, (Polygon) geom); + } } diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/BilinearInterpolation.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/BilinearInterpolation.java index 8ed18fd649..07ba49114e 100644 --- a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/BilinearInterpolation.java +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/BilinearInterpolation.java @@ -50,8 +50,8 @@ public class BilinearInterpolation implements Interpolation { double value = 0.0f; double missing = 1.0f; - int xi = (int) x; - int yi = (int) y; + int xi = (int) Math.floor(x); + int yi = (int) Math.floor(y); // Upper left corner double xWeight = 1 - x + xi; double yWeight = 1 - y + yi; diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/AbstractDataWrapper.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/AbstractDataWrapper.java index 0718924553..5517e44dda 100644 --- a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/AbstractDataWrapper.java +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/AbstractDataWrapper.java @@ -20,12 +20,8 @@ package com.raytheon.uf.common.geospatial.interpolation.data; import org.geotools.coverage.grid.GeneralGridGeometry; -import org.geotools.geometry.DirectPosition2D; -import org.geotools.referencing.CRS; -import org.geotools.referencing.crs.DefaultGeographicCRS; -import org.opengis.referencing.crs.CoordinateReferenceSystem; -import org.opengis.referencing.datum.PixelInCell; -import org.opengis.referencing.operation.MathTransform; + +import com.raytheon.uf.common.geospatial.util.GridGeometryWrapChecker; /** * @@ -63,7 +59,7 @@ public abstract class AbstractDataWrapper implements DataSource, public AbstractDataWrapper(GeneralGridGeometry geometry) { this.nx = geometry.getGridRange().getSpan(0); this.ny = geometry.getGridRange().getSpan(1); - checkForWrapping(geometry); + this.wrapX = GridGeometryWrapChecker.checkForWrapping(geometry); } public AbstractDataWrapper(int nx, int ny) { @@ -117,82 +113,4 @@ public abstract class AbstractDataWrapper implements DataSource, protected abstract void setDataValueInternal(double dataValue, int x, int y); - // Attempt to detect the case where a geographic coordinate reference - // system wraps around the world so that values out of range on the - // X-axis can be retrieved from the other side of the grid. If this is - // the case the sourceWrapX value will be set to the number of grid - // cells that are needed to wrap all the way around the world. - protected void checkForWrapping(GeneralGridGeometry geometry) { - try { - CoordinateReferenceSystem sourceCRS = geometry - .getCoordinateReferenceSystem(); - MathTransform grid2crs = geometry - .getGridToCRS(PixelInCell.CELL_CENTER); - MathTransform crs2LatLon = CRS.findMathTransform(sourceCRS, - DefaultGeographicCRS.WGS84); - // Although theoretically any two points would yield the same - // result, nx is chosen as the x coordinate because it overcomes - // some of the normalization performed in geotools math transforms. - // For most math transforms, geotools will normalize the LatLon - // values into into the range centralMeridian +/- 180. In these - // cases the 360 degree shift performed later is completely - // worthless since geotools will normalize the points into the - // same range regardless of how it is shifted. For a worldwide grid - // the nx coordinate is guaranteed to be just slightly over the - // normalized range, so that when the transform normalizes it will - // use a point that is -360 degrees away from the original point. - // This means that even though the -360 degree shift we apply is - // worthless, the normalization process actually applies an - // equivelant shift that yields the correct result. The end result - // is that whether the transform normalizes or not there is always a - // shift of -360 degrees for all worldwide grids. - - // Start with two points in grid space, one on each corner side of - // the y direction. - DirectPosition2D corner1 = new DirectPosition2D(nx, 0); - DirectPosition2D corner2 = new DirectPosition2D(nx, ny - 1); - // transform the points to crs space. - grid2crs.transform(corner1, corner1); - grid2crs.transform(corner2, corner2); - // and then to latLon space - crs2LatLon.transform(corner1, corner1); - crs2LatLon.transform(corner2, corner2); - // shift the points by 360 degrees because the goal is to know how - // many grid cells exist in one 360 roll of longitude. - corner1.x = corner1.x - 360; - corner2.x = corner2.x - 360; - // transform back to crs. - crs2LatLon.inverse().transform(corner1, corner1); - crs2LatLon.inverse().transform(corner2, corner2); - // and back to grid space - grid2crs.inverse().transform(corner1, corner1); - grid2crs.inverse().transform(corner2, corner2); - // the difference between the starting x value and the current x - // value is the number - int sourceWrapX = (int) (nx - corner1.x); - // In order to wrap then the transformed point x value should be - // on the other side of the grid and the y value should not have - // changed significantly. Additionally the wrapped x value - // should fall exactly on a grid cell. - if (corner1.x > nx - 1) { - return; - } else if (Math.abs(corner1.y - 0) > 0.0001) { - return; - } else if (Math.abs(corner2.y - ny + 1) > 0.0001) { - return; - } else if (Math.abs(corner1.x + sourceWrapX - nx) > 0.0001) { - return; - } else if (Math.abs(corner2.x + sourceWrapX - nx) > 0.0001) { - return; - } else { - this.wrapX = sourceWrapX; - } - - } catch (Exception e) { - // if anything goes wrong in this process just assume we don't - // wrap the x axis, thats not a big deal and it is normal for - // non geographic coordinate systems. - ; - } - } } \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/IntArrayWrapper.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/IntArrayWrapper.java new file mode 100644 index 0000000000..bcf8093239 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/IntArrayWrapper.java @@ -0,0 +1,80 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.geospatial.interpolation.data; + +import org.geotools.coverage.grid.GeneralGridGeometry; + +/** + * Wraps an int array as a {@link DataSource} and {@link DataDestination} + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 5, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class IntArrayWrapper extends DataWrapper1D { + + protected final int[] array; + + public IntArrayWrapper(int[] array, GeneralGridGeometry geometry) { + super(geometry); + this.array = array; + } + + public IntArrayWrapper(int[] array, int nx, int ny) { + super(nx, ny); + this.array = array; + } + + public IntArrayWrapper(int nx, int ny) { + this(new int[nx * ny], nx, ny); + } + + public IntArrayWrapper(GeneralGridGeometry geometry) { + // assume this is going to be a destination and avoid passing + // geometry to super to save time on checking for wrapping. + this(geometry.getGridRange().getSpan(0), geometry.getGridRange() + .getSpan(1)); + } + + public int[] getArray() { + return array; + } + + @Override + protected double getDataValueInternal(int index) { + return array[index]; + } + + @Override + protected void setDataValueInternal(double dataValue, int index) { + array[index] = (int) dataValue; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/UnitConvertingDataDestination.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/UnitConvertingDataDestination.java new file mode 100644 index 0000000000..093669023e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/UnitConvertingDataDestination.java @@ -0,0 +1,67 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.geospatial.interpolation.data; + +import javax.measure.converter.UnitConverter; + +/** + * A data destination that converts to a unit with the specified unit converter; + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 12, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class UnitConvertingDataDestination implements DataDestination { + + protected UnitConverter unitConverter; + + protected DataDestination wrappedDestination; + + /** + * Constructor + * + * @param converter + * the unit converter to apply when setting the values in the + * destination + * @param destination + * the destination to set values on + */ + public UnitConvertingDataDestination(UnitConverter converter, + DataDestination destination) { + this.unitConverter = converter; + this.wrappedDestination = destination; + } + + @Override + public void setDataValue(double dataValue, int x, int y) { + wrappedDestination.setDataValue(unitConverter.convert(dataValue), x, y); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/UnitConvertingDataSource.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/UnitConvertingDataSource.java new file mode 100644 index 0000000000..587e4953ca --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/interpolation/data/UnitConvertingDataSource.java @@ -0,0 +1,67 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.geospatial.interpolation.data; + +import javax.measure.converter.UnitConverter; + +/** + * A data source that converts requested values to a unit with the specified + * converter. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 12, 2012            njensen     Initial creation
+ * 
+ * 
+ * + * @author njensen + * @version 1.0 + */ + +public class UnitConvertingDataSource implements DataSource { + + protected UnitConverter unitConverter; + + protected DataSource wrappedSource; + + /** + * Constructor + * + * @param converter + * the unit converter to apply when getting the values in the + * data source + * @param source + * the source to get values from + */ + public UnitConvertingDataSource(UnitConverter converter, DataSource source) { + this.unitConverter = converter; + this.wrappedSource = source; + } + + @Override + public double getDataValue(int x, int y) { + return unitConverter.convert(wrappedSource.getDataValue(x, y)); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/GridGeometryWrapChecker.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/GridGeometryWrapChecker.java new file mode 100644 index 0000000000..86aa0c9235 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/GridGeometryWrapChecker.java @@ -0,0 +1,158 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.geospatial.util; + +import org.geotools.coverage.grid.GeneralGridGeometry; +import org.geotools.geometry.DirectPosition2D; +import org.geotools.referencing.CRS; +import org.geotools.referencing.crs.DefaultGeographicCRS; +import org.opengis.referencing.FactoryException; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.datum.PixelInCell; +import org.opengis.referencing.operation.MathTransform; +import org.opengis.referencing.operation.TransformException; + +/** + * Provide utility methods for determining if a grid geometry is world wide and + * wrapping so that out of range on the X-axis can be retrieved from the other + * side of the grid. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 5, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridGeometryWrapChecker { + + private static double TOLERANCE = 0.00001; + + /** + * + * Attempt to detect the case where a geographic coordinate reference system + * wraps around the world so that values out of range on the X-axis can be + * retrieved from the other side of the grid. + * + * If the provided grid geometry wraps than the result will be a positive + * value representing the number of grid cells used to wrap around the + * world. The return value can be used to extend the range of the grid + * infinitely in either direction by reusing column values at an interval of + * the return value. For example if a grid normally has an x range from 0 to + * 359 and the result of this method is 360 then the range can be extended + * to 360 by reusing the values from the 0 column, in fact any integer + * column can be referenced by simply taking columnNumber % 360 to get a + * value within the original valid range. + * + * If the grid does not wrap around then the result is -1; + * + * @param geometry + * @return + */ + public static int checkForWrapping(GeneralGridGeometry geometry) { + try { + int nx = geometry.getGridRange().getSpan(0); + int ny = geometry.getGridRange().getSpan(1); + CoordinateReferenceSystem sourceCRS = geometry + .getCoordinateReferenceSystem(); + MathTransform grid2crs = geometry + .getGridToCRS(PixelInCell.CELL_CENTER); + MathTransform crs2LatLon = CRS.findMathTransform(sourceCRS, + DefaultGeographicCRS.WGS84); + MathTransform latLon2crs = crs2LatLon.inverse(); + MathTransform crs2grid = grid2crs.inverse(); + // Although theoretically any two points would yield the same + // result, nx is chosen as the x coordinate because it overcomes + // some of the normalization performed in geotools math transforms. + // For most math transforms, geotools will normalize the LatLon + // values into into the range centralMeridian +/- 180. In these + // cases the 360 degree shift performed later is completely + // worthless since geotools will normalize the points into the + // same range regardless of how it is shifted. For a worldwide grid + // the nx coordinate is guaranteed to be just slightly over the + // normalized range, so that when the transform normalizes it will + // use a point that is -360 degrees away from the original point. + // This means that even though the -360 degree shift we apply is + // worthless, the normalization process actually applies an + // equivelant shift that yields the correct result. The end result + // is that whether the transform normalizes or not there is always a + // shift of -360 degrees for all worldwide grids. + + // Start with two points in grid space, one on each corner side of + // the y direction. + DirectPosition2D corner1 = new DirectPosition2D(nx, 0); + DirectPosition2D corner2 = new DirectPosition2D(nx, ny - 1); + // transform the points to crs space. + grid2crs.transform(corner1, corner1); + grid2crs.transform(corner2, corner2); + // and then to latLon space + crs2LatLon.transform(corner1, corner1); + crs2LatLon.transform(corner2, corner2); + // shift the points by 360 degrees because the goal is to know how + // many grid cells exist in one 360 roll of longitude. + corner1.x = corner1.x - 360; + corner2.x = corner2.x - 360; + // transform back to crs. + latLon2crs.transform(corner1, corner1); + latLon2crs.transform(corner2, corner2); + // and back to grid space + crs2grid.transform(corner1, corner1); + crs2grid.transform(corner2, corner2); + // the difference between the starting x value and the current x + // value is the number + int sourceWrapX = (int) (nx - corner1.x); + // In order to wrap then the transformed point x value should be + // on the other side of the grid and the y value should not have + // changed significantly. Additionally the wrapped x value + // should fall exactly on a grid cell. + if (corner1.x > nx - 1) { + return -1; + } else if (Math.abs(corner1.y - 0) > TOLERANCE) { + return -1; + } else if (Math.abs(corner2.y - ny + 1) > TOLERANCE) { + return -1; + } else if (Math.abs(corner1.x + sourceWrapX - nx) > TOLERANCE) { + return -1; + } else if (Math.abs(corner2.x + sourceWrapX - nx) > TOLERANCE) { + return -1; + } else { + return sourceWrapX; + } + } catch (FactoryException e) { + // Every known crs which can world wrap does not throw factory + // exceptions when getting transformation so if an exception is + // thrown assume it is because the grid does not world wrap. + return -1; + } catch (TransformException e) { + // this exception is expected for some grids that do not world + // wrap, often because while checking transformation is performed + // for invalid coordinates. + return -1; + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/WorldWrapCorrector.java b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/WorldWrapCorrector.java index e285c50fcb..59ad5a8766 100644 --- a/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/WorldWrapCorrector.java +++ b/edexOsgi/com.raytheon.uf.common.geospatial/src/com/raytheon/uf/common/geospatial/util/WorldWrapCorrector.java @@ -225,15 +225,25 @@ public class WorldWrapCorrector { // throw them out since we can't guarantee integrity GeometryFactory gf = flattenedGeom.getFactory(); double delta = 0.00001; - double start = checker.getLowInverseCentralMeridian() + offsets[0]; - double end = checker.getHighInverseCentralMeridian() + offsets[1]; + // Because Geometries are within bounds -180-180, ensure our initial + // start/end range will fully cover it + double lowInverseCentral = checker.getLowInverseCentralMeridian(); + if (lowInverseCentral > -180.0) { + lowInverseCentral -= 360.0; + } + double highInverseCentral = checker.getHighInverseCentralMeridian(); + if (highInverseCentral < 180.0) { + highInverseCentral += 360.0; + } + double start = lowInverseCentral + offsets[0]; + double end = highInverseCentral + offsets[1]; double minY = -90, maxY = 90; while (start < end) { double useStart = start; double useEnd = start + 360; double minX = useStart + delta; - double maxX = (useEnd) - delta; + double maxX = useEnd - delta; Geometry section = gf.createPolygon( gf.createLinearRing(new Coordinate[] { @@ -246,7 +256,7 @@ public class WorldWrapCorrector { if (section.isEmpty() == false) { geoms.add(section); } - start += 360.0; + start = useEnd; } } } diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/.classpath b/edexOsgi/com.raytheon.uf.common.gridcoverage/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/.project b/edexOsgi/com.raytheon.uf.common.gridcoverage/.project new file mode 100644 index 0000000000..bd0da3b92e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.gridcoverage + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.gridcoverage/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..23df60bb0e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Jan 31 13:49:11 CST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.gridcoverage/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..52c3666e0c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/META-INF/MANIFEST.MF @@ -0,0 +1,31 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Grid Coverage +Bundle-SymbolicName: com.raytheon.uf.common.gridcoverage +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Eclipse-RegisterBuddy: com.raytheon.uf.common.serialization +Import-Package: com.raytheon.uf.common.dataplugin, + com.raytheon.uf.common.dataplugin.annotations, + com.raytheon.uf.common.dataplugin.persist, + com.raytheon.uf.common.dataquery.requests, + com.raytheon.uf.common.dataquery.responses, + javax.persistence, + org.apache.commons.beanutils, + org.apache.commons.collections.map, + org.apache.commons.lang.builder, + org.hibernate.annotations +Export-Package: com.raytheon.uf.common.gridcoverage, + com.raytheon.uf.common.gridcoverage.convert, + com.raytheon.uf.common.gridcoverage.exception, + com.raytheon.uf.common.gridcoverage.lookup, + com.raytheon.uf.common.gridcoverage.request, + com.raytheon.uf.common.gridcoverage.subgrid +Require-Bundle: org.geotools;bundle-version="2.6.4", + com.raytheon.uf.common.serialization, + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + com.raytheon.uf.common.units;bundle-version="1.0.0", + com.raytheon.uf.common.geospatial;bundle-version="1.12.1174", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.common.util;bundle-version="1.12.1174" diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.gridcoverage/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject new file mode 100644 index 0000000000..417b02f0b1 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject @@ -0,0 +1,5 @@ +com.raytheon.uf.common.gridcoverage.LatLonGridCoverage +com.raytheon.uf.common.gridcoverage.MercatorGridCoverage +com.raytheon.uf.common.gridcoverage.PolarStereoGridCoverage +com.raytheon.uf.common.gridcoverage.LambertConformalGridCoverage +com.raytheon.uf.common.gridcoverage.StereographicGridCoverage \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/build.properties b/edexOsgi/com.raytheon.uf.common.gridcoverage/build.properties new file mode 100644 index 0000000000..5791d48d5f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ diff --git a/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/util/bufrua/package-info.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/res/scripts/gridcoverage_indices.sql similarity index 86% rename from edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/util/bufrua/package-info.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/res/scripts/gridcoverage_indices.sql index 02d6349bdf..c7667db9ce 100644 --- a/edexOsgi/com.raytheon.edex.plugin.bufrua/src/com/raytheon/edex/util/bufrua/package-info.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/res/scripts/gridcoverage_indices.sql @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -/** - * BUFR Upperair data access classes. and other possible utility classes. - */ -package com.raytheon.edex.util.bufrua; \ No newline at end of file +CREATE INDEX "gridCoverageTypeNxNy_idx" + ON gridcoverage + USING btree + (dtype, nx, ny); \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/res/spring/gridcoverage-converter-common.xml b/edexOsgi/com.raytheon.uf.common.gridcoverage/res/spring/gridcoverage-converter-common.xml new file mode 100644 index 0000000000..a228be39bf --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/res/spring/gridcoverage-converter-common.xml @@ -0,0 +1,10 @@ + + + + + com.raytheon.uf.common.gridcoverage.GridCoverage + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/Corner.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/Corner.java similarity index 92% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/Corner.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/Corner.java index d29dc80bce..6658a1e6f9 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/Corner.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/Corner.java @@ -17,10 +17,10 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.spatial.projections; +package com.raytheon.uf.common.gridcoverage; /** - * TODO Add Description + * enum for starting corner of GridCoverages * *
  * 
diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/GridCoverage.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/GridCoverage.java
similarity index 80%
rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/GridCoverage.java
rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/GridCoverage.java
index e6fc0f1667..9e3a66f8e9 100644
--- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/GridCoverage.java
+++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/GridCoverage.java
@@ -18,7 +18,7 @@
  * further licensing information.
  **/
 
-package com.raytheon.uf.common.dataplugin.grib.spatial.projections;
+package com.raytheon.uf.common.gridcoverage;
 
 import javax.measure.converter.UnitConverter;
 import javax.measure.unit.SI;
@@ -27,13 +27,18 @@ import javax.persistence.Column;
 import javax.persistence.Entity;
 import javax.persistence.EnumType;
 import javax.persistence.Enumerated;
+import javax.persistence.GeneratedValue;
+import javax.persistence.GenerationType;
 import javax.persistence.Id;
 import javax.persistence.Inheritance;
 import javax.persistence.InheritanceType;
+import javax.persistence.SequenceGenerator;
+import javax.persistence.Table;
 import javax.persistence.Transient;
 import javax.xml.bind.annotation.XmlAccessType;
 import javax.xml.bind.annotation.XmlAccessorType;
 import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
 
 import org.apache.commons.lang.builder.HashCodeBuilder;
 import org.geotools.coverage.grid.GridGeometry2D;
@@ -42,19 +47,20 @@ import org.opengis.referencing.FactoryException;
 import org.opengis.referencing.crs.CoordinateReferenceSystem;
 import org.opengis.referencing.operation.MathTransform;
 
-import com.raytheon.uf.common.dataplugin.grib.exception.GribException;
-import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid;
-import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef;
+import com.raytheon.uf.common.dataplugin.annotations.DataURI;
 import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject;
 import com.raytheon.uf.common.geospatial.CRSCache;
 import com.raytheon.uf.common.geospatial.ISpatialObject;
 import com.raytheon.uf.common.geospatial.MapUtil;
+import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException;
+import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid;
+import com.raytheon.uf.common.serialization.adapters.GeometryAdapter;
 import com.raytheon.uf.common.serialization.annotations.DynamicSerialize;
 import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement;
 import com.vividsolutions.jts.geom.Geometry;
 
 /**
- * Base class for encapsulating grib spatial information
+ * Base class for encapsulating grid spatial information
  * 
  * 
  * 
@@ -63,7 +69,9 @@ import com.vividsolutions.jts.geom.Geometry;
  * Date         Ticket#     Engineer    Description
  * ------------ ----------  ----------- --------------------------
  * 4/7/09       1994        bphillip    Initial Creation
+ * Sep 07, 2012 1102        djohnson    Add missing JAXB annotations.
  * 09/10/2012   DR 15270    D. Friedman Fix subgrid model name handling.
+ * Nov 02, 2012 1302        djohnson    Remove commented out code.
  * 
  * 
* @@ -71,29 +79,35 @@ import com.vividsolutions.jts.geom.Geometry; * @version 1 */ @Entity +@Table @Inheritance(strategy = InheritanceType.SINGLE_TABLE) +@SequenceGenerator(name = "GRIDCOVERAGE_GENERATOR", sequenceName = "gridcoverage_seq", allocationSize = 1) @XmlAccessorType(XmlAccessType.NONE) @DynamicSerialize -public abstract class GridCoverage extends PersistableDataObject implements - ISpatialObject { +public abstract class GridCoverage extends PersistableDataObject + implements ISpatialObject { private static final long serialVersionUID = -1355232934065074837L; - - protected static final String SUBGRID_TOKEN = "-SubGrid-"; + + protected static final String SUBGRID_TOKEN = "SubGrid-"; + + public static final double SPATIAL_TOLERANCE = 0.1; /** The id for this grid. This value is generated in the initialize method **/ @Id + @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GRIDCOVERAGE_GENERATOR") @DynamicSerializeElement - protected int id; + protected Integer id; /** The name of the grid */ - @Column(length = 2047) + @Column @XmlElement @DynamicSerializeElement + @DataURI(position = 0) protected String name; /** A description of the grid coverage */ - @Column(length = 3071) + @Transient @XmlElement @DynamicSerializeElement protected String description; @@ -101,11 +115,13 @@ public abstract class GridCoverage extends PersistableDataObject implements /** Geometry object holding the corner points of the grid */ @Column(name = "the_geom", columnDefinition = "geometry") @Type(type = "com.raytheon.edex.db.objects.hibernate.GeometryType") + @XmlJavaTypeAdapter(value = GeometryAdapter.class) @DynamicSerializeElement protected Geometry geometry; /** The CRS as a WKT String */ @Column(name = "crs", length = 2047) + @XmlElement @DynamicSerializeElement protected String crsWKT; @@ -198,7 +214,11 @@ public abstract class GridCoverage extends PersistableDataObject implements @Override public String toString() { - return "Coverage Information Not Specified yet"; + if (id == null) { + return "Coverage Information Not Specified yet"; + } else { + return Integer.toString(id); + } } @Override @@ -214,9 +234,6 @@ public abstract class GridCoverage extends PersistableDataObject implements */ public int generateHash() { HashCodeBuilder hashBuilder = new HashCodeBuilder(); - if (getName() == null) { - generateName(); - } hashBuilder.append(name); hashBuilder.append(nx); hashBuilder.append(ny); @@ -230,13 +247,13 @@ public abstract class GridCoverage extends PersistableDataObject implements } /** - * Initializes the grib coverage object. Initialization should entail + * Initializes the grid coverage object. Initialization should entail * creation of the crs and geometry object as well as assigning the id field * - * @throws GribException + * @throws GridCoverageException * If problems occur while creating the crs, geometry, or the id */ - public abstract void initialize() throws GribException; + public abstract void initialize() throws GridCoverageException; /** * Gets the name of the projection. The projection type is specified by each @@ -246,12 +263,6 @@ public abstract class GridCoverage extends PersistableDataObject implements */ public abstract String getProjectionType(); - /** - * If this grid coverage object describes a grid that is not predefined, - * this method is used to generate and assign a descriptive name. - */ - public abstract void generateName(); - /** * Trim this GridCoverage to a sub grid. * @@ -259,12 +270,14 @@ public abstract class GridCoverage extends PersistableDataObject implements * @param subGrid * @return trimmed coverage */ - public abstract GridCoverage trim(SubGridDef subGridDef, SubGrid subGrid); + public abstract GridCoverage trim(SubGrid subGrid); + @Override public Geometry getGeometry() { return geometry; } + @Override public CoordinateReferenceSystem getCrs() { if (crs == null) { try { @@ -282,7 +295,7 @@ public abstract class GridCoverage extends PersistableDataObject implements * * @return The id */ - public int getId() { + public Integer getId() { return id; } @@ -292,7 +305,7 @@ public abstract class GridCoverage extends PersistableDataObject implements * @param id * The id */ - public void setId(int id) { + public void setId(Integer id) { this.id = id; } @@ -377,8 +390,8 @@ public abstract class GridCoverage extends PersistableDataObject implements if (gridGeometry == null) { gridGeometry = MapUtil.getGridGeometry(this); } - - return gridGeometry; + + return gridGeometry; } public void setGridGeometry(GridGeometry2D gridGeometry) { @@ -401,14 +414,14 @@ public abstract class GridCoverage extends PersistableDataObject implements this.lo1 = lo1; } - public Double getLowerLeftLat() throws GribException { + public Double getLowerLeftLat() throws GridCoverageException { if (lowerLeftLat == null) { generateLowerLeft(); } return lowerLeftLat; } - public Double getLowerLeftLon() throws GribException { + public Double getLowerLeftLon() throws GridCoverageException { if (lowerLeftLon == null) { generateLowerLeft(); } @@ -423,6 +436,7 @@ public abstract class GridCoverage extends PersistableDataObject implements this.firstGridPointCorner = firstGridPointCorner; } + @Override public Integer getNx() { return nx; } @@ -431,6 +445,7 @@ public abstract class GridCoverage extends PersistableDataObject implements this.nx = nx; } + @Override public Integer getNy() { return ny; } @@ -490,7 +505,7 @@ public abstract class GridCoverage extends PersistableDataObject implements /** * */ - protected void generateLowerLeft() throws GribException { + protected void generateLowerLeft() throws GridCoverageException { try { if ("degree".equals(spacingUnit)) { switch (firstGridPointCorner) { @@ -520,7 +535,7 @@ public abstract class GridCoverage extends PersistableDataObject implements lowerLeftLon = lo1; } else { if (getCrs() == null) { - throw new GribException("CRS is null."); + throw new GridCoverageException("CRS is null."); } Unit spacingUnitObj = Unit.valueOf(spacingUnit); @@ -561,23 +576,22 @@ public abstract class GridCoverage extends PersistableDataObject implements lowerLeftLon = lonLat[0]; lowerLeftLat = lonLat[1]; } else { - throw new GribException("Cannot converter " + spacingUnit - + " to meters"); + throw new GridCoverageException("Cannot convert " + + spacingUnit + " to meters"); } } } catch (Exception e) { - throw new GribException( + throw new GridCoverageException( "Cannot determine LowerLeft and UpperRight points of grid", e); } lowerLeftLon = MapUtil.correctLon(lowerLeftLon); - lowerLeftLat = MapUtil.correctLat(lowerLeftLat); } - protected void generateGeometry() throws GribException { + protected void generateGeometry() throws GridCoverageException { if ("degree".equals(spacingUnit)) { // lower left is cell center, we want cell corners. - double minLat = MapUtil.correctLat(getLowerLeftLat() - dy / 2); + double minLat = getLowerLeftLat() - dy / 2; double maxLat = minLat + dy * ny; double minLon = getLowerLeftLon() - dx / 2; if (dx * nx <= 360) { @@ -613,7 +627,7 @@ public abstract class GridCoverage extends PersistableDataObject implements geometry = MapUtil.createGeometry(minLat, minLon, maxLat, maxLon); } catch (Exception e) { - throw new GribException("Error creating geometry", e); + throw new GridCoverageException("Error creating geometry", e); } } else { try { @@ -625,11 +639,12 @@ public abstract class GridCoverage extends PersistableDataObject implements getLowerLeftLon(), converter.convert(dx), converter.convert(dy), nx, ny); } else { - throw new GribException("Unable to convert " + spacingUnit + throw new GridCoverageException("Unable to convert " + + spacingUnit + " to meters while creating geometry!"); } } catch (Exception e) { - throw new GribException("Error creating geometry", e); + throw new GridCoverageException("Error creating geometry", e); } } } @@ -685,27 +700,76 @@ public abstract class GridCoverage extends PersistableDataObject implements return true; } - public void determineFirstGridPointCorner(int scanMode) { - if ((scanMode & 128) > 0) { - // -i - if ((scanMode & 64) > 0) { - // +j - setFirstGridPointCorner(Corner.LowerRight); - } else { - // -j - setFirstGridPointCorner(Corner.UpperRight); - } - } else { - // +i - if ((scanMode & 64) > 0) { - // +j - setFirstGridPointCorner(Corner.LowerLeft); - } else { - // -j - setFirstGridPointCorner(Corner.UpperLeft); - } - + /** + * Compare coverages to see if they are equivelant within a certain + * tolerance + * + * @param other + * @return true to indicate the coverages should be treated as equals, false + * if they are too different. + */ + public boolean spatialEquals(GridCoverage other) { + if (!this.getClass().equals(other.getClass())) { + return false; } + if (nx == null) { + if (other.nx != null) { + return false; + } + } else if (!nx.equals(other.nx)) { + return false; + } + if (ny == null) { + if (other.ny != null) { + return false; + } + } else if (!ny.equals(other.ny)) { + return false; + } + if (spacingUnit == null) { + if (other.spacingUnit != null) { + return false; + } + } else if (!spacingUnit.equals(other.spacingUnit)) { + return false; + } + if (firstGridPointCorner != other.firstGridPointCorner) { + return false; + } + if (Math.abs(dx - other.dx) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(dy - other.dy) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(la1 - other.la1) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(MapUtil.correctLon(lo1) + - MapUtil.correctLon(other.lo1)) > SPATIAL_TOLERANCE) { + return false; + } + return true; + } + + /** + * Unique key containing the spatial attributes of this coverage. + * + * @return + */ + public String spatialKey() { + StringBuilder key = new StringBuilder(96); + key.append(getProjectionType().replace(" ", "_")); + key.append(DataURI.SEPARATOR); + key.append(nx); + key.append(DataURI.SEPARATOR); + key.append(ny); + key.append(DataURI.SEPARATOR); + key.append(dx); + key.append(DataURI.SEPARATOR); + key.append(dy); + key.append(DataURI.SEPARATOR); + key.append(lo1); + key.append(DataURI.SEPARATOR); + key.append(la1); + return key.toString(); } public GridCoverage(GridCoverage coverage) { @@ -731,49 +795,4 @@ public abstract class GridCoverage extends PersistableDataObject implements this.includePole = coverage.includePole; } - /** - * Determines if this coverage is a subGrid. - * - * @return - */ - public boolean isSubGridded() { - String subGridName = getName(); - - if (subGridName != null) { - return getName().contains(SUBGRID_TOKEN); - } - - return false; - } - - /** - * If this coverage is subGridded, return the model it is a subGrid for, - * else null. - * - * @return - */ - public String getSubGridModel() { - String model = null; - if (isSubGridded()) { - String subGridName = getName(); - int index = subGridName.lastIndexOf(SUBGRID_TOKEN); - if (index >= 0 - && index + SUBGRID_TOKEN.length() < subGridName.length()) { - model = subGridName.substring(index + SUBGRID_TOKEN.length()); - } - } - return model; - } - - public String getParentGridName() { - String parentName = null; - if (isSubGridded()) { - String subGridName = getName(); - int index = subGridName.indexOf(SUBGRID_TOKEN); - if (index >= 0) { - parentName = subGridName.substring(0, index); - } - } - return parentName; - } } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/LambertConformalGridCoverage.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/LambertConformalGridCoverage.java similarity index 81% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/LambertConformalGridCoverage.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/LambertConformalGridCoverage.java index 9a6d4cc21a..af0cfd2255 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/LambertConformalGridCoverage.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/LambertConformalGridCoverage.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.spatial.projections; +package com.raytheon.uf.common.gridcoverage; import javax.measure.converter.UnitConverter; import javax.measure.unit.SI; @@ -34,11 +34,11 @@ import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang.builder.HashCodeBuilder; import org.opengis.referencing.operation.MathTransform; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.TrimUtil.Trim; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef; +import com.raytheon.uf.common.dataplugin.annotations.DataURI; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; +import com.raytheon.uf.common.gridcoverage.subgrid.TrimUtil; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -121,24 +121,15 @@ public class LambertConformalGridCoverage extends GridCoverage { } @Override - public void initialize() throws GribException { + public void initialize() throws GridCoverageException { crs = MapUtil.constructLambertConformal(majorAxis, minorAxis, latin1, latin2, lov); crsWKT = crs.toWKT(); generateGeometry(); - id = generateHash(); - } - - public void generateName() { - String nameAndDescription = "Unknown " + nx + " X " + ny + " " - + Math.round(dx) + " " + spacingUnit + " " - + getProjectionType() + " grid"; - this.setName(nameAndDescription); - this.setDescription(nameAndDescription); } @Override - public GridCoverage trim(SubGridDef subGridDef, SubGrid subGrid) { + public GridCoverage trim(SubGrid subGrid) { LambertConformalGridCoverage rval = new LambertConformalGridCoverage(); rval.description = this.description; rval.dx = this.dx; @@ -150,8 +141,6 @@ public class LambertConformalGridCoverage extends GridCoverage { rval.majorAxis = this.majorAxis; rval.minorAxis = this.minorAxis; - rval.setName(this.name + SUBGRID_TOKEN + subGrid.getModelName()); - try { Unit spacingUnitObj = Unit.valueOf(spacingUnit); if (spacingUnitObj.isCompatible(SI.METRE)) { @@ -163,35 +152,26 @@ public class LambertConformalGridCoverage extends GridCoverage { .getTransformFromLatLon(getCrs()); MathTransform toLatLon = fromLatLon.inverse(); - Trim trim = null; try { - trim = TrimUtil.trimMeterSpace(getLowerLeftLat(), - getLowerLeftLon(), subGridDef, this.nx, this.ny, + TrimUtil.trimMeterSpace(getLowerLeftLat(), + getLowerLeftLon(), subGrid, this.nx, this.ny, dxMeter, dyMeter, fromLatLon, toLatLon, true); - } catch (GribException e) { - statusHandler.handle(Priority.WARN, "Grib coverage [" + } catch (GridCoverageException e) { + statusHandler.handle(Priority.WARN, "Grid coverage [" + this.getName() + "] not applicable to this site"); return null; } - subGrid.setUpperLeftX(trim.upperLeftX); - subGrid.setUpperLeftY(trim.upperLeftY); - - subGrid.setNX(trim.nx); - subGrid.setNY(trim.ny); - rval.firstGridPointCorner = Corner.LowerLeft; - rval.lo1 = trim.lowerLeftLon; - rval.la1 = trim.lowerLeftLat; - rval.nx = trim.nx; - rval.ny = trim.ny; + rval.lo1 = subGrid.getLowerLeftLon(); + rval.la1 = subGrid.getLowerLeftLat(); + rval.nx = subGrid.getNX(); + rval.ny = subGrid.getNY(); - rval.setId(rval.hashCode()); + rval.setName(SUBGRID_TOKEN + this.getId()); } else { - statusHandler.handle( - Priority.PROBLEM, - "Error creating sub grid definition [" - + subGrid.getModelName() + statusHandler.handle(Priority.PROBLEM, + "Error creating sub grid definition [" + this.name + "], units are not compatible with meter [" + spacingUnit + "]"); rval = null; @@ -334,6 +314,34 @@ public class LambertConformalGridCoverage extends GridCoverage { return true; } + public boolean spatialEquals(GridCoverage other) { + if (super.spatialEquals(other)) { + LambertConformalGridCoverage otherLambert = (LambertConformalGridCoverage) other; + if (Math.abs(latin1 - otherLambert.latin1) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(latin2 - otherLambert.latin2) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(lov - otherLambert.lov) > SPATIAL_TOLERANCE) { + return false; + } + return true; + } + return false; + } + + @Override + public String spatialKey() { + StringBuilder key = new StringBuilder(96); + key.append(super.spatialKey()); + key.append(DataURI.SEPARATOR); + key.append(latin1); + key.append(DataURI.SEPARATOR); + key.append(latin2); + key.append(DataURI.SEPARATOR); + key.append(lov); + return key.toString(); + } + public LambertConformalGridCoverage() { super(); } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/LatLonGridCoverage.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/LatLonGridCoverage.java similarity index 80% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/LatLonGridCoverage.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/LatLonGridCoverage.java index 9cc4dffd6b..4c8576a1e6 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/LatLonGridCoverage.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/LatLonGridCoverage.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.spatial.projections; +package com.raytheon.uf.common.gridcoverage; import javax.persistence.Entity; import javax.persistence.Table; @@ -28,11 +28,10 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.TrimUtil.Trim; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; +import com.raytheon.uf.common.gridcoverage.subgrid.TrimUtil; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; @@ -91,7 +90,7 @@ public class LatLonGridCoverage extends GridCoverage { private int[] parallels; @Override - public void initialize() throws GribException { + public void initialize() throws GridCoverageException { // lower left is cell center, we want cell corners. double minLon = getLowerLeftLon() - dx / 2; double maxLon = minLon + dx * nx; @@ -113,17 +112,6 @@ public class LatLonGridCoverage extends GridCoverage { crsWKT = crs.toWKT(); generateGeometry(); - id = generateHash(); - } - - @Override - public void generateName() { - - String nameAndDescription = "Unknown " + nx + " X " + ny + " " - + getProjectionType() + " grid"; - this.setName(nameAndDescription); - this.setDescription(nameAndDescription); - } @Override @@ -142,36 +130,26 @@ public class LatLonGridCoverage extends GridCoverage { } @Override - public GridCoverage trim(SubGridDef subGridDef, SubGrid subGrid) { + public GridCoverage trim(SubGrid subGrid) { LatLonGridCoverage rval = new LatLonGridCoverage(); rval.description = this.description; rval.dx = this.dx; rval.dy = this.dy; rval.spacingUnit = this.spacingUnit; - rval.setName(this.name + SUBGRID_TOKEN + subGrid.getModelName()); - try { if (spacingUnit.equals("degree")) { - Trim trim = TrimUtil.trimLatLonSpace(getLowerLeftLat(), - getLowerLeftLon(), subGridDef, this.nx, this.ny, - this.dx, this.dy); - - subGrid.setUpperLeftX(trim.upperLeftX); - subGrid.setUpperLeftY(trim.upperLeftY); - - subGrid.setNX(trim.nx); - subGrid.setNY(trim.ny); + TrimUtil.trimLatLonSpace(getLowerLeftLat(), getLowerLeftLon(), + subGrid, this.nx, this.ny, this.dx, this.dy); rval.firstGridPointCorner = Corner.LowerLeft; - rval.lo1 = trim.lowerLeftLon; - rval.la1 = trim.lowerLeftLat; - rval.nx = trim.nx; - rval.ny = trim.ny; - - rval.setId(rval.hashCode()); + rval.lo1 = subGrid.getLowerLeftLon(); + rval.la1 = subGrid.getLowerLeftLat(); + rval.nx = subGrid.getNX(); + rval.ny = subGrid.getNY(); + rval.setName(SUBGRID_TOKEN + this.getId()); } else { - throw new GribException( + throw new GridCoverageException( "SubGridding a lat/lon grid not in lat lon spacing is unimplemented"); } } catch (Exception e) { diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/MercatorGridCoverage.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/MercatorGridCoverage.java similarity index 82% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/MercatorGridCoverage.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/MercatorGridCoverage.java index aaed40b631..afc8cd36f9 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/MercatorGridCoverage.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/MercatorGridCoverage.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.spatial.projections; +package com.raytheon.uf.common.gridcoverage; import javax.measure.converter.UnitConverter; import javax.measure.unit.SI; @@ -36,11 +36,11 @@ import org.geotools.geometry.DirectPosition2D; import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.opengis.referencing.operation.MathTransform; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.TrimUtil.Trim; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef; +import com.raytheon.uf.common.dataplugin.annotations.DataURI; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; +import com.raytheon.uf.common.gridcoverage.subgrid.TrimUtil; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -121,7 +121,7 @@ public class MercatorGridCoverage extends GridCoverage { } @Override - public void initialize() throws GribException { + public void initialize() throws GridCoverageException { double meridian = 0; if (la2 == null || lo2 == null) { initializeSecondCorner(); @@ -157,11 +157,9 @@ public class MercatorGridCoverage extends GridCoverage { crs = MapUtil.constructMercator(majorAxis, minorAxis, latin, meridian); crsWKT = crs.toWKT(); generateGeometry(); - id = generateHash(); - } - private void initializeSecondCorner() throws GribException { + private void initializeSecondCorner() throws GridCoverageException { // Since the CRS has not been produced yet, we create a dummy CRS for // calculation purposes @@ -179,31 +177,31 @@ public class MercatorGridCoverage extends GridCoverage { fromLatLon.transform(new DirectPosition2D(lo1, la1), firstPosition); // move firstPosition from cell center to cell corner - firstPosition.x -= 0.5 * dx; - firstPosition.y -= 0.5 * dy; + firstPosition.x -= 0.5 * dx * 1000; + firstPosition.y -= 0.5 * dy * 1000; // Determine the other corner point using the given dx,dy,nx, and // ny in meters DirectPosition2D position = null; switch (firstGridPointCorner) { case LowerLeft: - position = new DirectPosition2D(firstPosition.x + dx * nx, - firstPosition.y + dy * ny); + position = new DirectPosition2D(firstPosition.x + dx * 1000 + * nx, firstPosition.y + dy * 1000 * ny); break; case UpperLeft: - position = new DirectPosition2D(firstPosition.x + dx * nx, - firstPosition.y - dy * ny); + position = new DirectPosition2D(firstPosition.x + dx * 1000 + * nx, firstPosition.y - dy * 1000 * ny); break; case LowerRight: - position = new DirectPosition2D(firstPosition.x - dx * nx, - firstPosition.y - dy * ny); + position = new DirectPosition2D(firstPosition.x - dx * 1000 + * nx, firstPosition.y - dy * 1000 * ny); break; case UpperRight: - position = new DirectPosition2D(firstPosition.x - dx * nx, - firstPosition.y - dy * ny); + position = new DirectPosition2D(firstPosition.x - dx * 1000 + * nx, firstPosition.y - dy * 1000 * ny); break; default: - throw new GribException( + throw new GridCoverageException( "Inavalid grid point corner specified: " + this.firstGridPointCorner); } @@ -213,22 +211,13 @@ public class MercatorGridCoverage extends GridCoverage { lo2 = cornerPosition.x; la2 = cornerPosition.y; } catch (Exception e) { - throw new GribException( + throw new GridCoverageException( "Error calculating la2/lo2 for mercator projection!", e); } } @Override - public void generateName() { - String nameAndDescription = "Unknown " + nx + " X " + ny + " " - + Math.round(dx) + " " + spacingUnit + " " - + getProjectionType() + " grid"; - this.setName(nameAndDescription); - this.setDescription(nameAndDescription); - } - - @Override - public GridCoverage trim(SubGridDef subGridDef, SubGrid subGrid) { + public GridCoverage trim(SubGrid subGrid) { MercatorGridCoverage rval = new MercatorGridCoverage(); rval.description = this.description; rval.dx = this.dx; @@ -237,7 +226,6 @@ public class MercatorGridCoverage extends GridCoverage { rval.latin = this.latin; rval.majorAxis = this.majorAxis; rval.minorAxis = this.minorAxis; - rval.setName(this.name + SUBGRID_TOKEN + subGrid.getModelName()); try { Unit spacingUnitObj = Unit.valueOf(spacingUnit); @@ -250,37 +238,27 @@ public class MercatorGridCoverage extends GridCoverage { .getTransformFromLatLon(getCrs()); MathTransform toLatLon = fromLatLon.inverse(); - Trim trim = null; try { - trim = TrimUtil.trimMeterSpace(getLowerLeftLat(), - getLowerLeftLon(), subGridDef, this.nx, this.ny, + TrimUtil.trimMeterSpace(getLowerLeftLat(), + getLowerLeftLon(), subGrid, this.nx, this.ny, dxMeter, dyMeter, fromLatLon, toLatLon, true); - } catch (GribException e) { - statusHandler.handle(Priority.WARN, "Grib coverage [" + } catch (GridCoverageException e) { + statusHandler.handle(Priority.WARN, "Grid coverage [" + this.getName() + "] not applicable to this site"); return null; } - subGrid.setUpperLeftX(trim.upperLeftX); - subGrid.setUpperLeftY(trim.upperLeftY); - - subGrid.setNX(trim.nx); - subGrid.setNY(trim.ny); - rval.firstGridPointCorner = Corner.LowerLeft; - rval.lo1 = trim.lowerLeftLon; - rval.la1 = trim.lowerLeftLat; - rval.lo2 = trim.upperRightLon; - rval.la2 = trim.upperRightLat; - rval.nx = trim.nx; - rval.ny = trim.ny; - - rval.setId(rval.hashCode()); + rval.lo1 = subGrid.getLowerLeftLon(); + rval.la1 = subGrid.getLowerLeftLat(); + rval.lo2 = subGrid.getUpperRightLon(); + rval.la2 = subGrid.getUpperRightLat(); + rval.nx = subGrid.getNX(); + rval.ny = subGrid.getNY(); + rval.setName(SUBGRID_TOKEN + this.getId()); } else { - statusHandler.handle( - Priority.PROBLEM, - "Error creating sub grid definition [" - + subGrid.getModelName() + statusHandler.handle(Priority.PROBLEM, + "Error creating sub grid definition [" + this.name + "], units are not compatible with meter [" + spacingUnit + "]"); rval = null; @@ -396,6 +374,26 @@ public class MercatorGridCoverage extends GridCoverage { return true; } + public boolean spatialEquals(GridCoverage other) { + if (super.spatialEquals(other)) { + MercatorGridCoverage otherMercator = (MercatorGridCoverage) other; + if (Math.abs(latin - otherMercator.latin) > SPATIAL_TOLERANCE) { + return false; + } + return true; + } + return false; + } + + @Override + public String spatialKey() { + StringBuilder key = new StringBuilder(96); + key.append(super.spatialKey()); + key.append(DataURI.SEPARATOR); + key.append(latin); + return key.toString(); + } + public MercatorGridCoverage() { } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/PolarStereoGridCoverage.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/PolarStereoGridCoverage.java similarity index 82% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/PolarStereoGridCoverage.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/PolarStereoGridCoverage.java index 4c9aecf2a5..e7d61ca83d 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/PolarStereoGridCoverage.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/PolarStereoGridCoverage.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.spatial.projections; +package com.raytheon.uf.common.gridcoverage; import javax.measure.converter.UnitConverter; import javax.measure.unit.SI; @@ -34,11 +34,11 @@ import javax.xml.bind.annotation.XmlRootElement; import org.apache.commons.lang.builder.HashCodeBuilder; import org.opengis.referencing.operation.MathTransform; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.TrimUtil.Trim; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGrid; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef; +import com.raytheon.uf.common.dataplugin.annotations.DataURI; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; +import com.raytheon.uf.common.gridcoverage.subgrid.TrimUtil; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; import com.raytheon.uf.common.status.IUFStatusHandler; @@ -110,23 +110,14 @@ public class PolarStereoGridCoverage extends GridCoverage { } @Override - public void initialize() throws GribException { + public void initialize() throws GridCoverageException { crs = MapUtil.constructNorthPolarStereo(majorAxis, minorAxis, lad, lov); crsWKT = crs.toWKT(); generateGeometry(); - id = generateHash(); - } - - public void generateName() { - String nameAndDescription = "Unknown " + nx + " X " + ny + " " - + Math.round(dx) + " " + spacingUnit + " " - + getProjectionType() + " grid"; - this.setName(nameAndDescription); - this.setDescription(nameAndDescription); } @Override - public GridCoverage trim(SubGridDef subGridDef, SubGrid subGrid) { + public GridCoverage trim(SubGrid subGrid) { PolarStereoGridCoverage rval = new PolarStereoGridCoverage(); rval.description = this.description; rval.dx = this.dx; @@ -135,7 +126,6 @@ public class PolarStereoGridCoverage extends GridCoverage { rval.lov = this.lov; rval.majorAxis = this.majorAxis; rval.minorAxis = this.minorAxis; - rval.setName(this.name + SUBGRID_TOKEN + subGrid.getModelName()); try { Unit spacingUnitObj = Unit.valueOf(spacingUnit); @@ -149,35 +139,25 @@ public class PolarStereoGridCoverage extends GridCoverage { MathTransform toLatLon = fromLatLon.inverse(); // don't check world wrap on a polar stereo grid - Trim trim = null; try { - trim = TrimUtil.trimMeterSpace(getLowerLeftLat(), - getLowerLeftLon(), subGridDef, this.nx, this.ny, + TrimUtil.trimMeterSpace(getLowerLeftLat(), + getLowerLeftLon(), subGrid, this.nx, this.ny, dxMeter, dyMeter, fromLatLon, toLatLon, false); - } catch (GribException e) { - statusHandler.handle(Priority.WARN, "Grib coverage [" + } catch (GridCoverageException e) { + statusHandler.handle(Priority.WARN, "Grid coverage [" + this.getName() + "] not applicable to this site"); return null; } - subGrid.setUpperLeftX(trim.upperLeftX); - subGrid.setUpperLeftY(trim.upperLeftY); - - subGrid.setNX(trim.nx); - subGrid.setNY(trim.ny); - rval.firstGridPointCorner = Corner.LowerLeft; - rval.lo1 = trim.lowerLeftLon; - rval.la1 = trim.lowerLeftLat; - rval.nx = trim.nx; - rval.ny = trim.ny; - - rval.setId(rval.hashCode()); + rval.lo1 = subGrid.getLowerLeftLon(); + rval.la1 = subGrid.getLowerLeftLat(); + rval.nx = subGrid.getNX(); + rval.ny = subGrid.getNY(); + rval.setName(SUBGRID_TOKEN + this.getId()); } else { - statusHandler.handle( - Priority.PROBLEM, - "Error creating sub grid definition [" - + subGrid.getModelName() + statusHandler.handle(Priority.PROBLEM, + "Error creating sub grid definition [" + this.name + "], units are not compatible with meter [" + spacingUnit + "]"); rval = null; @@ -312,6 +292,30 @@ public class PolarStereoGridCoverage extends GridCoverage { return true; } + public boolean spatialEquals(GridCoverage other) { + if (super.spatialEquals(other)) { + PolarStereoGridCoverage otherPolar = (PolarStereoGridCoverage) other; + if (Math.abs(lad - otherPolar.lad) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(lov - otherPolar.lov) > SPATIAL_TOLERANCE) { + return false; + } + return true; + } + return false; + } + + @Override + public String spatialKey() { + StringBuilder key = new StringBuilder(96); + key.append(super.spatialKey()); + key.append(DataURI.SEPARATOR); + key.append(lov); + key.append(DataURI.SEPARATOR); + key.append(lad); + return key.toString(); + } + public PolarStereoGridCoverage() { } diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/StereographicGridCoverage.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/StereographicGridCoverage.java new file mode 100644 index 0000000000..de2303715d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/StereographicGridCoverage.java @@ -0,0 +1,163 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.gridcoverage; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import org.apache.commons.lang.builder.HashCodeBuilder; + +import com.raytheon.uf.common.dataplugin.annotations.DataURI; +import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; +import com.raytheon.uf.common.gridcoverage.subgrid.SubGrid; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; + +/** + * Stereographic Coverage used by radar data. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Apr 7, 2010  #4473     rjpeter     Initial creation
+ * 
+ * 
+ * + * @author rjpeter + * @version 1.0 + */ +@Entity +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class StereographicGridCoverage extends GridCoverage { + private static final long serialVersionUID = -3420227375272208743L; + + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(StereographicGridCoverage.class); + + /** Orientation of the grid */ + @Column + @XmlElement + @DynamicSerializeElement + private double lov; + + @Column + @XmlElement + @DynamicSerializeElement + private double lad; + + public double getLov() { + return lov; + } + + public void setLov(double lov) { + this.lov = lov; + } + + public double getLad() { + return lad; + } + + public void setLad(double lad) { + this.lad = lad; + } + + @Override + public String getProjectionType() { + return "Stereographic"; + } + + @Override + public void initialize() throws GridCoverageException { + crs = MapUtil.constructStereographic(MapUtil.AWIPS_EARTH_RADIUS, + MapUtil.AWIPS_EARTH_RADIUS, lad, lov); + crsWKT = crs.toWKT(); + generateGeometry(); + } + + @Override + public GridCoverage trim(SubGrid subGrid) { + statusHandler + .handle(Priority.ERROR, + "StereographicGridCoverage does not currently support subgridding"); + return null; + } + + @Override + public int generateHash() { + HashCodeBuilder hashBuilder = new HashCodeBuilder(); + hashBuilder.append(super.generateHash()); + hashBuilder.append(lov); + hashBuilder.append(lad); + return hashBuilder.toHashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (!super.equals(obj)) + return false; + if (getClass() != obj.getClass()) + return false; + StereographicGridCoverage other = (StereographicGridCoverage) obj; + if (Double.doubleToLongBits(lad) != Double.doubleToLongBits(other.lad)) + return false; + if (Double.doubleToLongBits(lov) != Double.doubleToLongBits(other.lov)) + return false; + return true; + } + + public boolean spatialEquals(GridCoverage other) { + if (super.spatialEquals(other)) { + StereographicGridCoverage otherStereo = (StereographicGridCoverage) other; + if (Math.abs(lad - otherStereo.lad) > SPATIAL_TOLERANCE) { + return false; + } else if (Math.abs(lov - otherStereo.lov) > SPATIAL_TOLERANCE) { + return false; + } + return true; + } + return false; + } + + @Override + public String spatialKey() { + StringBuilder key = new StringBuilder(96); + key.append(super.spatialKey()); + key.append(DataURI.SEPARATOR); + key.append(lov); + key.append(DataURI.SEPARATOR); + key.append(lad); + return key.toString(); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/convert/GridCoverageConverter.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/convert/GridCoverageConverter.java new file mode 100644 index 0000000000..a57be67ec4 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/convert/GridCoverageConverter.java @@ -0,0 +1,76 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.gridcoverage.convert; + +import org.apache.commons.beanutils.ConversionException; +import org.apache.commons.beanutils.Converter; + +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup; + +/** + * Convert an integer or a string representing a grid coverage id to a grid + * coverage using the GridCoverageLookup. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 12, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridCoverageConverter implements Converter { + + @Override + @SuppressWarnings("rawtypes") + public GridCoverage convert(Class clazz, Object value) { + Integer intValue = null; + if (value instanceof Integer) { + intValue = (Integer) value; + } else if (value instanceof String) { + try { + intValue = Integer.parseInt((String) value); + } catch (NumberFormatException e) { + ;// ignore and throw conversion exception later. + } + } + if (intValue != null) { + GridCoverage result = GridCoverageLookup.getInstance().getCoverage( + intValue); + if (result != null) { + return result; + } + throw new ConversionException( + "Cannot find GridCoverage with id of " + + String.valueOf(intValue)); + } + throw new ConversionException("Cannot convert " + String.valueOf(value) + + " of type " + value.getClass().getSimpleName() + + " to a GridCoverage."); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/exception/GridCoverageException.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/exception/GridCoverageException.java new file mode 100644 index 0000000000..dde4b0bd3f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/exception/GridCoverageException.java @@ -0,0 +1,71 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ + +package com.raytheon.uf.common.gridcoverage.exception; + +import com.raytheon.uf.common.dataplugin.PluginException; + +/** + * + * An exception that occurs when there are errors intializing grid coverages. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jan 31, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class GridCoverageException extends PluginException { + + /** + * Default serial version id + */ + private static final long serialVersionUID = 1L; + + /** + * Parser exception set with a cause. + * + * @param aCause + * The cause of the exception + */ + public GridCoverageException(String aCause) { + super(aCause); + } + + /** + * Parser exception set with a cause and an existing exception. Used for + * exception chaining to preserve state. + * + * @param aCause + * The cause of the exception + * @param anException + * The exception object + */ + public GridCoverageException(String aCause, Exception anException) { + super(aCause, anException); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageLookup.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageLookup.java new file mode 100644 index 0000000000..5e5e11e89d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageLookup.java @@ -0,0 +1,195 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.gridcoverage.lookup; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +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.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.request.GetGridCoverageRequest; +import com.raytheon.uf.common.serialization.comm.RequestRouter; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; + +/** + * Caching and convenience for finding coverages in the Database. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 12, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridCoverageLookup { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GridCoverageLookup.class); + + private static GridCoverageLookup instance; + + public static GridCoverageLookup getInstance() { + if (instance == null) { + instance = new GridCoverageLookup(); + } + return instance; + } + + // Maps id to coverage, this is a mirror of what is in the database. + private Map idToCoverage; + + private Map coverageToId; + + private GridCoverageLookup() { + initializeMaps(); + DbQueryRequest query = new DbQueryRequest(); + query.setEntityClass(GridCoverage.class.getName()); + try { + DbQueryResponse resp = (DbQueryResponse) RequestRouter.route(query); + for (Map map : resp.getResults()) { + GridCoverage coverage = (GridCoverage) map.get(null); + coverageToId.put(coverage, coverage.getId()); + idToCoverage.put(coverage.getId(), coverage); + } + } catch (Exception e) { + // do not rethrow, the lookup is not broken at this point so if the + // problems persist then more exceptions will come from the actual + // lookup methods themselves. + statusHandler.handle(Priority.PROBLEM, + "Error occurred retrieving coverages from server.", e); + } + } + + private void initializeMaps() { + idToCoverage = Collections + .synchronizedMap(new HashMap()); + coverageToId = Collections + .synchronizedMap(new GridCoverageSpatialMap()); + } + + public GridCoverage getCoverage(int id) throws GridCoverageLookupException { + GridCoverage result = idToCoverage.get(id); + if (result != null) { + return result; + } + HashMap constraints = new HashMap(); + constraints.put("id", new RequestConstraint(Integer.toString(id))); + DbQueryRequest query = new DbQueryRequest(); + query.setConstraints(constraints); + query.setEntityClass(GridCoverage.class.getName()); + try { + DbQueryResponse resp = (DbQueryResponse) RequestRouter.route(query); + if (!resp.getResults().isEmpty()) { + result = (GridCoverage) resp.getResults().get(0).get(null); + if (result != null) { + coverageToId.put(result, result.getId()); + idToCoverage.put(result.getId(), result); + } + return result; + } + } catch (Exception e) { + throw new GridCoverageLookupException( + "Error occurred retrieving GridCoverage information from server.", + e); + } + return null; + } + + /** + * bulk request multiple coverages by id, for any coverages not in the cache + * this can be significantly faster than requesting multiple coverages + * individually. + * + * @param ids + * @return + */ + public Map getCoverages(List ids) + throws GridCoverageLookupException { + RequestConstraint idConstraint = new RequestConstraint(null, + ConstraintType.IN); + Map result = new HashMap( + ids.size()); + for (Integer id : ids) { + GridCoverage cov = idToCoverage.get(id); + if (cov == null) { + idConstraint.addToConstraintValueList(id.toString()); + } + result.put(id, cov); + } + if (idConstraint.getConstraintValue() == null) { + // everything was a cache hit. + return result; + } + HashMap constraints = new HashMap(); + constraints.put("id", idConstraint); + DbQueryRequest query = new DbQueryRequest(); + query.setConstraints(constraints); + query.setEntityClass(GridCoverage.class.getName()); + try { + DbQueryResponse resp = (DbQueryResponse) RequestRouter.route(query); + for (Map thing : resp.getResults()) { + GridCoverage respCov = (GridCoverage) thing.get(null); + coverageToId.put(respCov, respCov.getId()); + idToCoverage.put(respCov.getId(), respCov); + result.put(respCov.getId(), respCov); + } + } catch (Exception e) { + throw new GridCoverageLookupException( + "Error occurred retrieving GridCoverage information from server.", + e); + } + return result; + } + + public GridCoverage getCoverage(GridCoverage coverage, boolean create) + throws GridCoverageLookupException { + Integer id = coverageToId.get(coverage); + if (id != null) { + return getCoverage(id); + } + try { + GridCoverage result = (GridCoverage) RequestRouter + .route(new GetGridCoverageRequest(coverage, create)); + if (result != null) { + coverageToId.put(result, result.getId()); + idToCoverage.put(result.getId(), result); + } + return result; + } catch (Exception e) { + throw new GridCoverageLookupException( + "Error occurred retrieving GridCoverage information from server.", + e); + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageLookupException.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageLookupException.java new file mode 100644 index 0000000000..4103366f6c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageLookupException.java @@ -0,0 +1,50 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.gridcoverage.lookup; + +/** + * Exception is thrown when GridCoverageLookup cannot execute IServerRequest + * using the RequestRouter. This is a RuntimeException because code that uses + * the GridCoverageLookup cannot reasonably be expected to recover from + * connection failure. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 1, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridCoverageLookupException extends RuntimeException { + + private static final long serialVersionUID = 1145174965583445888L; + + public GridCoverageLookupException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageSpatialMap.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageSpatialMap.java new file mode 100644 index 0000000000..b43e5461c1 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/lookup/GridCoverageSpatialMap.java @@ -0,0 +1,201 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.gridcoverage.lookup; + +import java.lang.ref.ReferenceQueue; +import java.lang.ref.SoftReference; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.lang.builder.HashCodeBuilder; + +import com.raytheon.uf.common.gridcoverage.GridCoverage; + +/** + * A map for GridCoverages that does not require them to be completely equal but + * instead uses the spatialEquals, also uses softreferences to coverages, so + * entries may dissappear if memory is needed. + * + * This map is not thread safe and must be externally synchronized. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 7, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridCoverageSpatialMap implements Map { + + private static class GridCoverageSpatialKey extends + SoftReference { + + private final int hash; + + public GridCoverageSpatialKey(GridCoverage coverage, + ReferenceQueue q) { + super(coverage, q); + HashCodeBuilder hashBuilder = new HashCodeBuilder(); + hashBuilder.append(coverage.getProjectionType()); + hashBuilder.append(coverage.getNx()); + hashBuilder.append(coverage.getNy()); + // this hash is not very unique and will lead to a fairly large + // number of collisions under some circumstances, the hashmap should + // be able to handle these collisions so there won't be errors and + // hopefully the performance loss due to bad hashing is negligible, + // but this may require further testing. + hash = hashBuilder.toHashCode(); + } + + @Override + public int hashCode() { + return hash; + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } else if (obj instanceof GridCoverageSpatialKey) { + GridCoverage thisCoverage = this.get(); + GridCoverage otherCoverage = ((GridCoverageSpatialKey) obj) + .get(); + return thisCoverage != null && otherCoverage != null + && thisCoverage.spatialEquals(otherCoverage); + } + return false; + } + + } + + private Map internalMap = new HashMap(); + + private ReferenceQueue refQueue = new ReferenceQueue(); + + @Override + public int size() { + clearStaleReferences(); + return internalMap.size(); + } + + @Override + public boolean isEmpty() { + clearStaleReferences(); + return internalMap.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return get(key) != null; + } + + @Override + public boolean containsValue(Object value) { + clearStaleReferences(); + return internalMap.containsValue(value); + } + + @Override + public Integer get(Object key) { + if (!(key instanceof GridCoverage)) { + return null; + } + clearStaleReferences(); + GridCoverageSpatialKey coverageKey = new GridCoverageSpatialKey( + (GridCoverage) key, null); + return internalMap.get(coverageKey); + } + + @Override + public Integer put(GridCoverage key, Integer value) { + clearStaleReferences(); + GridCoverageSpatialKey coverageKey = new GridCoverageSpatialKey(key, + refQueue); + return internalMap.put(coverageKey, value); + } + + @Override + public Integer remove(Object key) { + if (!(key instanceof GridCoverage)) { + return null; + } + clearStaleReferences(); + GridCoverageSpatialKey coverageKey = new GridCoverageSpatialKey( + (GridCoverage) key, null); + return internalMap.remove(coverageKey); + } + + @Override + public void putAll(Map m) { + for (Entry entry : m + .entrySet()) { + this.put(entry.getKey(), entry.getValue()); + } + } + + @Override + public void clear() { + internalMap.clear(); + } + + /** + * this method is not implemented + */ + @Override + public Set keySet() { + // TODO in order to fully comply with the map API this method should be + // implemented + return null; + } + + @Override + public Collection values() { + clearStaleReferences(); + return internalMap.values(); + } + + /** + * this method is not implemented + */ + @Override + public Set> entrySet() { + // TODO in order to fully comply with the map API this method should be + // implemented + return null; + } + + private void clearStaleReferences() { + GridCoverageSpatialKey key = (GridCoverageSpatialKey) refQueue.poll(); + while (key != null) { + internalMap.remove(key); + key = (GridCoverageSpatialKey) refQueue.poll(); + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/request/GetGridCoverageRequest.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/request/GetGridCoverageRequest.java new file mode 100644 index 0000000000..72ad388e37 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/request/GetGridCoverageRequest.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.gridcoverage.request; + +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.serialization.comm.IServerRequest; + +/** + * Request to lookup a grid coverage that is spatially equivelant to the + * provided coverage, also provides option for creating the coverage in the + * database if it does not already exist. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 26, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@DynamicSerialize +public class GetGridCoverageRequest implements IServerRequest { + + @DynamicSerializeElement + private GridCoverage coverage; + + @DynamicSerializeElement + private boolean create = false; + + public GetGridCoverageRequest() { + } + + public GetGridCoverageRequest(GridCoverage coverage) { + this.coverage = coverage; + this.create = false; + } + + public GetGridCoverageRequest(GridCoverage coverage, boolean create) { + this.coverage = coverage; + this.create = create; + } + + public GridCoverage getCoverage() { + return coverage; + } + + public void setCoverage(GridCoverage coverage) { + this.coverage = coverage; + } + + public boolean getCreate() { + return create; + } + + public void setCreate(boolean create) { + this.create = create; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/subgrid/SubGrid.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/subgrid/SubGrid.java similarity index 63% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/subgrid/SubGrid.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/subgrid/SubGrid.java index 7059ae730a..24521cb9a4 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/subgrid/SubGrid.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/subgrid/SubGrid.java @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.subgrid; +package com.raytheon.uf.common.gridcoverage.subgrid; /** * A sub grid definition @@ -35,6 +35,7 @@ package com.raytheon.uf.common.dataplugin.grib.subgrid; * @version 1.0 */ public class SubGrid { + /** The model name */ private String modelName; @@ -50,13 +51,17 @@ public class SubGrid { /** the height of the sub grid */ private int nY; - public String getModelName() { - return modelName; - } + /** lower left latitude of the subgrid area */ + private double lowerLeftLat; - public void setModelName(String modelName) { - this.modelName = modelName; - } + /** lower left longitude of the subgrid area */ + private double lowerLeftLon; + + /** upper right latitude of the subgrid area */ + private double upperRightLat; + + /** upper right longitude of the subgrid area */ + private double upperRightLon; public int getUpperLeftX() { return upperLeftX; @@ -89,4 +94,52 @@ public class SubGrid { public void setNY(int ny) { nY = ny; } + + public double getLowerLeftLat() { + return lowerLeftLat; + } + + public void setLowerLeftLat(double lowerLeftLat) { + this.lowerLeftLat = lowerLeftLat; + } + + public double getLowerLeftLon() { + return lowerLeftLon; + } + + public void setLowerLeftLon(double lowerLeftLon) { + this.lowerLeftLon = lowerLeftLon; + } + + public double getUpperRightLat() { + return upperRightLat; + } + + public void setUpperRightLat(double upperRightLat) { + this.upperRightLat = upperRightLat; + } + + public double getUpperRightLon() { + return upperRightLon; + } + + public void setUpperRightLon(double upperRightLon) { + this.upperRightLon = upperRightLon; + } + + /** + * @return the modelName + */ + public String getModelName() { + return modelName; + } + + /** + * @param modelName + * the modelName to set + */ + public void setModelName(String modelName) { + this.modelName = modelName; + } + } \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/TrimUtil.java b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/subgrid/TrimUtil.java similarity index 74% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/TrimUtil.java rename to edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/subgrid/TrimUtil.java index b9506f1078..fa1bab8dcd 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/spatial/projections/TrimUtil.java +++ b/edexOsgi/com.raytheon.uf.common.gridcoverage/src/com/raytheon/uf/common/gridcoverage/subgrid/TrimUtil.java @@ -17,16 +17,15 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.spatial.projections; +package com.raytheon.uf.common.gridcoverage.subgrid; import org.opengis.referencing.operation.MathTransform; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.subgrid.SubGridDef; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.exception.GridCoverageException; /** - * TODO Add Description + * Provides utility methods for trimming grids into subgrids. * *
  * 
@@ -42,29 +41,28 @@ import com.raytheon.uf.common.geospatial.MapUtil;
  */
 
 public class TrimUtil {
-    static class Trim {
-        public int nx;
 
-        public int ny;
-
-        public double lowerLeftLat;
-
-        public double lowerLeftLon;
-
-        public double upperRightLat;
-
-        public double upperRightLon;
-
-        public int upperLeftX;
-
-        public int upperLeftY;
-    }
-
-    public static Trim trimMeterSpace(double parentLLLat, double parentLLLon,
-            SubGridDef subGrid, int nx, int ny, double dxMeter, double dyMeter,
+    /**
+     * Uses the lat/lon values in subGrid to calculate a valid overlapping area
+     * to the parent grid and then sets the nx,ny and the lower Left x and y in
+     * the subgrid object.
+     * 
+     * @param parentLLLat
+     * @param parentLLLon
+     * @param subGrid
+     * @param nx
+     * @param ny
+     * @param dxMeter
+     * @param dyMeter
+     * @param fromLatLon
+     * @param toLatLon
+     * @param checkGridWrap
+     * @throws Exception
+     */
+    public static void trimMeterSpace(double parentLLLat, double parentLLLon,
+            SubGrid subGrid, int nx, int ny, double dxMeter, double dyMeter,
             MathTransform fromLatLon, MathTransform toLatLon,
             boolean checkGridWrap) throws Exception {
-        Trim rval = new Trim();
         double[] lonLats = new double[8];
         double[] lonLatsInMeters = new double[8];
         lonLats[0] = parentLLLon;
@@ -115,7 +113,7 @@ public class TrimUtil {
                 lonLatsInMeters[6] = lonLatsInMeters[2];
             }
             if (lonLatsInMeters[6] < lonLatsInMeters[4]) {
-                throw new GribException(
+                throw new GridCoverageException(
                         "Model does not contain area defined by sub grid.");
             }
         }
@@ -134,40 +132,53 @@ public class TrimUtil {
         lonLatsInMeters[5] = lonLatsInMeters[1] + (ny - lowerY) * dyMeter;
 
         // determine number points, round down to be inside sub grid, inclusive
-        rval.nx = (int) ((lonLatsInMeters[6] - lonLatsInMeters[4]) / dxMeter) + 1;
-        rval.ny = (int) ((lonLatsInMeters[7] - lonLatsInMeters[5]) / dyMeter) + 1;
+        subGrid.setNX((int) ((lonLatsInMeters[6] - lonLatsInMeters[4]) / dxMeter) + 1);
+        subGrid.setNY((int) ((lonLatsInMeters[7] - lonLatsInMeters[5]) / dyMeter) + 1);
 
         // just double check possible rounding error, in case of using
         // subgridding to shift a world wide grid
-        if (rval.nx > nx) {
-            rval.nx = nx;
+        if (subGrid.getNX() > nx) {
+            subGrid.setNX(nx);
         }
-        if (rval.ny > ny) {
-            rval.ny = ny;
+        if (subGrid.getNY() > ny) {
+            subGrid.setNY(ny);
         }
 
         // sub gridding needs the upper left x/y to pull out the data
         // X/Y is 0/0 at UR and NX/NY at LL
-        rval.upperLeftX = leftX;
-        rval.upperLeftY = lowerY - rval.ny;
+        subGrid.setUpperLeftX(leftX);
+        subGrid.setUpperLeftY(lowerY - subGrid.getNY());
 
         // determine exact UR in meter
-        lonLatsInMeters[6] = lonLatsInMeters[4] + (rval.nx - 1) * dxMeter;
-        lonLatsInMeters[7] = lonLatsInMeters[5] + (rval.ny - 1) * dyMeter;
+        lonLatsInMeters[6] = lonLatsInMeters[4] + (subGrid.getNX() - 1)
+                * dxMeter;
+        lonLatsInMeters[7] = lonLatsInMeters[5] + (subGrid.getNY() - 1)
+                * dyMeter;
 
         toLatLon.transform(lonLatsInMeters, 4, lonLats, 4, 1);
-        rval.lowerLeftLon = MapUtil.correctLon(lonLats[4]);
-        rval.lowerLeftLat = MapUtil.correctLat(lonLats[5]);
-        rval.upperRightLon = MapUtil.correctLon(lonLats[6]);
-        rval.upperRightLat = MapUtil.correctLat(lonLats[7]);
-
-        return rval;
+        subGrid.setLowerLeftLon(MapUtil.correctLon(lonLats[4]));
+        subGrid.setLowerLeftLat(MapUtil.correctLat(lonLats[5]));
+        subGrid.setUpperRightLon(MapUtil.correctLon(lonLats[6]));
+        subGrid.setUpperRightLat(MapUtil.correctLat(lonLats[7]));
     }
 
-    public static Trim trimLatLonSpace(double parentLLLat, double parentLLLon,
-            SubGridDef subGrid, int nx, int ny, double dx, double dy)
+    /**
+     * Uses the lat/lon values in subGrid to calculate a valid overlapping area
+     * to the parent grid and then sets the nx,ny and the lower Left x and y in
+     * the subgrid object.
+     * 
+     * @param parentLLLat
+     * @param parentLLLon
+     *            * @param subGrid
+     * @param nx
+     * @param ny
+     * @param dx
+     * @param dy
+     * @throws Exception
+     */
+    public static void trimLatLonSpace(double parentLLLat, double parentLLLon,
+            SubGrid subGrid, int nx, int ny, double dx, double dy)
             throws Exception {
-        Trim rval = new Trim();
 
         double lonLats[] = new double[8];
         lonLats[0] = parentLLLon;
@@ -217,37 +228,35 @@ public class TrimUtil {
         lonLats[5] = lonLats[1] + (ny - lowerY) * dy;
 
         // determine number points, round up and inclusive
-        rval.nx = (int) ((lonLats[6] - lonLats[4]) / dx + 0.5) + 1;
-        rval.ny = (int) ((lonLats[7] - lonLats[5]) / dy + 0.5) + 1;
+        subGrid.setNX((int) ((lonLats[6] - lonLats[4]) / dx + 0.5) + 1);
+        subGrid.setNY((int) ((lonLats[7] - lonLats[5]) / dy + 0.5) + 1);
 
         // just double check possible rounding error, in case of using
         // subgridding to shift a world wide grid
-        if (rval.nx > nx) {
-            rval.nx = nx;
+        if (subGrid.getNX() > nx) {
+            subGrid.setNX(nx);
         }
-        if (rval.ny > ny) {
-            rval.ny = ny;
+        if (subGrid.getNY() > ny) {
+            subGrid.setNY(ny);
         }
 
         // sub gridding needs the upper left x/y to pull out the data
         // X/Y is 0/0 at UR and NX/NY at LL
-        rval.upperLeftX = leftX;
-        rval.upperLeftY = lowerY - rval.ny;
+        subGrid.setUpperLeftX(leftX);
+        subGrid.setUpperLeftY(lowerY - subGrid.getNY());
 
         // determine exact UR
-        lonLats[6] = lonLats[4] + (rval.nx - 1) * dx;
-        lonLats[7] = lonLats[5] + (rval.ny - 1) * dy;
+        lonLats[6] = lonLats[4] + (subGrid.getNX() - 1) * dx;
+        lonLats[7] = lonLats[5] + (subGrid.getNY() - 1) * dy;
 
-        rval.lowerLeftLon = MapUtil.correctLon(lonLats[4]);
-        rval.lowerLeftLat = MapUtil.correctLat(lonLats[5]);
-        rval.upperRightLon = MapUtil.correctLon(lonLats[6]);
-        rval.upperRightLat = MapUtil.correctLat(lonLats[7]);
-
-        return rval;
+        subGrid.setLowerLeftLon(MapUtil.correctLon(lonLats[4]));
+        subGrid.setLowerLeftLat(MapUtil.correctLat(lonLats[5]));
+        subGrid.setUpperRightLon(MapUtil.correctLon(lonLats[6]));
+        subGrid.setUpperRightLat(MapUtil.correctLat(lonLats[7]));
     }
 
     private static void validateLongitudes(double lonLats[])
-            throws GribException {
+            throws GridCoverageException {
         // check > 180 and wrap back around
         if (lonLats[2] > 180) {
             lonLats[2] -= 360;
@@ -282,7 +291,7 @@ public class TrimUtil {
                     // verify LL is before UR of parent
                     if (lonLats[4] > lonLats[2]) {
                         // invalid grid
-                        throw new GribException(
+                        throw new GridCoverageException(
                                 "Model does not contain area defined by sub grid.");
                     }
 
@@ -302,7 +311,7 @@ public class TrimUtil {
                     // verify UR is after LL of parent
                     if (lonLats[6] < lonLats[0]) {
                         // invalid grid
-                        throw new GribException(
+                        throw new GridCoverageException(
                                 "Model does not contain area defined by sub grid.");
                     }
 
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileLocker.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileLocker.java
index 1302354e9f..5cc0038443 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileLocker.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileLocker.java
@@ -78,6 +78,8 @@ public class FileLocker {
         READ, WRITE
     }
 
+    private static final int MAX_WAIT = 30 * 1000;
+
     /** Map of waiters on threads */
     private Map> waiters = new HashMap>();
 
@@ -215,7 +217,7 @@ public class FileLocker {
                 while (true) {
                     // Sleep
                     try {
-                        Thread.sleep(1);
+                        Thread.sleep(10);
                     } catch (InterruptedException e) {
                         // Ignore
                     }
@@ -231,6 +233,20 @@ public class FileLocker {
                                             false);
                                 }
                             }
+                        } else {
+                            synchronized (lock) {
+                                if (lock.lockFile.exists() == false
+                                        || (System.currentTimeMillis()
+                                                - lock.lockFile.lastModified() > MAX_WAIT)) {
+                                    System.err
+                                            .println("Releasing lock since: "
+                                                    + (lock.lockFile.exists() ? "Lock has been allocated for more than "
+                                                            + (MAX_WAIT / 1000)
+                                                            + "s"
+                                                            : "Lock file no longer exists!"));
+                                    locks.remove(file);
+                                }
+                            }
                         }
                     }
                 }
@@ -317,7 +333,6 @@ public class FileLocker {
         File lockFile = new File(parentDir, "." + file.getName() + "_LOCK");
         boolean gotLock = lockFile.createNewFile();
         if (!gotLock) {
-            long MAX_WAIT = 30 * 1000;
             long waitInterval = 500;
             long tryCount = MAX_WAIT / waitInterval;
             for (int i = 0; !gotLock && i < tryCount; ++i) {
@@ -333,6 +348,7 @@ public class FileLocker {
         if (!gotLock) {
             System.err.println("Failed to obtain lock for: " + file
                     + ", returning anyway");
+            Thread.dumpStack();
         }
         lock.lockFile = lockFile;
         return lock;
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileUpdatedMessage.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileUpdatedMessage.java
index 84acdedba2..c64e510a82 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileUpdatedMessage.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/FileUpdatedMessage.java
@@ -63,14 +63,19 @@ public class FileUpdatedMessage implements ISerializableObject {
     @XmlElement
     private FileChangeType changeType;
 
+    @DynamicSerializeElement
+    @XmlAttribute
+    private long timeStamp;
+
     public FileUpdatedMessage() {
     }
 
     public FileUpdatedMessage(LocalizationContext context, String fileName,
-            FileChangeType changeType) {
+            FileChangeType changeType, long timeStamp) {
         this.context = context;
         this.fileName = fileName;
         this.changeType = changeType;
+        this.timeStamp = timeStamp;
     }
 
     public LocalizationContext getContext() {
@@ -96,4 +101,20 @@ public class FileUpdatedMessage implements ISerializableObject {
     public void setChangeType(FileChangeType changeType) {
         this.changeType = changeType;
     }
+
+    /**
+     * @return the timeStamp
+     */
+    public long getTimeStamp() {
+        return timeStamp;
+    }
+
+    /**
+     * @param timeStamp
+     *            the timeStamp to set
+     */
+    public void setTimeStamp(long timeStamp) {
+        this.timeStamp = timeStamp;
+    }
+
 }
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/ILocalizationAdapter.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/ILocalizationAdapter.java
index afd2678256..99f3407298 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/ILocalizationAdapter.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/ILocalizationAdapter.java
@@ -25,6 +25,7 @@ import java.util.Date;
 
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
+import com.raytheon.uf.common.localization.LocalizationFile.ModifiableLocalizationFile;
 import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException;
 
 /**
@@ -44,19 +45,6 @@ import com.raytheon.uf.common.localization.exception.LocalizationOpFailedExcepti
  */
 public interface ILocalizationAdapter {
 
-    /**
-     * Retrieves the directory name for the given localization type.
-     * 
-     * @param type
-     *            the localization type
-     * @return the directory name of the directory where the localization type
-     *         should be stored. The returned string is the directory name only,
-     *         NOT the fully qualified path.
-     * 
-     * @see #getPath(LocalizationContext, String)
-     */
-    public abstract String getDirNameForType(LocalizationType type);
-
     /**
      * Return the fully qualified path given a localization context and a file
      * name
@@ -93,19 +81,14 @@ public interface ILocalizationAdapter {
             throws LocalizationOpFailedException;
 
     /**
-     * Save a file given it's local pointer, a localization context and a file
-     * name
+     * Save a file a modifiable localization file
      * 
-     * @param localFile
-     *            the local file pointer
-     * @param context
-     *            the localization context
-     * @param fileName
-     *            the file name
+     * @param file
+     *            the modifiable localization file
      * @throws LocalizationOpFailedException
      */
-    public abstract boolean save(File localFile, LocalizationContext context,
-            String fileName) throws LocalizationOpFailedException;
+    public abstract boolean save(ModifiableLocalizationFile file)
+            throws LocalizationOpFailedException;
 
     /**
      * List a directory given a set of contexts and a path.
@@ -162,18 +145,14 @@ public interface ILocalizationAdapter {
             LocalizationLevel level);
 
     /**
-     * Delete a file given a local file pointer, context and filename
+     * Delete a file given a modifiable localization file
      * 
      * @param file
-     *            the file pointer
-     * @param context
-     *            the localization context
-     * @param fileName
-     *            the name of the file on the server
+     *            the modifiable localization file
      * @throws LocalizationOpFailedException
      */
-    public abstract boolean delete(File file, LocalizationContext context,
-            String fileName) throws LocalizationOpFailedException;
+    public abstract boolean delete(ModifiableLocalizationFile file)
+            throws LocalizationOpFailedException;
 
     public abstract String[] getContextList(LocalizationLevel level)
             throws LocalizationOpFailedException;
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/IPathManager.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/IPathManager.java
index 544546fa33..1c0516e85f 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/IPathManager.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/IPathManager.java
@@ -27,7 +27,10 @@ import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType;
 
 /**
- * A generalized interface for constructing LocalizationFiles.
+ * A generalized interface for constructing LocalizationFiles. NOTE: There will
+ * only exist a single reference to any LocalizationFile. It is the
+ * IPathManager's responsibility to ensure multiple objects of the same
+ * LocalizationFile are not returned
  * 
  * Note: Paths should use IPathManager.SEPARATOR as the separator for
  * consistency. The client OS could potentially differ from the localization
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFile.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFile.java
index 6ae591bc64..811ccdc6f1 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFile.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFile.java
@@ -23,17 +23,18 @@ import java.io.File;
 import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
-import java.io.OutputStream;
 import java.util.ArrayList;
 import java.util.Date;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 
+import com.raytheon.uf.common.localization.FileLocker.Type;
 import com.raytheon.uf.common.localization.ILocalizationAdapter.ListResponse;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
 import com.raytheon.uf.common.localization.exception.LocalizationException;
 import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException;
+import com.raytheon.uf.common.serialization.JAXBManager;
 import com.raytheon.uf.common.status.IUFStatusHandler;
 import com.raytheon.uf.common.status.UFStatus;
 import com.raytheon.uf.common.status.UFStatus.Priority;
@@ -85,12 +86,60 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
  * @version 1.0
  */
 
-public class LocalizationFile implements Comparable {
+public final class LocalizationFile implements Comparable {
     private static transient IUFStatusHandler statusHandler = UFStatus
             .getHandler(LocalizationFile.class);
 
+    /**
+     * Class {@link LocalizationFile} exposes to the
+     * {@link ILocalizationAdapter} objects so they can modify the file if
+     * anything changes. Don't want to expose ability to modify
+     * {@link LocalizationFile} contents to everyone
+     * 
+     * @author mschenke
+     * @version 1.0
+     */
+    public class ModifiableLocalizationFile {
+
+        private ModifiableLocalizationFile() {
+            // Private constructor
+        }
+
+        public LocalizationFile getLocalizationFile() {
+            return LocalizationFile.this;
+        }
+
+        public void setTimeStamp(Date timeStamp) {
+            getLocalizationFile().fileTimestamp = timeStamp;
+        }
+
+        public void setFileChecksum(String checksum) {
+            getLocalizationFile().fileCheckSum = checksum;
+        }
+
+        public void setIsAvailableOnServer(boolean isAvailableOnServer) {
+            getLocalizationFile().isAvailableOnServer = isAvailableOnServer;
+        }
+
+        public void setIsDirectory(boolean isDirectory) {
+            getLocalizationFile().isDirectory = isDirectory;
+        }
+
+        public File getLocalFile() {
+            return getLocalizationFile().file;
+        }
+
+        public String getFileName() {
+            return getLocalizationFile().path;
+        }
+
+        public LocalizationContext getContext() {
+            return getLocalizationFile().context;
+        }
+    }
+
     /** Local file pointer to localization file, will never be null */
-    private File file;
+    protected final File file;
 
     /** The file timestamp on the server, may be null if file doesn't exist yet */
     private Date fileTimestamp;
@@ -108,7 +157,7 @@ public class LocalizationFile implements Comparable {
     private boolean isAvailableOnServer;
 
     /** The localization adapter for the file */
-    final ILocalizationAdapter adapter;
+    protected final ILocalizationAdapter adapter;
 
     /** The localization path of the file */
     private final String path;
@@ -117,16 +166,17 @@ public class LocalizationFile implements Comparable {
     private LocalizationLevel protectedLevel;
 
     /** File changed observers */
-    private Set observers = new HashSet();
+    private final Set observers = new HashSet();
 
     /** Flag to set if file has been requested */
-    boolean fileRequested = false;
+    protected boolean fileRequested = false;
 
     /**
      * Construct a null localization file, used to keep track of files that
      * cannot exist.
      */
     LocalizationFile() {
+        file = null;
         path = null;
         adapter = null;
         context = null;
@@ -138,7 +188,8 @@ public class LocalizationFile implements Comparable {
      * @return
      */
     boolean isNull() {
-        return adapter == null && path == null && context == null;
+        return (adapter == null) && (path == null) && (context == null)
+                && (file == null);
     }
 
     LocalizationFile(ILocalizationAdapter adapter, LocalizationContext context,
@@ -173,6 +224,16 @@ public class LocalizationFile implements Comparable {
         }
     }
 
+    /**
+     * Returns a modifiable version of the localization file. Meant to be used
+     * internally within localization only which is why package level
+     * 
+     * @return
+     */
+    ModifiableLocalizationFile getModifiableFile() {
+        return new ModifiableLocalizationFile();
+    }
+
     /**
      * This returns the time stamp of the file where it is stored, not the local
      * version of the file
@@ -219,13 +280,14 @@ public class LocalizationFile implements Comparable {
             adapter.retrieve(this);
         }
 
-        if (isDirectory == false && !file.exists()) {
+        if ((isDirectory == false) && !file.exists()) {
             try {
                 file.getParentFile().mkdirs();
             } catch (Throwable t) {
-                // try to create the file's directory automatically, but if it
-                // fails, don't report it as it is just something to do to help
-                // the user of the file for easier creation of the file
+                // try to create the file's directory automatically, but if
+                // it fails, don't report it as it is just something to do
+                // to help the user of the file for easier creation of the
+                // file
             }
         }
 
@@ -255,7 +317,8 @@ public class LocalizationFile implements Comparable {
      * @return the InputStream to be used for reading the file
      * @throws LocalizationException
      */
-    public InputStream openInputStream() throws LocalizationException {
+    public LocalizationFileInputStream openInputStream()
+            throws LocalizationException {
         try {
             return new LocalizationFileInputStream(this);
         } catch (FileNotFoundException e) {
@@ -290,8 +353,8 @@ public class LocalizationFile implements Comparable {
             // Read in the bytes
             int offset = 0;
             int numRead = 0;
-            while (offset < rval.length
-                    && (numRead = is.read(rval, offset, rval.length - offset)) >= 0) {
+            while ((offset < rval.length)
+                    && ((numRead = is.read(rval, offset, rval.length - offset)) >= 0)) {
                 offset += numRead;
             }
 
@@ -324,7 +387,8 @@ public class LocalizationFile implements Comparable {
      * @return the OutputStream to be used for writing to the file
      * @throws LocalizationException
      */
-    public OutputStream openOutputStream() throws LocalizationException {
+    public LocalizationFileOutputStream openOutputStream()
+            throws LocalizationException {
         return openOutputStream(false);
     }
 
@@ -335,7 +399,7 @@ public class LocalizationFile implements Comparable {
      * @return the OutputStream to be used for writing to the file
      * @throws LocalizationException
      */
-    public OutputStream openOutputStream(boolean isAppending)
+    public LocalizationFileOutputStream openOutputStream(boolean isAppending)
             throws LocalizationException {
         try {
             return new LocalizationFileOutputStream(this, isAppending);
@@ -352,23 +416,20 @@ public class LocalizationFile implements Comparable {
      * @throws LocalizationException
      */
     public void write(byte[] bytes) throws LocalizationException {
-        OutputStream os = null;
+        LocalizationFileOutputStream os = null;
         try {
             os = openOutputStream();
             os.write(bytes);
-            save();
         } catch (IOException e) {
             throw new LocalizationException("Could not write to file "
                     + file.getName(), e);
         } finally {
             if (os != null) {
                 try {
-                    os.close();
+                    os.closeAndSave();
                 } catch (IOException e) {
-                    statusHandler
-                            .handle(Priority.INFO,
-                                    "Failed to close output stream to area geometries file",
-                                    e);
+                    statusHandler.handle(Priority.INFO,
+                            "Failed to close output stream for file", e);
                 }
             }
         }
@@ -426,23 +487,28 @@ public class LocalizationFile implements Comparable {
      * @throws LocalizationOpFailedException
      */
     public boolean save() throws LocalizationOpFailedException {
-        String checksum = "";
         try {
-            checksum = Checksum.getMD5Checksum(file);
-        } catch (Exception e) {
-            // Ignore
-        }
-        // Check if file differs from server file
-        if (!checksum.equals(fileCheckSum)) {
-            boolean rval = adapter.save(file, context, path);
-            if (rval) {
-                fileCheckSum = checksum;
+            FileLocker.lock(this, file, Type.WRITE);
+            String checksum = "";
+            try {
+                checksum = Checksum.getMD5Checksum(file);
+            } catch (Exception e) {
+                // Ignore
+            }
+            // Check if file differs from server file
+            if (!checksum.equals(fileCheckSum)) {
+                boolean rval = adapter.save(getModifiableFile());
+                if (rval) {
+                    fileCheckSum = checksum;
+                }
+                return rval;
             }
-            return rval;
-        }
 
-        // Local file matches server file, success technically
-        return true;
+            // Local file matches server file, success technically
+            return true;
+        } finally {
+            FileLocker.unlock(this, file);
+        }
     }
 
     /**
@@ -461,15 +527,20 @@ public class LocalizationFile implements Comparable {
      * @throws LocalizationOpFailedException
      */
     public boolean delete() throws LocalizationOpFailedException {
-        if (exists()) {
-            return adapter.delete(file, context, path);
-        } else if (file.exists()) {
-            // Local file does actually exist, delete manually
-            return file.delete();
-        }
+        try {
+            FileLocker.lock(this, file, Type.WRITE);
+            if (exists()) {
+                return adapter.delete(getModifiableFile());
+            } else if (file.exists()) {
+                // Local file does actually exist, delete manually
+                return file.delete();
+            }
 
-        // File doesn't exist, it is deleted, so technically success?
-        return true;
+            // File doesn't exist, it is deleted, so technically success?
+            return true;
+        } finally {
+            FileLocker.unlock(this, file);
+        }
     }
 
     /**
@@ -478,7 +549,7 @@ public class LocalizationFile implements Comparable {
      * @return true if the file exists
      */
     public boolean exists() {
-        return adapter.exists(this);
+        return (isNull() == false) && adapter.exists(this);
     }
 
     /**
@@ -526,6 +597,44 @@ public class LocalizationFile implements Comparable {
         }
     }
 
+    /**
+     * Returns the object version of this jaxb serialized file. Returns null if
+     * the file does not exist or is empty.
+     * 
+     * @param 
+     * @param resultClass
+     * @param manager
+     * @return
+     * @throws LocalizationException
+     */
+    public  T jaxbUnmarshal(Class resultClass, JAXBManager manager)
+            throws LocalizationException {
+        File f = getFile();
+        if (f.exists() && (f.length() > 0)) {
+            InputStream is = null;
+            try {
+                is = openInputStream();
+                T object = resultClass.cast(manager
+                        .jaxbUnmarshalFromInputStream(is));
+                return object;
+            } catch (Exception e) {
+                throw new LocalizationException("Could not unmarshal file "
+                        + file.getName(), e);
+            } finally {
+                if (is != null) {
+                    try {
+                        is.close();
+                    } catch (IOException e) {
+                        statusHandler.handle(Priority.WARN,
+                                "Failed to close input stream for file", e);
+                    }
+                }
+            }
+        }
+
+        return null;
+    }
+
     @Override
     public String toString() {
         return context + IPathManager.SEPARATOR + path;
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFileOutputStream.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFileOutputStream.java
index 7919746f13..78319992b3 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFileOutputStream.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationFileOutputStream.java
@@ -23,6 +23,7 @@ import java.io.FileNotFoundException;
 import java.io.IOException;
 
 import com.raytheon.uf.common.localization.exception.LocalizationException;
+import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException;
 
 /**
  * Class which opens a LocalizationFile for writing to
@@ -43,6 +44,8 @@ import com.raytheon.uf.common.localization.exception.LocalizationException;
 
 public class LocalizationFileOutputStream extends LockingFileOutputStream {
 
+    private LocalizationFile file;
+
     /**
      * @param file
      * @param isAppending
@@ -53,6 +56,25 @@ public class LocalizationFileOutputStream extends LockingFileOutputStream {
     LocalizationFileOutputStream(LocalizationFile file, boolean isAppending)
             throws FileNotFoundException, LocalizationException {
         super(file.getFile(false), isAppending);
+        this.file = file;
     }
 
+    /**
+     * Closes input stream for the {@link LocalizationFile} and calls
+     * {@link LocalizationFile#save()} on the file to ensure contents are
+     * persisted. Calling {@link #close()} does not trigger a save
+     * 
+     * @param save
+     * @throws IOException
+     */
+    public void closeAndSave() throws IOException,
+            LocalizationOpFailedException {
+        try {
+            closeWithoutUnlocking();
+            file.save();
+        } finally {
+            // Make sure we unlock the file
+            unlock();
+        }
+    }
 }
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationNotificationObserver.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationNotificationObserver.java
index aeb4ac425b..0ef58e324e 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationNotificationObserver.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LocalizationNotificationObserver.java
@@ -20,14 +20,14 @@
 package com.raytheon.uf.common.localization;
 
 import java.io.File;
-import java.util.ArrayList;
-import java.util.HashMap;
+import java.util.Collection;
+import java.util.Date;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
+import com.raytheon.uf.common.localization.FileLocker.Type;
 import com.raytheon.uf.common.localization.FileUpdatedMessage.FileChangeType;
 import com.raytheon.uf.common.localization.ILocalizationAdapter.ListResponse;
 import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel;
@@ -58,12 +58,12 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
 
 public class LocalizationNotificationObserver {
 
-    private static class LocalizationFileKey {
+    private static class LocalizationTypeFileKey {
         private final LocalizationType type;
 
         private final String path;
 
-        public LocalizationFileKey(LocalizationType type, String path) {
+        public LocalizationTypeFileKey(LocalizationType type, String path) {
             super();
             this.type = type;
             this.path = path;
@@ -89,7 +89,7 @@ public class LocalizationNotificationObserver {
             if (getClass() != obj.getClass()) {
                 return false;
             }
-            final LocalizationFileKey other = (LocalizationFileKey) obj;
+            final LocalizationTypeFileKey other = (LocalizationTypeFileKey) obj;
             if (path == null) {
                 if (other.path != null) {
                     return false;
@@ -119,7 +119,7 @@ public class LocalizationNotificationObserver {
 
     private Set globalObservers = new HashSet();
 
-    private final Map> observedFiles;
+    private final Map> observedFiles;
 
     private PathManager pm;
 
@@ -137,24 +137,25 @@ public class LocalizationNotificationObserver {
      * @param lf
      */
     void addObservedFile(LocalizationFile lf) {
-        LocalizationFileKey key = new LocalizationFileKey(lf.getContext()
-                .getLocalizationType(), lf.getName());
+        LocalizationTypeFileKey key = new LocalizationTypeFileKey(lf
+                .getContext().getLocalizationType(), lf.getName());
 
-        LocalizationFileRef ref = new LocalizationFileRef(lf);
-        Set lfList;
+        Set lfList;
         synchronized (observedFiles) {
             lfList = observedFiles.get(key);
             if (lfList == null) {
-                lfList = new HashSet();
-                // add now so cleanUpRefs() cannot remove the set
-                lfList.add(ref);
+                lfList = new HashSet();
                 observedFiles.put(key, lfList);
             }
         }
         synchronized (lfList) {
-            lfList.add(ref);
+            if (lfList.add(lf) == false) {
+                // Contract between IPathManager/LocalizationFile will force
+                // this to never occur and will be developer mistake if so
+                throw new RuntimeException(
+                        "Internal Error: Attempted to register LocalizationFile which had already been registered");
+            }
         }
-        cleanUpRefs();
     }
 
     /**
@@ -182,118 +183,79 @@ public class LocalizationNotificationObserver {
     }
 
     private LocalizationNotificationObserver() {
-        observedFiles = new ConcurrentHashMap>();
+        observedFiles = new ConcurrentHashMap>();
         pm = (PathManager) PathManagerFactory.getPathManager();
     }
 
-    public void fileUpdateMessageRecieved(FileUpdatedMessage fum) {
+    public synchronized void fileUpdateMessageRecieved(FileUpdatedMessage fum) {
         LocalizationType type = fum.getContext().getLocalizationType();
-        LocalizationLevel level = fum.getContext().getLocalizationLevel();
-        String contextName = fum.getContext().getContextName();
         String filename = LocalizationUtil.getSplitUnique(fum.getFileName());
 
-        // Cleanup LocalizationFiles that have been GC'd
-        cleanUpRefs();
+        // Check if file update is older than latest file data
+        Collection potentialFiles = getLocalizationFiles(
+                type, filename);
+
+        // Find exact match first:
+        for (LocalizationFile file : potentialFiles) {
+            if (file.getContext().equals(fum.getContext())) {
+                // exact match found, skip old updates (in case we have changed
+                // the file since this update)
+                try {
+                    FileLocker.lock(this, file.file, Type.WRITE);
+                    Date fileTS = file.getTimeStamp();
+                    if (fileTS != null && fileTS.getTime() > fum.getTimeStamp()) {
+                        // Update is older than latest file data, skip update as
+                        // a newer one should be coming
+                        return;
+                    } else {
+                        // Proceed with update process
+                        processUpdate(fum, file);
+                        break;
+                    }
+                } finally {
+                    FileLocker.unlock(this, file.file);
+                }
+            }
+        }
 
         // If file deleted, delete from filesystem if non directory
         if (fum.getChangeType() == FileChangeType.DELETED) {
             File local = pm.adapter.getPath(fum.getContext(), filename);
             if (local != null && local.isDirectory() == false && local.exists()) {
-                local.delete();
+                try {
+                    FileLocker.lock(this, local, Type.WRITE);
+                    local.delete();
+                } finally {
+                    FileLocker.unlock(this, local);
+                }
             }
         }
 
-        // Response map, only request updated data once per file reference key
-        Map responseMap = new HashMap();
+        // Process other file, skipping context match that was processed above
+        for (LocalizationFile file : potentialFiles) {
+            if (file.getContext().equals(fum.getContext()) == false) {
+                processUpdate(fum, file);
+            }
+        }
+
+        // Split parts so we update sub directories
+        String[] parts = LocalizationUtil.splitUnique(filename);
+        for (int idx = parts.length - 1; idx > 0; --idx) {
+            String subpath = "";
+            for (int i = 0; i < idx; ++i) {
+                subpath += parts[i];
+                if (i < (idx - 1)) {
+                    subpath += IPathManager.SEPARATOR;
+                }
+            }
 
-        do {
-            LocalizationFileKey key = new LocalizationFileKey(type, filename);
             // Get the file references for the key to notify
-            Set lfList;
-            synchronized (observedFiles) {
-                lfList = observedFiles.get(key);
+            Collection files = getLocalizationFiles(type,
+                    subpath);
+            for (LocalizationFile file : files) {
+                processUpdate(fum, file);
             }
-            if (lfList != null) {
-                Set copy;
-                synchronized (lfList) {
-                    copy = new HashSet(lfList);
-                }
-                // Flags so we only delete or request once
-                boolean requested = false;
-                for (LocalizationFileRef ref : copy) {
-                    LocalizationFile lf = ref.get();
-                    if (lf != null) {
-                        // If null, means it was garbage collected, will be
-                        // caught next update
-                        int compVal = lf.getContext().getLocalizationLevel()
-                                .compareTo(level);
-                        if (compVal <= 0) {
-                            boolean notify = false;
-
-                            if (compVal < 0) {
-                                // Different level, check our context name to
-                                // make sure it matches update message
-                                String ourContextName = pm.getContext(type,
-                                        level).getContextName();
-                                if ((ourContextName == null && contextName == null)
-                                        || (ourContextName != null && ourContextName
-                                                .equals(contextName))) {
-                                    notify = true;
-                                }
-                            }
-
-                            // This file should be NOTIFEID based on update...
-                            ListResponse resp = null;
-                            if (fum.getContext().equals(lf.getContext())) {
-                                // context perfectly matches, make sure we
-                                // notify
-                                notify = true;
-                                // This file should be MODIFIED based on
-                                // update...
-                                if (lf.isDirectory() == false) {
-                                    resp = responseMap.get(ref.getKey());
-                                    if (resp == null) {
-                                        // Make sure we only request metadata
-                                        // once per file update
-                                        resp = getMetadata(lf);
-                                        responseMap.put(ref.getKey(), resp);
-                                    }
-
-                                    // Update file with new metadata
-                                    lf.update(resp);
-
-                                    // If we are still not a directoy and we
-                                    // should request the file, request it
-                                    if (lf.isDirectory() == false
-                                            && lf.fileRequested && !requested) {
-                                        switch (fum.getChangeType()) {
-                                        case UPDATED:
-                                        case ADDED: {
-                                            requested = true;
-                                            lf.getFile();
-                                            break;
-                                        }
-                                        }
-                                    }
-                                }
-                            }
-
-                            if (notify) {
-                                // Notify file of change
-                                lf.notifyObservers(fum);
-                            }
-                        }
-                    }
-                }
-            }
-
-            int pos = filename.lastIndexOf(IPathManager.SEPARATOR);
-            if (pos > 0) {
-                filename = filename.substring(0, pos);
-            } else {
-                filename = "";
-            }
-        } while (!filename.isEmpty());
+        }
 
         // Notify system wide listeners
         synchronized (globalObservers) {
@@ -303,6 +265,74 @@ public class LocalizationNotificationObserver {
         }
     }
 
+    private void processUpdate(FileUpdatedMessage fum, LocalizationFile file) {
+        LocalizationContext context = fum.getContext();
+        LocalizationLevel level = context.getLocalizationLevel();
+        LocalizationType type = context.getLocalizationType();
+        String contextName = context.getContextName();
+
+        int compVal = file.getContext().getLocalizationLevel().compareTo(level);
+        if (compVal <= 0) {
+            boolean notify = false;
+            if (compVal < 0) {
+                // Different level, check our context name to
+                // make sure it matches update message
+                String ourContextName = pm.getContext(type, level)
+                        .getContextName();
+                if ((ourContextName == null && contextName == null)
+                        || (ourContextName != null && ourContextName
+                                .equals(contextName))) {
+                    notify = true;
+                }
+            }
+
+            if (fum.getContext().equals(file.getContext())) {
+                // context perfectly matches, make sure we
+                // notify
+                notify = true;
+                // This file should be MODIFIED based on
+                // update...
+                if (file.isDirectory() == false) {
+                    // Update file with new metadata
+                    file.update(getMetadata(file));
+
+                    // If we are still not a directoy and we
+                    // should request the file, request it
+                    if (file.isDirectory() == false && file.fileRequested) {
+                        switch (fum.getChangeType()) {
+                        case UPDATED:
+                        case ADDED: {
+                            file.getFile();
+                            break;
+                        }
+                        }
+                    }
+                }
+            }
+
+            if (notify) {
+                // Notify file of change
+                file.notifyObservers(fum);
+            }
+        }
+    }
+
+    private Collection getLocalizationFiles(
+            LocalizationType type, String fileName) {
+        Set copy = new HashSet();
+        Set lfList;
+        synchronized (observedFiles) {
+            lfList = observedFiles.get(new LocalizationTypeFileKey(type,
+                    fileName));
+        }
+        if (lfList != null) {
+            synchronized (lfList) {
+                copy = new HashSet(lfList);
+            }
+        }
+        return copy;
+    }
+
     /**
      * @param lf
      * @return
@@ -328,33 +358,4 @@ public class LocalizationNotificationObserver {
         return rval;
     }
 
-    /**
-     * Clean up stale references
-     */
-    private void cleanUpRefs() {
-        List keysToRemove = new ArrayList();
-        for (LocalizationFileKey key : observedFiles.keySet()) {
-            Set refs = observedFiles.get(key);
-            if (refs == null || refs.size() == 0) {
-                keysToRemove.add(key);
-            } else {
-                synchronized (refs) {
-                    List toRemove = new ArrayList();
-                    for (LocalizationFileRef ref : refs) {
-                        if (ref.get() == null) {
-                            toRemove.add(ref);
-                        }
-                    }
-                    refs.removeAll(toRemove);
-                    if (refs.size() == 0) {
-                        keysToRemove.add(key);
-                    }
-                }
-            }
-        }
-
-        for (LocalizationFileKey key : keysToRemove) {
-            observedFiles.remove(key);
-        }
-    }
 }
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LockingFileOutputStream.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LockingFileOutputStream.java
index ec095f6e7a..9c9cf6b5f4 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LockingFileOutputStream.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/LockingFileOutputStream.java
@@ -77,11 +77,36 @@ public class LockingFileOutputStream extends FileOutputStream {
 
     @Override
     public void close() throws IOException {
+        close(true);
+    }
+
+    /**
+     * Closes the output stream without unlocking the file. It is the
+     * responsibility of the caller to call {@link #unlock()} when they are done
+     * with the lock.
+     */
+    public void closeWithoutUnlocking() throws IOException {
+        close(false);
+    }
+
+    /**
+     * Closes the stream, flag designates if lock will be released or not. By
+     * default {@link #close()} will unlock the file
+     * 
+     * @param unlock
+     * @throws IOException
+     */
+    private void close(boolean unlock) throws IOException {
         try {
             super.close();
         } finally {
-            FileLocker.unlock(this, file);
+            if (unlock) {
+                unlock();
+            }
         }
     }
 
+    public void unlock() {
+        FileLocker.unlock(this, file);
+    }
 }
diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManager.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManager.java
index 2c3334b1f1..57c09fefa1 100644
--- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManager.java
+++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManager.java
@@ -54,6 +54,7 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * 02/12/2008              chammack    Initial Creation.
+ * Oct 23, 2012 1322       djohnson    Allow test code in the same package to clear fileCache.
  * 
  * 
* @@ -62,10 +63,11 @@ import com.raytheon.uf.common.status.UFStatus.Priority; */ public class PathManager implements IPathManager { - private static transient IUFStatusHandler statusHandler = UFStatus + private static final IUFStatusHandler statusHandler = UFStatus .getHandler(PathManager.class, "Localization"); - private static final Map fileCache = new ConcurrentHashMap(); + // @VisibleForTesting + static final Map fileCache = new ConcurrentHashMap(); final ILocalizationAdapter adapter; @@ -145,6 +147,7 @@ public class PathManager implements IPathManager { return file != null ? file.getFile() : null; } + @Override public Map getTieredLocalizationFile( LocalizationType type, String name) { Map map = new HashMap(); @@ -220,22 +223,13 @@ public class PathManager implements IPathManager { } if (entry != null) { - for (ListResponse lr : entry) { - // A null File means the file can never exist, therefore we - // set - // the context/name key as a null file object to avoid - // requesting data about the non-existent file again - LocalizationFile file = new LocalizationFile(); - File local = adapter.getPath(lr.context, name); - if (local != null) { - file = new LocalizationFile(this.adapter, lr.context, - local, lr.date, name, lr.checkSum, - lr.isDirectory, lr.existsOnServer, - lr.protectedLevel); - availableFiles.put(file.getContext(), file); + synchronized (fileCache) { + for (ListResponse lr : entry) { + LocalizationFile file = createFromResponse(lr); + if (file.isNull() == false) { + availableFiles.put(file.getContext(), file); + } } - fileCache.put(new LocalizationFileKey(lr.fileName, - lr.context), file); } } } @@ -252,6 +246,43 @@ public class PathManager implements IPathManager { return rval.toArray(new LocalizationFile[rval.size()]); } + /** + * Creates a LocalizationFile from a {@link ListResponse}, callers need to + * synchronize on fileCache before calling + * + * @param response + * @return LocalizationFile for response (never null), but be sure to check + * isNull() on file object + */ + private LocalizationFile createFromResponse(ListResponse response) { + // able to resolve file, lf will be set, check cache + LocalizationFileKey key = new LocalizationFileKey(response.fileName, + response.context); + LocalizationFile lf = fileCache.get(key); + if (lf != null && lf.isNull() == false) { + // Ensure latest data for file, will only be null if no File can be + // returned for path/context. + lf.update(response); + } else { + // Not in cache or null reference, see if file can be resolved + if (lf == null) { + // Default to null file if not from cache + lf = new LocalizationFile(); + } + File file = this.adapter.getPath(response.context, + response.fileName); + if (file != null) { + // No cache file available and path is resolved, create + lf = new LocalizationFile(this.adapter, response.context, file, + response.date, response.fileName, response.checkSum, + response.isDirectory, response.existsOnServer, + response.protectedLevel); + } + fileCache.put(key, lf); + } + return lf; + } + /* * (non-Javadoc) * @@ -277,6 +308,7 @@ public class PathManager implements IPathManager { * .edex.utility.LocalizationContext[], java.lang.String, * java.lang.String[]) */ + @Override public LocalizationFile[] listFiles(LocalizationContext[] contexts, String name, String[] filter, boolean recursive, boolean filesOnly) { try { @@ -284,41 +316,13 @@ public class PathManager implements IPathManager { ListResponse[] entries = this.adapter.listDirectory(contexts, name, recursive, filesOnly); - for (ListResponse entry : entries) { - if (entry.isDirectory - || matchesExtension(entry.fileName, filter)) { - File file = this.adapter.getPath(entry.context, - entry.fileName); - if (file != null) { - LocalizationFileKey key = new LocalizationFileKey( - entry.fileName, entry.context); - LocalizationFile lf = fileCache.get(key); - boolean fromCache = true; - if (lf == null) { - fromCache = false; - // No cache file available - lf = new LocalizationFile(this.adapter, - entry.context, file, entry.date, - entry.fileName, entry.checkSum, - entry.isDirectory, entry.existsOnServer, - entry.protectedLevel); - fileCache.put(key, lf); - } - if (lf.exists()) { - files.add(lf); - } else if (fromCache) { - // File from cache does not exist, check if entry - // from response exists. If so update cache with new - // file created from entry - lf = new LocalizationFile(this.adapter, - entry.context, file, entry.date, - entry.fileName, entry.checkSum, - entry.isDirectory, entry.existsOnServer, - entry.protectedLevel); - if (lf.exists()) { - files.add(lf); - fileCache.put(key, lf); - } + synchronized (fileCache) { + for (ListResponse entry : entries) { + if (entry.isDirectory + || matchesExtension(entry.fileName, filter)) { + LocalizationFile file = createFromResponse(entry); + if (file.exists()) { + files.add(file); } } } diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManagerFactory.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManagerFactory.java index ecc55ba737..a9cb3c0073 100644 --- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManagerFactory.java +++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/PathManagerFactory.java @@ -49,7 +49,7 @@ public class PathManagerFactory { private static final String EDEX_ADAPTER_CLASS = "com.raytheon.edex.utility.EDEXLocalizationAdapter"; - private static IPathManager pathManager; + static IPathManager pathManager; private static ILocalizationAdapter adapter; diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/DeleteUtilityResponse.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/DeleteUtilityResponse.java index 4b65eff5b6..e4996125ba 100644 --- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/DeleteUtilityResponse.java +++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/DeleteUtilityResponse.java @@ -22,10 +22,12 @@ package com.raytheon.uf.common.localization.msgs; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** * Defines the delete localization response @@ -47,19 +49,40 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; @DynamicSerialize public class DeleteUtilityResponse extends AbstractUtilityResponse { + @XmlAttribute + @DynamicSerializeElement + private long timeStamp; + public DeleteUtilityResponse() { } public DeleteUtilityResponse(LocalizationContext context, String errorText, - String fileName) { + String fileName, long timeStamp) { super(context, fileName, errorText); + this.timeStamp = timeStamp; + } + + /** + * @return the timeStamp + */ + public long getTimeStamp() { + return timeStamp; + } + + /** + * @param timeStamp + * the timeStamp to set + */ + public void setTimeStamp(long timeStamp) { + this.timeStamp = timeStamp; } /* * (non-Javadoc) * - * @see com.raytheon.edex.msg.utility.AbstractUtilityResponse#getFormattedErrorMessage() + * @see com.raytheon.edex.msg.utility.AbstractUtilityResponse# + * getFormattedErrorMessage() */ @Override public String getFormattedErrorMessage() { diff --git a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/GetServersResponse.java b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/GetServersResponse.java index f791f8bf6c..2c0a0569ba 100644 --- a/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/GetServersResponse.java +++ b/edexOsgi/com.raytheon.uf.common.localization/src/com/raytheon/uf/common/localization/msgs/GetServersResponse.java @@ -19,6 +19,8 @@ **/ package com.raytheon.uf.common.localization.msgs; +import java.util.Map; + import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; @@ -33,6 +35,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 6, 2009 mschenke Initial creation + * Sep 12, 2012 1167 djohnson Add datadelivery servers. * *
* @@ -54,6 +57,9 @@ public class GetServersResponse implements ISerializableObject { @DynamicSerializeElement private String serverDataDir; + @DynamicSerializeElement + private Map serverLocations; + public String getHttpServer() { return httpServer; } @@ -86,4 +92,18 @@ public class GetServersResponse implements ISerializableObject { this.serverDataDir = serverDataDir; } + /** + * @return + */ + public Map getServerLocations() { + return serverLocations; + } + + /** + * @param serverLocations + * the serverLocations to set + */ + public void setServerLocations(Map serverLocations) { + this.serverLocations = serverLocations; + } } diff --git a/edexOsgi/com.raytheon.uf.common.menus/build.properties b/edexOsgi/com.raytheon.uf.common.menus/build.properties index 5791d48d5f..34d2e4d2da 100644 --- a/edexOsgi/com.raytheon.uf.common.menus/build.properties +++ b/edexOsgi/com.raytheon.uf.common.menus/build.properties @@ -1,5 +1,4 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ - res/ + . diff --git a/edexOsgi/com.raytheon.uf.common.menus/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.menus/component-deploy.xml deleted file mode 100644 index 62a3667948..0000000000 --- a/edexOsgi/com.raytheon.uf.common.menus/component-deploy.xml +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.menus/res/spring/menu-request.xml b/edexOsgi/com.raytheon.uf.common.menus/res/spring/menu-request.xml deleted file mode 100644 index 2df0461185..0000000000 --- a/edexOsgi/com.raytheon.uf.common.menus/res/spring/menu-request.xml +++ /dev/null @@ -1,16 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.monitor/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.monitor/META-INF/MANIFEST.MF index 1d2419a551..111ac256e7 100644 --- a/edexOsgi/com.raytheon.uf.common.monitor/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.monitor/META-INF/MANIFEST.MF @@ -23,7 +23,6 @@ Require-Bundle: com.raytheon.uf.common.dataplugin;bundle-version="1.11.5", com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.0.0", com.raytheon.uf.common.localization;bundle-version="1.11.17", org.eclipse.swt, - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.26", com.raytheon.uf.common.sounding;bundle-version="1.12.1112", com.raytheon.uf.common.dataplugin.bufrua;bundle-version="1.12.1112", com.raytheon.uf.edex.pointdata;bundle-version="1.12.1112", diff --git a/edexOsgi/com.raytheon.uf.common.monitor/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.monitor/component-deploy.xml deleted file mode 100644 index bfed537159..0000000000 --- a/edexOsgi/com.raytheon.uf.common.monitor/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/ScanUtils.java b/edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/ScanUtils.java index 1ad2be83d3..49fc2d0149 100644 --- a/edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/ScanUtils.java +++ b/edexOsgi/com.raytheon.uf.common.monitor/src/com/raytheon/uf/common/monitor/scan/ScanUtils.java @@ -40,7 +40,6 @@ import org.opengis.referencing.operation.TransformException; import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; -import com.raytheon.uf.common.dataplugin.binlightning.dao.BinLightningDao; import com.raytheon.uf.common.dataplugin.binlightning.impl.LtgStrikeType; import com.raytheon.uf.common.dataplugin.bufrua.UAObs; import com.raytheon.uf.common.dataplugin.bufrua.UAObsAdapter; @@ -57,6 +56,7 @@ import com.raytheon.uf.common.sounding.VerticalSounding; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.edex.database.plugin.PluginDao; import com.raytheon.uf.edex.database.plugin.PluginFactory; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Geometry; @@ -295,13 +295,13 @@ public class ScanUtils { public static String SEVERE_THUNDERSTORM_PHENSIG = "SV.W"; - private static Map tableStdResLevels = new HashMap(); - -// private static String standardResolutionLevel = null; + private static Map tableStdResLevels = new HashMap(); - private static Map tableHighResLevels = new HashMap(); + // private static String standardResolutionLevel = null; -// private static String highResolutionLevel = null; + private static Map tableHighResLevels = new HashMap(); + + // private static String highResolutionLevel = null; private static String prevTable = ""; @@ -316,7 +316,7 @@ public class ScanUtils { BinLightningRecord lightRec = null; try { lightRec = new BinLightningRecord(uri); - BinLightningDao ld = (BinLightningDao) PluginFactory.getInstance() + PluginDao ld = (PluginDao) PluginFactory.getInstance() .getPluginDao(lightRec.getPluginName()); lightRec = (BinLightningRecord) ld.getMetadata(uri); IDataStore dataStore = ld.getDataStore(lightRec); @@ -630,7 +630,7 @@ public class ScanUtils { return outputGrid; } - + public static short[] reSizeGridMax(short[] inputGrid, int outputGridSize, int nx, int ny) { @@ -647,8 +647,9 @@ public class ScanUtils { for (int x = 0; x < 4; x++) { for (int y = 0; y < 4; y++) { // average the grid values - mxValue = (short) Math.max(inputGrid[(SCAN_GRID_DIM_1KM * (i * 4 + x)) - + (j * 4 + y)], mxValue); + mxValue = (short) Math + .max(inputGrid[(SCAN_GRID_DIM_1KM * (i * 4 + x)) + + (j * 4 + y)], mxValue); } } outputGrid[(SCAN_GRID_DIM * i) + j] = mxValue; @@ -668,8 +669,9 @@ public class ScanUtils { for (int x = 0; x < 2; x++) { for (int y = 0; y < 2; y++) { // average the grid values - mxValue = (short) Math.max(inputGrid[(SCAN_GRID_DIM_2KM * (i * 2 + x)) - + (j * 2 + y)], mxValue); + mxValue = (short) Math + .max(inputGrid[(SCAN_GRID_DIM_2KM * (i * 2 + x)) + + (j * 2 + y)], mxValue); } } outputGrid[(SCAN_GRID_DIM * i) + j] = mxValue; @@ -681,7 +683,7 @@ public class ScanUtils { return outputGrid; } - + /** * Converts the raw bytes array into DBZ short arrays * @@ -700,7 +702,8 @@ public class ScanUtils { * @param radRec * @return */ - public static short[] convertToGrid(RadarRecord radRec, int gridSize, boolean max) { + public static short[] convertToGrid(RadarRecord radRec, int gridSize, + boolean max) { short[] grid = null; @@ -735,7 +738,7 @@ public class ScanUtils { radRec, irow, icol); } } - + if ((radRec.getNumBins() * radRec.getNumRadials()) != gridSize) { if (max) grid = ScanUtils.reSizeGridMax(ogrid, gridSize, @@ -1613,12 +1616,12 @@ public class ScanUtils { // hail cap check if (rValue > hailCap) { - return (float)(MM_TO_INCH * hailCap); + return (float) (MM_TO_INCH * hailCap); } } else { - return (float) rValue; + return (float) rValue; } - + return (float) (MM_TO_INCH * rValue); } @@ -1845,7 +1848,7 @@ public class ScanUtils { */ public static String getStandardResolutionLevel(String tablename) { String resLevel = tableStdResLevels.get(tablename); - if(resLevel == null) { + if (resLevel == null) { setResolutionLevels(tablename); resLevel = tableStdResLevels.get(tablename); } @@ -1861,7 +1864,7 @@ public class ScanUtils { */ public static String getHighResolutionLevel(String tablename) { String resLevel = tableHighResLevels.get(tablename); - if(resLevel == null) { + if (resLevel == null) { setResolutionLevels(tablename); resLevel = tableHighResLevels.get(tablename); } diff --git a/edexOsgi/com.raytheon.uf.common.ohd/src/com/raytheon/uf/common/ohd/AppsDefaults.java b/edexOsgi/com.raytheon.uf.common.ohd/src/com/raytheon/uf/common/ohd/AppsDefaults.java index ee2c25c1aa..c9f7e9ab70 100644 --- a/edexOsgi/com.raytheon.uf.common.ohd/src/com/raytheon/uf/common/ohd/AppsDefaults.java +++ b/edexOsgi/com.raytheon.uf.common.ohd/src/com/raytheon/uf/common/ohd/AppsDefaults.java @@ -64,7 +64,8 @@ import com.raytheon.uf.common.util.FileUtil; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Sep 22, 2008 randerso Initial creation - * Apr 1, 2009 jelkins added getTokens + * Apr 1, 2009 jelkins added getTokens + * Oct 19, 2012 bgonzale App Context variable setup and token access. *
* * @author randerso @@ -112,6 +113,8 @@ public class AppsDefaults { private static final Object LOCK = new Object(); + private static final String APP_CONTEXT = "APP_CONTEXT"; + static { _trueSet.add("true"); _trueSet.add("on"); @@ -873,4 +876,118 @@ public class AppsDefaults { } + /** + *
+     * Set context using the callingContext in the APP_CONTEXT variable.
+     *    if a token for the context is defined and is ON 
+     *       then log run and return true.
+     * 
+     * If the token is defined and is OFF
+     *    then log not run and return false.
+     * 
+ * + * Used by java directly initiated by a cron. + * + * @param callingContext + * calling context for the application. + * @return true if context is ON; false otherwise. + */ + public boolean setAppContext(Object callingContext) { + String contextVar = setAppContextVar(callingContext, false); + boolean isOn = getBoolean(contextVar, true); + + if (logger.isWarnEnabled()) { + StringBuilder sb = new StringBuilder( + "App Execution Token for App Context "); + sb.append(contextVar); + sb.append(" is "); + sb.append(isOn); + logger.warn(sb.toString()); + } + + return isOn; + } + + /** + *
+     * If no token is defined for the expected app context
+     *    or if the token is defined and is ON 
+     *       then log run and return true.
+     * 
+     * If the token is defined and is OFF
+     *    then log not run and return false.
+     * 
+ * + * Used by java that was not directly initiated by a cron. + * + * @param callingContext + * calling context for the application. + * @return true if context is ON; false otherwise. + */ + public boolean checkAppContext(Object callingContext) { + String contextVar = setAppContextVar(callingContext, true); + boolean isOn = getBoolean(contextVar, true); + + if (logger.isWarnEnabled()) { + StringBuilder sb = new StringBuilder( + "App Execution Token for App Context "); + sb.append(contextVar); + sb.append(" is "); + sb.append(isOn); + logger.warn(sb.toString()); + } + + return isOn; + } + + /** + * Set and return the APP_CONTEXT variable. + * + *
+     * Example:
+     *    APP_CONTEXT for class C called by class B 
+     *    which was called by class A:
+     *       ClassA___ClassB___ClassC
+     * 
+ * + * @param callingContext + * @param useParentContext + * @return context name + */ + private String setAppContextVar(Object callingContext, + boolean useParentContext) { + String context = callingContext.getClass().getSimpleName(); + if (useParentContext) { + String existingContext = System.getProperty(APP_CONTEXT, context); + // Check if this context is a part of the existing context + if (!existingContext.endsWith(context)) { + StringBuilder sb = new StringBuilder(existingContext); + context = sb.append(".").append(context).toString(); + } else { + context = existingContext; + } + } + System.setProperty(APP_CONTEXT, context); + return context; + } + + /** + * Set the APP_CONTEXT variable in the processBuilder environment. + * + *
+     * Example:
+     *    APP_CONTEXT for class C called by class B 
+     *    which was called by class A:
+     *       ClassA___ClassB___ClassC
+     * 
+ * + * @param processBuilder + */ + public void setAppContext(ProcessBuilder processBuilder) { + String appContextVar = System.getProperty(APP_CONTEXT); + if (appContextVar != null) { + processBuilder.environment().put(APP_CONTEXT, appContextVar); + } + } + } // end class AppsDefaults diff --git a/edexOsgi/com.raytheon.uf.common.ohd/utility/common_static/base/hydro/Apps_defaults b/edexOsgi/com.raytheon.uf.common.ohd/utility/common_static/base/hydro/Apps_defaults index 76d38b038c..c54b6e2611 100644 --- a/edexOsgi/com.raytheon.uf.common.ohd/utility/common_static/base/hydro/Apps_defaults +++ b/edexOsgi/com.raytheon.uf.common.ohd/utility/common_static/base/hydro/Apps_defaults @@ -124,6 +124,7 @@ #07/07/08 - Added sshp_show_unadjusted_states // for sshp # #10/01/09 - Added 5 tokens for arcnav application. //only for arcnav for raxum application +#10/03/12 - Added token section for script execution # ============================================================================== @@ -157,6 +158,27 @@ vsys_dir : $(apps_dir)/rfc/verify #base verify directory #AWIPS_MODIFICATION_BLOCK_END +#===================== Apps/Script Execution Tokens ================================= +WhfsSrv : ON +WhfsSrv.purge_files : ON +WhfsSrv.run_db_purge : ON +WhfsSrv.run_floodseq : ON +PprocSrv : ON +PprocSrv.purge_mpe_files : ON +PprocSrv.purge_hpe_file : ON +MpeFieldGenSrv.run_mpe_fieldgen : ON +WhfsSrv.run_pdc_pp : ON +WhfsSrv.run_alarm_whfs : ON +WhfsSrv.run_alarm_whfs.run_roc_checker : ON +WhfsSrv.run_alarm_whfs.run_report_alarm : ON +WhfsSrv.run_alarm_whfs.run_report_alarm.textdb : ON +ArealQpeGenSrv : ON +DqcPreProcSrv : ON +DqcPreProcSrv.run_dqc_preprocessor : ON +MpeRUCFreezingLevel : ON +MpeLightningSrv : ON +#==================================================================================== + # ============================================================================== # Executable directory tokens. diff --git a/edexOsgi/com.raytheon.uf.common.parameter/.classpath b/edexOsgi/com.raytheon.uf.common.parameter/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.parameter/.project b/edexOsgi/com.raytheon.uf.common.parameter/.project new file mode 100644 index 0000000000..ec9c4b048b --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.parameter + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.parameter/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.parameter/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..e8142cf597 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Jan 31 13:33:35 CST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.parameter/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.parameter/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..cfea789dc6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/META-INF/MANIFEST.MF @@ -0,0 +1,26 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Parameter +Bundle-SymbolicName: com.raytheon.uf.common.parameter +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Eclipse-BuddyPolicy: registered, ext, global +Eclipse-RegisterBuddy: com.raytheon.uf.common.serialization +Import-Package: com.raytheon.uf.common.dataplugin.annotations, + com.raytheon.uf.common.dataplugin.persist, + com.raytheon.uf.common.dataquery.requests, + com.raytheon.uf.common.dataquery.responses, + com.raytheon.uf.common.localization, + com.raytheon.uf.common.serialization, + com.raytheon.uf.common.serialization.annotations, + com.raytheon.uf.common.serialization.comm, + com.raytheon.uf.common.status, + javax.measure.converter, + javax.measure.unit, + javax.persistence +Export-Package: com.raytheon.uf.common.parameter, + com.raytheon.uf.common.parameter.lookup, + com.raytheon.uf.common.parameter.mapping, + com.raytheon.uf.common.parameter.request +Require-Bundle: com.raytheon.uf.common.util;bundle-version="1.12.1174" diff --git a/edexOsgi/com.raytheon.uf.common.parameter/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.parameter/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject new file mode 100644 index 0000000000..5174addd21 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject @@ -0,0 +1 @@ +com.raytheon.uf.common.parameter.Parameter \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.parameter/build.properties b/edexOsgi/com.raytheon.uf.common.parameter/build.properties new file mode 100644 index 0000000000..34d2e4d2da --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/Parameter.java b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/Parameter.java new file mode 100644 index 0000000000..b7ecd7d3bb --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/Parameter.java @@ -0,0 +1,257 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ + +package com.raytheon.uf.common.parameter; + +import java.text.ParseException; + +import javax.measure.converter.UnitConverter; +import javax.measure.unit.Unit; +import javax.measure.unit.UnitFormat; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.dataplugin.annotations.DataURI; +import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * + * Defines a parameter as a unique abbreviation, a human readable name, and a + * unit. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jan 12, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@DynamicSerialize +@Entity +@Table(name = "parameter") +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement +public class Parameter extends PersistableDataObject implements + ISerializableObject { + + private static final long serialVersionUID = 4866022583462757340L; + + @Id + @DynamicSerializeElement + @XmlElement + @DataURI(position = 0) + private String abbreviation; + + @Column(nullable = false) + @DynamicSerializeElement + @XmlElement + private String name; + + @Column(name = "unit") + @DynamicSerializeElement + @XmlElement(name = "unit") + private String unitString = ""; + + private transient Unit unit = null; + + public Parameter() { + + } + + public Parameter(String abbreviation) { + this.abbreviation = abbreviation; + this.name = abbreviation; + } + + public Parameter(String abbreviation, Unit unit) { + this(abbreviation); + this.setUnit(unit); + } + + public Parameter(String abbrevation, String name) { + this(abbrevation); + this.name = name; + } + + public Parameter(String abbrevation, String name, Unit unit) { + this(abbrevation, name); + this.setUnit(unit); + } + + public Parameter(String abbrevation, String name, String unitString) { + this(abbrevation, name); + this.setUnitString(unitString); + } + + public String getAbbreviation() { + return abbreviation; + } + + public void setAbbreviation(String abbreviation) { + this.abbreviation = abbreviation; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getUnitString() { + return unitString; + } + + public void setUnitString(String unitString) { + this.unitString = unitString; + this.unit = null; + } + + public Unit getUnit() { + if (unit == null) { + if (unitString != null && unitString.length() > 0) { + try { + unit = (Unit) UnitFormat.getUCUMInstance().parseObject( + unitString); + } catch (ParseException e) { + // UFStatus.getHandler().handle(Priority.WARN, + // "Unable to parse Parameter unit string: " + unitString); + unit = Unit.ONE; + } + } else { + unit = Unit.ONE; + } + } + return unit; + } + + public void setUnit(Unit unit) { + this.unit = unit; + if (unit.equals(Unit.ONE) || unit == null) { + this.unitString = ""; + } else { + this.unitString = UnitFormat.getUCUMInstance().format(unit); + } + } + + /** + * Compare the unit and unit string of two parameters and return a converter + * or null if they are incompatible. In addition to checking the units for + * convertability it will also return an IdentityConverter if the + * unitStrings are equal, even if they are not parseable as a unit object. + * + * @param sourceParameter + * @param destParameter + * @return a converter that can convert the units of sourceParameter to the + * units of destParameter + */ + public static UnitConverter compareUnits(Parameter sourceParameter, + Parameter destParameter) { + String srcString = sourceParameter.getUnitString(); + String destString = destParameter.getUnitString(); + Unit srcUnit = sourceParameter.getUnit(); + Unit destUnit = destParameter.getUnit(); + + if (srcString == null) { + if (destString == null) { + // Both strings are null, that is the same units + return UnitConverter.IDENTITY; + } else { + // src string is null and dest is not, not compatible. + return null; + } + } else if (srcString.equals(destString)) { + // unit strings are equal, thay are the same + return UnitConverter.IDENTITY; + } else if (srcUnit == null || destUnit == null) { + // One or both units are null and the strings are different, not + // compatible + return null; + } else if (srcUnit.isCompatible(destUnit)) { + // regular unit converter + return srcUnit.getConverterTo(destUnit); + } else { + // strings are different and units are incompatible. + return null; + } + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + + ((abbreviation == null) ? 0 : abbreviation.hashCode()); + result = prime * result + ((name == null) ? 0 : name.hashCode()); + result = prime * result + + ((unitString == null) ? 0 : unitString.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Parameter other = (Parameter) obj; + if (abbreviation == null) { + if (other.abbreviation != null) + return false; + } else if (!abbreviation.equals(other.abbreviation)) + return false; + if (name == null) { + if (other.name != null) + return false; + } else if (!name.equals(other.name)) + return false; + if (unitString == null) { + if (other.unitString != null) + return false; + } else if (!unitString.equals(other.unitString)) + return false; + return true; + } + + @Override + public String toString() { + return "Parameter [abbreviation=" + abbreviation + ", name=" + name + + ", unitString=" + unitString + "]"; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelAliasList.java b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/ParameterList.java similarity index 72% rename from edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelAliasList.java rename to edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/ParameterList.java index 282c4b3ded..2d99842cc0 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelAliasList.java +++ b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/ParameterList.java @@ -17,41 +17,44 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.level.xml; +package com.raytheon.uf.common.parameter; + +import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import com.raytheon.uf.common.serialization.ISerializableObject; - /** - * LevelAliasList + * A XMLSerializeable list of parameters. * *
+ * 
  * SOFTWARE HISTORY
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Sep 03, 2009            rjpeter     Initial creation.
+ * Mar 22, 2012            bsteffen     Initial creation
+ * 
  * 
* - * @author rjpeter + * @author bsteffen * @version 1.0 */ -@XmlRootElement @XmlAccessorType(XmlAccessType.NONE) -public class LevelAliasList implements ISerializableObject { - @XmlElement(name = "level") - private LevelAlias[] levels; +@XmlRootElement +public class ParameterList { - public LevelAlias[] getLevels() { - return levels; + @XmlElement(name = "parameter") + private List parameters; + + public List getParameters() { + return parameters; } - public void setLevels(LevelAlias[] levels) { - this.levels = levels; + public void setParameters(List parameters) { + this.parameters = parameters; } } diff --git a/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/lookup/ParameterLookup.java b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/lookup/ParameterLookup.java new file mode 100644 index 0000000000..b57f5858f5 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/lookup/ParameterLookup.java @@ -0,0 +1,250 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.parameter.lookup; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +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.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.parameter.ParameterList; +import com.raytheon.uf.common.parameter.request.GetParameterRequest; +import com.raytheon.uf.common.serialization.comm.RequestRouter; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; + +/** + * Caching and convenience for finding parameters in the Database. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 12, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class ParameterLookup { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(ParameterLookup.class); + + private static ParameterLookup instance; + + public static ParameterLookup getInstance() { + if (instance == null) { + instance = new ParameterLookup(); + } + return instance; + } + + // Maps abbreviation to parameter, this is a mirror of what is in the + // database. + private Map abbrevToParam; + + private ParameterLookup() { + initializeMaps(); + DbQueryRequest query = new DbQueryRequest(); + query.setEntityClass(Parameter.class.getName()); + try { + DbQueryResponse resp = (DbQueryResponse) RequestRouter.route(query); + for (Map map : resp.getResults()) { + Parameter param = (Parameter) map.get(null); + abbrevToParam.put(param.getAbbreviation(), param); + } + } catch (Exception e) { + // do not rethrow, the lookup is not broken at this point so if the + // problems persist then more exceptions will come from the actual + // lookup methods themselves. + statusHandler.handle(Priority.PROBLEM, + "Error occurred retrieving parameters from server.", e); + } + Unmarshaller unmarshaller = null; + try { + JAXBContext context = JAXBContext.newInstance(ParameterList.class); + unmarshaller = context.createUnmarshaller(); + } catch (JAXBException e) { + statusHandler + .error("Error creating Context for parameter defintions, no parameter defintions will be used.", + e); + } + if (unmarshaller != null) { + IPathManager pathMgr = PathManagerFactory.getPathManager(); + LocalizationContext commonStaticBase = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.BASE); + + LocalizationContext commonStaticSite = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + LocalizationFile[] files = pathMgr.listFiles( + new LocalizationContext[] { commonStaticSite, + commonStaticBase }, "parameter" + + IPathManager.SEPARATOR + "definition", + new String[] { ".xml" }, true, true); + + for (LocalizationFile file : files) { + if (file == null || !file.exists() + || file.getFile().length() < 0) { + continue; + } + Object obj = null; + try { + obj = unmarshaller.unmarshal(file.getFile()); + } catch (JAXBException e) { + statusHandler.error("Error reading parameter defintions: " + + file.getName() + " has been ignored.", e); + continue; + } + if (obj instanceof ParameterList) { + ParameterList list = (ParameterList) obj; + if (list.getParameters() != null) { + for (Parameter p : list.getParameters()) { + getParameter(p, true); + } + } + } else { + statusHandler.error("Error reading parameter defintions: " + + file.getName() + " was a " + + obj.getClass().getSimpleName()); + } + } + } + } + + private void initializeMaps() { + abbrevToParam = Collections + .synchronizedMap(new HashMap()); + } + + public Parameter getParameter(String abbreviation) + throws ParameterLookupException { + Parameter result = abbrevToParam.get(abbreviation); + if (result != null) { + return result; + } + HashMap constraints = new HashMap(); + constraints.put("abbreviation", new RequestConstraint(abbreviation)); + DbQueryRequest query = new DbQueryRequest(); + query.setConstraints(constraints); + query.setEntityClass(Parameter.class.getName()); + try { + DbQueryResponse resp = (DbQueryResponse) RequestRouter.route(query); + if (!resp.getResults().isEmpty()) { + result = (Parameter) resp.getResults().get(0).get(null); + if (result != null) { + abbrevToParam.put(result.getAbbreviation(), result); + } + return result; + } + } catch (Exception e) { + throw new ParameterLookupException( + "Error occurred retrieving Parameter information from server.", + e); + } + return null; + } + + /** + * bulk request multiple parameters by abbreviation, for any parameters not + * in the cache this can be significantly faster than requesting multiple + * parameters individually. + * + * @param ids + * @return + */ + public Map getParameters(List abbreviations) + throws ParameterLookupException { + RequestConstraint abbreviationConstraint = new RequestConstraint(null, + ConstraintType.IN); + Map result = new HashMap( + abbreviations.size()); + for (String abbreviation : abbreviations) { + Parameter param = abbrevToParam.get(abbreviation); + if (param == null) { + abbreviationConstraint.addToConstraintValueList(abbreviation); + } + result.put(abbreviation, param); + } + if (abbreviationConstraint.getConstraintValue() == null) { + // everything was a cache hit. + return result; + } + HashMap constraints = new HashMap(); + constraints.put("abbreviation", abbreviationConstraint); + DbQueryRequest query = new DbQueryRequest(); + query.setConstraints(constraints); + query.setEntityClass(Parameter.class.getName()); + try { + DbQueryResponse resp = (DbQueryResponse) RequestRouter.route(query); + for (Map thing : resp.getResults()) { + Parameter respParam = (Parameter) thing.get(null); + abbrevToParam.put(respParam.getAbbreviation(), respParam); + result.put(respParam.getAbbreviation(), respParam); + } + } catch (Exception e) { + throw new ParameterLookupException( + "Error occurred retrieving Parameter information from server.", + e); + } + return result; + } + + public Parameter getParameter(Parameter parameter, boolean create) + throws ParameterLookupException { + Parameter p = abbrevToParam.get(parameter.getAbbreviation()); + if (p != null) { + return p; + } + try { + Parameter result = (Parameter) RequestRouter + .route(new GetParameterRequest(parameter, create)); + if (result != null) { + abbrevToParam.put(result.getAbbreviation(), result); + } + return result; + } catch (Exception e) { + throw new ParameterLookupException( + "Error occurred retrieving Parameter information from server.", + e); + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/lookup/ParameterLookupException.java b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/lookup/ParameterLookupException.java new file mode 100644 index 0000000000..d7ecb390a4 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/lookup/ParameterLookupException.java @@ -0,0 +1,50 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.parameter.lookup; + +/** + * Exception is thrown when ParameterLookup cannot execute IServerRequest using + * the RequestRouter. This is a RuntimeException because code that uses the + * ParameterLookup cannot reasonably be expected to recover from connection + * failure. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 1, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class ParameterLookupException extends RuntimeException { + + private static final long serialVersionUID = -3401893094682026053L; + + public ParameterLookupException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/mapping/ParameterMapper.java b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/mapping/ParameterMapper.java new file mode 100644 index 0000000000..3727985880 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/mapping/ParameterMapper.java @@ -0,0 +1,147 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.parameter.mapping; + +import java.util.HashSet; +import java.util.Set; + +import javax.xml.bind.JAXBException; + +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.parameter.lookup.ParameterLookup; +import com.raytheon.uf.common.parameter.lookup.ParameterLookupException; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.util.mapping.Mapper; +import com.raytheon.uf.common.util.mapping.MultipleMappingException; + +/** + * + * Provide mapping of parameter abbreviations. The base set is defined by what + * is in the parameter database, which is initially populated from the parameter + * definitions files. As well as providing name mapping it is also possible to + * map from an alias to a Parameter object. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 2, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class ParameterMapper extends Mapper { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(ParameterMapper.class); + + private ParameterMapper() { + IPathManager pathMgr = PathManagerFactory.getPathManager(); + LocalizationContext commonStaticBase = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.BASE); + + LocalizationContext commonStaticSite = pathMgr.getContext( + LocalizationContext.LocalizationType.COMMON_STATIC, + LocalizationContext.LocalizationLevel.SITE); + + // read in the namespace map + LocalizationFile[] files = pathMgr.listFiles(new LocalizationContext[] { + commonStaticSite, commonStaticBase }, "parameter" + + IPathManager.SEPARATOR + "alias", new String[] { ".xml" }, + true, true); + for (LocalizationFile file : files) { + try { + addAliasList(file.getFile()); + } catch (JAXBException e) { + statusHandler.error( + "Error reading parameter aliases: " + file.getName() + + " has been ignored.", e); + } + } + } + + /** + * same functionality as lookupBaseNames but maps each baseName to a + * Parameter object. + * + * @param alias + * @param namespace + * @return + * @throws ParameterLookupException + */ + public Set lookupParameters(String alias, String namespace) + throws ParameterLookupException { + Set baseNames = super.lookupBaseNames(alias, namespace); + Set result = new HashSet( + (int) (baseNames.size() / 0.75) + 1, 0.75f); + for (String baseName : baseNames) { + result.add(getBaseParameter(baseName)); + } + return result; + } + + /** + * same functionality as lookupBaseName but maps the baseName to a Parameter + * Object. + * + * @param alias + * @param namespace + * @return + * @throws ParameterLookupException + * @throws MultipleMappingException + */ + public Parameter lookupParameter(String alias, String namespace) + throws ParameterLookupException, MultipleMappingException { + String baseName = super.lookupBaseName(alias, namespace); + return getBaseParameter(baseName); + } + + /** + * get a parameter object for a baseName, no mapping is done, this is + * provided here for convenience. + * + * @param baseName + * @return + * @throws ParameterLookupException + */ + public Parameter getBaseParameter(String baseName) + throws ParameterLookupException { + return ParameterLookup.getInstance().getParameter(baseName); + } + + private static ParameterMapper instance; + + public static synchronized ParameterMapper getInstance() { + if (instance == null) { + instance = new ParameterMapper(); + } + return instance; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/request/GetParameterRequest.java b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/request/GetParameterRequest.java new file mode 100644 index 0000000000..34831ee060 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/src/com/raytheon/uf/common/parameter/request/GetParameterRequest.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.parameter.request; + +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.serialization.comm.IServerRequest; + +/** + * Request to lookup a parameter that has the same abbreviation as the provided + * parameter, also provides option for creating the parameter in the database if + * it does not already exist. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 26, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@DynamicSerialize +public class GetParameterRequest implements IServerRequest { + + @DynamicSerializeElement + private Parameter parameter; + + @DynamicSerializeElement + private boolean create = false; + + public GetParameterRequest() { + } + + public GetParameterRequest(Parameter parameter) { + this.parameter = parameter; + this.create = false; + } + + public GetParameterRequest(Parameter parameter, boolean create) { + this.parameter = parameter; + this.create = create; + } + + public Parameter getParameter() { + return parameter; + } + + public void setParameter(Parameter parameter) { + this.parameter = parameter; + } + + public boolean getCreate() { + return create; + } + + public void setCreate(boolean create) { + this.create = create; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/cf.xml b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/cf.xml new file mode 100644 index 0000000000..4dc5e05b5a --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/cf.xml @@ -0,0 +1,75 @@ + + + + + atmosphere_absolute_vorticity + convective_cloud_area_fraction + convective_precipitation_amount + dew_point_temperature + dew_point_depression + direction_of_wind_wave_velocity + direction_of_swell_wave_velocity + pseudo_equivalent_potential_temperature + water_evaporation_amount + geopotential_height + altitude + high_cloud_area_fraction + sea_ice_thickness + humidity_mixing_ratio + air_temperature_lapse_rate + low_cloud_area_fraction + large_scale_precipitation_amount + surface_upward_latent_heat_flux + wind_wave_period + swell_wave_period + medium_cloud_area_fraction + air_pressure + air_pressure_at_sea_level + air_potential_temperature + precipitation_flux + air_pressure_anomaly + atmosphere_water_vapour_content + relative_humidity + water_vapour_saturation_deficit + significant_height_of_swell_waves + significant_height_of_wind_waves + surface_snow_thickness + specific_humidity + surface_upward_sensible_heat_flux + soil_temperature + air_temperature + air_temperature_anomaly + thunderstorm_probability + cloud_area_fraction + precipitation_amount + eastward_wind + northward_wind + water_vapour_pressure + wind_speed_shear + vertical_air_velocity_expressed_as_tendency_of_pressure + visibility_in_air + virtual_temperature + surface_snow_amount + wind_mixing_energy_flux_into_ocean + wind_from_direction + wind_speed + wind_speed_of_gust + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/gempak.xml b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/gempak.xml new file mode 100644 index 0000000000..19161c27f9 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/gempak.xml @@ -0,0 +1,116 @@ + + + + HGHT5 + AVOR + WXTR + WXTZ + WXTP + WXTS + CWTR + CAPE + CINH + CCLD + C01M + C03M + C06M + C09M + C12M + C12M + DWPK + DPDK + DRCTWW + DRCTSW + THTE + EVAP + HGHT + DIST + HEAT + CLDH + ICET + MIXR + LAPS + CLDL + S01M + S03M + FXLH + TMNK + PERDWW + PERDSW + CLDM + TMXK + LIFT + PRES + PMSL + EMSL + MMSL + THTA + PCPR + PRESA + DRCTPW + PERDPW + POPZ + POPF + PVOR + PEVAP + PEVP + PWTR + RELH + SATD + DRCTSW + PERDSW + HGHTSW + HGHTWW + SCVR + SNDM + SPFH + FXSH + SLTK + HLCY + LIFT + TMPK + TMPKA + TSTM + CLD + P01M + P03M + P06M + P09M + P12M + P18M + P24M + P48M + USTRM + VSTRM + UREL + VREL + VAPR + VWSH + OMEG + VSBY + THTV + TVRK + SWEM + ENRG + DRCT + SPED + GUST + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/grads.xml b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/grads.xml new file mode 100644 index 0000000000..62b9192e9f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/grads.xml @@ -0,0 +1,107 @@ + + + + + capesfc + cinsfc + cfrzrsfc + crainsfc + cicepsfc + csnowsfc + cpratsfc + wvdirsfc + dirswsfc + dirpwsfc + epotsfc + hgtsfc + hlcysfc + ncpcpsfc + wvpersfc + perswsfc + perpwsfc + pratesfc + pressfc + snowcsfc + snodsfc + lftxsfc + tmpsfc + apcpsfc + ugrdsfc + vgrdsfc + vissfc + wdirsfc + gustsfc + windsfc + weasdsfc + + absvprs + dptprs + hgtprs + rhprs + ugrdprs + vgrdprs + vvelprs + spfhprs + tmpprs + + absvprs + dpt2m + depr2m + pot2m + rh2m + ugrd2m + vgrd2m + spfh2m + tmp2m + + pottrop + hgttrop + prestrop + tmptrop + ugrdtrop + vgrdtrop + + hgtmwl + presmwl + tmpmwl + ugrdmwl + vgrdmwl + + ugrd10m + vgrd10m + wdir10m + wind10m + + cwatclm + pwatclm + rhclm + tcdcclm + + tcdchcll + tcdclcll + tcdcmcll + + prmslmsl + msletmsl + + absv500mb + no5wavh500mb + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/sedris.xml b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/sedris.xml new file mode 100644 index 0000000000..919967f66c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/alias/sedris.xml @@ -0,0 +1,85 @@ + + + + + WIND_ABSOLUTE_VORTICITY + FREEZING_RAIN_PRESENT + CLOUD_LIQUID_WATER_CONTENT + CONVECTIVE_CLOUD_LAYER + CONVECTIVE_PRECIPITATION_DENSITY + DEW_POINT_TEMPERATURE + DEW_POINT_DEPRESSION + WIND_WAVE_DIRECTION + MEAN_SWELL_WAVE_DIRECTION + EQUIV_POTENTIAL_TEMPERATURE + GEOPOTENTIAL_ALTITUDE + TEMPERATURE_HEAT_INDEX + HIGH_CLOUD_COVERAGE + ICE_LAYER_THICKNESS + MIXING_RATIO + TEMPERATURE_LAPSE_RATE + LOW_CLOUD_COVERAGE + LARGE_SCALE_PRECIPITATION + LATENT_HEAT_FLUX + MINIMUM_AIR_TEMPERATURE + MEAN_WIND_WAVE_PERIOD + MEAN_SWELL_WAVE_PERIOD + MIDDLE_CLOUD_COVERAGE + MAXIMUM_AIR_TEMPERATURE + ATM_PRESSURE + ATM_PRESSURE_REDUCED_MSL + POTENTIAL_AIR_TEMPERATURE + PRECIPITATION_RATE + PRIMARY_WAVE_DIRECTION + MEAN_PRIMARY_WAVE_PERIOD + WIND_POTENTIAL_VORTICITY + EVAPORATION_POTENTIAL + PRECIPITABLE_WATER + RELATIVE_HUMIDITY + SECONDARY_WAVE_DIRECTION + MEAN_SECONDARY_WAVE_PERIOD + SIFNIF_SWELL_WAVE_HEIGHT + SIFNIF_WIND_WAVE_HEIGHT + SNOW_GROUND_COVER_FRACTION + SNOW_ONLY_DEPTH + SPECIFIC_HUMIDITY + SENSIBLE_HEAT_FLUX + SOIL_TEMPERATURE + STORM_RELATIVE_HELICITY + AIR_TEMPERATURE + THUNDERSTORM_PROBABILITY + TOTAL_CLOUD_COVERAGE + ACCUM_PRECIP + ACCUM_PRECIP_3_HOUR + ACCUM_PRECIP_6_HOUR + ACCUM_PRECIP_24_HOUR + WIND_SPEED_U + WIND_SPEED_V + WIND_SHEAR_VERTICAL + WIND_OMEGA + VISIBILITY_DISTANCE + VIRTUAL_POTENTIAL_TEMPERATURE + VIRTUAL_AIR_TEMPERATURE + SNOW_ACCUM_DEPTH_EQUIVALENT + WIND_DIRECTION + WIND_SPEED + WIND_GUST_SPEED + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/definition/parameters.xml b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/definition/parameters.xml new file mode 100644 index 0000000000..9c9ccd493f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.parameter/utility/common_static/base/parameter/definition/parameters.xml @@ -0,0 +1,502 @@ + + + + + + 5-Wave Geopotential Height + WGH + gpm + + + Absolute Vorticity + AV + /s + + + Categorical Rain + CRAIN + bit + + + Categorical Freezing Rain + CFRZR + bit + + + Categorical Ice Pellets + CICEP + bit + + + Categorical Snow + CSNOW + bit + + + Cloud Water + CWAT + mm + + + Convective Available Potential Energy + CAPE + J/kg + + + Convective Inhibition + CIn + J/kg + + + Convective Cloud Cover + CDCON + % + + + Convective Precipitation + CP + mm + + + Convective Precipitation(1 hour) + CP1hr + mm + + + Convective Precipitation(3 hours) + CP3hr + mm + + + Convective Precipitation(6 hours) + CP6hr + mm + + + Convective Precipitation(9 hours) + CP9hr + mm + + + Convective Precipitation(12 hours) + CP12hr + mm + + + Convective Precipitation Rate + CPRAT + mm/s + + + Dew Point Depression + DpD + K + + + Dew Point Temperature + DpT + K + + + Direction of Wind Waves + WVDIR + deg + + + Direction of Swell Waves + SWDIR + deg + + + Equivalent Potential Temperature + EPT + K + + + Evaporation + EVP + kg/m^2 + + + Geometric Height + GeH + m + + + Geopotential Height + GH + gpm + + + Heat Index + HIdx + K + + + High Cloud Cover + HCDC + % + + + Humidity Mixing Ratio + MIXR + kg/kg + + + Ice Thickness + ICETK + m + + + Lapse Rate + LAPR + K/m + + + Large Scale Precipitation + LgSP + mm + + + Large Scale Precipitation(1 hour) + LgSP1hr + mm + + + Large Scale Precipitation(3 hour) + LgSP3hr + mm + + + Latent Heat Flux + LHF + W/m^2 + + + Low Cloud Cover + LCDC + % + + + Minimum Temperature + MnT + K + + + Mean Period of Wind Waves + WVPER + s + + + Mean Period of Swell Waves + SWPER + s + + + Medium Cloud Cover + MCDC + % + + + Maximum Temperature + MxT + K + + + Parcel Lifted Index (to 500 mb) + PLI + K + + + Potential Temperature + PoT + K + + + Pressure Anomaly + PRESA + Pa + + + Pressure + P + Pa + + + Pressure Reduced to MSL + PMSL + Pa + + + MSLP (ETA Reduction) + EMSP + Pa + + + MSLP (MAPS Reduction) + MMSP + Pa + + + Primary Wave Direction + DIRPW + deg + + + Primary Wave Mean Period + PERPW + s + + + Precipitation Rate + PR + mm/s + + + Probability of Frozen Precip + CPOFP + % + + + Probability of Freezing Precip + CPOZP + % + + + Potential Evaporation + PEVAP + mm + + + Potential Evaporation Rate + PEVPR + W/m^2 + + + Potential Vorticity + PVORT + m^2*kg^-1*s^-1 + + + Precipitable Water + PW + mm + + + Relative Humidity + RH + % + + + Sensible Heat Flux + SHF + W/m^2 + + + Saturation Deficit + SATD + Pa + + + Secondary Wave Direction + DIRSW + deg + + + Secondary Wave Mean Period + PERSW + s + + + Significant Height of Wind Waves + WVHGT + m + + + Significant Height of Swell Waves + SWELL + m + + + Snow Cover + SCP + % + + + Snow Depth + SnD + m + + + Soil Temperature + TSOIL + K + + + Specific Humidity + SH + % + + + Storm Relative Helicity + Heli + m^2/s^2 + + + Surface Lifted Index + SLI + K + + + Temperature + T + K + + + Total Cloud Cover + TCC + % + + + Temperature Anomaly + Ta + K + + + Thunderstorm Probability + ThP + % + + + Total Precipitation + TP + mm + + + Total Precipitation(1 hour) + TP1hr + mm + + + Total Precipitation(3 hours) + TP3hr + mm + + + Total Precipitation(6 hours) + TP6hr + mm + + + Total Precipitation(9 hours) + TP9hr + mm + + + Total Precipitation(12 hours) + TP12hr + mm + + + Total Precipitation(18 hours) + TP18hr + mm + + + Total Precipitation(24 hours) + TP24hr + mm + + + Total Precipitation(48 hours) + TP48hr + mm + + + U-Component of Storm Motion + USTM + m/s + + + V-Component of Storm Motion + VSTM + m/s + + + U-Component of Wind + uW + m/s + + + V-Component of Wind + vW + m/s + + + Vapor Pressure + VAPP + Pa + + + Vertical Speed Shear + VWSH + /s + + + Vertical Velocity Pressure + PVV + Pa/s + + + Visibility + Vis + m + + + Virtual Potential Temperature + VPT + K + + + Virtual Temperature + VTMP + K + + + Water Equivalent of Accumulated Snow Depth + WEASD + mm + + + Wind Direction (from which blowing) + WD + deg + + + Wind Mixing Energy + WMIXE + J + + + Wind Speed + WS + m/s + + + Wind Gust Speed + WGS + m/s + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/MANIFEST.MF index 368c4c8c6e..32501c5d08 100644 --- a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/MANIFEST.MF @@ -5,8 +5,13 @@ Bundle-SymbolicName: com.raytheon.uf.common.plugin.nwsauth Bundle-Version: 1.12.1174.qualifier Bundle-Vendor: RAYTHEON Eclipse-RegisterBuddy: com.raytheon.uf.common.serialization -Eclipse-BuddyPolicy: registered, ext, global Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Import-Package: com.raytheon.uf.common.auth.user -Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.12.2" -Export-Package: com.raytheon.uf.common.plugin.nwsauth.user +Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.12.2", + com.raytheon.uf.common.auth;bundle-version="1.12.1174", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.common.localization;bundle-version="1.12.1174" +Export-Package: com.raytheon.uf.common.plugin.nwsauth, + com.raytheon.uf.common.plugin.nwsauth.exception, + com.raytheon.uf.common.plugin.nwsauth.user, + com.raytheon.uf.common.plugin.nwsauth.xml +Import-Package: com.raytheon.uf.common.plugin.nwsauth.exception diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject index 84750500ee..dcdb98d253 100644 --- a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject @@ -1 +1,5 @@ -com.raytheon.uf.common.plugin.nwsauth.user.UserId \ No newline at end of file +com.raytheon.uf.common.plugin.nwsauth.user.UserId +com.raytheon.uf.common.plugin.nwsauth.xml.NwsRoleData +com.raytheon.uf.common.plugin.nwsauth.xml.PermissionXML +com.raytheon.uf.common.plugin.nwsauth.xml.RoleXML +com.raytheon.uf.common.plugin.nwsauth.xml.UserXML diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/NwsPermission.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/NwsPermission.java new file mode 100644 index 0000000000..0fc804f04e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/NwsPermission.java @@ -0,0 +1,69 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.plugin.nwsauth; + +import com.raytheon.uf.common.auth.user.IPermission; + +/** + * NWS implementation of {@link IPermission}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 5, 2012  1302      djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class NwsPermission implements IPermission { + + private final String description; + + private final String name; + + /** + * @param name + * @param description + */ + public NwsPermission(String name, String description) { + this.name = name; + this.description = description; + } + + /** + * {@inheritDoc} + */ + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return name; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/NwsRole.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/NwsRole.java new file mode 100644 index 0000000000..aec100577d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/NwsRole.java @@ -0,0 +1,82 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.plugin.nwsauth; + +import java.util.Collections; +import java.util.List; + +import com.raytheon.uf.common.auth.user.IPermission; +import com.raytheon.uf.common.auth.user.IRole; + +/** + * NWS implementation of {@link IRole}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 5, 2012  1302      djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class NwsRole implements IRole { + + private final List permissions; + + private final String description; + + private final String name; + + public NwsRole(String name, List permissions, + String description) { + this.name = name; + this.permissions = (permissions == null) ? Collections + . emptyList() : permissions; + this.description = description; + } + + /** + * {@inheritDoc} + */ + @Override + public List getPermissions() { + return permissions; + } + + /** + * {@inheritDoc} + */ + @Override + public String getDescription() { + return description; + } + + @Override + public String toString() { + return name; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/exception/RoleApplicationNotFoundException.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/exception/RoleApplicationNotFoundException.java new file mode 100644 index 0000000000..2fa212e9f3 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/exception/RoleApplicationNotFoundException.java @@ -0,0 +1,73 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.plugin.nwsauth.exception; + +import com.raytheon.uf.common.auth.exception.AuthorizationException; + +/** + * Exception when the application id for a role is not found. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 18, 2012            bgonzale     Initial creation
+ * 
+ * 
+ * + * @author bgonzale + * @version 1.0 + */ + +public class RoleApplicationNotFoundException extends AuthorizationException { + + private static final long serialVersionUID = 1L; + + /** + * + */ + public RoleApplicationNotFoundException() { + } + + /** + * @param message + */ + public RoleApplicationNotFoundException(String message) { + super(message); + } + + /** + * @param cause + */ + public RoleApplicationNotFoundException(Throwable cause) { + super(cause); + } + + /** + * @param message + * @param cause + */ + public RoleApplicationNotFoundException(String message, Throwable cause) { + super(message, cause); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/NwsRoleData.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/NwsRoleData.java new file mode 100644 index 0000000000..6dd1df05b6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/NwsRoleData.java @@ -0,0 +1,305 @@ +package com.raytheon.uf.common.plugin.nwsauth.xml; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +@XmlRootElement(name = "nwsRoleData") +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class NwsRoleData implements ISerializableObject { + @DynamicSerializeElement + @XmlElement(name = "application") + private String application; + + @DynamicSerializeElement + @XmlElements({ @XmlElement(name = "permission", type = PermissionXML.class) }) + private List permissionList = new ArrayList(); + + @DynamicSerializeElement + @XmlElements({ @XmlElement(name = "role", type = RoleXML.class) }) + private List roleList = new ArrayList(); + + @DynamicSerializeElement + @XmlElements({ @XmlElement(name = "user", type = UserXML.class) }) + private List userList = new ArrayList(); + + /** Map of user to all permissions */ + private transient Map> permissionMap = new HashMap>(); + + /** + * @return the permissionList + */ + public List getPermissionList() { + return permissionList; + } + + /** + * @param permissionList + * the permissionList to set + */ + public void setPermissionList(List permissionList) { + this.permissionList = permissionList; + } + + /** + * @return the roleList + */ + public List getRoleList() { + return roleList; + } + + /** + * @param roleList + * the roleList to set + */ + public void setRoleList(List roleList) { + this.roleList = roleList; + } + + /** + * @return the userList + */ + public List getUserList() { + return userList; + } + + /** + * @param userList + * the userList to set + */ + public void setUserList(List userList) { + this.userList = userList; + } + + /** + * @return the application + */ + public String getApplication() { + return application; + } + + /** + * @param application + * the application to set + */ + public void setApplication(String application) { + this.application = application; + } + + public String[] getPermissions() { + ArrayList perms = new ArrayList(); + for (PermissionXML p : this.permissionList) { + perms.add(p.getId()); + } + Collections.sort(perms); + + return perms.toArray(new String[perms.size()]); + } + + public String[] getRoles() { + ArrayList roles = new ArrayList(); + for (RoleXML r : this.roleList) { + roles.add(r.getRoleId()); + } + Collections.sort(roles); + + return roles.toArray(new String[roles.size()]); + } + + public String[] getUsers() { + ArrayList users = new ArrayList(); + for (UserXML r : this.userList) { + users.add(r.getUserId()); + } + Collections.sort(users); + + return users.toArray(new String[users.size()]); + } + + public void addUser(String user) { + if (user != null && user.length() > 0) { + UserXML userXml = new UserXML(); + userXml.setUserId(user); + this.userList.add(userXml); + } + } + + public void addRole(String role, String description) { + if (role != null && description != null && role.length() > 0 && description.length() > 0) { + RoleXML roleXml = new RoleXML(); + roleXml.setRoleDescription(description); + roleXml.setRoleId(role); + this.roleList.add(roleXml); + } + } + + /** + * Add a permission. This should only be used for + * Localization permissions, which are directory access + * permissions. + * + * @param permission + */ + public void addPermission(String permission) { + if (permission != null && permission.length() > 0) { + PermissionXML pXml = new PermissionXML(); + pXml.setId(permission); + this.permissionList.add(pXml); + } + } + + /** + * Get the user's permissions + * + * @param userId id of the user + * @return String[] of permissions + */ + public String[] getUserPermissions(String userId) { + ArrayList userPermissions = new ArrayList(); + + for (UserXML userXml : this.userList) { + if (userXml.getUserId().equals(userId)) { + for (String permission : userXml.getPermissionList()) { + userPermissions.add(permission); + } + break; + } + } + Collections.sort(userPermissions); + + return userPermissions.toArray(new String[userPermissions.size()]); + } + + /** + * Get an array of all defined permissions + * + * @return String[] of all defined permissions + */ + public String[] getAllDefinedPermissions() { + ArrayList permissions = new ArrayList(); + for (PermissionXML p: this.permissionList) { + permissions.add(p.getId()); + } + + return permissions.toArray(new String[permissions.size()]); + } + + public String[] getRolePermissions(String roleId) { + ArrayList rolePermissions = new ArrayList(); + + for (RoleXML roleXml : this.roleList) { + if (roleXml.getRoleId().equals(roleId)) { + for (String permission : roleXml.getPermissionList()) { + rolePermissions.add(permission); + } + break; + } + } + Collections.sort(rolePermissions); + + return rolePermissions.toArray(new String[rolePermissions.size()]); + } + + public String[] getUserRoles(String userId) { + ArrayList userRoles = new ArrayList(); + + for (UserXML userXml : this.userList) { + if (userXml.getUserId().equals(userId)) { + for (String role : userXml.getRoleList()) { + userRoles.add(role); + } + break; + } + } + Collections.sort(userRoles); + + return userRoles.toArray(new String[userRoles.size()]); + } + + public String[] getRoleIdList() { + ArrayList roleIdList = new ArrayList(); + for (RoleXML rx : this.roleList) { + roleIdList.add(rx.getRoleId()); + } + Collections.sort(roleIdList); + + return roleIdList.toArray(new String[roleIdList.size()]); + } + + /** + * Get a list of all permissions for this user. + * + * @param user + * The user + * + * @return Set of all permissions + */ + private Set getAuthorizedPermissions(String user) { + if (!permissionMap.containsKey(user)) { + Set permSet = new HashSet(); + + for (String p : this.getUserPermissions(user)) { + permSet.add(p); + } + + String[] roles = this.getUserRoles(user); + + for (RoleXML roleXml : roleList) { + for (String role : roles) { + if (roleXml.getRoleId().equals(role)) { + for (String p: roleXml.getPermissionList()) { + permSet.add(p); + } + } + } + } + + permissionMap.put(user, permSet); + } + + return permissionMap.get(user); + } + + /** + * If the user has the permission then the user is authorized. + * + * @param permission + * the permission id + * @param user + * the user id + * @return true if the user has the permission + */ + public boolean isAuthorized(String permission, String user) { + Set authorizedPermissions = this.getAuthorizedPermissions(user); + Set allAuthorizedPermissions = this.getAuthorizedPermissions("ALL"); + + for (String perm: authorizedPermissions) { + if (perm.equalsIgnoreCase(permission)) { + return true; + } + } + + for (String perm: allAuthorizedPermissions) { + if (perm.equalsIgnoreCase(permission)) { + return true; + } + } + + return false; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/Group.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/PermissionXML.java similarity index 67% rename from edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/Group.java rename to edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/PermissionXML.java index 10aa1e89a1..824f9af8de 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/Group.java +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/PermissionXML.java @@ -17,71 +17,81 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.level.xml; +package com.raytheon.uf.common.plugin.nwsauth.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** - * Group definition + * Permission Element * *
+ * 
  * SOFTWARE HISTORY
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Sep 03, 2009            rjpeter     Initial creation.
+ * May 18, 2012            mpduff     Initial creation.
+ * Oct  2, 2012   1237     jpiatt     Allow for null description.
+ * 
  * 
* - * @author rjpeter + * @author mpduff * @version 1.0 */ -@DynamicSerialize -@XmlRootElement @XmlAccessorType(XmlAccessType.NONE) -@XmlType(namespace = "group") -public class Group implements ISerializableObject { +@DynamicSerialize +public class PermissionXML implements ISerializableObject { + @DynamicSerializeElement - @XmlAttribute + @XmlAttribute(name = "id") private String id; @DynamicSerializeElement - @XmlAttribute + @XmlElement(name = "description", type = String.class) private String description; - @DynamicSerializeElement - @XmlElement(name = "level") - private Level[] levels; - + /** + * Get the permission id. + * + * @return the id + */ public String getId() { return id; } + /** + * Set the permission id. + * + * @param id + * the id to set + */ public void setId(String id) { this.id = id; } - public Level[] getLevels() { - return levels; - } - - public void setLevels(Level[] levels) { - this.levels = levels; - } - + /** + * Get the permission description. + * + * @return the description + */ public String getDescription() { return description; } + /** + * Set the permission description. + * + * @param description + * the description to set + */ public void setDescription(String description) { - this.description = description; + this.description = (description == null) ? null : description.trim(); } } diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/RoleXML.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/RoleXML.java new file mode 100644 index 0000000000..e7837915a3 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/RoleXML.java @@ -0,0 +1,120 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.plugin.nwsauth.xml; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Role element + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 18, 2012            mpduff     Initial creation
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class RoleXML implements ISerializableObject { + @DynamicSerializeElement + @XmlAttribute(name = "roleId") + private String roleId; + + @DynamicSerializeElement + @XmlElement(name = "roleDescription", type = String.class) + private String roleDescription = null; + + @DynamicSerializeElement + @XmlElements({ @XmlElement(name = "rolePermission", type = String.class) }) + private List permissionList = new ArrayList(); + + /** + * @return the roleId + */ + public String getRoleId() { + return roleId; + } + + /** + * @param roleId + * the roleId to set + */ + public void setRoleId(String roleId) { + this.roleId = roleId; + } + + /** + * @return the description + */ + public String getRoleDescription() { + return roleDescription.trim(); + } + + /** + * @param roleDescription + * the description to set + */ + public void setRoleDescription(String roleDescription) { + this.roleDescription = roleDescription.trim(); + } + + /** + * @return the permissionList + */ + public List getPermissionList() { + return permissionList; + } + + /** + * @param permissionList + * the permissionList to set + */ + public void setPermissionList(List permissionList) { + this.permissionList = permissionList; + } + + /** + * Add a permission + * + * @param permission + * The permission to add + */ + public void addPermission(String permission) { + this.permissionList.add(permission); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/UserXML.java b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/UserXML.java new file mode 100644 index 0000000000..aa8089901e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.plugin.nwsauth/src/com/raytheon/uf/common/plugin/nwsauth/xml/UserXML.java @@ -0,0 +1,175 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.plugin.nwsauth.xml; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; + +import com.raytheon.uf.common.auth.user.IAuthenticationData; +import com.raytheon.uf.common.auth.user.IUser; +import com.raytheon.uf.common.auth.user.IUserId; +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * User element + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 18, 2012            mpduff     Initial creation
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class UserXML implements IUser, ISerializableObject { + @DynamicSerializeElement + @XmlAttribute(name = "userId") + private String userId; + + @DynamicSerializeElement + @XmlElements({ @XmlElement(name = "userPermission", type = String.class) }) + private List permissionList = new ArrayList(); + + @DynamicSerializeElement + @XmlElements({ @XmlElement(name = "userRole", type = String.class) }) + private List roleList = new ArrayList(); + + /** + * @return the userId + */ + public String getUserId() { + return userId; + } + + /** + * @param iduserId + * the userId to set + */ + public void setUserId(String userId) { + this.userId = userId; + } + + /** + * @return the permissionList + */ + public List getPermissionList() { + return permissionList; + } + + /** + * @param permissionList + * the permissionList to set + */ + public void setPermissionList(List permissionList) { + this.permissionList = permissionList; + } + + /** + * Add a permission + * + * @param permission + * The permission to add + */ + public void addPermission(String permission) { + if (!this.permissionList.contains(permission)) { + this.permissionList.add(permission); + } + } + + /** + * @return the roleList + */ + public List getRoleList() { + return roleList; + } + + /** + * @param roleList + * the roleList to set + */ + public void setRoleList(List roleList) { + this.roleList = roleList; + } + + public void addRole(String role) { + if (!this.roleList.contains(role)) { + this.roleList.add(role); + } + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + final String nl = "\n"; + StringBuilder sb = new StringBuilder(); + sb.append(this.getUserId()).append(nl); + + for (String role : this.roleList) { + sb.append(" ").append(role).append(nl); + } + + for (String perm : permissionList) { + sb.append(" ").append(perm).append(nl); + } + + return sb.toString(); + } + + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.common.auth.user.IUser#uniqueId() + */ + @Override + public IUserId uniqueId() { + // TODO Auto-generated method stub + return null; + } + + /* + * (non-Javadoc) + * + * @see com.raytheon.uf.common.auth.user.IUser#authenticationData() + */ + @Override + public IAuthenticationData authenticationData() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.serialization.comm/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.serialization.comm/META-INF/MANIFEST.MF index 4bdb30baf4..4674fd70ec 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization.comm/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.serialization.comm/META-INF/MANIFEST.MF @@ -8,9 +8,9 @@ Eclipse-RegisterBuddy: com.raytheon.uf.common.serialization Eclipse-BuddyPolicy: registered, ext, global Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Export-Package: com.raytheon.uf.common.serialization.comm, - com.raytheon.uf.common.serialization.comm.response, - com.raytheon.uf.common.serialization.comm.util + com.raytheon.uf.common.serialization.comm.response Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.11.12", net.sf.cglib;bundle-version="2.1.3", - com.raytheon.uf.common.status + com.raytheon.uf.common.status, + com.raytheon.uf.common.util;bundle-version="1.12.1174" Import-Package: com.raytheon.uf.common.message diff --git a/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/RequestRouter.java b/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/RequestRouter.java index ee53104a27..e4156528ef 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/RequestRouter.java +++ b/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/RequestRouter.java @@ -19,16 +19,13 @@ **/ package com.raytheon.uf.common.serialization.comm; -import java.util.Iterator; -import java.util.ServiceConfigurationError; -import java.util.ServiceLoader; - import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.util.registry.GenericRegistry; +import com.raytheon.uf.common.util.registry.RegistryException; /** - * TODO Add Description + * Routes requests via {@link IRequestRouter}s. * *
  * 
@@ -36,7 +33,8 @@ import com.raytheon.uf.common.status.UFStatus.Priority;
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Dec 9, 2010            rjpeter     Initial creation
+ * Dec 9, 2010             rjpeter     Initial creation
+ * Nov 15, 2012 1322       djohnson    Add ability to route by server key.
  * 
  * 
* @@ -44,34 +42,92 @@ import com.raytheon.uf.common.status.UFStatus.Priority; * @version 1.0 */ -public class RequestRouter { - private static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(RequestRouter.class); - private static final IRequestRouter requestRouter; +public final class RequestRouter { + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(RequestRouter.class); - static { - // lookup router via service loader - ServiceLoader loader = ServiceLoader.load( - IRequestRouter.class, RequestRouter.class.getClassLoader()); + static final String REQUEST_SERVICE = "request.server"; - Iterator iter = loader.iterator(); - IRequestRouter tmp = null; - try { - if (iter.hasNext()) { - tmp = iter.next(); + /** + * {@link GenericRegistry} implementation that holds {@link IRequestRouter} + * instances keyed by their server. Intentionally package-private. + */ + static class RouterRegistry extends GenericRegistry { + + /** + * {@inheritDoc} + */ + @Override + public Object register(String t, IRequestRouter s) + throws RegistryException { + if (registry.containsKey(t)) { + throw new RegistryException("Unable to register router", + new IllegalStateException( + "IRequestRouter of type [" + + s.getClass().getName() + + "] already registered for key [" + t + "]")); } - } catch (ServiceConfigurationError e) { - statusHandler.handle( - Priority.FATAL, - "No Service Handler found for " - + IRequestRouter.class.getName() - + ". Unable to route requests to server."); - throw e; + return super.register(t, s); } + + /** + * Clear the registry. Intentionally package-private so it can be cleared by test code. + */ + void clear() { + registry.clear(); + } + }; + + private static final RouterRegistry routerRegistry = new RouterRegistry(); - requestRouter = tmp; + /** + * Disabled constructor. + */ + private RequestRouter() { } + /** + * Get the router registry. + * + * @return the registry for routers + */ + public static RouterRegistry getRouterRegistry() { + return routerRegistry; + } + + /** + * Route a request to the request service router. + * + * @param request + * the request + * @return the response + * @throws Exception + */ public static Object route(IServerRequest request) throws Exception { - return requestRouter.route(request); + return route(request, REQUEST_SERVICE); + } + + /** + * Route a request using the router registered for the specific service. + * + * @param request + * the request + * @param service + * the service name + * @return the response + * @throws Exception + */ + public static Object route(IServerRequest request, String service) + throws Exception { + final IRequestRouter router = routerRegistry.getRegisteredObject(service); + if (router == null) { + statusHandler + .error("There is no registered router for service [" + + service + + "]. Routing to the request service, but the request may not be able to be processed!"); + return route(request); + } else { + return router.route(request); + } } } diff --git a/edexOsgi/com.raytheon.uf.common.serialization/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.serialization/META-INF/MANIFEST.MF index 92942f1f33..c45eeae5b7 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.serialization/META-INF/MANIFEST.MF @@ -11,7 +11,8 @@ Require-Bundle: com.facebook.thrift, javax.persistence, org.geotools, javax.measure;resolution:=optional, - com.raytheon.uf.common.util + com.raytheon.uf.common.util, + org.apache.commons.codec;bundle-version="1.4.0" Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.common.serialization, com.raytheon.uf.common.serialization.adapters, diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BaseSerializationContext.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BaseSerializationContext.java new file mode 100644 index 0000000000..9d9b72d483 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BaseSerializationContext.java @@ -0,0 +1,72 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.serialization; + + +/** + * Provides reusable functionality among {@link ISerializationContext} + * implementations. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 14, 2012 1169       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public abstract class BaseSerializationContext implements + ISerializationContext, IDeserializationContext { + protected final DynamicSerializationManager serializationManager; + + /** + * Constructor. + * + * @param serializationManager + * the serialization manager + */ + public BaseSerializationContext( + DynamicSerializationManager serializationManager) { + this.serializationManager = serializationManager; + } + + /** + * {@inheritDoc} + */ + @Override + public Object readObject() throws SerializationException { + return this.serializationManager.deserialize(this); + } + + /** + * {@inheritDoc} + * + * @throws SerializationException + */ + @Override + public void writeObject(Object obj) throws SerializationException { + this.serializationManager.serialize(this, obj); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BuiltInTypeSupport.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BuiltInTypeSupport.java index 9aa034d9ef..8f694f3a35 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BuiltInTypeSupport.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/BuiltInTypeSupport.java @@ -20,11 +20,19 @@ package com.raytheon.uf.common.serialization; import java.math.BigDecimal; +import java.math.BigInteger; import java.sql.Timestamp; import java.util.Calendar; import java.util.Date; +import java.util.GregorianCalendar; import java.util.TimeZone; +import javax.xml.datatype.DatatypeConfigurationException; +import javax.xml.datatype.DatatypeFactory; +import javax.xml.datatype.Duration; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + /** * Provides serialization support for certain Java built-in classes * @@ -32,7 +40,11 @@ import java.util.TimeZone; * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Sep 3, 2008 #1448 chammack Initial creation + * Sep 03, 2008 #1448 chammack Initial creation + * Mar 27, 2012 #428 dgilling Add support for built-in + * classes used by data delivery's + * registry service. + * Sep 14, 2012 #1169 djohnson Add {@link ThrowableSerializer}. *
* * @author chammack @@ -130,6 +142,45 @@ public class BuiltInTypeSupport { } } + /** + * Serialization for {@link javax.xml.datatype.XMLGregorianCalendar} + * + * + * @author dgilling + * @version 1.0 + */ + public static class XMLGregorianCalendarSerializer implements + ISerializationTypeAdapter { + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.edex.esb.serialize.ISerializationFactory#deserialize + * (com.raytheon.edex.esb.serialize.ISerializer) + */ + @Override + public XMLGregorianCalendar deserialize(IDeserializationContext arg0) + throws SerializationException { + try { + long t = arg0.readI64(); + GregorianCalendar c = new GregorianCalendar( + TimeZone.getTimeZone("GMT")); + c.setTimeInMillis(t); + return DatatypeFactory.newInstance().newXMLGregorianCalendar(c); + } catch (DatatypeConfigurationException e) { + throw new SerializationException(e); + } + } + + @Override + public void serialize(ISerializationContext arg0, + XMLGregorianCalendar arg1) throws SerializationException { + long t = arg1.toGregorianCalendar().getTimeInMillis(); + arg0.writeI64(t); + } + } + public static class SqlDateSerializer implements ISerializationTypeAdapter { @@ -183,4 +234,126 @@ public class BuiltInTypeSupport { } } + + public static class BigIntegerSerializer implements + ISerializationTypeAdapter { + + /* + * (non-Javadoc) + * + * @seecom.raytheon.uf.common.serialization.ISerializationTypeAdapter# + * deserialize + * (com.raytheon.uf.common.serialization.IDeserializationContext) + */ + @Override + public BigInteger deserialize(IDeserializationContext deserializer) + throws SerializationException { + return new BigInteger(deserializer.readBinary()); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.serialization.ISerializationTypeAdapter#serialize + * (com.raytheon.uf.common.serialization.ISerializationContext, + * java.lang.Object) + */ + @Override + public void serialize(ISerializationContext serializer, + BigInteger object) throws SerializationException { + serializer.writeBinary(object.toByteArray()); + } + } + + /** + * Serialization for {@link javax.xml.datatype.Duration} + * + * + * @author dgilling + * @version 1.0 + */ + public static class DurationSerializer implements + ISerializationTypeAdapter { + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.edex.esb.serialize.ISerializationFactory#deserialize + * (com.raytheon.edex.esb.serialize.ISerializer) + */ + @Override + public Duration deserialize(IDeserializationContext arg0) + throws SerializationException { + try { + String durationStr = arg0.readString(); + return DatatypeFactory.newInstance().newDuration(durationStr); + } catch (DatatypeConfigurationException e) { + throw new SerializationException(e); + } + } + + @Override + public void serialize(ISerializationContext arg0, Duration arg1) + throws SerializationException { + arg0.writeString(arg1.toString()); + } + } + + /** + * Serialization for {@link javax.xml.namespace.QName} + * + * + * @author dgilling + * @version 1.0 + */ + public static class QNameSerializer implements + ISerializationTypeAdapter { + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.edex.esb.serialize.ISerializationFactory#deserialize + * (com.raytheon.edex.esb.serialize.ISerializer) + */ + @Override + public QName deserialize(IDeserializationContext arg0) + throws SerializationException { + return QName.valueOf(arg0.readString()); + } + + @Override + public void serialize(ISerializationContext arg0, QName arg1) + throws SerializationException { + arg0.writeString(arg1.toString()); + } + } + + /** + * Serializes a {@link Throwable} and deserializes it into a + * {@link Throwable}. + * + * NOTE: The deserialized object is NOT an instance of the original + * throwable type, rather it is an instance of + * {@link SerializableExceptionWrapper} whose toString() and getMessage() + * methods will return the same value as the original. + */ + public static class ThrowableSerializer implements + ISerializationTypeAdapter { + @Override + public void serialize(ISerializationContext serializer, Throwable object) + throws SerializationException { + serializer.writeObject(ExceptionWrapper.wrapThrowable(object)); + } + + @Override + public Throwable deserialize(IDeserializationContext deserializer) + throws SerializationException { + return ExceptionWrapper + .unwrapThrowable(SerializableExceptionWrapper.class + .cast(deserializer.readObject())); + } + } } diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/DynamicSerializationManager.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/DynamicSerializationManager.java index f2e5ddc33b..075ad03b2f 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/DynamicSerializationManager.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/DynamicSerializationManager.java @@ -26,6 +26,7 @@ import java.io.OutputStream; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; +import java.math.BigInteger; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.FloatBuffer; @@ -42,6 +43,9 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import javax.xml.datatype.Duration; +import javax.xml.namespace.QName; + import net.sf.cglib.beans.BeanMap; import org.geotools.coverage.grid.GeneralGridGeometry; @@ -67,6 +71,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeTypeAdap import com.raytheon.uf.common.serialization.thrift.ThriftSerializationContext; import com.raytheon.uf.common.serialization.thrift.ThriftSerializationContextBuilder; import com.raytheon.uf.common.util.ByteArrayOutputStreamPool; +import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; @@ -77,12 +82,17 @@ import com.vividsolutions.jts.geom.Geometry; * *
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * Aug 13, 2008	#1448		chammack	Initial creation
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * Aug 13, 2008 #1448       chammack    Initial creation
+ * Mar 27, 2012 #428        dgilling    Add support for built-in
+ *                                      classes used by data delivery's
+ *                                      registry service.
+ * Sep 28, 2012 #1195       djohnson    Add ability to specify adapter at field level.
  * Oct 08, 2012 #1251       dgilling    Ensure type registered with
  *                                      serialization adapter is encoded
  *                                      in serialization stream.
+ * Nov 02, 2012 1302        djohnson    Remove field level adapters, they break python serialization.
  * 
  * 
* @@ -113,6 +123,8 @@ public class DynamicSerializationManager { // TODO: Can the registration of adapters that require dependencies be // moved to a separate plugin somehow? registerAdapter(GregorianCalendar.class, new CalendarSerializer()); + registerAdapter(XMLGregorianCalendarImpl.class, + new BuiltInTypeSupport.XMLGregorianCalendarSerializer()); registerAdapter(Date.class, new DateSerializer()); registerAdapter(Timestamp.class, new TimestampSerializer()); registerAdapter(java.sql.Date.class, @@ -121,12 +133,19 @@ public class DynamicSerializationManager { registerAdapter(Coordinate.class, new CoordAdapter()); registerAdapter(BigDecimal.class, new BuiltInTypeSupport.BigDecimalSerializer()); + registerAdapter(BigInteger.class, + new BuiltInTypeSupport.BigIntegerSerializer()); registerAdapter(Geometry.class, new GeometryTypeAdapter()); registerAdapter(Envelope.class, new JTSEnvelopeAdapter()); registerAdapter(GridGeometry2D.class, new GridGeometry2DAdapter()); registerAdapter(GeneralGridGeometry.class, new GridGeometryAdapter()); registerAdapter(EnumSet.class, new EnumSetAdapter()); registerAdapter(StackTraceElement.class, new StackTraceElementAdapter()); + registerAdapter(Duration.class, + new BuiltInTypeSupport.DurationSerializer()); + registerAdapter(QName.class, new BuiltInTypeSupport.QNameSerializer()); + registerAdapter(Throwable.class, + new BuiltInTypeSupport.ThrowableSerializer()); // These two are OBE by BufferAdapter and should be deleted sometime registerAdapter(ByteBuffer.class, new ByteBufferAdapter()); registerAdapter(FloatBuffer.class, new FloatBufferAdapter()); @@ -479,5 +498,4 @@ public class DynamicSerializationManager { return sm; } - -} \ No newline at end of file +} diff --git a/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/util/ExceptionWrapper.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ExceptionWrapper.java similarity index 94% rename from edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/util/ExceptionWrapper.java rename to edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ExceptionWrapper.java index 6b460f8c6b..da8527f8bb 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/util/ExceptionWrapper.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ExceptionWrapper.java @@ -17,9 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.serialization.comm.util; - -import com.raytheon.uf.common.serialization.SerializableExceptionWrapper; +package com.raytheon.uf.common.serialization; /** * Class used to wrap/unwrap throwables in a serializable form to be transported @@ -31,6 +29,7 @@ import com.raytheon.uf.common.serialization.SerializableExceptionWrapper; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 10, 2009 mschenke Initial creation + * Sep 14, 2012 1169 djohnson Moved to com.raytheon.uf.common.serialization * *
* diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/IDeserializationContext.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/IDeserializationContext.java index 5e546f9200..8acfd9ed24 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/IDeserializationContext.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/IDeserializationContext.java @@ -24,9 +24,10 @@ package com.raytheon.uf.common.serialization; * *
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
+ * Date	        Ticket#     Engineer    Description
  * ------------	----------	-----------	--------------------------
- * Aug 12, 2008				chammack	Initial creation
+ * Aug 12, 2008             chammack    Initial creation
+ * Sep 14, 2012 1169        djohnson    Added readObject().
  * 
  * 
* @@ -41,7 +42,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract boolean readBool() throws SerializationException; + boolean readBool() throws SerializationException; /** * Read a byte @@ -49,7 +50,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract byte readByte() throws SerializationException; + byte readByte() throws SerializationException; /** * Read a short @@ -57,7 +58,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract short readI16() throws SerializationException; + short readI16() throws SerializationException; /** * Read an int @@ -65,7 +66,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract int readI32() throws SerializationException; + int readI32() throws SerializationException; /** * Read a long @@ -73,7 +74,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract long readI64() throws SerializationException; + long readI64() throws SerializationException; /** * Read a double @@ -81,7 +82,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract double readDouble() throws SerializationException; + double readDouble() throws SerializationException; /** * Read a double array @@ -89,7 +90,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract double[] readDoubleArray() throws SerializationException; + double[] readDoubleArray() throws SerializationException; /** * Read a float @@ -97,7 +98,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract float readFloat() throws SerializationException; + float readFloat() throws SerializationException; /** * Read a string @@ -105,7 +106,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract String readString() throws SerializationException; + String readString() throws SerializationException; /** * Read a binary blob @@ -113,7 +114,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract byte[] readBinary() throws SerializationException; + byte[] readBinary() throws SerializationException; /** * Read a float array @@ -121,7 +122,7 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract float[] readFloatArray() throws SerializationException; + float[] readFloatArray() throws SerializationException; /** * Read a message header @@ -129,13 +130,21 @@ public interface IDeserializationContext { * @return * @throws SerializationException */ - public abstract String readMessageStart() throws SerializationException; + String readMessageStart() throws SerializationException; /** * Read a message footer * * @throws SerializationException */ - public abstract void readMessageEnd() throws SerializationException; + void readMessageEnd() throws SerializationException; + /** + * Read an object. + * + * @return the read object + * + * @throws SerializationException + */ + Object readObject() throws SerializationException; } diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ISerializationContext.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ISerializationContext.java index 5fda8c537a..2ea75e5a18 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ISerializationContext.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/ISerializationContext.java @@ -24,9 +24,10 @@ package com.raytheon.uf.common.serialization; * *
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * Aug 7, 2008				chammack	Initial creation
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * Aug 07, 2008             chammack    Initial creation
+ * Sep 14, 2012 1169        djohnson    Added writeObject(OBject).
  * 
  * 
* @@ -42,7 +43,7 @@ public interface ISerializationContext { * @param b * @throws SerializationException */ - public abstract void writeBool(boolean b) throws SerializationException; + void writeBool(boolean b) throws SerializationException; /** * Write a byte @@ -50,7 +51,7 @@ public interface ISerializationContext { * @param b * @throws SerializationException */ - public abstract void writeByte(byte b) throws SerializationException; + void writeByte(byte b) throws SerializationException; /** * Write a short @@ -58,7 +59,7 @@ public interface ISerializationContext { * @param i16 * @throws SerializationException */ - public abstract void writeI16(short i16) throws SerializationException; + void writeI16(short i16) throws SerializationException; /** * Write an int @@ -66,7 +67,7 @@ public interface ISerializationContext { * @param i32 * @throws SerializationException */ - public abstract void writeI32(int i32) throws SerializationException; + void writeI32(int i32) throws SerializationException; /** * Write a long @@ -74,7 +75,7 @@ public interface ISerializationContext { * @param i64 * @throws SerializationException */ - public abstract void writeI64(long i64) throws SerializationException; + void writeI64(long i64) throws SerializationException; /** * Write a double @@ -82,7 +83,7 @@ public interface ISerializationContext { * @param dub * @throws SerializationException */ - public abstract void writeDouble(double dub) throws SerializationException; + void writeDouble(double dub) throws SerializationException; /** * Write a double array @@ -90,7 +91,7 @@ public interface ISerializationContext { * @param dub * @throws SerializationException */ - public abstract void writeDoubleArray(double[] dubs) + void writeDoubleArray(double[] dubs) throws SerializationException; /** @@ -99,7 +100,7 @@ public interface ISerializationContext { * @param flt * @throws SerializationException */ - public abstract void writeFloat(float flt) throws SerializationException; + void writeFloat(float flt) throws SerializationException; /** * Write a string @@ -107,7 +108,7 @@ public interface ISerializationContext { * @param str * @throws SerializationException */ - public abstract void writeString(String str) throws SerializationException; + void writeString(String str) throws SerializationException; /** * Write a binary blob @@ -115,7 +116,7 @@ public interface ISerializationContext { * @param bin * @throws SerializationException */ - public abstract void writeBinary(byte[] bin) throws SerializationException; + void writeBinary(byte[] bin) throws SerializationException; /** * Write a float array @@ -123,7 +124,7 @@ public interface ISerializationContext { * @param floats * @throws SerializationException */ - public abstract void writeFloatArray(float[] floats) + void writeFloatArray(float[] floats) throws SerializationException; /** @@ -132,7 +133,7 @@ public interface ISerializationContext { * @param messageName * @throws SerializationException */ - public abstract void writeMessageStart(String messageName) + void writeMessageStart(String messageName) throws SerializationException; /** @@ -140,6 +141,14 @@ public interface ISerializationContext { * * @throws SerializationException */ - public abstract void writeMessageEnd() throws SerializationException; + void writeMessageEnd() throws SerializationException; + /** + * Write another object. + * + * @param obj + * the object + * @throws SerializationException + */ + void writeObject(Object obj) throws SerializationException; } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/GroupList.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/MapEntryType.java similarity index 57% rename from edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/GroupList.java rename to edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/MapEntryType.java index 8f6799ddfb..1fbc74d1a2 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/GroupList.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/MapEntryType.java @@ -17,47 +17,61 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.level.xml; +package com.raytheon.uf.common.serialization; + +import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; - -import com.raytheon.uf.common.serialization.ISerializableObject; -import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; -import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** - * List of group definitions. + * Used by Jaxb to represent a {@link Map.Entry}. * *
+ * 
  * SOFTWARE HISTORY
  * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Sep 03, 2009            rjpeter     Initial creation.
+ * Jul 31, 2012 955        djohnson     Initial creation
+ * 
  * 
* - * @author rjpeter + * @author djohnson * @version 1.0 */ -@DynamicSerialize -@XmlRootElement(name = "groupList", namespace = "group") + @XmlAccessorType(XmlAccessType.NONE) -@XmlType(namespace = "group") -public class GroupList implements ISerializableObject { - @DynamicSerializeElement - @XmlElement(name = "group") - private Group[] groups; +public class MapEntryType { - public Group[] getGroups() { - return groups; + @XmlElement + private K key; + + @XmlElement + private V value; + + public MapEntryType() { } - public void setGroups(Group[] groups) { - this.groups = groups; + public MapEntryType(Map.Entry e) { + key = e.getKey(); + value = e.getValue(); } + public K getKey() { + return key; + } + + public void setKey(K key) { + this.key = key; + } + + public V getValue() { + return value; + } + + public void setValue(V value) { + this.value = value; + } } diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/MapType.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/MapType.java new file mode 100644 index 0000000000..f70e7fb1fb --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/MapType.java @@ -0,0 +1,62 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.serialization; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Used by Jaxb to represent a {@link Map}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 31, 2012 955        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class MapType { + private List> entry = new ArrayList>(); + + public MapType() { + } + + public MapType(Map map) { + for (Map.Entry mapEntry : map.entrySet()) { + entry.add(new MapEntryType(mapEntry)); + } + } + + public List> getEntry() { + return entry; + } + + public void setEntry(List> entry) { + this.entry = entry; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableExceptionWrapper.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableExceptionWrapper.java index 2cf2293699..4463489d51 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableExceptionWrapper.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableExceptionWrapper.java @@ -32,6 +32,7 @@ import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Aug 10, 2009 mschenke Initial creation + * Sep 14, 2012 1169 djohnson Moved to com.raytheon.uf.common.serialization * *
* diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableManager.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableManager.java index 8e66da2368..fd973cd298 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableManager.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializableManager.java @@ -37,6 +37,7 @@ import java.util.Set; import javax.persistence.Embeddable; import javax.persistence.Entity; import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRegistry; import com.raytheon.uf.common.serialization.jaxb.JaxbDummyObject; @@ -298,7 +299,8 @@ public class SerializableManager { Class c = (Class) Class .forName(clazz, true, cl); boolean added = false; - if (c.getAnnotation(XmlAccessorType.class) != null) { + if (c.getAnnotation(XmlAccessorType.class) != null + || c.getAnnotation(XmlRegistry.class) != null) { addToClazzSet(c); added = true; } diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializationUtil.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializationUtil.java index 2cd17e7efd..c853ad84e1 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializationUtil.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/SerializationUtil.java @@ -40,6 +40,9 @@ import com.raytheon.uf.common.serialization.DynamicSerializationManager.Serializ * ------------ ---------- ----------- -------------------------- * Sep 24, 2008 chammack Initial creation * Nov 13, 2008 njensen Added thrift methods + * Sep 07, 2012 1102 djohnson Overload jaxbUnmarshall and transformFromThrift methods + * to accept class parameter, deprecate old versions. Improve performance + * of getJaxbManager(). * * * @@ -47,43 +50,79 @@ import com.raytheon.uf.common.serialization.DynamicSerializationManager.Serializ * @version 1.0 */ -public class SerializationUtil { +public final class SerializationUtil { - private static JAXBManager jaxbManager = null; + // @VisibleForTesting + static volatile JAXBManager jaxbManager; private SerializationUtil() { } - public static synchronized JAXBManager getJaxbManager() - throws JAXBException { - if (jaxbManager == null) { - List> jaxbClasses = SerializableManager - .getInstance().getJaxbables(); - jaxbManager = new JAXBManager( - jaxbClasses.toArray(new Class[jaxbClasses.size()])); - } - return jaxbManager; - } + /** + * Retrieve the {@link JAXBManager} instance. Lazily-initialized using + * proper double-checked locking. This version performs better than + * synchronizing the entire method. + * + * @return the {@link JAXBManager} + * @see http://en.wikipedia.org/wiki/Double-checked_locking + * @throws JAXBException + */ + public static JAXBManager getJaxbManager() throws JAXBException { + JAXBManager result = jaxbManager; + if (result == null) { + synchronized (SerializationUtil.class) { + result = jaxbManager; + if (result == null) { + List> jaxbClasses = SerializableManager + .getInstance().getJaxbables(); + jaxbManager = result = new JAXBManager( + jaxbClasses.toArray(new Class[jaxbClasses.size()])); + + } + } + } + return result; + } public static JAXBContext getJaxbContext() throws JAXBException { return getJaxbManager().getJaxbContext(); } - /** - * Instantiates an object from the XML representation in a string. Uses - * JAXB. - * - * @param xml - * The XML representation - * @return A new instance from the XML representation - * @throws JAXBException - */ + /** + * Instantiates an object from the XML representation in a string. Uses + * JAXB. + * + * @param xml + * The XML representation + * @return A new instance from the XML representation + * @throws JAXBException + * @deprecated Use {@link #unmarshalFromXml(Class, String)} which performs + * the cast for you, and wraps any {@link ClassCastException}s + * in a serialization exception + */ + @Deprecated public static Object unmarshalFromXml(String xml) throws JAXBException { - return getJaxbManager().unmarshalFromXml(xml); + return unmarshalFromXml(Object.class, xml); } + /** + * Instantiates an object from the XML representation in a string. Uses + * JAXB. + * + * @param clazz + * the class object of the result type + * @param xml + * The XML representation + * @return A new instance from the XML representation + * @throws JAXBException + */ + public static T unmarshalFromXml(Class clazz, String xml) + throws JAXBException { + return clazz.cast(getJaxbManager().unmarshalFromXml(xml)); + } + /** * Convert an instance of a class to an XML representation in a string. Uses * JAXB. @@ -117,58 +156,123 @@ public class SerializationUtil { } - /** - * Instantiates an object from the XML representation in a File. Uses JAXB. - * - * @param filePath - * The path to the XML file - * @return A new instance from the XML representation - * @throws SerializationException - */ + /** + * Instantiates an object from the XML representation in a File. Uses JAXB. + * + * @param filePath + * The path to the XML file + * @return A new instance from the XML representation + * @throws SerializationException + * @deprecated Use {@link #jaxbUnmarshalFromXmlFile(Class, String)} which + * performs the cast for you, and wraps any + * {@link ClassCastException}s in a serialization exception + */ + @Deprecated public static Object jaxbUnmarshalFromXmlFile(String filePath) throws SerializationException { - try { - return getJaxbManager().jaxbUnmarshalFromXmlFile(filePath); - } catch (JAXBException e) { - throw new SerializationException(e); - } + return jaxbUnmarshalFromXmlFile(Object.class, filePath); } - /** - * Instantiates an object from the XML representation in a File. Uses JAXB. - * - * @param filePath - * The XML file - * @return A new instance from the XML representation - * @throws SerializationException - */ + /** + * Instantiates an object from the XML representation in a File. Uses JAXB. + * + * @param clazz + * the result type class + * @param filePath + * The path to the XML file + * @return A new instance from the XML representation + * @throws SerializationException + * + */ + public static T jaxbUnmarshalFromXmlFile(Class clazz, String filePath) + throws SerializationException { + try { + return clazz.cast(getJaxbManager().jaxbUnmarshalFromXmlFile( + filePath)); + } catch (JAXBException e) { + throw new SerializationException(e); + } + } + + /** + * Instantiates an object from the XML representation in a File. Uses JAXB. + * + * @param filePath + * The XML file + * @return A new instance from the XML representation + * @throws SerializationException + * @deprecated Use {@link #jaxbUnmarshalFromXmlFile(Class, File)} which + * performs the cast for you, and wraps any + * {@link ClassCastException}s in a serialization exception + */ + @Deprecated public static Object jaxbUnmarshalFromXmlFile(File file) throws SerializationException { - try { - return getJaxbManager().jaxbUnmarshalFromXmlFile(file); - } catch (Exception e) { - throw new SerializationException(e.getLocalizedMessage(), e); - } + return jaxbUnmarshalFromXmlFile(Object.class, file); } - /** - * Instantiates an object from the XML representation in a stream. Uses - * JAXB. - * - * @param is - * The input stream. The stream will be closed by this operation. - * @return A new instance from the XML representation - * @throws SerializationException - */ + /** + * Instantiates an object from the XML representation in a File. Uses JAXB. + * + * @param clazz + * the clazz object used to dynamically cast the result + * @param filePath + * The XML file + * @return A new instance from the XML representation + * @throws SerializationException + * if JAXB encounters an exception, or a + * {@link ClassCastException} occurs + */ + public static T jaxbUnmarshalFromXmlFile(Class clazz, File file) + throws SerializationException { + try { + return clazz.cast(getJaxbManager().jaxbUnmarshalFromXmlFile(file)); + } catch (Exception e) { + throw new SerializationException(e.getLocalizedMessage(), e); + } + } + + /** + * Instantiates an object from the XML representation in a stream. Uses + * JAXB. + * + * @param is + * The input stream. The stream will be closed by this operation. + * @return A new instance from the XML representation + * @throws SerializationException + * @deprecated Use {@link #jaxbUnmarshalFromInputStream(Class, InputStream)} + * which performs the cast for you, and wraps any + * {@link ClassCastException}s in a serialization exception + */ + @Deprecated public static Object jaxbUnmarshalFromInputStream(InputStream is) throws SerializationException { - try { - return getJaxbManager().jaxbUnmarshalFromInputStream(is); - } catch (Exception e) { - throw new SerializationException(e.getLocalizedMessage(), e); - } + return jaxbUnmarshalFromInputStream(Object.class, is); } + /** + * Instantiates an object from the XML representation in a stream. Uses + * JAXB. + * + * @param clazz + * the class object of the result type + * @param is + * The input stream. The stream will be closed by this operation. + * @return A new instance from the XML representation + * @throws SerializationException + * + */ + public static T jaxbUnmarshalFromInputStream(Class clazz, + InputStream is) + throws SerializationException { + try { + return clazz + .cast(getJaxbManager().jaxbUnmarshalFromInputStream(is)); + } catch (Exception e) { + throw new SerializationException(e.getLocalizedMessage(), e); + } + } + /** * Transforms an object to the thrift protocol using DynamicSerialize. The * object will exist in memory 3 times during this process: once in its @@ -207,32 +311,52 @@ public class SerializationUtil { dsm.serialize(obj, os); } - /** - * Transforms a byte array from the thrift protocol to an object using - * DynamicSerialize - * - * @param bytes - * the object as bytes - * @return the Java object - * @throws SerializationException - */ - public static Object transformFromThrift(byte[] bytes) + /** + * Transforms a byte array from the thrift protocol to an object using + * DynamicSerialize + * + * @param bytes + * the object as bytes + * @return the Java object + * @throws SerializationException + * @deprecated Use {@link #transformFromThrift(Class, byte[]) which performs + * the cast for you, and wraps any {@link ClassCastException}s + * in a serialization exception + */ + @Deprecated + public static Object transformFromThrift(byte[] bytes) throws SerializationException { - DynamicSerializationManager dsm = DynamicSerializationManager - .getManager(SerializationType.Thrift); - ByteArrayInputStream bais = null; - try { - bais = new ByteArrayInputStream(bytes); - return dsm.deserialize(bais); - } finally { - if (bais != null) { - try { - bais.close(); - } catch (IOException e) { - // ignore - } - } - } + return transformFromThrift(Object.class, bytes); } + /** + * Transforms a byte array from the thrift protocol to an object using + * DynamicSerialize + * + * @param bytes + * the object as bytes + * @return the Java object + * @throws SerializationException + * if a serialization or class cast exception occurs + */ + public static T transformFromThrift(Class clazz, byte[] bytes) + throws SerializationException { + DynamicSerializationManager dsm = DynamicSerializationManager + .getManager(SerializationType.Thrift); + ByteArrayInputStream bais = null; + try { + bais = new ByteArrayInputStream(bytes); + return clazz.cast(dsm.deserialize(bais)); + } catch (ClassCastException cce) { + throw new SerializationException(cce); + } finally { + if (bais != null) { + try { + bais.close(); + } catch (IOException e) { + // ignore + } + } + } + } } diff --git a/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/util/WrappedException.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/WrappedException.java similarity index 88% rename from edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/util/WrappedException.java rename to edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/WrappedException.java index 14dc344932..21d09ef066 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization.comm/src/com/raytheon/uf/common/serialization/comm/util/WrappedException.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/WrappedException.java @@ -17,7 +17,7 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.serialization.comm.util; +package com.raytheon.uf.common.serialization; /** * Wrapped exception, prints the original exception @@ -27,7 +27,8 @@ package com.raytheon.uf.common.serialization.comm.util; * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Jul 9, 2010 mschenke Initial creation + * Jul 09, 2010 mschenke Initial creation + * Sep 14, 2012 1169 djohnson Moved to com.raytheon.uf.common.serialization * * * @@ -39,7 +40,7 @@ public class WrappedException extends Exception { private static final long serialVersionUID = 1L; - private String exceptionClass; + private final String exceptionClass; /** * @param message diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/XmlGenericMapAdapter.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/XmlGenericMapAdapter.java new file mode 100644 index 0000000000..d124696c39 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/XmlGenericMapAdapter.java @@ -0,0 +1,69 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.serialization; + +import java.util.HashMap; +import java.util.Map; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +/** + * Handles the conversion between Java {@link Map} classes to Jaxb usable + * {@link MapType} classes. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 31, 2012 955        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public class XmlGenericMapAdapter extends + XmlAdapter, Map> { + + @Override + public Map unmarshal(MapType serialized) throws Exception { + HashMap map = new HashMap(); + + for (MapEntryType mapEntryType : serialized.getEntry()) { + map.put(mapEntryType.getKey(), mapEntryType.getValue()); + } + return map; + } + + @Override + public MapType marshal(Map unserialized) throws Exception { + MapType mapType = new MapType(); + + for (Map.Entry entry : unserialized.entrySet()) { + MapEntryType mapEntryType = new MapEntryType(); + mapEntryType.setKey(entry.getKey()); + mapEntryType.setValue(entry.getValue()); + mapType.getEntry().add(mapEntryType); + } + return mapType; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/annotations/DynamicSerializeElement.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/annotations/DynamicSerializeElement.java index e6c3845e51..3fd3bd75ac 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/annotations/DynamicSerializeElement.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/annotations/DynamicSerializeElement.java @@ -25,6 +25,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import com.raytheon.uf.common.serialization.ISerializationTypeAdapter; + /** * An annotation that indicates that a class should have this element * serialized. @@ -32,18 +34,24 @@ import java.lang.annotation.Target; * The annotation should be added to the field itself. The assumption is made * that setters and getters are available for this property. * + * If the {@link #value()} specifies an {@link ISerializationTypeAdapter}, the + * factory will be used to serialize/deserialize the value. + * *
+ * 
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * Aug 7, 2008				chammack	Initial creation
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 07, 2008            chammack    Initial creation
+ * Sep 28, 2012 1195       djohnson    Add value() to specify a type adapter.
+ * Nov 02, 2012 1302       djohnson    No more field level adapters.
  * 
  * 
* - * @author chammack + * @author dgilling * @version 1.0 */ - @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @Documented diff --git a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/thrift/ThriftSerializationContext.java b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/thrift/ThriftSerializationContext.java index 6a96c50acc..c2b41b87b1 100644 --- a/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/thrift/ThriftSerializationContext.java +++ b/edexOsgi/com.raytheon.uf.common.serialization/src/com/raytheon/uf/common/serialization/thrift/ThriftSerializationContext.java @@ -42,11 +42,10 @@ import com.facebook.thrift.protocol.TMessage; import com.facebook.thrift.protocol.TSet; import com.facebook.thrift.protocol.TStruct; import com.facebook.thrift.protocol.TType; +import com.raytheon.uf.common.serialization.BaseSerializationContext; import com.raytheon.uf.common.serialization.DynamicSerializationManager; import com.raytheon.uf.common.serialization.DynamicSerializationManager.EnclosureType; import com.raytheon.uf.common.serialization.DynamicSerializationManager.SerializationMetadata; -import com.raytheon.uf.common.serialization.IDeserializationContext; -import com.raytheon.uf.common.serialization.ISerializationContext; import com.raytheon.uf.common.serialization.ISerializationTypeAdapter; import com.raytheon.uf.common.serialization.SerializationCache; import com.raytheon.uf.common.serialization.SerializationException; @@ -59,11 +58,14 @@ import com.raytheon.uf.common.serialization.SerializationException; * *
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * Aug 12, 2008	#1448		chammack	Initial creation
- * Jun 17, 2010   #5091        njensen     Optimized primitive arrays
- * Mar 1, 2011                       njensen     Restructured deserializeArray()
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * Aug 12, 2008 #1448       chammack    Initial creation
+ * Jun 17, 2010 #5091       njensen     Optimized primitive arrays
+ * Mar 01, 2011             njensen     Restructured deserializeArray()
+ * Sep 14, 2012 #1169       djohnson    Add ability to write another object into the stream directly.
+ * Sep 28, 2012 #1195       djohnson    Add ability to specify adapter at field level.
+ * Nov 02, 2012 1302        djohnson    No more field level adapters.
  * 
  * 
* @@ -72,17 +74,14 @@ import com.raytheon.uf.common.serialization.SerializationException; */ // Warnings are suppressed in this class because generics cause issues with the // extensive use of reflection. The erased objects are used instead. -@SuppressWarnings("unchecked") -public class ThriftSerializationContext implements ISerializationContext, - IDeserializationContext { +@SuppressWarnings({ "unchecked", "rawtypes" }) +public class ThriftSerializationContext extends BaseSerializationContext { /** The tag that is used to indicate the value of an enumeration */ private static final String ENUM_VALUE_TAG = "__enumValue__"; private final SelfDescribingBinaryProtocol protocol; - private final DynamicSerializationManager serializationManager; - private static Map, Byte> types; private static Map> fieldClass = new ConcurrentHashMap>(); @@ -115,8 +114,9 @@ public class ThriftSerializationContext implements ISerializationContext, */ public ThriftSerializationContext(SelfDescribingBinaryProtocol protocol, DynamicSerializationManager serializationManager) { + super(serializationManager); + this.protocol = protocol; - this.serializationManager = serializationManager; } /* @@ -718,10 +718,6 @@ public class ThriftSerializationContext implements ISerializationContext, field.name = keyStr; protocol.writeFieldBegin(field); - // if (adapter != null) { - // // If there is an adapter, use it to serialize - // adapter.serialize(this, val); - // } else if (type != TType.VOID) { // Otherwise, as long as it's not void, use basic type serialization serializeType(val, valClass, type); @@ -851,9 +847,6 @@ public class ThriftSerializationContext implements ISerializationContext, FastClass fc, BeanMap bm) throws TException, SerializationException { TField field = protocol.readFieldBegin(); - // System.out.println(field.type); - // ISerializationTypeAdapter factory = md.attributesWithFactories - // .get(field.name); Object obj = null; if (field.type == TType.STOP) { @@ -861,12 +854,8 @@ public class ThriftSerializationContext implements ISerializationContext, } if (field.type != TType.VOID) { - // if (factory != null) { - // obj = factory.deserialize(this); - // } else { obj = deserializeType(field.type, o.getClass(), fc, field.name, EnclosureType.FIELD); - // } if (field.type == TType.STRING) { Class fieldClass = findFieldClass(o.getClass(), field.name); if (fieldClass != null && fieldClass.isEnum()) { @@ -895,7 +884,6 @@ public class ThriftSerializationContext implements ISerializationContext, * @return * @throws SerializationException */ - @SuppressWarnings("rawtypes") private Object deserializeType(byte type, Class clazz, FastClass fclazz, String fieldName, EnclosureType enclosureType) throws SerializationException { @@ -1102,7 +1090,6 @@ public class ThriftSerializationContext implements ISerializationContext, * @return * @throws SerializationException */ - @SuppressWarnings("rawtypes") private Object deserializeArray(FastClass fclazz, String fieldName) throws SerializationException { try { @@ -1363,5 +1350,4 @@ public class ThriftSerializationContext implements ISerializationContext, throw new SerializationException(e); } } - -} \ No newline at end of file +} diff --git a/edexOsgi/com.raytheon.uf.common.site/src/com/raytheon/uf/common/site/notify/ClusterActivationNotification.java b/edexOsgi/com.raytheon.uf.common.site/src/com/raytheon/uf/common/site/notify/ClusterActivationNotification.java index cb3f933d4a..038c03c5e0 100644 --- a/edexOsgi/com.raytheon.uf.common.site/src/com/raytheon/uf/common/site/notify/ClusterActivationNotification.java +++ b/edexOsgi/com.raytheon.uf.common.site/src/com/raytheon/uf/common/site/notify/ClusterActivationNotification.java @@ -71,23 +71,23 @@ public class ClusterActivationNotification extends SiteActivationNotification { } public String toString() { - StringBuffer buffer = new StringBuffer(); + StringBuilder buffer = new StringBuilder(); if (isActivation()) { if (isFailure()) { - buffer.append(this.getModifiedSite() - + " has failed to activate on some or all cluster memebers. See logs for details"); + buffer.append(this.getModifiedSite()); + buffer.append(" has failed to activate on some or all cluster members. See logs for details"); } else { - buffer.append(this.getModifiedSite() - + " has been successfully activated on all cluster members"); + buffer.append(this.getModifiedSite()); + buffer.append(" has been successfully activated on all cluster members"); } } else{ if (isFailure()) { - buffer.append(this.getModifiedSite() - + " has failed to deactivate on some or all cluster memebers. See logs for details"); + buffer.append(this.getModifiedSite()); + buffer.append(" has failed to deactivate on some or all cluster members. See logs for details"); } else { - buffer.append(this.getModifiedSite() - + " has been successfully deactivated on all cluster members"); + buffer.append(this.getModifiedSite()); + buffer.append(" has been successfully deactivated on all cluster members"); } } return buffer.toString(); diff --git a/edexOsgi/com.raytheon.uf.common.sounding/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.sounding/META-INF/MANIFEST.MF index eb127bece8..fe03e26a1c 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.sounding/META-INF/MANIFEST.MF @@ -15,8 +15,6 @@ Export-Package: com.raytheon.uf.common.sounding, com.raytheon.uf.common.sounding.adapter, com.raytheon.uf.common.sounding.util Import-Package: com.raytheon.uf.common.localization, - com.raytheon.uf.common.menus, - com.raytheon.uf.common.menus.xml, com.raytheon.uf.common.serialization, com.raytheon.uf.common.status, org.apache.commons.logging diff --git a/edexOsgi/com.raytheon.uf.common.sounding/build.properties b/edexOsgi/com.raytheon.uf.common.sounding/build.properties index 02bc25751f..34d2e4d2da 100644 --- a/edexOsgi/com.raytheon.uf.common.sounding/build.properties +++ b/edexOsgi/com.raytheon.uf.common.sounding/build.properties @@ -1,5 +1,4 @@ source.. = src/ output.. = bin/ bin.includes = META-INF/,\ - .,\ - res/spring/ + . diff --git a/edexOsgi/com.raytheon.uf.common.sounding/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.sounding/component-deploy.xml deleted file mode 100644 index 154d8ca27c..0000000000 --- a/edexOsgi/com.raytheon.uf.common.sounding/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/.classpath b/edexOsgi/com.raytheon.uf.common.spatial/.classpath similarity index 100% rename from edexOsgi/com.raytheon.uf.common.datastorage.remote/.classpath rename to edexOsgi/com.raytheon.uf.common.spatial/.classpath diff --git a/edexOsgi/com.raytheon.uf.common.spatial/.project b/edexOsgi/com.raytheon.uf.common.spatial/.project new file mode 100644 index 0000000000..f8fdc72bc1 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.spatial + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.spatial/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.spatial/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..295d77f55d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Thu Dec 02 10:55:26 CST 2010 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.spatial/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.spatial/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..5da49e577a --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/META-INF/MANIFEST.MF @@ -0,0 +1,16 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: com.raytheon.uf.common.spatial +Bundle-SymbolicName: com.raytheon.uf.common.spatial +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Export-Package: com.raytheon.uf.common.spatial.reprojection +Require-Bundle: org.apache.commons.lang;bundle-version="2.3.0", + org.apache.commons.logging;bundle-version="1.1.1", + org.geotools;bundle-version="2.6.4", + com.raytheon.uf.common.geospatial;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin;bundle-version="1.12.1174", + com.raytheon.uf.common.datastorage;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174" + diff --git a/edexOsgi/com.raytheon.uf.common.spatial/build.properties b/edexOsgi/com.raytheon.uf.common.spatial/build.properties new file mode 100644 index 0000000000..34d2e4d2da --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/build.properties @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/AbstractDataReprojector.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/AbstractDataReprojector.java new file mode 100644 index 0000000000..6d371973d6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/AbstractDataReprojector.java @@ -0,0 +1,150 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Jun 15, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.awt.image.DataBuffer; +import java.awt.image.WritableRaster; + +import javax.media.jai.RasterFactory; + +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.coverage.grid.GridCoverageFactory; +import org.geotools.geometry.jts.ReferencedEnvelope; + +import com.raytheon.uf.common.datastorage.Request; +import com.raytheon.uf.common.datastorage.records.IDataRecord; + +/** + * + * @author bclement + * @version 1.0 + */ +public abstract class AbstractDataReprojector { + + public static class RequestWrapper { + public Request req; + public ReferencedEnvelope env; + } + + /** + * Copy data record into geotools grid coverage object + * + * @param dataRecord + * datset + * @param env + * geographics bounds for dataset + * @return + * @throws Exception + */ + protected abstract GridCoverage2D getGridCoverage(IDataRecord dataRecord, + ReferencedEnvelope env) throws Exception; + + /** + * Copy data record into geotools grid coverage object + * + * @param dataRecord + * datset + * @param env + * geographics bounds for dataset + * @return + * @throws Exception + */ + protected abstract GridCoverage2D getMaskCoverage(IDataRecord dataRecord, + ReferencedEnvelope env) throws Exception; + + /** + * Extract data from geotools coverage object into data record object + * + * @param coverage + * @return + */ + protected abstract T extractData(GridCoverage2D coverage); + + /** + * Extract data from geotools coverage object into data record object with a + * mask for covering the non-data area. + * + * @param coverage + * @param maskCoverage + * @return + */ + protected abstract T extractData(GridCoverage2D coverage, + GridCoverage2D maskCoverage); + + /** + * Apply slab request to data record, returning result in a new data record + * object. + * + * @param dataRecord + * @param req + * @return + */ + protected abstract T getDataSlice(IDataRecord dataRecord, Request req); + + /** + * @param dataRecord + * @return true if this object can operate on native type of data record + */ + protected abstract boolean compatible(IDataRecord dataRecord); + + /** + * Apply point request to data record, returning result in a new data record + * object. + * + * @param record + * @param req + * @return + */ + protected abstract IDataRecord getDataPoints(IDataRecord record, Request req); + + /** + * Construct a new geotools grid coverage object using data buffer + * + * @param name + * name of coverage + * @param data + * raw data + * @param width + * @param height + * @param env + * geographic bounds of coverage + * @return + * @throws Exception + */ + public static GridCoverage2D constructGridCoverage(String name, + DataBuffer data, int width, int height, ReferencedEnvelope env) + throws Exception { + WritableRaster raster = RasterFactory.createBandedRaster(data, width, + height, width, new int[] { 0 }, new int[] { 0 }, null); + return new GridCoverageFactory().create(name, raster, env); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ByteDataReprojector.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ByteDataReprojector.java new file mode 100644 index 0000000000..bb0f55e88c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ByteDataReprojector.java @@ -0,0 +1,238 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * May 18, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.awt.Point; +import java.awt.image.DataBufferByte; +import java.awt.image.Raster; +import java.awt.image.RenderedImage; +import java.util.Arrays; + +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; + +import com.raytheon.uf.common.datastorage.Request; +import com.raytheon.uf.common.datastorage.records.ByteDataRecord; +import com.raytheon.uf.common.datastorage.records.IDataRecord; + +/** + * + * @author bclement + * @version 1.0 + */ +public class ByteDataReprojector extends + AbstractDataReprojector { + + protected byte fill = 0; + + protected byte dataMaskValue = -1; + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getGridCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getGridCoverage(IDataRecord record, + ReferencedEnvelope env) + throws Exception { + ByteDataRecord dataRecord = (ByteDataRecord) record; + byte[] data = dataRecord.getByteData(); + DataBufferByte buff = new DataBufferByte(data, data.length); + int x = (int) dataRecord.getSizes()[0]; + int y = (int) dataRecord.getSizes()[1]; + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getMaskCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getMaskCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + int x = (int) record.getSizes()[0]; + int y = (int) record.getSizes()[1]; + byte[] mask = new byte[x * y]; + Arrays.fill(mask, dataMaskValue); + DataBufferByte buff = new DataBufferByte(mask, mask.length); + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected ByteDataRecord extractData(GridCoverage2D coverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); + byte[] data = dataBuffer.getData(); + int height = raster.getHeight(); + int width = raster.getWidth(); + return new ByteDataRecord("", "", data, 2, new long[] { width, height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D, + * org.geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected ByteDataRecord extractData(GridCoverage2D coverage, + GridCoverage2D maskCoverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferByte dataBuffer = (DataBufferByte) raster.getDataBuffer(); + byte[] data = dataBuffer.getData(); + + // Extract mask + image = maskCoverage.getRenderedImage(); + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + dataBuffer = (DataBufferByte) raster.getDataBuffer(); + byte[] mask = dataBuffer.getData(); + + if (mask.length == data.length) { + for (int i = 0; i < data.length; ++i) { + if (mask[i] != dataMaskValue) { + data[i] = fill; + } + } + } + + int height = raster.getHeight(); + int width = raster.getWidth(); + return new ByteDataRecord("", "", data, 2, new long[] { width, height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getDataSlice(com + * .raytheon.uf.common.datastorage.records.IDataRecord, + * com.raytheon.uf.common.datastorage.Request) + */ + @Override + protected ByteDataRecord getDataSlice(IDataRecord record, Request req) { + ByteDataRecord dataRecord = (ByteDataRecord) record; + int[] max = req.getMaxIndexForSlab(); + int[] min = req.getMinIndexForSlab(); + int toWidth = max[0] - min[0]; + int toHeight = max[1] - min[1]; + byte[] from = dataRecord.getByteData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + byte[] to = new byte[toWidth * toHeight]; + for (int fromY = min[1], toY = 0; fromY < max[1]; ++fromY, ++toY) { + int toRow = toY * toWidth; + int fromRow = fromY * fromWidth; + for (int fromX = min[0], toX = 0; fromX < max[0]; ++fromX, ++toX) { + to[toRow + toX] = from[fromRow + fromX]; + } + } + long[] sizes = { toWidth, toHeight }; + return new ByteDataRecord("", "", to, 2, sizes); + } + + public byte getFill() { + return fill; + } + + public void setFill(byte fill) { + this.fill = fill; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.AbstractDataReprojector#compatible + * (com.raytheon.uf.common.datastorage.records.IDataRecord) + */ + @Override + protected boolean compatible(IDataRecord dataRecord) { + return dataRecord instanceof ByteDataRecord; + } + + @Override + protected IDataRecord getDataPoints(IDataRecord record, Request req) { + ByteDataRecord dataRecord = (ByteDataRecord) record; + byte[] from = dataRecord.getByteData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + Point[] points = req.getPoints(); + byte[] to = new byte[points.length]; + for (int i = 0; i < to.length; ++i) { + Point p = points[i]; + to[i] = from[p.y * fromWidth + p.x]; + } + return new ByteDataRecord("", "", to, 1, new long[] { to.length }); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/DataReprojector.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/DataReprojector.java new file mode 100644 index 0000000000..ae208ad2a2 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/DataReprojector.java @@ -0,0 +1,624 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * May 18, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.awt.Point; +import java.io.FileNotFoundException; +import java.util.Iterator; +import java.util.Set; + +import javax.media.jai.Interpolation; + +import org.apache.commons.lang.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.geotools.coverage.grid.GeneralGridEnvelope; +import org.geotools.coverage.grid.GridCoordinates2D; +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.coverage.grid.GridGeometry2D; +import org.geotools.coverage.grid.ViewType; +import org.geotools.coverage.processing.Operations; +import org.geotools.geometry.DirectPosition2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.opengis.geometry.DirectPosition; +import org.opengis.geometry.MismatchedDimensionException; +import org.opengis.metadata.spatial.PixelOrientation; +import org.opengis.referencing.FactoryException; +import org.opengis.referencing.ReferenceIdentifier; +import org.opengis.referencing.crs.CoordinateReferenceSystem; +import org.opengis.referencing.operation.MathTransform2D; +import org.opengis.referencing.operation.TransformException; + +import com.raytheon.uf.common.dataplugin.PluginException; +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.ByteDataRecord; +import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.datastorage.records.IntegerDataRecord; +import com.raytheon.uf.common.datastorage.records.ShortDataRecord; +import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.spatial.reprojection.AbstractDataReprojector.RequestWrapper; +import com.raytheon.uf.common.spatial.reprojection.KeyLocker.KeyLock; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Envelope; + +/** + * + * @author bclement + * @version 1.0 + */ +public class DataReprojector { + + protected IDataStore dataStore; + + protected String dataSetBase = "Data-"; + + protected String dataSet = "Data"; + + private AbstractDataReprojector _typeProjector; + + protected static Log log = LogFactory.getLog(DataReprojector.class); + + protected static KeyLocker locker = new KeyLocker(); + + public DataReprojector(IDataStore dataStore) { + this.dataStore = dataStore; + } + + /** + * @param group + * name of the datastore group that contains requested dataset + * @param spatial + * spatial object tied to requested dataset + * @param nativeEnv + * native bounds of dataset + * @param crs + * desired crs of returned data + * @param coords + * coordinates of requested data in requested crs + * @return null if any of the coordinates are out of the bounds of the grid + * geometry + * @throws Exception + */ + public IDataRecord getProjectedPoints(String group, ISpatialObject spatial, + ReferencedEnvelope nativeEnv, CoordinateReferenceSystem crs, + Coordinate[] coords) throws Exception { + // get envelope in requested projection + ReferencedEnvelope targetEnv = nativeEnv.transform(crs, true); + // get target grid geometry + GridGeometry2D geom = getGridGeometry(targetEnv, spatial.getNx(), + spatial.getNy()); + Point[] points = new Point[coords.length]; + for (int i = 0; i < points.length; ++i) { + Coordinate coord = coords[i]; + GridCoordinates2D point = getGridPoint(geom, coord); + int nx = spatial.getNx(); + int ny = spatial.getNy(); + // coordinate was out of bounds, bail + if (point.x < 0 || point.x > nx || point.y < 0 || point.y > ny) { + return null; + } + // need to repackage point due to pypies not knowing about + // gridcoordinates2d + points[i] = new Point(point); + } + String reprojectedDataset = buildDatasetName(crs); + Request req = Request.buildPointRequest(points); + return getDataRecordWithReproject(group, reprojectedDataset, spatial, + crs, req); + } + + /** + * @param group + * name of the datastore group that contains requested dataset + * @param reprojectedDataset + * dataset name for reprojected data + * @param spatial + * spatial object tied to requested dataset + * @param crs + * desired crs of returned data + * @param req + * datastore request object + * @return + * @throws Exception + */ + protected IDataRecord getDataRecordWithReproject(String group, + String reprojectedDataset, ISpatialObject spatial, + CoordinateReferenceSystem crs, Request req) throws Exception { + IDataRecord dataRecord; + // check if data has already been reprojected + if (!datasetExists(group, reprojectedDataset)) { + // it hasn't lock and reproject + dataRecord = reprojectLocked(group, reprojectedDataset, spatial, + crs, req); + } else { + // it has, just request the data + dataRecord = getDataRecord(group, reprojectedDataset, req); + } + return dataRecord; + } + + /** + * @param group + * name of the datastore group that contains requested dataset + * @param reprojectedDataset + * dataset name for reprojected data + * @param spatial + * spatial object tied to requested dataset + * @param crs + * desired crs of returned data + * @param req + * datastore request object + * @return + * @throws Exception + */ + protected IDataRecord reprojectLocked(String group, + String reprojectedDataset, ISpatialObject spatial, + CoordinateReferenceSystem crs, Request req) throws Exception { + KeyLock lock = null; + IDataRecord dataRecord; + try { + // get reproject lock + lock = locker.getLock(group + reprojectedDataset); + lock.lock(); + // recheck that dataset still doesn't exist + if (!datasetExists(group, reprojectedDataset)) { + // still not there, reproject + dataRecord = reprojectAndStore(spatial, group, crs, req); + } else { + // another thread created it, just grab it + dataRecord = getDataRecord(group, reprojectedDataset, req); + } + lock.unlock(); + return dataRecord; + } finally { + if (lock != null) { + lock.release(); + } + } + } + + /** + * @param group + * @param dataset + * @return true if dataset exists in datastore + * @throws FileNotFoundException + * @throws StorageException + */ + protected boolean datasetExists(String group, String dataset) + throws FileNotFoundException, StorageException { + String[] datasets = dataStore.getDatasets(group); + return ArrayUtils.contains(datasets, dataset); + } + + /** + * @param geom + * Grid geometry + * @param coord + * desired geographic coordinate + * @return grid point for coordinate + * @throws PluginException + */ + public static GridCoordinates2D getGridPoint(GridGeometry2D geom, + Coordinate coord) throws PluginException { + DirectPosition src = new DirectPosition2D(coord.x, coord.y); + DirectPosition inGrid = new DirectPosition2D(); + try { + MathTransform2D crsToGrid2D = geom + .getCRSToGrid2D(PixelOrientation.UPPER_LEFT); + crsToGrid2D.transform(src, inGrid); + } catch (Exception e) { + throw new PluginException("Unable to get grid point for geometry", + e); + } + // floor of grid points should be upper left of pixel + int x = (int) Math.floor(inGrid.getOrdinate(0)); + int y = (int) Math.floor(inGrid.getOrdinate(1)); + GridCoordinates2D rval = new GridCoordinates2D(x, y); + return rval; + } + + /** + * @param group + * name of the datastore group that contains requested dataset + * @param spatial + * spatial object tied to requested dataset + * @param nativeEnv + * native bounds of dataset + * @param targetEnv + * bounds of requested data + * @return null if target envelope is out of bounds for dataset + * @throws Exception + */ + public GridCoverage2D getReprojectedCoverage(String group, + ISpatialObject spatial, ReferencedEnvelope nativeEnv, + ReferencedEnvelope targetEnv) + throws Exception { + ReferencedDataRecord rep = getReprojected(group, spatial, nativeEnv, + targetEnv); + if (rep == null) { + return null; + } + ReferencedEnvelope re = rep.getEnvelope(); + IDataRecord record = rep.getRecord(); + return getTypeProjector(record).getGridCoverage(rep.getRecord(), re); + } + + /** + * @param group + * name of the datastore group that contains requested dataset + * @param spatial + * spatial object tied to requested dataset + * @param nativeEnvelope + * native bounds of dataset + * @param targetEnvelope + * bounds of requested data + * @return null if target envelope is out of bounds for dataset + * @throws Exception + */ + public ReferencedDataRecord getReprojected(String group, + ISpatialObject spatial, ReferencedEnvelope nativeEnvelope, + ReferencedEnvelope targetEnvelope) + throws Exception { + RequestWrapper req = getRequest(spatial, nativeEnvelope, targetEnvelope); + if (req == null) { + return null; + } + CoordinateReferenceSystem targetCrs = targetEnvelope + .getCoordinateReferenceSystem(); + String reprojectedDataset = buildDatasetName(targetCrs); + IDataRecord dataRecord = getDataRecordWithReproject(group, + reprojectedDataset, spatial, targetCrs, req.req); + return new ReferencedDataRecord(dataRecord, req.env); + } + + /** + * @param group + * name of the datastore group that contains requested dataset + * @param targetDataset + * dataset name for requested data + * @param req + * datastore request object + * @return + * @throws Exception + */ + protected IDataRecord getDataRecord(String group, String targetDataset, + Request req) throws Exception { + IDataRecord rval = dataStore.retrieve(group, targetDataset, req); + return rval; + } + + /** + * Get a projector that is compatible with record + * + * @param record + * @return + * @throws Exception + */ + protected AbstractDataReprojector getTypeProjector( + IDataRecord record) throws Exception { + if (_typeProjector == null || !_typeProjector.compatible(record)) { + if (record instanceof ByteDataRecord) { + _typeProjector = new ByteDataReprojector(); + } else if (record instanceof FloatDataRecord) { + _typeProjector = new FloatDataReprojector(); + } else if (record instanceof ShortDataRecord) { + _typeProjector = new ShortDataReprojector(); + } else if (record instanceof IntegerDataRecord) { + _typeProjector = new IntDataReprojector(); + } else { + throw new Exception("Unsupported data store type"); + } + } + return _typeProjector; + } + + /** + * Gets the entire coverage from the store and reprojects it. Reprojected + * coverage is then stored under a name derived from the projected crs. + * + * @param spatial + * spatial object tied to requested dataset + * @param group + * name of the datastore group that contains requested dataset + * @param targetCRS + * desired crs of returned data + * @param req + * datastore request object + * @return datarecord as per the request object + * @throws Exception + */ + protected IDataRecord reprojectAndStore(ISpatialObject spatial, + String group, CoordinateReferenceSystem targetCRS, Request req) + throws Exception { + GridGeometry2D geom = MapUtil.getGridGeometry(spatial); + IDataRecord original = getDataRecord(group, dataSet, Request.ALL); + ReferencedEnvelope env = new ReferencedEnvelope(geom.getEnvelope()); + AbstractDataReprojector typeProjector = getTypeProjector(original); + GridCoverage2D cov = typeProjector.getGridCoverage(original, env); + GridCoverage2D reprojected = MapUtil.reprojectCoverage(cov, targetCRS); + IDataRecord rval; + + if (typeProjector instanceof FloatDataReprojector) { + // TODO So far, the problem that this fixes has only appeared with + // float data. If it happens with other data we can change this. + GridCoverage2D maskCov = typeProjector.getMaskCoverage(original, + env); + GridCoverage2D reprojectedMask = (GridCoverage2D) Operations.DEFAULT + .resample(maskCov.view(ViewType.GEOPHYSICS), targetCRS, + null, Interpolation + .getInstance(Interpolation.INTERP_NEAREST)); + rval = typeProjector.extractData(reprojected, reprojectedMask); + } else { + rval = typeProjector.extractData(reprojected); + } + + rval.setGroup(group); + rval.setName(buildDatasetName(targetCRS)); + dataStore.addDataRecord(rval); + dataStore.store(); + return getDataPerReq(rval, req); + } + + /** + * @param record + * data record containing full coverage + * @param req + * datastore request object + * @return result of applying request object to data record + * @throws Exception + */ + protected IDataRecord getDataPerReq(IDataRecord record, Request req) + throws Exception { + AbstractDataReprojector typeProjector = getTypeProjector(record); + IDataRecord rval; + switch (req.getType()) { + case ALL: + rval = record; + break; + case POINT: + rval = typeProjector.getDataPoints(record, req); + break; + case SLAB: + rval = typeProjector.getDataSlice(record, req); + break; + case XLINE: + case YLINE: + default: + throw new Exception("Data reprojector " + req.getType() + + " not implemented"); + } + return rval; + } + + /** + * @param env + * geographic bounds of data + * @param nx + * length of x axis + * @param ny + * length of y axis + * @return + */ + public static GridGeometry2D getGridGeometry(ReferencedEnvelope env, + int nx, int ny) { + // TODO cache + GridGeometry2D mapGeom = null; + mapGeom = new GridGeometry2D(new GeneralGridEnvelope( + new int[] { 0, 0 }, new int[] { nx, ny }, false), env); + return mapGeom; + } + + /** + * Build up slice request for reprojected dataset + * + * @param record + * @param crs + * @param targetEnvelope + * bbox in crs + * @return null if envelope is outside of data bounds + * @throws TransformException + * @throws MismatchedDimensionException + * @throws FactoryException + */ + protected RequestWrapper getRequest(ISpatialObject spatial, + ReferencedEnvelope nativeEnv, ReferencedEnvelope targetEnvelope) + throws MismatchedDimensionException, + TransformException, FactoryException { + RequestWrapper rval = null; + CoordinateReferenceSystem targetCrs = targetEnvelope + .getCoordinateReferenceSystem(); + // get full bounds of reprojected dataset + ReferencedEnvelope dataEnv = nativeEnv.transform(targetCrs, true); + if (!dataEnv.intersects((Envelope) targetEnvelope)) { + // request and data envelopes are disjoint, return null + return null; + } + // get grid geometry for reprojected dataset + GridGeometry2D geom = getGridGeometry(dataEnv, spatial.getNx(), + spatial.getNy()); + int[] dims = { spatial.getNx(), spatial.getNy() }; + if (dataEnv.contains((Envelope) targetEnvelope)) { + // requested slice is entirely inside data bounds + // build slice based on requested bounds + rval = getSubSlice(geom, targetEnvelope, dims); + } else { + // build slice based on intersection + Envelope intersection = targetEnvelope.intersection(dataEnv); + rval = getSubSlice(geom, intersection, dims); + } + return rval; + } + + /** + * @param geom + * grid geometry for projected dataset + * @param env + * geographic bounds for slice + * @param dims + * dimensions of dataset + * @return grid slice that corresponds to env + * @throws MismatchedDimensionException + * @throws TransformException + */ + protected RequestWrapper getSubSlice(GridGeometry2D geom, Envelope env, + int[] dims) throws MismatchedDimensionException, TransformException { + RequestWrapper rval = new RequestWrapper(); + MathTransform2D crsToGrid2D = geom + .getCRSToGrid2D(PixelOrientation.UPPER_LEFT); + // find a slice that has data for entire envelope (can have extra) + int[][] minmax = transformEnv(crsToGrid2D, env, dims); + MathTransform2D gridToCrs = crsToGrid2D.inverse(); + // find an envelope that matches the slice (could be a bit larger than + // previous envelope) + rval.env = transformGrid(gridToCrs, minmax, + geom.getCoordinateReferenceSystem()); + rval.req = Request.buildSlab(minmax[0], minmax[1]); + return rval; + } + + /** + * @param gridToCrs + * @param minmax + * 2d array holding slice + * @param crs + * @return + * @throws MismatchedDimensionException + * @throws TransformException + */ + protected ReferencedEnvelope transformGrid(MathTransform2D gridToCrs, + int[][] minmax, CoordinateReferenceSystem crs) + throws MismatchedDimensionException, TransformException { + int[] min = minmax[0]; + int[] max = minmax[1]; + DirectPosition lower = new DirectPosition2D(min[0], min[1]); + DirectPosition upper = new DirectPosition2D(max[0], max[1]); + DirectPosition lowerCrs = gridToCrs.transform(lower, null); + DirectPosition upperCrs = gridToCrs.transform(upper, null); + double x0 = lowerCrs.getOrdinate(0); + double x1 = upperCrs.getOrdinate(0); + // handle y axis flip + double y0 = upperCrs.getOrdinate(1); + double y1 = lowerCrs.getOrdinate(1); + return new ReferencedEnvelope(x0, x1, y0, y1, crs); + } + + /** + * transforms crs coordinates to grid indexes using given math transform + * + * @param crsToGrid + * @param env + * @param dims + * max bounds to be limited to + * @return an array with [[minx, miny], [maxx, maxy]] + * @throws MismatchedDimensionException + * @throws TransformException + */ + protected int[][] transformEnv(MathTransform2D crsToGrid, Envelope env, + int[] dims) throws MismatchedDimensionException, TransformException { + DirectPosition lower = new DirectPosition2D(env.getMinX(), + env.getMinY()); + DirectPosition upper = new DirectPosition2D(env.getMaxX(), + env.getMaxY()); + DirectPosition lowerGrid = crsToGrid.transform(lower, null); + DirectPosition upperGrid = crsToGrid.transform(upper, null); + int x0 = (int) Math.floor(lowerGrid.getOrdinate(0)); + // we want ceiling since slices are inclusive + int x1 = (int) Math.ceil(upperGrid.getOrdinate(0)); + // handle y axis flip + int y0 = (int) Math.floor(upperGrid.getOrdinate(1)); + // we want ceiling since slices are inclusive + int y1 = (int) Math.ceil(lowerGrid.getOrdinate(1)); + // truncate requests to dataset dimensions + if (x0 < 0) { + x0 = 0; + } + if (y0 < 0) { + y0 = 0; + } + if (x1 > dims[0]) { + x1 = dims[0]; + } + if (y1 > dims[1]) { + y1 = dims[1]; + } + return new int[][] { { x0, y0 }, { x1, y1 } }; + } + + /** + * construct the dataset name based on the name of the crs. + * + * @param crs + * @return + */ + protected String buildDatasetName(CoordinateReferenceSystem crs) { + Set ids = crs.getIdentifiers(); + String code; + if (ids == null || ids.isEmpty()) { + code = crs.getName().toString(); + } else { + Iterator i = ids.iterator(); + code = i.next().toString(); + while (i.hasNext()) { + code += "-" + i.next().toString(); + } + } + return dataSetBase + code; + } + + public IDataStore getDataStore() { + return dataStore; + } + + public void setDataStore(IDataStore dataStore) { + this.dataStore = dataStore; + } + + public String getDataSetBase() { + return dataSetBase; + } + + public void setDataSetBase(String dataSetBase) { + this.dataSetBase = dataSetBase; + } + + public String getDataSet() { + return dataSet; + } + + public void setDataSet(String dataSet) { + this.dataSet = dataSet; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/FloatDataReprojector.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/FloatDataReprojector.java new file mode 100644 index 0000000000..4d1da89252 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/FloatDataReprojector.java @@ -0,0 +1,246 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Jun 13, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.awt.Point; +import java.awt.image.DataBufferFloat; +import java.awt.image.Raster; +import java.awt.image.RenderedImage; +import java.util.Arrays; + +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; + +import com.raytheon.uf.common.datastorage.Request; +import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.datastorage.records.IDataRecord; + +/** + * + * @author bclement + * @version 1.0 + */ +public class FloatDataReprojector extends + AbstractDataReprojector { + + protected float fill = -999999.0f; + + protected float dataMaskValue = -0; + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getGridCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getGridCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + FloatDataRecord dataRecord = (FloatDataRecord) record; + float[] data = dataRecord.getFloatData(); + DataBufferFloat buff = new DataBufferFloat(data, data.length); + int x = (int) dataRecord.getSizes()[0]; + int y = (int) dataRecord.getSizes()[1]; + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getMaskCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getMaskCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + int x = (int) record.getSizes()[0]; + int y = (int) record.getSizes()[1]; + float[] mask = new float[x * y]; + Arrays.fill(mask, dataMaskValue); + DataBufferFloat buff = new DataBufferFloat(mask, mask.length); + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected FloatDataRecord extractData(GridCoverage2D coverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferFloat dataBuffer = (DataBufferFloat) raster.getDataBuffer(); + float[] data = dataBuffer.getData(); + int height = raster.getHeight(); + int width = raster.getWidth(); + return new FloatDataRecord("", "", data, 2, + new long[] { width, height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D, + * org.geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected FloatDataRecord extractData(GridCoverage2D coverage, + GridCoverage2D maskCoverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferFloat dataBuffer = (DataBufferFloat) raster.getDataBuffer(); + float[] data = dataBuffer.getData(); + + // Extract mask + image = maskCoverage.getRenderedImage(); + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + dataBuffer = (DataBufferFloat) raster.getDataBuffer(); + float[] mask = dataBuffer.getData(); + + if (mask.length == data.length) { + for (int i = 0; i < data.length; ++i) { + if (mask[i] != dataMaskValue) { + data[i] = fill; + } + } + } + + int height = raster.getHeight(); + int width = raster.getWidth(); + return new FloatDataRecord("", "", data, 2, + new long[] { width, height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getDataSlice(com + * .raytheon.uf.common.datastorage.records.IDataRecord, + * com.raytheon.uf.common.datastorage.Request) + */ + @Override + protected FloatDataRecord getDataSlice(IDataRecord record, Request req) { + FloatDataRecord dataRecord = (FloatDataRecord) record; + int[] max = req.getMaxIndexForSlab(); + int[] min = req.getMinIndexForSlab(); + int toWidth = max[0] - min[0]; + int toHeight = max[1] - min[1]; + float[] from = dataRecord.getFloatData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + float[] to = new float[toWidth * toHeight]; + for (int fromY = min[1], toY = 0; fromY < max[1]; ++fromY, ++toY) { + int toRow = toY * toWidth; + int fromRow = fromY * fromWidth; + for (int fromX = min[0], toX = 0; fromX < max[0]; ++fromX, ++toX) { + to[toRow + toX] = from[fromRow + fromX]; + } + } + long[] sizes = { toWidth, toHeight }; + return new FloatDataRecord("", "", to, 2, sizes); + } + + /** + * @return the fill + */ + public float getFill() { + return fill; + } + + /** + * @param fill + * the fill to set + */ + public void setFill(float fill) { + this.fill = fill; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.AbstractDataReprojector#compatible + * (com.raytheon.uf.common.datastorage.records.IDataRecord) + */ + @Override + protected boolean compatible(IDataRecord dataRecord) { + return dataRecord instanceof FloatDataRecord; + } + + @Override + protected IDataRecord getDataPoints(IDataRecord record, Request req) { + FloatDataRecord dataRecord = (FloatDataRecord) record; + float[] from = dataRecord.getFloatData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + Point[] points = req.getPoints(); + float[] to = new float[points.length]; + for (int i = 0; i < to.length; ++i) { + Point p = points[i]; + to[i] = from[p.y * fromWidth + p.x]; + } + return new FloatDataRecord("", "", to, 1, new long[] { to.length }); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/IntDataReprojector.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/IntDataReprojector.java new file mode 100644 index 0000000000..384c15466c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/IntDataReprojector.java @@ -0,0 +1,247 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Jun 13, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.awt.Point; +import java.awt.image.DataBuffer; +import java.awt.image.DataBufferInt; +import java.awt.image.Raster; +import java.awt.image.RenderedImage; +import java.util.Arrays; + +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; + +import com.raytheon.uf.common.datastorage.Request; +import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.datastorage.records.IntegerDataRecord; + +/** + * + * @author bclement + * @version 1.0 + */ +public class IntDataReprojector extends + AbstractDataReprojector { + + protected int fill = 0; + + protected int dataMaskValue = -1; + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getGridCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getGridCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + IntegerDataRecord dataRecord = (IntegerDataRecord) record; + int[] data = dataRecord.getIntData(); + DataBuffer buff = new DataBufferInt(data, data.length); + int x = (int) dataRecord.getSizes()[0]; + int y = (int) dataRecord.getSizes()[1]; + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getMaskCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getMaskCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + int x = (int) record.getSizes()[0]; + int y = (int) record.getSizes()[1]; + int[] mask = new int[x * y]; + Arrays.fill(mask, dataMaskValue); + DataBufferInt buff = new DataBufferInt(mask, mask.length); + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected IntegerDataRecord extractData(GridCoverage2D coverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer(); + int[] data = dataBuffer.getData(); + int height = raster.getHeight(); + int width = raster.getWidth(); + return new IntegerDataRecord("", "", data, 2, new long[] { width, + height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D, + * org.geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected IntegerDataRecord extractData(GridCoverage2D coverage, + GridCoverage2D maskCoverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferInt dataBuffer = (DataBufferInt) raster.getDataBuffer(); + int[] data = dataBuffer.getData(); + + // Extract mask + image = maskCoverage.getRenderedImage(); + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + dataBuffer = (DataBufferInt) raster.getDataBuffer(); + int[] mask = dataBuffer.getData(); + + if (mask.length == data.length) { + for (int i = 0; i < data.length; ++i) { + if (mask[i] != dataMaskValue) { + data[i] = fill; + } + } + } + + int height = raster.getHeight(); + int width = raster.getWidth(); + return new IntegerDataRecord("", "", data, 2, new long[] { width, + height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getDataSlice(com + * .raytheon.uf.common.datastorage.records.IDataRecord, + * com.raytheon.uf.common.datastorage.Request) + */ + @Override + protected IntegerDataRecord getDataSlice(IDataRecord record, Request req) { + IntegerDataRecord dataRecord = (IntegerDataRecord) record; + int[] max = req.getMaxIndexForSlab(); + int[] min = req.getMinIndexForSlab(); + int toWidth = max[0] - min[0]; + int toHeight = max[1] - min[1]; + int[] from = dataRecord.getIntData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + int[] to = new int[toWidth * toHeight]; + for (int fromY = min[1], toY = 0; fromY < max[1]; ++fromY, ++toY) { + int toRow = toY * toWidth; + int fromRow = fromY * fromWidth; + for (int fromX = min[0], toX = 0; fromX < max[0]; ++fromX, ++toX) { + to[toRow + toX] = from[fromRow + fromX]; + } + } + long[] sizes = { toWidth, toHeight }; + return new IntegerDataRecord("", "", to, 2, sizes); + } + + /** + * @return the fill + */ + public int getFill() { + return fill; + } + + /** + * @param fill + * the fill to set + */ + public void setFill(int fill) { + this.fill = fill; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.AbstractDataReprojector#compatible + * (com.raytheon.uf.common.datastorage.records.IDataRecord) + */ + @Override + protected boolean compatible(IDataRecord dataRecord) { + return dataRecord instanceof IntegerDataRecord; + } + + @Override + protected IDataRecord getDataPoints(IDataRecord record, Request req) { + IntegerDataRecord dataRecord = (IntegerDataRecord) record; + int[] from = dataRecord.getIntData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + Point[] points = req.getPoints(); + int[] to = new int[points.length]; + for (int i = 0; i < to.length; ++i) { + Point p = points[i]; + to[i] = from[p.y * fromWidth + p.x]; + } + return new IntegerDataRecord("", "", to, 1, new long[] { to.length }); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/KeyLocker.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/KeyLocker.java new file mode 100644 index 0000000000..b47c48408f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/KeyLocker.java @@ -0,0 +1,104 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.Lock; +import java.util.concurrent.locks.ReentrantLock; + +/** + * Class for managing a pool of concurrency locks organized by string keys. + * + * @author bclement + * @version 1.0 + */ +public class KeyLocker { + + public class KeyLock { + private final String key; + + private final Lock lock; + + private boolean released = false; + + public KeyLock(String key, Lock lock) { + this.key = key; + this.lock = lock; + } + + @Override + protected void finalize() throws Throwable { + release(); + } + + public void release() { + if (!this.released) { + releaseLock(this.key); + this.released = true; + } + } + + public void lock() { + this.lock.lock(); + } + + public void unlock() { + this.lock.unlock(); + } + + } + + private class Entry { + int count = 0; + final Lock lock = new ReentrantLock(); + } + + private final Map locks = new HashMap(); + + public KeyLock getLock(String key) { + synchronized (locks) { + Entry e = locks.get(key); + if (e == null) { + e = new Entry(); + locks.put(key, e); + } + e.count++; + return new KeyLock(key, e.lock); + } + } + + void releaseLock(String key) { + synchronized (locks) { + Entry e = locks.get(key); + if (e != null) { + e.count--; + if (e.count <= 0) { + locks.remove(key); + } + } + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ReferencedDataRecord.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ReferencedDataRecord.java new file mode 100644 index 0000000000..fd38a68b2d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ReferencedDataRecord.java @@ -0,0 +1,64 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * May 18, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import org.geotools.geometry.jts.ReferencedEnvelope; + +import com.raytheon.uf.common.datastorage.records.IDataRecord; + +public class ReferencedDataRecord{ + + protected IDataRecord record; + + protected ReferencedEnvelope envelope; + + public ReferencedDataRecord(IDataRecord record, ReferencedEnvelope envlope) { + this.record = record; + this.envelope = envlope; + } + + public IDataRecord getRecord() { + return record; + } + + public void setRecord(IDataRecord record) { + this.record = record; + } + + public ReferencedEnvelope getEnvelope() { + return envelope; + } + + public void setEnvelope(ReferencedEnvelope envelope) { + this.envelope = envelope; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ShortDataReprojector.java b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ShortDataReprojector.java new file mode 100644 index 0000000000..4c40a28930 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.spatial/src/com/raytheon/uf/common/spatial/reprojection/ShortDataReprojector.java @@ -0,0 +1,248 @@ +/* + * The following software products were developed by Raytheon: + * + * ADE (AWIPS Development Environment) software + * CAVE (Common AWIPS Visualization Environment) software + * EDEX (Environmental Data Exchange) software + * uFrameâ„¢ (Universal Framework) software + * + * Copyright (c) 2010 Raytheon Co. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Eclipse Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/org/documents/epl-v10.php + * + * + * Contractor Name: Raytheon Company + * Contractor Address: + * 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * + * SOFTWARE HISTORY + * + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Jun 13, 2011 bclement Initial creation + * + */ +package com.raytheon.uf.common.spatial.reprojection; + +import java.awt.Point; +import java.awt.image.DataBuffer; +import java.awt.image.DataBufferShort; +import java.awt.image.Raster; +import java.awt.image.RenderedImage; +import java.util.Arrays; + +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.opengis.referencing.crs.CoordinateReferenceSystem; + +import com.raytheon.uf.common.datastorage.Request; +import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.datastorage.records.ShortDataRecord; + +/** + * TODO Add Description + * + * @author bclement + * @version 1.0 + */ +public class ShortDataReprojector extends + AbstractDataReprojector { + + protected short fill = 0; + + protected short dataMaskValue = -1; + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getGridCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getGridCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + ShortDataRecord dataRecord = (ShortDataRecord) record; + short[] data = dataRecord.getShortData(); + DataBuffer buff = new DataBufferShort(data, data.length); + int x = (int) dataRecord.getSizes()[0]; + int y = (int) dataRecord.getSizes()[1]; + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getMaskCoverage + * (com.raytheon.uf.common.datastorage.records.IDataRecord, + * org.opengis.referencing.crs.CoordinateReferenceSystem, + * org.opengis.geometry.Envelope) + */ + @Override + protected GridCoverage2D getMaskCoverage(IDataRecord record, + ReferencedEnvelope env) throws Exception { + int x = (int) record.getSizes()[0]; + int y = (int) record.getSizes()[1]; + short[] mask = new short[x * y]; + Arrays.fill(mask, dataMaskValue); + DataBufferShort buff = new DataBufferShort(mask, mask.length); + CoordinateReferenceSystem crs = env.getCoordinateReferenceSystem(); + return constructGridCoverage(crs.getName() + " Grid", buff, x, y, env); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected ShortDataRecord extractData(GridCoverage2D coverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferShort dataBuffer = (DataBufferShort) raster.getDataBuffer(); + short[] data = dataBuffer.getData(); + int height = raster.getHeight(); + int width = raster.getWidth(); + return new ShortDataRecord("", "", data, 2, + new long[] { width, height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#extractData(org + * .geotools.coverage.grid.GridCoverage2D, + * org.geotools.coverage.grid.GridCoverage2D) + */ + @Override + protected ShortDataRecord extractData(GridCoverage2D coverage, + GridCoverage2D maskCoverage) { + RenderedImage image = coverage.getRenderedImage(); + Raster raster; + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + DataBufferShort dataBuffer = (DataBufferShort) raster.getDataBuffer(); + short[] data = dataBuffer.getData(); + + // Extract mask + image = maskCoverage.getRenderedImage(); + if (image.getNumXTiles() == 1 && image.getNumYTiles() == 1) { + // we can directly access data + raster = image.getTile(0, 0); + } else { + // need to copy data out + raster = image.getData(); + } + dataBuffer = (DataBufferShort) raster.getDataBuffer(); + short[] mask = dataBuffer.getData(); + + if (mask.length == data.length) { + for (int i = 0; i < data.length; ++i) { + if (mask[i] != dataMaskValue) { + data[i] = fill; + } + } + } + + int height = raster.getHeight(); + int width = raster.getWidth(); + return new ShortDataRecord("", "", data, 2, + new long[] { width, height }); + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.DataReprojector#getDataSlice(com + * .raytheon.uf.common.datastorage.records.IDataRecord, + * com.raytheon.uf.common.datastorage.Request) + */ + @Override + protected ShortDataRecord getDataSlice(IDataRecord record, Request req) { + ShortDataRecord dataRecord = (ShortDataRecord) record; + int[] max = req.getMaxIndexForSlab(); + int[] min = req.getMinIndexForSlab(); + int toWidth = max[0] - min[0]; + int toHeight = max[1] - min[1]; + short[] from = dataRecord.getShortData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + short[] to = new short[toWidth * toHeight]; + for (int fromY = min[1], toY = 0; fromY < max[1]; ++fromY, ++toY) { + int toRow = toY * toWidth; + int fromRow = fromY * fromWidth; + for (int fromX = min[0], toX = 0; fromX < max[0]; ++fromX, ++toX) { + to[toRow + toX] = from[fromRow + fromX]; + } + } + long[] sizes = { toWidth, toHeight }; + return new ShortDataRecord("", "", to, 2, sizes); + } + + /** + * @return the fill + */ + public short getFill() { + return fill; + } + + /** + * @param fill + * the fill to set + */ + public void setFill(short fill) { + this.fill = fill; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.spatial.reprojection.AbstractDataReprojector#compatible + * (com.raytheon.uf.common.datastorage.records.IDataRecord) + */ + @Override + protected boolean compatible(IDataRecord dataRecord) { + return dataRecord instanceof ShortDataRecord; + } + + @Override + protected IDataRecord getDataPoints(IDataRecord record, Request req) { + ShortDataRecord dataRecord = (ShortDataRecord) record; + short[] from = dataRecord.getShortData(); + int fromWidth = (int) dataRecord.getSizes()[0]; + Point[] points = req.getPoints(); + short[] to = new short[points.length]; + for (int i = 0; i < to.length; ++i) { + Point p = points[i]; + to[i] = from[p.y * fromWidth + p.x]; + } + return new ShortDataRecord("", "", to, 1, new long[] { to.length }); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/.classpath b/edexOsgi/com.raytheon.uf.common.stats/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.stats/.project b/edexOsgi/com.raytheon.uf.common.stats/.project new file mode 100644 index 0000000000..b961719532 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.stats + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.stats/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.stats/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..277fa3721e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Aug 06 10:54:57 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.stats/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.stats/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..81c3d897a6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/META-INF/MANIFEST.MF @@ -0,0 +1,20 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Stats +Bundle-SymbolicName: com.raytheon.uf.common.stats +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Export-Package: com.raytheon.uf.common.stats, + com.raytheon.uf.common.stats.data, + com.raytheon.uf.common.stats.util, + com.raytheon.uf.common.stats.xml +Require-Bundle: com.raytheon.uf.common.time;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + javax.persistence;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin;bundle-version="1.12.1174", + com.raytheon.uf.common.event;bundle-version="1.0.0", + com.google.guava;bundle-version="1.0.0", + com.raytheon.uf.common.util;bundle-version="1.12.1174", + com.raytheon.uf.common.status;bundle-version="1.12.1174" diff --git a/edexOsgi/com.raytheon.uf.common.stats/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.common.stats/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject new file mode 100644 index 0000000000..62f07fe400 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject @@ -0,0 +1,2 @@ +com.raytheon.uf.common.stats.StatsRecord +com.raytheon.uf.common.stats.AggregateRecord \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.stats/build.properties b/edexOsgi/com.raytheon.uf.common.stats/build.properties new file mode 100644 index 0000000000..242efb0ca2 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/package-info.java b/edexOsgi/com.raytheon.uf.common.stats/res/scripts/stats_indices.sql similarity index 79% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/package-info.java rename to edexOsgi/com.raytheon.uf.common.stats/res/scripts/stats_indices.sql index 8946012722..ff3f977deb 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/package-info.java +++ b/edexOsgi/com.raytheon.uf.common.stats/res/scripts/stats_indices.sql @@ -17,7 +17,14 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -/** - * Contains the core classes for decoding, storing, and accessing grib data. - */ -package com.raytheon.uf.common.dataplugin.grib; \ No newline at end of file + +CREATE INDEX "aggregateQuery_idx" + ON events.aggregate + USING btree + (startDate, endDate, eventType, field); + +CREATE INDEX "statsQuery_idx" + ON events.stats + USING btree + (date, eventType); + diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregateRecord.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregateRecord.java new file mode 100644 index 0000000000..fba2d6127d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregateRecord.java @@ -0,0 +1,283 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats; + +import java.util.Calendar; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Record class for an aggregate result. + * + *
+ *
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Initial creation
+ * Nov 12, 2012            dhladky      Updates some things for stats
+ *
+ * 
+ * + * @author jsanchez + * @version 1.0 + */ +@Entity +@Table(name = "aggregate", schema = "events") +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class AggregateRecord extends PersistableDataObject { + private static final long serialVersionUID = -4553588456131256014L; + + @GeneratedValue(strategy = GenerationType.AUTO) + @Id + @DynamicSerializeElement + private Integer id; + + @Column(nullable = false) + @DynamicSerializeElement + private Calendar startDate; + + @Column(nullable = false) + @DynamicSerializeElement + private Calendar endDate; + + @Column(nullable = false) + @DynamicSerializeElement + private String eventType; + + @DynamicSerializeElement + private String grouping; + + @Column(nullable = false) + @DynamicSerializeElement + private String field; + + @DynamicSerializeElement + private double max; + + @DynamicSerializeElement + private double min; + + @DynamicSerializeElement + private double sum; + + @DynamicSerializeElement + private double count; + + public AggregateRecord() { + + } + + public AggregateRecord(String eventType, Calendar startDate, + Calendar endDate, String groupings, String field) { + this.eventType = eventType; + this.startDate = startDate; + this.endDate = endDate; + grouping = groupings; + this.field = field; + } + + public double getCount() { + return count; + } + + public Calendar getEndDate() { + return endDate; + } + + public String getEventType() { + return eventType; + } + + public String getField() { + return field; + } + + public String getGrouping() { + return grouping; + } + + public Integer getId() { + return id; + } + + public double getMax() { + return max; + } + + public double getMin() { + return min; + } + + public Calendar getStartDate() { + return startDate; + } + + public double getSum() { + return sum; + } + + public void setCount(double count) { + this.count = count; + } + + public void setEndDate(Calendar endDate) { + this.endDate = endDate; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public void setField(String field) { + this.field = field; + } + + public void setGrouping(String grouping) { + this.grouping = grouping; + } + + public void setId(Integer id) { + this.id = id; + } + + public void setMax(double max) { + this.max = max; + } + + public void setMin(double min) { + this.min = min; + } + + public void setStartDate(Calendar startDate) { + this.startDate = startDate; + } + + public void setSum(double sum) { + this.sum = sum; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + final int prime = 31; + int result = super.hashCode(); + long temp; + temp = Double.doubleToLongBits(count); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + ((endDate == null) ? 0 : endDate.hashCode()); + result = prime * result + + ((eventType == null) ? 0 : eventType.hashCode()); + result = prime * result + ((field == null) ? 0 : field.hashCode()); + result = prime * result + + ((grouping == null) ? 0 : grouping.hashCode()); + temp = Double.doubleToLongBits(max); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(min); + result = prime * result + (int) (temp ^ (temp >>> 32)); + result = prime * result + + ((startDate == null) ? 0 : startDate.hashCode()); + temp = Double.doubleToLongBits(sum); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!super.equals(obj)) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + AggregateRecord other = (AggregateRecord) obj; + if (Double.doubleToLongBits(count) != Double + .doubleToLongBits(other.count)) { + return false; + } + if (endDate == null) { + if (other.endDate != null) { + return false; + } + } else if (!endDate.equals(other.endDate)) { + return false; + } + if (eventType == null) { + if (other.eventType != null) { + return false; + } + } else if (!eventType.equals(other.eventType)) { + return false; + } + if (field == null) { + if (other.field != null) { + return false; + } + } else if (!field.equals(other.field)) { + return false; + } + if (grouping == null) { + if (other.grouping != null) { + return false; + } + } else if (!grouping.equals(other.grouping)) { + return false; + } + if (Double.doubleToLongBits(max) != Double.doubleToLongBits(other.max)) { + return false; + } + if (Double.doubleToLongBits(min) != Double.doubleToLongBits(other.min)) { + return false; + } + if (startDate == null) { + if (other.startDate != null) { + return false; + } + } else if (!startDate.equals(other.startDate)) { + return false; + } + if (Double.doubleToLongBits(sum) != Double.doubleToLongBits(other.sum)) { + return false; + } + return true; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregatedStatsRequest.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregatedStatsRequest.java new file mode 100644 index 0000000000..0f1cd8d474 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregatedStatsRequest.java @@ -0,0 +1,88 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.serialization.comm.IServerRequest; +import com.raytheon.uf.common.time.TimeRange; + +/** + * Request results from the metadata.aggregate table. + * + * SOFTWARE HISTORY + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Aug 21, 2012 jsanchez Initial creation + * + * @author jsanchez + * + */ +@DynamicSerialize +public class AggregatedStatsRequest implements IServerRequest { + @DynamicSerializeElement + private TimeRange timeRange; + + @DynamicSerializeElement + private String eventType; + + @DynamicSerializeElement + private String[] grouping; + + @DynamicSerializeElement + private String field; + + public AggregatedStatsRequest() { + + } + + public TimeRange getTimeRange() { + return timeRange; + } + + public void setTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String[] getGrouping() { + return grouping; + } + + public void setGrouping(String[] grouping) { + this.grouping = grouping; + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregatedStatsResponse.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregatedStatsResponse.java new file mode 100644 index 0000000000..d5abe7ac05 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/AggregatedStatsResponse.java @@ -0,0 +1,107 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.time.TimeRange; + +/** + * Response from the handler of the results in the metadata.aggregate table. + * + * SOFTWARE HISTORY + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Aug 21, 2012 jsanchez Initial creation + * + * @author jsanchez + * + */ +@DynamicSerialize +public class AggregatedStatsResponse implements ISerializableObject { + @DynamicSerializeElement + private TimeRange timeRange; + + @DynamicSerializeElement + private String eventType; + + @DynamicSerializeElement + private String[] grouping; + + @DynamicSerializeElement + private String field; + + @DynamicSerializeElement + private AggregateRecord[] records; + + public AggregatedStatsResponse() { + + } + + public AggregatedStatsResponse(TimeRange timeRange, String eventType, + String[] grouping, String field) { + this.timeRange = timeRange; + this.eventType = eventType; + this.grouping = grouping; + this.field = field; + } + + public TimeRange getTimeRange() { + return timeRange; + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public String[] getGrouping() { + return grouping; + } + + public void setGrouping(String[] grouping) { + this.grouping = grouping; + } + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + public void setTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + } + + public AggregateRecord[] getRecords() { + return records; + } + + public void setRecords(AggregateRecord[] records) { + this.records = records; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/GraphDataRequest.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/GraphDataRequest.java new file mode 100644 index 0000000000..340fb9ff9b --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/GraphDataRequest.java @@ -0,0 +1,200 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats; + +import java.util.List; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.serialization.comm.IServerRequest; +import com.raytheon.uf.common.time.TimeRange; + +/** + * Request object to retrieve data for the Stats graphs + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 11, 2012   728      mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +public class GraphDataRequest implements IServerRequest { + /** The time range */ + @DynamicSerializeElement + private TimeRange timeRange; + + /** Statistics Category */ + @DynamicSerializeElement + private String category; + + /** Statistics event type */ + @DynamicSerializeElement + private String eventType; + + /** Statistics field */ + @DynamicSerializeElement + private String field; + + /** List of groups */ + @DynamicSerializeElement + private List grouping; + + /** Event data type/Attribute */ + @DynamicSerializeElement + private String dataType; + + /** Metadata request flag */ + @DynamicSerializeElement + private boolean metaDataRequest = false; + + /** + * Data timestep (frequency) in minutes. + */ + @DynamicSerializeElement + private int timeStep; + + /** + * @return the timeRange + */ + public TimeRange getTimeRange() { + return timeRange; + } + + /** + * @param timeRange + * the timeRange to set + */ + public void setTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + } + + /** + * @return the eventType + */ + public String getEventType() { + return eventType; + } + + /** + * @param eventType + * the eventType to set + */ + public void setEventType(String eventType) { + this.eventType = eventType; + } + + /** + * @return the field + */ + public String getField() { + return field; + } + + /** + * @param field + * the field to set + */ + public void setField(String field) { + this.field = field; + } + + /** + * @return the grouping + */ + public List getGrouping() { + return grouping; + } + + /** + * @param grouping + * the grouping to set + */ + public void setGrouping(List grouping) { + this.grouping = grouping; + } + + /** + * @param timeStep + * the timeStep to set + */ + public void setTimeStep(int timeStep) { + this.timeStep = timeStep; + } + + /** + * @return the timeStep + */ + public int getTimeStep() { + return timeStep; + } + + /** + * @return the dataType + */ + public String getDataType() { + return dataType; + } + + /** + * @param dataType + * the dataType to set + */ + public void setDataType(String dataType) { + this.dataType = dataType; + } + + /** + * @param metaDataRequest + * the metaDataRequest to set + */ + public void setMetaDataRequest(boolean metaDataRequest) { + this.metaDataRequest = metaDataRequest; + } + + /** + * @return the category + */ + public String getCategory() { + return category; + } + + /** + * @param category + * the category to set + */ + public void setCategory(String category) { + this.category = category; + } + + /** + * @return the metaDataRequest + */ + public boolean isMetaDataRequest() { + return metaDataRequest; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/requests/ThriftDataResponse.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/GraphDataResponse.java similarity index 51% rename from edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/requests/ThriftDataResponse.java rename to edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/GraphDataResponse.java index 5d1fb6a27a..6582162b18 100644 --- a/edexOsgi/com.raytheon.uf.common.datastorage.remote/src/com/raytheon/uf/common/datastorage/remote/requests/ThriftDataResponse.java +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/GraphDataResponse.java @@ -1,94 +1,90 @@ /** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * + * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. - * + * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 - * + * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.datastorage.remote.requests; +package com.raytheon.uf.common.stats; + +import java.util.List; -import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.stats.data.GraphData; +import com.raytheon.uf.common.stats.xml.StatisticsConfig; /** - * Data response object - * + * Response object for the GraphDataRequest. + * *
- * 
+ *
  * SOFTWARE HISTORY
+ *
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Aug 18, 2009            mschenke     Initial creation
- * 
+ * Sep 11, 2012    728     mpduff      Initial creation
+ *
  * 
- * - * @author mschenke + * + * @author mpduff * @version 1.0 */ @DynamicSerialize -public class ThriftDataResponse implements ISerializableObject { +public class GraphDataResponse implements ISerializableObject { + @DynamicSerializeElement + private GraphData graphData; @DynamicSerializeElement - private String[] datasets; + private List configList; - @DynamicSerializeElement - private IDataRecord[] records; - - @DynamicSerializeElement - private IDataRecord record; - - public ThriftDataResponse() { + public GraphDataResponse() { } - public ThriftDataResponse(String[] datsets) { - this.datasets = datsets; + /** + * @return the configList + */ + public List getConfigList() { + return configList; } - public ThriftDataResponse(IDataRecord[] records) { - this.records = records; + /** + * @param configList + * the configList to set + */ + public void setConfigList(List configList) { + this.configList = configList; } - public ThriftDataResponse(IDataRecord record) { - this.record = record; + /** + * Set the GraphData object + * + * @param graphData + */ + public void setGraphData(GraphData graphData) { + this.graphData = graphData; } - public String[] getDatasets() { - return datasets; + /** + * Get the GraphData object + * + * @return + */ + public GraphData getGraphData() { + return this.graphData; } - - public void setDatasets(String[] datasets) { - this.datasets = datasets; - } - - public IDataRecord[] getRecords() { - return records; - } - - public void setRecords(IDataRecord[] records) { - this.records = records; - } - - public IDataRecord getRecord() { - return record; - } - - public void setRecord(IDataRecord record) { - this.record = record; - } - } diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/ProcessEvent.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/ProcessEvent.java new file mode 100644 index 0000000000..ff93d8ea8b --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/ProcessEvent.java @@ -0,0 +1,167 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats; + +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Event for file ingest statistics (processing time and processing latency.) + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 25, 2012  #1292     bgonzale     Initial creation
+ * 
+ * 
+ * + * @author bgonzale + * @version 1.0 + */ +@DynamicSerialize +public class ProcessEvent extends StatisticsEvent { + + private static final long serialVersionUID = 1L; + + private static final Map FIELD_UNIT_MAP; + static { + Map m = new HashMap(); + m.put("processingLatency", "ms"); + m.put("processingTime", "ms"); + FIELD_UNIT_MAP = Collections.unmodifiableMap(m); + } + + @DynamicSerializeElement + private String message; + + @DynamicSerializeElement + private String pluginName; + + @DynamicSerializeElement + private String fileName; + + /* + * Processing time in milliseconds + */ + @DynamicSerializeElement + private long processingTime; + + /* + * Processing latency in milliseconds + */ + @DynamicSerializeElement + private long processingLatency; + + public ProcessEvent() { + } + + @Override + protected Map getFieldUnitMap() { + return FIELD_UNIT_MAP; + } + + /** + * @return the fileName + */ + public String getFileName() { + return fileName; + } + + /** + * @return the message + */ + public String getMessage() { + return message; + } + + /** + * @return the pluginName + */ + public String getPluginName() { + return pluginName; + } + + /** + * @return the processingLatency in milliseconds + */ + public long getProcessingLatency() { + return processingLatency; + } + + /** + * @return the processingTime in milliseconds + */ + public long getProcessingTime() { + return processingTime; + } + + /** + * @param fileName + * the fileName to set + */ + public void setFileName(String fileName) { + this.fileName = fileName; + } + + /** + * @param message + * the message to set + */ + public void setMessage(String message) { + this.message = message; + } + + /** + * @param pluginName + * the pluginName to set + */ + public void setPluginName(String pluginName) { + this.pluginName = pluginName; + } + + /** + * @param processingLatency + * the processingLatency in milliseconds to set + */ + public void setProcessingLatency(long processingLatency) { + this.processingLatency = processingLatency; + } + + /** + * @param processingTime + * the processingTime in milliseconds to set + */ + public void setProcessingTime(long processingTime) { + this.processingTime = processingTime; + } + + @Override + public String toString() { + return super.toString() + " : " + getMessage(); + } + +} \ No newline at end of file diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/ModelNode.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/StatisticsEvent.java similarity index 61% rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/ModelNode.java rename to edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/StatisticsEvent.java index 362e5b60cb..9e37e948b0 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/gridcache/ModelNode.java +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/StatisticsEvent.java @@ -1,57 +1,58 @@ +package com.raytheon.uf.common.stats; + /** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * + * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. - * + * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 - * + * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.viz.grid.gridcache; -import java.util.ArrayList; -import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.raytheon.uf.common.event.Event; /** - * Model node, top of the node tree. + * Event used for statistics * *
- *
+ * 
  * SOFTWARE HISTORY
- *
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Nov 13, 2009 3579       mpduff      Initial creation
- *
+ * Oct 25, 2012  #1340     dhladky     Initial creation
+ * 
  * 
- * - * @author mpduff - * @version 1.0 + * + * @author dhladky + * @version 1.0 */ -public class ModelNode extends CacheNode { - private List parameterNodeList = new ArrayList(); - - - /** - * @return the parameterNodeList - */ - public List getParameterNodeList() { - return parameterNodeList; +public abstract class StatisticsEvent extends Event { + + private static final long serialVersionUID = 1L; + + public Set getFields() { + return getFieldUnitMap().keySet(); } + protected abstract Map getFieldUnitMap(); - public void addParameterNode(ParameterNode pnode) { - parameterNodeList.add(pnode); + public String getStorageUnit(String field) { + return getFieldUnitMap().get(field); } } diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/StatsRecord.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/StatsRecord.java new file mode 100644 index 0000000000..7c23b9f571 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/StatsRecord.java @@ -0,0 +1,119 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats; + +import java.util.Calendar; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Record class for stats waiting to be stored in the appropriate bucket. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Initial creation
+ * 
+ * 
+ * + * @author jsanchez + * + */ +@Entity +@Table(name = "stats", schema = "events") +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class StatsRecord extends PersistableDataObject { + @GeneratedValue(strategy = GenerationType.AUTO) + @Id + @DynamicSerializeElement + private Integer id; + + @Column(nullable = false) + @DynamicSerializeElement + private Calendar date; + + @Column(nullable = false) + @DynamicSerializeElement + private String eventType; + + @Column(nullable = false) + @DynamicSerializeElement + private byte[] event; + + public Calendar getDate() { + return date; + } + + public byte[] getEvent() { + return event; + } + + public String getEventType() { + return eventType; + } + + public Integer getId() { + return id; + } + + public void setDate(Calendar date) { + this.date = date; + } + + public void setEvent(byte[] event) { + this.event = event; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public void setId(Integer id) { + this.id = id; + } + + @Override + public String toString() { + + StringBuilder sb = new StringBuilder(); + sb.append(getEventType() + " "); + sb.append(getDate() + " "); + sb.append(getId() + " "); + return sb.toString(); + + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/DataPoint.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/DataPoint.java new file mode 100644 index 0000000000..569bd719cd --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/DataPoint.java @@ -0,0 +1,280 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.data; + +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.TimeZone; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.stats.util.DataViewUtils; + +/** + * Class holding an x,y data point and other associated information for the + * point. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 7, 2012            mpduff     Initial creation
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class DataPoint implements Comparable { + /** Date Format object */ + private final ThreadLocal sdf = new ThreadLocal() { + @Override + protected SimpleDateFormat initialValue() { + SimpleDateFormat sTemp = new SimpleDateFormat("MM/dd/yyyy HH:mm"); + sTemp.setTimeZone(TimeZone.getTimeZone("GMT")); + return sTemp; + } + }; + + /** Decimal Format object */ + private final ThreadLocal decFormat = new ThreadLocal() { + @Override + protected DecimalFormat initialValue() { + DecimalFormat format = new DecimalFormat("########.#"); + return format; + } + }; + + /** + * X value - millis + */ + @DynamicSerializeElement + private long x; + + /** + * Text display for the sampling of this point + */ + @DynamicSerializeElement + protected String sampleText; + + /** Min value */ + @DynamicSerializeElement + private BigDecimal min = new BigDecimal(Integer.MAX_VALUE); + + /** Max value */ + @DynamicSerializeElement + private BigDecimal max = new BigDecimal(Integer.MIN_VALUE); + + /** Count */ + @DynamicSerializeElement + private BigDecimal count = new BigDecimal(0); + + /** Sum */ + @DynamicSerializeElement + private BigDecimal sum = new BigDecimal(0); + + /** Constructor */ + public DataPoint() { + sum = sum.setScale(1, BigDecimal.ROUND_HALF_UP); + min = min.setScale(1, BigDecimal.ROUND_HALF_UP); + max = max.setScale(1, BigDecimal.ROUND_HALF_UP); + count = count.setScale(1, BigDecimal.ROUND_HALF_UP); + } + + /** + * @param sampleText + * the sampleText to set + */ + public void setSampleText(String sampleText) { + this.sampleText = sampleText; + } + + /** + * Get the sample text for this point object + * + * @return the sample text string + */ + public String getSampleText(String view) { + SimpleDateFormat dateFormat = sdf.get(); + DecimalFormat decimalFormat = decFormat.get(); + + return dateFormat.format(new Date(x)) + "Z, " + + decimalFormat.format(getValue(view)); + } + + /** + * @param x + * the x to set + */ + public void setX(long x) { + this.x = x; + } + + /** + * @return the x + */ + public long getX() { + return x; + } + + /** + * {@inheritDoc} + */ + @Override + public int compareTo(DataPoint dp) { + if (this.x == dp.x) { + return 0; + } else if (this.x < dp.x) { + return -1; + } else if (this.x > dp.x) { + return 1; + } + + return 0; + } + + /** + * @return the min + */ + public double getMin() { + return min.doubleValue(); + } + + /** + * Set the min value if it is less than the current min. + * + * @param min + * the min to set + */ + public void setMin(double min) { + if (this.min.doubleValue() > min) { + BigDecimal m = new BigDecimal(min); + m = m.setScale(1, BigDecimal.ROUND_HALF_UP); + this.min = m; + } + } + + /** + * @return the max + */ + public double getMax() { + return max.doubleValue(); + } + + /** + * Set the max value if it is greater than the current max. + * + * @param max + * the max to set + */ + public void setMax(double max) { + if (this.max.doubleValue() < max) { + this.max = new BigDecimal(max); + this.max = this.max.setScale(1, BigDecimal.ROUND_HALF_UP); + } + } + + /** + * @return the count + */ + public double getCount() { + return count.doubleValue(); + } + + /** + * @param count + * the count to set + */ + public void setCount(double count) { + this.count = new BigDecimal(count); + this.count = this.count.setScale(1, BigDecimal.ROUND_HALF_UP); + } + + /** + * + * @param count + * the count to add + */ + public void addToCount(double count) { + BigDecimal cnt = new BigDecimal(count); + cnt = cnt.setScale(1, BigDecimal.ROUND_HALF_UP); + this.count = this.count.add(cnt); + } + + /** + * @return the sum + */ + public double getSum() { + return sum.doubleValue(); + } + + /** + * @param sum + * the sum to set + */ + public void setSum(double sum) { + BigDecimal s = new BigDecimal(sum); + s = s.setScale(1, BigDecimal.ROUND_HALF_UP); + this.sum = this.sum.add(s); + } + + /** + * @return the avg + */ + public double getAvg() { + if (count.doubleValue() > 0) { + return sum.divide(count, BigDecimal.ROUND_HALF_UP).doubleValue(); + } + + return 0; + } + + /** + * Get the value for the provided data view type. + * + * @param view + * the view type + */ + public double getValue(String view) { + if (view.equals(DataViewUtils.DataView.AVG.getView())) { + return getAvg(); + } else if (view.equals(DataViewUtils.DataView.MIN.getView())) { + return getMin(); + } else if (view.equals(DataViewUtils.DataView.MAX.getView())) { + return getMax(); + } else if (view.equals(DataViewUtils.DataView.SUM.getView())) { + return getSum(); + } else { + return getCount(); + } + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/GraphData.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/GraphData.java new file mode 100644 index 0000000000..c05481534f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/GraphData.java @@ -0,0 +1,422 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.data; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +import com.google.common.annotations.VisibleForTesting; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.StatisticsEvent; +import com.raytheon.uf.common.stats.util.UnitUtils; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.time.TimeRange; +import com.raytheon.uf.common.util.ReflectionException; +import com.raytheon.uf.common.util.ReflectionUtil; + +/** + * Data object for the statistics graph. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 3, 2012     728     mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +public class GraphData { + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(GraphData.class); + + /** Map of milliseconds -> StatsBin object */ + @DynamicSerializeElement + private final Map bins = new TreeMap(); + + /** List of member keys */ + @DynamicSerializeElement + private List keys; + + /** AggregateRecord list */ + @DynamicSerializeElement + private List recordList = new ArrayList(); + + /** + * key -> stats data object + */ + @DynamicSerializeElement + private Map statsDataMap = new HashMap(); + + /** Time range */ + @DynamicSerializeElement + private TimeRange timeRange; + + /** Map of group -> key */ + @DynamicSerializeElement + private final Map keySequenceMap = new LinkedHashMap(); + + /** StatsLabelData object */ + @DynamicSerializeElement + private StatsLabelData statsLabelData; + + /** Display unit */ + @DynamicSerializeElement + private String displayUnit; + + /** UnitUtils object */ + private UnitUtils unitUtils; + + /** + * Constructor. + */ + public GraphData() { + + } + + /** + * @return the bins + */ + public Map getStatsBins() { + return bins; + } + + /** + * @param recordList + * the recordList to set + */ + public void setRecordList(List recordList) { + this.recordList = recordList; + } + + /** + * @return the recordList + */ + public List getRecordList() { + return recordList; + } + + /** + * Add an AggregateRecord. + * + * @param record + */ + public void addRecord(AggregateRecord record) { + if (!recordList.contains(record)) { + recordList.add(record); + } + } + + /** + * @return the statsData + */ + public StatsData getStatsData(String groupMemberName) { + return this.statsDataMap.get(groupMemberName); + } + + /** + * Get a list of group memebers. + * + * @return + */ + public List getGroupMembers() { + List memberList = new ArrayList(statsDataMap.keySet()); + Collections.sort(memberList); + + return memberList; + } + + /** + * Get the smallest value in the data set. + * + * @return + */ + public double getMinValue() { + double min = Double.MAX_VALUE; + for (String key : statsDataMap.keySet()) { + double minVal = statsDataMap.get(key).getMinValue(); + if (minVal < min) { + min = minVal; + } + } + + return min; + } + + /** + * Get the largest value in the data set. + * + * @return + */ + public double getMaxValue() { + double max = Double.MIN_VALUE; + for (String key : statsDataMap.keySet()) { + double maxVal = statsDataMap.get(key).getMaxValue(); + if (maxVal > max) { + max = maxVal; + } + } + + return max; + } + + /** + * Get the smallest value in the data set. + * + * @return + */ + public double getMinValue(Set visibleDataSet, String view) { + if (visibleDataSet.isEmpty()) { + return 0; + } + + double min = Double.MAX_VALUE; + for (String key : statsDataMap.keySet()) { + if (visibleDataSet.contains(key)) { + double minVal = statsDataMap.get(key).getMinValue(view); + if (minVal < min) { + min = minVal; + } + } + } + + return min; + } + + /** + * Get the largest value in the data set. + * + * @return + */ + public double getMaxValue(Set visibleDataSet, String view) { + if (visibleDataSet.isEmpty()) { + return 1; + } + double max = Double.MIN_VALUE; + for (String key : statsDataMap.keySet()) { + if (visibleDataSet.contains(key)) { + double maxVal = statsDataMap.get(key).getMaxValue(view); + if (maxVal > max) { + max = maxVal; + } + } + } + + return max; + } + + /** + * Get the time range for this object. + * + * @return + */ + public TimeRange getTimeRange() { + return this.timeRange; + } + + /** + * Set the TimeRange + * + * @param timeRange + */ + public void setTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + } + + /** + * Set the key sequence + * + * @param keySequence + */ + public void setKeySequence(List keySequence) { + for (String key : keySequence) { + keySequenceMap.put(key, ""); + } + + keys = keySequence; + } + + /** + * Get the key sequence. + * + * @return + */ + public List getKeySequence() { + return keys; + } + + /** + * Get a list of all keys. + * + * @return the keys + */ + public List getKeys() { + return keys; + } + + /** + * Get a list of keys that contain data. + * + * @return the keys with data + */ + public List getKeysWithData() { + List keysWithData = new ArrayList(); + for (String key : keys) { + StatsData sd = this.getStatsData(key); + if (sd != null) { + keysWithData.add(key); + } + } + + return keysWithData; + } + + /** + * Set the StatsLabelData object + * + * @param statsLabelData + */ + public void setStatsLabelData(StatsLabelData statsLabelData) { + this.statsLabelData = statsLabelData; + this.keys = statsLabelData.makeKeys(); + } + + /** + * Get the StatsLabelData + * + * @return + */ + public StatsLabelData getStatsLabelData() { + return this.statsLabelData; + } + + /** + * Get the group and names map. + * + * @return + */ + public Map> getGroupAndNamesMap() { + return statsLabelData.getGroupAndNamesMap(); + } + + /** + * Get the units from the event object + * + * @param eventId + * Event id + * @param field + * data field + * + * @return The units + */ + @VisibleForTesting + static String getUnitsFromEventObject(String eventId, String field) { + // Get the units from the event class + String units = "Count"; + + try { + StatisticsEvent obj = ReflectionUtil.newInstanceOfAssignableType( + StatisticsEvent.class, eventId); + units = obj.getStorageUnit(field); + } catch (ReflectionException e) { + statusHandler.handle(Priority.ERROR, "Error Instantiating " + + eventId, e); + } + + return units; + } + + /** + * @return the statsDataMap + */ + public Map getStatsDataMap() { + return statsDataMap; + } + + /** + * @return the keySequenceMap + */ + public Map getKeySequenceMap() { + return keySequenceMap; + } + + /** + * @return the displayUnit + */ + public String getDisplayUnit() { + return displayUnit; + } + + /** + * @param displayUnit + * the displayUnit to set + */ + public void setDisplayUnit(String displayUnit) { + this.displayUnit = displayUnit; + } + + /** + * @param keys + * the keys to set + */ + public void setKeys(List keys) { + this.keys = keys; + } + + /** + * Set the StatsData map. + * + * @param statsDataMap + */ + public void setStatsDataMap(Map statsDataMap) { + this.statsDataMap = statsDataMap; + } + + /** + * @return the unitUtils + */ + public UnitUtils getUnitUtils() { + return unitUtils; + } + + /** + * @param unitUtils + * the unitUtils to set + */ + public void setUnitUtils(UnitUtils unitUtils) { + this.unitUtils = unitUtils; + this.unitUtils.setConversion(this.getMaxValue()); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsBin.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsBin.java new file mode 100644 index 0000000000..b06266cf9f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsBin.java @@ -0,0 +1,92 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.data; + +import java.util.ArrayList; +import java.util.List; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.stats.AggregateRecord; + +/** + * A bin of Statistical data. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 11, 2012   723      mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +public class StatsBin { + /** Millisecond value for this bin */ + @DynamicSerializeElement + private long binMillis; + + /** List of AggregateRecords */ + @DynamicSerializeElement + private final List data = new ArrayList(); + + /** Constructor */ + public StatsBin() { + + } + + /** + * @return the binMillis + */ + public long getBinMillis() { + return binMillis; + } + + /** + * @param binMillis + * the binMillis to set + */ + public void setBinMillis(long binMillis) { + this.binMillis = binMillis; + } + + /** + * Add an AggregateRecord object. + * + * @param record + */ + public void setData(AggregateRecord record) { + this.data.add(record); + } + + /** + * Get the AggregateRecord objects + * + * @return + */ + public List getData() { + return data; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsData.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsData.java new file mode 100644 index 0000000000..2b4dc162ff --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsData.java @@ -0,0 +1,347 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.data; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.util.UnitUtils; +import com.raytheon.uf.common.time.TimeRange; + +/** + * Statistical data object holding data to be graphed. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 07, 2012    728     mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +@XmlRootElement +@XmlAccessorType(XmlAccessType.NONE) +@DynamicSerialize +public class StatsData { + /** Key to this object */ + @DynamicSerializeElement + private String key; + + /** List of AggregateRecords */ + @DynamicSerializeElement + private final List recordList = new ArrayList(); + + /** + * Frequency (timestep) of the data 5 min, hourly, daily + */ + @DynamicSerializeElement + private int dataFrequency; + + /** + * Time Range of the data in this object + */ + @DynamicSerializeElement + private TimeRange timeRange = new TimeRange(); + + /** List of DataPoint objects */ + @DynamicSerializeElement + private List pointList = new ArrayList(); + + /** Map of millis -> StatsBin objects */ + @DynamicSerializeElement + private Map bins; + + /** UnitUtils object */ + private UnitUtils unitUtils; + + /** Constructor */ + public StatsData() { + + } + + /** + * Constructor + * + * @param key + * Key to the object + * @param tsMillis + * timestep in ms + * @param timeRange + * TimeRange object + * @param unitUtils + * UnitUtils object + */ + public StatsData(String key, long tsMillis, TimeRange timeRange, + UnitUtils unitUtils) { + this.key = key; + this.dataFrequency = (int) tsMillis; + this.timeRange = timeRange; + this.unitUtils = unitUtils; + } + + /** + * @return the minValue + */ + public Double getMinValue() { + double minValue = Integer.MAX_VALUE; + + for (DataPoint point : pointList) { + if (point.getMin() < minValue) { + minValue = point.getMin(); + } + } + + return minValue; + } + + /** + * @return the minValue + */ + public Double getMinValue(String view) { + double minValue = Integer.MAX_VALUE; + + for (DataPoint point : pointList) { + if (point.getValue(view) < minValue) { + minValue = point.getValue(view); + } + } + + return minValue; + } + + /** + * @return the minValue + */ + public Double getMaxValue(String view) { + double maxValue = Integer.MIN_VALUE; + + for (DataPoint point : pointList) { + if (point.getValue(view) > maxValue) { + maxValue = point.getValue(view); + } + } + + return maxValue; + } + + /** + * @return the maxValue + */ + public Double getMaxValue() { + double maxValue = Integer.MIN_VALUE; + + for (DataPoint point : pointList) { + if (point.getAvg() > maxValue) { + maxValue = point.getAvg(); + } + } + + return maxValue; + } + + /** + * @return the dataFrequency + */ + public int getDataFrequency() { + return dataFrequency; + } + + /** + * @param dataFrequency + * the dataFrequency to set + */ + public void setDataFrequency(int dataFrequency) { + this.dataFrequency = dataFrequency; + } + + /** + * Get the list of DataPoint objects for the key. + * + * @param key + * The key + * @return List of DataPoint objects + */ + public List getData() { + Collections.sort(pointList); + return pointList; + } + + /** + * @return the timeRange + */ + public TimeRange getTimeRange() { + return timeRange; + } + + /** + * @param pointList + * the pointList to set + */ + public void setPointList(List pointList) { + this.pointList = pointList; + } + + /** + * Add an AggregateRecord. + * + * @param rec + * the record to add + */ + public void addRecord(AggregateRecord rec) { + this.recordList.add(rec); + } + + /** + * Get the key + * + * @return + */ + public String getKey() { + return key; + } + + /** + * Set the key + * + * @param key + * the key to set + */ + public void setKey(String key) { + this.key = key; + } + + /** + * Set the StatsBin object map. + * + * @param bins + */ + public void setBins(Map bins) { + this.bins = bins; + } + + /** + * Accumulates the AggregateRecord objects into the correct bins. + */ + public void accumulate() { + pointList.clear(); + for (AggregateRecord record : recordList) { + Date startDate = record.getStartDate().getTime(); + + long start = startDate.getTime(); + long bin = getBinKey(start); + if (bins.get(bin) != null) { + bins.get(bin).setData(record); + } + } + + createPoints(); + } + + /** + * Create the points for this key. + * + * @param dataKey + */ + private void createPoints() { + // Bins are created, now make the graph group member and point objects + // convert the data values before storing in the data object + double conversion = unitUtils.getConversion(); + for (long key : bins.keySet()) { + StatsBin sb = bins.get(key); + List dataList = sb.getData(); + if (!dataList.isEmpty()) { + DataPoint point = new DataPoint(); + point.setX(sb.getBinMillis()); + + for (AggregateRecord rec : dataList) { + // Check for an existing point object + point.setMax(rec.getMax() / conversion); + point.setMin(rec.getMin() / conversion); + point.setSum(rec.getSum() / conversion); + point.addToCount(rec.getCount()); + } + + pointList.add(point); + } + } + } + + /** + * Get the bin key for the given millisecond value. + * + * @param millis + * The millisecond value + * @return The bin that should hold this millisecond value + */ + private long getBinKey(long millis) { + for (long bin : this.bins.keySet()) { + if (millis <= bins.get(bin).getBinMillis()) { + return bin; + } + } + + return 0; + } + + /** + * @return the recordList + */ + public List getRecordList() { + return recordList; + } + + /** + * @return the pointList + */ + public List getPointList() { + return pointList; + } + + /** + * @return the bins + */ + public Map getBins() { + return bins; + } + + /** + * @param timeRange + * the timeRange to set + */ + public void setTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsEventData.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsEventData.java new file mode 100644 index 0000000000..c7351576bd --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsEventData.java @@ -0,0 +1,164 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.data; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Stats Event helper object. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 8, 2012    728      mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class StatsEventData { + /** Event Type */ + private String type; + + /** Event display name */ + private String displayName; + + /** List of groups */ + private List groupList = new ArrayList(); + + /** List of Attributes */ + private List attributeList = new ArrayList(); + + /** Map of Display Name -> Name */ + private final Map groupMap = new HashMap(); + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param type + * the type to set + */ + public void setType(String type) { + this.type = type; + } + + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } + + /** + * @param displayName + * the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * @return the groupList + */ + public List getGroupList() { + return groupList; + } + + /** + * @param groupList + * the groupList to set + */ + public void setGroupList(List groupList) { + this.groupList = groupList; + } + + /** + * @return the attributeList + */ + public List getAttributeList() { + return attributeList; + } + + /** + * @param attributeList + * the attributeList to set + */ + public void setAttributeList(List attributeList) { + this.attributeList = attributeList; + } + + /** + * @param group + * displayName of the group to add + */ + public void addGroup(String displayName, String name) { + this.groupList.add(displayName); + this.groupMap.put(displayName, name); + } + + /** + * @param attribute + * the attribute to add + */ + public void addAttribute(String attribute) { + this.attributeList.add(attribute); + } + + /** + * Get the group list + * + * @return + */ + public String[] getGroups() { + return groupList.toArray(new String[groupList.size()]); + } + + /** + * Get the attribute list + * + * @return + */ + public String[] getAttributes() { + return attributeList.toArray(new String[groupList.size()]); + } + + /** + * Get the group name from the display name. + * + * @param displayName + * @return + */ + public String getGroupNameFromDisplayName(String displayName) { + return groupMap.get(displayName); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsLabelData.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsLabelData.java new file mode 100644 index 0000000000..c3329c9ad4 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/data/StatsLabelData.java @@ -0,0 +1,183 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.data; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Statistics Label Object. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 16, 2012    728     mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +public class StatsLabelData { + /** Group string */ + @DynamicSerializeElement + private String group = ""; + + /** List of group names */ + @DynamicSerializeElement + private List groupNames = new ArrayList(); + + /** Recursive reference */ + @DynamicSerializeElement + private StatsLabelData statsLabelData = null; + + /** + * Constructor. + */ + public StatsLabelData() { + + } + + /** + * Constructor. + * + * @param group + * @param groupNames + */ + public StatsLabelData(String group, List groupNames) { + this.groupNames = groupNames; + this.group = group; + } + + /** + * Get the group. + * + * @return + */ + public String getGroup() { + return group; + } + + /** + * Set the group + * + * @param group + */ + public void setGroup(String group) { + this.group = group; + } + + /** + * Get the group names + * + * @return + */ + public List getGroupNames() { + return groupNames; + } + + /** + * Set the group name list + * + * @param groupNames + */ + public void setGroupNames(List groupNames) { + this.groupNames = groupNames; + } + + /** + * Get the StatsLabelData object. + * + * @return + */ + public StatsLabelData getStatsLabelData() { + return statsLabelData; + } + + /** + * Set the StatsLabelData object + * + * @param statsLabelData + */ + public void setStatsLabelData(StatsLabelData statsLabelData) { + this.statsLabelData = statsLabelData; + } + + /** + * Add a group name. + * + * @param name + */ + public void addGroupName(String name) { + groupNames.add(name); + } + + /** + * Make the data keys + * + * @return List of the data keys + */ + public List makeKeys() { + ArrayList keysArray = new ArrayList(); + + if (statsLabelData == null) { + return groupNames; + } + + List subKeys = statsLabelData.makeKeys(); + + for (String grpName : groupNames) { + for (String subKey : subKeys) { + keysArray.add(grpName + ":" + subKey); + } + } + + return keysArray; + } + + /** + * Get the group and group names map. + * + * @return + */ + public LinkedHashMap> getGroupAndNamesMap() { + LinkedHashMap> groupMap = new LinkedHashMap>(); + + groupMap.put(group, groupNames); + + if (statsLabelData != null) { + LinkedHashMap> tmpMap = statsLabelData + .getGroupAndNamesMap(); + for (String s : tmpMap.keySet()) { + groupMap.put(s, tmpMap.get(s)); + } + } + + return groupMap; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/util/DataViewUtils.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/util/DataViewUtils.java new file mode 100644 index 0000000000..a9566df815 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/util/DataViewUtils.java @@ -0,0 +1,54 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.util; + +/** + * TODO Add Description + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 27, 2012            mpduff     Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class DataViewUtils { + public enum DataView { + AVG("Average"), MIN("Minimum"), MAX("Maximum"), + SUM("Sum"), COUNT("Count"); + + private final String view; + + private DataView(String view) { + this.view = view; + } + + public String getView() { + return view; + } + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/util/UnitUtils.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/util/UnitUtils.java new file mode 100644 index 0000000000..3369c245a6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/util/UnitUtils.java @@ -0,0 +1,287 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.util; + +import java.util.HashSet; +import java.util.Set; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; +import com.raytheon.uf.common.time.util.TimeUtil; + +/** + * Utility class for data size conversions. KB vs MB vs GB + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 14, 2012    728     mpduff      Initial creation.
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +public class UnitUtils implements ISerializableObject { + /** Bytes per Kilobyte */ + private static final double BYTES_PER_KILOBYTE = 1024.0; + + /** Different unit types for statistics */ + public static enum UnitTypes { + DATA_SIZE, TIME, COUNT + } + + /** + * Data Size Conversions + */ + public static enum DataSize { + KB("KB", BYTES_PER_KILOBYTE), MB("MB", BYTES_PER_KILOBYTE + * BYTES_PER_KILOBYTE), GB("GB", BYTES_PER_KILOBYTE + * BYTES_PER_KILOBYTE * BYTES_PER_KILOBYTE); + + private final String unit; + + private final double conversion; + + private static Set dataUnits; + + private DataSize(String unit, double conversion) { + this.unit = unit; + this.conversion = conversion; + populateSet(); + } + + private static void populateSet() { + dataUnits = new HashSet(); + dataUnits.add("KB"); + dataUnits.add("MB"); + dataUnits.add("GB"); + } + + public String getDataUnit() { + return unit; + } + + public double getConversion() { + return conversion; + } + + public static Set getDataUnits() { + return dataUnits; + } + } + + /** + * Time Conversions. + */ + public static enum TimeConversion { + MS("ms", 1), Second("seconds", TimeUtil.MILLIS_PER_SECOND), Minute( + "minutes", TimeUtil.MILLIS_PER_MINUTE), Hour("hours", + TimeUtil.MILLIS_PER_HOUR); + + private static Set dataUnits; + + private final String unit; + + private final double conversion; + + private TimeConversion(String unit, double conversion) { + this.unit = unit; + this.conversion = conversion; + populateSet(); + } + + private static void populateSet() { + dataUnits = new HashSet(); + dataUnits.add("seconds"); + dataUnits.add("ms"); + dataUnits.add("minutes"); + dataUnits.add("hours"); + } + + public String getDataUnit() { + return unit; + } + + public double getConversion() { + return conversion; + } + + public static Set getDataUnits() { + return dataUnits; + } + } + + /** The event type */ + private String eventType; + + /** The data type */ + private String dataType; + + /** The display unit */ + @DynamicSerializeElement + private String displayUnit; + + /** The unit type */ + @DynamicSerializeElement + private UnitTypes unitType; + + /** Copnversion factor */ + @DynamicSerializeElement + private double conversion = 1; + + /** + * Constructor + */ + public UnitUtils() { + + } + + /** + * Constructor + * + * @param eventType + * event type + * @param dataType + * event attribute/data type + */ + public UnitUtils(String eventType, String dataType) { + this.eventType = eventType; + this.dataType = dataType; + // Default to count + this.unitType = UnitTypes.COUNT; + } + + /** + * The largest value of the data set. This is used to determine which + * conversion to use if one is not specified. + * + * @param value + * Largest value of the data set + * + * @return The conversion factor + */ + public void setConversion(double value) { + // Which unit type is it? + if (unitType == UnitTypes.COUNT) { + conversion = 1; + } else if (unitType == UnitTypes.DATA_SIZE) { + if (value < DataSize.MB.getConversion()) { + conversion = DataSize.KB.getConversion(); + } else if (value < DataSize.GB.getConversion()) { + conversion = DataSize.MB.getConversion(); + } else if (value >= DataSize.GB.getConversion()) { + conversion = DataSize.GB.getConversion(); + } + } else if (unitType == UnitTypes.TIME) { + if (value < TimeUtil.MILLIS_PER_MINUTE) { + conversion = TimeUtil.MILLIS_PER_SECOND; + } else if (value < TimeUtil.MILLIS_PER_HOUR) { + conversion = TimeUtil.MILLIS_PER_MINUTE; + } else { + conversion = TimeUtil.MILLIS_PER_SECOND; + } + } + } + + /** + * @return the eventType + */ + public String getEventType() { + return eventType; + } + + /** + * @return the dataType + */ + public String getDataType() { + return dataType; + } + + /** + * Get the conversion + * + * @return + */ + public double getConversion() { + return conversion; + } + + /** + * @return the unitType + */ + public UnitTypes getUnitType() { + return unitType; + } + + /** + * @param unitType + * the unitType to set + */ + public void setUnitType(UnitTypes unitType) { + this.unitType = unitType; + } + + /** + * @return the displayUnit + */ + public String getDisplayUnit() { + return displayUnit; + } + + /** + * Set the display unit. + * + * @param displayUnit + */ + public void setDisplayUnit(String displayUnit) { + this.displayUnit = displayUnit; + + // Determine the unitType + if (DataSize.getDataUnits().contains(displayUnit)) { + unitType = UnitTypes.DATA_SIZE; + } else if (TimeConversion.getDataUnits().contains(displayUnit)) { + unitType = UnitTypes.TIME; + } + + if (unitType == UnitTypes.DATA_SIZE) { + if (displayUnit.equals(DataSize.KB.getDataUnit())) { + conversion = DataSize.KB.getConversion(); + } else if (displayUnit.equals(DataSize.MB.getDataUnit())) { + conversion = DataSize.MB.getConversion(); + } else if (displayUnit.equals(DataSize.GB.getDataUnit())) { + conversion = DataSize.GB.getConversion(); + } + } else if (unitType == UnitTypes.TIME) { + if (displayUnit.equals(TimeConversion.MS.getDataUnit())) { + conversion = 1; + } else if (displayUnit.equals(TimeConversion.Second.getDataUnit())) { + conversion = TimeUtil.MILLIS_PER_SECOND; + } else if (displayUnit.equals(TimeConversion.Minute.getDataUnit())) { + conversion = TimeUtil.MILLIS_PER_MINUTE; + } + } + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsAggregate.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsAggregate.java new file mode 100644 index 0000000000..388a98dbd2 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsAggregate.java @@ -0,0 +1,106 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.xml; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Statistics configuration aggregate element. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 6, 2012     728     mpduff      Initial creation.
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +@XmlRootElement(name = "statisticsAggregate") +@XmlAccessorType(XmlAccessType.NONE) +public class StatisticsAggregate { + /** the field to perform the function on. */ + @XmlAttribute + @DynamicSerializeElement + private String field; + + @XmlAttribute + @DynamicSerializeElement + private String displayName; + + @XmlAttribute + @DynamicSerializeElement + private String displayUnit; + + /** + * @return the field + */ + public String getField() { + return field; + } + + /** + * @param field + * the field to set + */ + public void setField(String field) { + this.field = field; + } + + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } + + /** + * @param displayName + * the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * @return the displayUnit + */ + public String getDisplayUnit() { + return displayUnit; + } + + /** + * @param displayUnit the displayUnit to set + */ + public void setDisplayUnit(String displayUnit) { + this.displayUnit = displayUnit; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsConfig.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsConfig.java new file mode 100644 index 0000000000..580683cda6 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsConfig.java @@ -0,0 +1,91 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.xml; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Statistical Configuration File. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 6, 2012      728    mpduff      Initial creation.
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +@XmlRootElement(name = "statisticsConfig") +@XmlAccessorType(XmlAccessType.NONE) +public class StatisticsConfig implements ISerializableObject { + @XmlElements({ @XmlElement(name = "statisticsEvent", type = StatisticsEvent.class) }) + @DynamicSerializeElement + private List events; + + /** + * @return the events + */ + public List getEvents() { + return events; + } + + /** + * @param events + * the events to set + */ + public void setEvents(List events) { + this.events = events; + } + + /** + * Return the list of categories in this config file. + * + * @return List of categories + */ + public List getCategories() { + Set categories = new HashSet(); + if (events != null && events.size() > 0) { + for (StatisticsEvent event : events) { + categories.add(event.getCategory()); + } + } + + return new ArrayList(categories); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsEvent.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsEvent.java new file mode 100644 index 0000000000..5f58b5a3d5 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsEvent.java @@ -0,0 +1,182 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.stats.xml; + +import java.lang.reflect.Method; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElements; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.event.Event; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * Statistics Configuration Event xml element. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 6, 2012    728      mpduff      Initial creation.
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ +@DynamicSerialize +@XmlRootElement(name = "event") +@XmlAccessorType(XmlAccessType.NONE) +public class StatisticsEvent { + + @XmlAttribute + @DynamicSerializeElement + private String type; + + @XmlAttribute + @DynamicSerializeElement + private String displayName; + + @XmlAttribute + @DynamicSerializeElement + private String category; + + @XmlElements({ @XmlElement(name = "statisticsGroup", type = StatisticsGroup.class) }) + @DynamicSerializeElement + private List groupList; + + @XmlElements({ @XmlElement(name = "statisticsAggregate", type = StatisticsAggregate.class) }) + @DynamicSerializeElement + private List aggregateList; + + private Class typeClass = null; + + private List groupByMethods = null; + + private List aggregateMethods = null; + + /** + * @return the aggregateList + */ + public List getAggregateList() { + return aggregateList; + } + + /** + * @return the category + */ + public String getCategory() { + return category; + } + + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } + + /** + * @return the groupList + */ + public List getGroupList() { + return groupList; + } + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @param aggregateList + * the aggregateList to set + */ + public void setAggregateList(List aggregateList) { + this.aggregateList = aggregateList; + } + + /** + * @param category + * the category to set + */ + public void setCategory(String category) { + this.category = category; + } + + /** + * @param displayName + * the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * @param groupList + * the groupList to set + */ + public void setGroupList(List groupList) { + this.groupList = groupList; + } + + /** + * @param type + * the type to set + */ + public void setType(String type) { + this.type = type; + } + + public Class getTypeClass() { + return typeClass; + } + + public void setTypeClass(Class typeClass) { + this.typeClass = typeClass; + } + + public List getGroupByMethods() { + return groupByMethods; + } + + public void setGroupByMethods(List groupByMethods) { + this.groupByMethods = groupByMethods; + } + + public List getAggregateMethods() { + return aggregateMethods; + } + + public void setAggregateMethods(List aggregateMethods) { + this.aggregateMethods = aggregateMethods; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelValue.java b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsGroup.java similarity index 64% rename from edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelValue.java rename to edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsGroup.java index ecb1ef729e..2ae4ce25da 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/LevelValue.java +++ b/edexOsgi/com.raytheon.uf.common.stats/src/com/raytheon/uf/common/stats/xml/StatisticsGroup.java @@ -1,75 +1,87 @@ /** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * + * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. - * + * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 - * + * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.level.xml; +package com.raytheon.uf.common.stats.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** - * Defines specific level values within a level. - * + * Statistics configuration groupBy element. + * *
+ *
  * SOFTWARE HISTORY
- * 
+ *
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Sep 03, 2009            rjpeter     Initial creation.
+ * Nov 6, 2012      728    mpduff      Initial creation.
+ *
  * 
- * - * @author rjpeter + * + * @author mpduff * @version 1.0 */ @DynamicSerialize -@XmlRootElement(namespace = "group") +@XmlRootElement(name = "statisticsGroup") @XmlAccessorType(XmlAccessType.NONE) -@XmlType(namespace = "group") -public class LevelValue implements ISerializableObject { - @DynamicSerializeElement +public class StatisticsGroup { @XmlAttribute - private Double valueOne; - @DynamicSerializeElement + private String name; + @XmlAttribute - private Double valueTwo; + @DynamicSerializeElement + private String displayName; - public Double getValueOne() { - return valueOne; + /** + * @return the name + */ + public String getName() { + return name; } - public void setValueOne(Double valueOne) { - this.valueOne = valueOne; + /** + * @param name + * the name to set + */ + public void setName(String name) { + this.name = name; } - public Double getValueTwo() { - return valueTwo; + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; } - public void setValueTwo(Double valueTwo) { - this.valueTwo = valueTwo; + /** + * @param displayName + * the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; } - } diff --git a/edexOsgi/com.raytheon.uf.common.time/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.time/META-INF/MANIFEST.MF index 96e2aa7ccb..e2914c2ca3 100644 --- a/edexOsgi/com.raytheon.uf.common.time/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.time/META-INF/MANIFEST.MF @@ -5,12 +5,12 @@ Bundle-SymbolicName: com.raytheon.uf.common.time Bundle-Version: 1.12.1174.qualifier Bundle-Vendor: RAYTHEON Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: net.sf.cglib -Import-Package: com.raytheon.uf.common.serialization, - com.raytheon.uf.common.serialization.adapters, - com.raytheon.uf.common.serialization.annotations, - com.raytheon.uf.common.serialization.comm, - javax.persistence, +Require-Bundle: net.sf.cglib, + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + com.raytheon.uf.common.util;bundle-version="1.12.1174" +Import-Package: javax.persistence, org.apache.commons.beanutils, org.apache.commons.lang, org.apache.commons.lang.builder, diff --git a/edexOsgi/com.raytheon.uf.common.time/res/spring/time-common.xml b/edexOsgi/com.raytheon.uf.common.time/res/spring/time-common.xml index 499243104b..061cb94a31 100644 --- a/edexOsgi/com.raytheon.uf.common.time/res/spring/time-common.xml +++ b/edexOsgi/com.raytheon.uf.common.time/res/spring/time-common.xml @@ -1,21 +1,18 @@ + xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd"> - + com.raytheon.uf.common.time.DataTime - + java.util.Calendar - + java.util.Date diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/BinOffset.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/BinOffset.java index d8ac36da97..8c132aecbd 100644 --- a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/BinOffset.java +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/BinOffset.java @@ -20,6 +20,8 @@ package com.raytheon.uf.common.time; import java.util.Date; +import java.util.HashSet; +import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; @@ -140,6 +142,22 @@ public class BinOffset implements ISerializableObject { return normalizedTime; } + /** + * Takes range and offsets into account to determine what the times should + * be normalized to in the range + * + * @param times + * the times to normalize + * @return the normalized times + */ + public Set getNormalizedTimes(DataTime[] times) { + Set set = new HashSet(); + for (DataTime dt : times) { + set.add(getNormalizedTime(dt)); + } + return set; + } + public TimeRange getTimeRange(DataTime baseTime) { long negSkew = -negOffset * 1000l; long posSkew = posOffset * 1000l; diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/SimulatedTime.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/SimulatedTime.java index 32c1cc5306..dcf3bf8897 100644 --- a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/SimulatedTime.java +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/SimulatedTime.java @@ -32,9 +32,12 @@ import java.util.TimeZone; * *
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * Jul 16, 2008				randerso	Initial creation
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 16, 2008            randerso    Initial creation
+ * Aug 24, 2012 0743       djohnson    Add option to use milliseconds for operations, change to singleton.
+ * Nov 02, 2012 1302       djohnson    Change mistakenly public constructor to private.
  * 
  * 
* @@ -42,7 +45,7 @@ import java.util.TimeZone; * @version 1.0 */ -public class SimulatedTime { +public final class SimulatedTime { /** * The system global simulated time instance */ @@ -95,7 +98,7 @@ public class SimulatedTime { * Creates a simulated time that matches real time. * */ - public SimulatedTime() { + private SimulatedTime() { setRealTime(); } @@ -111,8 +114,24 @@ public class SimulatedTime { * @param isFrozen * true to freeze time */ - public SimulatedTime(Date date, double scale, boolean isFrozen) { - setTime(date); + private SimulatedTime(Date date, double scale, boolean isFrozen) { + this(date.getTime(), scale, isFrozen); + } + + /** + * Creates a simulated time starting at the specified time with + * acceleration/deceleration, optionally frozen. + * + * @param millis + * starting time in milliseconds + * @param scale + * 1.0 for normal time rate, >1.0 for accelerated time < 1.0 for + * decelerated time. If negative time will run backward. + * @param isFrozen + * true to freeze time + */ + private SimulatedTime(long millis, double scale, boolean isFrozen) { + setTime(millis); this.scale = scale; this.isFrozen = isFrozen; } @@ -142,11 +161,14 @@ public class SimulatedTime { * @return current simulated time */ public Date getTime() { + return new Date(getMillis()); + } + + public long getMillis() { if (isFrozen) { - return new Date(frozenTime); + return frozenTime; } else { - return new Date(Math.round((now() - baseTime) * scale) + baseTime - + offset); + return Math.round((now() - baseTime) * scale) + baseTime + offset; } } @@ -156,11 +178,20 @@ public class SimulatedTime { * @param date */ public void setTime(Date date) { + setTime(date.getTime()); + } + + /** + * Set the current simulated time + * + * @param millis + */ + public void setTime(long millis) { if (isFrozen) { - frozenTime = date.getTime(); + frozenTime = millis; } else { baseTime = now(); - offset = date.getTime() - baseTime; + offset = millis - baseTime; } } @@ -206,7 +237,7 @@ public class SimulatedTime { } if (isFrozen) { - frozenTime = getTime().getTime(); + frozenTime = getMillis(); } else { baseTime = now(); offset = frozenTime - baseTime; diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/AbstractTimer.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/AbstractTimer.java new file mode 100644 index 0000000000..0be0ed7b40 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/AbstractTimer.java @@ -0,0 +1,107 @@ +package com.raytheon.uf.common.time.util; + + +/** + * + * Provides the basic {@link ITimer} implementation, such as the state machine + * functionality. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 16, 2012 0743       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +// @NotThreadSafe +abstract class AbstractTimer implements ITimer { + private long start; + + private long stop; + + private long elapsedTime; + + /** + * {@inheritDoc} + */ + @Override + public void start() { + if (isTimerStopped()) { + elapsedTime += (stop - start); + stop = 0; + } else if (isTimerStarted()) { + throw new IllegalStateException( + "A timer that is running must be stopped before start() is called again!"); + } + this.start = getCurrentTime(); + } + + /** + * {@inheritDoc} + */ + @Override + public void stop() { + if (!isTimerStarted()) { + throw new IllegalStateException( + "Timer must be started before it can be stopped!"); + } + // If the timer has already been stopped, don't change the time + if (!isTimerStopped()) { + this.stop = getCurrentTime(); + } + } + + /** + * {@inheritDoc} + */ + @Override + public long getElapsedTime() { + long currentOrStopTime = (isTimerRunning()) ? getCurrentTime() : stop; + return (currentOrStopTime - start) + elapsedTime; + } + + /** + * {@inheritDoc} + */ + @Override + public void reset() { + start = 0; + stop = 0; + elapsedTime = 0; + } + + protected abstract long getCurrentTime(); + + /** + * Check whether the timer is actively running. + * + * @return true if the timer is running + */ + private boolean isTimerRunning() { + return isTimerStarted() && !isTimerStopped(); + } + + /** + * Check whether the timer was started. + * + * @return true if the timer was started + */ + private boolean isTimerStarted() { + return start > 0; + } + + /** + * Check whether the timer is stopped. + * + * @return true if the timer is stopped + */ + private boolean isTimerStopped() { + return stop > 0; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ITimeStrategy.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ITimeStrategy.java new file mode 100644 index 0000000000..77a25a02f0 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ITimeStrategy.java @@ -0,0 +1,32 @@ +package com.raytheon.uf.common.time.util; + +/** + * + * Denotes a strategy to retrieve the current time. In production this will + * always retrieve it from {@link System#currentTimeMillis()} but in tests it + * can be used to give the behavior of specific time spans, or to freeze time + * entirely. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 16, 2012 0743       djohnson     Initial creation
+ * Nov 02, 2012 1302       djohnson     Add more Javadoc.
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +interface ITimeStrategy { + + /** + * Retrieves the current time in milliseconds. + * + * @return the current time in milliseconds + */ + long currentTimeMillis(); +} \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ITimer.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ITimer.java new file mode 100644 index 0000000000..0a028176ad --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ITimer.java @@ -0,0 +1,50 @@ +package com.raytheon.uf.common.time.util; + +/** + * + * Defines a timer that can be started and stopped. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 16, 2012 0743       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public interface ITimer { + + /** + * Start the time on the timer. + * + * @throws IllegalStateException + * if the timer is already running, or has been stopped and not + * reset + */ + void start() throws IllegalStateException; + + /** + * Stop the time on the timer. + * + * @throws IllegalStateException + * if the timer hasn't been started + */ + void stop() throws IllegalStateException; + + /** + * Get the elapsed time, in milliseconds. + * + * @return the elapsed time in milliseconds + */ + long getElapsedTime(); + + /** + * Reset the timer. + */ + void reset(); +} diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ImmutableDate.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ImmutableDate.java new file mode 100644 index 0000000000..b46fe7c2b3 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ImmutableDate.java @@ -0,0 +1,201 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.time.util; + +import java.util.Date; + +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.raytheon.uf.common.serialization.IDeserializationContext; +import com.raytheon.uf.common.serialization.ISerializationContext; +import com.raytheon.uf.common.serialization.ISerializationTypeAdapter; +import com.raytheon.uf.common.serialization.SerializationException; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeTypeAdapter; +import com.raytheon.uf.common.time.SimulatedTime; + +/** + * An immutable version of {@link Date}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 15, 2012 0743       djohnson     Initial creation
+ * Sep 19, 2012 0726       jspinks      Added XmlJavaTypeAdaptor annotation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +@XmlJavaTypeAdapter(value=ImmutableDateAdapter.class) +// @Immutable +@DynamicSerialize +@DynamicSerializeTypeAdapter(factory = ImmutableDate.class) +public final class ImmutableDate extends Date implements + ISerializationTypeAdapter { + + private static final long serialVersionUID = -4228048757897650258L; + + private static final String IMMUTABLE_MSG = "This version of date is immutable."; + + private static final String IMMUTABLE_AND_DEPRECATED_MSG = IMMUTABLE_MSG + + " In addition, this method is deprecated."; + + private final int hashCode; + + /** + * Construct an {@link ImmutableDate} from the current time. + */ + public ImmutableDate() { + this(SimulatedTime.getSystemTime().getMillis()); + } + + + /** + * Construct an {@link ImmutableDate} from a {@link Date} object. + * + * @param date + * the date + */ + public ImmutableDate(Date date) { + this(date.getTime()); + } + + /** + * Construct an {@link ImmutableDate} from the specified time in + * milliseconds. + * + * @param time + * the millliseconds + */ + public ImmutableDate(long time) { + super(time); + + this.hashCode = super.hashCode(); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param year + * @throws UnsupportedOperationException + */ + @Override + public void setYear(int year) { + throw new UnsupportedOperationException( + IMMUTABLE_AND_DEPRECATED_MSG); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param month + * @throws UnsupportedOperationException + */ + @Override + public void setMonth(int month) { + throw new UnsupportedOperationException(IMMUTABLE_AND_DEPRECATED_MSG); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param date + * @throws UnsupportedOperationException + */ + @Override + public void setDate(int date) { + throw new UnsupportedOperationException(IMMUTABLE_AND_DEPRECATED_MSG); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param hours + * @throws UnsupportedOperationException + */ + @Override + public void setHours(int hours) { + throw new UnsupportedOperationException(IMMUTABLE_AND_DEPRECATED_MSG); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param minutes + * @throws UnsupportedOperationException + */ + @Override + public void setMinutes(int minutes) { + throw new UnsupportedOperationException(IMMUTABLE_AND_DEPRECATED_MSG); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param seconds + * @throws UnsupportedOperationException + */ + @Override + public void setSeconds(int seconds) { + throw new UnsupportedOperationException(IMMUTABLE_AND_DEPRECATED_MSG); + } + + /** + * Overridden to throw {@link UnsupportedOperationException}. + * + * @param time + * @throws UnsupportedOperationException + */ + @Override + public void setTime(long time) { + throw new UnsupportedOperationException(IMMUTABLE_MSG); + } + + /** + * {@inheritDoc} + */ + @Override + public int hashCode() { + return hashCode; + } + + /** + * {@inheritDoc} + */ + @Override + public void serialize(ISerializationContext serializer, ImmutableDate object) + throws SerializationException { + serializer.writeI64(object.getTime()); + } + + /** + * {@inheritDoc} + */ + @Override + public ImmutableDate deserialize(IDeserializationContext deserializer) + throws SerializationException { + return new ImmutableDate(deserializer.readI64()); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ImmutableDateAdapter.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ImmutableDateAdapter.java new file mode 100644 index 0000000000..f54ef4e241 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/ImmutableDateAdapter.java @@ -0,0 +1,38 @@ +package com.raytheon.uf.common.time.util; + +import java.util.Date; + +import javax.xml.bind.annotation.adapters.XmlAdapter; + +/** + * An {@link XmlAdapter} version that allows JABX marshaling/unmarshaling + * of {@link ImmutableDate}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 19, 2012 726        jspinks     Initial creation
+ * 
+ * 
+ * + * @version 1.0 + */ +public class ImmutableDateAdapter extends XmlAdapter { + + @Override + public ImmutableDate unmarshal(Date date) throws Exception { + return new ImmutableDate(date); + } + + /** + * + * @return + */ + @Override + public Date marshal(ImmutableDate immutableDate) throws Exception { + return immutableDate; + } +} diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimeUtil.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimeUtil.java index f137f1813f..5f1e23940d 100644 --- a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimeUtil.java +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimeUtil.java @@ -1,19 +1,19 @@ /** * 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. **/ @@ -25,26 +25,83 @@ import java.util.Calendar; import java.util.Date; import java.util.TimeZone; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.time.SimulatedTime; + /** * Utilities for time, some extracted from Util. - * + * *
- * 
+ *
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Feb 2, 2009            njensen     Initial creation
- * 
+ * Feb 02, 2009            njensen     Initial creation
+ * Sep 11, 2012 1154       djohnson    Add MILLIS constants and isNewerDay().
+ * Nov 09, 2012 1322       djohnson    Add SECONDS_PER_MINUTE.
+ * Nov 21, 2012  728       mpduff      Added MILLIS_PER_MONTH.
+ *
  * 
- * + * * @author njensen * @version 1.0 */ public class TimeUtil { + /** + * A clock that does not really return the current time. Useful when you + * only want to keep track of times in a conditional sense, such as if a + * logging priority is enabled. This is an example of the Null Object + * pattern. + * + * @see http://en.wikipedia.org/wiki/Null_Object_pattern + * + * @author djohnson + * + */ + private static class NullClock extends AbstractTimer { + @Override + protected long getCurrentTime() { + return 1; + } + } + + /** + * Delegates the retrieval of the current time to the system clock. + * Production code will always use this. + * + * @author djohnson + * + */ + private static class SystemTimeStrategy implements ITimeStrategy { + @Override + public long currentTimeMillis() { + return System.currentTimeMillis(); + } + } + public static final String DATE_STRING = "(\\d{4})-(\\d{2})-(\\d{2})[ _](\\d{2}):(\\d{2}):(\\d{2})\\.(\\d{1,3})"; + // Util.java has a few of these constants, but that is located in an EDEX + // plugin and this is a more appropriate place for them anyways + public static final long MILLIS_PER_SECOND = 1000; + + public static final long MILLIS_PER_MINUTE = MILLIS_PER_SECOND * 60; + + public static final long MILLIS_PER_HOUR = MILLIS_PER_MINUTE * 60; + + public static final long MILLIS_PER_DAY = MILLIS_PER_HOUR * 24; + + public static final long MILLIS_PER_WEEK = MILLIS_PER_DAY * 7; + + public static final long MILLIS_PER_MONTH = MILLIS_PER_DAY * 30; + + public static final long MILLIS_PER_YEAR = 3600 * 24 * 1000 * 365; + + public static final int SECONDS_PER_MINUTE = 60; + // create instance of simple date format on class load, as instantiating it // is expensive the SimpleDateFormat class is not thread-safe, // so calling methods use synchronized @@ -58,52 +115,18 @@ public class TimeUtil { sqlSdf.setTimeZone(TimeZone.getTimeZone("GMT")); } - /** - * Retrieve date as a string in the index standard format: yyyy-MM-dd - * kk:mm:ss.SSS - * - * @param aCalendar - * A Calendar instance - * @return The formatted date string from the Calendar instance - */ - public static String formatDate(Calendar aCalendar) { - return formatDate(aCalendar.getTime()); - } + static final ITimeStrategy SYSTEM_TIME_STRATEGY = new SystemTimeStrategy(); + + static final ITimer NULL_CLOCK = new NullClock(); /** - * Retrieve date as a string in the index standard format: yyyy-MM-dd - * kk:mm:ss.SSS - * - * @param aDate - * A Date instance - * @return The formatted date string from the Date instance + * The strategy to retrieve the "current time" value from. */ - public static String formatDate(Date aDate) { - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cal.setTimeInMillis(aDate.getTime()); - return formatCalendar(cal); - } - - /** - * Formats a calendar object into the following format yyyy-MM-dd_HH:mm:ss.S - * - * @param cal - * The calendar to format - * @return The formatted result - */ - public static String formatCalendar(Calendar cal) { - String format = null; - - synchronized (sdf) { - sdf.setTimeZone(cal.getTimeZone()); - format = sdf.format(cal.getTime()); - } - return format; - } + static ITimeStrategy timeStrategy = SYSTEM_TIME_STRATEGY; /** * Converts a Calendar in the local time zone to a GMT date - * + * * @param cal * A Calendar object in the local time zone * @return The GMT date @@ -125,6 +148,66 @@ public class TimeUtil { return dt; } + /** + * Retrieve the current time in milliseconds. This method should be used + * instead of {@link System#currentTimeMillis()}. This method DOES NOT use + * {@link SimulatedTime} and therefore should be isolated to duration + * checks, and logging type statements. If the desired result is the + * currently configured system time, e.g. CAVE sessions where the user has + * configured the system to a specific time. Those purposes are handled by + * the {@link SimulatedTime} class. The {@link Date} and {@link Calendar} + * returning methods in this class will delegate to {@link SimulatedTime}. + * + * @see {@link SimulatedTime} + * @return the current time in milliseconds + */ + public static long currentTimeMillis() { + return timeStrategy.currentTimeMillis(); + } + + /** + * Formats a calendar object into the following format yyyy-MM-dd_HH:mm:ss.S + * + * @param cal + * The calendar to format + * @return The formatted result + */ + public static String formatCalendar(Calendar cal) { + String format = null; + + synchronized (sdf) { + sdf.setTimeZone(cal.getTimeZone()); + format = sdf.format(cal.getTime()); + } + return format; + } + + /** + * Retrieve date as a string in the index standard format: yyyy-MM-dd + * kk:mm:ss.SSS + * + * @param aCalendar + * A Calendar instance + * @return The formatted date string from the Calendar instance + */ + public static String formatDate(Calendar aCalendar) { + return formatDate(aCalendar.getTime()); + } + + /** + * Retrieve date as a string in the index standard format: yyyy-MM-dd + * kk:mm:ss.SSS + * + * @param aDate + * A Date instance + * @return The formatted date string from the Date instance + */ + public static String formatDate(Date aDate) { + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + cal.setTimeInMillis(aDate.getTime()); + return formatCalendar(cal); + } + public static long formattedDateToLong(String formattedDate) { long retVal = 0; try { @@ -141,4 +224,109 @@ public class TimeUtil { } } + /** + * Retrieve a {@link ITimer} instance that will only actually keep track of + * time if the specified priority level is enabled. This allows efficient + * use of system resources, while calling code need not change. + * + * @param handler + * the handler to use to check for a priority level being enabled + * @param priority + * the priority level + * @return the {@link ITimer} instance + */ + public static ITimer getPriorityEnabledTimer(IUFStatusHandler handler, + Priority priority) { + return handler.isPriorityEnabled(priority) ? getTimer() : NULL_CLOCK; + } + + /** + * Retrieve a {@link ITimer} that allows the demarcation of arbitrary start + * and stop times. + * + * @return a {@link ITimer} + */ + public static ITimer getTimer() { + return new TimerImpl(); + } + + /** + * Check whether the time represented by a {@link Date} is a new day + * compared to another {@link Date} object. + * + * @param earlierDate + * the earlier date + * @param laterDate + * the later date + * @param timeZone + * the timeZone to use when determining what date it is for the + * specified time + * @return true if the laterDate is a new day compared to earlierDate + */ + public static boolean isNewerDay(Date earlierDate, Date laterDate, + TimeZone timeZone) { + Calendar earlierCal = TimeUtil.newCalendar(timeZone); + earlierCal.setTime(earlierDate); + + Calendar laterCal = TimeUtil.newCalendar(timeZone); + laterCal.setTime(laterDate); + + return laterCal.get(Calendar.DAY_OF_YEAR) > earlierCal + .get(Calendar.DAY_OF_YEAR) + || laterCal.get(Calendar.YEAR) > earlierCal.get(Calendar.YEAR); + } + + /** + * Return a new {@link Calendar} instance. This method delegates to the + * {@link SimulatedTime} class to determine the currently configured system + * time. + * + * @see {@link SimulatedTime} + * @return the calendar + */ + public static Calendar newCalendar() { + Calendar cal = Calendar.getInstance(); + cal.setTimeInMillis(SimulatedTime.getSystemTime().getMillis()); + return cal; + } + + /** + * Return a new {@link Calendar} instance for the specified {@link TimeZone} + * . This method delegates to the {@link SimulatedTime} class to determine + * the currently configured system time. + * + * @param timeZone + * the time zone + * @see {@link SimulatedTime} + * @return the calendar + */ + public static Calendar newCalendar(TimeZone timeZone) { + Calendar cal = Calendar.getInstance(timeZone); + cal.setTimeInMillis(SimulatedTime.getSystemTime().getMillis()); + return cal; + } + + /** + * Return a new {@link Date} instance. This method delegates to the + * {@link SimulatedTime} class to determine the currently configured system + * time. + * + * @see {@link SimulatedTime} + * @return the current {@link Date} + */ + public static Date newDate() { + return SimulatedTime.getSystemTime().getTime(); + } + + /** + * Return a new ImmutableDate. This method delegates to the + * {@link SimulatedTime} class to determine the currently configured system + * time. + * + * @see {@link SimulatedTime} + * @return an immutable date for the current time + */ + public static ImmutableDate newImmutableDate() { + return new ImmutableDate(SimulatedTime.getSystemTime().getMillis()); + } } diff --git a/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimerImpl.java b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimerImpl.java new file mode 100644 index 0000000000..337deafa35 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.time/src/com/raytheon/uf/common/time/util/TimerImpl.java @@ -0,0 +1,33 @@ +package com.raytheon.uf.common.time.util; + + +/** + * + * A default {@link ITimer} implementation that will use + * {@link TimeUtil#currentTimeMillis()} to keep track of time. It is good for + * use inside both production code and tests. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 16, 2012 0743       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +// @NotThreadSafe +class TimerImpl extends AbstractTimer { + + /** + * {@inheritDoc} + */ + @Override + protected long getCurrentTime() { + return TimeUtil.currentTimeMillis(); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.units/.classpath b/edexOsgi/com.raytheon.uf.common.units/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.units/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.common.units/.project b/edexOsgi/com.raytheon.uf.common.units/.project new file mode 100644 index 0000000000..a5e13db529 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.units/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.common.units + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.common.units/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.common.units/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..5df4e25912 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.units/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Nov 05 16:48:55 CST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.common.units/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.units/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..c46b0bd322 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.units/META-INF/MANIFEST.MF @@ -0,0 +1,11 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Units +Bundle-SymbolicName: com.raytheon.uf.common.units +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: javax.measure;bundle-version="1.0.0";visibility:=reexport, + com.raytheon.uf.common.util;bundle-version="1.12.1174", + org.apache.commons.beanutils;bundle-version="1.8.3" +Export-Package: com.raytheon.uf.common.units diff --git a/edexOsgi/com.raytheon.uf.common.units/build.properties b/edexOsgi/com.raytheon.uf.common.units/build.properties new file mode 100644 index 0000000000..5791d48d5f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.units/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ diff --git a/edexOsgi/com.raytheon.uf.common.units/res/spring/units-common.xml b/edexOsgi/com.raytheon.uf.common.units/res/spring/units-common.xml new file mode 100644 index 0000000000..f34aad4525 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.units/res/spring/units-common.xml @@ -0,0 +1,10 @@ + + + + + javax.measure.unit.Unit + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/convert/UnitConverter.java b/edexOsgi/com.raytheon.uf.common.units/src/com/raytheon/uf/common/units/UnitConverter.java similarity index 94% rename from edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/convert/UnitConverter.java rename to edexOsgi/com.raytheon.uf.common.units/src/com/raytheon/uf/common/units/UnitConverter.java index aa70f3f2fc..e88faa4c19 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/convert/UnitConverter.java +++ b/edexOsgi/com.raytheon.uf.common.units/src/com/raytheon/uf/common/units/UnitConverter.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.convert; +package com.raytheon.uf.common.units; import java.text.ParseException; @@ -41,7 +41,7 @@ import org.apache.commons.beanutils.Converter; */ public class UnitConverter implements Converter { - @SuppressWarnings("unchecked") + @SuppressWarnings("rawtypes") @Override public Object convert(Class clazz, Object value) { if (value instanceof String) { diff --git a/edexOsgi/com.raytheon.uf.common.util/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.common.util/META-INF/MANIFEST.MF index d4b62e6588..bb0e35bd63 100644 --- a/edexOsgi/com.raytheon.uf.common.util/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.common.util/META-INF/MANIFEST.MF @@ -5,9 +5,13 @@ Bundle-SymbolicName: com.raytheon.uf.common.util Bundle-Version: 1.12.1174.qualifier Bundle-Vendor: RAYTHEON Bundle-RequiredExecutionEnvironment: JavaSE-1.6 -Require-Bundle: org.junit;bundle-version="1.0.0" +Require-Bundle: org.junit;bundle-version="1.0.0", + org.apache.commons.beanutils;bundle-version="1.8.3", + com.raytheon.uf.common.status;bundle-version="1.12.1174" Export-Package: com.raytheon.uf.common.util, com.raytheon.uf.common.util.cache, com.raytheon.uf.common.util.header, - com.raytheon.uf.common.util.registry + com.raytheon.uf.common.util.registry, + com.raytheon.uf.common.util.mapping, + com.raytheon.uf.common.util.session Import-Package: org.apache.commons.lang diff --git a/edexOsgi/com.raytheon.uf.common.util/component-deploy.xml b/edexOsgi/com.raytheon.uf.common.util/component-deploy.xml deleted file mode 100644 index 15709bdd0b..0000000000 --- a/edexOsgi/com.raytheon.uf.common.util/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/CollectionUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/CollectionUtil.java new file mode 100644 index 0000000000..c9b21378ae --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/CollectionUtil.java @@ -0,0 +1,84 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + + +/** + * Utility class for collection types. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 13, 2012 740        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public final class CollectionUtil { + + private CollectionUtil() { + + } + + /** + * Check whether an array is null or empty. + * + * @param array + * the array + * @return true if the array is null or empty + */ + public static boolean isNullOrEmpty(T[] array) { + return array == null || array.length == 0; + } + + /** + * Check whether a collection is null or empty. + * + * @param coll + * the collection + * @return true if the collection is null or empty + */ + public static boolean isNullOrEmpty(Collection coll) { + return coll == null || coll.isEmpty(); + } + + /** + * Create a set from the specified items. Assumes the items can be stored in + * a {@link HashSet}. + * + * @param items + * the items + * @return the set + */ + public static Set asSet(T... items) { + return new HashSet(Arrays.asList(items)); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/convert/ConvertUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ConvertUtil.java similarity index 57% rename from edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/convert/ConvertUtil.java rename to edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ConvertUtil.java index 8b0fc37f44..5bf7204cff 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin/src/com/raytheon/uf/common/dataplugin/convert/ConvertUtil.java +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ConvertUtil.java @@ -17,7 +17,13 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.convert; +package com.raytheon.uf.common.util; + +import java.lang.reflect.Field; +import java.util.Calendar; +import java.util.Date; + +import javax.xml.bind.DatatypeConverter; import org.apache.commons.beanutils.ConvertUtils; import org.apache.commons.beanutils.Converter; @@ -86,7 +92,58 @@ public class ConvertUtil { if (value.equals("null")) { return null; } + if (desiredClass.equals(Calendar.class)) { + try { + // see if string is in ISO 8601 + return DatatypeConverter.parseDateTime(value); + } catch (Exception e) { + // let convertUtils try + } + } + if (desiredClass.equals(Date.class)) { + try { + // see if string is in ISO 8601 + return DatatypeConverter.parseDateTime(value).getTime(); + } catch (Exception e) { + // let convertUtils try + } + } return ConvertUtils.convert(value, desiredClass); } + public static String toString(Object obj) { + return ConvertUtils.convert(obj); + } + + public static Object convertAsType(String value, Class entity, + String fieldName) throws SecurityException, NoSuchFieldException { + Field field = getField(fieldName, entity); + return convertObject(value, field.getType()); + } + + public static Object convertAsType(String value, Class entity, + String[] fieldPath) throws SecurityException, NoSuchFieldException { + Field f = getField(fieldPath[0], entity); + for (int i = 1; i < fieldPath.length; ++i) { + f = getField(fieldPath[i], f.getType()); + } + return convertObject(value, f.getType()); + } + + protected static Field getField(String fieldName, Class c) + throws SecurityException, NoSuchFieldException { + Field rval; + try { + rval = c.getDeclaredField(fieldName); + } catch (NoSuchFieldException e) { + Class parent = c.getSuperclass(); + if (parent.isInstance(Object.class)) { + throw e; + } else { + rval = getField(fieldName, c.getSuperclass()); + } + } + return rval; + } + } diff --git a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GribSkewTLoadProperties.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ExceptionUtil.java similarity index 63% rename from cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GribSkewTLoadProperties.java rename to edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ExceptionUtil.java index 2565c600a3..9deebf6dca 100644 --- a/cave/com.raytheon.viz.grid/src/com/raytheon/viz/grid/rsc/GribSkewTLoadProperties.java +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ExceptionUtil.java @@ -17,44 +17,45 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.viz.grid.rsc; - -import com.raytheon.uf.viz.core.rsc.LoadProperties; +package com.raytheon.uf.common.util; /** - * TODO Add Description + * Utilities for working with {@link Exception}s. * *
  * 
  * SOFTWARE HISTORY
+ * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Feb 20, 2009            chammack     Initial creation
- * 10-21-09     #1711      bsteffen    Updated Cordiante rather than POINT
+ * Jul 5, 2012  740        djohnson     Initial creation
  * 
  * 
* - * @author chammack + * @author djohnson * @version 1.0 */ -public class GribSkewTLoadProperties extends LoadProperties { +public final class ExceptionUtil { - private String point; - - /** - * @return the point - */ - public String getPoint() { - return point; + private ExceptionUtil() { } /** - * @param point - * the point to set + * Retrieve the root cause of a {@link Throwable} chain. + * + * @param t + * the throwable + * @return the root cause */ - public void setPoint(String point) { - this.point = point; + public static Throwable getRootCause(Throwable t) { + Throwable result = t; + + while (result.getCause() != null) { + result = result.getCause(); + } + + return result; } } diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/FileUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/FileUtil.java index d96e390326..1c606eb9e8 100644 --- a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/FileUtil.java +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/FileUtil.java @@ -49,7 +49,7 @@ import java.util.zip.GZIPOutputStream; * return false when unable to * obtain directory listing. * Sep 16, 2008 1250 jelkins Added join function - * - AWIPS2 Baseline Repository -------- + * Jun 28, 2012 0819 djohnson Add write method. * Jul 06, 2012 798 jkorman Added more robust {@link #copyFile}. Added methods * to create temporary directories and files. * @@ -619,6 +619,24 @@ public class FileUtil { public static boolean isValidFilename(String fileName) { return VALID_FILENAME.matcher(fileName).matches(); } + + /** + * Write the contents of an input stream to a file. + * + * @param is + * the input stream to read from + * @param file + * the file to write to + * @throws IOException + */ + public static void write(InputStream is, File file) throws IOException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + + int read = 0; + while ((read = is.read()) != -1) { + os.write(read); + } + } /** * Copy a file from one location to another. The file copy may begin at some diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/JarUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/JarUtil.java index 2314d27915..46a36be939 100644 --- a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/JarUtil.java +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/JarUtil.java @@ -21,6 +21,7 @@ package com.raytheon.uf.common.util; import java.io.File; import java.io.IOException; +import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; @@ -29,7 +30,7 @@ import java.util.jar.JarEntry; import java.util.jar.JarFile; /** - * TODO Add Description + * Utilities for working with Jar files. * *
  * 
@@ -38,6 +39,7 @@ import java.util.jar.JarFile;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Jan 28, 2011            njensen     Initial creation
+ * Nov 09, 2012 1322       djohnson    Add getResResourcePath.
  * 
  * 
* @@ -179,4 +181,24 @@ public class JarUtil { } } + /** + * Attempts to find the specified resource on the classpath. First it + * searches for the provided string resource path, if that fails, returns + * the string prepended with "/res" since that is where the "res" resources + * are placed in the jar files. This is required because in Eclipse the + * Spring files are not prepended with "res" as they are in jar files. + * + * @param resourcePath + * the resource path + * @return the String resource path to use + */ + public static String getResResourcePath(String resourcePath) { + URL url = JarUtil.class.getResource(resourcePath); + if (url != null) { + return resourcePath; + } else { + return "/res" + resourcePath; + } + } + } diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/LogUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/LogUtil.java new file mode 100644 index 0000000000..ca00d4f3f8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/LogUtil.java @@ -0,0 +1,74 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus.Priority; + +/** + * Utilities for logging. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 26, 2012 1322       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public final class LogUtil { + + private LogUtil() { + } + + /** + * Logs the message, then each iterable to the output with a new line + * separator between each iterable. + * + *
+     * 
+     * Example:
+     * 
+     * This would be the message:
+     *    iterable1
+     *    iterable2
+     * 
+ * + * @param statusHandler + * the status handler + * @param priority + * the priority + * @param message + * the message + * @param iterable + * the iterables + */ + public static void logIterable(IUFStatusHandler statusHandler, + Priority priority, String message, Iterable iterables) { + String msg = StringUtil.createMessage(message, iterables, 3); + statusHandler.handle(priority, msg); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/PropertiesUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/PropertiesUtil.java new file mode 100644 index 0000000000..3f2dc3db28 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/PropertiesUtil.java @@ -0,0 +1,107 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import java.io.Closeable; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.Properties; + +/** + * Utility class to work with {@link Properties}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jun 28, 2012 819        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public final class PropertiesUtil { + + /** + * Prevent instantiation. + */ + private PropertiesUtil() { + } + + /** + * Read an input stream to load a {@link Properties} instance. + * + * @param is + * the input stream + * @return the Properties + * @throws IOException + * on error reading the {@link InputStream} + */ + public static Properties read(InputStream is) throws IOException { + Reader reader = null; + try { + reader = new InputStreamReader(is); + + Properties properties = new Properties(); + properties.load(reader); + + return properties; + } finally { + close(reader); + } + } + + /** + * Read a {@link File} to load a {@link Properties} instance. + * + * @param file + * the file to read + * @return the Properties + * @throws IOException + * on error reading the {@link File} + */ + public static Properties read(File file) throws IOException { + InputStream is = null; + try { + is = new FileInputStream(file); + return read(is); + } finally { + close(is); + } + } + + public static void close(Closeable closeable) { + if (closeable != null) { + try { + closeable.close(); + } catch (IOException e) { + // Nothing to do, closing... + } + } + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ReflectionException.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ReflectionException.java new file mode 100644 index 0000000000..30d12bd487 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ReflectionException.java @@ -0,0 +1,58 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +/** + * A wrapper runtime exception for problems that occur with reflection. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 10, 2012 634        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class ReflectionException extends RuntimeException { + + private static final long serialVersionUID = -6622684607744047392L; + + public ReflectionException() { + super(); + } + + public ReflectionException(String message, Throwable cause) { + super(message, cause); + } + + public ReflectionException(String message) { + super(message); + } + + public ReflectionException(Throwable cause) { + super(cause); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ReflectionUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ReflectionUtil.java new file mode 100644 index 0000000000..96e693721b --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/ReflectionUtil.java @@ -0,0 +1,238 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import org.apache.commons.beanutils.PropertyUtils; + +/** + * Reflection utilities. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 10, 2012 634        djohnson     Initial creation
+ * Jul 10, 2012 455        djohnson     Move in methods from RegistryUtil, 
+ *                                      fix setter method to use parameter types.
+ * Sep 28, 2012 1195       djohnson     Add {@link #forName(String)}.
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public final class ReflectionUtil { + + private static ConcurrentMap, List> classFields = new ConcurrentHashMap, List>(); + + private ReflectionUtil() { + // Utility class + } + + public static T newInstanceOfAssignableType(Class assignableClass, + String className) { + try { + @SuppressWarnings("unchecked") + Class clazz = (Class) Class + .forName(className); + return newInstanceOfAssignableType(assignableClass, clazz); + } catch (ClassCastException cce) { + throw new ReflectionException(String.format( + "%s is not assignable to a field of type %s", className, + assignableClass.getName()), cce); + } catch (ClassNotFoundException e) { + throw new ReflectionException(e); + } + } + + public static T newInstanceOfAssignableType(Class assignableClass, + Class clazz) { + try { + return assignableClass.cast(newInstance(clazz)); + } catch (ClassCastException cce) { + throw new ReflectionException(String.format( + "%s is not assignable to a field of type %s", + clazz.getName(), assignableClass.getName()), cce); + } + } + + public static Method getGetterMethod(Class clazz, String name) + throws ReflectionException { + // Assume camel cased names - capitalize first letter... + String method = Character.toUpperCase(name.charAt(0)) + + name.substring(1); + try { + Method m; + try { + // Try common 'get' first... + m = clazz.getMethod("get" + method); + } catch (NoSuchMethodException e) { + // Try 'is' as a prefix + m = clazz.getMethod("is" + method); + } + + return m; + } catch (Exception e) { + throw new ReflectionException(e); + } + } + + public static Object getter(Object object, String name) + throws ReflectionException { + try { + return getGetterMethod(object.getClass(), name).invoke(object, + (Object[]) null); + } catch (Exception e) { + throw new ReflectionException(e); + } + } + + public static T getter(Class resultType, Object obj, String name) { + Object result = null; + try { + result = getter(obj, name); + return resultType.cast(result); + } catch (ClassCastException cce) { + throw new ReflectionException(String.format( + "%s is not assignable to a field of type %s", result + .getClass().getName(), resultType.getName()), cce); + } + } + + public static void setter(Object object, String name, Object... parameters) + throws ReflectionException { + try { + String method = "set" + Character.toUpperCase(name.charAt(0)) + + name.substring(1); + + Class[] parameterTypes = new Class[parameters.length]; + for (int i = 0; i < parameters.length; i++) { + parameterTypes[i] = parameters[i].getClass(); + } + + Method m = object.getClass().getMethod(method, parameterTypes); + m.invoke(object, parameters); + } catch (Exception e) { + throw new ReflectionException(e); + } + } + + /** + * Constructs a new instance of the specified class. + * + * @param clazz + * the class to construct + * @return the constructed instance + * @throws ReflectionException + * on error constructing the instance + */ + public static Object newInstance(Class clazz) throws ReflectionException { + try { + return clazz.newInstance(); + } catch (Exception e) { + throw new ReflectionException(String.format( + "Unable to construct an object of type %s!", + clazz.getName()), e); + } + } + + /** + * Gets all fields for a given class. Fields from the superclass are also + * included + * + * @param fields + * The list used to hold the fields + * @param type + * The class type to look at + * @return The complete list of all fields including inherited fields + */ + public static List getAllFields(Class type) { + List storedFields = classFields.get(type); + if (storedFields != null) { + return storedFields; + } + List fields = new ArrayList(); + for (Field field : type.getDeclaredFields()) { + fields.add(field); + } + if (type.getSuperclass() != null) { + fields.addAll(getAllFields(type.getSuperclass())); + } + classFields.putIfAbsent(type, fields); + return fields; + } + + /** + * Checks the fields of a class to see if the desired annotation is present + * on any fields. If the annotation is found, the value of the field is + * returned + * + * @param obj + * The object to check + * @param annotation + * The annotation class to look for + * @return The value of the annotated field + * @throws ReflectionException + * If reflection errors occur + */ + public static String getAnnotatedField(Object obj, + Class annotation) throws ReflectionException { + List fields = getAllFields(obj.getClass()); + + for (Field field : fields) { + Annotation ann = field.getAnnotation(annotation); + if (ann != null) { + try { + return PropertyUtils.getProperty(obj, field.getName()) + .toString(); + } catch (Exception e) { + throw new ReflectionException( + "Error getting annotated field value", e); + } + } + } + return null; + } + + /** + * Create a class instance from its name. + * + * @param className + * the class name + * @return the class + */ + public static Class forName(String className) { + try { + return Class.forName(className); + } catch (ClassNotFoundException e) { + throw new ReflectionException(e); + } + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/StringUtil.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/StringUtil.java index 4895600367..abdf2af446 100644 --- a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/StringUtil.java +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/StringUtil.java @@ -20,6 +20,8 @@ package com.raytheon.uf.common.util; import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; import java.util.List; import org.apache.commons.lang.StringUtils; @@ -34,13 +36,21 @@ import org.apache.commons.lang.StringUtils; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Oct 20, 2011 rferrel Initial creation + * Jul 13, 2012 740 djohnson Add join. + * Nov 09, 2012 1322 djohnson Add NEWLINE, createMessage. * * * * @author rferrel * @version 1.0 */ -public class StringUtil { +public final class StringUtil { + + public static final String NEWLINE = System.getProperty("line.separator"); + + private StringUtil() { + + } /** * Splits a string using given separator characters; strings are trimmed and @@ -75,4 +85,104 @@ public class StringUtil { } return result; } + + /** + * Concatenate an array of object into a single string with each array + * element's toString() value separated by the joinCharacter. + * + * @param portions + * the array of objects + * @param joinCharacter + * the character to join them with + * @return the concatenated string + */ + public static String join(final T[] portions, final char joinCharacter) { + StringBuilder stringBuilder = new StringBuilder(); + + if (CollectionUtil.isNullOrEmpty(portions)) { + return null; + } + + for (T portion : portions) { + stringBuilder.append(portion); + stringBuilder.append(joinCharacter); + } + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + + return stringBuilder.toString(); + } + + /** + * Concatenate a collection of objects into a single string with each + * object's toString() value separated by the joinCharacter. + * + * @param portions + * the collections of objects + * @param joinCharacter + * the character to join them with + * @return the concatenated string + */ + public static String join(final Collection portions, final char joinCharacter) { + StringBuilder stringBuilder = new StringBuilder(); + + if (CollectionUtil.isNullOrEmpty(portions)) { + return null; + } + + for (T portion : portions) { + stringBuilder.append(portion); + stringBuilder.append(joinCharacter); + } + stringBuilder.deleteCharAt(stringBuilder.length() - 1); + + return stringBuilder.toString(); + } + + /** + * Creates a message based on the preamble and the provided iterables, each + * iterable will be displayed on its own line. + * + * @param preamble + * the preamble message, such as + * String preamble = "The following are numbers:" + * @param iterables + * the iterable to retrieve items from, such as
+ * List<String> iterables = Arrays.asList("one", "two"); + * @return the message + */ + public static String createMessage(String preamble, Iterable iterables) { + return createMessage(preamble, iterables, 0); + } + + /** + * Creates a message based on the preamble and the provided iterables, each + * iterable will be displayed on its own line. + * + * @param preamble + * the preamble message, such as + * String preamble = "The following are numbers:" + * @param iterables + * the iterable to retrieve items from, such as
+ * List<String> iterables = Arrays.asList("one", "two"); + * @param iterableIndent + * the number of spaces to indent each iterable + * @return the message + */ + public static String createMessage(String preamble, Iterable iterables, + int iterableIndent) { + StringBuilder msg = new StringBuilder(preamble) + .append(StringUtil.NEWLINE); + for (Iterator iter = iterables.iterator(); iter.hasNext();) { + for (int i = 0; i < iterableIndent; i++) { + msg.append(' '); + } + msg.append(iter.next()); + + if (iter.hasNext()) { + msg.append(StringUtil.NEWLINE); + } + } + + return msg.toString(); + } } diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/Alias.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/Alias.java new file mode 100644 index 0000000000..53f5d08ae4 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/Alias.java @@ -0,0 +1,77 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.mapping; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlValue; + +/** + * Alias definition, base should be a well defined name and alias is an + * alternative name that can be used to describe the same thing. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 22, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.NONE) +public class Alias { + + @XmlAttribute + private String base; + + @XmlValue + private String alias; + + public Alias() { + } + + public Alias(String base, String alias) { + this.base = base; + this.alias = alias; + } + + public String getBase() { + return base; + } + + public void setBase(String base) { + this.base = base; + } + + public String getAlias() { + return alias; + } + + public void setAlias(String alias) { + this.alias = alias; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/AliasList.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/AliasList.java new file mode 100644 index 0000000000..b8ba12017c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/AliasList.java @@ -0,0 +1,108 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.mapping; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * + * A AliasList represents a set of alternative names for a base name. This list + * defines the alternatives within a namespace so that it is possible to match + * aliases for only a specific group. Parent namespaces can be used to bring all + * aliases from another list into this namespace. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 22, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement +public class AliasList { + + /** + * A name for this group of parameter aliases + */ + @XmlAttribute + private String namespace; + + /** + * A name for this group of parameter aliases + */ + @XmlAttribute + private boolean caseSensitive = true; + + /** + * The actual alias definitions for the list + */ + @XmlElement(name = "alias") + private List aliasList = new ArrayList(); + + public AliasList() { + } + + public AliasList(String name) { + this.namespace = name; + } + + public String getNamespace() { + return namespace; + } + + public void setNamespace(String namespace) { + this.namespace = namespace; + } + + public List getAliasList() { + return aliasList; + } + + public void setAliasList(List aliasList) { + this.aliasList = aliasList; + } + + public void addAlias(Alias alias) { + this.aliasList.add(alias); + } + + public boolean isCaseSensitive() { + return caseSensitive; + } + + public void setCaseSensitive(boolean caseSensitive) { + this.caseSensitive = caseSensitive; + } + +} \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/AliasNamespace.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/AliasNamespace.java new file mode 100644 index 0000000000..ff90a8d84f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/AliasNamespace.java @@ -0,0 +1,113 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.mapping; + +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlRootElement; + +/** + * + * A AliasNamespace represents a set of alternative names for a base name. This + * list defines the alternatives within a namespace so that it is possible to + * match aliases for only a specific group. Parent namespaces can be used to + * bring all aliases from another list into this namespace. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 22, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +@XmlAccessorType(XmlAccessType.NONE) +@XmlRootElement +public class AliasNamespace { + + protected final boolean caseSensitive; + + /** + * Map an alias name to base names + */ + protected Map> alias2base = new HashMap>(); + + /** + * maps base names to alias names. + */ + protected Map> base2alias = new HashMap>(); + + public AliasNamespace(AliasList aliasList) { + this.caseSensitive = aliasList.isCaseSensitive(); + int mapSize = (int) (aliasList.getAliasList().size() / 0.75) + 1; + alias2base = new HashMap>(mapSize, 0.75f); + base2alias = new HashMap>(mapSize, 0.75f); + for (Alias def : aliasList.getAliasList()) { + String alias = def.getAlias(); + if (!caseSensitive) { + alias = alias.toLowerCase(); + } + String base = def.getBase(); + Set baseSet = alias2base.get(alias); + if (baseSet == null) { + baseSet = new HashSet(); + alias2base.put(alias, baseSet); + } + baseSet.add(base); + Set aliasSet = base2alias.get(base); + if (aliasSet == null) { + aliasSet = new HashSet(); + base2alias.put(base, aliasSet); + } + aliasSet.add(alias); + } + } + + public Set lookupBaseNames(String alias) { + if (!caseSensitive) { + alias = alias.toLowerCase(); + } + Set base = alias2base.get(alias); + if (base == null) { + return base; + } + return Collections.unmodifiableSet(base); + } + + public Set lookupAliases(String base) { + Set alias = base2alias.get(base); + if (alias == null) { + return alias; + } + return Collections.unmodifiableSet(alias); + } + +} \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/Mapper.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/Mapper.java new file mode 100644 index 0000000000..9e28be25a8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/Mapper.java @@ -0,0 +1,265 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.mapping; + +import java.io.File; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +/** + * This class can be used to map names between different naming conventions. + * + * Names are grouped into namespaces which allows mapping from any namespace + * into the "base" namespace. The "base" namespace does not actually exist but + * it is a theoretical namespace that other things map into, often defined by + * the contents of a file or database table depending on the implementation. + * + * The "deprecated" namespace is handled specially. This namespace will contain + * any names that were previously base names but have since changed. When any + * mapping is performed, if the base name is deprecated it will map correctly to + * the new base. Over time it is expected that all mappings and code will be + * updated and any deprecated entries can be removed. + * + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 22, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public abstract class Mapper { + + /** + * The name of the special deprecated namespace + */ + public static final String DEPRECATED = "deprecated"; + + private static Unmarshaller unmarshaller; + + private Map namespaceMap = new HashMap(); + + protected void addAliasList(AliasList list) { + namespaceMap.put(list.getNamespace(), new AliasNamespace(list)); + } + + protected void addAliasList(File file) throws JAXBException { + if (file == null || !file.exists() || file.length() < 0) { + return; + } + Unmarshaller unmarshaller = Mapper.unmarshaller; + if (unmarshaller == null) { + // This will be safe if multiple threads get in before the sync + // block. + JAXBContext context = JAXBContext.newInstance(AliasList.class, + Alias.class); + unmarshaller = context.createUnmarshaller(); + } + synchronized (unmarshaller) { + Object obj = unmarshaller.unmarshal(file); + if (obj instanceof AliasList) { + addAliasList((AliasList) obj); + } + } + Mapper.unmarshaller = unmarshaller; + } + + protected Set lookupBaseNames(String alias, String namespace, + boolean defaultUseAlias) { + AliasNamespace list = namespaceMap.get(namespace); + Set baseNames = null; + if (list != null) { + baseNames = list.lookupBaseNames(alias); + } + if (baseNames == null) { + if (defaultUseAlias) { + baseNames = new HashSet(Arrays.asList(alias)); + } else { + return null; + } + } + AliasNamespace deprecated = namespaceMap.get(DEPRECATED); + if (deprecated != null) { + Set newBaseNames = new HashSet( + (int) (baseNames.size() / 0.75) + 1, 0.75f); + for (String name : baseNames) { + Set undepNames = deprecated.lookupBaseNames(name); + if (undepNames == null) { + newBaseNames.add(name); + } else { + newBaseNames.addAll(baseNames); + } + } + // We don't really need to make this unmodifiable, but if we don't + // and people start modifying the result then everything breaks if + // there are no deprecated names. + baseNames = Collections.unmodifiableSet(newBaseNames); + } + return baseNames; + } + + /** + * Lookup all the baseNames associated with the given alias in a namespace. + * If no baseNames are defined the alias is returned. + * + * @param namespace + * - the defined alias namespace to look for the name + * @param alias + * - the name of an alias defined in the namespace + * @return the base names or the alias if the namespace or alias is + * undefined + */ + public Set lookupBaseNames(String alias, String namespace) { + return lookupBaseNames(alias, namespace, true); + } + + /** + * Lookup all the baseNames associated with the given alias in a namespace. + * If no baseNames are defined null is returned. + * + * @param namespace + * - the defined alias namespace to look for the name + * @param alias + * - the name of an alias defined in the namespace + * @return the base names or null if the namespace or alias is undefined + */ + public Set lookupBaseNamesOrNull(String alias, String namespace) { + return lookupBaseNames(alias, namespace, false); + } + + protected Set lookupAliases(String base, String namespace, + boolean defaultUseBase) { + AliasNamespace ns = namespaceMap.get(namespace); + Set aliases = null; + if (ns != null) { + aliases = ns.lookupAliases(base); + } + if (aliases == null) { + AliasNamespace deprecated = namespaceMap.get(DEPRECATED); + if (deprecated != null) { + Set depNames = deprecated.lookupAliases(base); + if (depNames != null) { + Set newAliases = new HashSet(); + for (String depName : depNames) { + Set depAliases = ns.lookupBaseNames(depName); + if (depAliases != null) { + newAliases.addAll(depAliases); + } + } + if (!newAliases.isEmpty()) { + aliases = newAliases; + } else if (defaultUseBase) { + aliases = depNames; + } + } + } + if (aliases == null && defaultUseBase) { + aliases = new HashSet(Arrays.asList(base)); + } + } + return aliases; + } + + /** + * Lookup an alias name within a given namespace for a base name. If no + * alias is defined then the baseName is returned + * + * @param parameter + * - The base name to find an alias for + * @param namespace + * - The namespace in which to look for an alias. + * @return an alias abbreviation or the base name if none is found. + */ + public Set lookupAliases(String base, String namespace) { + return lookupAliases(base, namespace, true); + } + + /** + * Lookup an alias name within a given namespace for a base name. If no + * alias is defined then null is returned + * + * @param parameter + * - The base name to find an alias for + * @param namespace + * - The namespace in which to look for an alias. + * @return an alias abbreviation or null if none is found. + */ + public Set lookupAliasesOrNull(String base, String namespace) { + return lookupAliases(base, namespace, false); + } + + /** + * Provides same functionality as lookupBaseNames but is more convenient + * when only alias is expected. + * + * @param alias + * @param namespace + * @return + * @throws MultipleMappingException + */ + public String lookupBaseName(String alias, String namespace) + throws MultipleMappingException { + Set baseNames = lookupBaseNames(alias, namespace); + if (baseNames == null || baseNames.isEmpty()) { + return null; + } else if (baseNames.size() == 1) { + return baseNames.iterator().next(); + } else { + throw new MultipleMappingException(false, alias, namespace, + baseNames); + } + } + + /** + * Provides same functionality as lookupAliases but is more convenient when + * only one base name is expected. + * + * @param base + * @param namespace + * @return + * @throws MultipleMappingException + */ + public String lookupAlias(String base, String namespace) + throws MultipleMappingException { + Set aliases = lookupAliases(base, namespace); + if (aliases == null) { + return null; + } else if (aliases.size() == 1) { + return aliases.iterator().next(); + } else { + throw new MultipleMappingException(true, base, namespace, aliases); + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/MultipleMappingException.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/MultipleMappingException.java new file mode 100644 index 0000000000..7c66e488a8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/mapping/MultipleMappingException.java @@ -0,0 +1,118 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.mapping; + +import java.util.Set; + +/** + * Exception thrown when trying to map an alias or baseName to exactly one name + * and multiple definitions are defined. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 26, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class MultipleMappingException extends Exception { + + private static final long serialVersionUID = -376467583718598176L; + + private final boolean base; + + private final String name; + + private final String namespace; + + private final Set mappings; + + public MultipleMappingException(boolean base, String name, + String namespace, Set mappings) { + super(); + this.base = base; + this.name = name; + this.namespace = namespace; + this.mappings = mappings; + } + + public boolean isBase() { + return base; + } + + public String getName() { + return name; + } + + public String getNamespace() { + return namespace; + } + + /** + * Get all the defined mappings. + * + * @return + */ + public Set getMappings() { + return mappings; + } + + /** + * Get one of the mappings, no guarantee as to which one. + * + * @return + */ + public String getArbitraryMapping() { + return mappings.iterator().next(); + } + + @Override + public String getMessage() { + StringBuilder message = new StringBuilder(100); + if (base) { + message.append("Base name("); + } else { + message.append("Alias name("); + } + message.append(name); + message.append(") maps to multiple names("); + boolean first = true; + for (String name : mappings) { + if (first) { + first = false; + } else { + message.append(", "); + } + message.append(name); + } + message.append(") in "); + message.append(namespace); + message.append(" when only one mapping is expected."); + return message.toString(); + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/session/SessionContext.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/session/SessionContext.java new file mode 100644 index 0000000000..bb06d78335 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/session/SessionContext.java @@ -0,0 +1,53 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.session; + +/** + * This interface should be implemented for each session management type. For + * example, in a persistence session the extension class could hold the + * transaction. Each thread is given a single {@link SessionContext}, therefore + * the implementors do not need to be thread-safe. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 26, 2012 1195       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public interface SessionContext { + /** + * Open the context, called by {@link SessionManager} when the context is + * initially created for a thread. + */ + void open(); + + /** + * Close the context, called by {@link SessionManager} when the context is + * destroyed for a thread. + */ + void close(); +} diff --git a/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/session/SessionManager.java b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/session/SessionManager.java new file mode 100644 index 0000000000..556b9f81e2 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/src/com/raytheon/uf/common/util/session/SessionManager.java @@ -0,0 +1,182 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util.session; + +import java.util.HashMap; +import java.util.Map; + +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.util.ReflectionUtil; + +/** + * Provides the functionality to manage a 'session'. Each thread has its own + * instance of the context. 1..N open requests can be made, and once the Nth + * close request comes in the session is closed. All data related to the session + * is stored in the sub-class of {@link SessionContext}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 26, 2012 1195       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public final class SessionManager { + + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(SessionManager.class); + + /** + * Inner-class used to hold the SessionContext tracking data. + */ + private static class SessionContextTracker { + private int openRequests; + private final SessionContext sessionContext; + + /** + * Constructor. + * + * @param sessionContext + * the session context to track + */ + private SessionContextTracker(SessionContext sessionContext) { + this.sessionContext = sessionContext; + } + } + + /** + * Kept in a ThreadLocal to avoid synchronization expenditures. + */ + private static final ThreadLocal> context = new ThreadLocal>() { + + /** + * {@inheritDoc} + */ + @Override + protected Map initialValue() { + return new HashMap(); + } + }; + + /** + * Opens a session and binds the context to a thread, if not already open. + * + * @param contextClass + * the context class for the session type + */ + public static T openSession( + Class contextClass) { + final Map map = context.get(); + final String key = contextClass.getName(); + + SessionContextTracker ctxTracker = map.get(key); + if (ctxTracker == null) { + SessionContext ctx = ReflectionUtil.newInstanceOfAssignableType( + SessionContext.class, contextClass); + ctx.open(); + + ctxTracker = new SessionContextTracker(ctx); + map.put(key, ctxTracker); + } + + ctxTracker.openRequests++; + + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.debug(String.format( + " context [%s] openRequests [%s]", contextClass.getName(), + ctxTracker.openRequests)); + } + + return contextClass.cast(ctxTracker.sessionContext); + } + + /** + * Closes the session currently bound to this thread, if the last open + * requester has signaled it should be closed. + * + * @param contextClass + * the context class for the session type + * @throws IllegalStateException + * if the session is not open + */ + public static void closeSession( + Class contextClass) { + final Map map = context.get(); + final String key = contextClass.getName(); + + SessionContextTracker ctxTracker = map.get(key); + + if (ctxTracker == null) { + throw new IllegalStateException( + "Unable to close a session that is not opened! " + + "Please be sure to pair the closeSession() request with a prior openSession() request."); + } + + ctxTracker.openRequests--; + + // If the last open request finally checked in, close it down + if (ctxTracker.openRequests < 1) { + if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.debug(String.format( + "context [%s] closing, openRequests [%s]", + contextClass.getName(), ctxTracker.openRequests)); + } + + SessionContext ctx = ctxTracker.sessionContext; + ctx.close(); + map.remove(key); + } else if (statusHandler.isPriorityEnabled(Priority.DEBUG)) { + statusHandler.debug(String.format( + "context [%s] not closing, openRequests [%s]", + contextClass.getName(), ctxTracker.openRequests)); + } + } + + /** + * Retrieve the session context class for an open session. + * + * @param contextClass + * the context class for the session type + * @return + * @throws IllegalStateException + * if the session is not open + */ + public static T getSessionContext( + Class contextClass) { + final Map map = context.get(); + final String key = contextClass.getName(); + + SessionContextTracker ctxTracker = map.get(key); + if (ctxTracker == null) { + throw new IllegalStateException("No session is currently open!"); + } + + return contextClass.cast(ctxTracker.sessionContext); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/CollectionUtilTest.java b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/CollectionUtilTest.java new file mode 100644 index 0000000000..bf8a31f492 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/CollectionUtilTest.java @@ -0,0 +1,83 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; + +import org.junit.Test; + +/** + * Test {@link CollectionUtil}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 13, 2012 740        djohnson     Initial creation
+ * Jul 26, 2012 955        djohnson     Add isNullOrEmpty for {@link Collection}s.
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class CollectionUtilTest { + + @Test + public void testIsNullOrEmptyReturnsTrueForNullArray() { + String[] array = null; + assertTrue(CollectionUtil.isNullOrEmpty(array)); + } + + @Test + public void testIsNullOrEmptyReturnsTrueForEmptyArray() { + String[] array = new String[0]; + assertTrue(CollectionUtil.isNullOrEmpty(array)); + } + + @Test + public void testIsNullOrEmptyReturnsFalseForNonEmptyArray() { + String[] array = new String[] { "" }; + assertFalse(CollectionUtil.isNullOrEmpty(array)); + } + + @Test + public void testIsNullOrEmptyReturnsTrueForNullCollection() { + assertTrue(CollectionUtil.isNullOrEmpty((Collection) null)); + } + + @Test + public void testIsNullOrEmptyReturnsTrueForEmptyCollection() { + assertTrue(CollectionUtil.isNullOrEmpty(Collections.emptyList())); + } + + @Test + public void testIsNullOrEmptyReturnsFalseForNonEmptyCollection() { + assertFalse(CollectionUtil.isNullOrEmpty(Arrays.asList("not empty"))); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/ExceptionUtilTest.java b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/ExceptionUtilTest.java new file mode 100644 index 0000000000..35ea8d6d30 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/ExceptionUtilTest.java @@ -0,0 +1,64 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import static org.junit.Assert.assertSame; + +import java.io.FileNotFoundException; + +import org.junit.Test; + +/** + * Test {@link ExceptionUtil}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 5, 2012  740        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class ExceptionUtilTest { + + @Test + public void testGettingRootCauseGoesNLevelsDeep() { + final FileNotFoundException root = new FileNotFoundException("root"); + final Throwable t = new Throwable(new IllegalArgumentException( + new IllegalStateException(root))); + + assertSame("Didn't get the correct exception for the root cause!", + root, ExceptionUtil.getRootCause(t)); + } + + @Test + public void testGettingRootCauseWillReturnParameterIfNoCauseFound() { + final FileNotFoundException root = new FileNotFoundException(); + + assertSame("Didn't get the correct exception for the root cause!", + root, ExceptionUtil.getRootCause(root)); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/PropertiesUtilTest.java b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/PropertiesUtilTest.java new file mode 100644 index 0000000000..8397b32dcc --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/PropertiesUtilTest.java @@ -0,0 +1,90 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +import org.junit.Test; + +/** + * Test {@link PropertiesUtil}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jun 28, 2012 819        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class PropertiesUtilTest { + + private static final Class CLASS = PropertiesUtilTest.class; + + @Test + public void testCanReadPropertiesInputStream() throws IOException { + InputStream is = null; + try { + is = CLASS.getResourceAsStream(CLASS.getSimpleName() + + ".properties"); + Properties properties = PropertiesUtil.read(is); + + assertFalse( + "The properties should not be empty after reading an InputStream!", + properties.isEmpty()); + } finally { + PropertiesUtil.close(is); + } + } + + @Test + public void testCanReadPropertiesFile() throws IOException { + File fileToRead = File.createTempFile( + PropertiesUtilTest.class.getSimpleName(), null); + + InputStream is = null; + try { + is = CLASS.getResourceAsStream(CLASS.getSimpleName() + + ".properties"); + + FileUtil.write(is, fileToRead); + + assertTrue("The file to read should exist!", fileToRead.isFile()); + } finally { + PropertiesUtil.close(is); + } + + Properties properties = PropertiesUtil.read(fileToRead); + assertFalse("The properties should not be empty after reading a file!", + properties.isEmpty()); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/PropertiesUtilTest.properties b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/PropertiesUtilTest.properties new file mode 100644 index 0000000000..f51889fddc --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/PropertiesUtilTest.properties @@ -0,0 +1,2 @@ +string.property=value +integer.property=10 \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/ReflectionUtilTest.java b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/ReflectionUtilTest.java new file mode 100644 index 0000000000..c3288f93ec --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/ReflectionUtilTest.java @@ -0,0 +1,132 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; + +import org.junit.Test; + +/** + * Test {@link ReflectionUtil}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 10, 2012 634        djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public class ReflectionUtilTest { + + private static final String NON_EXISTANT = "nonExistant"; + + @Test + public void testNewInstanceOfAssignableTypeWithInterface() { + List list = ReflectionUtil.newInstanceOfAssignableType(List.class, + ArrayList.class.getName()); + assertTrue(list instanceof ArrayList); + } + + @Test(expected = ReflectionException.class) + public void testNewInstanceOfAssignableTypeThrowsReflectionExceptionOnIncompatibleCast() { + ReflectionUtil.newInstanceOfAssignableType(List.class, + HashSet.class.getName()); + } + + @Test(expected = ReflectionException.class) + public void testNewInstanceOfAssignableTypeThrowsReflectionExceptionOnInvalidClassname() { + ReflectionUtil.newInstanceOfAssignableType(List.class, NON_EXISTANT); + } + + @Test + public void testGetterRetrievesGetPrefixedValue() { + byte[] expected = new byte[] { 't', 'e', 's', 't' }; + String value = new String(expected); + + byte[] actual = (byte[]) ReflectionUtil.getter(value, "bytes"); + + assertArrayEquals( + "Did not receive the expected value from the getter!", + expected, actual); + } + + @Test + public void testGetterWithCastResult() { + byte[] expected = new byte[] { 't', 'e', 's', 't' }; + String value = new String(expected); + + byte[] actual = ReflectionUtil.getter(byte[].class, value, "bytes"); + + assertArrayEquals( + "Did not receive the expected value from the getter!", + expected, actual); + } + + @Test + public void testGetterRetrievesIsPrefixedValue() { + List list = Collections.emptyList(); + + boolean value = (Boolean) ReflectionUtil.getter(list, "empty"); + + assertTrue( + "Incorrect value retrieved from the getter using an is prefix!", + value); + } + + @Test(expected = ReflectionException.class) + public void testGetterThrowsReflectionExceptionOnNoSuchMethod() { + byte[] expected = new byte[] { 't', 'e', 's', 't' }; + String value = new String(expected); + + ReflectionUtil.getter(value, NON_EXISTANT); + } + + @Test + public void testSetterCanSetValueOnProperlyNamedMethod() { + final String name = "blah"; + + Thread thread = new Thread(); + ReflectionUtil.setter(thread, "name", name); + + assertEquals("Setter did not set the correct value!", name, + thread.getName()); + } + + @Test(expected = ReflectionException.class) + public void testSetterThrowsReflectionExceptionOnNoSuchMethod() { + String string = "blah"; + + Thread thread = new Thread(); + ReflectionUtil.setter(thread, string, NON_EXISTANT); + } +} diff --git a/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/StringUtilTest.java b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/StringUtilTest.java new file mode 100644 index 0000000000..d79ecf9729 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.common.util/unit-test/com/raytheon/uf/common/util/StringUtilTest.java @@ -0,0 +1,64 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.common.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +/** + * Test {@link StringUtil}. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Jul 13, 2012 740        djohnson     Initial creation
+ * Aug 20, 2012 0743       djohnson     Disambiguate method call.
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class StringUtilTest { + + @Test + public void testJoinedStringsUseJoinCharacter() + { + assertEquals("1,2,3", + StringUtil.join(new String[] { "1", "2", "3" }, ',')); + } + + @Test + public void testJoinReturnsNullForNullArrayOfStrings() { + assertNull(StringUtil.join((Object[]) null, ',')); + } + + @Test + public void testJoinReturnsNullForZeroLengthArray() { + assertNull(StringUtil.join(new String[0], ',')); + } + +} diff --git a/edexOsgi/com.raytheon.uf.edex.auth/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.auth/META-INF/MANIFEST.MF index 9b94d8d0cb..f3cf512e01 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.auth/META-INF/MANIFEST.MF @@ -9,7 +9,8 @@ Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.11.31", com.raytheon.uf.common.serialization.comm;bundle-version="1.11.31", com.raytheon.uf.common.auth;bundle-version="1.0.0", com.raytheon.edex.common;bundle-version="1.11.31", - com.raytheon.uf.common.status;bundle-version="1.11.31" + com.raytheon.uf.common.status;bundle-version="1.11.31", + com.raytheon.uf.common.comm;bundle-version="1.12.1174" Export-Package: com.raytheon.uf.edex.auth, com.raytheon.uf.edex.auth.authentication, com.raytheon.uf.edex.auth.req, diff --git a/edexOsgi/com.raytheon.uf.edex.auth/META-INF/services/com.raytheon.uf.common.serialization.comm.IRequestRouter b/edexOsgi/com.raytheon.uf.edex.auth/META-INF/services/com.raytheon.uf.common.serialization.comm.IRequestRouter deleted file mode 100644 index 64d3634c3d..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.auth/META-INF/services/com.raytheon.uf.common.serialization.comm.IRequestRouter +++ /dev/null @@ -1 +0,0 @@ -com.raytheon.uf.edex.auth.ServerRequestRouter \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.auth/res/spring/auth-common.xml b/edexOsgi/com.raytheon.uf.edex.auth/res/spring/auth-common.xml index e24b24607c..ae3d9ae5f8 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/res/spring/auth-common.xml +++ b/edexOsgi/com.raytheon.uf.edex.auth/res/spring/auth-common.xml @@ -1,16 +1,15 @@ - - - - - - - - - - + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestRouteWrapper.java b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestRouteWrapper.java index 832be233f8..772f270245 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestRouteWrapper.java +++ b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestRouteWrapper.java @@ -21,12 +21,12 @@ package com.raytheon.uf.edex.auth; import com.raytheon.uf.common.auth.AuthException; import com.raytheon.uf.common.auth.resp.AuthServerErrorResponse; +import com.raytheon.uf.common.serialization.ExceptionWrapper; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; import com.raytheon.uf.common.serialization.comm.IServerRequest; import com.raytheon.uf.common.serialization.comm.RequestWrapper; import com.raytheon.uf.common.serialization.comm.response.ServerErrorResponse; -import com.raytheon.uf.common.serialization.comm.util.ExceptionWrapper; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.util.SizeUtil; diff --git a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestServer.java b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestServer.java index d735acef38..1573df4e7e 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestServer.java +++ b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteRequestServer.java @@ -97,7 +97,7 @@ public class RemoteRequestServer { // check handler if user has authorization AuthorizationResponse authResp = privHandler.authorized(user, privReq); - if (authResp != null && !authResp.isAuthorized()) { + if (authResp != null && !authResp.isAuthorized() && authResp.getResponseMessage() != null) { return ResponseFactory.constructNotAuthorized(privReq, authResp.getResponseMessage()); } diff --git a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteServerRequestRouter.java b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteServerRequestRouter.java new file mode 100644 index 0000000000..89b0c05a36 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/RemoteServerRequestRouter.java @@ -0,0 +1,106 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.auth; + +import java.rmi.RemoteException; + +import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest; +import com.raytheon.uf.common.comm.CommunicationException; +import com.raytheon.uf.common.comm.HttpClient; +import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.serialization.comm.IRequestRouter; +import com.raytheon.uf.common.serialization.comm.IServerRequest; +import com.raytheon.uf.edex.auth.req.ServerPrivilegedRequestHandler; + +/** + * {@link IRequestRouter} implementation that transfers requests to another + * server for processing. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 14, 2012 1322       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class RemoteServerRequestRouter implements IRequestRouter { + + private final String httpAddress; + + /** + * Constructor. + * + * @param httpAddress + * the http address to be used to connect to the remote server + */ + public RemoteServerRequestRouter(String httpAddress) { + this.httpAddress = httpAddress; + } + + /** + * {@inheritDoc} + */ + @Override + public Object route(IServerRequest request) throws Exception { + // Wrap privileged requests so they are not checked for privileges + // internally to the server + if (request instanceof AbstractPrivilegedRequest) { + request = new ServerPrivilegedRequestHandler.ServerPrivilegedRequest(request); + } + + byte[] message = SerializationUtil.transformToThrift(request); + byte[] response = null; + try { + response = sendSerializedRequest(message); + } catch (Exception e) { + throw new RemoteException("Error communicating with the server.", e); + } + Object rval = null; + if (response != null) { + rval = SerializationUtil + .transformFromThrift(Object.class, response); + } + return rval; + } + + /** + * Send the serialized request, and return the response. Package-access so + * the test can override for verification. + * + * @param message + * the binary data + * @return the response + * @throws CommunicationException + * @throws Exception + */ + byte[] sendSerializedRequest(byte[] message) + throws CommunicationException, Exception { + return HttpClient.getInstance() + .postBinary(httpAddress, message); + } + +} diff --git a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/ServerRequestRouter.java b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/ServerRequestRouter.java index 8064a59926..24f463e789 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/ServerRequestRouter.java +++ b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/ServerRequestRouter.java @@ -19,8 +19,10 @@ **/ package com.raytheon.uf.edex.auth; +import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest; import com.raytheon.uf.common.serialization.comm.IRequestRouter; import com.raytheon.uf.common.serialization.comm.IServerRequest; +import com.raytheon.uf.edex.auth.req.ServerPrivilegedRequestHandler; /** * Routes the request directly to the RemoteRequestServer. @@ -31,7 +33,8 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest; * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Dec 9, 2010 rjpeter Initial creation + * Dec 9, 2010 rjpeter Initial creation + * Nov 15, 2012 1322 djohnson Allow servers the ability to bypass authorization. * * * @@ -41,6 +44,12 @@ import com.raytheon.uf.common.serialization.comm.IServerRequest; public class ServerRequestRouter implements IRequestRouter { @Override public Object route(IServerRequest request) throws Exception { + // Wrap privileged requests so they are not checked for privileges + // internally to the server + if (request instanceof AbstractPrivilegedRequest) { + request = new ServerPrivilegedRequestHandler.ServerPrivilegedRequest(request); + } + return RemoteRequestServer.getInstance().handleThriftRequest(request); } diff --git a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/req/AbstractPrivilegedRequestHandler.java b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/req/AbstractPrivilegedRequestHandler.java index 643cdca6a7..912a068a96 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/req/AbstractPrivilegedRequestHandler.java +++ b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/req/AbstractPrivilegedRequestHandler.java @@ -19,6 +19,7 @@ **/ package com.raytheon.uf.edex.auth.req; +import com.raytheon.uf.common.auth.exception.AuthorizationException; import com.raytheon.uf.common.auth.req.AbstractPrivilegedRequest; import com.raytheon.uf.common.auth.user.IUser; import com.raytheon.uf.common.serialization.comm.IRequestHandler; @@ -51,6 +52,7 @@ public abstract class AbstractPrivilegedRequestHandlerserver request to bypass the normal privileged + * request checks. This class MUST remain in an EDEX specific plugin. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 15, 2012 1322       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ + +public class ServerPrivilegedRequestHandler + implements + IRequestHandler { + + /** + * Wraps a server request in a special request that allows server->server + * communication to bypass privileged request verification. + */ + @DynamicSerialize + public static class ServerPrivilegedRequest implements IServerRequest { + + @DynamicSerializeElement + private IServerRequest wrappedRequest; + + /** + * Added only to comply with dynamic serialization. + * + * @deprecated added only to comply with dynamic serialization + */ + @Deprecated + public ServerPrivilegedRequest() { + } + + /** + * Constructor. + * + * @param wrappedRequest + * the request to wrap + */ + public ServerPrivilegedRequest(IServerRequest wrappedRequest) { + this.wrappedRequest = wrappedRequest; + } + + /** + * @return the wrappedRequest + */ + public IServerRequest getWrappedRequest() { + return wrappedRequest; + } + + /** + * @param wrappedRequest + * the wrappedRequest to set + */ + public void setWrappedRequest(IServerRequest wrappedRequest) { + this.wrappedRequest = wrappedRequest; + } + } + + private final HandlerRegistry registry; + + /** + * Constructor. + * + * @param handlerRegistry + * the handler registry + */ + public ServerPrivilegedRequestHandler(HandlerRegistry handlerRegistry) { + this.registry = handlerRegistry; + } + + /** + * {@inheritDoc} + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public Object handleRequest(ServerPrivilegedRequest request) throws Exception { + // Delegate to the handler for the wrapped request + String id = request.wrappedRequest.getClass().getCanonicalName(); + IRequestHandler handler = registry.getRequestHandler(id); + + // Send back a SuccessfulExecution since that's expected of privileged + // requests + SuccessfulExecution response = new SuccessfulExecution(); + response.setResponse(handler.handleRequest(request.wrappedRequest)); + + return response; + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/roles/IRoleStorage.java b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/roles/IRoleStorage.java index 783c32b7b0..0daa3dc1ee 100644 --- a/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/roles/IRoleStorage.java +++ b/edexOsgi/com.raytheon.uf.edex.auth/src/com/raytheon/uf/edex/auth/roles/IRoleStorage.java @@ -19,6 +19,8 @@ **/ package com.raytheon.uf.edex.auth.roles; +import com.raytheon.uf.common.auth.exception.AuthorizationException; + /** * Storage class for roles. Should have a concept of a default role which all * users get by default and the ability to lookup a role given an id. NOTE, ALL @@ -40,19 +42,32 @@ package com.raytheon.uf.edex.auth.roles; public interface IRoleStorage { /** - * Given the (case insensitive) role id, return the role object + * Determine if the permission is valid for the user in the application. * - * @param roleId - * @return + * @param permission + * The permissions id + * @param user + * The user id + * @param application + * The application + * + * @return true if the permission is authorized for the user in the + * specified application + * @throws AuthorizationException */ - public IRole lookupRole(String roleId); + public boolean isAuthorized(String permission, String user, + String application) throws AuthorizationException; /** - * Given the role, determine if it is the default role + * Get all the defined permissions for this application. * - * @param role - * @return + * @param application + * The application + * + * @return String[] of permissions + * @throws AuthorizationException */ - public boolean isDefaultRole(IRole role); + public String[] getAllDefinedPermissions(String application) + throws AuthorizationException; } diff --git a/edexOsgi/com.raytheon.uf.edex.common.core.feature/feature.xml b/edexOsgi/com.raytheon.uf.edex.common.core.feature/feature.xml index 8484870e30..de0bca7678 100644 --- a/edexOsgi/com.raytheon.uf.edex.common.core.feature/feature.xml +++ b/edexOsgi/com.raytheon.uf.edex.common.core.feature/feature.xml @@ -73,13 +73,6 @@ version="0.0.0" unpack="false"/> - - + + + + + + + * * @author chammack @@ -63,6 +64,11 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory; */ public class EDEXUtil implements ApplicationContextAware { + public static final String EDEX_HOME = System.getProperty("edex.home"); + + public static final String EDEX_BIN = EDEX_HOME + File.separatorChar + + "bin"; + static Log logger = LogFactory.getLog(EDEXUtil.class); private static ApplicationContext CONTEXT; @@ -89,6 +95,7 @@ public class EDEXUtil implements ApplicationContextAware { return serverId; } + @Override public void setApplicationContext(ApplicationContext context) throws BeansException { CONTEXT = context; diff --git a/edexOsgi/com.raytheon.uf.edex.cots.feature/feature.xml b/edexOsgi/com.raytheon.uf.edex.cots.feature/feature.xml index b8ae845cd0..a628a823f7 100644 --- a/edexOsgi/com.raytheon.uf.edex.cots.feature/feature.xml +++ b/edexOsgi/com.raytheon.uf.edex.cots.feature/feature.xml @@ -293,6 +293,13 @@ install-size="0" version="0.0.0"/> + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.dat.feature/feature.xml b/edexOsgi/com.raytheon.uf.edex.dat.feature/feature.xml index 66988d6e49..f8d998693d 100644 --- a/edexOsgi/com.raytheon.uf.edex.dat.feature/feature.xml +++ b/edexOsgi/com.raytheon.uf.edex.dat.feature/feature.xml @@ -21,6 +21,13 @@ + + - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.dat.utils/res/spring/dat-request.xml b/edexOsgi/com.raytheon.uf.edex.dat.utils/res/spring/dat-request.xml index b675c610e6..820c8ed7c4 100644 --- a/edexOsgi/com.raytheon.uf.edex.dat.utils/res/spring/dat-request.xml +++ b/edexOsgi/com.raytheon.uf.edex.dat.utils/res/spring/dat-request.xml @@ -5,7 +5,6 @@ http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - diff --git a/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DATUtils.java b/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DATUtils.java index 80c2001187..0b64cbd375 100644 --- a/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DATUtils.java +++ b/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DATUtils.java @@ -25,11 +25,10 @@ import java.util.ArrayList; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import com.raytheon.edex.plugin.grib.dao.GribDao; import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.ffmp.FFMPVirtualGageBasin; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.persist.IPersistable; import com.raytheon.uf.common.dataplugin.shef.util.ShefConstants; import com.raytheon.uf.common.datastorage.IDataStore; @@ -97,12 +96,12 @@ public class DATUtils { * @param uri * @return */ - public static GribRecord getGribRecord(String uri) throws PluginException { + public static GridRecord getGridRecord(String uri) throws PluginException { - GribRecord gr = new GribRecord(uri); - GribDao gd = (GribDao) PluginFactory.getInstance().getPluginDao( + GridRecord gr = new GridRecord(uri); + PluginDao gd = PluginFactory.getInstance().getPluginDao( gr.getPluginName()); - gr = (GribRecord) gd.getMetadata(uri); + gr = (GridRecord) gd.getMetadata(uri); if (gr != null) { @@ -264,30 +263,30 @@ public class DATUtils { * @param param * @return */ - public static GribRecord getMostRecentGribRecord(int interval, String sql, + public static GridRecord getMostRecentGridRecord(int interval, String sql, SCANModelParameterXML param) { - GribRecord rec = null; + GridRecord rec = null; try { ScanDataCache cache = ScanDataCache.getInstance(); Object[] obs = dbRequest(sql); - GribRecord newRec = null; + GridRecord newRec = null; if (obs != null && obs.length > 0) { String uri = (String) obs[0]; - newRec = getGribRecord(uri); + newRec = getGridRecord(uri); } if (cache.getModelData().isType(param.getModelName(), param.getParameterName())) { - GribRecord oldRec = cache.getModelData().getGribRecord( + GridRecord oldRec = cache.getModelData().getGridRecord( param.getModelName(), param.getParameterName()); if (newRec != null) { if (newRec.getDataTime().getRefTime() .after(oldRec.getDataTime().getRefTime())) { - cache.getModelData().setGribRecord( + cache.getModelData().setGridRecord( param.getModelName(), param.getParameterName(), newRec); rec = newRec; @@ -299,7 +298,7 @@ public class DATUtils { } } else { if (newRec != null) { - cache.getModelData().setGribRecord(param.getModelName(), + cache.getModelData().setGridRecord(param.getModelName(), param.getParameterName(), newRec); rec = newRec; } diff --git a/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DatMenuUtil.java b/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DatMenuUtil.java index 39877637bd..db2f36252e 100644 --- a/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DatMenuUtil.java +++ b/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/DatMenuUtil.java @@ -30,7 +30,6 @@ import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; import com.raytheon.uf.common.localization.LocalizationFile; import com.raytheon.uf.common.localization.PathManager; import com.raytheon.uf.common.localization.PathManagerFactory; -import com.raytheon.uf.common.menus.AbstractMenuUtil; import com.raytheon.uf.common.menus.xml.CommonAbstractMenuContribution; import com.raytheon.uf.common.menus.xml.CommonIncludeMenuContribution; import com.raytheon.uf.common.menus.xml.CommonIncludeMenuItem; @@ -50,6 +49,7 @@ import com.raytheon.uf.common.monitor.xml.ProductXML; import com.raytheon.uf.common.monitor.xml.SourceXML; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.menus.AbstractMenuUtil; /** * TODO Add Description diff --git a/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/FreezingLevel.java b/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/FreezingLevel.java index 734e89484c..797ff6d8c0 100644 --- a/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/FreezingLevel.java +++ b/edexOsgi/com.raytheon.uf.edex.dat.utils/src/com/raytheon/uf/edex/dat/utils/FreezingLevel.java @@ -27,7 +27,7 @@ import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map.Entry; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.monitor.xml.SCANModelParameterXML; import com.vividsolutions.jts.geom.Coordinate; @@ -245,14 +245,14 @@ public class FreezingLevel { * @param param * @return */ - private GribRecord populateRecord(String model, String param, Date refTime) { + private GridRecord populateRecord(String model, String param, Date refTime) { int interval = 1440; SCANModelParameterXML paramXML = new SCANModelParameterXML(); paramXML.setModelName(model); paramXML.setParameterName(param); String sql = getSQL(interval, model, param, refTime); - GribRecord modelRec = DATUtils.getMostRecentGribRecord(interval, sql, + GridRecord modelRec = DATUtils.getMostRecentGridRecord(interval, sql, paramXML); if (modelRec != null) { @@ -353,16 +353,12 @@ public class FreezingLevel { } // Gets the most recent record of it's type - String sql = "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" + String sql = "select grid.datauri from grid, grid_info, level where grid.info_id = grid_info.id and grid_info.level_id = level.id and grid_info.parameter_abbreviation = \'" + paramName - + "\' and modelname = \'" + + "\' and grid_info.datasetId = \'" + model - + "\' and level_id = (select id from level where masterlevel_name = 'MB' and levelonevalue = '" - + level - + "\'" - + " limit 1)) and reftime='" - + refTimeStr - + "' order by reftime desc, forecasttime desc limit 1"; + + "\' and level.masterlevel_name = 'MB' and level.levelonevalue = '" + + level + "\' and reftime=\'" + refTimeStr + "\' order by grid.reftime desc, grid.forecasttime desc limit 1"; return sql; } } diff --git a/edexOsgi/com.raytheon.uf.edex.database/.classpath b/edexOsgi/com.raytheon.uf.edex.database/.classpath index ad32c83a78..1fa3e6803d 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/.classpath +++ b/edexOsgi/com.raytheon.uf.edex.database/.classpath @@ -1,6 +1,6 @@ - + diff --git a/edexOsgi/com.raytheon.uf.edex.database/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.database/META-INF/MANIFEST.MF index 95e019caac..9a7fc7243e 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.database/META-INF/MANIFEST.MF @@ -19,7 +19,8 @@ Require-Bundle: com.raytheon.uf.common.dataquery;bundle-version="1.0.0", com.raytheon.uf.common.time;bundle-version="1.12.1174", com.raytheon.uf.common.geospatial;bundle-version="1.12.1174", org.geotools;bundle-version="2.6.4", - com.raytheon.uf.common.localization;bundle-version="1.12.1174" + com.raytheon.uf.common.localization;bundle-version="1.12.1174", + com.raytheon.uf.common.spatial Export-Package: com.raytheon.uf.edex.database, com.raytheon.uf.edex.database.cluster, com.raytheon.uf.edex.database.cluster.handler, diff --git a/edexOsgi/com.raytheon.uf.edex.database/res/spring/database-request.xml b/edexOsgi/com.raytheon.uf.edex.database/res/spring/database-common.xml similarity index 96% rename from edexOsgi/com.raytheon.uf.edex.database/res/spring/database-request.xml rename to edexOsgi/com.raytheon.uf.edex.database/res/spring/database-common.xml index 047504d527..200e44abc3 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/res/spring/database-request.xml +++ b/edexOsgi/com.raytheon.uf.edex.database/res/spring/database-common.xml @@ -14,7 +14,7 @@ - + diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/CoreDao.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/CoreDao.java index 15624f9058..5d493a29a2 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/CoreDao.java +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/CoreDao.java @@ -47,7 +47,6 @@ import net.sf.ehcache.management.ManagementService; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; -import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.criterion.Criterion; import org.hibernate.criterion.DetachedCriteria; @@ -64,6 +63,7 @@ import org.springframework.transaction.support.TransactionCallbackWithoutResult; import org.springframework.transaction.support.TransactionTemplate; import com.raytheon.uf.common.dataplugin.PluginDataObject; +import com.raytheon.uf.common.dataplugin.persist.IPersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataquery.db.QueryParam; import com.raytheon.uf.common.dataquery.db.QueryResult; @@ -71,7 +71,6 @@ import com.raytheon.uf.common.dataquery.db.QueryResultRow; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.query.DatabaseQuery; @@ -83,7 +82,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; *

* Data types which must be persisted to the database must have an associated * dao which extends this class. Each class needing a dao must also extend the - * PersistableDataObject class. + * PersistableDataObject class. *

* NOTE: Direct instantiation of this class is discouraged. Use * DaoPool.getInstance().borrowObject() for retrieving all data access objects @@ -96,6 +95,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; * ------------ ---------- ----------- -------------------------- * 7/24/07 353 bphillip Initial Check in * 5/14/08 1076 brockwoo Fix for distinct with multiple properties + * Oct 10, 2012 1261 djohnson Incorporate changes to DaoConfig, add generic to {@link IPersistableDataObject}. * * * @@ -103,7 +103,9 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; * @version 1 */ public class CoreDao extends HibernateDaoSupport { - protected static final transient IUFStatusHandler statusHandler = UFStatus.getHandler(CoreDao.class); + protected static final IUFStatusHandler statusHandler = UFStatus + .getHandler(CoreDao.class); + /** * The Hibernate transaction manager. Methods do not directly use this * class. Instead, use the Transaction template @@ -113,11 +115,6 @@ public class CoreDao extends HibernateDaoSupport { /** The convenience wrapper for the Hibernate transaction manager */ protected final TransactionTemplate txTemplate; - /** - * The cache region to store query - */ - private final String QUERY_CACHE_REGION = "Queries"; - /** The class associated with this dao */ protected Class daoClass; @@ -132,16 +129,11 @@ public class CoreDao extends HibernateDaoSupport { * has been assigned */ public CoreDao(DaoConfig config) { - txManager = (HibernateTransactionManager) EDEXUtil - .getESBComponent(config.getTxManagerName()); + this.txManager = config.getTxManager(); txTemplate = new TransactionTemplate(txManager); - // SessionFactory sf = ((DatabaseSessionFactoryBean) - // EDEXUtil.getESBComponent("&" + config - // .getSessionFactoryName())).getMoreBetterSessionFactory(); - setSessionFactory((SessionFactory) EDEXUtil.getESBComponent(config - .getSessionFactoryName())); + setSessionFactory(config.getSessionFactory()); - daoClass = config.getDaoClassName(); + this.daoClass = config.getDaoClass(); getHibernateTemplate().setCacheQueries(true); } @@ -192,7 +184,7 @@ public class CoreDao extends HibernateDaoSupport { * @param obj * The object to be persisted to the database */ - public void saveOrUpdate(final PersistableDataObject obj) { + public void saveOrUpdate(final PersistableDataObject obj) { txTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { @@ -223,7 +215,7 @@ public class CoreDao extends HibernateDaoSupport { * @param obj * The object to be persisted to the database */ - public void update(final PersistableDataObject obj) { + public void update(final PersistableDataObject obj) { txTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { @@ -265,15 +257,15 @@ public class CoreDao extends HibernateDaoSupport { private static final String mergeSqlFormat = "select id from awips.%s where dataURI=:dataURI"; - public List mergeAll( - final List obj) { - List duplicates = new ArrayList(); + public List> mergeAll( + final List> obj) { + List> duplicates = new ArrayList>(); Session s = this.getHibernateTemplate().getSessionFactory() .openSession(); Transaction tx = s.beginTransaction(); try { Map pluginQueryMap = new HashMap(); - for (PersistableDataObject pdo : obj) { + for (PersistableDataObject pdo : obj) { if (pdo == null) { logger.error("Attempted to insert null PersistableDataObject"); continue; @@ -291,11 +283,8 @@ public class CoreDao extends HibernateDaoSupport { if (!pdo.isOverwriteAllowed()) { duplicates.add(pdo); } else { - statusHandler.handle( - Priority.DEBUG, - "Overwriting " - + ((PersistableDataObject) pdo) - .getIdentifier()); + statusHandler.handle(Priority.DEBUG, "Overwriting " + + pdo.getIdentifier()); } } } @@ -310,43 +299,6 @@ public class CoreDao extends HibernateDaoSupport { } } return duplicates; - - // return (List) txTemplate - // .execute(new TransactionCallback() { - // @Override - // public List doInTransaction( - // TransactionStatus arg0) { - // Session s = getHibernateTemplate().getSessionFactory() - // .getCurrentSession(); - // List duplicates = new - // ArrayList(); - // Map pluginQueryMap = new HashMap(); - // for (PersistableDataObject pdo : obj) { - // if (pdo == null) { - // logger - // .error("Attempted to insert null PersistableDataObject"); - // continue; - // } - // String plugin = ((PluginDataObject) pdo) - // .getPluginName(); - // Query q = pluginQueryMap.get(plugin); - // if (q == null) { - // q = s.createSQLQuery(String.format( - // mergeSqlFormat, plugin)); - // pluginQueryMap.put(plugin, q); - // } - // q - // .setString("dataURI", (String) pdo - // .getIdentifier()); - // if (q.list().size() == 0) { - // s.persist(pdo); - // } else { - // duplicates.add(pdo); - // } - // } - // return duplicates; - // } - // }); } /** @@ -355,7 +307,7 @@ public class CoreDao extends HibernateDaoSupport { * @param obj * The object to delete */ - public void delete(final PersistableDataObject obj) { + public void delete(final PersistableDataObject obj) { txTemplate.execute(new TransactionCallbackWithoutResult() { @Override public void doInTransactionWithoutResult(TransactionStatus status) { @@ -373,12 +325,14 @@ public class CoreDao extends HibernateDaoSupport { * @return The object with the matching id.
* Null if not found */ - public PersistableDataObject queryById(final Serializable id) { - PersistableDataObject retVal = (PersistableDataObject) txTemplate + public PersistableDataObject queryById(final Serializable id) { + @SuppressWarnings("unchecked") + PersistableDataObject retVal = (PersistableDataObject) txTemplate .execute(new TransactionCallback() { - public PersistableDataObject doInTransaction( + @Override + public PersistableDataObject doInTransaction( TransactionStatus status) { - return (PersistableDataObject) getHibernateTemplate() + return (PersistableDataObject) getHibernateTemplate() .get(daoClass, id); } }); @@ -392,10 +346,12 @@ public class CoreDao extends HibernateDaoSupport { * The id * @return The object */ - public PersistableDataObject queryById(final PluginDataObject id) { - PersistableDataObject retVal = (PersistableDataObject) txTemplate + public PersistableDataObject queryById(final PluginDataObject id) { + @SuppressWarnings("unchecked") + PersistableDataObject retVal = (PersistableDataObject) txTemplate .execute(new TransactionCallback() { - public PersistableDataObject doInTransaction( + @Override + public PersistableDataObject doInTransaction( TransactionStatus status) { DetachedCriteria criteria = DetachedCriteria.forClass( id.getClass()) @@ -425,11 +381,12 @@ public class CoreDao extends HibernateDaoSupport { * @return A list of similar objects */ @SuppressWarnings("unchecked") - public List queryByExample( - final PersistableDataObject obj, final int maxResults) { - List retVal = (List) txTemplate + public List> queryByExample( + final PersistableDataObject obj, final int maxResults) { + List> retVal = (List>) txTemplate .execute(new TransactionCallback() { - public List doInTransaction( + @Override + public List> doInTransaction( TransactionStatus status) { return getHibernateTemplate().findByExample(obj, 0, maxResults); @@ -448,7 +405,8 @@ public class CoreDao extends HibernateDaoSupport { * The partially populated object * @return A list of similar objects */ - public List queryByExample(PersistableDataObject obj) { + public List> queryByExample( + PersistableDataObject obj) { return queryByExample(obj, -1); } @@ -468,6 +426,7 @@ public class CoreDao extends HibernateDaoSupport { // Get a session and create a new criteria instance rowsDeleted = (Integer) txTemplate .execute(new TransactionCallback() { + @Override public Integer doInTransaction(TransactionStatus status) { String queryString = query.createHQLDelete(); Query hibQuery = getSession(false).createQuery( @@ -504,6 +463,7 @@ public class CoreDao extends HibernateDaoSupport { // Get a session and create a new criteria instance queryResult = (List) txTemplate .execute(new TransactionCallback() { + @Override public List doInTransaction(TransactionStatus status) { String queryString = query.createHQLQuery(); Query hibQuery = getSession(false).createQuery( @@ -531,6 +491,15 @@ public class CoreDao extends HibernateDaoSupport { return queryResult; } + public void deleteAll(final List objs) { + txTemplate.execute(new TransactionCallbackWithoutResult() { + @Override + public void doInTransactionWithoutResult(TransactionStatus status) { + getHibernateTemplate().deleteAll(objs); + } + }); + } + /** * * @param fields @@ -723,6 +692,7 @@ public class CoreDao extends HibernateDaoSupport { QueryResult result = (QueryResult) txTemplate .execute(new TransactionCallback() { + @Override public QueryResult doInTransaction(TransactionStatus status) { Query hibQuery = getSession(false) .createQuery(hqlQuery); @@ -776,6 +746,7 @@ public class CoreDao extends HibernateDaoSupport { int queryResult = (Integer) txTemplate .execute(new TransactionCallback() { + @Override public Integer doInTransaction(TransactionStatus status) { Query hibQuery = getSession(false).createQuery(hqlStmt); // hibQuery.setCacheMode(CacheMode.NORMAL); @@ -800,6 +771,7 @@ public class CoreDao extends HibernateDaoSupport { long start = System.currentTimeMillis(); List queryResult = (List) txTemplate .execute(new TransactionCallback() { + @Override public List doInTransaction(TransactionStatus status) { return getSession(false).createSQLQuery(sql).list(); } @@ -814,6 +786,7 @@ public class CoreDao extends HibernateDaoSupport { long start = System.currentTimeMillis(); List queryResult = (List) txTemplate .execute(new TransactionCallback() { + @Override public List doInTransaction(TransactionStatus status) { Criteria crit = getSession(false).createCriteria( @@ -848,6 +821,7 @@ public class CoreDao extends HibernateDaoSupport { long start = System.currentTimeMillis(); int updateResult = (Integer) txTemplate .execute(new TransactionCallback() { + @Override public Integer doInTransaction(TransactionStatus status) { return getSession(false).createSQLQuery(sql) .executeUpdate(); diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/DaoConfig.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/DaoConfig.java index 98486c5b91..a02bdaed73 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/DaoConfig.java +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/DaoConfig.java @@ -20,6 +20,11 @@ package com.raytheon.uf.edex.database.dao; +import org.hibernate.SessionFactory; +import org.springframework.orm.hibernate3.HibernateTransactionManager; + +import com.raytheon.uf.edex.core.EDEXUtil; + /** * Configuration settings for a data access object.
* This object contains the required information to correctly instantiate a @@ -31,14 +36,15 @@ package com.raytheon.uf.edex.database.dao; * * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * 12/11/07 600 bphillip Initial Check in - * + * 12/11/07 600 bphillip Initial Check in + * Oct 10, 2012 1261 djohnson Add ability for test overriding of bean lookups. + * * * * @author bphillip * @version 1 */ -public class DaoConfig { +public abstract class DaoConfig { /** The default database name */ public static final String DEFAULT_DB_NAME = "metadata"; @@ -49,6 +55,21 @@ public class DaoConfig { /** The transaction manager suffix */ private static final String TX_MANAGER = "TxManager"; + // @VisibleForTesting + static SpringBeanLocator DEFAULT_LOCATOR = new SpringBeanLocator() { + @Override + public T lookupBean(Class resultClass, String beanName) { + return resultClass.cast(EDEXUtil.getESBComponent(beanName)); + } + }; + + /** + * Used to locate Spring beans. By default, uses EDEXUtil to look them up. + * Package-level access for testing purposes. + */ + // @VisibleForTesting + static SpringBeanLocator locator = DEFAULT_LOCATOR; + /** * The default data access object configuration. This configuration * specifies the metadata database @@ -56,69 +77,27 @@ public class DaoConfig { public static final DaoConfig DEFAULT = DaoConfig .forDatabase(DEFAULT_DB_NAME); - /** The database to connect to */ - private String dbName; - - /** The class for which the desired data access object is to be used for */ - private Class daoClassName; - - /** The name of the Hibernate session factory to use */ - private String sessionFactoryName; - - /** The name of the Hibernate transaction manager to use */ - private String txManagerName; - /** - * Default constructor. - */ - private DaoConfig() { - this.dbName = DEFAULT_DB_NAME; - this.sessionFactoryName = DEFAULT_DB_NAME + SESSION_FACTORY; - this.txManagerName = DEFAULT_DB_NAME + TX_MANAGER; - } - - /** - * Constructs a DaoConfig object using the specified class name, default - * session factory, and the default transaction manager + * Retrieve the transaction manager. * - * @param className - * The class object + * @return the transaction manager */ - private DaoConfig(Class className) { - this.daoClassName = className; - this.dbName = DEFAULT_DB_NAME; - this.sessionFactoryName = DEFAULT_DB_NAME + SESSION_FACTORY; - this.txManagerName = DEFAULT_DB_NAME + TX_MANAGER; - } + public abstract HibernateTransactionManager getTxManager(); /** - * Constructs a DaoConfig object for the specified database using the - * specified class name. The appropriate session factory and transaction - * manager will be determined from the database name. + * Retrieve the session factory. * - * @param dbName - * The database name - * @param className - * The class object + * @return the session factory */ - private DaoConfig(String dbName, Class className) { - this.daoClassName = className; - this.dbName = dbName; - this.sessionFactoryName = dbName + SESSION_FACTORY; - this.txManagerName = dbName + TX_MANAGER; - } + public abstract SessionFactory getSessionFactory(); /** - * Constructs a DaoConfig object for the specified database. + * Retrieve the class type this DAO manages. * - * @param dbName - * The database name + * @return the class type */ - private DaoConfig(String dbName) { - this.dbName = dbName; - this.sessionFactoryName = dbName + SESSION_FACTORY; - this.txManagerName = dbName + TX_MANAGER; - } + public abstract Class getDaoClass(); + /** * Gets a DaoConfig object for the specified class using the default session @@ -130,7 +109,7 @@ public class DaoConfig { * factory and default transaction manager. */ public static DaoConfig forClass(Class className) { - return new DaoConfig(className); + return new SpringLookupDaoConfig(className); } /** @@ -146,8 +125,8 @@ public class DaoConfig { */ public static DaoConfig forClass(String className) throws ClassNotFoundException { - return new DaoConfig(DaoConfig.class.getClassLoader().loadClass( - ((String) className).trim())); + return new SpringLookupDaoConfig(DaoConfig.class.getClassLoader().loadClass( + (className).trim())); } /** @@ -161,7 +140,7 @@ public class DaoConfig { * name */ public static DaoConfig forClass(String dbName, Class className) { - return new DaoConfig(dbName, className); + return new SpringLookupDaoConfig(dbName, className); } /** @@ -178,8 +157,8 @@ public class DaoConfig { */ public static DaoConfig forClass(String dbName, String className) throws ClassNotFoundException { - return new DaoConfig(dbName, DaoConfig.class.getClassLoader() - .loadClass(((String) className).trim())); + return new SpringLookupDaoConfig(dbName, DaoConfig.class.getClassLoader() + .loadClass((className).trim())); } /** @@ -188,39 +167,87 @@ public class DaoConfig { * @return */ public static DaoConfig forDatabase(String dbName) { - return new DaoConfig(dbName); + return new SpringLookupDaoConfig(dbName); } - /** - * Gets the database name - * @return The database name - */ - public String getDbName() { - return dbName; - } + private static class SpringLookupDaoConfig extends DaoConfig { - /** - * Gets the dao class name - * @return The dao class name - */ - public Class getDaoClassName() { - return daoClassName; - } + /** The class for which the desired data access object is to be used for */ + private final Class daoClass; - /** - * Gets the session factory name - * @return The session factory name - */ - public String getSessionFactoryName() { - return sessionFactoryName; - } + /** The name of the Hibernate session factory to use */ + private final String sessionFactoryName; - /** - * Gets the transaction manager name - * @return The transaction manager name - */ - public String getTxManagerName() { - return txManagerName; - } + /** The name of the Hibernate transaction manager to use */ + private final String txManagerName; + /** + * Default constructor. + */ + private SpringLookupDaoConfig() { + this((Class) null); + } + + /** + * Constructs a DaoConfig object using the specified class name, default + * session factory, and the default transaction manager + * + * @param className + * The class object + */ + private SpringLookupDaoConfig(Class className) { + this(DEFAULT_DB_NAME, className); + } + + /** + * Constructs a DaoConfig object for the specified database. + * + * @param dbName + * The database name + */ + private SpringLookupDaoConfig(String dbName) { + this(dbName, null); + } + + /** + * Constructs a DaoConfig object for the specified database using the + * specified class name. The appropriate session factory and transaction + * manager will be determined from the database name. + * + * @param dbName + * The database name + * @param daoClass + * The class object + */ + private SpringLookupDaoConfig(String dbName, Class daoClass) { + this.daoClass = daoClass; + this.sessionFactoryName = dbName + SESSION_FACTORY; + this.txManagerName = dbName + TX_MANAGER; + } + + /** + * {@inheritDoc} + */ + @Override + public HibernateTransactionManager getTxManager() { + return locator.lookupBean(HibernateTransactionManager.class, + txManagerName); + } + + /** + * {@inheritDoc} + */ + @Override + public SessionFactory getSessionFactory() { + return locator.lookupBean(SessionFactory.class, sessionFactoryName); + } + + /** + * {@inheritDoc} + */ + @Override + public Class getDaoClass() { + return daoClass; + } + } } diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/SpringBeanLocator.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/SpringBeanLocator.java new file mode 100644 index 0000000000..bd3fc6e0fe --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/dao/SpringBeanLocator.java @@ -0,0 +1,52 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.database.dao; + +/** + * Defines a strategy for looking up Spring beans. + * + *

+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 10, 2012 1261       djohnson     Initial creation
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public interface SpringBeanLocator { + + /** + * Lookup a Spring bean by its name. + * + * @param + * the result type + * @param resultClass + * the result class type + * @param beanName + * the bean name + * @return the looked up bean, or null, if not found + */ + T lookupBean(Class resultClass, String beanName); +} diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/plugin/PluginDao.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/plugin/PluginDao.java index 0ed4d3a658..95a6139e72 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/plugin/PluginDao.java +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/plugin/PluginDao.java @@ -35,6 +35,10 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.geotools.coverage.grid.GridCoverage2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.opengis.referencing.FactoryException; +import org.opengis.referencing.crs.CoordinateReferenceSystem; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallbackWithoutResult; @@ -51,7 +55,13 @@ import com.raytheon.uf.common.datastorage.IDataStore.StoreOp; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.StorageException; import com.raytheon.uf.common.datastorage.StorageStatus; +import com.raytheon.uf.common.datastorage.records.ByteDataRecord; +import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.datastorage.records.IntegerDataRecord; +import com.raytheon.uf.common.geospatial.ISpatialEnabled; +import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.geospatial.MapUtil; import com.raytheon.uf.common.localization.IPathManager; import com.raytheon.uf.common.localization.LocalizationContext; import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; @@ -60,6 +70,8 @@ import com.raytheon.uf.common.localization.LocalizationFile; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.spatial.reprojection.DataReprojector; +import com.raytheon.uf.common.spatial.reprojection.ReferencedDataRecord; import com.raytheon.uf.common.time.util.TimeUtil; import com.raytheon.uf.common.util.FileUtil; import com.raytheon.uf.edex.core.EdexException; @@ -71,6 +83,10 @@ import com.raytheon.uf.edex.database.purge.PurgeLogger; import com.raytheon.uf.edex.database.purge.PurgeRule; import com.raytheon.uf.edex.database.purge.PurgeRuleSet; import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.Envelope; +import com.vividsolutions.jts.geom.Geometry; +import com.vividsolutions.jts.geom.Polygon; /** * Abstract implementation of a Plugin data access object @@ -86,6 +102,7 @@ import com.raytheon.uf.edex.database.query.DatabaseQuery; * 2/6/09 1990 bphillip Initial creation * 6/29/12 #828 dgilling Force getPurgeRulesForPlugin() * to search only COMMON_STATIC. + * Oct 10, 2012 1261 djohnson Add some generics wildcarding. * * * @author bphillip @@ -174,13 +191,14 @@ public abstract class PluginDao extends CoreDao { persistToDatabase(records); } + @SuppressWarnings("unchecked") public PluginDataObject[] persistToDatabase(PluginDataObject... records) { - List toPersist = new ArrayList(); + List> toPersist = new ArrayList>(); for (PluginDataObject record : records) { toPersist.add(record); } - List duplicates = mergeAll(toPersist); - for (PersistableDataObject pdo : duplicates) { + List> duplicates = mergeAll(toPersist); + for (PersistableDataObject pdo : duplicates) { logger.info("Discarding duplicate: " + ((PluginDataObject) (pdo)).getDataURI()); toPersist.remove(pdo); @@ -442,21 +460,45 @@ public abstract class PluginDao extends CoreDao { * If problems occur while interacting with the data stores */ public void purgeAllData() throws PluginException { + purgeAllData(null); + } + + /** + * Purges all data associated with the productKeys and owning plugin + * + * @throws PluginException + * If problems occur while interacting with the data stores + */ + public void purgeAllData(Map productsKeys) + throws PluginException { + boolean purgeHdf5Data = false; + try { + // Determine if this plugin uses HDF5 to store data + purgeHdf5Data = (PluginFactory.getInstance() + .getPluginRecordClass(pluginName).newInstance() instanceof IPersistable); + } catch (Exception e) { + PurgeLogger.logError( + "Unabled to determine if plugin has HDF5 data to purge", + this.pluginName, e); + } + try { List allRefTimes = getRefTimes(); Map> filesToDelete = new HashMap>(); for (Date d : allRefTimes) { - this.purgeDataByRefTime(d, null, true, false, filesToDelete); + this.purgeDataByRefTime(d, productsKeys, purgeHdf5Data, false, + filesToDelete); } - for (String file : filesToDelete.keySet()) { - try { - IDataStore ds = DataStoreFactory - .getDataStore(new File(file)); - ds.deleteFiles(null); - } catch (Exception e) { - PurgeLogger.logError( - "Error occurred purging file: " + file, - this.pluginName, e); + if (purgeHdf5Data) { + for (String file : filesToDelete.keySet()) { + try { + IDataStore ds = DataStoreFactory.getDataStore(new File( + file)); + ds.deleteFiles(null); + } catch (Exception e) { + PurgeLogger.logError("Error occurred purging file: " + + file, this.pluginName, e); + } } } } catch (Exception e) { @@ -1054,7 +1096,9 @@ public abstract class PluginDao extends CoreDao { /** * Purges data from the database for this plugin with the given reference * time matching the given productKeys. If refTime is null, will purge all - * data associated with the productKeys. + * data associated with the productKeys. Hdf5 must be purged separately as + * most hdf5 files can't be purged with a single reference time. Use the + * passed map to track what needs to be done with hdf5. * * @param refTime * The reftime to delete data for. A null will purge all data for @@ -1426,8 +1470,8 @@ public abstract class PluginDao extends CoreDao { return null; } try { - PurgeRuleSet purgeRules = (PurgeRuleSet) SerializationUtil - .jaxbUnmarshalFromXmlFile(defaultRule); + PurgeRuleSet purgeRules = SerializationUtil + .jaxbUnmarshalFromXmlFile(PurgeRuleSet.class, defaultRule); return purgeRules.getDefaultRules(); } catch (SerializationException e) { PurgeLogger.logError("Error deserializing default purge rule!", @@ -1536,4 +1580,130 @@ public abstract class PluginDao extends CoreDao { return (List) this.queryByCriteria(dbQuery); } + + public double getHDF5Value(PluginDataObject pdo, + CoordinateReferenceSystem crs, Coordinate coord, + double defaultReturn) throws Exception { + IDataStore store = getDataStore((IPersistable) pdo); + // TODO a cache would probably be good here + double rval = defaultReturn; + if (pdo instanceof ISpatialEnabled) { + ISpatialObject spat = getSpatialObject(pdo); + DataReprojector reprojector = getDataReprojector(store); + ReferencedEnvelope nativeEnv = getNativeEnvelope(spat); + IDataRecord data = reprojector.getProjectedPoints(pdo.getDataURI(), + spat, nativeEnv, crs, new Coordinate[] { coord }); + Double res = extractSingle(data); + if (res != null) { + rval = res; + } + } + return rval; + } + + /** + * @param record + * @param crs + * target crs for projected data + * @param envelope + * bounding box in target crs + * @return null if envelope is disjoint with data bounds + * @throws Exception + */ + public ReferencedDataRecord getProjected(PluginDataObject record, + CoordinateReferenceSystem crs, Envelope envelope) throws Exception { + ReferencedEnvelope targetEnv = new ReferencedEnvelope( + envelope.getMinX(), envelope.getMaxX(), envelope.getMinY(), + envelope.getMaxY(), crs); + return getProjected(record, targetEnv); + } + + /** + * @param record + * @param crs + * target crs for projected data + * @param envelope + * bounding box in target crs + * @return null if envelope is disjoint with data bounds + * @throws Exception + */ + public GridCoverage2D getProjectedCoverage(PluginDataObject record, + CoordinateReferenceSystem crs, Envelope envelope) throws Exception { + ReferencedEnvelope targetEnv = new ReferencedEnvelope( + envelope.getMinX(), envelope.getMaxX(), envelope.getMinY(), + envelope.getMaxY(), crs); + return getProjectedCoverage(record, targetEnv); + } + + /** + * @param record + * @param targetEnvelope + * bounding box in target crs + * @return null if envelope is disjoint with data bounds + * @throws Exception + */ + public ReferencedDataRecord getProjected(PluginDataObject record, + ReferencedEnvelope targetEnvelope) throws Exception { + ISpatialObject spatial = getSpatialObject(record); + IDataStore store = getDataStore((IPersistable) record); + DataReprojector reprojector = getDataReprojector(store); + ReferencedEnvelope nativeEnvelope = getNativeEnvelope(spatial); + return reprojector.getReprojected(record.getDataURI(), spatial, + nativeEnvelope, targetEnvelope); + } + + /** + * @param record + * @param targetEnvelope + * bounding box in target crs + * @return null if envelope is disjoint with data bounds + * @throws Exception + */ + public GridCoverage2D getProjectedCoverage(PluginDataObject record, + ReferencedEnvelope envelope) throws Exception { + ISpatialObject spatial = getSpatialObject(record); + IDataStore store = getDataStore((IPersistable) record); + DataReprojector reprojector = getDataReprojector(store); + ReferencedEnvelope nativeEnvelope = getNativeEnvelope(spatial); + return reprojector.getReprojectedCoverage(record.getDataURI(), spatial, + nativeEnvelope, envelope); + } + + protected ISpatialObject getSpatialObject(PluginDataObject record) + throws Exception { + if (record instanceof ISpatialEnabled) { + return ((ISpatialEnabled) record).getSpatialObject(); + } else { + throw new Exception(record.getClass() + " is not spatially enabled"); + } + } + + protected DataReprojector getDataReprojector(IDataStore dataStore) { + return new DataReprojector(dataStore); + } + + protected ReferencedEnvelope getNativeEnvelope(ISpatialObject spatial) + throws FactoryException { + CoordinateReferenceSystem crs = spatial.getCrs(); + Geometry geom = spatial.getGeometry(); + return MapUtil.getBoundingEnvelope(crs, (Polygon) geom); + } + + public Double extractSingle(IDataRecord record) { + Double rval = null; + if (record == null) { + return rval; + } + if (record instanceof ByteDataRecord) { + byte[] data = ((ByteDataRecord) record).getByteData(); + rval = (double) data[0]; + } else if (record instanceof FloatDataRecord) { + float[] data = ((FloatDataRecord) record).getFloatData(); + rval = (double) data[0]; + } else if (record instanceof IntegerDataRecord) { + int[] data = ((IntegerDataRecord) record).getIntData(); + rval = (double) data[0]; + } + return rval; + } } diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleSet.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleSet.java index 6a15bc50c4..41c4d9d404 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleSet.java +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleSet.java @@ -21,6 +21,7 @@ package com.raytheon.uf.edex.database.purge; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; @@ -63,7 +64,7 @@ public class PurgeRuleSet implements ISerializableObject { * List of purge rules for/from the XML. */ @XmlElements({ @XmlElement(name = "rule", type = PurgeRule.class) }) - private ArrayList rules; + private List rules; private PurgeRuleTree purgeTree = null; @@ -98,8 +99,8 @@ public class PurgeRuleSet implements ISerializableObject { * * @return */ - public ArrayList getRules() { - return rules; + public List getRules() { + return (rules == null) ? Collections. emptyList() : rules; } public void setRules(final ArrayList rules) { diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleTree.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleTree.java index bd9454625c..cac946812f 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleTree.java +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/purge/PurgeRuleTree.java @@ -49,7 +49,7 @@ public class PurgeRuleTree { public PurgeRuleTree(PurgeRuleSet ruleSet) { root = new PurgeNode(); root.setRules(ruleSet.getDefaultRules()); - ArrayList rules = ruleSet.getRules(); + List rules = ruleSet.getRules(); if (rules != null) { for (PurgeRule rule : rules) { PurgeNode curNode = root; diff --git a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/query/DatabaseQuery.java b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/query/DatabaseQuery.java index 7235404136..2e195101c6 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/query/DatabaseQuery.java +++ b/edexOsgi/com.raytheon.uf.edex.database/src/com/raytheon/uf/edex/database/query/DatabaseQuery.java @@ -34,13 +34,13 @@ import org.hibernate.SQLQuery; import org.hibernate.SessionFactory; import org.hibernate.metadata.ClassMetadata; -import com.raytheon.uf.common.dataplugin.convert.ConvertUtil; import com.raytheon.uf.common.dataquery.db.JoinField; import com.raytheon.uf.common.dataquery.db.OrderField; import com.raytheon.uf.common.dataquery.db.OrderField.ResultOrder; import com.raytheon.uf.common.dataquery.db.QueryParam; import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; import com.raytheon.uf.common.dataquery.db.ReturnedField; +import com.raytheon.uf.common.util.ConvertUtil; import com.raytheon.uf.edex.database.DataAccessLayerException; /** diff --git a/edexOsgi/com.raytheon.uf.edex.esb.camel/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.esb.camel/META-INF/MANIFEST.MF index 1e03fcae7e..3b8acf636e 100644 --- a/edexOsgi/com.raytheon.uf.edex.esb.camel/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.esb.camel/META-INF/MANIFEST.MF @@ -12,11 +12,15 @@ Require-Bundle: org.apache.camel;bundle-version="1.0.0", org.apache.http;bundle-version="3.0.1", com.raytheon.uf.common.localization;bundle-version="1.11.17", com.raytheon.uf.common.status, + com.raytheon.uf.common.util, com.raytheon.uf.edex.core, org.apache.commons.logging, - javax.servlet + javax.servlet, + com.raytheon.uf.common.stats;bundle-version="1.0.0" Export-Package: com.raytheon.uf.edex.esb.camel, com.raytheon.uf.edex.esb.camel.directvm -Import-Package: com.raytheon.uf.common.message, +Import-Package: com.raytheon.uf.common.event, + com.raytheon.uf.common.message, com.raytheon.uf.edex.database.cluster, + com.raytheon.uf.edex.event, javax.persistence diff --git a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/Executor.java b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/Executor.java index b74ee1ea74..53fd45356f 100644 --- a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/Executor.java +++ b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/Executor.java @@ -26,12 +26,15 @@ import java.io.FilenameFilter; import java.io.IOException; import java.lang.management.ManagementFactory; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; +import java.util.Properties; import java.util.jar.JarEntry; import java.util.jar.JarFile; +import java.util.regex.Pattern; import javax.management.MBeanServerConnection; import javax.management.ObjectInstance; @@ -43,9 +46,12 @@ import javax.xml.bind.Unmarshaller; import org.apache.activemq.console.util.JmxMBeansUtil; import org.springframework.context.support.ClassPathXmlApplicationContext; +import com.raytheon.uf.common.util.PropertiesUtil; +import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.core.props.PropertiesFactory; import com.raytheon.uf.edex.esb.camel.context.ContextManager; import com.raytheon.uf.edex.esb.camel.spring.DefaultEdexMode; +import com.raytheon.uf.edex.esb.camel.spring.EdexMode; import com.raytheon.uf.edex.esb.camel.spring.EdexModesContainer; /** @@ -56,9 +62,14 @@ import com.raytheon.uf.edex.esb.camel.spring.EdexModesContainer; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Nov 14, 2008 chammack Initial creation - * Jul 14, 2009 #2950 njensen Basic spring file ordering - * Apr 5, 2010 #3857 njensen Removed file ordering in favor of - * spring's depends-on attribute + * Jul 14, 2009 #2950 njensen Basic spring file ordering + * Apr 05, 2010 #3857 njensen Removed file ordering in favor of + * spring's depends-on attribute + * Jun 12, 2012 #0609 djohnson Use EDEXUtil for EDEX_HOME. + * Jul 09, 2012 #0643 djohnson Read plugin provided resources into system properties. + * Jul 17, 2012 #0740 djohnson Redo changes since the decomposed repositories lost them. + * Oct 19, 2012 #1274 bgonzale Load properties from files in conf + * resources directory. * * * @@ -70,6 +81,11 @@ public class Executor { public static final String XML = ".xml"; + private static final Pattern XML_PATTERN = Pattern.compile("\\" + XML); + + private static final Pattern RES_SPRING_PATTERN = Pattern + .compile("res/spring/"); + private static final String MODES_FILE = "modes.xml"; public static void start() throws Exception { @@ -84,26 +100,41 @@ public class Executor { List xmlFiles = new ArrayList(); - File confDir = new File(System.getProperty("edex.home") + List propertiesFiles = new ArrayList(); + File confDir = new File(EDEXUtil.EDEX_HOME + File.separator + "conf"); - File springDir = new File(confDir, "spring"); - File[] springFiles = springDir.listFiles(new FileFilter() { + File resourcesDir = new File(confDir, "resources"); + propertiesFiles.addAll(Arrays.asList(findFiles(resourcesDir, + ".properties"))); + // load site files after loading the config files so that their + // properties take precedence. + String site = System.getProperty("aw.site.identifier"); + File siteResourcesDir = new File(confDir, "resources" + File.separator + + "site" + File.separator + site); + propertiesFiles.addAll(Arrays.asList(findFiles(siteResourcesDir, + ".properties"))); + + // Add each file to the system properties + for (File propertiesFile : propertiesFiles) { + Properties properties = PropertiesUtil.read(propertiesFile); + System.getProperties().putAll(properties); + } + + File springDir = new File(confDir, "spring"); + File[] springFiles = findFiles(springDir, XML); - @Override - public boolean accept(File pathname) { - return pathname.getName().endsWith(XML); - } - }); List springList = new ArrayList(); for (File f : springFiles) { - xmlFiles.add(f.getName()); - springList.add(f.getName().replace(XML, "")); + String name = f.getName(); + + xmlFiles.add(name); + springList.add(XML_PATTERN.matcher(name).replaceAll("")); } EdexModesContainer emc = getModeFilter(confDir); String modeName = System.getProperty("edex.run.mode"); String highMem = System.getProperty("HighMem"); - boolean highMemEnabled = (highMem != null && highMem.equals("on")); + boolean highMemEnabled = "on".equals(highMem); if (modeName != null && modeName.length() > 0) { System.out.println("EDEX run configuration: " + modeName @@ -114,7 +145,16 @@ public class Executor { } System.out.println("EDEX site configuration: " + System.getProperty("aw.site.identifier")); - FilenameFilter mode = emc.getMode(modeName, highMemEnabled); + + EdexMode edexMode = emc.getMode(modeName, highMemEnabled); + + if (edexMode != null && edexMode.isTemplate()) { + throw new UnsupportedOperationException(modeName + + " is a template mode, and is not bootable."); + } + + FilenameFilter mode = edexMode; + if (mode == null) { if (modeName == null || modeName.length() == 0) { mode = new DefaultEdexMode(); @@ -180,22 +220,40 @@ public class Executor { } } + /** + * Finds all files in the specified directory with specified extension. + * + * @param directory + * the directory + * @param extension + * file extension + * @return the file array + */ + private static File[] findFiles(File directory, final String extension) { + File[] files = directory.listFiles(new FileFilter() { + @Override + public boolean accept(File pathname) { + return pathname.getName().endsWith(extension); + } + }); + + // If no files were found return an empty array + return (files == null) ? new File[0] : files; + } + private static String printList(List components) { StringBuffer sb = new StringBuffer(); - boolean first = true; Collections.sort(components); Iterator iterator = components.iterator(); while (iterator.hasNext()) { - if (first) { - first = false; - } else { - sb.append(", "); - } - sb.append(iterator.next()); + sb.append(", "); } + int length = sb.length(); + sb.delete(length - 2, length); + return sb.toString(); } @@ -231,7 +289,9 @@ public class Executor { String name = e.getName(); if (filter.accept(null, name)) { files.add(name); - retVal.add(name.replace(XML, "").replace("res/spring/", "")); + retVal.add(RES_SPRING_PATTERN.matcher( + XML_PATTERN.matcher(name).replaceAll("")) + .replaceAll("")); } } @@ -242,8 +302,7 @@ public class Executor { private static EdexModesContainer getModeFilter(File confDir) throws IOException, JAXBException { - String path = confDir.getPath() + File.separator + MODES_FILE; - File file = new File(path); + File file = new File(confDir.getPath(), MODES_FILE); FileReader reader = null; Unmarshaller msh = null; @@ -256,11 +315,7 @@ public class Executor { return emc; } finally { if (reader != null) { - try { - reader.close(); - } catch (IOException e) { - // ignore - } + PropertiesUtil.close(reader); } } } diff --git a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/FileToString.java b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/FileToString.java index e793947fe6..f3225a83b9 100644 --- a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/FileToString.java +++ b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/FileToString.java @@ -26,6 +26,8 @@ import org.apache.camel.Processor; import org.apache.camel.component.file.GenericFile; import org.springframework.util.FileCopyUtils; +import com.raytheon.uf.edex.core.EDEXUtil; + /** * Provides a capability to transform java.io.File to Strings * @@ -36,7 +38,8 @@ import org.springframework.util.FileCopyUtils; * SOFTWARE HISTORY * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- - * Dec 3, 2008 chammack Initial creation + * Dec 03, 2008 chammack Initial creation + * Jun 12, 2012 00609 djohnson Use EDEXUtil for EDEX_HOME. * * * @@ -46,7 +49,7 @@ import org.springframework.util.FileCopyUtils; public class FileToString implements Processor { - private static String DIR = System.getProperty("edex.home") + private static String DIR = EDEXUtil.EDEX_HOME + File.separator + "data" + File.separator + "processing"; @Override diff --git a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/ProcessUtil.java b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/ProcessUtil.java index 26b85ddfed..16eaef1f55 100644 --- a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/ProcessUtil.java +++ b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/ProcessUtil.java @@ -29,9 +29,11 @@ import org.apache.camel.Header; import org.apache.camel.Headers; import com.raytheon.uf.common.dataplugin.PluginDataObject; +import com.raytheon.uf.common.stats.ProcessEvent; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.edex.event.EventBus; /** * Provides logging and deletion services for camel @@ -53,6 +55,8 @@ public class ProcessUtil { protected static final IUFStatusHandler handler = UFStatus .getNamedHandler("Ingest"); + protected static final EventBus eventBus = EventBus.getInstance(); + protected transient final static ThreadLocal FORMAT = new ThreadLocal() { @Override @@ -65,74 +69,6 @@ public class ProcessUtil { }; - public void delete(@Header(value = "ingestFileName") String path) { - File f = new File(path); - if (f.exists()) { - f.delete(); - } - } - - public void deleteFile(File f) { - if (f.exists()) { - f.delete(); - } - } - - /** - * - * @param headers - */ - public void log(@Headers Map headers) { - - long curTime = System.currentTimeMillis(); - - StringBuilder sb = new StringBuilder(128); - - String pluginName = getHeaderProperty(headers, "pluginName"); - if (pluginName != null) { - sb.append(pluginName); - } - - String fileName = getHeaderProperty(headers, "ingestFileName"); - if (fileName != null) { - sb.append(":: "); - sb.append(fileName); - } - - Long dequeueTime = getHeaderProperty(headers, "dequeueTime"); - DecimalFormat df = FORMAT.get(); - if (dequeueTime != null) { - double elapsed = (curTime - dequeueTime) / 1000.0; - sb.append(" processed in: "); - sb.append(df.format(elapsed)); - sb.append(" (sec)"); - } - - Long enqueueTime = getHeaderProperty(headers, "enqueueTime"); - if (enqueueTime != null) { - double latency = (curTime - enqueueTime) / 1000.0; - sb.append(" Latency: "); - sb.append(df.format(latency)); - sb.append(" (sec)"); - } - // Make sure we have something to log. - if (sb.length() > 0) { - handler.handle(Priority.INFO, sb.toString()); - } else { - handler.handle(Priority.INFO, "No logging information available"); - } - } - - /** - * Return an incoming array as an Iterator to the elements. - * - * @param objects - * @return - */ - public static Iterator iterate(PluginDataObject[] objects) { - return Arrays.asList(objects).iterator(); - } - /** * Get the value of a specified property if it exists. * @@ -157,4 +93,87 @@ public class ProcessUtil { } return result; } + + /** + * Return an incoming array as an Iterator to the elements. + * + * @param objects + * @return + */ + public static Iterator iterate(PluginDataObject[] objects) { + return Arrays.asList(objects).iterator(); + } + + public void delete(@Header(value = "ingestFileName") String path) { + File f = new File(path); + if (f.exists()) { + f.delete(); + } + } + + public void deleteFile(File f) { + if (f.exists()) { + f.delete(); + } + } + + /** + * + * @param headers + */ + public void log(@Headers Map headers) { + + long curTime = System.currentTimeMillis(); + + StringBuilder sb = new StringBuilder(128); + + ProcessEvent processEvent = new ProcessEvent(); + String pluginName = getHeaderProperty(headers, "pluginName"); + if (pluginName != null) { + sb.append(pluginName); + processEvent.setPluginName(pluginName); + } + + String fileName = getHeaderProperty(headers, "ingestFileName"); + if (fileName != null) { + sb.append(":: "); + sb.append(fileName); + processEvent.setFileName(fileName); + } + + Long dequeueTime = getHeaderProperty(headers, "dequeueTime"); + DecimalFormat df = FORMAT.get(); + if (dequeueTime != null) { + long elapsedMilliseconds = curTime - dequeueTime; + double elapsed = elapsedMilliseconds / 1000.0; + sb.append(" processed in: "); + sb.append(df.format(elapsed)); + sb.append(" (sec)"); + processEvent.setProcessingTime(elapsedMilliseconds); + } + + Long enqueueTime = getHeaderProperty(headers, "enqueueTime"); + if (enqueueTime != null) { + long latencyMilliseconds = curTime - enqueueTime; + double latency = latencyMilliseconds / 1000.0; + sb.append(" Latency: "); + sb.append(df.format(latency)); + sb.append(" (sec)"); + processEvent.setProcessingLatency(latencyMilliseconds); + } + + // processing in less than 0 millis isn't trackable, usually due to an + // error occurred and statement logged incorrectly + if ((processEvent.getProcessingLatency() > 0) + && (processEvent.getProcessingTime() > 0)) { + eventBus.publish(processEvent); + } + + // Make sure we have something to log. + if (sb.length() > 0) { + handler.handle(Priority.INFO, sb.toString()); + } else { + handler.handle(Priority.INFO, "No logging information available"); + } + } } diff --git a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/spring/EdexMode.java b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/spring/EdexMode.java index 32caf43dfa..0cda0096d3 100644 --- a/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/spring/EdexMode.java +++ b/edexOsgi/com.raytheon.uf.edex.esb.camel/src/com/raytheon/uf/edex/esb/camel/spring/EdexMode.java @@ -21,6 +21,7 @@ package com.raytheon.uf.edex.esb.camel.spring; import java.io.File; import java.util.ArrayList; +import java.util.List; import java.util.regex.Pattern; import javax.xml.bind.annotation.XmlAccessType; @@ -28,6 +29,8 @@ import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElements; +import javax.xml.bind.annotation.XmlID; +import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlRootElement; /** @@ -40,6 +43,7 @@ import javax.xml.bind.annotation.XmlRootElement; * Date Ticket# Engineer Description * ------------ ---------- ----------- -------------------------- * Apr 22, 2010 njensen Initial creation + * Sep 19, 2012 1195 djohnson Allow 0..n other modes to be included. * * * @@ -52,31 +56,54 @@ import javax.xml.bind.annotation.XmlRootElement; public class EdexMode extends DefaultEdexMode { @XmlAttribute(name = "name") + @XmlID private String name; @XmlElements( { @XmlElement(name = "include", type = String.class) }) - private ArrayList includeList; + private final List includeList; - private ArrayList compiledIncludes; + private final List compiledIncludes; @XmlElements( { @XmlElement(name = "exclude", type = String.class) }) - private ArrayList excludeList; + private final List excludeList; - private ArrayList compiledExcludes; + private final List compiledExcludes; - private boolean inited = false; + @XmlElements({ @XmlElement(name = "includeMode") }) + @XmlIDREF + private final List includedModes; + + private boolean inited; + + @XmlAttribute + private boolean template; public EdexMode() { - includeList = new ArrayList(); - compiledIncludes = new ArrayList(); - excludeList = new ArrayList(); - compiledExcludes = new ArrayList(); + this(new ArrayList(), new ArrayList(), + new ArrayList()); + } + + // @VisibleForTesting + EdexMode(List includeList, List excludeList, + List includedModes) { + this.includeList = includeList; + compiledIncludes = new ArrayList(includeList.size()); + this.excludeList = excludeList; + compiledExcludes = new ArrayList(excludeList.size()); + this.includedModes = includedModes; } /** * Compiles the patterns */ public void init() { + + for (EdexMode includedMode : includedModes) { + if (!includedMode.isInited()) { + includedMode.init(); + } + } + for (String s : includeList) { compiledIncludes.add(Pattern.compile(s)); } @@ -84,6 +111,11 @@ public class EdexMode extends DefaultEdexMode { for (String s : excludeList) { compiledExcludes.add(Pattern.compile(s)); } + + for (EdexMode includedMode : includedModes) { + compiledIncludes.addAll(includedMode.compiledIncludes); + compiledExcludes.addAll(includedMode.compiledExcludes); + } inited = true; } @@ -100,9 +132,17 @@ public class EdexMode extends DefaultEdexMode { .substring(filename.lastIndexOf(File.separator) + 1); } + // If we explicitly exclude the pattern, just return false + for (Pattern p : compiledExcludes) { + if (p.matcher(filename).find()) { + return false; + } + } + boolean matches = false; + // default to include * if no include regexes are present - if (compiledIncludes.size() == 0) { + if (compiledIncludes.isEmpty()) { matches = true; } else { for (Pattern p : compiledIncludes) { @@ -113,15 +153,6 @@ public class EdexMode extends DefaultEdexMode { } } - if (matches) { - for (Pattern p : compiledExcludes) { - if (p.matcher(filename).find()) { - matches = false; - break; - } - } - } - return matches; } @@ -150,4 +181,24 @@ public class EdexMode extends DefaultEdexMode { this.inited = inited; } + /** + * Return whether or not the mode is a template mode. Template modes cannot + * be booted. + * + * @return the template + */ + public boolean isTemplate() { + return template; + } + + /** + * Set whether the mode is a template or not. + * + * @param template + * true to denote a template mode + */ + public void setTemplate(boolean template) { + this.template = template; + } + } diff --git a/edexOsgi/com.raytheon.uf.edex.event.feature/.project b/edexOsgi/com.raytheon.uf.edex.event.feature/.project new file mode 100644 index 0000000000..daa16ed48a --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event.feature/.project @@ -0,0 +1,17 @@ + + + com.raytheon.uf.edex.event.feature + + + + + + org.eclipse.pde.FeatureBuilder + + + + + + org.eclipse.pde.FeatureNature + + diff --git a/edexOsgi/com.raytheon.uf.edex.event.feature/build.properties b/edexOsgi/com.raytheon.uf.edex.event.feature/build.properties new file mode 100644 index 0000000000..64f93a9f0b --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event.feature/build.properties @@ -0,0 +1 @@ +bin.includes = feature.xml diff --git a/edexOsgi/com.raytheon.uf.edex.event.feature/feature.xml b/edexOsgi/com.raytheon.uf.edex.event.feature/feature.xml new file mode 100644 index 0000000000..0e7b859168 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event.feature/feature.xml @@ -0,0 +1,48 @@ + + + + + [Enter Feature Description here.] + + + + [Enter Copyright Description here.] + + + + [Enter License Description here.] + + + + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.event/.classpath b/edexOsgi/com.raytheon.uf.edex.event/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.event/.project b/edexOsgi/com.raytheon.uf.edex.event/.project new file mode 100644 index 0000000000..254c0a6afa --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.edex.event + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.edex.event/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.edex.event/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..9cb7470e61 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Thu Jun 14 11:22:23 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.event/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.event/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..f515c34baa --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/META-INF/MANIFEST.MF @@ -0,0 +1,22 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Event +Bundle-SymbolicName: com.raytheon.uf.edex.event +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: com.google.guava;bundle-version="1.0.0", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.edex.core;bundle-version="1.12.1174", + com.raytheon.uf.common.event;bundle-version="1.0.0", + org.apache.commons.logging;bundle-version="1.1.1", + com.raytheon.uf.common.time;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.edex.database;bundle-version="1.0.0", + com.raytheon.uf.common.dataquery;bundle-version="1.0.0", + org.springframework;bundle-version="2.5.6", + com.raytheon.uf.common.localization;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin;bundle-version="1.12.1174", + org.junit +Export-Package: com.raytheon.uf.edex.event diff --git a/edexOsgi/com.raytheon.uf.edex.event/build.properties b/edexOsgi/com.raytheon.uf.edex.event/build.properties new file mode 100644 index 0000000000..5791d48d5f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ diff --git a/edexOsgi/com.raytheon.uf.edex.database/component-deploy.xml b/edexOsgi/com.raytheon.uf.edex.event/component-deploy.xml similarity index 96% rename from edexOsgi/com.raytheon.uf.edex.database/component-deploy.xml rename to edexOsgi/com.raytheon.uf.edex.event/component-deploy.xml index 5ce82feb6c..98acd607b6 100644 --- a/edexOsgi/com.raytheon.uf.edex.database/component-deploy.xml +++ b/edexOsgi/com.raytheon.uf.edex.event/component-deploy.xml @@ -1,4 +1,4 @@ - + diff --git a/edexOsgi/com.raytheon.uf.edex.event/res/spring/event-common.xml b/edexOsgi/com.raytheon.uf.edex.event/res/spring/event-common.xml new file mode 100644 index 0000000000..7619438902 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/res/spring/event-common.xml @@ -0,0 +1,9 @@ + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.event/res/spring/event-ingest.xml b/edexOsgi/com.raytheon.uf.edex.event/res/spring/event-ingest.xml new file mode 100644 index 0000000000..e9b737c3d9 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/res/spring/event-ingest.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.event/resources/eventBus.properties b/edexOsgi/com.raytheon.uf.edex.event/resources/eventBus.properties new file mode 100644 index 0000000000..5f0d71f7c5 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/resources/eventBus.properties @@ -0,0 +1,2 @@ +# Number of threads for async event bus +eventBusThreadCount=15 \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.event/src/com/raytheon/uf/edex/event/EventBus.java b/edexOsgi/com.raytheon.uf.edex.event/src/com/raytheon/uf/edex/event/EventBus.java new file mode 100644 index 0000000000..e49b91ee8d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/src/com/raytheon/uf/edex/event/EventBus.java @@ -0,0 +1,84 @@ +package com.raytheon.uf.edex.event; + +import java.util.concurrent.Executors; + +import com.google.common.eventbus.AsyncEventBus; +import com.raytheon.uf.common.event.Event; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; + +/** + * + * The EventBus. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Oct 11, 2012 1261       djohnson     Add SW history, create constants for fields, 
+ *                                      add unregister.
+ * 
+ * 
+ * + * @author djohnson + * @version 1.0 + */ +public class EventBus { + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(EventBus.class); + + private static final EventBus instance = new EventBus(); + + private static final AsyncEventBus asyncEventBus; + static { + int threadCount = 15; + try { + threadCount = Integer.parseInt(System.getProperty( + "eventBusThreadCount", "15")); + } catch (Exception e) { + statusHandler + .error("Unable to set thread pool size from property eventBusThreadCount; defaulting size to " + + threadCount + ".", e); + } + asyncEventBus = new AsyncEventBus("EventBus", + Executors.newFixedThreadPool(threadCount)); + } + + /** + * Returns the same instance of the data delivery event bus + * + * @return + */ + public static EventBus getInstance() { + return instance; + } + + /** + * Register an object with the event bus. + * + * @param subscriber + */ + public void register(Object subscriber) { + asyncEventBus.register(subscriber); + } + + /** + * Publishes events for all subscribers to receive + * + * @param event + */ + public void publish(Event event) { + asyncEventBus.post(event); + } + + /** + * Unregister an object with the event bus. + * + * @param instance2 + */ + public void unregister(Object subscriber) { + asyncEventBus.unregister(subscriber); + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.event/src/com/raytheon/uf/edex/event/handler/LogHandler.java b/edexOsgi/com.raytheon.uf.edex.event/src/com/raytheon/uf/edex/event/handler/LogHandler.java new file mode 100644 index 0000000000..788397d42d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.event/src/com/raytheon/uf/edex/event/handler/LogHandler.java @@ -0,0 +1,76 @@ +package com.raytheon.uf.edex.event.handler; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import com.google.common.eventbus.AllowConcurrentEvents; +import com.google.common.eventbus.Subscribe; +import com.raytheon.uf.common.event.Event; +import com.raytheon.uf.edex.event.EventBus; + +/** + * + * Logs ALL events published on the event bus + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 1, 2012            jsanchez     Initial creation
+ * Nov 5, 2012  #1305     bgonzale     Added log level Event logging.
+ * 
+ * 
+ * + * @author jsanchez + * @version 1.0 + */ +public class LogHandler { + + private final Log logger; + + private static EventBus eventBus = EventBus.getInstance(); + + /** + * Creates a new object + */ + public LogHandler() { + eventBus.register(this); + logger = LogFactory.getLog("Event"); + } + + /** + * Listens for any DataDeliveryEvent object published on the event bus + * + * @param event + */ + @Subscribe + @AllowConcurrentEvents + public void eventListener(Event event) { + switch (event.getLogLevel()) { + case DEBUG: + logger.debug(event.toString()); + break; + case INFO: + logger.info(event.toString()); + break; + case WARN: + logger.warn(event.toString()); + break; + case ERROR: + logger.error(event.toString()); + break; + case FATAL: + logger.fatal(event.toString()); + break; + case TRACE: + logger.trace(event.toString()); + break; + default: + // ALL + // logger.(event.toString()); + break; + } + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.grib.feature/feature.xml b/edexOsgi/com.raytheon.uf.edex.grib.feature/feature.xml index dc2b086fc4..77563eda3c 100644 --- a/edexOsgi/com.raytheon.uf.edex.grib.feature/feature.xml +++ b/edexOsgi/com.raytheon.uf.edex.grib.feature/feature.xml @@ -31,4 +31,46 @@ version="0.0.0" unpack="false"/> + + + + + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/.classpath b/edexOsgi/com.raytheon.uf.edex.gridcoverage/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/.project b/edexOsgi/com.raytheon.uf.edex.gridcoverage/.project new file mode 100644 index 0000000000..9e143887e2 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.edex.gridcoverage + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.edex.gridcoverage/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..67fede9efa --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Jan 31 14:13:40 CST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.gridcoverage/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..415ed90741 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/META-INF/MANIFEST.MF @@ -0,0 +1,23 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Grid Coverage +Bundle-SymbolicName: com.raytheon.uf.edex.gridcoverage +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Import-Package: com.raytheon.edex.db.dao, + com.raytheon.uf.common.dataplugin, + com.raytheon.uf.common.dataplugin.persist, + com.raytheon.uf.common.geospatial, + com.raytheon.uf.common.gridcoverage, + com.raytheon.uf.common.gridcoverage.exception, + com.raytheon.uf.common.gridcoverage.lookup, + com.raytheon.uf.common.gridcoverage.request, + com.raytheon.uf.common.serialization, + com.raytheon.uf.common.serialization.comm, + com.raytheon.uf.common.status, + com.raytheon.uf.edex.database.dao, + org.hibernate, + org.hibernate.criterion, + org.springframework.orm.hibernate3.support +Export-Package: com.raytheon.uf.edex.gridcoverage diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/build.properties b/edexOsgi/com.raytheon.uf.edex.gridcoverage/build.properties new file mode 100644 index 0000000000..5791d48d5f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/res/spring/gridcoverage-common.xml b/edexOsgi/com.raytheon.uf.edex.gridcoverage/res/spring/gridcoverage-common.xml new file mode 100644 index 0000000000..63f4240062 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/res/spring/gridcoverage-common.xml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.gridcoverage/src/com/raytheon/uf/edex/gridcoverage/GetGridCoverageHandler.java b/edexOsgi/com.raytheon.uf.edex.gridcoverage/src/com/raytheon/uf/edex/gridcoverage/GetGridCoverageHandler.java new file mode 100644 index 0000000000..82b5520cb7 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.gridcoverage/src/com/raytheon/uf/edex/gridcoverage/GetGridCoverageHandler.java @@ -0,0 +1,157 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.gridcoverage; + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; + +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.request.GetGridCoverageRequest; +import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; + +/** + * Handles database access of grid coverage, GetGridCoverageRequest can be used + * to do spatial lookup and creation. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 26, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GetGridCoverageHandler implements + IRequestHandler { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GetGridCoverageHandler.class); + + private final CoreDao dao; + + public GetGridCoverageHandler() { + dao = new CoreDao(DaoConfig.forClass(GridCoverage.class)); + } + + @Override + public GridCoverage handleRequest(GetGridCoverageRequest request) + throws Exception { + return checkDatabase(request.getCoverage(), request.getCreate()); + } + + private GridCoverage checkDatabase(GridCoverage coverage, boolean create) { + GridCoverage rval = null; + + Session sess = null; + Transaction trans = null; + try { + sess = dao.getSessionFactory().openSession(); + trans = sess.beginTransaction(); + + Criteria crit = sess.createCriteria(coverage.getClass()); + + crit.add(Restrictions.eq("nx", coverage.getNx())); + crit.add(Restrictions.eq("ny", coverage.getNx())); + crit.add(Restrictions.between("dx", coverage.getDx() + - GridCoverage.SPATIAL_TOLERANCE, coverage.getDx() + + GridCoverage.SPATIAL_TOLERANCE)); + crit.add(Restrictions.between("dy", coverage.getDy() + - GridCoverage.SPATIAL_TOLERANCE, coverage.getDy() + + GridCoverage.SPATIAL_TOLERANCE)); + crit.add(Restrictions.between("la1", coverage.getLa1() + - GridCoverage.SPATIAL_TOLERANCE, coverage.getLa1() + + GridCoverage.SPATIAL_TOLERANCE)); + crit.add(Restrictions.between("lo1", coverage.getLo1() + - GridCoverage.SPATIAL_TOLERANCE, coverage.getLo1() + + GridCoverage.SPATIAL_TOLERANCE)); + List vals = crit.list(); + for (Object val : vals) { + if (((GridCoverage) val).spatialEquals(coverage)) { + rval = (GridCoverage) val; + } + } + if (rval == null + && (Math.abs(coverage.getLo1()) > 179 || Math.abs(coverage + .getLa1()) > 89)) { + // if we got here nothing matches, try a query with no la1, and + // lo1 in case there are world wrap issues. + crit = sess.createCriteria(coverage.getClass()); + + crit.add(Restrictions.eq("nx", coverage.getNx())); + crit.add(Restrictions.eq("ny", coverage.getNx())); + crit.add(Restrictions.between("dx", coverage.getDx() + - GridCoverage.SPATIAL_TOLERANCE, coverage.getDx() + + GridCoverage.SPATIAL_TOLERANCE)); + crit.add(Restrictions.between("dy", coverage.getDy() + - GridCoverage.SPATIAL_TOLERANCE, coverage.getDy() + + GridCoverage.SPATIAL_TOLERANCE)); + vals = crit.list(); + for (Object val : vals) { + if (((GridCoverage) val).spatialEquals(coverage)) { + return (GridCoverage) val; + } + } + } + if (rval == null && create) { + // if it still does not exist, create it if requested + coverage.initialize(); + sess.saveOrUpdate(coverage); + rval = coverage; + } + + trans.commit(); + } catch (Exception e) { + statusHandler.error("Error occurred looking up GridCoverage[" + + coverage.getName() + "]", e); + + if (trans != null) { + try { + trans.rollback(); + } catch (Exception e1) { + statusHandler.error( + "Error occurred rolling back transaction", e); + } + } + } finally { + if (sess != null) { + try { + sess.close(); + } catch (Exception e) { + statusHandler.error("Error occurred closing session", e); + } + } + } + + return rval; + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.menus/.classpath b/edexOsgi/com.raytheon.uf.edex.menus/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.menus/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.menus/.project b/edexOsgi/com.raytheon.uf.edex.menus/.project new file mode 100644 index 0000000000..94e603dbc3 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.menus/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.edex.menus + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.edex.menus/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.edex.menus/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..4ce6e190d5 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.menus/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Nov 02 09:55:31 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.menus/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.menus/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..a69beddf3a --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.menus/META-INF/MANIFEST.MF @@ -0,0 +1,14 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Edex Menus +Bundle-SymbolicName: com.raytheon.uf.edex.menus +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: com.raytheon.uf.common.menus;bundle-version="1.12.1174";visibility:=reexport, + com.raytheon.uf.common.localization;bundle-version="1.12.1174", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.common.util;bundle-version="1.12.1174" +Export-Package: com.raytheon.uf.edex.menus diff --git a/edexOsgi/com.raytheon.uf.edex.menus/build.properties b/edexOsgi/com.raytheon.uf.edex.menus/build.properties new file mode 100644 index 0000000000..5791d48d5f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.menus/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ diff --git a/edexOsgi/com.raytheon.uf.edex.menus/res/spring/menus-request.xml b/edexOsgi/com.raytheon.uf.edex.menus/res/spring/menus-request.xml new file mode 100644 index 0000000000..7aeb8f380e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.menus/res/spring/menus-request.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/AbstractMenuUtil.java b/edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/AbstractMenuUtil.java similarity index 85% rename from edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/AbstractMenuUtil.java rename to edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/AbstractMenuUtil.java index d598410eb1..37507a6131 100644 --- a/edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/AbstractMenuUtil.java +++ b/edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/AbstractMenuUtil.java @@ -17,10 +17,9 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.menus; +package com.raytheon.uf.edex.menus; import java.io.File; -import java.io.IOException; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; @@ -35,10 +34,27 @@ import com.raytheon.uf.common.localization.PathManager; import com.raytheon.uf.common.localization.PathManagerFactory; import com.raytheon.uf.common.localization.exception.LocalizationException; import com.raytheon.uf.common.localization.exception.LocalizationOpFailedException; +import com.raytheon.uf.common.menus.MenuSerialization; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; +/** + * + * Abstract class for generting menu files + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 8, 2012            mschenke     Initial javadoc creation
+ * 
+ * 
+ * + * @author unknown + * @version 1.0 + */ public abstract class AbstractMenuUtil { private static final transient IUFStatusHandler statusHandler = UFStatus .getHandler(AbstractMenuUtil.class); @@ -151,35 +167,18 @@ public abstract class AbstractMenuUtil { LocalizationFile olFile = pm.getLocalizationFile(caveConfigured, "menus" + File.separator + type + File.separator + "." + type + "MenuTime"); - File ofFile = olFile.getFile(); - File ffile = lFile.getFile(); - long useTime = ffile.lastModified(); - - long writeTime = 0; - - // read the time from a file, and write the current time to a file - try { - writeTime = ofFile.lastModified(); - if (!olFile.exists()) { - File file = olFile.getFile(); - try { - file.createNewFile(); - olFile.write(new byte[0]); - } catch (IOException e) { - e.printStackTrace(); - } catch (LocalizationException e) { - e.printStackTrace(); - } - olFile.save(); - } - } catch (LocalizationOpFailedException e) { - statusHandler.handle(Priority.PROBLEM, - "Unable to save file to localization", e); - return false; - } + long useTime = lFile.getFile().lastModified(); + long writeTime = olFile.getFile().lastModified(); if (writeTime < useTime) { + try { + // Update menu creation time file + olFile.write(new byte[0]); + olFile.save(); + } catch (LocalizationException e) { + statusHandler.error("Error saving menu creation time file", e); + } return false; } else { statusHandler.info("Timestamp in " + fileName diff --git a/edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/MenuCreationHandler.java b/edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/MenuCreationHandler.java similarity index 91% rename from edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/MenuCreationHandler.java rename to edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/MenuCreationHandler.java index d0677a0d7d..b65bee0c34 100644 --- a/edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/MenuCreationHandler.java +++ b/edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/MenuCreationHandler.java @@ -17,14 +17,16 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.menus; +package com.raytheon.uf.edex.menus; +import com.raytheon.uf.common.menus.MenuCreationRequest; import com.raytheon.uf.common.serialization.comm.IRequestHandler; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; /** - * TODO Add Description + * Request handler for {@link MenuCreationRequest} objects. Uses + * {@link MenuCreationRegistry} to find object that will create the menus * *
  * 
diff --git a/edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/MenuCreationRegistry.java b/edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/MenuCreationRegistry.java
similarity index 91%
rename from edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/MenuCreationRegistry.java
rename to edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/MenuCreationRegistry.java
index 255efe9bae..f6b7982ef5 100644
--- a/edexOsgi/com.raytheon.uf.common.menus/src/com/raytheon/uf/common/menus/MenuCreationRegistry.java
+++ b/edexOsgi/com.raytheon.uf.edex.menus/src/com/raytheon/uf/edex/menus/MenuCreationRegistry.java
@@ -17,12 +17,13 @@
  * See the AWIPS II Master Rights File ("Master Rights File.pdf") for
  * further licensing information.
  **/
-package com.raytheon.uf.common.menus;
+package com.raytheon.uf.edex.menus;
 
 import com.raytheon.uf.common.util.registry.GenericRegistry;
 
 /**
- * The registry for t
+ * The registry for {@link AbstractMenuUtil} objects to register they are able
+ * to generate menus.
  * 
  * 
  * 
diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.ohd/META-INF/MANIFEST.MF
index 104fe57166..600a0e69c5 100644
--- a/edexOsgi/com.raytheon.uf.edex.ohd/META-INF/MANIFEST.MF
+++ b/edexOsgi/com.raytheon.uf.edex.ohd/META-INF/MANIFEST.MF
@@ -5,16 +5,11 @@ Bundle-SymbolicName: com.raytheon.uf.edex.ohd
 Bundle-Version: 1.12.1174.qualifier
 Bundle-Vendor: RAYTHEON
 Bundle-RequiredExecutionEnvironment: JavaSE-1.6
-Import-Package: com.raytheon.edex.db.dao,
- com.raytheon.edex.exception,
- com.raytheon.edex.plugin.grib.dao,
- com.raytheon.edex.plugin.shef,
- com.raytheon.edex.util,
+Import-Package: com.raytheon.edex.util,
  com.raytheon.uf.common.dataplugin.binlightning,
- com.raytheon.uf.common.dataplugin.grib,
+ com.raytheon.uf.common.dataplugin.grid,
  com.raytheon.uf.common.dataplugin.shef.util,
  com.raytheon.uf.common.localization,
- com.raytheon.uf.common.monitor,
  com.raytheon.uf.common.ohd,
  com.raytheon.uf.common.serialization.comm,
  com.raytheon.uf.edex.core,
@@ -30,9 +25,7 @@ Export-Package: com.raytheon.uf.edex.ohd,
 Require-Bundle: com.raytheon.edex.common,
  com.raytheon.uf.common.mpe;bundle-version="1.11.15",
  com.raytheon.uf.common.hydro;bundle-version="1.11.15",
- com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0",
- org.geotools;bundle-version="2.6.4",
- com.raytheon.edex.plugin.shef,
  javax.measure;bundle-version="1.0.0",
  com.raytheon.uf.common.status;bundle-version="1.12.1174",
- com.raytheon.uf.common.monitor
+ com.raytheon.uf.common.monitor,
+ com.raytheon.uf.common.parameter;bundle-version="1.0.0"
diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/res/spring/dpaDecoder-spring.xml b/edexOsgi/com.raytheon.uf.edex.ohd/res/spring/DPADecoder-spring.xml
similarity index 100%
rename from edexOsgi/com.raytheon.uf.edex.ohd/res/spring/dpaDecoder-spring.xml
rename to edexOsgi/com.raytheon.uf.edex.ohd/res/spring/DPADecoder-spring.xml
diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/resources/com.raytheon.uf.edex.ohd.properties b/edexOsgi/com.raytheon.uf.edex.ohd/resources/com.raytheon.uf.edex.ohd.properties
new file mode 100644
index 0000000000..3f433d22c4
--- /dev/null
+++ b/edexOsgi/com.raytheon.uf.edex.ohd/resources/com.raytheon.uf.edex.ohd.properties
@@ -0,0 +1,11 @@
+#crontab values
+logfilepurger.cron=0+1+1,5,9,13,17,21+*+*+?
+ihfsdbpurge.cron=0+45+7+*+*+?
+floodarchiver.cron=0+30+6+*+*+?
+mpehpefilepurge.cron=0+1+12+*+*+?
+mpefieldgen.cron=0+25+*+*+*+?
+pointdataretrieval.cron=0+2,17,32,47+*+*+*+?
+alarmwhfs.cron=0+7,17,27,37,47,57+*+*+*+?
+arealqpegen.cron=0+10,25,40,55+*+*+*+?
+dqcpreprocessor.cron=0+20+0,6,12,18+*+*+?
+mpelightningsrv.cron=0+0/30+*+*+*+?
diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/MainMethod.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/MainMethod.java
index 086cf95e32..f2ae88c8f4 100644
--- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/MainMethod.java
+++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/MainMethod.java
@@ -30,6 +30,7 @@ import java.util.ArrayList;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 
+import com.raytheon.uf.common.ohd.AppsDefaults;
 import com.raytheon.uf.edex.core.props.PropertiesFactory;
 
 /**
@@ -49,6 +50,7 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Oct 28, 2008            jelkins     Initial creation
+ * Oct 19, 2012  #1274     bgonzale    Set AppContext on the process builder in ctor.
  * 
* * @author jelkins @@ -57,272 +59,273 @@ import com.raytheon.uf.edex.core.props.PropertiesFactory; public class MainMethod extends Process { - protected Log log; + protected Log log; - private ProcessBuilder processBuilder; + private ProcessBuilder processBuilder; - private Process process; + private Process process; - private BufferedReader fromStdOut; + private BufferedReader fromStdOut; - private BufferedReader fromStdErr; + private BufferedReader fromStdErr; - /** - * Contains the initial command used to initialize the process. This field - * is useful to use when overriding the start method like in the RocChecker - * and RpfBatch classes. - */ - protected ArrayList initialCommand; + /** + * Contains the initial command used to initialize the process. This field + * is useful to use when overriding the start method like in the RocChecker + * and RpfBatch classes. + */ + protected ArrayList initialCommand; - /** - * Thrown when the process has not yet been started. - *

- * Make sure to call start()! - */ - public class ProcessNotStartedException extends RuntimeException { + /** + * Thrown when the process has not yet been started. + *

+ * Make sure to call start()! + */ + public class ProcessNotStartedException extends RuntimeException { - private static final long serialVersionUID = 5620316335774758460L; + private static final long serialVersionUID = 5620316335774758460L; - } + } - /** - * Run a program - * - * @param args - * The first argument in the string list _must_ be only the - * command without any arguments. The arguments to the command - * are given by proceeding elements in the argument string list. - * @return The return value of the program. - */ - public static int runProgram(String... args) { - MainMethod program = new MainMethod(new ProcessBuilder(args)); - return program.execute(); - } + /** + * Run a program + * + * @param args + * The first argument in the string list _must_ be only the + * command without any arguments. The arguments to the command + * are given by proceeding elements in the argument string list. + * @return The return value of the program. + */ + public static int runProgram(String... args) { + MainMethod program = new MainMethod(new ProcessBuilder(args)); + return program.execute(); + } - /** - * Default constructor - *

- * Constructs a main method process from the given class. - * - * @param arguments - * the string of arguments to pass to the main process - */ - public MainMethod(ProcessBuilder builder) { + /** + * Default constructor + *

+ * Constructs a main method process from the given class. + * + * @param arguments + * the string of arguments to pass to the main process + */ + public MainMethod(ProcessBuilder builder) { - this.processBuilder = builder; - this.log = LogFactory.getLog(processBuilder.getClass()); + this.processBuilder = builder; + this.log = LogFactory.getLog(processBuilder.getClass()); - try { - processBuilder.environment().put( - "apps_dir", - new File(PropertiesFactory.getInstance().getEnvProperties() - .getEnvValue("SHAREDIR") - + File.separator + "hydroapps").getCanonicalPath()); - } catch (IOException e) { - log.error("Unable to get apps_dir", e); - } + try { + processBuilder.environment().put( + "apps_dir", + new File(PropertiesFactory.getInstance().getEnvProperties() + .getEnvValue("SHAREDIR") + + File.separator + "hydroapps").getCanonicalPath()); + AppsDefaults.getInstance().setAppContext(processBuilder); + } catch (IOException e) { + log.error("Unable to get apps_dir", e); + } - this.initialCommand = new ArrayList(getProcessBuilder() - .command()); + this.initialCommand = new ArrayList(getProcessBuilder() + .command()); - } + } - /** - * Execute the method. - *

- * - * @return the exit value of the method. Usually 0 if nothing went wrong. - */ - public int execute() { - int exitValue = 0; - // Start the main method - this.start(); - try { - this.waitFor(); - } catch (InterruptedException e) { - log.error("Native process interrupted!!", e); - } finally { - exitValue = this.exitValue(); - this.closeStreams(); - this.destroy(); - } + /** + * Execute the method. + *

+ * + * @return the exit value of the method. Usually 0 if nothing went wrong. + */ + public int execute() { + int exitValue = 0; + // Start the main method + this.start(); + try { + this.waitFor(); + } catch (InterruptedException e) { + log.error("Native process interrupted!!", e); + } finally { + exitValue = this.exitValue(); + this.closeStreams(); + this.destroy(); + } - if (exitValue != 0) { - StringBuffer error = new StringBuffer(); - for (int i = 0; i < processBuilder.command().size(); i++) { - error.append(processBuilder.command().get(i)).append(" "); - } - error.append("failed with exit code "+exitValue); - log.error(error); - } + if (exitValue != 0) { + StringBuffer error = new StringBuffer(); + for (int i = 0; i < processBuilder.command().size(); i++) { + error.append(processBuilder.command().get(i)).append(" "); + } + error.append("failed with exit code " + exitValue); + log.error(error); + } - return exitValue; - } + return exitValue; + } - /** - * Get the processBuilder object of this process - *

- * - * @return the processBuilder - */ - public ProcessBuilder getProcessBuilder() { - return processBuilder; - } + /** + * Get the processBuilder object of this process + *

+ * + * @return the processBuilder + */ + public ProcessBuilder getProcessBuilder() { + return processBuilder; + } - /** - * Start the process. - *

- * Output that would normally be written to stdout and stderror are - * redirected to the log. - */ - private void start() { - try { - process = processBuilder.start(); + /** + * Start the process. + *

+ * Output that would normally be written to stdout and stderror are + * redirected to the log. + */ + private void start() { + try { + process = processBuilder.start(); - // TODO seperate the stream readers into threads + // TODO seperate the stream readers into threads - // redirect the normal output to log as info - fromStdOut = new BufferedReader(new InputStreamReader(process - .getInputStream())); - // redirect the normal error to log as error - fromStdErr = new BufferedReader(new InputStreamReader(process - .getErrorStream())); + // redirect the normal output to log as info + fromStdOut = new BufferedReader(new InputStreamReader( + process.getInputStream())); + // redirect the normal error to log as error + fromStdErr = new BufferedReader(new InputStreamReader( + process.getErrorStream())); - } catch (IOException e) { - log.error(e.getMessage(), e); - } - } + } catch (IOException e) { + log.error(e.getMessage(), e); + } + } - /** - * @param br - * @return - */ - private String read(BufferedReader br) { - StringBuffer returnString = new StringBuffer(); - String line; - try { - while ((line = br.readLine()) != null) { - returnString.append(line).append("\n"); - } - } catch (IOException e) { - log.error(e.getMessage(), e); - } - return returnString.toString(); - } + /** + * @param br + * @return + */ + private String read(BufferedReader br) { + StringBuffer returnString = new StringBuffer(); + String line; + try { + while ((line = br.readLine()) != null) { + returnString.append(line).append("\n"); + } + } catch (IOException e) { + log.error(e.getMessage(), e); + } + return returnString.toString(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Process#destroy() - */ - @Override - public void destroy() { - if (process == null) { - throw new ProcessNotStartedException(); - } - process.destroy(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Process#destroy() + */ + @Override + public void destroy() { + if (process == null) { + throw new ProcessNotStartedException(); + } + process.destroy(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Process#exitValue() - */ - @Override - public int exitValue() { - if (process == null) { - throw new ProcessNotStartedException(); - } - return process.exitValue(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Process#exitValue() + */ + @Override + public int exitValue() { + if (process == null) { + throw new ProcessNotStartedException(); + } + return process.exitValue(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Process#getErrorStream() - */ - @Override - public InputStream getErrorStream() { - if (process == null) { - throw new ProcessNotStartedException(); - } - return process.getErrorStream(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Process#getErrorStream() + */ + @Override + public InputStream getErrorStream() { + if (process == null) { + throw new ProcessNotStartedException(); + } + return process.getErrorStream(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Process#getInputStream() - */ - @Override - public InputStream getInputStream() { - if (process == null) { - throw new ProcessNotStartedException(); - } - return process.getInputStream(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Process#getInputStream() + */ + @Override + public InputStream getInputStream() { + if (process == null) { + throw new ProcessNotStartedException(); + } + return process.getInputStream(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Process#getOutputStream() - */ - @Override - public OutputStream getOutputStream() { - if (process == null) { - throw new ProcessNotStartedException(); - } - return process.getOutputStream(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Process#getOutputStream() + */ + @Override + public OutputStream getOutputStream() { + if (process == null) { + throw new ProcessNotStartedException(); + } + return process.getOutputStream(); + } - /* - * (non-Javadoc) - * - * @see java.lang.Process#waitFor() - */ - @Override - public int waitFor() throws InterruptedException { - if (process == null) { - throw new ProcessNotStartedException(); - } - int retVal = process.waitFor(); - String stdOut = read(fromStdOut); - String stdErr = read(fromStdErr); - if (!stdOut.isEmpty()) { - log.info(stdOut); - } - if (!stdErr.isEmpty()) { - log.error(stdErr); - } - return retVal; - } + /* + * (non-Javadoc) + * + * @see java.lang.Process#waitFor() + */ + @Override + public int waitFor() throws InterruptedException { + if (process == null) { + throw new ProcessNotStartedException(); + } + int retVal = process.waitFor(); + String stdOut = read(fromStdOut); + String stdErr = read(fromStdErr); + if (!stdOut.isEmpty()) { + log.info(stdOut); + } + if (!stdErr.isEmpty()) { + log.error(stdErr); + } + return retVal; + } - public void closeStreams() { - try { - if (this.getInputStream() != null) { - this.getInputStream().close(); - } - } catch (IOException e) { - log.error("Unable to close input stream! Resource leak possible.", - e); - } - try { - if (this.getOutputStream() != null) { - this.getOutputStream().close(); - } - } catch (IOException e) { - log.error("Unable to close output stream! Resource leak possible", - e); - } + public void closeStreams() { + try { + if (this.getInputStream() != null) { + this.getInputStream().close(); + } + } catch (IOException e) { + log.error("Unable to close input stream! Resource leak possible.", + e); + } + try { + if (this.getOutputStream() != null) { + this.getOutputStream().close(); + } + } catch (IOException e) { + log.error("Unable to close output stream! Resource leak possible", + e); + } - try { - if (this.getErrorStream() != null) { - this.getErrorStream().close(); - } - } catch (IOException e) { - log.error("Unable to close error stream! Resource leadk possible", - e); - } - } + try { + if (this.getErrorStream() != null) { + this.getErrorStream().close(); + } + } catch (IOException e) { + log.error("Unable to close error stream! Resource leadk possible", + e); + } + } } diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/ArealQpeGenSrv.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/ArealQpeGenSrv.java index 25130efb98..a6411a4ec1 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/ArealQpeGenSrv.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/ArealQpeGenSrv.java @@ -27,6 +27,7 @@ import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.TimeZone; @@ -35,9 +36,9 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opengis.metadata.spatial.PixelOrientation; -import com.raytheon.edex.plugin.grib.dao.GribDao; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.IDataStore; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; @@ -50,9 +51,12 @@ import com.raytheon.uf.common.mpe.util.XmrgFile; import com.raytheon.uf.common.mpe.util.XmrgFile.XmrgHeader; import com.raytheon.uf.common.ohd.AppsDefaults; import com.raytheon.uf.common.util.FileUtil; +import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.dao.CoreDao; import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.plugin.PluginDao; import com.raytheon.uf.edex.database.plugin.PluginFactory; +import com.raytheon.uf.edex.database.query.DatabaseQuery; import com.raytheon.uf.edex.ohd.MainMethod; import com.vividsolutions.jts.geom.Coordinate; @@ -256,128 +260,134 @@ public class ArealQpeGenSrv { // gribit environment vars Map envVars = new HashMap(); - envVars.put("grib_in_dir", gaq_temp_xmrg_dir); - envVars.put("grib_out_dir", gaq_temp_xmrg_dir); - envVars.put("grib_set_subcenter_0", "on"); + if (AppsDefaults.getInstance().setAppContext(this)) { + envVars.put("grib_in_dir", gaq_temp_xmrg_dir); + envVars.put("grib_out_dir", gaq_temp_xmrg_dir); + envVars.put("grib_set_subcenter_0", "on"); - String pproc_bin = appsDefaults.getToken("pproc_bin"); - MainMethod m = new MainMethod(new ProcessBuilder(pproc_bin + "/" - + GRIBIT)); + String pproc_bin = appsDefaults.getToken("pproc_bin"); + MainMethod m = new MainMethod(new ProcessBuilder(pproc_bin + + "/" + GRIBIT)); - for (File fr : fa) { - String inFile = ""; - String gribOutFile = ""; - inFile = fr.getName(); - gribOutFile = inFile + ".grib"; - envVars.put("grib_in_file", inFile); - envVars.put("grib_out_file", gribOutFile); - if (envVars != null) { - m.getProcessBuilder().environment().putAll(envVars); - } - int exitValue = m.execute(); + for (File fr : fa) { + String inFile = ""; + String gribOutFile = ""; + inFile = fr.getName(); + gribOutFile = inFile + ".grib"; + envVars.put("grib_in_file", inFile); + envVars.put("grib_out_file", gribOutFile); + if (envVars != null) { + m.getProcessBuilder().environment().putAll(envVars); + } + int exitValue = m.execute(); - // Output result - if (exitValue == 0) { - log.info("Areal QPE wrote output grib file: " + gribOutFile); - } else { - log.error("Areal QPE grib file out process terminated with exit code: " - + exitValue); - return; - } + // Output result + if (exitValue == 0) { + log.info("Areal QPE wrote output grib file: " + + gribOutFile); + } else { + log.error("Areal QPE grib file out process terminated with exit code: " + + exitValue); + return; + } - try { - RandomAccessFile raf = new RandomAccessFile(new File( - fr.getParentFile(), gribOutFile), "rw"); - raf.seek(0); + try { + RandomAccessFile raf = new RandomAccessFile(new File( + fr.getParentFile(), gribOutFile), "rw"); + raf.seek(0); - int idx = 0; - byte b = raf.readByte(); + int idx = 0; + byte b = raf.readByte(); - boolean found = false; - while (!found) { - if (b == (byte) 'G') { - b = raf.readByte(); - if (b == (byte) 'R') { + boolean found = false; + while (!found) { + if (b == (byte) 'G') { b = raf.readByte(); - if (b == (byte) 'I') { + if (b == (byte) 'R') { b = raf.readByte(); - if (b == (byte) 'B') { - found = true; + if (b == (byte) 'I') { + b = raf.readByte(); + if (b == (byte) 'B') { + found = true; + } else { + idx += 3; + } } else { - idx += 3; + idx += 2; } } else { - idx += 2; + idx += 1; } } else { idx += 1; + b = raf.readByte(); } - } else { - idx += 1; - b = raf.readByte(); + } + + // Index 8 bytes for Section 0 of grib spec, and 5 bytes + // for + // Section 1 of grib spec to get to gen process id index + idx += (8 + 5); + + // Increment gen process id + raf.seek(idx); + byte gpid = raf.readByte(); + raf.seek(idx); + raf.writeByte(gpid + 1); + + raf.close(); + } catch (Exception e) { + log.error("Error modifying grib output file", e); + return; + } + + String newFname = fr.getName() + ".grib"; + File mvFile = new File(gaq_grib_dir + "/" + newFname); + File goFile = new File(gaq_temp_xmrg_dir + "/" + + gribOutFile); + Date dt = new Date(); + Calendar cc = Calendar.getInstance(TimeZone + .getTimeZone("GMT")); + cc.setTime(dt); + SimpleDateFormat ffn = new SimpleDateFormat("ddHHmmss"); + String dString = ffn.format(cc.getTime()); + File gribIngestFile = new File(d2d_input_dir + + File.separator + "arealQpeGenSrv" + + File.separator + fr.getName() + "_" + dString + + ".grib"); + log.info("Move and rename grib file " + goFile + " to " + + mvFile); + boolean fmv = goFile.renameTo(mvFile); + + // The move failed. Remove the grib file. + if (fmv == false) { + log.error("Move and rename grib file " + goFile + + " to " + mvFile + " failed. "); + goFile.delete(); + } else { + try { + FileUtil.copyFile(mvFile, gribIngestFile); + log.info("Copied grib file " + mvFile.getName() + + " to " + d2d_input_dir + File.separator + + "arealQpeGenSrv" + " for ingest to D2D. "); + } catch (IOException e) { + log.error("Copy grib file " + mvFile.getName() + + " to " + d2d_input_dir + File.separator + + "arealQpeGenSrv" + " failed. "); + e.printStackTrace(); } } - - // Index 8 bytes for Section 0 of grib spec, and 5 bytes for - // Section 1 of grib spec to get to gen process id index - idx += (8 + 5); - - // Increment gen process id - raf.seek(idx); - byte gpid = raf.readByte(); - raf.seek(idx); - raf.writeByte(gpid + 1); - - raf.close(); - } catch (Exception e) { - log.error("Error modifying grib output file", e); - return; - } - - String newFname = fr.getName() + ".grib"; - File mvFile = new File(gaq_grib_dir + "/" + newFname); - File goFile = new File(gaq_temp_xmrg_dir + "/" + gribOutFile); - Date dt = new Date(); - Calendar cc = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - cc.setTime(dt); - SimpleDateFormat ffn = new SimpleDateFormat("ddHHmmss"); - String dString = ffn.format(cc.getTime()); - File gribIngestFile = new File(d2d_input_dir + File.separator + - "arealQpeGenSrv" + File.separator - + fr.getName() + "_" + dString + ".grib"); - log.info("Move and rename grib file " + goFile + " to " - + mvFile); - boolean fmv = goFile.renameTo(mvFile); - - // The move failed. Remove the grib file. - if (fmv == false) { - log.error("Move and rename grib file " + goFile + " to " - + mvFile + " failed. "); - goFile.delete(); - } else { - try { - FileUtil.copyFile(mvFile, gribIngestFile); - log.info("Copied grib file " + mvFile.getName() - + " to " + d2d_input_dir + File.separator + - "arealQpeGenSrv" - + " for ingest to D2D. "); - } catch (IOException e) { - log.error("Copy grib file " + mvFile.getName() + " to " - + d2d_input_dir + File.separator + - "arealQpeGenSrv" + " failed. "); - e.printStackTrace(); + // Remove the xmrg file from the temp directory. + fr.delete(); + if (log.isDebugEnabled()) { + log.debug("Removed file " + fr + + " from rfcqpe_temp directory."); } + mvFile = null; + goFile = null; } - // Remove the xmrg file from the temp directory. - fr.delete(); - if (log.isDebugEnabled()) { - log.debug("Removed file " + fr - + " from rfcqpe_temp directory."); - } - mvFile = null; - goFile = null; + m = null; } - m = null; } else { log.info("No QPE mosaic files found in " + gaq_temp_xmrg_dir); Date dt = new Date(); @@ -585,24 +595,26 @@ public class ArealQpeGenSrv { * @param today * Today's date in database string format * @return The database uri, or null if no data + * @throws DataAccessLayerException */ - private String getDataURI(String rfc, String duration, String today) { + private String getDataURI(String rfc, String duration, String today) + throws DataAccessLayerException { String uri = null; // Query for uri - String sql = "select datauri from grib where modelinfo_id = (select id from grib_models where modelname = " - + "'QPE-" - + rfc - + "' and " - + "parameterabbreviation like 'QPE" - + duration + "%') " + "and rangeend = '" + today + "'"; + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addReturnedField("dataURI"); + query.addQueryParam(GridConstants.DATASET_ID, "QPE-" + rfc); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "QPE" + + duration + "%", "like"); + query.addQueryParam("dataTime.validPeriod.end", today); + CoreDao dao = null; dao = new CoreDao(DaoConfig.forDatabase("metadata")); - - Object[] rs = dao.executeSQLQuery(sql); - if ((rs != null) && (rs.length > 0)) { - if ((rs[0] != null) && (rs[0] instanceof String)) { - uri = (String) rs[0]; + List rs = dao.queryByCriteria(query); + if ((rs != null) && (!rs.isEmpty())) { + if ((rs.get(0) != null) && (rs.get(0) instanceof String)) { + uri = (String) rs.get(0); } } else { uri = null; @@ -648,12 +660,11 @@ public class ArealQpeGenSrv { return false; } - GribRecord gr = new GribRecord(uri); - GribDao gd = null; + GridRecord gr = new GridRecord(uri); + PluginDao gd = null; - gd = (GribDao) PluginFactory.getInstance().getPluginDao( - gr.getPluginName()); - gr = (GribRecord) gd.getMetadata(uri); + gd = PluginFactory.getInstance().getPluginDao(gr.getPluginName()); + gr = (GridRecord) gd.getMetadata(uri); grReftime = gr.getDataTime().getRefTime(); dataStore = gd.getDataStore(gr); diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/DqcPreProcSrv.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/DqcPreProcSrv.java index 3aedbb5fbe..e5fa02e3f3 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/DqcPreProcSrv.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/DqcPreProcSrv.java @@ -59,26 +59,28 @@ public class DqcPreProcSrv { } int exitValue = 0; - if (dqcArg.matches(DAYS_ARG)) { - logger.info("Executing DQC Preprocessor with argument: " + dqcArg); - exitValue = MainMethod.runProgram("ksh", appsDefaults - .getToken("pproc_bin") - + "/run_dqc_preprocessor", "-d" + dqcArg); - } else if (DAYS_ARG == null) { - logger - .info("Executing DQC Preprocessor with default number of days: " - + defaultNumDays); - exitValue = MainMethod.runProgram("ksh", appsDefaults - .getToken("pproc_bin") - + "/run_dqc_preprocessor", "-d" + defaultNumDays); - } + if (AppsDefaults.getInstance().setAppContext(this)) { + if (dqcArg.matches(DAYS_ARG)) { + logger.info("Executing DQC Preprocessor with argument: " + + dqcArg); + exitValue = MainMethod.runProgram("ksh", + appsDefaults.getToken("pproc_bin") + + "/run_dqc_preprocessor", "-d" + dqcArg); + } else if (DAYS_ARG == null) { + logger.info("Executing DQC Preprocessor with default number of days: " + + defaultNumDays); + exitValue = MainMethod.runProgram("ksh", + appsDefaults.getToken("pproc_bin") + + "/run_dqc_preprocessor", "-d" + + defaultNumDays); + } - if (exitValue == 0) { - logger.info("DQC Preprocessor execution successful"); - } else { - logger - .error("DQC Preprocessor terminated abnormally with exit code: " - + exitValue); + if (exitValue == 0) { + logger.info("DQC Preprocessor execution successful"); + } else { + logger.error("DQC Preprocessor terminated abnormally with exit code: " + + exitValue); + } } return exitValue; } diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFF.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFF.java index 4bcb69c6f1..ea9725a6e2 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFF.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFF.java @@ -32,9 +32,8 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opengis.metadata.spatial.PixelOrientation; -import com.raytheon.edex.plugin.grib.dao.GribDao; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.IDataStore; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; @@ -47,6 +46,7 @@ import com.raytheon.uf.common.mpe.util.XmrgFile; import com.raytheon.uf.common.mpe.util.XmrgFile.XmrgHeader; import com.raytheon.uf.common.ohd.AppsDefaults; import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.edex.database.plugin.PluginDao; import com.raytheon.uf.edex.database.plugin.PluginFactory; import com.vividsolutions.jts.geom.Coordinate; @@ -226,23 +226,22 @@ public class GAFF { this.hsa = db.getHsa(); } - - public boolean shouldGAFFRun() - { - // Only run every 12 minutes - final int minutesBetweenRuns = 12; - - Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - if (cal.getTimeInMillis() - this.lastRunTime < minutesBetweenRuns * 60 * 1000) { - if (log.isDebugEnabled()) { - float time = (cal.getTimeInMillis() - this.lastRunTime) / 1000 / 60; + + public boolean shouldGAFFRun() { + // Only run every 12 minutes + final int minutesBetweenRuns = 12; + + Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + if (cal.getTimeInMillis() - this.lastRunTime < minutesBetweenRuns * 60 * 1000) { + if (log.isDebugEnabled()) { + float time = (cal.getTimeInMillis() - this.lastRunTime) / 1000 / 60; log.debug("Only run every 12 minutes. " + time - + " minutes since last run."); - } - return false; - } - - return true; + + " minutes since last run."); + } + return false; + } + + return true; } public void process() { @@ -348,12 +347,12 @@ public class GAFF { continue; } - GribRecord gr = new GribRecord(uri); - GribDao gd = null; + GridRecord gr = new GridRecord(uri); + PluginDao gd = null; - gd = (GribDao) PluginFactory.getInstance().getPluginDao( + gd = PluginFactory.getInstance().getPluginDao( gr.getPluginName()); - gr = (GribRecord) gd.getMetadata(uri); + gr = (GridRecord) gd.getMetadata(uri); grReftime = gr.getDataTime().getRefTime(); dataStore = gd.getDataStore(gr); diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFFDB.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFFDB.java index 8e5a9240ee..568917e710 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFFDB.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/GAFFDB.java @@ -23,14 +23,18 @@ import java.math.BigInteger; import java.sql.Timestamp; import java.text.SimpleDateFormat; import java.util.Calendar; +import java.util.List; import java.util.TimeZone; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.edex.database.DataAccessLayerException; import com.raytheon.uf.edex.database.dao.CoreDao; import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.query.DatabaseQuery; /** * GAFF Database access class. @@ -55,10 +59,10 @@ public class GAFFDB { private static final int DEFAULT_QC_VALUE = 1879048191; private static final String GEOAREA_QUERY = "select area_id from GeoArea where " - + "boundary_type = 'BASIN' AND area_id IN (SELECT area_id FROM linesegs)"; + + "boundary_type = 'BASIN' AND area_id IN (SELECT area_id FROM linesegs)"; private static final String LINESEGS_QUERY = "select hrap_row, hrap_beg_col, " - + "hrap_end_col, area from linesegs"; + + "hrap_end_col, area from linesegs"; private Log log = LogFactory.getLog("GenArealFFG"); @@ -159,22 +163,27 @@ public class GAFFDB { * @param today * Today's date in database string format * @return The database uri, or null if no data + * @throws DataAccessLayerException */ - public String getDataURI(String rfc, String duration, String today) { + public String getDataURI(String rfc, String duration, String today) + throws DataAccessLayerException { String uri = null; // Query for uri - String sql = "select datauri from grib where modelinfo_id in " - + "(select id from grib_models where modelname = " + "'FFG-" - + rfc + "' and " + "parameterabbreviation = 'FFG" + duration - + "24hr') " + "and reftime >= '" + today - + "' order by gridversion desc"; + DatabaseQuery query = new DatabaseQuery(GridRecord.class); + query.addReturnedField("dataURI"); + query.addQueryParam(GridConstants.DATASET_ID, "FFG-" + rfc); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "FFG" + + duration + "24hr"); + query.addQueryParam("dataTime.refTime", today, ">="); + query.addOrder(GridConstants.SECONDARY_ID, false); + CoreDao dao = null; dao = new CoreDao(DaoConfig.forDatabase("metadata")); - Object[] rs = dao.executeSQLQuery(sql); - if ((rs != null) && (rs.length > 0)) { - if ((rs[0] != null) && (rs[0] instanceof String)) { - uri = (String) rs[0]; + List rs = dao.queryByCriteria(query); + if ((rs != null) && (!rs.isEmpty())) { + if ((rs.get(0) != null) && (rs.get(0) instanceof String)) { + uri = (String) rs.get(0); } } else { uri = null; @@ -313,12 +322,12 @@ public class GAFFDB { return rs; } - + public Object[] getLineSegs(String areaId) { CoreDao dao = null; dao = new CoreDao(DaoConfig.forDatabase(IHFS)); - Object[] rs = dao.executeSQLQuery(LINESEGS_QUERY - + " where area_Id = '" + areaId + "'"); + Object[] rs = dao.executeSQLQuery(LINESEGS_QUERY + " where area_Id = '" + + areaId + "'"); return rs; } diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeFieldGenSrv.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeFieldGenSrv.java index 65c009a570..6271e6e0d4 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeFieldGenSrv.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeFieldGenSrv.java @@ -68,21 +68,23 @@ public class MpeFieldGenSrv { } int exitValue = 0; - if (mpeArg.matches(HOURS_ARG)) { - logger.info("Executing MPE FieldGen with argument: " + mpeArg); - exitValue = MainMethod.runProgram("ksh", appsDefaults - .getToken("pproc_bin") - + "/run_mpe_fieldgen", mpeArg); - } else if (mpeArg.matches(HOURS_DATE_ARG)) { - logger.info("Executing MPE FieldGen with arguments: " + mpeArg); - Matcher matcher = HOURS_DATE_PATTERN.matcher(mpeArg); - if (matcher.find()) { - exitValue = MainMethod.runProgram("ksh", appsDefaults - .getToken("pproc_bin") - + "/run_mpe_fieldgen", matcher.group(1), matcher - .group(2), matcher.group(3)); - } + if (appsDefaults.setAppContext(this)) { + if (mpeArg.matches(HOURS_ARG)) { + logger.info("Executing MPE FieldGen with argument: " + mpeArg); + exitValue = MainMethod.runProgram("ksh", + appsDefaults.getToken("pproc_bin") + + "/run_mpe_fieldgen", mpeArg); + } else if (mpeArg.matches(HOURS_DATE_ARG)) { + logger.info("Executing MPE FieldGen with arguments: " + mpeArg); + Matcher matcher = HOURS_DATE_PATTERN.matcher(mpeArg); + if (matcher.find()) { + exitValue = MainMethod.runProgram("ksh", + appsDefaults.getToken("pproc_bin") + + "/run_mpe_fieldgen", matcher.group(1), + matcher.group(2), matcher.group(3)); + } + } } if (exitValue == 0) { diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeRUCFreezingLevel.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeRUCFreezingLevel.java index 4fea49cc5b..446538c0c2 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeRUCFreezingLevel.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/MpeRUCFreezingLevel.java @@ -93,16 +93,24 @@ public class MpeRUCFreezingLevel { public static String[] models = new String[] { "RUC236" }; public MpeRUCFreezingLevel() { - File directory = new File(stationFilePath); + try { + File directory = new File(stationFilePath); - if (directory != null) { - for (File file : directory.listFiles()) { - if (file.isFile() - && file.getName().contains("freezing_station_list")) { - this.stationFile = file; - break; + if (directory != null) { + for (File file : directory.listFiles()) { + if (file != null) { + if (file.isFile() + && file.getName().contains( + "freezing_station_list")) { + this.stationFile = file; + break; + } + } } } + } catch (Exception e) { + statusHandler + .handle(Priority.WARN, "No mpe_station_list_dir found"); } // correct env vairiable dqcPreprocessorBasetime if needed @@ -325,6 +333,10 @@ public class MpeRUCFreezingLevel { * Process the MPE freezing Levels */ public void processMpeRuc() { + if (!AppsDefaults.getInstance().setAppContext(this)) { + return; + } + Integer forecastHour = null; HashMap> freezingTimeMap = new HashMap>(); LinkedHashMap freezingStations = new LinkedHashMap(); diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/PprocSrv.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/PprocSrv.java index 66e338eef7..454e56199a 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/PprocSrv.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/PprocSrv.java @@ -60,10 +60,12 @@ public class PprocSrv implements ServiceInterface { @Override public void execute() throws EdexException { - for (String script : serviceScripts) { - ScriptService s = new ScriptService(scriptDir + File.separatorChar - + script); - s.execute(); + if (AppsDefaults.getInstance().setAppContext(this)) { + for (String script : serviceScripts) { + ScriptService s = new ScriptService(scriptDir + + File.separatorChar + script); + s.execute(); + } } } } diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPreURIFilter.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPreURIFilter.java index 6964c3d318..6961980e11 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPreURIFilter.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPreURIFilter.java @@ -55,7 +55,7 @@ public class SatPreURIFilter { if (message instanceof DataURINotificationMessage) { String uri = ""; for (String data : message.getDataURIs()) { - if (data.startsWith("/grib")) { + if (data.startsWith("/grid")) { if (data.contains(AUTOSPE)) { uri = data; break; diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPrecipFileBuilder.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPrecipFileBuilder.java index 64405df1c9..530e3f6c9e 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPrecipFileBuilder.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/pproc/SatPrecipFileBuilder.java @@ -31,10 +31,9 @@ import javax.measure.converter.UnitConverter; import javax.measure.unit.SI; import javax.measure.unit.Unit; -import com.raytheon.edex.plugin.grib.dao.GribDao; import com.raytheon.edex.util.UnitConv; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.IDataStore; import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; @@ -45,6 +44,7 @@ import com.raytheon.uf.common.hydro.spatial.HRAPCoordinates; import com.raytheon.uf.common.mpe.util.XmrgFile; import com.raytheon.uf.common.mpe.util.XmrgFile.XmrgHeader; import com.raytheon.uf.common.ohd.AppsDefaults; +import com.raytheon.uf.edex.database.plugin.PluginDao; import com.raytheon.uf.edex.database.plugin.PluginFactory; /** @@ -69,7 +69,7 @@ public class SatPrecipFileBuilder { XmrgFile xmfile = null; - GribRecord gr = null; + GridRecord gr = null; private IDataRecord dataRec; @@ -117,14 +117,14 @@ public class SatPrecipFileBuilder { public void createSatPre() { try { - getGribRecord(); + getGridRecord(); } catch (PluginException e) { e.printStackTrace(); } float[] fa = null; fa = new float[((float[]) gr.getMessageData()).length]; fa = (float[]) gr.getMessageData(); - String gribUnit = gr.getModelInfo().getParameterUnit(); + String gribUnit = gr.getParameter().getUnitString(); UnitConverter cv = null; Unit gi = Unit.ONE; try { @@ -187,7 +187,7 @@ public class SatPrecipFileBuilder { * @param uri * @return */ - public void getGribRecord() throws PluginException { + public void getGridRecord() throws PluginException { try { extent = HRAPCoordinates.getHRAPCoordinates(); } catch (Exception e) { @@ -206,10 +206,10 @@ public class SatPrecipFileBuilder { int[] minIndex = { minX, minY }; int[] maxIndex = { minX + width, minY + height }; - gr = new GribRecord(uri); - GribDao gd = (GribDao) PluginFactory.getInstance().getPluginDao( + gr = new GridRecord(uri); + PluginDao gd = PluginFactory.getInstance().getPluginDao( gr.getPluginName()); - gr = (GribRecord) gd.getMetadata(uri); + gr = (GridRecord) gd.getMetadata(uri); IDataStore dataStore = gd.getDataStore(gr); try { diff --git a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/whfs/WhfsSrv.java b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/whfs/WhfsSrv.java index d23746a7b6..c3532dd917 100644 --- a/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/whfs/WhfsSrv.java +++ b/edexOsgi/com.raytheon.uf.edex.ohd/src/com/raytheon/uf/edex/ohd/whfs/WhfsSrv.java @@ -59,11 +59,13 @@ public class WhfsSrv implements ServiceInterface { */ @Override public void execute() throws EdexException { - for (String script : serviceScripts) { ScriptService s = new ScriptService(scriptDir + File.separatorChar + script); - s.execute(); + + if (AppsDefaults.getInstance().setAppContext(this)) { + s.execute(); + } } } } diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/.classpath b/edexOsgi/com.raytheon.uf.edex.parameter/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/.project b/edexOsgi/com.raytheon.uf.edex.parameter/.project new file mode 100644 index 0000000000..42c5e94499 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.edex.parameter + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.edex.parameter/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..17226f0555 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Tue Jan 31 13:38:02 CST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.parameter/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..b15a531746 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/META-INF/MANIFEST.MF @@ -0,0 +1,25 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Parameter +Bundle-SymbolicName: com.raytheon.uf.edex.parameter +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Import-Package: com.raytheon.edex.db.dao, + com.raytheon.uf.common.dataplugin, + com.raytheon.uf.common.datastorage, + com.raytheon.uf.common.serialization.comm, + com.raytheon.uf.common.status, + com.raytheon.uf.edex.core, + com.raytheon.uf.edex.database, + com.raytheon.uf.edex.database.dao, + com.raytheon.uf.edex.database.plugin, + javax.measure.unit, + org.apache.commons.logging, + org.hibernate, + org.hibernate.criterion, + org.springframework.dao.support, + org.springframework.orm.hibernate3.support +Export-Package: com.raytheon.uf.edex.parameter +Require-Bundle: com.raytheon.uf.common.parameter;bundle-version="1.0.0", + com.raytheon.uf.common.serialization;bundle-version="1.12.1174" diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/build.properties b/edexOsgi/com.raytheon.uf.edex.parameter/build.properties new file mode 100644 index 0000000000..b48786a04c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ +src.includes = res/ diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/res/spring/parameter-common.xml b/edexOsgi/com.raytheon.uf.edex.parameter/res/spring/parameter-common.xml new file mode 100644 index 0000000000..5792beebc3 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/res/spring/parameter-common.xml @@ -0,0 +1,27 @@ + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.parameter/src/com/raytheon/uf/edex/parameter/GetParameterHandler.java b/edexOsgi/com.raytheon.uf.edex.parameter/src/com/raytheon/uf/edex/parameter/GetParameterHandler.java new file mode 100644 index 0000000000..77810b11f4 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.parameter/src/com/raytheon/uf/edex/parameter/GetParameterHandler.java @@ -0,0 +1,128 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.parameter; + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.criterion.Criterion; +import org.hibernate.criterion.Restrictions; + +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.parameter.request.GetParameterRequest; +import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; + +/** + * + * Cache the parameters defined in the database to avoid repeated lookups. + * + *

+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 7, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class GetParameterHandler implements + IRequestHandler { + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(GetParameterHandler.class); + + private final CoreDao dao; + + public GetParameterHandler() { + dao = new CoreDao(DaoConfig.forClass(Parameter.class)); + } + + private Parameter checkDatabase(Parameter parameter, boolean create) { + Parameter rval = null; + + Session sess = null; + Transaction trans = null; + for (int tries = 0; tries < 2 && rval == null; tries++) { + // If this fails the most likely cause is that another node in the + // cluster is trying to insert at the same time. Trying again will + // work without errors, if it turns out this was a real problem then + // the second try will catch it and log it. + try { + sess = dao.getSessionFactory().openSession(); + trans = sess.beginTransaction(); + + Criteria crit = sess.createCriteria(Parameter.class); + + Criterion nameCrit = Restrictions.eq("abbreviation", + parameter.getAbbreviation()); + crit.add(nameCrit); + List vals = crit.list(); + + if (vals.size() > 0) { + rval = (Parameter) vals.get(0); + } else if (create) { + sess.saveOrUpdate(parameter); + rval = parameter; + } + + trans.commit(); + } catch (Exception e) { + if (tries > 0) { + // Don't log errors on the first try. + statusHandler.error("Error occurred looking up Parameter[" + + parameter.getAbbreviation() + "]", e); + } + if (trans != null) { + try { + trans.rollback(); + } catch (Exception e1) { + statusHandler.error( + "Error occurred rolling back transaction", e); + } + } + } finally { + if (sess != null) { + try { + sess.close(); + } catch (Exception e) { + statusHandler + .error("Error occurred closing session", e); + } + } + } + } + + return rval; + } + + @Override + public Parameter handleRequest(GetParameterRequest request) { + return checkDatabase(request.getParameter(), request.getCreate()); + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.acars/src/com/raytheon/uf/edex/plugin/acars/dao/ACARSDao.java b/edexOsgi/com.raytheon.uf.edex.plugin.acars/src/com/raytheon/uf/edex/plugin/acars/dao/ACARSDao.java index 4e0099d432..3e81fd1a43 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.acars/src/com/raytheon/uf/edex/plugin/acars/dao/ACARSDao.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.acars/src/com/raytheon/uf/edex/plugin/acars/dao/ACARSDao.java @@ -29,12 +29,12 @@ import org.springframework.transaction.support.TransactionCallback; import com.raytheon.edex.db.dao.DefaultPluginDao; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.acars.ACARSRecord; +import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.edex.database.DataAccessLayerException; /** - * TODO Add Description + * ACARDS dao. * *
  * 
@@ -42,6 +42,8 @@ import com.raytheon.uf.edex.database.DataAccessLayerException;
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
  * Jan 21, 2009       1939 jkorman     Initial creation
+ * Oct 10, 2012 1261       djohnson    Add some generics wildcarding.
+ * Nov 02, 2012 1302       djohnson    Add Javadoc.
  * 
  * 
* @@ -51,11 +53,6 @@ import com.raytheon.uf.edex.database.DataAccessLayerException; public class ACARSDao extends DefaultPluginDao { - /** - * The cache region to store query - */ - private final String QUERY_CACHE_REGION = "Queries"; - /** * Creates a new ReccoDao * @@ -103,10 +100,11 @@ public class ACARSDao extends DefaultPluginDao { List retData = null; - List results = super.queryByExample(example); + @SuppressWarnings("unchecked") + List> results = super.queryByExample(example); if (results != null) { retData = new ArrayList(); - for (PersistableDataObject d : results) { + for (PersistableDataObject d : results) { retData.add((ACARSRecord) d); } } @@ -125,6 +123,7 @@ public class ACARSDao extends DefaultPluginDao { List result = (List) txTemplate .execute(new TransactionCallback() { + @Override public List doInTransaction(TransactionStatus status) { Query hibQuery = getSession(false) .createQuery(hqlQuery); diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/component-deploy.xml b/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/component-deploy.xml deleted file mode 100644 index dcf9730239..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/component-deploy.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acars-sounding-plugin.xml b/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acars-sounding-plugin.xml deleted file mode 100644 index 6d13b53ce2..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acars-sounding-plugin.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - - - - - - - - - - - - - - - \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/res/spring/acarssounding-common.xml b/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acarssounding-common.xml similarity index 100% rename from edexOsgi/com.raytheon.uf.common.dataplugin.acarssounding/res/spring/acarssounding-common.xml rename to edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acarssounding-common.xml diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acarssounding-ingest.xml b/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acarssounding-ingest.xml index 67834c612d..74d5ea4bb9 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acarssounding-ingest.xml +++ b/edexOsgi/com.raytheon.uf.edex.plugin.acarssounding/res/spring/acarssounding-ingest.xml @@ -6,6 +6,10 @@ + + + + @@ -15,7 +19,7 @@ - @@ -63,5 +67,9 @@ + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.cwat/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.cwat/META-INF/MANIFEST.MF index e817351e35..41e7e5454a 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.cwat/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.plugin.cwat/META-INF/MANIFEST.MF @@ -5,12 +5,9 @@ Bundle-SymbolicName: com.raytheon.uf.edex.plugin.cwat Bundle-Version: 1.12.1174.qualifier Bundle-Vendor: RAYTHEON Eclipse-RegisterBuddy: com.raytheon.edex.common, com.raytheon.uf.common.serialization, com.raytheon.uf.viz.core -Require-Bundle: org.eclipse.ui, - org.eclipse.core.runtime, - com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.7";resolution:=optional, +Require-Bundle: com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.7";resolution:=optional, com.raytheon.edex.common;bundle-version="1.11.7", com.raytheon.uf.common.monitor;bundle-version="1.11.7", - org.geotools;bundle-version="2.5.2", org.apache.commons.collections, org.apache.commons.logging;bundle-version="1.0.4", com.raytheon.uf.common.dataplugin.cwat;bundle-version="1.0.0", @@ -18,11 +15,10 @@ Require-Bundle: org.eclipse.ui, com.raytheon.uf.common.monitor.cpg;bundle-version="1.0.0", com.raytheon.uf.common.status;bundle-version="1.12.1152", com.raytheon.uf.common.localization, - com.raytheon.uf.common.comm, com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", com.raytheon.uf.common.dataplugin.scan;bundle-version="1.12.1174", com.raytheon.uf.common.sounding;bundle-version="1.12.1174", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.12.1174", + com.raytheon.uf.common.dataplugin.grid, com.raytheon.uf.edex.plugin.scan;bundle-version="1.12.1174", com.raytheon.uf.edex.dat.utils;bundle-version="1.12.1174" Bundle-RequiredExecutionEnvironment: JavaSE-1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/CWAThreat.java b/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/CWAThreat.java index cbb4ce4df5..d8038c7110 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/CWAThreat.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/CWAThreat.java @@ -31,7 +31,7 @@ import org.opengis.referencing.datum.PixelInCell; import org.opengis.referencing.operation.TransformException; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.radar.RadarRecord; import com.raytheon.uf.common.dataplugin.radar.util.RadarConstants; import com.raytheon.uf.common.dataplugin.radar.util.RadarConstants.MapValues; @@ -1074,7 +1074,7 @@ public class CWAThreat { * @param rec * @return */ - private Coordinate getGridCoordinate(Coordinate coor, GribRecord rec) { + private Coordinate getGridCoordinate(Coordinate coor, GridRecord rec) { Coordinate latLonCoor = null; ReferencedCoordinate rcoor = new ReferencedCoordinate(coor, diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/common/CWATConfig.java b/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/common/CWATConfig.java index 972b802e62..b93edcfbfd 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/common/CWATConfig.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.cwat/src/com/raytheon/uf/edex/plugin/cwat/common/CWATConfig.java @@ -29,7 +29,7 @@ import org.opengis.referencing.crs.ProjectedCRS; import com.raytheon.edex.urifilter.URIGenerateMessage; import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.radar.RadarRecord; import com.raytheon.uf.common.dataplugin.radar.RadarStation; import com.raytheon.uf.common.dataplugin.radar.util.RadarConstants.GraphicBlockValues; @@ -123,13 +123,13 @@ public class CWATConfig { public static final int dimensions = 2; /** wind speed u 700 mb **/ - public GribRecord u700 = null; + public GridRecord u700 = null; /** wind speed v 700 mb **/ - public GribRecord v700 = null; + public GridRecord v700 = null; /** U wind at 500 mb **/ - public GribRecord u500 = null; + public GridRecord u500 = null; public VerticalSounding vs = null; @@ -462,23 +462,23 @@ public class CWATConfig { } } - public GribRecord getU700() { + public GridRecord getU700() { return u700; } - public GribRecord getV700() { + public GridRecord getV700() { return v700; } - public void setU700(GribRecord u700) { + public void setU700(GridRecord u700) { this.u700 = u700; } - public void setV700(GribRecord v700) { + public void setV700(GridRecord v700) { this.v700 = v700; } - public GribRecord getU500() { + public GridRecord getU500() { return u500; } @@ -563,15 +563,15 @@ public class CWATConfig { // check back for a couple hours int interval = 1440; - u700 = DATUtils.getMostRecentGribRecord(interval, + u700 = DATUtils.getMostRecentGridRecord(interval, U700Product.getSQL(interval, U700Product.U700), param700U); - v700 = DATUtils.getMostRecentGribRecord(interval, + v700 = DATUtils.getMostRecentGridRecord(interval, V700Product.getSQL(interval, V700Product.V700), param700V); - u500 = DATUtils.getMostRecentGribRecord(interval, + u500 = DATUtils.getMostRecentGridRecord(interval, U500Product.getSQL(interval, U500Product.U500), param500U); diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/META-INF/MANIFEST.MF index 6219ccaee2..969a862327 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/META-INF/MANIFEST.MF @@ -5,14 +5,10 @@ Bundle-SymbolicName: com.raytheon.uf.edex.plugin.ffmp Bundle-Version: 1.12.1174.qualifier Bundle-Vendor: RAYTHEON Eclipse-RegisterBuddy: com.raytheon.edex.common, com.raytheon.uf.common.serialization, com.raytheon.uf.viz.core -Require-Bundle: org.eclipse.ui, - org.eclipse.core.runtime, - com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.7";resolution:=optional, +Require-Bundle: com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.7";resolution:=optional, com.raytheon.edex.common;bundle-version="1.11.7", com.raytheon.uf.common.monitor;bundle-version="1.11.7", - org.geotools;bundle-version="2.5.2", org.apache.commons.logging;bundle-version="1.0.4", - com.raytheon.uf.common.dataplugin.qpf;bundle-version="1.11.9", com.raytheon.uf.common.mpe;bundle-version="1.0.0", com.raytheon.uf.common.hydro;bundle-version="1.11.11", com.raytheon.uf.common.localization;bundle-version="1.11.26", @@ -21,12 +17,8 @@ Require-Bundle: org.eclipse.ui, com.raytheon.edex.plugin.radar;bundle-version="1.12.1174", com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", com.raytheon.uf.common.cache;bundle-version="1.12.1174" -Import-Package: com.raytheon.edex.plugin.grib, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, - com.raytheon.uf.common.dataplugin.scan.data, +Import-Package: com.raytheon.uf.common.dataplugin.grid, com.raytheon.uf.common.ohd, - com.raytheon.uf.common.pointdata, com.raytheon.uf.common.status, com.raytheon.uf.edex.dat.utils;resolution:=optional, com.raytheon.uf.edex.plugin.scan.common diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/FFMPGenerator.java b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/FFMPGenerator.java index bd2084624c..74dc7d497c 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/FFMPGenerator.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/FFMPGenerator.java @@ -31,6 +31,7 @@ import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.regex.Pattern; @@ -168,7 +169,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements /** checks for initial load **/ public ArrayList loadedData = new ArrayList(); - + /** thread the productkeys **/ public ConcurrentHashMap> productKeys = new ConcurrentHashMap>(); @@ -678,20 +679,20 @@ public class FFMPGenerator extends CompositeProductGenerator implements sites.add(siteKey); } - + int i = 0; if (sites != null) { // set the latch keys ArrayList lsites = new ArrayList(); - for (String site: sites) { + for (String site : sites) { lsites.add(site); } - + productKeys.put(ffmpProduct.getSourceName(), lsites); } - + for (String productKey : sites) { - + FFMPRecord ffmpRec = new FFMPRecord(); ffmpRec.setSourceName(ffmpProduct.getSourceName()); ffmpRec.setDataKey(dataKey); @@ -704,7 +705,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements ffmpRec.constructDataURI(); if (ffmpRec != null) { - + if (ffmp.isFFTI()) { fftiDone = false; if (!fftiSources.contains(ffmp.getFFTISource())) { @@ -712,22 +713,25 @@ public class FFMPGenerator extends CompositeProductGenerator implements generator, ffmpRec, ffmp.getFFTISource()); fftiSources.add(ffmp.getFFTISource()); - //System.out.println("Adding source to FFTISources!!!!!!!!!!!!"+ffmpRec.getSourceName()); + // System.out.println("Adding source to FFTISources!!!!!!!!!!!!"+ffmpRec.getSourceName()); ffti.processFFTI(); } } // this is a threaded process!!!!!!!!!!! - // Added this to speed the processing of mosaiced sources. - // Before all processing was in line to the source thread. + // Added this to speed the processing of mosaiced + // sources. + // Before all processing was in line to the source + // thread. // This caused slowness in the overall processing. // By allowing the mosaic components to be concurrently - // processed it has drastically sped up overall FFMP performance. + // processed it has drastically sped up overall FFMP + // performance. processDataContainer(ffmpRec, productKey); ffmpRecords.add(ffmpRec); } i++; } - + while (productKeys.size() > 0) { // wait for all threads to finish before returning try { @@ -1049,10 +1053,10 @@ public class FFMPGenerator extends CompositeProductGenerator implements for (String rfc : filter.getRFC()) { // get a hash of the sources and their grib ids - HashMap sources = FFMPUtils.getFFGModelInfo(rfc); + Set sources = FFMPUtils.getFFGParameters(rfc); if (sources != null) { if (sources.size() > 0) { - for (String source : sources.keySet()) { + for (String source : sources) { SourceXML sourceXml = getSourceConfig().getSource( source); @@ -1061,8 +1065,8 @@ public class FFMPGenerator extends CompositeProductGenerator implements String plugin = getSourceConfig().getSource(source) .getPlugin(); - uris.add(FFMPUtils.getFFGDataURI( - sources.get(source), plugin)); + uris.add(FFMPUtils.getFFGDataURI(rfc, source, + plugin)); } } } @@ -1202,7 +1206,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements filter.setValidTime(new Date(System.currentTimeMillis())); filter.reset(); } - + /** * Process this data container * @@ -1213,9 +1217,10 @@ public class FFMPGenerator extends CompositeProductGenerator implements */ public void processDataContainer(FFMPRecord ffmpRec, String productKey) { - this.getProcessExecutor().execute(new ProcessDataContainer(ffmpRec, productKey)); + this.getProcessExecutor().execute( + new ProcessDataContainer(ffmpRec, productKey)); } - + /** * Inner class to thread writing of BuddyFiles * @@ -1225,6 +1230,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements private class ProcessDataContainer implements Runnable { private FFMPRecord ffmpRec; + private String productKey; public void run() { @@ -1254,7 +1260,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements String sourceSiteDataKey = null; FFMPDataContainer fdc = null; boolean write = true; - + try { // write out the fast loader buddy file @@ -1278,7 +1284,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements .getTime() - (3600 * 1000 * 6)); } - + // deal with setting of needed HUCS ArrayList hucs = template.getTemplateMgr() .getHucLevels(); @@ -1379,7 +1385,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements SOURCE_TYPE.GUIDANCE.getSourceType())) { // only write last one write = false; - + if (!ffmpData.containsKey(sourceSiteDataKey)) { ffmpData.put(sourceSiteDataKey, fdc); } else { @@ -1397,13 +1403,15 @@ public class FFMPGenerator extends CompositeProductGenerator implements "Failed Processing FFMPDataContainer" + e.getMessage()); } finally { - // moved writing here to remain safe from possible race condition between processing threads + // moved writing here to remain safe from possible race + // condition between processing threads if (productKeys != null) { if (productKeys.containsKey(ffmpRec.getSourceName())) { - productKeys.get(ffmpRec.getSourceName()).remove(productKey); - //System.out.println("Removed productKey: "+productKey); + productKeys.get(ffmpRec.getSourceName()).remove( + productKey); + // System.out.println("Removed productKey: "+productKey); if (productKeys.get(ffmpRec.getSourceName()).size() == 0) { - //System.out.println("Removed source: "+ffmpRec.getSourceName()+" now writing"); + // System.out.println("Removed source: "+ffmpRec.getSourceName()+" now writing"); productKeys.remove(ffmpRec.getSourceName()); // last one, allow write write = true; @@ -1417,7 +1425,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements backDate = new Date((System.currentTimeMillis()) - (3600 * 1000 * 6)); } - + fdc.purge(backDate); if (write) { @@ -1487,7 +1495,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements * @param huc * @param wfo * @return - * @throws IOException + * @throws IOException */ private FFMPBasinData readLoaderBuddyFile(String sourceSiteDataKey, String huc, String wfo, Date backDate) throws IOException { @@ -1498,27 +1506,24 @@ public class FFMPGenerator extends CompositeProductGenerator implements BufferedInputStream is = null; try { - is = new BufferedInputStream( - new FileInputStream(file)); + is = new BufferedInputStream(new FileInputStream(file)); DynamicSerializationManager dsm = DynamicSerializationManager .getManager(SerializationType.Thrift); basinData = (FFMPBasinData) dsm.deserialize(is); } catch (SerializationException e) { - statusHandler.handle(Priority.ERROR, - "Serialization Error Reading buddy file: " - + e.getMessage()); + statusHandler + .handle(Priority.ERROR, + "Serialization Error Reading buddy file: " + + e.getMessage()); } catch (IOException e) { statusHandler.handle(Priority.ERROR, - "IO Error Reading buddy file: " - + e.getMessage()); + "IO Error Reading buddy file: " + e.getMessage()); } catch (Exception e) { statusHandler.handle(Priority.ERROR, - "General Error Reading buddy file: " - + e.getMessage()); + "General Error Reading buddy file: " + e.getMessage()); } catch (Throwable t) { statusHandler.handle(Priority.ERROR, - "Bogus Thrift Error Reading buddy file: " - + t.getMessage()); + "Bogus Thrift Error Reading buddy file: " + t.getMessage()); } finally { if (is != null) { is.close(); @@ -1876,8 +1881,8 @@ public class FFMPGenerator extends CompositeProductGenerator implements statusHandler.handle(Priority.ERROR, "Unable to locate file " + f.getName(), fnfe); } catch (SerializationException se) { - statusHandler.handle(Priority.ERROR, - "Unable to serialize file " + f.getName(), se); + statusHandler.handle(Priority.ERROR, "Unable to serialize file " + + f.getName(), se); } catch (IOException ioe) { statusHandler.handle(Priority.ERROR, "IO problem reading file " + f.getName(), ioe); @@ -1926,7 +1931,7 @@ public class FFMPGenerator extends CompositeProductGenerator implements public ConcurrentHashMap getFFTIDataContainer() { return fftiData; } - + /** * the executor runner * diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPConfig.java b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPConfig.java index 3ad6076b9a..4be04071ce 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPConfig.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPConfig.java @@ -27,7 +27,7 @@ import java.util.Map; import java.util.TimeZone; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.monitor.config.FFMPSourceConfigurationManager; import com.raytheon.uf.common.monitor.config.FFMPTemplateConfigurationManager; @@ -152,7 +152,7 @@ public class FFMPConfig { * @param dataUri * @return */ - public float[] getGribData(GribRecord rec) { + public float[] getGribData(GridRecord rec) { return ((FloatDataRecord) rec.getMessageData()).getFloatData(); } @@ -258,10 +258,10 @@ public class FFMPConfig { * * @return */ - public GribRecord getGrib(String uri) { - GribRecord rec = null; + public GridRecord getGrib(String uri) { + GridRecord rec = null; try { - rec = DATUtils.getGribRecord(uri); + rec = DATUtils.getGridRecord(uri); } catch (PluginException e) { e.printStackTrace(); } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPProcessor.java b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPProcessor.java index 53a268b806..47467bdad6 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPProcessor.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.ffmp/src/com/raytheon/uf/edex/plugin/ffmp/common/FFMPProcessor.java @@ -47,7 +47,7 @@ import com.raytheon.uf.common.dataplugin.ffmp.FFMPVirtualGageBasinMetaData; import com.raytheon.uf.common.dataplugin.ffmp.SourceBin; import com.raytheon.uf.common.dataplugin.ffmp.SourceBinEntry; import com.raytheon.uf.common.dataplugin.ffmp.SourceBinList; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.radar.RadarRecord; import com.raytheon.uf.common.dataplugin.radar.util.RadarConstants.DHRValues; import com.raytheon.uf.common.dataplugin.radar.util.RadarDataInterrogator; @@ -123,7 +123,7 @@ public class FFMPProcessor { private FFMPRecord ffmpRec = null; - private GribRecord gribRec = null; + private GridRecord gribRec = null; private float[] gribData = null; @@ -305,7 +305,7 @@ public class FFMPProcessor { recdate = imp.getDataTime().getRefTime(); } else if (type == FFMPSourceConfigurationManager.DATA_TYPE.GRID) { - gribRec = (GribRecord) config.getSourceData( + gribRec = (GridRecord) config.getSourceData( source.getSourceName()).get(dataKey); gribData = config.getGribData(gribRec); recdate = gribRec.getDataTime().getRefTime(); @@ -523,7 +523,7 @@ public class FFMPProcessor { try { - gribRec = (GribRecord) config.getSourceData(source.getSourceName()) + gribRec = (GridRecord) config.getSourceData(source.getSourceName()) .get(dataKey); setGridGeometry(gribRec); gribData = config.getGribData(gribRec); @@ -1366,7 +1366,7 @@ public class FFMPProcessor { /** * Sets up the gridgeometry for FFG */ - public void setGridGeometry(GribRecord rec) { + public void setGridGeometry(GridRecord rec) { ffgNx = rec.getSpatialObject().getNx(); ffgNy = rec.getSpatialObject().getNy(); ffgGeometry = MapUtil.getGridGeometry(rec.getSpatialObject()); diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/.classpath b/edexOsgi/com.raytheon.uf.edex.plugin.grid/.classpath new file mode 100644 index 0000000000..f77c5c56bb --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/.project b/edexOsgi/com.raytheon.uf.edex.plugin.grid/.project new file mode 100644 index 0000000000..8b4643dc92 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.edex.plugin.grid + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.edex.plugin.grid/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..5718e24147 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Fri Feb 03 13:25:55 CST 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.grid/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..38314ed4a8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/META-INF/MANIFEST.MF @@ -0,0 +1,65 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Grid +Bundle-SymbolicName: com.raytheon.uf.edex.plugin.grid +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Import-Package: com.raytheon.edex.site, + com.raytheon.uf.common.dataplugin, + com.raytheon.uf.common.dataplugin.grid, + com.raytheon.uf.common.dataplugin.grid.dataset, + com.raytheon.uf.common.dataplugin.grid.request, + com.raytheon.uf.common.dataplugin.level, + com.raytheon.uf.common.dataplugin.persist, + com.raytheon.uf.common.dataquery.db, + com.raytheon.uf.common.datastorage, + com.raytheon.uf.common.datastorage.records, + com.raytheon.uf.common.derivparam.tree, + com.raytheon.uf.common.geospatial, + com.raytheon.uf.common.geospatial.interpolation, + com.raytheon.uf.common.gridcoverage, + com.raytheon.uf.common.gridcoverage.lookup, + com.raytheon.uf.common.serialization, + com.raytheon.uf.common.serialization.comm, + com.raytheon.uf.common.status, + com.raytheon.uf.common.util, + com.raytheon.uf.common.util.registry, + com.raytheon.uf.edex.core, + com.raytheon.uf.edex.core.dataplugin, + com.raytheon.uf.edex.core.props, + com.raytheon.uf.edex.database, + com.raytheon.uf.edex.database.cluster, + com.raytheon.uf.edex.database.dao, + com.raytheon.uf.edex.database.plugin, + com.raytheon.uf.edex.database.query, + com.raytheon.uf.edex.parameter, + com.vividsolutions.jts.geom, + javax.measure.converter, + javax.measure.unit, + org.apache.commons.logging, + org.geotools.coverage, + org.geotools.coverage.grid, + org.geotools.factory, + org.geotools.geometry, + org.geotools.geometry.jts, + org.geotools.referencing, + org.geotools.referencing.operation, + org.geotools.referencing.operation.builder, + org.geotools.referencing.operation.transform, + org.hibernate, + org.hibernate.criterion, + org.opengis.coverage.grid, + org.opengis.geometry, + org.opengis.metadata.spatial, + org.opengis.parameter, + org.opengis.referencing, + org.opengis.referencing.crs, + org.opengis.referencing.datum, + org.opengis.referencing.operation, + org.springframework.dao.support, + org.springframework.orm.hibernate3.support +Export-Package: com.raytheon.uf.edex.plugin.grid.dao, + com.raytheon.uf.edex.plugin.grid.handler, + com.raytheon.uf.edex.plugin.grid.topo +Require-Bundle: com.raytheon.uf.common.parameter;bundle-version="1.0.0" diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/build.properties b/edexOsgi/com.raytheon.uf.edex.plugin.grid/build.properties new file mode 100644 index 0000000000..73974cda80 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/build.properties @@ -0,0 +1,6 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/,\ + utility/ diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/res/spring/grid-common.xml b/edexOsgi/com.raytheon.uf.edex.plugin.grid/res/spring/grid-common.xml new file mode 100644 index 0000000000..2c946935c5 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/res/spring/grid-common.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + com.raytheon.uf.common.dataplugin.level + com.raytheon.uf.common.parameter + com.raytheon.uf.common.gridcoverage + + + + + + + + + + + + + + + + com.raytheon.uf.common.dataplugin.grid.units.GridUnits + + + register + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/res/spring/grid-request.xml b/edexOsgi/com.raytheon.uf.edex.plugin.grid/res/spring/grid-request.xml new file mode 100644 index 0000000000..9236e4b482 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/res/spring/grid-request.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/dao/GridDao.java b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/dao/GridDao.java new file mode 100644 index 0000000000..3beb5c4ad9 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/dao/GridDao.java @@ -0,0 +1,406 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ + +package com.raytheon.uf.edex.plugin.grid.dao; + +import java.io.FileNotFoundException; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import javax.measure.converter.UnitConverter; + +import com.raytheon.uf.common.dataplugin.PluginDataObject; +import com.raytheon.uf.common.dataplugin.PluginException; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridPathProvider; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; +import com.raytheon.uf.common.dataplugin.level.Level; +import com.raytheon.uf.common.dataplugin.level.LevelFactory; +import com.raytheon.uf.common.dataplugin.level.MasterLevel; +import com.raytheon.uf.common.dataplugin.persist.IPersistable; +import com.raytheon.uf.common.dataquery.db.QueryResult; +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.StorageProperties; +import com.raytheon.uf.common.datastorage.StorageStatus; +import com.raytheon.uf.common.datastorage.records.AbstractStorageRecord; +import com.raytheon.uf.common.datastorage.records.FloatDataRecord; +import com.raytheon.uf.common.datastorage.records.IDataRecord; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.lookup.GridCoverageLookup; +import com.raytheon.uf.common.parameter.Parameter; +import com.raytheon.uf.common.parameter.lookup.ParameterLookup; +import com.raytheon.uf.edex.core.EDEXUtil; +import com.raytheon.uf.edex.core.EdexException; +import com.raytheon.uf.edex.core.dataplugin.PluginRegistry; +import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.edex.database.plugin.PluginDao; + +/** + * Data access object for accessing Grid records from the database + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#     Engineer    Description
+ * ------------ ----------  ----------- --------------------------
+ * 4/7/09       1994        bphillip    Initial Creation
+ * 
+ * 
+ * + * @author bphillip + * @version 1 + */ +public class GridDao extends PluginDao { + + private static String purgeModelCacheTopic = null; + + public static String setPurgeModelCacheTopic(String purgeModelCacheTopic) { + GridDao.purgeModelCacheTopic = purgeModelCacheTopic; + return purgeModelCacheTopic; + } + + public GridDao() throws PluginException { + super(GridConstants.GRID); + } + + public GridDao(String pluginName) throws PluginException { + super(pluginName); + } + + @Override + protected IDataStore populateDataStore(IDataStore dataStore, + IPersistable obj) throws Exception { + GridRecord gridRec = (GridRecord) obj; + Object messageData = gridRec.getMessageData(); + GridCoverage location = gridRec.getLocation(); + if (location != null && messageData instanceof float[]) { + long[] sizes = new long[] { location.getNx(), location.getNy() }; + String abbrev = gridRec.getParameter().getAbbreviation(); + String group = gridRec.getDataURI(); + if (GridPathProvider.STATIC_PARAMETERS.contains(abbrev)) { + group = "/" + location.getId(); + } + AbstractStorageRecord storageRecord = new FloatDataRecord("Data", + group, (float[]) messageData, 2, sizes); + + storageRecord.setCorrelationObject(gridRec); + StorageProperties sp = new StorageProperties(); + String compression = PluginRegistry.getInstance() + .getRegisteredObject(pluginName).getCompression(); + if (compression != null) { + sp.setCompression(StorageProperties.Compression + .valueOf(compression)); + } + sp.setChunked(true); + dataStore.addDataRecord(storageRecord, sp); + } else { + throw new Exception("Cannot create data record, spatialData = " + + location + " and messageData = " + messageData); + } + return dataStore; + } + + @Override + public void persistRecords(PluginDataObject... records) + throws PluginException { + List toPersist = new ArrayList( + records.length); + for (PluginDataObject record : records) { + GridRecord rec = (GridRecord) record; + if (rec.getParameter() == null + || rec.getParameter().getName() == null + || rec.getParameter().getName().equals("Missing")) { + logger.info("Discarding record due to missing or unknown parameter mapping: " + + record); + } else { + boolean validLevel = false; + Level level = rec.getLevel(); + + if (level != null) { + MasterLevel ml = level.getMasterLevel(); + + if (ml != null + && !LevelFactory.UNKNOWN_LEVEL.equals(ml.getName())) { + validLevel = true; + } + } + + if (validLevel) { + toPersist.add(rec); + } else { + logger.info("Discarding record due to missing or unknown level mapping: " + + record); + } + } + } + + super.persistRecords(toPersist.toArray(new PluginDataObject[toPersist + .size()])); + } + + @Override + public PluginDataObject[] persistToDatabase(PluginDataObject... records) { + return super.persistToDatabase(verifyRecords(records)); + } + + @Override + public StorageStatus persistToHDF5(PluginDataObject... records) + throws PluginException { + return super.persistToHDF5(verifyRecords(records)); + } + + @Override + public List getHDF5Data(List objects, + int tileSet) throws PluginException { + + List retVal = new ArrayList( + objects.size()); + + for (PluginDataObject rec : objects) { + if (rec instanceof GridRecord) { + try { + GridRecord obj = (GridRecord) rec; + IDataStore dataStore = getDataStore(obj); + String abbrev = obj.getParameter().getAbbreviation(); + if (GridPathProvider.STATIC_PARAMETERS.contains(abbrev)) { + IDataRecord[] record = new IDataRecord[4]; + record[0] = dataStore.retrieve("/" + + obj.getLocation().getId(), abbrev, + Request.ALL); + retVal.add(record); + } else { + /* connect to the data store and retrieve the data */ + IDataRecord[] record = new IDataRecord[4]; + record[0] = dataStore.retrieve(obj.getDataURI(), + "Data", Request.ALL); + + retVal.add(record); + } + } catch (StorageException e) { + throw new PluginException("Error getting HDF5 data", e); + } catch (FileNotFoundException e) { + throw new PluginException("Error getting HDF5 data", e); + } + } + } + + return retVal; + } + + private PluginDataObject[] verifyRecords(PluginDataObject... records) { + List toPersist = new ArrayList( + records.length); + for (PluginDataObject record : records) { + GridRecord rec = (GridRecord) record; + if (validateDataset(rec)) { + toPersist.add(rec); + } + } + return toPersist.toArray(new GridRecord[toPersist.size()]); + } + + private boolean validateDataset(GridRecord record) { + if (!validateParameter(record)) { + return false; + } + if (!validateLevel(record)) { + return false; + } + if (!validateCoverage(record)) { + return false; + } + record.setInfo(GridInfoCache.getInstance() + .getGridInfo(record.getInfo())); + return true; + + } + + private boolean validateParameter(GridRecord record) { + Parameter parameter = record.getParameter(); + boolean result = true; + if (parameter == null) { + result = false; + } else if (parameter.getName() == null) { + result = false; + } else if (parameter.getName().equals("Missing")) { + result = false; + } else { + Parameter dbParameter = ParameterLookup.getInstance().getParameter( + parameter, true); + if (!parameter.equals(dbParameter)) { + // This check is for debugging purposes + // if (!parameter.getName().equals(dbParameter.getName())) { + // logger.info("Record parameter name(" + parameter.getName() + // + ") does not match database(" + // + dbParameter.getName() + ") " + // + record.getDataURI()); + // } + UnitConverter converter = Parameter.compareUnits(parameter, + dbParameter); + // if (converter == null) { + // logger.info("Record parameter unit(" + // + parameter.getUnitString() + // + ") does not match database(" + // + dbParameter.getUnitString() + ") " + // + record.getDataURI()); + // // For absolute accuracy we should abort if units don't + // // match, but currently we will persist it anyway. + // // result = false; + // } else + if (converter != null && converter != UnitConverter.IDENTITY) { + Object messageData = record.getMessageData(); + if (messageData instanceof float[]) { + float[] data = (float[]) messageData; + for (int i = 0; i < data.length; i++) { + data[i] = (float) converter.convert(data[i]); + } + } else { + logger.info("Unable to convert grid data to correct units: " + + record.getDataURI()); + } + } + } + record.setParameter(dbParameter); + } + if (!result) { + logger.info("Discarding record due to missing or unknown parameter mapping: " + + record); + } + return result; + } + + private boolean validateCoverage(GridRecord record) { + GridCoverage coverage = record.getLocation(); + if (coverage == null) { + logger.info("Discarding record due to missing location: " + record); + return false; + } + GridCoverage dbCoverage = GridCoverageLookup.getInstance().getCoverage( + coverage, false); + if (coverage == dbCoverage) { + return true; + } + if (dbCoverage == null) { + dbCoverage = GridCoverageLookup.getInstance().getCoverage(coverage, + true); + logger.error("Unable to persist " + record + + " because storing the location failed."); + if (dbCoverage == null) { + return false; + } + } + record.setLocation(dbCoverage); + if (!coverage.getId().equals(dbCoverage.getId())) { + record.setDataURI(null); + try { + record.constructDataURI(); + } catch (PluginException e) { + logger.info("Error constructing dataURI: " + record); + return false; + } + } + return true; + } + + private boolean validateLevel(GridRecord record) { + boolean result = false; + Level level = record.getLevel(); + + if (level != null) { + MasterLevel ml = level.getMasterLevel(); + + if (ml != null && !LevelFactory.UNKNOWN_LEVEL.equals(ml.getName())) { + result = true; + } + } + + if (!result) { + logger.info("Discarding record due to missing or unknown level mapping: " + + record); + } + return result; + } + + /** + * Overridden to clean up orphan GridInfoRecords. + */ + @Override + public void delete(List objs) { + super.delete(objs); + Set orphanedIds = new HashSet(objs.size()); + StringBuilder sqlString = new StringBuilder(objs.size() * 15 + 80); + sqlString + .append("select distinct info_id from awips.grid where info_id in ("); + for (PluginDataObject pdo : objs) { + if (pdo instanceof GridRecord) { + Integer id = ((GridRecord) pdo).getInfo().getId(); + if (orphanedIds.add(id)) { + if (orphanedIds.size() > 1) { + sqlString.append(", "); + } + sqlString.append(id); + } + } + } + sqlString.append(");"); + try { + QueryResult result = (QueryResult) this.executeNativeSql(sqlString + .toString()); + for (int i = 0; i < result.getResultCount(); i++) { + orphanedIds.remove((Integer) result.getRowColumnValue(i, 0)); + } + if (!orphanedIds.isEmpty()) { + sqlString = new StringBuilder(orphanedIds.size() * 15 + 60); + sqlString.append("delete from awips.grid_info where id in ("); + boolean first = true; + for (Integer id : orphanedIds) { + if (!first) { + sqlString.append(", "); + } else { + first = false; + } + sqlString.append(id); + } + sqlString.append(");"); + if (purgeModelCacheTopic != null) { + this.executeNativeSql(sqlString.toString()); + EDEXUtil.getMessageProducer().sendAsyncUri( + purgeModelCacheTopic, orphanedIds); + } else { + GridInfoCache.getInstance().purgeCache( + new ArrayList(orphanedIds)); + statusHandler + .warn("Unable to purge model cache of clustered edices"); + } + } + } catch (DataAccessLayerException e1) { + statusHandler.error("Error purging orphaned grid info entries", e1); + } catch (EdexException e) { + statusHandler.error( + "Error sending message to purge grid info topic", e); + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/dao/GridInfoCache.java b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/dao/GridInfoCache.java new file mode 100644 index 0000000000..ae17c6708c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/dao/GridInfoCache.java @@ -0,0 +1,113 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.plugin.grid.dao; + +import java.lang.ref.SoftReference; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.WeakHashMap; + +import com.raytheon.uf.common.dataplugin.grid.GridInfoRecord; +import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; + +/** + * Cache the gridInfo objects from the database to avoid repeated lookups. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 21, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ + +public class GridInfoCache { + + private static GridInfoCache instance = new GridInfoCache(); + + public static GridInfoCache getInstance() { + return instance; + } + + private final CoreDao dao; + + // A weak hashmap of soft references is used as a SoftSet. + private Map> cache = null; + + private GridInfoCache() { + cache = Collections + .synchronizedMap(new WeakHashMap>()); + dao = new CoreDao(DaoConfig.forClass(GridInfoRecord.class)); + } + + public GridInfoRecord getGridInfo(GridInfoRecord record) { + GridInfoRecord result = checkLocalCache(record); + if (result == null) { + synchronized (this) { + // It is possible that this query will return multiple results, + // for example if the record we are looking for has a null + // secondaryId but some db entries have a secondaryId set then + // this query will return all matching models ignoring + // secondaryId. In general these cases should be rare and small. + // So we handle it by caching everything returned and then + // double checking the cache. + List> dbList = dao + .queryByExample(record); + if (dbList != null && !dbList.isEmpty()) { + for (PersistableDataObject pdo : dbList) { + GridInfoRecord gir = (GridInfoRecord) pdo; + cache.put(gir, new SoftReference(gir)); + } + } + result = checkLocalCache(record); + if (result == null) { + dao.saveOrUpdate(record); + result = record; + } + } + } + return result; + } + + private GridInfoRecord checkLocalCache(GridInfoRecord record) { + GridInfoRecord result = null; + SoftReference ref = cache.get(record); + if (ref != null) { + result = ref.get(); + } + return result; + } + + public void purgeCache(List modelKeys) { + for (Integer key : modelKeys) { + cache.remove(key); + } + } + +} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/handler/DeleteAllGridDataHandler.java b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/handler/DeleteAllGridDataHandler.java new file mode 100644 index 0000000000..bed72d0720 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/handler/DeleteAllGridDataHandler.java @@ -0,0 +1,70 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.plugin.grid.handler; + +import java.util.HashMap; +import java.util.Map; + +import com.raytheon.uf.common.dataplugin.grid.request.DeleteAllGridDataRequest; +import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.edex.core.EDEXUtil; +import com.raytheon.uf.edex.plugin.grid.dao.GridDao; + +/** + * Request handler for DeleteAllGridDataRequest. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 2, 2012            dgilling     Initial creation
+ * 
+ * 
+ * + * @author dgilling + * @version 1.0 + */ + +public class DeleteAllGridDataHandler implements + IRequestHandler { + + private static final String PLUGIN_PURGED_TOPIC = "jms-generic:topic:pluginPurged"; + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.serialization.comm.IRequestHandler#handleRequest + * (com.raytheon.uf.common.serialization.comm.IServerRequest) + */ + @Override + public Boolean handleRequest(DeleteAllGridDataRequest request) + throws Exception { + Map productKeys = new HashMap(); + productKeys.put("info.datasetId", request.getModelName()); + GridDao dao = new GridDao(); + dao.purgeAllData(productKeys); + + EDEXUtil.getMessageProducer().sendAsyncUri(PLUGIN_PURGED_TOPIC, "grid"); + return Boolean.TRUE; + } +} diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/uengine/tasks/grib/GridCatalog.java b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/handler/GridTreeHandler.java similarity index 53% rename from edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/uengine/tasks/grib/GridCatalog.java rename to edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/handler/GridTreeHandler.java index 0d4f25f2e9..8ca65f1f5f 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/uengine/tasks/grib/GridCatalog.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/handler/GridTreeHandler.java @@ -17,77 +17,58 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.edex.uengine.tasks.grib; +package com.raytheon.uf.edex.plugin.grid.handler; import java.util.ArrayList; import java.util.Arrays; -import java.util.Calendar; import java.util.List; -import java.util.TimeZone; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import com.raytheon.edex.uengine.tasks.ScriptTask; -import com.raytheon.uf.common.dataplugin.grib.GribModel; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; +import com.raytheon.uf.common.dataplugin.grid.GridInfoConstants; +import com.raytheon.uf.common.dataplugin.grid.GridInfoRecord; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfo; +import com.raytheon.uf.common.dataplugin.grid.dataset.DatasetInfoLookup; +import com.raytheon.uf.common.dataplugin.grid.request.GetGridTreeRequest; import com.raytheon.uf.common.derivparam.tree.DataTree; -import com.raytheon.uf.edex.core.EdexException; +import com.raytheon.uf.common.serialization.comm.IRequestHandler; import com.raytheon.uf.edex.database.dao.CoreDao; import com.raytheon.uf.edex.database.dao.DaoConfig; import com.raytheon.uf.edex.database.query.DatabaseQuery; /** - * The GridCatalog script task is used to retrieve the necessary elements needed - * to populate a grid tree. This includes center id, subcenter id, generating - * process, parameter abbreviation, and level info. - * + * Build a DataTree representing all the grid data in the db. * *
+ * 
  * SOFTWARE HISTORY
- * Date			Ticket#		Engineer	Description
- * ------------	----------	-----------	--------------------------
- * Apr 10, 2008				brockwoo	Initial creation
- * May 1, 2009  2321        brockwoo    Check if a bad row out of grib model is returned
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 5, 2012            bsteffen     Initial creation
  * 
  * 
* - * @author brockwoo + * @author bsteffen * @version 1.0 */ -public class GridCatalog extends ScriptTask { +public class GridTreeHandler implements IRequestHandler { - protected final transient static Log logger = LogFactory - .getLog(GridCatalog.class); + private static final String[] GRIDFIELDS = { GridInfoConstants.DATASET_ID, + GridInfoConstants.PARAMETER_ABBREVIATION, + GridInfoConstants.PARAMETER_NAME, GridInfoConstants.PARAMETER_UNIT, + GridInfoConstants.LEVEL_ID }; - private static final String[] GRIDFIELDS = { "modelName", - "parameterAbbreviation", "parameterName", "parameterUnit", - "level.id" }; - - private Long insertTime; - - /* - * (non-Javadoc) - * - * @see com.raytheon.edex.uengine.tasks.ScriptTask#execute() - */ @Override - public Object execute() throws EdexException { + public DataTree handleRequest(GetGridTreeRequest request) throws Exception { DataTree gridTree = null; CoreDao gribDao = null; List queryResults = null; - gribDao = new CoreDao(DaoConfig.forClass(GribModel.class)); + gribDao = new CoreDao(DaoConfig.forClass(GridInfoRecord.class)); // if we do not get a table back, just return an empty list gridTree = new DataTree(); - DatabaseQuery query = new DatabaseQuery(GribModel.class.getName()); - if (insertTime != null) { - Calendar time = Calendar.getInstance(TimeZone.getTimeZone("GMT")); - time.setTimeInMillis(insertTime); - query.addQueryParam("insertTime", time, ">"); - } + DatabaseQuery query = new DatabaseQuery(GridInfoRecord.class.getName()); + List distinctFields = Arrays.asList(GRIDFIELDS); query.addOrder(distinctFields.get(0), true); @@ -96,8 +77,8 @@ public class GridCatalog extends ScriptTask { if (queryResults.size() > 0) { for (Object gridField : queryResults) { if (gridField.getClass().isArray()) { - ArrayList gridFields = new ArrayList(Arrays - .asList((Object[]) gridField)); + ArrayList gridFields = new ArrayList( + Arrays.asList((Object[]) gridField)); String model = gridFields.get(0).toString(); gridTree.addBranch(model, getDt(model), gridFields.get(1) .toString(), gridFields.get(2).toString(), @@ -110,10 +91,9 @@ public class GridCatalog extends ScriptTask { } private int getDt(String modelName) { - GridModel model = GribModelLookup.getInstance().getModelByName( - modelName); - if (model != null && model.getDt() != null) { - int dTinSeconds = model.getDt(); + DatasetInfo info = DatasetInfoLookup.getInstance().getInfo(modelName); + if (info != null && info.getDt() != null) { + int dTinSeconds = info.getDt(); // dT <= 24 is in hours, need to convert to seconds if (Math.abs(dTinSeconds) <= 24) { @@ -124,8 +104,4 @@ public class GridCatalog extends ScriptTask { return -1; } - public void setInsertTime(long time) { - insertTime = new Long(time); - } - } diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticTopoData.java b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/topo/StaticTopoData.java similarity index 63% rename from edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticTopoData.java rename to edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/topo/StaticTopoData.java index b16b36a17e..2753f73d24 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/StaticTopoData.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/topo/StaticTopoData.java @@ -18,17 +18,17 @@ * further licensing information. **/ -package com.raytheon.edex.plugin.grib.topo; +package com.raytheon.uf.edex.plugin.grid.topo; +import java.awt.Point; import java.io.File; import java.io.FileInputStream; +import java.io.FileNotFoundException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -48,6 +48,7 @@ import org.geotools.referencing.operation.AbstractCoordinateOperationFactory; import org.geotools.referencing.operation.builder.GridToEnvelopeMapper; import org.geotools.referencing.operation.transform.IdentityTransform; import org.opengis.geometry.DirectPosition; +import org.opengis.geometry.MismatchedDimensionException; import org.opengis.metadata.spatial.PixelOrientation; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; @@ -59,13 +60,7 @@ import org.opengis.referencing.operation.MathTransform; import org.opengis.referencing.operation.MathTransformFactory; import org.opengis.referencing.operation.TransformException; -import com.raytheon.edex.plugin.grib.spatial.GribSpatialCache; -import com.raytheon.edex.plugin.grib.util.GribParamInfoLookup; import com.raytheon.edex.site.SiteUtil; -import com.raytheon.uf.common.dataplugin.grib.exception.GribException; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.util.GribModelLookup; -import com.raytheon.uf.common.dataplugin.grib.util.GridModel; import com.raytheon.uf.common.datastorage.DataStoreFactory; import com.raytheon.uf.common.datastorage.IDataStore; import com.raytheon.uf.common.datastorage.IDataStore.StoreOp; @@ -73,12 +68,11 @@ import com.raytheon.uf.common.datastorage.Request; import com.raytheon.uf.common.datastorage.StorageException; import com.raytheon.uf.common.datastorage.StorageProperties; import com.raytheon.uf.common.datastorage.StorageProperties.Compression; -import com.raytheon.uf.common.datastorage.records.ByteDataRecord; import com.raytheon.uf.common.datastorage.records.FloatDataRecord; import com.raytheon.uf.common.geospatial.CRSCache; import com.raytheon.uf.common.geospatial.MapUtil; +import com.raytheon.uf.common.gridcoverage.GridCoverage; import com.raytheon.uf.common.serialization.SerializationException; -import com.raytheon.uf.common.serialization.SerializationUtil; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; @@ -127,8 +121,8 @@ public class StaticTopoData { private static final String TASK_NAME = "initStaticTopo"; - /** The HDF group containing the static topo information for gfe */ - private static final String STOPO_GROUP = "/stopo/"; + /** The HDF dataset name for the static topo information for gfe */ + private static final String STOPO_DATASET = "Topo"; /** The .dat.gz suffix */ private static final String DAT_GZ_SUFFIX = ".dat.gz"; @@ -278,7 +272,6 @@ public class StaticTopoData { } initAttributes(); - checkModelTopo(); } catch (Exception e) { statusHandler.handle(Priority.CRITICAL, "Error initializing static topo data!", e); @@ -359,8 +352,10 @@ public class StaticTopoData { for (String dataset : dataSets) { if (dataset.startsWith("attr")) { - TopoAttributes.attributeMap.put(dataset.replace("attr", ""), - sTopoDataStore.retrieve("/", dataset, Request.ALL) + TopoAttributes.attributeMap.put( + dataset.replace("attr", ""), + sTopoDataStore.retrieve("/", dataset, + Request.buildPointRequest(new Point(0, 0))) .getDataAttributes()); } } @@ -375,11 +370,13 @@ public class StaticTopoData { * The site for which to initalize the topo data * @param config * The site's configuration information - * @throws GribException + * @throws StorageException + * @throws SerializationException * If the topography data cannot be initialized for the given * site */ - public void initStopoData(GridCoverage coverage) throws GribException { + public void initStopoData(GridCoverage coverage) throws StorageException, + SerializationException { if (coverage.getNx() < 0 || coverage.getNy() < 0) { statusHandler.handle(Priority.PROBLEM, coverage.getName() + " is not applicable to " + SiteUtil.getSite() @@ -390,36 +387,17 @@ public class StaticTopoData { // Gets the location data and extracts it from the static topo file float[] finalData = null; - try { - finalData = getTopoData(inGeom, coverage.getCrs(), - coverage.getNx(), coverage.getNy()); - } catch (Exception e) { - throw new GribException( - "Error getting topo data for GFE grid location for " - + coverage.getName() + " model", e); - } + finalData = getTopoData(inGeom, coverage.getCrs(), coverage.getNx(), + coverage.getNy()); // Create an HDF5 data record and store it - try { - FloatDataRecord outRecord = new FloatDataRecord(coverage.getName(), - STOPO_GROUP, finalData, 2, new long[] { - inGeom.getGridRange().getHigh(0) + 1, - inGeom.getGridRange().getHigh(1) + 1 }); - siteDataStore.addDataRecord(outRecord, sp); - siteDataStore.store(StoreOp.REPLACE); + FloatDataRecord outRecord = new FloatDataRecord(STOPO_DATASET, + coverage.spatialKey(), finalData, 2, new long[] { + inGeom.getGridRange().getHigh(0) + 1, + inGeom.getGridRange().getHigh(1) + 1 }); + siteDataStore.addDataRecord(outRecord, sp); + siteDataStore.store(StoreOp.REPLACE); - ByteDataRecord coverageRecord = new ByteDataRecord( - coverage.getName() + "coverage", "/coverages", - SerializationUtil.transformToThrift(coverage)); - siteDataStore.addDataRecord(coverageRecord, sp); - siteDataStore.store(StoreOp.REPLACE); - } catch (StorageException e) { - throw new GribException( - "Error persisting topo data for GFE grid location for site " - + coverage.getName(), e); - } catch (SerializationException e) { - throw new GribException("Error serializing coverage object.", e); - } statusHandler .handle(Priority.INFO, "Stopo data successfully initialized for " @@ -430,99 +408,31 @@ public class StaticTopoData { * Private method used by the initialization code to see if the static topo * data for a coverage has been initialized */ - private void checkModelTopo() { - Map models = GribModelLookup.getInstance() - .getModelByNameMap(); + public boolean checkModelTopo(GridCoverage coverage) { + ClusterTask ct = ClusterLockUtils.lock(TASK_NAME, + coverage.spatialKey(), 120000, false); - GridCoverage coverage = null; - List modelsToProcess = new LinkedList(models.keySet()); - int size = modelsToProcess.size(); - while (size > 0) { - Iterator iter = modelsToProcess.iterator(); - while (iter.hasNext()) { - String name = iter.next(); - boolean processed = false; - if (GribParamInfoLookup.getInstance().getParameterInfo(name, - "staticTopo") != null) { - coverage = GribSpatialCache.getInstance().getGrid(name); - ClusterTask ct = ClusterLockUtils.lock(TASK_NAME, name, - 120000, false); - - if (LockState.SUCCESSFUL.equals(ct.getLockState())) { - // set processed to true regardless of successfully - // update coverage so we don't infinite loop - processed = true; - try { - if (coverage == null) { - statusHandler.handle(Priority.INFO, - "Coverage object was null for for " - + name + " model"); - } else if (updateCoverage(name, coverage)) { - statusHandler.handle(Priority.INFO, - "Initializing static topo for grid " - + coverage.getName() + " for " - + name + " model"); - initStopoData(coverage); - } - } catch (GribException e) { - statusHandler.handle(Priority.INFO, - "Error storing static topo data for " - + name + " model", e); - } finally { - ClusterLockUtils.unlock(ct, false); - } - } - } else { - processed = true; - } - - // remove the item from the queue - if (processed) { - iter.remove(); + if (LockState.SUCCESSFUL.equals(ct.getLockState())) { + // set processed to true regardless of successfully + // update coverage so we don't infinite loop + try { + if (!topoExists(coverage)) { + statusHandler.handle( + Priority.INFO, + "Initializing static topo for grid " + + coverage.getName()); + initStopoData(coverage); } + } catch (Exception e) { + statusHandler.handle( + Priority.INFO, + "Error storing static topo data for " + + coverage.getName(), e); + } finally { + ClusterLockUtils.unlock(ct, false); } - - int curSize = modelsToProcess.size(); - if (curSize > 0 && curSize == size) { - // we still have items to process and we didn't process any then - // they are in process by another server and we need to sleep - // and try again - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - // ignore - } - } - - size = curSize; - } - } - - private boolean updateCoverage(String modelName, GridCoverage coverage) - throws GribException { - if (!modelTopoExists(modelName)) { return true; } - try { - ByteDataRecord coverageRecord = (ByteDataRecord) siteDataStore - .retrieve("/coverages", coverage.getName() + "coverage", - Request.ALL); - GridCoverage storedCoverage = (GridCoverage) SerializationUtil - .transformFromThrift(coverageRecord.getByteData()); - if (!storedCoverage.equals(coverage)) { - statusHandler.handle(Priority.INFO, - "GridCoverage has changed for " + coverage.getName() - + ". Updating static topo"); - siteDataStore.delete("/coverages/" + coverage.getName() - + "coverage"); - siteDataStore.delete(STOPO_GROUP + coverage.getName()); - return true; - } - } catch (Exception e) { - throw new GribException("Error retrieving GridCoverage from file", - e); - } - return false; } @@ -534,19 +444,18 @@ public class StaticTopoData { * @return True if the data exists, else false * @throws GribException */ - private boolean modelTopoExists(String modelName) throws GribException { + private boolean topoExists(GridCoverage coverage) { List dataSets = null; try { - String[] modelArray = siteDataStore.getDatasets(STOPO_GROUP); + String[] modelArray = siteDataStore.getDatasets(coverage + .spatialKey()); dataSets = Arrays.asList(modelArray); } catch (Exception e) { return false; } - if (dataSets.contains(modelName) - || dataSets.contains(GribSpatialCache.getInstance() - .getGrid(modelName).getName())) { + if (dataSets.contains(STOPO_DATASET)) { return true; } @@ -562,17 +471,21 @@ public class StaticTopoData { * @throws GribException * If an error occurs while retrieving the topo data */ - public FloatDataRecord getStopoData(String modelName) throws GribException { + public FloatDataRecord getStopoData(GridCoverage coverage) { + if (!topoExists(coverage)) { + while (!checkModelTopo(coverage)) { + } + } FloatDataRecord record = null; try { - GridCoverage coverage = GribSpatialCache.getInstance().getGrid( - modelName); - record = (FloatDataRecord) siteDataStore.retrieve(STOPO_GROUP, - coverage.getName(), Request.ALL); + record = (FloatDataRecord) siteDataStore.retrieve( + coverage.spatialKey(), STOPO_DATASET, Request.ALL); } catch (Exception e) { - statusHandler.handle(Priority.INFO, - "Static topo data does not exist for grid " + modelName); + statusHandler.handle( + Priority.INFO, + "Static topo data does not exist for grid " + + coverage.getName()); return null; } return record; @@ -590,15 +503,14 @@ public class StaticTopoData { * If the data cannot be extracted */ private float[] getTopoData(GridGeometry2D inGeom, - CoordinateReferenceSystem inCrs, int coverageNx, int coverageNy) - throws GribException { + CoordinateReferenceSystem inCrs, int coverageNx, int coverageNy) { /* * Iterate through each of the data sets until the returned data set is * fully populated */ float[] finalData = null; - + for (String topoData : TOPO_FILES) { for (String dataSet : TopoAttributes.attributeMap.keySet()) { if (dataSet.startsWith(topoData)) { @@ -614,15 +526,15 @@ public class StaticTopoData { break; } } - + for (int i = 0; i < finalData.length; i++) { - float v = finalData[i]; - if (Float.isNaN(v)) - finalData[i] = TOPO_FILL; - else if (v == DATA_FILL || (v > -0.5 && v < 0.5)) - finalData[i] = 0.0f; - else - finalData[i] = v; + float v = finalData[i]; + if (Float.isNaN(v)) + finalData[i] = TOPO_FILL; + else if (v == DATA_FILL || (v > -0.5 && v < 0.5)) + finalData[i] = 0.0f; + else + finalData[i] = v; } return finalData; @@ -702,10 +614,12 @@ public class StaticTopoData { inGeom.getEnvelope2D(), inCrs); refEnv = refEnv.transform(topoCrs, true); - DirectPosition upperCorner = topoGeom.getCRSToGrid2D(PixelOrientation.UPPER_LEFT).transform( - refEnv.getUpperCorner(), null); - DirectPosition lowerCorner = topoGeom.getCRSToGrid2D(PixelOrientation.UPPER_LEFT).transform( - refEnv.getLowerCorner(), null); + DirectPosition upperCorner = topoGeom.getCRSToGrid2D( + PixelOrientation.UPPER_LEFT).transform(refEnv.getUpperCorner(), + null); + DirectPosition lowerCorner = topoGeom.getCRSToGrid2D( + PixelOrientation.UPPER_LEFT).transform(refEnv.getLowerCorner(), + null); int minx = (int) Math.floor(Math.min(lowerCorner.getOrdinate(0), upperCorner.getOrdinate(0))); @@ -717,48 +631,47 @@ public class StaticTopoData { upperCorner.getOrdinate(1))); if ("world".equals(name)) { - if (minx - DATA_MARGIN < 0 || - miny - DATA_MARGIN < 0 || - maxx + DATA_MARGIN >= nx || - maxy + DATA_MARGIN >= ny) { - /* TODO: Have to do quite a bit more for minimal world - * projection subset. Just load the whole thing for now. + if (minx - DATA_MARGIN < 0 || miny - DATA_MARGIN < 0 + || maxx + DATA_MARGIN >= nx || maxy + DATA_MARGIN >= ny) { + /* + * TODO: Have to do quite a bit more for minimal world + * projection subset. Just load the whole thing for now. */ - minx = miny = 0; - maxx = nx; - maxy = ny; - } + minx = miny = 0; + maxx = nx; + maxy = ny; + } } else { - if (minx - DATA_MARGIN >= 0) { - minx -= DATA_MARGIN; - } else { - minx = 0; - } - - if (miny - DATA_MARGIN >= 0) { - miny -= DATA_MARGIN; - } else { - miny = 0; - } - - if (maxx + DATA_MARGIN <= nx) { - maxx += DATA_MARGIN; - } else { - maxx = nx; - } - - if (maxy + DATA_MARGIN <= ny) { - maxy += DATA_MARGIN; - } else { - maxy = ny; - } + if (minx - DATA_MARGIN >= 0) { + minx -= DATA_MARGIN; + } else { + minx = 0; + } + + if (miny - DATA_MARGIN >= 0) { + miny -= DATA_MARGIN; + } else { + miny = 0; + } + + if (maxx + DATA_MARGIN <= nx) { + maxx += DATA_MARGIN; + } else { + maxx = nx; + } + + if (maxy + DATA_MARGIN <= ny) { + maxy += DATA_MARGIN; + } else { + maxy = ny; + } } double[] input = new double[] { minx, miny, maxx, maxy }; double[] output = new double[input.length]; - topoGeom.getGridToCRS(PixelInCell.CELL_CORNER) - .transform(input, 0, output, 0, input.length / 2); + topoGeom.getGridToCRS(PixelInCell.CELL_CORNER).transform(input, 0, + output, 0, input.length / 2); DirectPosition dpUpper = new DirectPosition2D(Math.max(output[0], output[2]), Math.max(output[1], output[3])); @@ -797,12 +710,13 @@ public class StaticTopoData { // Reproject the data into the requested CRS and geometry float[] f1 = null; try { - f1 = simpleResample(topoCoverage, slabData, inGeom, name, minx, miny); + f1 = simpleResample(topoCoverage, slabData, inGeom, name, minx, + miny); } catch (Exception e) { - statusHandler.error("rasample failed", e); - throw e; + statusHandler.error("rasample failed", e); + throw e; } - + if (finalData == null) { finalData = f1; } else { @@ -816,182 +730,202 @@ public class StaticTopoData { return finalData; } - float[] simpleResample(GridCoverage2D sourceGC, float[][] sourceData, GridGeometry2D targetGG, String pfx, int minx, int miny) { - int sourceWidth = sourceGC.getGridGeometry().getGridRange2D().getSpan(0); - int sourceHeight = sourceGC.getGridGeometry().getGridRange2D().getSpan(1); - int targetWidth = targetGG.getGridRange2D().getSpan(0); - int targetHeight = targetGG.getGridRange2D().getSpan(1); - float[] output = new float[targetWidth * targetHeight]; - Arrays.fill(output, Float.NaN); + float[] simpleResample(GridCoverage2D sourceGC, float[][] sourceData, + GridGeometry2D targetGG, String pfx, int minx, int miny) { + int sourceWidth = sourceGC.getGridGeometry().getGridRange2D() + .getSpan(0); + int sourceHeight = sourceGC.getGridGeometry().getGridRange2D() + .getSpan(1); + int targetWidth = targetGG.getGridRange2D().getSpan(0); + int targetHeight = targetGG.getGridRange2D().getSpan(1); + float[] output = new float[targetWidth * targetHeight]; + Arrays.fill(output, Float.NaN); - ArrayList transforms = new ArrayList(); - ArrayList toGeoXforms = new ArrayList(); - ArrayList sourceToGeoXforms = new ArrayList(); + ArrayList transforms = new ArrayList(); + ArrayList toGeoXforms = new ArrayList(); + ArrayList sourceToGeoXforms = new ArrayList(); - MathTransform targetGtoCRS = targetGG.getGridToCRS(PixelInCell.CELL_CENTER); - MathTransform sourceCRStoG = sourceGC.getGridGeometry().getCRSToGrid2D(PixelOrientation.CENTER); - CoordinateReferenceSystem targetCRS = targetGG.getCoordinateReferenceSystem(); - CoordinateReferenceSystem sourceCRS = sourceGC.getCoordinateReferenceSystem(); - - transforms.add(targetGtoCRS); - if (! CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) { - GeographicCRS sourceGeoCRS = null; - GeographicCRS targetGeoCRS = null; - if (sourceCRS instanceof ProjectedCRS) { - sourceGeoCRS = ((ProjectedCRS) sourceCRS).getBaseCRS(); - } - if (targetCRS instanceof ProjectedCRS) { - targetGeoCRS = ((ProjectedCRS) targetCRS).getBaseCRS(); - } - try { - transforms.add(CRS.findMathTransform(targetCRS, targetGeoCRS, true)); - toGeoXforms.addAll(transforms); - if (CRS.equalsIgnoreMetadata(sourceGeoCRS, targetGeoCRS)) { - // nothing... - } else { - transforms.add(CRS.findMathTransform(targetGeoCRS, sourceGeoCRS)); - } - transforms.add(CRS.findMathTransform(sourceGeoCRS, sourceCRS, true)); - sourceToGeoXforms.add(0, CRS.findMathTransform(sourceCRS, sourceGeoCRS)); - } catch (FactoryException e) { - // TODO: log - return output; - } - } - transforms.add(sourceCRStoG); - sourceToGeoXforms.add(0, sourceGC.getGridGeometry().getGridToCRS(PixelInCell.CELL_CENTER)); + MathTransform targetGtoCRS = targetGG + .getGridToCRS(PixelInCell.CELL_CENTER); + MathTransform sourceCRStoG = sourceGC.getGridGeometry().getCRSToGrid2D( + PixelOrientation.CENTER); + CoordinateReferenceSystem targetCRS = targetGG + .getCoordinateReferenceSystem(); + CoordinateReferenceSystem sourceCRS = sourceGC + .getCoordinateReferenceSystem(); + + transforms.add(targetGtoCRS); + if (!CRS.equalsIgnoreMetadata(sourceCRS, targetCRS)) { + GeographicCRS sourceGeoCRS = null; + GeographicCRS targetGeoCRS = null; + if (sourceCRS instanceof ProjectedCRS) { + sourceGeoCRS = ((ProjectedCRS) sourceCRS).getBaseCRS(); + } + if (targetCRS instanceof ProjectedCRS) { + targetGeoCRS = ((ProjectedCRS) targetCRS).getBaseCRS(); + } + try { + transforms.add(CRS.findMathTransform(targetCRS, targetGeoCRS, + true)); + toGeoXforms.addAll(transforms); + if (CRS.equalsIgnoreMetadata(sourceGeoCRS, targetGeoCRS)) { + // nothing... + } else { + transforms.add(CRS.findMathTransform(targetGeoCRS, + sourceGeoCRS)); + } + transforms.add(CRS.findMathTransform(sourceGeoCRS, sourceCRS, + true)); + sourceToGeoXforms.add(0, + CRS.findMathTransform(sourceCRS, sourceGeoCRS)); + } catch (FactoryException e) { + // TODO: log + return output; + } + } + transforms.add(sourceCRStoG); + sourceToGeoXforms.add(0, + sourceGC.getGridGeometry() + .getGridToCRS(PixelInCell.CELL_CENTER)); + + MathTransform mt; + try { + mt = concatenateTransforms(transforms); + } catch (FactoryException e1) { + // TODO: log + return output; + } + + double[] coord = new double[2]; + + /* + * Output index. Assumes we iterate top-left to bottom-right in + * row-major order. + */ + int oi = 0; + for (int y = 0; y < targetHeight; ++y) { + for (int x = 0; x < targetWidth; ++x, ++oi) { + coord[0] = x; + coord[1] = y; + try { + mt.transform(coord, 0, coord, 0, 1); + } catch (TransformException e) { + continue; + } + + // Integer cell coordinates of upper-left cell of the 2x2 cell + // sample area + int sulx = (int) coord[0]; + int suly = (int) coord[1]; + + double fx = coord[0] - sulx; + double fy = coord[1] - suly; + + double tv = 0; // sum of weighted valid values + double tw = 0; // sum of valid weights + float v0; + double w0; + if (sulx >= 0 && suly >= 0 && sulx < sourceWidth - 1 + && suly < sourceHeight - 1) { + if (valid(v0 = fix(sourceData[suly][sulx]))) { + w0 = (1 - fx) * (1 - fy); + tv += v0 * w0; + tw += w0; + } + if (valid(v0 = fix(sourceData[suly][sulx + 1]))) { + w0 = (fx) * (1 - fy); + tv += v0 * w0; + tw += w0; + } + if (valid(v0 = fix(sourceData[suly + 1][sulx]))) { + w0 = (1 - fx) * (fy); + tv += v0 * w0; + tw += w0; + } + if (valid(v0 = fix(sourceData[suly + 1][sulx + 1]))) { + w0 = (fx) * (fy); + tv += v0 * w0; + tw += w0; + } + } else { + if (isValidCoord(sulx, suly, sourceWidth, sourceHeight) + && valid(v0 = fix(sourceData[suly][sulx]))) { + w0 = (1 - fx) * (1 - fy); + tv += v0 * w0; + tw += w0; + } + if (isValidCoord(sulx + 1, suly, sourceWidth, sourceHeight) + && valid(v0 = fix(sourceData[suly][sulx + 1]))) { + w0 = (fx) * (1 - fy); + tv += v0 * w0; + tw += w0; + } + if (isValidCoord(sulx, suly + 1, sourceWidth, sourceHeight) + && valid(v0 = fix(sourceData[suly + 1][sulx]))) { + w0 = (1 - fx) * (fy); + tv += v0 * w0; + tw += w0; + } + if (isValidCoord(sulx + 1, suly + 1, sourceWidth, + sourceHeight) + && valid(v0 = fix(sourceData[suly + 1][sulx + 1]))) { + w0 = (fx) * (fy); + tv += v0 * w0; + tw += w0; + } + } + if (tw != 0) { + output[oi] = (float) (tv / tw); + } + } + } + + return output; - MathTransform mt; - try { - mt = concatenateTransforms(transforms); - } catch (FactoryException e1) { - // TODO: log - return output; - } - - double[] coord = new double[2]; - - /* - * Output index. Assumes we iterate top-left to bottom-right in - * row-major order. - */ - int oi = 0; - for (int y = 0; y < targetHeight; ++y) { - for (int x = 0; x < targetWidth; ++x, ++oi) { - coord[0] = x; - coord[1] = y; - try { - mt.transform(coord, 0, coord, 0, 1); - } catch (TransformException e) { - continue; - } - - // Integer cell coordinates of upper-left cell of the 2x2 cell sample area - int sulx = (int) coord[0]; - int suly = (int) coord[1]; - - double fx = coord[0] - sulx; - double fy = coord[1] - suly; - - double tv = 0; // sum of weighted valid values - double tw = 0; // sum of valid weights - float v0; - double w0; - if (sulx >= 0 && suly >= 0 && sulx < sourceWidth - 1 - && suly < sourceHeight - 1) { - if (valid(v0 = fix(sourceData[suly][sulx]))) { - w0 = (1-fx)*(1-fy); - tv += v0 * w0; - tw += w0; - } - if (valid(v0 = fix(sourceData[suly][sulx+1]))) { - w0 = (fx)*(1-fy); - tv += v0 * w0; - tw += w0; - } - if (valid(v0 = fix(sourceData[suly+1][sulx]))) { - w0 = (1-fx)*(fy); - tv += v0 * w0; - tw += w0; - } - if (valid(v0 = fix(sourceData[suly+1][sulx+1]))) { - w0 = (fx)*(fy); - tv += v0 * w0; - tw += w0; - } - } else { - if (isValidCoord(sulx, suly, sourceWidth, sourceHeight) - && valid(v0 = fix(sourceData[suly][sulx]))) { - w0 = (1-fx)*(1-fy); - tv += v0 * w0; - tw += w0; - } - if (isValidCoord(sulx + 1, suly, sourceWidth, sourceHeight) - && valid(v0 = fix(sourceData[suly][sulx+1]))) { - w0 = (fx)*(1-fy); - tv += v0 * w0; - tw += w0; - } - if (isValidCoord(sulx, suly + 1, sourceWidth, sourceHeight) - && valid(v0 = fix(sourceData[suly+1][sulx]))) { - w0 = (1-fx)*(fy); - tv += v0 * w0; - tw += w0; - } - if (isValidCoord(sulx + 1, suly + 1, sourceWidth, sourceHeight) - && valid(v0 = fix(sourceData[suly+1][sulx+1]))) { - w0 = (fx)*(fy); - tv += v0 * w0; - tw += w0; - } - } - if (tw != 0) { - output[oi] = (float) (tv / tw); - } - } - } - - return output; - } - + private static final boolean isValidCoord(int ulx, int uly, int nx, int ny) { - return ulx >= 0 && uly >= 0 && ulx < nx && uly < ny; + return ulx >= 0 && uly >= 0 && ulx < nx && uly < ny; } private static final boolean valid(float v) { - return ! Float.isNaN(v) && v > DATA_FILL; + return !Float.isNaN(v) && v > DATA_FILL; } - + // A1: passes N -9999 to test_grhi_remap, setting // all source -9999 values to 0. private static float fix(float v) { - return v > DATA_FILL ? v : 0; + return v > DATA_FILL ? v : 0; } - - private MathTransform concatenateTransforms(ArrayList transforms) throws FactoryException { - Hints hints = new Hints(); - final CoordinateOperationFactory factory = - ReferencingFactoryFinder.getCoordinateOperationFactory(hints); - final MathTransformFactory mtFactory; - if (factory instanceof AbstractCoordinateOperationFactory) { - mtFactory = ((AbstractCoordinateOperationFactory) factory).getMathTransformFactory(); - } else { - mtFactory = ReferencingFactoryFinder.getMathTransformFactory(hints); - } - - MathTransform mt = null; - for (MathTransform mti : transforms/*int i = 0; i < transforms.size(); ++i*/) { - if (mt == null) - mt = mti; - else { - mt = mtFactory.createConcatenatedTransform(mt, mti); - } - } - - return mt != null ? mt : IdentityTransform.create(2); + + private MathTransform concatenateTransforms( + ArrayList transforms) throws FactoryException { + Hints hints = new Hints(); + final CoordinateOperationFactory factory = ReferencingFactoryFinder + .getCoordinateOperationFactory(hints); + final MathTransformFactory mtFactory; + if (factory instanceof AbstractCoordinateOperationFactory) { + mtFactory = ((AbstractCoordinateOperationFactory) factory) + .getMathTransformFactory(); + } else { + mtFactory = ReferencingFactoryFinder.getMathTransformFactory(hints); + } + + MathTransform mt = null; + for (MathTransform mti : transforms/* + * int i = 0; i < transforms.size(); + * ++i + */) { + if (mt == null) + mt = mti; + else { + mt = mtFactory.createConcatenatedTransform(mt, mti); + } + } + + return mt != null ? mt : IdentityTransform.create(2); } - + /** * Reads the raw data from the topo files * @@ -1091,46 +1025,42 @@ public class StaticTopoData { * @param ny * The y axis points * @return The generated geometry + * @throws TransformException + * @throws MismatchedDimensionException + * @throws FactoryException * @throws GribException * If the geometry cannot be created */ private GridGeometry2D createGridGeometry(CoordinateReferenceSystem crs, Coordinate llCoord, Coordinate urCoord, int nx, int ny) - throws GribException { - try { - MathTransform WGS84toPROJCRS = MapUtil.getTransformFromLatLon(crs); + throws MismatchedDimensionException, TransformException, + FactoryException { + MathTransform WGS84toPROJCRS = MapUtil.getTransformFromLatLon(crs); - GeneralEnvelope envelope = new GeneralEnvelope(2); + GeneralEnvelope envelope = new GeneralEnvelope(2); - DirectPosition ll = WGS84toPROJCRS.transform(new DirectPosition2D( - llCoord.x, llCoord.y), null); + DirectPosition ll = WGS84toPROJCRS.transform(new DirectPosition2D( + llCoord.x, llCoord.y), null); - DirectPosition ur = WGS84toPROJCRS.transform(new DirectPosition2D( - urCoord.x, urCoord.y), null); + DirectPosition ur = WGS84toPROJCRS.transform(new DirectPosition2D( + urCoord.x, urCoord.y), null); - envelope.setRange(0, - Math.min(ll.getOrdinate(0), ur.getOrdinate(0)), - Math.max(ll.getOrdinate(0), ur.getOrdinate(0))); - envelope.setRange(1, - Math.min(ll.getOrdinate(1), ur.getOrdinate(1)), - Math.max(ll.getOrdinate(1), ur.getOrdinate(1))); + envelope.setRange(0, Math.min(ll.getOrdinate(0), ur.getOrdinate(0)), + Math.max(ll.getOrdinate(0), ur.getOrdinate(0))); + envelope.setRange(1, Math.min(ll.getOrdinate(1), ur.getOrdinate(1)), + Math.max(ll.getOrdinate(1), ur.getOrdinate(1))); - envelope.setCoordinateReferenceSystem(crs); - - GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(); - mapper.setEnvelope(envelope); - mapper.setGridRange(new GeneralGridEnvelope( - new int[] { 1, 1 }, new int[] { nx, ny }, false)); - mapper.setPixelAnchor(PixelInCell.CELL_CENTER); - mapper.setReverseAxis(new boolean[] { false, true }); - MathTransform mt = mapper.createTransform(); + envelope.setCoordinateReferenceSystem(crs); - return new GridGeometry2D(PixelInCell.CELL_CORNER, mt, envelope, - null); + GridToEnvelopeMapper mapper = new GridToEnvelopeMapper(); + mapper.setEnvelope(envelope); + mapper.setGridRange(new GeneralGridEnvelope(new int[] { 1, 1 }, + new int[] { nx, ny }, false)); + mapper.setPixelAnchor(PixelInCell.CELL_CENTER); + mapper.setReverseAxis(new boolean[] { false, true }); + MathTransform mt = mapper.createTransform(); - } catch (Exception e) { - throw new GribException("Error creating grid geometry", e); - } + return new GridGeometry2D(PixelInCell.CELL_CORNER, mt, envelope, null); } /** @@ -1148,21 +1078,18 @@ public class StaticTopoData { * @param maxY * The endgin y offset * @return The extracted slab of data - * @throws GribException + * @throws StorageException + * @throws FileNotFoundException * If the data slab cannot be read */ private float[] getSlab(String name, int minX, int minY, int maxX, int maxY) - throws GribException { - try { - return ((FloatDataRecord) sTopoDataStore.retrieve( - "/", - name, - Request.buildSlab(new int[] { minX, minY }, new int[] { - maxX, maxY }))).getFloatData(); - } catch (Exception e) { - throw new GribException( - "Error retrieving static topo data slab from HDF5", e); - } + throws FileNotFoundException, StorageException { + return ((FloatDataRecord) sTopoDataStore.retrieve( + "/", + name, + Request.buildSlab(new int[] { minX, minY }, new int[] { maxX, + maxY }))).getFloatData(); + } /** diff --git a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/TopoAttributes.java b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/topo/TopoAttributes.java similarity index 99% rename from edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/TopoAttributes.java rename to edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/topo/TopoAttributes.java index d3ebfee32e..ffe6468b68 100644 --- a/edexOsgi/com.raytheon.edex.plugin.grib/src/com/raytheon/edex/plugin/grib/topo/TopoAttributes.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/src/com/raytheon/uf/edex/plugin/grid/topo/TopoAttributes.java @@ -18,7 +18,7 @@ * further licensing information. **/ -package com.raytheon.edex.plugin.grib.topo; +package com.raytheon.uf.edex.plugin.grid.topo; import java.util.HashMap; import java.util.Map; diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/utility/common_static/base/path/gridPathKeys.xml b/edexOsgi/com.raytheon.uf.edex.plugin.grid/utility/common_static/base/path/gridPathKeys.xml new file mode 100644 index 0000000000..70e44eccb8 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/utility/common_static/base/path/gridPathKeys.xml @@ -0,0 +1,11 @@ + + + + info.datasetId + 0 + + + info.level.masterLevel.name + 0 + + \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.grid/utility/common_static/base/purge/gridPurgeRules.xml b/edexOsgi/com.raytheon.uf.edex.plugin.grid/utility/common_static/base/purge/gridPurgeRules.xml new file mode 100644 index 0000000000..603623b255 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.grid/utility/common_static/base/purge/gridPurgeRules.xml @@ -0,0 +1,723 @@ + + + info.datasetId + + + 2 + + + + ETA + 2 + + + + RUC + 8 + + + + AVN + 2 + + + + LAPS + 30 + + + + NGM + 2 + + + + MRF + 2 + + + + MSAS + 24 + + + + GFS201 + 2 + + + + mrfNH + 2 + + + + GFS213 + 2 + + + + NGM213 + 1 + 00-00:15:00 + + + + NGM202 + 2 + + + + AVN211 + 2 + + + + mesoEta212 + 2 + 00-00:15:00 + + + + mesoEta215 + 2 + 00-00:15:00 + + + + ENSEMBLE + 2 + + + ENSEMBLE37 + 2 + + + ENSEMBLE38 + 2 + + + ENSEMBLE39 + 2 + + + ENSEMBLE40 + 2 + + + ENSEMBLE41 + 2 + + + ENSEMBLE42 + 2 + + + ENSEMBLE43 + 2 + + + ENSEMBLE44 + 2 + + + + ETA212 + 1 + 00-00:15:00 + + + + MRF203 + 3 + + + + AVN203 + 3 + + + + MRF204 + 3 + + + + MRF205 + 3 + + + + NGM207 + 3 + + + + NAM207 + 3 + + + + ECMF-NorthernHemisphere + 2 + + + ECMF1 + 2 + + + ECMF2 + 2 + + + ECMF3 + 2 + + + ECMF4 + 2 + + + ECMF5 + 2 + + + ECMF6 + 2 + + + ECMF7 + 2 + + + ECMF8 + 2 + + + ECMF9 + 2 + + + ECMF10 + 2 + + + ECMF11 + 2 + + + ECMF12 + 2 + + + + UKMET-NorthernHemisphere + 2 + + + UKMET37 + 2 + + + UKMET38 + 2 + + + UKMET39 + 2 + + + UKMET40 + 2 + + + UKMET41 + 2 + + + UKMET42 + 2 + + + UKMET43 + 2 + + + UKMET44 + 2 + + + + AVN-NorthernHemisphere + 2 + + + AVN37 + 2 + + + AVN38 + 2 + + + AVN39 + 2 + + + AVN40 + 2 + + + AVN41 + 2 + + + AVN42 + 2 + + + AVN43 + 2 + + + AVN44 + 2 + + + + GWW233 + 1 + 00-00:15:00 + + + + RFCqpf + 5 + + + + RUC236 + 8 + + + + AVN225 + 3 + + + + WNAWAVE238 + 1 + 00-00:15:00 + + + + mesoEta216 + 1 + 00-00:15:00 + + + + mesoEta217 + 1 + 00-00:15:00 + + + + ETA218 + 1 + 00-00:15:00 + + + + ETA242 + 1 + 00-00:15:00 + + + + HPCqpf + 5 + + + + ENPWAVE253 + 1 + 00-00:15:00 + + + + HPCdelta + 4 + + + + HurWind226 + 4 + + + + CPCoutlook211 + 14 + + + + RTGSSTHR + 2 + + + + NICICE + 2 + + + + DGEX185 + 2 + 00-00:15:00 + + + + HPCGuide + 2 + 00-00:15:00 + + + + GFSGuide + 8 + 00-00:15:00 + + + + GFS212 + 1 + 00-00:15:00 + + + + GFS160 + 1 + 00-00:15:00 + + + + GFS254 + 1 + 00-00:15:00 + + + + GFS161 + 1 + 00-00:15:00 + + + + MPE-Local + 72 + + + + TPCWindProb + 8 + 00-00:15:00 + + + + MOSGuide + 2 + 00-00:15:00 + + + + QPE + 72 + + + QPE-TUA + 72 + + + QPE-ACR + 72 + + + QPE-STR + 72 + + + QPE-RSA + 72 + + + QPE-ORN + 72 + + + QPE-RHA + 72 + + + QPE-KRF + 72 + + + QPE-MSR + 72 + + + QPE-TAR + 72 + + + QPE-PTR + 72 + + + QPE-TIR + 72 + + + QPE-ALR + 72 + + + QPE-FWR + 72 + + + + + OPCWave180 + 8 + 00-00:15:00 + + + + OPCWave181 + 8 + 00-00:15:00 + + + + OPCWave182 + 8 + 00-00:15:00 + + + + RTMA + 24 + 00-00:15:00 + + + + SREF212 + 2 + 00-00:15:00 + + + + RTGSST + 2 + 00-00:15:00 + + + + GFSLAMPTstorm + 24 + 00-00:15:00 + + + + ECMWF-HiRes + 2 + 00-00:15:00 + + + + HPCqpfNDFD + 42 + 00-00:15:00 + + + + NamDNG5 + 2 + 00-00:15:00 + + + + TPCSurgeProb + 3 + 00-00:15:00 + + + + HPE + 00-12:00:00 + 00-00:15:00 + + + + BHPE + 00-12:00:00 + 00-00:15:00 + + + + GlobalWave + 1 + 00-00:15:00 + + + + AKWave10 + 1 + 00-00:15:00 + + + + AKWave4 + 1 + 00-00:15:00 + + + + EPWave10 + 1 + 00-00:15:00 + + + + WCWave10 + 1 + 00-00:15:00 + + + + WCWave4 + 1 + 00-00:15:00 + + + + WNAWave10 + 1 + 00-00:15:00 + + + + WNAWave4 + 1 + 00-00:15:00 + + + + MOSGuide-AK + 2 + 00-00:15:00 + + + + HI_RTMA + 24 + + + + HiRes-ARW-East + 2 + 00-00:15:00 + + + + HiRes-ARW-West + 1 + 00-00:15:00 + + + + HiRes-ARW-AK + 1 + 00-00:15:00 + + + + HiRes-ARW-HI + 2 + 00-00:15:00 + + + + HiRes-ARW-SJU + 1 + 00-00:15:00 + + + + HiRes-NMM-East + 2 + 00-00:15:00 + + + + HiRes-NMM-West + 1 + 00-00:15:00 + + + + HiRes-NMM-AK + 1 + 00-00:15:00 + + + + HiRes-NMM-HI + 2 + 00-00:15:00 + + + + HiRes-NMM-SJU + 1 + 00-00:15:00 + + + + GRLKwave + 1 + 00-00:15:00 + + + + CPCoutlook-Short + 5 + 00-00:15:00 + + + + CPCoutlook-Medium + 7 + 00-00:15:00 + + + + CPCoutlook-Short-AK + 5 + 00-00:15:00 + + + + CPCoutlook-Medium-AK + 7 + 00-00:15:00 + + + + SPCGuide + 5 + 00-00:15:00 + + diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/MANIFEST.MF index efc77f8c3e..db55acc1af 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/MANIFEST.MF @@ -7,7 +7,9 @@ Bundle-Vendor: RAYTHEON Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Require-Bundle: com.raytheon.uf.edex.auth;bundle-version="1.12.2", com.raytheon.uf.common.auth;bundle-version="1.12.2", - com.raytheon.uf.common.plugin.nwsauth;bundle-version="1.0.0" + com.raytheon.uf.common.plugin.nwsauth;bundle-version="1.0.0", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + com.raytheon.uf.common.localization Import-Package: com.raytheon.uf.common.localization, com.raytheon.uf.common.serialization, com.raytheon.uf.common.status, diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject deleted file mode 100644 index c7bd175870..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/META-INF/services/com.raytheon.uf.common.serialization.ISerializableObject +++ /dev/null @@ -1,2 +0,0 @@ -com.raytheon.uf.edex.plugin.nwsauth.roles.NwsRole -com.raytheon.uf.edex.plugin.nwsauth.roles.NwsRoleData \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/res/spring/nwsauth-request.xml b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/res/spring/nwsauth-request.xml index 6ca9f69189..8157f3b3f6 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/res/spring/nwsauth-request.xml +++ b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/res/spring/nwsauth-request.xml @@ -4,7 +4,7 @@ http://activemq.apache.org/schema/core http://activemq.apache.org/schema/core/activemq-core.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> - + diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/NwsRoleStorage.java b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/NwsRoleStorage.java new file mode 100644 index 0000000000..08988dd73e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/NwsRoleStorage.java @@ -0,0 +1,140 @@ +package com.raytheon.uf.edex.plugin.nwsauth; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import com.raytheon.uf.common.auth.exception.AuthorizationException; +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.plugin.nwsauth.exception.RoleApplicationNotFoundException; +import com.raytheon.uf.common.plugin.nwsauth.xml.NwsRoleData; +import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.edex.auth.roles.IRoleStorage; + +/** + * Implementation of IRoleStorage + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * May 25, 2010            rgeorge     Initial creation
+ * 
+ * 
+ * + * @author rgeorge + * @version 1.0 + */ +public class NwsRoleStorage implements IRoleStorage { + private static NwsRoleStorage instance = null; + + private final Map lastUsedFileMap = new HashMap(); + + private final Map lastModificationTimeMap = new HashMap(); + + private final Map applicationRoleMap = new HashMap(); + + /** + * This is called from the CAVE side for the User Administration dialogs. Do + * not call this from EDEX, use AuthManager instead + * + * @return Instance of NwsRoleStorage + */ + public static NwsRoleStorage getInstance() { + if (instance == null) { + instance = new NwsRoleStorage(); + } + + return instance; + } + + private NwsRoleStorage() { + getRoleDataFiles(); + } + + private synchronized void getRoleDataFiles() { + IPathManager pm = PathManagerFactory.getPathManager(); + + // Check COMMON_STATIC base and site levels + LocalizationContext[] contexts = new LocalizationContext[2]; + contexts[0] = pm.getContext(LocalizationType.COMMON_STATIC, LocalizationLevel.BASE); + contexts[1] = pm.getContext(LocalizationType.COMMON_STATIC, LocalizationLevel.SITE); + + String[] extensions = new String[] { ".xml" }; + LocalizationFile[] localizationFiles = + PathManagerFactory.getPathManager().listFiles(contexts, "roles", extensions, true, true); + + File file = null; + for (LocalizationFile locFile : localizationFiles) { + NwsRoleData roleData = new NwsRoleData(); + if (locFile.exists()) { + file = locFile.getFile(); + + if (lastUsedFileMap.get(locFile.getName()) == null + || (file != null && (file.equals(lastUsedFileMap.get(locFile.getName())) == false || file + .lastModified() > lastModificationTimeMap.get(locFile.getName())))) { + // First time we found a role file, or we have a different + // file to + // use or we were modified since our last check + lastUsedFileMap.put(locFile.getName(), file); + try { + roleData = (NwsRoleData) SerializationUtil.jaxbUnmarshalFromXmlFile(file.getAbsolutePath()); + applicationRoleMap.put(roleData.getApplication(), roleData); + } catch (Exception e) { + UFStatus.getHandler().handle(Priority.PROBLEM, "Error loading file: " + file.getName(), e); + } + + lastModificationTimeMap.put(locFile.getName(), file.lastModified()); + } + } + } + } + + /** + * Get the role/permission data for the application specified. + * + * @param application + * The application + * + * @return the NWSRoleData object for that application. + */ + public NwsRoleData getRoleData(String application) + throws AuthorizationException { + getRoleDataFiles(); + NwsRoleData roleData = applicationRoleMap.get(application); + if (roleData == null) { + throw new RoleApplicationNotFoundException("Application name, \"" + + application + + "\", was not found in the authorization configuration."); + } + return roleData; + } + + /* + * (non-Javadoc) + * + * @see + * com.raytheon.uf.common.plugin.nwsauth.roles.IRoleStorage#isAuthorized + * (java.lang.String, java.lang.String, java.lang.String) + */ + @Override + public boolean isAuthorized(String permission, String user, + String application) throws AuthorizationException { + NwsRoleData roleData = getRoleData(application); + return roleData.isAuthorized(permission, user); + } + + @Override + public String[] getAllDefinedPermissions(String application) + throws AuthorizationException { + return getRoleData(application).getAllDefinedPermissions(); + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRole.java b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRole.java deleted file mode 100644 index bcbc2193c2..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRole.java +++ /dev/null @@ -1,138 +0,0 @@ -package com.raytheon.uf.edex.plugin.nwsauth.roles; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; - -import com.raytheon.uf.common.auth.user.IUser; -import com.raytheon.uf.common.plugin.nwsauth.user.UserId; -import com.raytheon.uf.edex.auth.roles.IRole; - -/** - * Implementation of IRole - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * May 25, 2010            rgeorge     Initial creation
- * 
- * 
- * - * @author rgeorge - * @version 1.0 - */ -@XmlAccessorType(XmlAccessType.NONE) -public class NwsRole implements IRole { - private static final UserId ALL = new UserId("ALL"); - - @XmlAttribute - private String roleId; - - private NwsRole parentRole; - - private Set users = new HashSet(); - - private Set subRoles = new HashSet(); - - @XmlElement(name = "user") - public void setUserIdCollection(UserId[] userIds) { - users = new HashSet(Arrays.asList(userIds)); - } - - public UserId[] getUserIdCollection() { - return users.toArray(new UserId[users.size()]); - } - - @XmlElement(name = "subRole") - public void setSubRolesCollection(String[] subRoles) { - this.subRoles = new HashSet(Arrays.asList(subRoles)); - } - - public String[] getSubRolesCollection() { - return subRoles.toArray(new String[subRoles.size()]); - } - - public String getRoleId() { - return roleId; - } - - public void setRoleId(String roleId) { - this.roleId = roleId; - } - - public void setParentRole(NwsRole parent) { - this.parentRole = parent; - } - - /** - * @param userRolesMap - */ - public void addRolesForUsers(Map userRolesMap) { - for (String subRoleId : subRoles) { - NwsRole subRole = userRolesMap.get(subRoleId.toLowerCase()); - if (subRole != null) { - subRole.setParentRole(this); - subRole.addRolesForUsers(userRolesMap); - } - } - } - - @Override - public boolean validForUser(IUser user) { - if (user != null) { - if (users.contains(ALL)) { - return true; - } - for (UserId id : users) { - if (id.equals(user.uniqueId())) { - return true; - } - } - } - - if (parentRole != null && parentRole.validForUser(user)) { - return true; - } - - return false; - } - - @Override - public String toString() { - return this.roleId; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((roleId == null) ? 0 : roleId.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - NwsRole other = (NwsRole) obj; - if (roleId == null) { - if (other.roleId != null) - return false; - } else if (!roleId.equals(other.roleId)) - return false; - return true; - } - -} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRoleData.java b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRoleData.java deleted file mode 100644 index bf3237db6a..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRoleData.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.raytheon.uf.edex.plugin.nwsauth.roles; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.bind.JAXBException; -import javax.xml.bind.annotation.XmlAccessType; -import javax.xml.bind.annotation.XmlAccessorType; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import com.raytheon.uf.common.serialization.ISerializableObject; -import com.raytheon.uf.common.serialization.SerializationUtil; -import com.raytheon.uf.edex.core.EdexException; - -@XmlRootElement -@XmlAccessorType(XmlAccessType.NONE) -public class NwsRoleData implements ISerializableObject { - - private Map userRolesMap; - - private List allRoles = new ArrayList(); - - public NwsRole lookupRole(String roleId) { - if (userRolesMap == null) { - userRolesMap = new HashMap(); - for (NwsRole role : allRoles) { - userRolesMap.put(role.getRoleId().toLowerCase(), role); - } - - for (NwsRole role : allRoles) { - role.addRolesForUsers(userRolesMap); - } - } - return userRolesMap.get(("" + roleId).toLowerCase()); - } - - public NwsRole[] getAllRolesCollection() { - return this.allRoles.toArray(new NwsRole[this.allRoles.size()]); - } - - @XmlElement(name = "role") - public void setAllRolesCollection(NwsRole[] allRolesArray) { - this.allRoles = new ArrayList(Arrays.asList(allRolesArray)); - } - - public String toXML() throws EdexException { - try { - return SerializationUtil.marshalToXml(this); - } catch (JAXBException e) { - throw new EdexException("", e); - } - } - - public static NwsRoleData loadRoleData(File file) throws EdexException { - try { - return (NwsRoleData) SerializationUtil - .jaxbUnmarshalFromXmlFile(file.getAbsolutePath()); - } catch (Exception e) { - e.printStackTrace(); - throw new EdexException("", e); - } - } - - public void storeRoleData(File file) throws EdexException { - try { - if (file != null) { - SerializationUtil.jaxbMarshalToXmlFile(this, - file.getAbsolutePath()); - } - } catch (Exception e) { - e.printStackTrace(); - throw new EdexException("", e); - } - } -} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRoleStorage.java b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRoleStorage.java deleted file mode 100644 index daeb760b7e..0000000000 --- a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/src/com/raytheon/uf/edex/plugin/nwsauth/roles/NwsRoleStorage.java +++ /dev/null @@ -1,110 +0,0 @@ -package com.raytheon.uf.edex.plugin.nwsauth.roles; - -import java.io.File; -import java.util.Map; - -import com.raytheon.uf.common.localization.LocalizationContext; -import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; -import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; -import com.raytheon.uf.common.localization.LocalizationFile; -import com.raytheon.uf.common.localization.PathManagerFactory; -import com.raytheon.uf.common.status.IUFStatusHandler; -import com.raytheon.uf.common.status.UFStatus; -import com.raytheon.uf.common.status.UFStatus.Priority; -import com.raytheon.uf.edex.auth.roles.IRole; -import com.raytheon.uf.edex.auth.roles.IRoleStorage; -import com.raytheon.uf.edex.core.EdexException; - -/** - * Implementation of IRoleStorage - * - *
- * 
- * SOFTWARE HISTORY
- * Date         Ticket#    Engineer    Description
- * ------------ ---------- ----------- --------------------------
- * May 25, 2010            rgeorge     Initial creation
- * 
- * 
- * - * @author rgeorge - * @version 1.0 - */ -public class NwsRoleStorage implements IRoleStorage { - private static final transient IUFStatusHandler statusHandler = UFStatus - .getHandler(NwsRoleStorage.class); - - private static final NwsRole DEFAULT_ROLE = new NwsRole(); - - private static final LocalizationLevel BASE = LocalizationContext.LocalizationLevel.BASE; - - private static final LocalizationType EDEX_STATIC = LocalizationContext.LocalizationType.EDEX_STATIC; - - private static final String ROLES_FILE_NAME = "roles" + File.separator - + "userRoles.xml"; - - private NwsRoleData roleData = null; - - private File lastUsedFile = null; - - private long lastModificationTime = 0; - - private synchronized NwsRoleData getRoleData() { - Map fileMap = PathManagerFactory - .getPathManager().getTieredLocalizationFile( - LocalizationType.EDEX_STATIC, ROLES_FILE_NAME); - LocalizationLevel[] levels = PathManagerFactory.getPathManager() - .getAvailableLevels(); - - File file = null; - // reverse search for file to get highest level - for (int i = levels.length - 1; i >= 0; --i) { - LocalizationFile locFile = fileMap.get(levels[i]); - if (locFile != null && locFile.exists()) { - file = locFile.getFile(); - break; - } - } - - if (file == null && lastUsedFile == null) { - // No file found and lastFile wasn't set before, default - roleData = new NwsRoleData(); - } else if (lastUsedFile == null - || (file != null && (file.equals(lastUsedFile) == false || file - .lastModified() > lastModificationTime))) { - // First time we found a role file, or we have a different file to - // use or we were modified since our last check - lastUsedFile = file; - try { - roleData = NwsRoleData.loadRoleData(file); - } catch (EdexException e) { - UFStatus.getHandler().handle(Priority.PROBLEM, - "Error loading NWS Roles file", e); - roleData = new NwsRoleData(); - } - lastModificationTime = file.lastModified(); - } - - return roleData; - } - - @Override - public boolean isDefaultRole(IRole role) { - return role == DEFAULT_ROLE; - } - - @Override - public IRole lookupRole(String roleId) { - if (roleId != null && "".equals(roleId) == false) { - NwsRoleData roleData = getRoleData(); - NwsRole role = roleData.lookupRole(roleId); - if (role == null) { - return DEFAULT_ROLE; - } - return role; - } - - return DEFAULT_ROLE; - } - -} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/utility/common_static/base/roles/userRoles.xml b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/utility/common_static/base/roles/userRoles.xml new file mode 100644 index 0000000000..67ab28709d --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.nwsauth/utility/common_static/base/roles/userRoles.xml @@ -0,0 +1,124 @@ + + + Localization + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + com.raytheon.localization.site/common_static/purge + com.raytheon.localization.site/cave_static/colormaps + com.raytheon.localization.site/cave_static/ffmp + com.raytheon.localization.site/cave_static/fog + com.raytheon.localization.site/common_static/fog + com.raytheon.localization.site/cave_static/safeseas + com.raytheon.localization.site/common_static/safeseas + com.raytheon.localization.site/cave_static/snow + com.raytheon.localization.site/common_static/snow + com.raytheon.localization.site/cave_static/scan + com.raytheon.localization.site/cave_static/aviation/config + com.raytheon.localization.site/cave_static/aviation/tmp + com.raytheon.localization.site/cave_static/monitorIcons + com.raytheon.localization.site/cave_static/alertViz + com.raytheon.localization.site/common_static/hydro + com.raytheon.localization.site/common_static/gfe + com.raytheon.localization.site/cave_static/gfe/comboData + com.raytheon.localization.site/cave_static/gfe + com.raytheon.localization.site/common_static/isc + com.raytheon.localization.user/common_static/gfe + com.raytheon.localization.user/cave_static/gfe + com.raytheon.localization.site/common_static/ffmp + com.raytheon.localization.site/common_static/scan + com.raytheon.localization.site/common_static/monitoring + com.raytheon.localization.site/cave_static/scan/config/trendSets/CellTrendSets.xml + com.raytheon.localization.site/cave_static/aviation/avnwatch + com.raytheon.localization.site/common_static/radar/rmr/rmrAvailableRequests.xml + com.raytheon.localization.site/common_static/shef + com.raytheon.localization.site/common_static/roles + + + diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.qpf/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.qpf/META-INF/MANIFEST.MF index a8fc6ddddd..f3a7c2645c 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.qpf/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.plugin.qpf/META-INF/MANIFEST.MF @@ -9,22 +9,16 @@ Require-Bundle: com.raytheon.uf.common.monitor;bundle-version="1.0.0", com.raytheon.edex.common;bundle-version="1.11.1", org.apache.commons.logging;bundle-version="1.0.4", com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.1";resolution:=optional, - org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.dataplugin.qpf, - com.raytheon.uf.common.geospatial;bundle-version="1.0.0", com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.0.0", com.raytheon.uf.common.monitor.cpg;bundle-version="1.0.0", - org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.status;bundle-version="1.12.1152", - com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", com.raytheon.uf.common.dataplugin.scan;bundle-version="1.12.1174", com.raytheon.uf.edex.dat.utils;bundle-version="1.12.1174", com.raytheon.uf.edex.plugin.scan;bundle-version="1.12.1174" -Import-Package: com.raytheon.edex.plugin.grib.dao, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.edex.plugin.scan.common, - javax.measure.unit +Import-Package: com.raytheon.uf.common.dataplugin.grid, + com.raytheon.uf.edex.plugin.scan.common Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.edex.plugin.qpf, diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.qpf/src/com/raytheon/uf/edex/plugin/qpf/common/QPFConfig.java b/edexOsgi/com.raytheon.uf.edex.plugin.qpf/src/com/raytheon/uf/edex/plugin/qpf/common/QPFConfig.java index 13adfcd0a9..08f76976b7 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.qpf/src/com/raytheon/uf/edex/plugin/qpf/common/QPFConfig.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.qpf/src/com/raytheon/uf/edex/plugin/qpf/common/QPFConfig.java @@ -29,7 +29,7 @@ import java.util.TimeZone; import com.raytheon.edex.urifilter.URIFilter; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.qpf.QPFUtils; import com.raytheon.uf.common.dataplugin.radar.RadarRecord; import com.raytheon.uf.common.dataplugin.radar.RadarStation; @@ -541,10 +541,10 @@ public class QPFConfig { int interval = 1440; - GribRecord modelURec = DATUtils.getMostRecentGribRecord(interval, + GridRecord modelURec = DATUtils.getMostRecentGridRecord(interval, U700Product.getSQL(interval, U700Product.U700), paramXMLU); - GribRecord modelVRec = DATUtils.getMostRecentGribRecord(interval, + GridRecord modelVRec = DATUtils.getMostRecentGridRecord(interval, V700Product.getSQL(interval, V700Product.V700), paramXMLV); if (modelURec != null && modelVRec != null) { diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.scan/META-INF/MANIFEST.MF index 4cfca35953..8b6ba6eafc 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/META-INF/MANIFEST.MF @@ -6,31 +6,21 @@ Bundle-Version: 1.12.1174.qualifier Bundle-Vendor: RAYTHEON Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Eclipse-RegisterBuddy: com.raytheon.edex.common, com.raytheon.uf.common.serialization, com.raytheon.uf.viz.core -Require-Bundle: com.raytheon.uf.common.dataplugin;bundle-version="1.11.26", - com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.11.26", - com.raytheon.uf.common.dataplugin.bufrua;bundle-version="1.11.26", +Require-Bundle: com.raytheon.uf.common.dataplugin.binlightning;bundle-version="1.11.26", com.raytheon.uf.common.dataplugin.scan;bundle-version="1.11.26", - org.geotools;bundle-version="2.5.8", - com.raytheon.uf.common.geospatial;bundle-version="1.11.26", com.raytheon.uf.common.monitor;bundle-version="1.11.26", com.raytheon.uf.common.monitor.cpg;bundle-version="1.0.0", com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.1";resolution:=optional, - com.raytheon.uf.common.time;bundle-version="1.11.26", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.26", + com.raytheon.uf.common.dataplugin.grid, com.raytheon.edex.common;bundle-version="1.11.26", org.apache.commons.logging, com.raytheon.uf.common.status, - com.raytheon.edex.plugin.grib;bundle-version="1.11.26", com.raytheon.uf.common.dataplugin.level;bundle-version="1.11.31", - com.raytheon.uf.edex.plugin.ffmp;bundle-version="1.11.31", com.raytheon.uf.common.sounding;bundle-version="1.12.1112", - com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0", - com.raytheon.edex.plugin.radar;bundle-version="1.12.1174" + com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0" Export-Package: com.raytheon.uf.edex.plugin.scan, com.raytheon.uf.edex.plugin.scan.process Import-Package: com.raytheon.uf.common.localization, - com.raytheon.uf.common.menus, - com.raytheon.uf.common.menus.xml, com.raytheon.uf.edex.dat.utils, com.raytheon.uf.edex.plugin.scan.common, javax.measure.converter, diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/res/spring/scan-common.xml b/edexOsgi/com.raytheon.uf.edex.plugin.scan/res/spring/scan-common.xml index 98c9f456cd..affa790ef3 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/res/spring/scan-common.xml +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/res/spring/scan-common.xml @@ -18,7 +18,7 @@
+ depends-on="radarRegistered,bufruaRegistered,gridRegistered"> diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/ScanURIFilter.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/ScanURIFilter.java index 3be6735acb..cfe48c426e 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/ScanURIFilter.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/ScanURIFilter.java @@ -36,7 +36,7 @@ import com.raytheon.edex.urifilter.URIFilter; import com.raytheon.edex.urifilter.URIGenerateMessage; import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.radar.RadarRecord; import com.raytheon.uf.common.dataplugin.scan.data.CellTableData; import com.raytheon.uf.common.dataplugin.scan.data.DMDTableData; @@ -506,7 +506,7 @@ public class ScanURIFilter extends URIFilter { if ((message != null) && (message.getDataURIs().length > 0)) { for (String dataUri : message.getDataURIs()) { // check for the needed data types - if (dataUri.startsWith("/grib") || dataUri.startsWith("/radar") + if (dataUri.startsWith("/grid") || dataUri.startsWith("/radar") || dataUri.startsWith("/binlightning") || dataUri.startsWith("/bufrua")) { // add your pattern checks to the key @@ -763,13 +763,13 @@ public class ScanURIFilter extends URIFilter { * @return * @throws Exception */ - private GribRecord getRecordGrib(String guri) throws Exception { + private GridRecord getRecordGrib(String guri) throws Exception { - GribRecord grib = null; + GridRecord grib = null; try { if (!guri.isEmpty()) { - grib = DATUtils.getGribRecord(guri); + grib = DATUtils.getGridRecord(guri); } } catch (Exception e) { @@ -827,13 +827,13 @@ public class ScanURIFilter extends URIFilter { /** * Set Grib Record in Model Data */ - public void setGribRecord(String prodType, String guri) { + public void setGridRecord(String prodType, String guri) { String modelName = site.getModelParameter(prodType).getModelName(); try { scan.getCache().getModelData() - .setGribRecord(modelName, prodType, getRecordGrib(guri)); + .setGridRecord(modelName, prodType, getRecordGrib(guri)); } catch (Exception e) { logger.debug("Grib record setter failed....."); } @@ -842,13 +842,13 @@ public class ScanURIFilter extends URIFilter { /** * Set Grib Record in Model Data */ - public void setGribRecord(String prodType, GribRecord rec) { + public void setGridRecord(String prodType, GridRecord rec) { String modelName = site.getModelParameter(prodType).getModelName(); try { scan.getCache().getModelData() - .setGribRecord(modelName, prodType, rec); + .setGridRecord(modelName, prodType, rec); } catch (Exception e) { logger.debug("Grib record setter failed....."); } @@ -866,50 +866,50 @@ public class ScanURIFilter extends URIFilter { /** * Set Grib Record in Model Data */ - public void setGribRecords() { + public void setGridRecords() { try { - GribRecord[] records = { null, null, null, null, null, null, null, + GridRecord[] records = { null, null, null, null, null, null, null, null }; - records = getGribRecords(); + records = getGridRecords(); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(CAPEProduct.cape) .getModelName(), CAPEProduct.cape, records[0]); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(HELIProduct.heli) .getModelName(), HELIProduct.heli, records[1]); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(U500Product.U500) .getModelName(), U500Product.U500, records[2]); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(U700Product.U700) .getModelName(), U700Product.U700, records[3]); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(V700Product.V700) .getModelName(), V700Product.V700, records[4]); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(GH500Product.GH500) .getModelName(), GH500Product.GH500, records[5]); scan.getCache() .getModelData() - .setGribRecord( + .setGridRecord( site.getModelParameter(GH1000Product.GH1000) .getModelName(), GH1000Product.GH1000, records[6]); @@ -921,12 +921,12 @@ public class ScanURIFilter extends URIFilter { /** * Get Grib Record from Model Data */ - public GribRecord getGribRecord(String prodType) { - GribRecord rec = null; + public GridRecord getGridRecord(String prodType) { + GridRecord rec = null; String modelName = site.getModelParameter(prodType).getModelName(); try { rec = scan.getCache().getModelData() - .getGribRecord(modelName, prodType); + .getGridRecord(modelName, prodType); } catch (Exception e) { logger.debug("No Grib Data available....."); } @@ -1022,7 +1022,7 @@ public class ScanURIFilter extends URIFilter { * to retrieve the data from a database. */ public void init() { - setGribRecords(); + setGridRecords(); setSoundingRecord(ScanProduct.UA, ""); } @@ -1101,25 +1101,25 @@ public class ScanURIFilter extends URIFilter { * * @return */ - public GribRecord[] getGribRecords() throws PluginException { + public GridRecord[] getGridRecords() throws PluginException { - GribRecord[] records = { null, null, null, null, null, null, null, null }; + GridRecord[] records = { null, null, null, null, null, null, null, null }; try { String[] modelUris = getModelSQL(); // CAPE - records[0] = DATUtils.getGribRecord(modelUris[0]); + records[0] = DATUtils.getGridRecord(modelUris[0]); // HELI - records[1] = DATUtils.getGribRecord(modelUris[1]); + records[1] = DATUtils.getGridRecord(modelUris[1]); // U500 - records[2] = DATUtils.getGribRecord(modelUris[2]); + records[2] = DATUtils.getGridRecord(modelUris[2]); // U700 - records[3] = DATUtils.getGribRecord(modelUris[3]); + records[3] = DATUtils.getGridRecord(modelUris[3]); // V700 - records[4] = DATUtils.getGribRecord(modelUris[4]); + records[4] = DATUtils.getGridRecord(modelUris[4]); // GH500 - records[5] = DATUtils.getGribRecord(modelUris[5]); + records[5] = DATUtils.getGridRecord(modelUris[5]); // GH1000 - records[6] = DATUtils.getGribRecord(modelUris[6]); + records[6] = DATUtils.getGridRecord(modelUris[6]); } catch (Exception e) { logger.error("No Grib record(s) found....."); } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CAPEProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CAPEProduct.java index 85e23f7d1e..47810616ea 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CAPEProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CAPEProduct.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -31,7 +31,7 @@ import com.raytheon.uf.common.monitor.config.SCANRunSiteConfigurationManager; import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables; import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; -public class CAPEProduct extends ScanProduct { +public class CAPEProduct extends GridProduct { /** * @@ -59,10 +59,10 @@ public class CAPEProduct extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(CAPEProduct.cape, uri); - grib = filter.getGribRecord(CAPEProduct.cape); + filter.setGridRecord(CAPEProduct.cape, uri); + grib = filter.getGridRecord(CAPEProduct.cape); } catch (Exception e) { e.printStackTrace(); } @@ -72,20 +72,20 @@ public class CAPEProduct extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(cape, rec); + filter.setGridRecord(cape, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -108,11 +108,8 @@ public class CAPEProduct extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile(uriSeparator + GRIB + uriSeparator + wildCard - + uriSeparator + model + uriSeparator + cape + uriSeparator - + "SFC" + uriSeparator + "0.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, cape, "SFC", "0.0", + Level.getInvalidLevelValueAsString()); } /** @@ -122,16 +119,7 @@ public class CAPEProduct extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "CAPE" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'SFC' and levelonevalue = '0.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc limit 1"; + return getGridSQL(interval, model, cape, "SFC", "0.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CompositeReflectivityProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CompositeReflectivityProduct.java index fc6662cb58..64264f0506 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CompositeReflectivityProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/CompositeReflectivityProduct.java @@ -65,14 +65,12 @@ import com.raytheon.uf.edex.core.EDEXUtil; *
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
- * ------------ --------- ---------- --------------------------
- * 05/07/2009   2037      dhladky     Initial Creation.
- * 02/22/2012	DR14414	  mgamazay    Added initializing the ScanTableData table
- * 									  to an empty map if no features are present.
- * 09/06/2012	14727	  Xiaochuan	  setIsNew(false) for the storm id should based  	
- * 									  on FCSTRAN, FCSTDIR values.
- * 11/13/2012	14368	  Xiaochuan	  Required to set alarm time in a quiet time period 
- * 									  from the last event to new event (new storm come in).
+ * ------------ ---------- ----------- --------------------------
+ * 05/07/2009   2037      dhladky    Initial Creation.
+ * 02/22/2012	DR14414	  mgamazay   Added initializing the ScanTableData table
+ * 									 to an empty map if no features are present.
+ * 09/06/2012	14727	  Xiaochuan	 setIsNew(false) for the storm id should based  	
+ * 									 on FCSTRAN, FCSTDIR values.	 
  * 
  * 
* @@ -218,7 +216,7 @@ public class CompositeReflectivityProduct extends RadarProduct { if (previousTime == null) { previousTime = rec.getDataTime().getRefTime(); } - + if (alarms != null && newIds.size() > 0 && previousTime != null) { if (((alarms.getCellAlarmTime() * 60 * 1000) <= (rec .getDataTime().getRefTime().getTime() - previousTime @@ -229,8 +227,8 @@ public class CompositeReflectivityProduct extends RadarProduct { alarmString.append("NEW cell for " + filter.icao + " over the last " + alarms.getCellAlarmTime() + " minutes."); + previousTime = rec.getDataTime().getRefTime(); } - previousTime = rec.getDataTime().getRefTime(); } // add new rows last for (String id : newIds) { diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/DigitalMesoCycloneTabularProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/DigitalMesoCycloneTabularProduct.java index 9ff0131ee6..93f92a3b72 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/DigitalMesoCycloneTabularProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/DigitalMesoCycloneTabularProduct.java @@ -55,11 +55,8 @@ import com.raytheon.uf.edex.core.EDEXUtil; *
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
- * ------------ -------- ----------  --------------------------
- * 05/07/2009   2037      dhladky     Initial Creation.
- * 11/13/2012	14368	  Xiaochuan	  Required to set alarm time in a quiet time period 
- * 									  from the last event to new event (new storm come in).
- * 
+ * ------------ ---------- ----------- --------------------------
+ * 05/07/2009   2037      dhladky    Initial Creation.
  * 
  * 
* @@ -147,12 +144,13 @@ public class DigitalMesoCycloneTabularProduct extends RadarProduct { } else { for (String fid : getDeletions(dmdKeys, table)) { table.removeRow(fid); + // System.out.println("Removed DMD fid: " + fid); } for (String fid : getUpdates(dmdKeys, table)) { table.updateRow(fid, write(table.getRow(fid), rec, fid)); - + // System.out.println("Updating DMD fid: " + fid); } } } @@ -175,8 +173,8 @@ public class DigitalMesoCycloneTabularProduct extends RadarProduct { alarmString.append("NEW DMDcirculation for " + filter.icao + " over the last " + alarms.getDmdAlarmTime() + " minutes."); + previousTime = rec.getDataTime().getRefTime(); } - previousTime = rec.getDataTime().getRefTime(); } for (String fid : newIds) { diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH1000Product.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH1000Product.java index a687682681..4d7ad4a5cc 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH1000Product.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH1000Product.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -47,7 +47,7 @@ import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; * @version 1.0 */ -public class GH1000Product extends ScanProduct { +public class GH1000Product extends GridProduct { private static final long serialVersionUID = 1L; @@ -72,12 +72,12 @@ public class GH1000Product extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(GH1000, uri); + filter.setGridRecord(GH1000, uri); // statusHandler.handle(Priority.INFO, "MATCHED " + GH1000 // + " MODEL URI: " + uri); - grib = filter.getGribRecord(GH1000); + grib = filter.getGridRecord(GH1000); } catch (Exception e) { e.printStackTrace(); } @@ -87,20 +87,20 @@ public class GH1000Product extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(GH1000, rec); + filter.setGridRecord(GH1000, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -129,11 +129,8 @@ public class GH1000Product extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile("^" + uriSeparator + GRIB + uriSeparator - + wildCard + uriSeparator + model + uriSeparator + "GH" - + uriSeparator + "MB" + uriSeparator + "1000.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, "GH", "MB", "1000.0", + Level.getInvalidLevelValueAsString()); } /** @@ -142,17 +139,8 @@ public class GH1000Product extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "GH" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'MB' and levelonevalue = '1000.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc" + " limit 1"; + return getGridSQL(interval, model, "GH", "MB", "1000.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH500Product.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH500Product.java index 6e7660855b..ac41d746db 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH500Product.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GH500Product.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -47,7 +47,7 @@ import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; * @version 1.0 */ -public class GH500Product extends ScanProduct { +public class GH500Product extends GridProduct { private static final long serialVersionUID = 1L; @@ -72,12 +72,12 @@ public class GH500Product extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(GH500, uri); + filter.setGridRecord(GH500, uri); // statusHandler.handle(Priority.INFO, "MATCHED " + GH500 // + " MODEL URI: " + uri); - grib = filter.getGribRecord(GH500); + grib = filter.getGridRecord(GH500); } catch (Exception e) { e.printStackTrace(); } @@ -87,20 +87,20 @@ public class GH500Product extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(GH500, rec); + filter.setGridRecord(GH500, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -129,11 +129,8 @@ public class GH500Product extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile("^" + uriSeparator + GRIB + uriSeparator - + wildCard + uriSeparator + model + uriSeparator + "GH" - + uriSeparator + "MB" + uriSeparator + "500.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, "GH", "MB", "500.0", + Level.getInvalidLevelValueAsString()); } /** @@ -142,17 +139,8 @@ public class GH500Product extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "GH" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'MB' and levelonevalue = '500.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc" + " limit 1"; + return getGridSQL(interval, model, "GH", "MB", "500.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GridProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GridProduct.java new file mode 100644 index 0000000000..f6416befcc --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/GridProduct.java @@ -0,0 +1,124 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.plugin.scan.process; + +import java.util.regex.Pattern; + +import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables; +import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; + +/** + * + * TODO Add Description + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 2, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public abstract class GridProduct extends ScanProduct { + + private static final long serialVersionUID = 1L; + + public static String GRID = "grid"; + + public GridProduct(String uri, ScanTables tableType, ScanURIFilter filter) { + super(uri, tableType, filter); + } + + protected static Pattern getGridPattern(String dataset, String parameter, + String levelName, String levelOne, String levelTwo) { + // Format = + // /pluginName/time/datasetId/secondaryId/locationName/parameterAbbr/levelName/levelOne/levelTwo/perturbation + StringBuilder pattern = new StringBuilder("^"); + // pluginName + pattern.append(uriSeparator); + pattern.append(GRID); + // dataTime + pattern.append(uriSeparator); + pattern.append(wildCard); + // datasetId + pattern.append(uriSeparator); + pattern.append(dataset); + // secondaryId + pattern.append(uriSeparator); + pattern.append(".*"); + // locationName + pattern.append(uriSeparator); + pattern.append(".*"); + // parameterAbbr + pattern.append(uriSeparator); + pattern.append(parameter); + // levelName + pattern.append(uriSeparator); + pattern.append(levelName); + // levelOne + pattern.append(uriSeparator); + pattern.append(levelOne); + // levelTwo + pattern.append(uriSeparator); + pattern.append(levelTwo); + // perturbation + pattern.append(uriSeparator); + pattern.append("null"); + return Pattern.compile(pattern.toString()); + + } + + /** + * The SQL for MODEL 500 thickness + * + * @return + */ + public static String getGridSQL(int interval, String dataset, + String parameter, String levelName, String levelOne, String levelTwo) { + StringBuilder sql = new StringBuilder( + "select grid.datauri from grid, grid_info, level where"); + sql.append(" grid.info_id = grid_info.id"); + sql.append(" and"); + // datasetId + sql.append(" grid_info.datasetId = \'" + dataset + "\'"); + sql.append(" and"); + // parameterAbbreviation + sql.append(" grid_info.parameter_abbreviation = \'" + parameter + "\'"); + sql.append(" and"); + // level + sql.append(" level.id = grid_info.level_id"); + sql.append(" and"); + sql.append(" level.masterlevel_name = \'" + levelName + "\'"); + sql.append(" and"); + sql.append(" level.levelonevalue = \'" + levelOne + "\'"); + sql.append(" and"); + sql.append(" level.leveltwovalue = \'" + levelTwo + "\'"); + // interval + sql.append("and reftime > (now()- interval \'" + interval + + " minutes\')"); + sql.append(" order by forecasttime desc" + " limit 1"); + return sql.toString(); + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/HELIProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/HELIProduct.java index 35a955ffe2..d321836cc4 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/HELIProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/HELIProduct.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -47,7 +47,7 @@ import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; * @version 1.0 */ -public class HELIProduct extends ScanProduct { +public class HELIProduct extends GridProduct { /** * */ @@ -74,12 +74,12 @@ public class HELIProduct extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(HELIProduct.heli, uri); + filter.setGridRecord(HELIProduct.heli, uri); // statusHandler.handle(Priority.INFO, "MATCHED " + heli // + " MODEL URI: " + uri); - grib = filter.getGribRecord(HELIProduct.heli); + grib = filter.getGridRecord(HELIProduct.heli); } catch (Exception e) { e.printStackTrace(); } @@ -89,20 +89,20 @@ public class HELIProduct extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(heli, rec); + filter.setGridRecord(heli, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -125,11 +125,8 @@ public class HELIProduct extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile("^" + uriSeparator + GRIB + uriSeparator - + wildCard + uriSeparator + model + uriSeparator + "Heli" - + uriSeparator + "SFC" + uriSeparator + "0.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, "Heli", "SFC", "0.0", + Level.getInvalidLevelValueAsString()); } /** @@ -139,16 +136,7 @@ public class HELIProduct extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "Heli" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'SFC' and levelonevalue = '0.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc limit 1"; + return getGridSQL(interval, model, "Heli", "SFC", "0.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/MesoCycloneTabularProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/MesoCycloneTabularProduct.java index 3c4ae305ce..b8e1fc7b7e 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/MesoCycloneTabularProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/MesoCycloneTabularProduct.java @@ -55,14 +55,13 @@ import com.vividsolutions.jts.geom.Coordinate; *
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
- * ------------ -------- ----------- --------------------------
- * 05/07/2009   2037     dhladky     Initial Creation.
- * 02/23/2012	14536	 Xiaochuan	 Add method getIdsFromGraphicBlock() to 
- * 									 hold the ids that have the same order   
- * 									 as the ids in source file.
- * 11/13/2012	14368	 Xiaochuan	 Required to set alarm time in a quiet time period 
- * 									 from the last event to new event (new storm come in).
- * 
+ * ------------ ---------- ----------- --------------------------
+ * 05/07/2009   2037       dhladky      Initial Creation.
+ * 02/23/2012	14536	   Xiaochuan	Add method getIdsFromGraphicBlock() to 
+ * 										hold the ids that have the same order   
+ * 										as the ids in source file.
+ *
+ *
  * 
* * @author dhladky @@ -133,12 +132,12 @@ public class MesoCycloneTabularProduct extends RadarProduct { + " over the last " + alarms.getMesoAlarmTime() + " minutes."); + previousTime = rec.getDataTime().getRefTime(); + EDEXUtil.sendMessageAlertViz(Priority.SIGNIFICANT, RadarConstants.PLUGIN_ID, SCAN, "RADAR", alarmString.toString(), null, null); } - previousTime = rec.getDataTime().getRefTime(); - } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/ScanProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/ScanProduct.java index 3b3c1cb93d..10e5aeea04 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/ScanProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/ScanProduct.java @@ -27,11 +27,10 @@ import java.util.List; import org.geotools.referencing.GeodeticCalculator; -import com.raytheon.edex.plugin.grib.dao.GribDao; import com.raytheon.uf.common.dataplugin.PluginException; import com.raytheon.uf.common.dataplugin.binlightning.BinLightningRecord; import com.raytheon.uf.common.dataplugin.binlightning.impl.LtgStrikeType; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; import com.raytheon.uf.common.dataplugin.radar.RadarRecord; @@ -50,6 +49,7 @@ import com.raytheon.uf.common.monitor.scan.ScanUtils; import com.raytheon.uf.common.monitor.scan.config.SCANConfigEnums.ScanTables; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.database.plugin.PluginDao; import com.raytheon.uf.edex.database.plugin.PluginFactory; import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; import com.vividsolutions.jts.geom.Coordinate; @@ -93,8 +93,6 @@ public abstract class ScanProduct implements Serializable { public static String BINLIGHTNING = "binlightning"; - public static String GRIB = "grib"; - public static String UA = "bufrua"; public static GeometryFactory factory = new GeometryFactory(); @@ -252,12 +250,12 @@ public abstract class ScanProduct implements Serializable { * @param uri * @return */ - public static GribRecord getGribRecord(String uri) throws PluginException { + public static GridRecord getGridRecord(String uri) throws PluginException { - GribRecord gr = new GribRecord(uri); - GribDao gd = (GribDao) PluginFactory.getInstance().getPluginDao( + GridRecord gr = new GridRecord(uri); + PluginDao gd = PluginFactory.getInstance().getPluginDao( gr.getPluginName()); - gr = (GribRecord) gd.getMetadata(uri); + gr = (GridRecord) gd.getMetadata(uri); IDataStore dataStore = gd.getDataStore(gr); try { @@ -283,8 +281,7 @@ public abstract class ScanProduct implements Serializable { * @param table */ public static void processLightning(ScanURIFilter filter, - RadarRecord radarRecord, - Date startTime, Date stopTime, + RadarRecord radarRecord, Date startTime, Date stopTime, ScanTableData table) { if (table.getTableData().size() > 0) { @@ -308,9 +305,9 @@ public abstract class ScanProduct implements Serializable { for (BinLightningRecord rec : recs) { for (int i = 0; i < rec.getLatitudes().length; i++) { // check the time first - long obsTime = rec.getObsTimes()[i]; - if (obsTime >= startTime.getTime() && - obsTime < stopTime.getTime()) { + long obsTime = rec.getObsTimes()[i]; + if (obsTime >= startTime.getTime() + && obsTime < stopTime.getTime()) { Coordinate strikeCoor = new Coordinate( rec.getLongitudes()[i], rec.getLatitudes()[i], 0.0); diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/TVSTabularProduct.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/TVSTabularProduct.java index 1f324cabae..7b125659d4 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/TVSTabularProduct.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/TVSTabularProduct.java @@ -49,10 +49,8 @@ import com.raytheon.uf.edex.core.EDEXUtil; *
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
- * ------------ -------- ----------  --------------------------
- * 05/07/2009   2037     dhladky      Initial Creation.
- * 11/13/2012	14368	 Xiaochuan	  Required to set alarm time in a quiet time period 
- * 									  from the last event to new event (new storm come in).
+ * ------------ ---------- ----------- --------------------------
+ * 05/07/2009   2037      dhladky    Initial Creation.
  * 
  * 
* @@ -140,9 +138,9 @@ public class TVSTabularProduct extends RadarProduct { EDEXUtil.sendMessageAlertViz(Priority.CRITICAL, RadarConstants.PLUGIN_ID, SCAN, "RADAR", alarmString.toString(), null, null); - + + previousTime = rec.getDataTime().getRefTime(); } - previousTime = rec.getDataTime().getRefTime(); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U500Product.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U500Product.java index 991bb7121c..64249d530e 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U500Product.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U500Product.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -47,7 +47,7 @@ import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; * @version 1.0 */ -public class U500Product extends ScanProduct { +public class U500Product extends GridProduct { private static final long serialVersionUID = 1L; @@ -72,12 +72,12 @@ public class U500Product extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(U500, uri); + filter.setGridRecord(U500, uri); // statusHandler.handle(Priority.INFO, "MATCHED " + U500 // + " MODEL URI: " + uri); - grib = filter.getGribRecord(U500); + grib = filter.getGridRecord(U500); } catch (Exception e) { e.printStackTrace(); } @@ -87,20 +87,20 @@ public class U500Product extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(U500, rec); + filter.setGridRecord(U500, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -129,11 +129,8 @@ public class U500Product extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile("^" + uriSeparator + GRIB + uriSeparator - + wildCard + uriSeparator + model + uriSeparator + "uW" - + uriSeparator + "MB" + uriSeparator + "500.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, "uW", "MB", "500.0", + Level.getInvalidLevelValueAsString()); } /** @@ -143,17 +140,8 @@ public class U500Product extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "uW" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'MB' and levelonevalue = '500.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc" + " limit 1"; + return getGridSQL(interval, model, "uW", "MB", "500.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U700Product.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U700Product.java index 2503735634..ef2cb01b6e 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U700Product.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/U700Product.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -47,7 +47,7 @@ import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; * @version 1.0 */ -public class U700Product extends ScanProduct { +public class U700Product extends GridProduct { private static final long serialVersionUID = 1L; @@ -72,12 +72,12 @@ public class U700Product extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(U700, uri); + filter.setGridRecord(U700, uri); // statusHandler.handle(Priority.INFO, "MATCHED " + U700 // + " MODEL URI: " + uri); - grib = filter.getGribRecord(U700); + grib = filter.getGridRecord(U700); } catch (Exception e) { e.printStackTrace(); } @@ -87,20 +87,20 @@ public class U700Product extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(U700, rec); + filter.setGridRecord(U700, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -129,11 +129,8 @@ public class U700Product extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile("^" + uriSeparator + GRIB + uriSeparator - + wildCard + uriSeparator + model + uriSeparator + "uW" - + uriSeparator + "MB" + uriSeparator + "700.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, "uW", "MB", "700.0", + Level.getInvalidLevelValueAsString()); } /** @@ -142,17 +139,8 @@ public class U700Product extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "uW" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'MB' and levelonevalue = '700.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc" + " limit 1"; + return getGridSQL(interval, model, "uW", "MB", "700.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/V700Product.java b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/V700Product.java index 268dcb1714..6ac5e2709a 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/V700Product.java +++ b/edexOsgi/com.raytheon.uf.edex.plugin.scan/src/com/raytheon/uf/edex/plugin/scan/process/V700Product.java @@ -22,7 +22,7 @@ package com.raytheon.uf.edex.plugin.scan.process; import java.util.regex.Pattern; import com.raytheon.uf.common.dataplugin.PluginException; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import com.raytheon.uf.common.dataplugin.level.Level; import com.raytheon.uf.common.dataplugin.persist.PersistableDataObject; import com.raytheon.uf.common.dataplugin.persist.PersistablePluginDataObject; @@ -47,7 +47,7 @@ import com.raytheon.uf.edex.plugin.scan.ScanURIFilter; * @version 1.0 */ -public class V700Product extends ScanProduct { +public class V700Product extends GridProduct { private static final long serialVersionUID = 1L; @@ -72,12 +72,12 @@ public class V700Product extends ScanProduct { @Override public PersistablePluginDataObject getRecord() throws PluginException, Exception { - GribRecord grib = null; + GridRecord grib = null; try { - filter.setGribRecord(V700, uri); + filter.setGridRecord(V700, uri); // statusHandler.handle(Priority.INFO, "MATCHED " + V700 // + " MODEL URI: " + uri); - grib = filter.getGribRecord(V700); + grib = filter.getGridRecord(V700); } catch (Exception e) { e.printStackTrace(); } @@ -87,20 +87,20 @@ public class V700Product extends ScanProduct { @Override public void process() throws Exception { - GribRecord rec = null; + GridRecord rec = null; try { - rec = (GribRecord) getRecord(); + rec = (GridRecord) getRecord(); } catch (Exception pe) { pe.printStackTrace(); } if (rec != null) { - filter.setGribRecord(V700, rec); + filter.setGridRecord(V700, rec); } } @Override public void setDataType() { - this.dataType = GRIB; + this.dataType = GRID; } @@ -129,11 +129,8 @@ public class V700Product extends ScanProduct { * @return */ public static Pattern getPattern(String model) { - return Pattern.compile("^" + uriSeparator + GRIB + uriSeparator - + wildCard + uriSeparator + model + uriSeparator + "vW" - + uriSeparator + "MB" + uriSeparator + "700.0" + uriSeparator - + Level.getInvalidLevelValueAsString() + uriSeparator + "null" - + uriSeparator + "null" + uriSeparator + "0"); + return getGridPattern(model, "vW", "MB", "700.0", + Level.getInvalidLevelValueAsString()); } /** @@ -143,17 +140,8 @@ public class V700Product extends ScanProduct { * @return */ public static String getSQL(int interval, String model) { - return "select datauri from grib where modelinfo_id = (select id from grib_models where parameterabbreviation = \'" - + "vW" - + "\' and modelname = \'" - + model - + "\' and level_id = (select id from level where masterlevel_name = 'MB' and levelonevalue = '700.0' and leveltwovalue = " - + "\'" - + Level.getInvalidLevelValueAsString() - + "\'" - + ")) and reftime > (now()- interval \'" - + interval - + " minutes\') order by forecasttime desc" + " limit 1"; + return getGridSQL(interval, model, "vW", "MB", "700.0", + Level.getInvalidLevelValueAsString()); } } diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.vaa/utility/common_static/base/purge/vaaPurgeRules.xml b/edexOsgi/com.raytheon.uf.edex.plugin.vaa/utility/common_static/base/purge/vaaPurgeRules.xml index 4d78875fb9..1182b36c71 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.vaa/utility/common_static/base/purge/vaaPurgeRules.xml +++ b/edexOsgi/com.raytheon.uf.edex.plugin.vaa/utility/common_static/base/purge/vaaPurgeRules.xml @@ -2,5 +2,7 @@ 24 + =00-01:00:00 + 00-01:00:00 diff --git a/edexOsgi/com.raytheon.uf.edex.plugin.vil/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.plugin.vil/META-INF/MANIFEST.MF index 1a964e3e30..ca2692fb21 100644 --- a/edexOsgi/com.raytheon.uf.edex.plugin.vil/META-INF/MANIFEST.MF +++ b/edexOsgi/com.raytheon.uf.edex.plugin.vil/META-INF/MANIFEST.MF @@ -9,16 +9,11 @@ Require-Bundle: com.raytheon.uf.common.monitor;bundle-version="1.0.0", com.raytheon.edex.common;bundle-version="1.11.1", org.apache.commons.logging;bundle-version="1.0.4", com.raytheon.uf.edex.cpgsrv;bundle-version="1.11.1";resolution:=optional, - org.geotools;bundle-version="2.5.2", com.raytheon.uf.common.dataplugin.vil, - com.raytheon.uf.common.geospatial;bundle-version="1.0.0", com.raytheon.uf.common.monitor.cpg;bundle-version="1.0.0", com.raytheon.uf.common.status;bundle-version="1.12.1152", com.raytheon.uf.common.dataplugin.radar;bundle-version="1.0.0" -Import-Package: com.raytheon.edex.plugin.grib.dao, - com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.edex.plugin.scan.common, - javax.measure.unit +Import-Package: com.raytheon.uf.edex.plugin.scan.common Bundle-RequiredExecutionEnvironment: JavaSE-1.6 Bundle-ActivationPolicy: lazy Export-Package: com.raytheon.uf.edex.plugin.vil, diff --git a/edexOsgi/com.raytheon.uf.edex.pointdata/src/com/raytheon/uf/edex/pointdata/PointDataQuery.java b/edexOsgi/com.raytheon.uf.edex.pointdata/src/com/raytheon/uf/edex/pointdata/PointDataQuery.java index 2917a7451d..1646a6ed2a 100644 --- a/edexOsgi/com.raytheon.uf.edex.pointdata/src/com/raytheon/uf/edex/pointdata/PointDataQuery.java +++ b/edexOsgi/com.raytheon.uf.edex.pointdata/src/com/raytheon/uf/edex/pointdata/PointDataQuery.java @@ -63,75 +63,77 @@ import com.raytheon.uf.edex.pointdata.PointDataPluginDao.LevelRequest; public class PointDataQuery { - protected PointDataPluginDao dao; + protected PointDataPluginDao dao; - protected TableQuery tq; + protected TableQuery tq; - protected String[] attribs; + protected String[] attribs; - protected PointDataPluginDao.LevelRequest requestStyle = LevelRequest.NONE; + protected PointDataPluginDao.LevelRequest requestStyle = LevelRequest.NONE; - public PointDataQuery(String plugin) throws DataAccessLayerException, - PluginException { - this.tq = new TableQuery(PluginFactory.getInstance() - .getDatabase(plugin), PluginFactory.getInstance() - .getPluginRecordClass(plugin).getName()); - try { - PluginDao pd = PluginFactory.getInstance().getPluginDao(plugin); - if (!(pd instanceof PointDataPluginDao)) { - throw new PluginException(plugin - + " DAO is not a point data DAO"); - } - this.dao = (PointDataPluginDao) pd; - } catch (Exception e) { - e.printStackTrace(); - throw new DataAccessLayerException( - "Unable to instantiate data access object on database: " - + plugin, e); - } - } + public PointDataQuery(final String plugin) throws DataAccessLayerException, + PluginException { + this.tq = new TableQuery(PluginFactory.getInstance() + .getDatabase(plugin), PluginFactory.getInstance() + .getPluginRecordClass(plugin).getName()); + try { + PluginDao pd = PluginFactory.getInstance().getPluginDao(plugin); + if (!(pd instanceof PointDataPluginDao)) { + throw new PluginException(plugin + + " DAO is not a point data DAO"); + } + this.dao = (PointDataPluginDao) pd; + } catch (Exception e) { + e.printStackTrace(); + throw new DataAccessLayerException( + "Unable to instantiate data access object on database: " + + plugin, e); + } + } - public void setParameters(String params) { - String[] strs = params.split(","); - for (int i = 0; i < strs.length; i++) { - strs[i] = strs[i].trim(); - } - this.attribs = strs; - } + public void setParameters(final String params) { + String[] strs = params.split(","); + for (int i = 0; i < strs.length; i++) { + strs[i] = strs[i].trim(); + } + this.attribs = strs; + } - public void addParameter(String name, String value, String operand) { - if (operand == null) - operand = "="; + public void addParameter(final String name, final String value, + String operand) { + if (operand == null) { + operand = "="; + } - tq.addParameter(name, value, operand); + tq.addParameter(name, value, operand); - } + } - public void requestAllLevels() { - this.requestStyle = LevelRequest.ALL; - } + public void requestAllLevels() { + this.requestStyle = LevelRequest.ALL; + } - public void requestSpecificLevel(String parameter, String vals) { - String[] valList = vals.split(","); - double[] d = new double[valList.length]; - for (int i = 0; i < d.length; i++) { - d[i] = Double.parseDouble(valList[i]); - } + public void requestSpecificLevel(final String parameter, final String vals) { + String[] valList = vals.split(","); + double[] d = new double[valList.length]; + for (int i = 0; i < d.length; i++) { + d[i] = Double.parseDouble(valList[i]); + } - this.requestStyle = LevelRequest.SPECIFIC; - this.requestStyle.setLevels(parameter, d); - } + this.requestStyle = LevelRequest.SPECIFIC; + this.requestStyle.setLevels(parameter, d); + } - public ResponseMessageCatalog getAvailableParameters() throws Exception { + public ResponseMessageCatalog getAvailableParameters() throws Exception { - Set parameters = new HashSet(); + Set parameters = new HashSet(); - PointDataDbDescription dbDesc = dao.getPointDataDbDescription(); - if (dbDesc != null) { - for (DbParameterDescription parameter : dbDesc.parameters) { - parameters.add(parameter.getParameterName()); - } - } + PointDataDbDescription dbDesc = dao.getPointDataDbDescription(); + if (dbDesc != null) { + for (DbParameterDescription parameter : dbDesc.parameters) { + parameters.add(parameter.getParameterName()); + } + } boolean needsDbQuery = false; for (String key : dao.getKeysRequiredForFileName()) { if (!key.equals("dataTime.refTime")) { @@ -165,201 +167,202 @@ public class PointDataQuery { return cat; } - private List> performDbQuery(List fields, - int limit) throws Exception { + private List> performDbQuery(final List fields, + final int limit) throws Exception { - for (String field : fields) { - tq.addReturnedField(field, null); - } - tq.setCount(limit); - List queryResults = tq.execute(); + for (String field : fields) { + tq.addReturnedField(field, null); + } + tq.setCount(limit); + List queryResults = tq.execute(); - List> results = new ArrayList>(); + List> results = new ArrayList>(); - for (Object o : queryResults) { - Map workingMap = new HashMap(); - if (o instanceof Object[]) { - Object[] oArr = (Object[]) o; - for (int i = 0; i < fields.size(); i++) { - workingMap.put(fields.get(i), oArr[i]); - } - } else if (fields.size() == 1) { - workingMap.put(fields.get(0), o); - } - results.add(workingMap); - } + for (Object o : queryResults) { + Map workingMap = new HashMap(); + if (o instanceof Object[]) { + Object[] oArr = (Object[]) o; + for (int i = 0; i < fields.size(); i++) { + workingMap.put(fields.get(i), oArr[i]); + } + } else if (fields.size() == 1) { + workingMap.put(fields.get(0), o); + } + results.add(workingMap); + } - return results; + return results; - } + } - /* - * (non-Javadoc) - * - * @see com.raytheon.edex.uengine.tasks.query.TableQuery#execute() - */ - public PointDataContainer execute() throws Exception { + /* + * (non-Javadoc) + * + * @see com.raytheon.edex.uengine.tasks.query.TableQuery#execute() + */ + public PointDataContainer execute() throws Exception { - List hdf5attribList = new ArrayList(); - HashSet dbAttribSet = new HashSet(); - List dbParamDesc = new ArrayList(); + List hdf5attribList = new ArrayList(); + HashSet dbAttribSet = new HashSet(); + List dbParamDesc = new ArrayList(); - PointDataDbDescription dbDesc = dao.getPointDataDbDescription(); - if (dbDesc == null) { - hdf5attribList.addAll(Arrays.asList(attribs)); - } else { - for (String attrib : attribs) { - DbParameterDescription desc = dbDesc.getDescription(attrib); - if (desc != null) { - dbAttribSet.add(desc.getQueryName()); - dbParamDesc.add(desc); - } else { - hdf5attribList.add(attrib); - } - } - } + PointDataDbDescription dbDesc = dao.getPointDataDbDescription(); + if (dbDesc == null) { + hdf5attribList.addAll(Arrays.asList(attribs)); + } else { + for (String attrib : attribs) { + DbParameterDescription desc = dbDesc.getDescription(attrib); + if (desc != null) { + dbAttribSet.add(desc.getQueryName()); + dbParamDesc.add(desc); + } else { + hdf5attribList.add(attrib); + } + } + } - dbAttribSet.add("id"); - if (!hdf5attribList.isEmpty()) { - dbAttribSet.add("pointDataView.curIdx"); - dbAttribSet.addAll(Arrays.asList(dao.getKeysRequiredForFileName())); - } + dbAttribSet.add("id"); + if (!hdf5attribList.isEmpty()) { + dbAttribSet.add("pointDataView.curIdx"); + dbAttribSet.addAll(Arrays.asList(dao.getKeysRequiredForFileName())); + } - List> dbResults = performDbQuery( - new ArrayList(dbAttribSet), 999999); + List> dbResults = performDbQuery( + new ArrayList(dbAttribSet), 999999); - if (dbResults == null || dbResults.isEmpty()) { - return null; - } + if ((dbResults == null) || dbResults.isEmpty()) { + return null; + } - Map> dbResultMap = new HashMap>(); - PointDataContainer masterPDC = null; + Map> dbResultMap = new HashMap>(); + PointDataContainer masterPDC = null; - if (hdf5attribList.isEmpty()) { - int[] idArr = new int[dbResults.size()]; - for (int j = 0; j < dbResults.size(); j++) { - Map workingMap = dbResults.get(j); - idArr[j] = (Integer) workingMap.get("id"); - dbResultMap.put(idArr[j], workingMap); - } - masterPDC = PointDataContainer - .build(new IDataRecord[] { new IntegerDataRecord("id", "", - idArr) }); - masterPDC.setCurrentSz(masterPDC.getAllocatedSz()); - } else { - List files = new ArrayList(); - List> ids = new ArrayList>(); - List> indexes = new ArrayList>(); + if (hdf5attribList.isEmpty()) { + int[] idArr = new int[dbResults.size()]; + for (int j = 0; j < dbResults.size(); j++) { + Map workingMap = dbResults.get(j); + idArr[j] = (Integer) workingMap.get("id"); + dbResultMap.put(idArr[j], workingMap); + } + masterPDC = PointDataContainer + .build(new IDataRecord[] { new IntegerDataRecord("id", "", + idArr) }); + masterPDC.setCurrentSz(masterPDC.getAllocatedSz()); + } else { + List files = new ArrayList(); + List> ids = new ArrayList>(); + List> indexes = new ArrayList>(); - for (Map workingMap : dbResults) { - int id = (Integer) workingMap.get("id"); - int idx = (Integer) workingMap.get("pointDataView.curIdx"); - dbResultMap.put(id, workingMap); - String fileName = dao.getPointDataFileName(workingMap); - int listIndex = files.indexOf(fileName); - if (listIndex == -1) { - listIndex = files.size(); - files.add(fileName); - ids.add(new ArrayList()); - indexes.add(new ArrayList()); - hdf5attribList.retainAll(Arrays.asList(dao - .getPointDataDescription(workingMap) - .getParameterNames())); - } - ids.get(listIndex).add(id); - indexes.get(listIndex).add(idx); - } - long t0 = System.currentTimeMillis(); - for (int i = 0; i < files.size(); i++) { - File file = new File(files.get(i)); - List attribSet = new ArrayList(hdf5attribList); - int[] idxArr = new int[indexes.get(i).size()]; - int[] idArr = new int[ids.get(i).size()]; - for (int j = 0; j < idArr.length; j++) { - idxArr[j] = indexes.get(i).get(j); - idArr[j] = ids.get(i).get(j); - } - PointDataContainer pdc = dao.getPointData(file, idxArr, idArr, - attribSet.toArray(new String[0]), this.requestStyle); - if (masterPDC == null) { - masterPDC = pdc; - masterPDC.setCurrentSz(masterPDC.getAllocatedSz()); - } else { - masterPDC.combine(pdc); - masterPDC.setCurrentSz(masterPDC.getAllocatedSz()); - } - } - long t1 = System.currentTimeMillis(); - System.out - .println("Total time spent on pointdata hdf5 retrieval (all files): " - + (t1 - t0)); - } + for (Map workingMap : dbResults) { + int id = (Integer) workingMap.get("id"); + int idx = (Integer) workingMap.get("pointDataView.curIdx"); + dbResultMap.put(id, workingMap); + String fileName = dao.getPointDataFileName(workingMap); + int listIndex = files.indexOf(fileName); + if (listIndex == -1) { + listIndex = files.size(); + files.add(fileName); + ids.add(new ArrayList()); + indexes.add(new ArrayList()); + hdf5attribList.retainAll(Arrays.asList(dao + .getPointDataDescription(workingMap) + .getParameterNames())); + } + ids.get(listIndex).add(id); + indexes.get(listIndex).add(idx); + } + long t0 = System.currentTimeMillis(); + for (int i = 0; i < files.size(); i++) { + File file = new File(files.get(i)); + List attribSet = new ArrayList(hdf5attribList); + int[] idxArr = new int[indexes.get(i).size()]; + int[] idArr = new int[ids.get(i).size()]; + for (int j = 0; j < idArr.length; j++) { + idxArr[j] = indexes.get(i).get(j); + idArr[j] = ids.get(i).get(j); + } + PointDataContainer pdc = dao.getPointData(file, idxArr, idArr, + attribSet.toArray(new String[0]), this.requestStyle); + if (masterPDC == null) { + masterPDC = pdc; + masterPDC.setCurrentSz(masterPDC.getAllocatedSz()); + } else { + masterPDC.combine(pdc); + masterPDC.setCurrentSz(masterPDC.getAllocatedSz()); + } + } + long t1 = System.currentTimeMillis(); + System.out + .println("Total time spent on pointdata hdf5 retrieval (all files): " + + (t1 - t0)); + } - if (!dbParamDesc.isEmpty()) { - for (DbParameterDescription desc : dbParamDesc) { - switch (desc.getType()) { - case FLOAT: - float[] fdata = new float[masterPDC.getCurrentSz()]; - FloatDataRecord frec = new FloatDataRecord( - desc.getParameterName(), "", fdata); - if (desc.getFillValue() != null) { - frec.setFillValue(Float.parseFloat(desc.getFillValue())); - } - masterPDC.add(frec, desc.getUnit()); - break; - case INT: - int[] idata = new int[masterPDC.getCurrentSz()]; - masterPDC - .add(new IntegerDataRecord(desc.getParameterName(), - "", idata), desc.getUnit()); - break; - case LONG: - long[] ldata = new long[masterPDC.getCurrentSz()]; - masterPDC.add(new LongDataRecord(desc.getParameterName(), - "", ldata), desc.getUnit()); - break; - case STRING: - String[] sdata = new String[masterPDC.getCurrentSz()]; - masterPDC.add(new StringDataRecord(desc.getParameterName(), - "", sdata), desc.getUnit()); - break; - } - } - for (int i = 0; i < masterPDC.getAllocatedSz(); i++) { - PointDataView pdv = masterPDC.readRandom(i); - Map dbMap = dbResultMap.get(pdv.getInt("id")); - for (DbParameterDescription desc : dbParamDesc) { - Object obj = dbMap.get(desc.getQueryName()); - if (obj == null) { - obj = pdv.getContainer() - .getParameterRecord(desc.getParameterName()) - .getFillValue(); - if (obj == null) { - continue; - } - } - switch (desc.getType()) { - case FLOAT: - pdv.setFloat(desc.getParameterName(), - ((Number) obj).floatValue()); - break; - case INT: + if (!dbParamDesc.isEmpty()) { + for (DbParameterDescription desc : dbParamDesc) { + switch (desc.getType()) { + case FLOAT: + float[] fdata = new float[masterPDC.getCurrentSz()]; + FloatDataRecord frec = new FloatDataRecord( + desc.getParameterName(), "", fdata); + if (desc.getFillValue() != null) { + frec.setFillValue(Float.parseFloat(desc.getFillValue())); + } + masterPDC.add(frec, desc.getUnit()); + break; + case INT: + int[] idata = new int[masterPDC.getCurrentSz()]; + masterPDC + .add(new IntegerDataRecord(desc.getParameterName(), + "", idata), desc.getUnit()); + break; + case LONG: + long[] ldata = new long[masterPDC.getCurrentSz()]; + masterPDC.add(new LongDataRecord(desc.getParameterName(), + "", ldata), desc.getUnit()); + break; + case STRING: + String[] sdata = new String[masterPDC.getCurrentSz()]; + masterPDC.add(new StringDataRecord(desc.getParameterName(), + "", sdata), desc.getUnit()); + break; + } + } + for (int i = 0; i < masterPDC.getAllocatedSz(); i++) { + PointDataView pdv = masterPDC.readRandom(i); + Map dbMap = dbResultMap.get(pdv.getInt("id")); + for (DbParameterDescription desc : dbParamDesc) { + Object obj = dbMap.get(desc.getQueryName()); + if (obj == null) { + obj = pdv.getContainer() + .getParameterRecord(desc.getParameterName()) + .getFillValue(); + if (obj == null) { + continue; + } + } + switch (desc.getType()) { + case FLOAT: + pdv.setFloat(desc.getParameterName(), + ((Number) obj).floatValue()); + break; + case INT: - pdv.setInt(desc.getParameterName(), - ((Number) obj).intValue()); - break; - case LONG: - pdv.setLong(desc.getParameterName(), - ((Number) obj).longValue()); - break; - case STRING: - pdv.setString(desc.getParameterName(), obj.toString()); - break; - } - } - } - } + pdv.setInt(desc.getParameterName(), + ((Number) obj).intValue()); + break; + case LONG: + pdv.setLong(desc.getParameterName(), + ((Number) obj).longValue()); + break; + case STRING: + pdv.setString(desc.getParameterName(), obj.toString()); + break; + } + } + } + } - return masterPDC; - } + return masterPDC; + } } + diff --git a/edexOsgi/com.raytheon.uf.edex.purgesrv/res/spring/purge-spring.xml b/edexOsgi/com.raytheon.uf.edex.purgesrv/res/spring/purge-spring.xml index 5c16e396ed..7bdb3df6e7 100644 --- a/edexOsgi/com.raytheon.uf.edex.purgesrv/res/spring/purge-spring.xml +++ b/edexOsgi/com.raytheon.uf.edex.purgesrv/res/spring/purge-spring.xml @@ -53,7 +53,7 @@ - + @@ -67,7 +67,7 @@ - + @@ -80,7 +80,7 @@ - + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/.classpath b/edexOsgi/com.raytheon.uf.edex.stats/.classpath new file mode 100644 index 0000000000..ad32c83a78 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/.classpath @@ -0,0 +1,7 @@ + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/.project b/edexOsgi/com.raytheon.uf.edex.stats/.project new file mode 100644 index 0000000000..3da103ed13 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/.project @@ -0,0 +1,28 @@ + + + com.raytheon.uf.edex.stats + + + + + + org.eclipse.jdt.core.javabuilder + + + + + org.eclipse.pde.ManifestBuilder + + + + + org.eclipse.pde.SchemaBuilder + + + + + + org.eclipse.pde.PluginNature + org.eclipse.jdt.core.javanature + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/.settings/org.eclipse.jdt.core.prefs b/edexOsgi/com.raytheon.uf.edex.stats/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 0000000000..d9eae69d6f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,8 @@ +#Mon Jun 18 16:45:16 CDT 2012 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/edexOsgi/com.raytheon.uf.edex.stats/META-INF/MANIFEST.MF b/edexOsgi/com.raytheon.uf.edex.stats/META-INF/MANIFEST.MF new file mode 100644 index 0000000000..2c0c6cafe7 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/META-INF/MANIFEST.MF @@ -0,0 +1,26 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Stats +Bundle-SymbolicName: com.raytheon.uf.edex.stats +Bundle-Version: 1.0.0.qualifier +Bundle-Vendor: RAYTHEON +Bundle-RequiredExecutionEnvironment: JavaSE-1.6 +Require-Bundle: com.raytheon.uf.common.serialization;bundle-version="1.12.1174", + com.raytheon.uf.edex.event;bundle-version="1.0.0", + com.raytheon.uf.common.event;bundle-version="1.0.0", + com.google.guava;bundle-version="1.0.0", + com.raytheon.uf.edex.database;bundle-version="1.0.0", + com.raytheon.uf.common.localization;bundle-version="1.12.1174", + com.raytheon.uf.common.dataquery;bundle-version="1.0.0", + com.raytheon.uf.common.time;bundle-version="1.12.1174", + com.raytheon.uf.common.serialization.comm;bundle-version="1.12.1174", + com.raytheon.uf.common.stats;bundle-version="1.0.0", + com.raytheon.uf.common.dataplugin;bundle-version="1.12.1174", + com.raytheon.uf.common.util, + org.springframework;bundle-version="2.5.6", + com.raytheon.uf.edex.core;bundle-version="1.12.1174", + com.raytheon.uf.common.status;bundle-version="1.12.1174", + org.apache.commons.collections;bundle-version="3.2.0", + org.junit, + javax.measure +Import-Package: javax.measure.unit diff --git a/edexOsgi/com.raytheon.uf.edex.stats/build.properties b/edexOsgi/com.raytheon.uf.edex.stats/build.properties new file mode 100644 index 0000000000..5791d48d5f --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/build.properties @@ -0,0 +1,5 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + .,\ + res/ diff --git a/edexOsgi/com.raytheon.uf.edex.stats/res/spring/edex-process-stats.xml b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/edex-process-stats.xml new file mode 100644 index 0000000000..cf2b57d112 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/edex-process-stats.xml @@ -0,0 +1,41 @@ + + + + + + + + + + + + + + + + + + + + + + java.lang.Throwable + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-common.xml b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-common.xml new file mode 100644 index 0000000000..420e3344a1 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-common.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-graph-request.xml b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-graph-request.xml new file mode 100644 index 0000000000..56356ed96c --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-graph-request.xml @@ -0,0 +1,13 @@ + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-request.xml b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-request.xml new file mode 100644 index 0000000000..41e6dd11eb --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/res/spring/stats-request.xml @@ -0,0 +1,19 @@ + + + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/resources/edexProcessStats.properties b/edexOsgi/com.raytheon.uf.edex.stats/resources/edexProcessStats.properties new file mode 100644 index 0000000000..fe31fc60f3 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/resources/edexProcessStats.properties @@ -0,0 +1,4 @@ +# scan interval of stats table in minutes +stats.scanInterval=2 +# bucket interval or period of when to aggregate in minutes +stats.period=5 \ No newline at end of file diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/AggregateManager.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/AggregateManager.java new file mode 100644 index 0000000000..4e914a1b94 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/AggregateManager.java @@ -0,0 +1,340 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats; + +import java.lang.reflect.Method; +import java.util.Calendar; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.TimeZone; + +import com.google.common.collect.ArrayListMultimap; +import com.google.common.collect.Multimap; +import com.raytheon.uf.common.event.Event; +import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.StatsRecord; +import com.raytheon.uf.common.stats.xml.StatisticsAggregate; +import com.raytheon.uf.common.stats.xml.StatisticsEvent; +import com.raytheon.uf.common.stats.xml.StatisticsGroup; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.time.TimeRange; +import com.raytheon.uf.common.time.util.TimeUtil; +import com.raytheon.uf.common.util.CollectionUtil; +import com.raytheon.uf.edex.stats.dao.AggregateRecordDao; +import com.raytheon.uf.edex.stats.dao.StatsDao; +import com.raytheon.uf.edex.stats.util.ConfigLoader; + +/** + * Aggregates stat records based on the statsConfig files and stores them after + * a configured period. + * + * * + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez    Stored the aggregate buckets in the db.
+ * Nov 07, 2012   1317     mpduff      Updated Configuration Files.
+ * Nov 28, 2012   1350     rjpeter     Simplied aggregation and added aggregation with current db aggregate records.
+ * 
+ * + * @author jsanchez + * + */ +public class AggregateManager { + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(AggregateManager.class); + + /** In minutes */ + private int bucketInterval; + + /** default value */ + private static final int defaultBucketInterval = 5; + + /** default value */ + private static final int defaultScanInterval = 15; + + public AggregateManager(String bucketInterval) { + validateIntervals(bucketInterval); + } + + /** + * Aggregates the grouped events and then aggregates them with any matching + * range in DB and stores the updated aggregate. + * + * @param dao + * @param statsEvent + * @param timeRange + * @param groupedEvents + */ + private void aggregate(AggregateRecordDao dao, StatisticsEvent statsEvent, + TimeRange timeRange, Multimap groupedEvents) { + Calendar start = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT")); + start.setTime(timeRange.getStart()); + + Calendar end = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT")); + end.setTime(timeRange.getEnd()); + + // perform aggregate functions on the grouped data + for (String groupKey : groupedEvents.keySet()) { + Collection groupData = groupedEvents.get(groupKey); + Iterator aggrMethodIter = statsEvent.getAggregateMethods() + .iterator(); + Iterator statAggrIter = statsEvent + .getAggregateList().iterator(); + int count = groupData.size(); + + while (aggrMethodIter.hasNext() && statAggrIter.hasNext()) { + String field = statAggrIter.next().getField(); + Method m = aggrMethodIter.next(); + + try { + double max = -Double.MAX_VALUE; + double min = Double.MAX_VALUE; + double sum = 0; + + for (Event event : groupData) { + Number number = (Number) m.invoke(event, new Object[0]); + double value = number.doubleValue(); + sum += value; + if (value > max) { + max = value; + } + + if (value < min) { + min = value; + } + } + + AggregateRecord record = new AggregateRecord( + statsEvent.getType(), start, end, groupKey, field); + record.setSum(sum); + record.setMin(min); + record.setMax(max); + record.setCount(count); + dao.mergeRecord(record); + } catch (Exception e) { + statusHandler.error("Unable to aggregate '" + field + "'", + e); + } + } + } + } + + /** + * Creates a time range from a date and the bucket interval. The time range + * start time that will be the date rounded to the next bucket interval. The + * time range end time will be the start time plus the bucket interval. + * + * @param date + * @return + */ + private TimeRange createTimeRange(Calendar date) { + Calendar start = getBucketStartTime(date); + Calendar end = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + end.setTimeInMillis(start.getTimeInMillis()); + end.add(Calendar.MINUTE, bucketInterval); + + return new TimeRange(start, end); + } + + /** + * Calculates the start time that will be the date rounded to the next + * bucket interval + * + * @param date + * @return + */ + private Calendar getBucketStartTime(Calendar date) { + int currentMinutes = date.get(Calendar.MINUTE); + + int incrementsWithinHour = bucketInterval; + // checks if period is larger than 60 minutes + if (bucketInterval > 60) { + incrementsWithinHour = bucketInterval % 60; + } + + int mod = currentMinutes % incrementsWithinHour; + + Calendar start = Calendar.getInstance(TimeZone.getTimeZone("GMT")); + start.setTimeInMillis(date.getTimeInMillis()); + start.add(Calendar.MINUTE, -mod); + start.set(Calendar.SECOND, 0); + start.set(Calendar.MILLISECOND, 0); + + return start; + } + + /** + * Scans the stats table to be stored in buckets and aggregate if necessary. + */ + public void scan() throws Exception { + long t0 = System.currentTimeMillis(); + ConfigLoader configLoader = ConfigLoader.getInstance(); + StatsDao statsRecordDao = new StatsDao(); + AggregateRecordDao aggrRecordDao = new AggregateRecordDao(); + + Map statsMap = configLoader.getTypeView(); + + // latest time to pull + Calendar timeToProcess = Calendar.getInstance(TimeZone + .getTimeZone("GMT")); + int count = 0; + + // process the events by type + for (Map.Entry entry : statsMap.entrySet()) { + String type = entry.getKey(); + StatisticsEvent event = entry.getValue(); + List records = null; + + do { + // retrieve stats in blocks of 1000 + records = statsRecordDao.retrieveRecords(timeToProcess, type, + 2000); + + if (!CollectionUtil.isNullOrEmpty(records)) { + // sort events into time buckets + Map> timeMap = sort( + event, records); + + for (Map.Entry> timeMapEntry : timeMap + .entrySet()) { + aggregate(aggrRecordDao, event, timeMapEntry.getKey(), + timeMapEntry.getValue()); + } + + try { + statsRecordDao.deleteAll(records); + } catch (Exception e) { + statusHandler.error("Error deleting stat records", e); + } + + count += records.size(); + } + } while (!CollectionUtil.isNullOrEmpty(records)); + } + + long t1 = System.currentTimeMillis(); + statusHandler.info("Aggregated " + count + " stat events in " + + (t1 - t0) + " ms"); + } + + /** + * Sorts the records into time buckets and groups by the underlying Event. + * + * @param records + * @return + */ + private Map> sort( + StatisticsEvent statEvent, List records) { + Map> rval = new HashMap>(); + TimeRange timeRange = null; + Multimap eventsByGroup = null; + final Object[] EMPTY_OBJ_ARR = new Object[0]; + StringBuilder group = new StringBuilder(); + + for (StatsRecord record : records) { + if ((timeRange == null) + || !timeRange.contains(record.getDate().getTime())) { + // Create bucket based on stats record date + timeRange = createTimeRange(record.getDate()); + eventsByGroup = rval.get(timeRange); + if (eventsByGroup == null) { + eventsByGroup = ArrayListMultimap.create(); + rval.put(timeRange, eventsByGroup); + } + } + + try { + // get underlying event + Event event = SerializationUtil.transformFromThrift( + Event.class, record.getEvent()); + + // determine group + boolean addDelim = false; + Iterator gMethodIter = statEvent.getGroupByMethods() + .iterator(); + Iterator gFieldNameIter = statEvent + .getGroupList().iterator(); + group.setLength(0); + + while (gMethodIter.hasNext() && gFieldNameIter.hasNext()) { + Method m = gMethodIter.next(); + String field = gFieldNameIter.next().getName(); + String gVal = String + .valueOf(m.invoke(event, EMPTY_OBJ_ARR)); + + if (addDelim) { + group.append('-'); + } else { + addDelim = true; + } + + group.append(field).append(':').append(gVal); + } + + eventsByGroup.put(group.toString(), event); + } catch (Exception e) { + statusHandler + .error("Error processing event. Aggregation may be inaccurate. ", + e); + } + } + + return rval; + } + + /** + * Tests if the bucket interval is a valid value. If value is invalid then + * value will be set to default value. + * + * @param bucketInt + * @return + */ + private void validateIntervals(String bucketInt) { + try { + bucketInterval = Integer.parseInt(bucketInt); + } catch (NumberFormatException e) { + bucketInterval = defaultBucketInterval; + statusHandler.info("'" + bucketInt + + "' is not a valid bucket interval value. Setting to '" + + defaultBucketInterval + "'"); + } + + int incrementsWithinHour = bucketInterval; + // checks if period is larger than 60 minutes + if (bucketInterval > 60) { + incrementsWithinHour = bucketInterval % 60; + } + if (60 % incrementsWithinHour != 0) { + bucketInterval = defaultBucketInterval; + statusHandler + .info("The bucket interval must go into an hour evenly. Setting bucket interval to '" + + bucketInterval + "'"); + } + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/StatsPurge.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/StatsPurge.java new file mode 100644 index 0000000000..14a9fa4364 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/StatsPurge.java @@ -0,0 +1,189 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats; + +import java.io.File; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.List; +import java.util.TimeZone; + +import javax.xml.bind.JAXBException; + +import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.serialization.SerializationException; +import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.StatsRecord; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.purge.PurgeRule; +import com.raytheon.uf.edex.database.purge.PurgeRuleSet; +import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.stats.util.Archiver; + +/** + * Purges the stats table of expired/unused stat records. Purges the aggregate + * table and write it to disk. + * + * * + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Initial creation.
+ * 
+ * 
+ * + * @author jsanchez + * + */ +public class StatsPurge { + + private static final transient IUFStatusHandler statusHandler = UFStatus + .getHandler(StatsPurge.class); + + private Archiver archiver; + + private final CoreDao aggregateRecordDao = new CoreDao(DaoConfig.forClass( + "metadata", AggregateRecord.class)); + + private final CoreDao statsRecordDao = new CoreDao(DaoConfig.forClass( + "metadata", StatsRecord.class)); + + private final PurgeRuleSet aggregatePurgeRules; + + private final PurgeRuleSet statsPurgeRules; + + public StatsPurge() { + aggregatePurgeRules = readPurgeRules("aggregatePurgeRules.xml"); + statsPurgeRules = readPurgeRules("statsPurgeRules.xml"); + try { + archiver = new Archiver(); + purgeStats(); + } catch (DataAccessLayerException e) { + statusHandler + .error("Error purging stats on start up. Stats will not be purged. ", + e); + } + } + + /** + * Purges records from the aggregate table and writes them to disk. + */ + public void purgeAggregates() throws JAXBException, + DataAccessLayerException { + if (aggregatePurgeRules != null) { + Calendar expiration = Calendar.getInstance(TimeZone + .getTimeZone("GMT")); + DatabaseQuery query = new DatabaseQuery(AggregateRecord.class); + List allRules = new ArrayList(); + + // check for specific rules, if none, apply defaults + if (!aggregatePurgeRules.getRules().isEmpty()) { + allRules.addAll(aggregatePurgeRules.getRules()); + } else if (!aggregatePurgeRules.getDefaultRules().isEmpty()) { + allRules.addAll(aggregatePurgeRules.getDefaultRules()); + } + + for (PurgeRule rule : allRules) { + if (rule.isPeriodSpecified()) { + long ms = rule.getPeriodInMillis(); + int minutes = new Long(ms / (1000 * 60)).intValue(); + expiration.add(Calendar.MINUTE, -minutes); + + query.addQueryParam("endDate", expiration, + QueryOperand.LESSTHAN); + + List objects = aggregateRecordDao.queryByCriteria(query); + + if (!objects.isEmpty()) { + AggregateRecord[] aggregateRecords = new AggregateRecord[objects + .size()]; + + for (int i = 0; i < aggregateRecords.length; i++) { + aggregateRecords[i] = (AggregateRecord) objects + .get(i); + } + archiver.writeToDisk(aggregateRecords); + aggregateRecordDao.deleteAll(objects); + } + } + } + } + } + + /** + * Purges records from the stats table if they are older than the expiration + * time. + */ + private void purgeStats() throws DataAccessLayerException { + if (statsPurgeRules != null) { + Calendar expiration = Calendar.getInstance(TimeZone + .getTimeZone("GMT")); + DatabaseQuery deleteStmt = new DatabaseQuery(StatsRecord.class); + + for (PurgeRule rule : statsPurgeRules.getRules()) { + if (rule.isPeriodSpecified()) { + long ms = rule.getPeriodInMillis(); + int minutes = new Long(ms / (1000 * 60)).intValue(); + expiration.add(Calendar.MINUTE, -minutes); + deleteStmt.addQueryParam("date", expiration, + QueryOperand.LESSTHAN); + statsRecordDao.deleteByCriteria(deleteStmt); + } + } + } + } + + /** + * Reads the purge files. + */ + private PurgeRuleSet readPurgeRules(String xml) { + PurgeRuleSet purgeRules = null; + try { + File file = PathManagerFactory.getPathManager().getStaticFile( + "purge/" + xml); + if (file != null) { + try { + purgeRules = SerializationUtil.jaxbUnmarshalFromXmlFile( + PurgeRuleSet.class, file); + + } catch (SerializationException e) { + statusHandler.error("Error deserializing purge rule " + xml + + "!"); + } + + } else { + statusHandler.error(xml + + " rule not defined!! Data will not be purged."); + } + } catch (Exception e) { + statusHandler.error("Error reading purge file " + xml, e); + } + return purgeRules; + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/dao/AggregateRecordDao.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/dao/AggregateRecordDao.java new file mode 100644 index 0000000000..622ed63451 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/dao/AggregateRecordDao.java @@ -0,0 +1,64 @@ +package com.raytheon.uf.edex.stats.dao; + +import java.util.List; + +import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.util.CollectionUtil; +import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.query.DatabaseQuery; + +public class AggregateRecordDao extends CoreDao { + /** + * Creates a new data access object + */ + public AggregateRecordDao() { + super(DaoConfig.forClass("metadata", AggregateRecord.class)); + } + + /** + * Retrieves stat records that has a date before the limit. + * + * @param limit + * @param eventType + * @param maxResults + * if greater than 0 will limit database results to maxResults + * @return an array of stat records. If an error occurs, then an array of + * size 0 will be returned. + * @throws DataAccessLayerException + */ + @SuppressWarnings("unchecked") + public void mergeRecord(AggregateRecord newRecord) + throws DataAccessLayerException { + DatabaseQuery query = new DatabaseQuery(AggregateRecord.class); + query.addQueryParam("eventType", newRecord.getEventType(), + QueryOperand.EQUALS); + query.addQueryParam("field", newRecord.getField(), QueryOperand.EQUALS); + query.addQueryParam("grouping", newRecord.getGrouping(), + QueryOperand.EQUALS); + query.addQueryParam("startDate", newRecord.getStartDate(), + QueryOperand.EQUALS); + query.addQueryParam("endDate", newRecord.getEndDate(), + QueryOperand.EQUALS); + + List results = (List) queryByCriteria(query); + if (!CollectionUtil.isNullOrEmpty(results)) { + // shouldn't be able to get multiple results, just merge with first + // and update + AggregateRecord prevRecord = results.get(0); + prevRecord.setCount(prevRecord.getCount() + newRecord.getCount()); + prevRecord.setSum(prevRecord.getSum() + newRecord.getSum()); + if (newRecord.getMin() < prevRecord.getMin()) { + prevRecord.setMin(newRecord.getMin()); + } + if (newRecord.getMax() > prevRecord.getMax()) { + prevRecord.setMax(newRecord.getMax()); + } + update(prevRecord); + } else { + persist(newRecord); + } + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/dao/StatsDao.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/dao/StatsDao.java new file mode 100644 index 0000000000..b1e1df0439 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/dao/StatsDao.java @@ -0,0 +1,46 @@ +package com.raytheon.uf.edex.stats.dao; + +import java.util.Calendar; +import java.util.List; + +import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; +import com.raytheon.uf.common.stats.StatsRecord; +import com.raytheon.uf.edex.database.DataAccessLayerException; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.query.DatabaseQuery; + +public class StatsDao extends CoreDao { + /** + * Creates a new data access object + */ + public StatsDao() { + super(DaoConfig.forClass("metadata", StatsRecord.class)); + } + + /** + * Retrieves stat records that has a date before the limit. + * + * @param limit + * @param eventType + * @param maxResults + * if greater than 0 will limit database results to maxResults + * @return an array of stat records. If an error occurs, then an array of + * size 0 will be returned. + * @throws DataAccessLayerException + */ + @SuppressWarnings("unchecked") + public List retrieveRecords(Calendar limit, String eventType, + int maxResults) throws DataAccessLayerException { + DatabaseQuery query = new DatabaseQuery(StatsRecord.class); + query.addQueryParam("eventType", eventType, QueryOperand.EQUALS); + query.addQueryParam("date", limit, QueryOperand.LESSTHAN); + query.addOrder("date", true); + + if (maxResults > 0) { + query.setMaxResults(maxResults); + } + + return (List) queryByCriteria(query); + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/data/StatsDataAccumulator.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/data/StatsDataAccumulator.java new file mode 100644 index 0000000000..c21c31ff5e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/data/StatsDataAccumulator.java @@ -0,0 +1,342 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.data; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.TreeSet; +import java.util.regex.Pattern; + +import com.google.common.annotations.VisibleForTesting; +import com.raytheon.uf.common.serialization.SerializationException; +import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.data.GraphData; +import com.raytheon.uf.common.stats.data.StatsBin; +import com.raytheon.uf.common.stats.data.StatsData; +import com.raytheon.uf.common.stats.data.StatsLabelData; +import com.raytheon.uf.common.stats.util.UnitUtils; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.time.TimeRange; +import com.raytheon.uf.common.time.util.TimeUtil; + +/** + * Accumulates the statistics data. + * + *
+ *
+ * SOFTWARE HISTORY
+ *
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Nov 15, 2012    728     mpduff      Initial creation
+ *
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class StatsDataAccumulator { + private static final Pattern COLON_PATTERN = Pattern.compile(":"); + + private static final Pattern DASH_PATTERN = Pattern.compile("-"); + + private static final String COLON = ":"; + + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(StatsDataAccumulator.class); + + /** List of records */ + private AggregateRecord[] records; + + /** List of groups */ + @VisibleForTesting + List groups; + + /** TimeRange oject */ + private TimeRange timeRange; + + /** Event type */ + private String eventType; + + /** Event data type/attribute */ + private String dataType; + + /** Display unit */ + private String displayUnit; + + /** Data's timestep */ + private long timeStep; + + /** Stats data map */ + @VisibleForTesting + final Map statsDataMap = new HashMap(); + + /** Map of time in ms -> StatsBin objects */ + @VisibleForTesting + final Map bins = new TreeMap(); + + /** Map of group name -> group members */ + @VisibleForTesting + Map> groupMemberMap = new HashMap>(); + + /** + * Set the AggregateRecord[] + * + * @param records + * array of AggregateRecord objects + */ + public void setRecords(AggregateRecord[] records) { + this.records = records; + } + + /** + * Set up the grouping objects. + */ + @VisibleForTesting + public void setupGroupings() { + for (AggregateRecord aggRec : records) { + String grouping = aggRec.getGrouping(); + String[] groupString = DASH_PATTERN.split(grouping); + String group; + String member; + for (String grp : groupString) { + String[] parts = COLON_PATTERN.split(grp); + group = parts[0]; + member = parts[1]; + if (!groupMemberMap.containsKey(group)) { + groupMemberMap.put(group, new TreeSet()); + } + + groupMemberMap.get(group).add(member); + } + } + + groups = new ArrayList(groupMemberMap.keySet()); + } + + /** + * Get the GraphData object + * + * @param groups + * List of groups + * @return The GraphData object + */ + public GraphData getGraphData(List groups) { + // Create the StatsLableData object + // Create the keys (owner:plugin:provider) + // Loop backwards over the data + StatsLabelData prevLabelData = null; + StatsLabelData statsLabelData = null; + UnitUtils unitUtils = new UnitUtils(eventType, dataType); + unitUtils.setDisplayUnit(displayUnit); + + for (int i = groups.size() - 1; i >= 0; i--) { + String group = groups.get(i); + statsLabelData = new StatsLabelData(group, new ArrayList( + groupMemberMap.get(group))); + if (prevLabelData != null) { + statsLabelData.setStatsLabelData(prevLabelData); + } + prevLabelData = statsLabelData; + } + + gather(unitUtils, groups); + + // StatsLabelData is created and holds all the keys + GraphData graphData = new GraphData(); + graphData.setStatsLabelData(statsLabelData); + graphData.setDisplayUnit(displayUnit); + graphData.setStatsDataMap(statsDataMap); + graphData.setTimeRange(timeRange); + graphData.setKeys(new ArrayList(this.statsDataMap.keySet())); + graphData.setUnitUtils(unitUtils); + graphData.setKeySequence(groups); + + return graphData; + } + + /** + * Create the StatsDataMap keys + * + * @param unitUtils + * UnitUtils object + * @param groups + * List of groups + */ + @VisibleForTesting + void createStatsDataMap(UnitUtils unitUtils, List groups) { + Map keySequenceMap = new LinkedHashMap(); + for (String key : groups) { + keySequenceMap.put(key, ""); + } + + String builtKey = ""; + for (AggregateRecord record : records) { + if (record.getEventType().equals(eventType) + && record.getField().equals(dataType)) { + + // Have a matching record + for (String key : keySequenceMap.keySet()) { + keySequenceMap.put(key, ""); + } + String[] groupings = DASH_PATTERN.split(record.getGrouping()); + + for (String grouping : groupings) { + String[] parts = COLON_PATTERN.split(grouping); + String group = parts[0]; + String groupMember = parts[1]; + + for (String key : keySequenceMap.keySet()) { + if (group.equals(key)) { + keySequenceMap.put(key, keySequenceMap.get(key) + .concat(groupMember + COLON)); + break; + } + } + } + + for (String key : keySequenceMap.keySet()) { + builtKey = builtKey.concat(keySequenceMap.get(key)); + } + + if (builtKey.length() != 0) { + // Drop the last ":" + builtKey = builtKey.substring(0, builtKey.length() - 1); + } + + if (!statsDataMap.containsKey(builtKey)) { + statsDataMap.put(builtKey, new StatsData(builtKey, + timeStep, this.timeRange, unitUtils)); + } + + statsDataMap.get(builtKey).addRecord(record); + builtKey = ""; + } + } + } + + /** + * Gather the data together in each bin. + * + * @param unitUtils + * UnitUtils object + * @param groups + * List of groups + */ + @SuppressWarnings("unchecked") + private void gather(UnitUtils unitUtils, List groups) { + createStatsDataMap(unitUtils, groups); + calculateBins(); + for (String key : statsDataMap.keySet()) { + Map newMap = Collections.emptyMap(); + try { + newMap = SerializationUtil.transformFromThrift(Map.class, + SerializationUtil.transformToThrift(bins)); + } catch (SerializationException e) { + statusHandler + .handle(Priority.PROBLEM, + "Error serializing/deserializing StatsBin data. Skipping...", + e); + } + StatsData data = statsDataMap.get(key); + data.setBins(newMap); + data.accumulate(); + statsDataMap.put(key, data); + } + } + + /** + * Calculate the bins for the graph. + */ + @VisibleForTesting + void calculateBins() { + bins.clear(); + + long duration = timeRange.getDuration(); + long startMillis = timeRange.getStart().getTime(); + long numBins = duration / (timeStep * TimeUtil.MILLIS_PER_MINUTE); + for (long i = 0; i < numBins; i++) { + StatsBin sb = new StatsBin(); + sb.setBinMillis(startMillis + + (i * timeStep * TimeUtil.MILLIS_PER_MINUTE)); + bins.put(i, sb); + } + } + + /** + * @param timeRange + * the timeRange to set + */ + public void setTimeRange(TimeRange timeRange) { + this.timeRange = timeRange; + } + + /** + * @return the timeRange + */ + public TimeRange getTimeRange() { + return timeRange; + } + + /** + * @param eventType + * the eventType to set + */ + public void setEventType(String eventType) { + this.eventType = eventType; + } + + /** + * @param dataType + * the dataType to set + */ + public void setDataType(String dataType) { + this.dataType = dataType; + } + + /** + * Set the display units. + * + * @param displayUnit + * the displayUnit to set + */ + public void setDisplayUnits(String displayUnit) { + this.displayUnit = displayUnit; + } + + /** + * TimeStep in minutes + * + * @param timeStep + */ + public void setTimeStep(int timeStep) { + this.timeStep = timeStep; + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/AggregatedStatsHandler.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/AggregatedStatsHandler.java new file mode 100644 index 0000000000..90a3194951 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/AggregatedStatsHandler.java @@ -0,0 +1,98 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.handler; + +import java.util.List; + +import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; +import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.AggregatedStatsRequest; +import com.raytheon.uf.common.stats.AggregatedStatsResponse; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.query.DatabaseQuery; + +/** + * Handles an AggregateStatsRequest and queries the metadata.aggregate table and + * return the results in an AggregateStatsResponse + * + * *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Initial creation.
+ * 
+ * 
+ * + * @author jsanchez + * + */ +public class AggregatedStatsHandler implements + IRequestHandler { + + private CoreDao dao = new CoreDao(DaoConfig.forClass("metadata", + AggregateRecord.class)); + + @Override + public AggregatedStatsResponse handleRequest(AggregatedStatsRequest request) + throws Exception { + DatabaseQuery query = new DatabaseQuery(AggregateRecord.class.getName()); + + // TODO Add a time range implementation + + if (request.getEventType() != null) { + query.addQueryParam("eventType", request.getEventType(), + QueryOperand.EQUALS); + } + + if (request.getGrouping() != null) { + StringBuffer grouping = new StringBuffer(); + for (String group : request.getGrouping()) { + if (grouping.length() > 0) { + grouping.append("-"); + } + grouping.append(group); + } + query.addQueryParam("grouping", grouping, QueryOperand.EQUALS); + } + + if (request.getField() != null) { + query.addQueryParam("field", request.getField(), + QueryOperand.EQUALS); + } + + List results = dao.queryByCriteria(query); + AggregateRecord[] records = new AggregateRecord[results.size()]; + for (int i = 0; i < results.size(); i++) { + if (results.get(i) instanceof AggregateRecord) { + records[i] = (AggregateRecord) results.get(i); + } + } + + AggregatedStatsResponse response = new AggregatedStatsResponse( + request.getTimeRange(), request.getEventType(), + request.getGrouping(), request.getField()); + response.setRecords(records); + + return response; + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/GraphDataHandler.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/GraphDataHandler.java new file mode 100644 index 0000000000..2323a58b02 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/GraphDataHandler.java @@ -0,0 +1,219 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.handler; + +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.TimeZone; + +import com.raytheon.uf.common.dataquery.db.QueryParam.QueryOperand; +import com.raytheon.uf.common.serialization.comm.IRequestHandler; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.stats.GraphDataRequest; +import com.raytheon.uf.common.stats.GraphDataResponse; +import com.raytheon.uf.common.stats.data.GraphData; +import com.raytheon.uf.common.stats.xml.StatisticsAggregate; +import com.raytheon.uf.common.stats.xml.StatisticsConfig; +import com.raytheon.uf.common.stats.xml.StatisticsEvent; +import com.raytheon.uf.common.time.util.TimeUtil; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.database.query.DatabaseQuery; +import com.raytheon.uf.edex.stats.data.StatsDataAccumulator; +import com.raytheon.uf.edex.stats.util.ConfigLoader; + +/** + * Graph Data Request Handler. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Sep 11, 2012   728      mpduff      Initial creation
+ * 
+ * 
+ * + * @author mpduff + * @version 1.0 + */ + +public class GraphDataHandler implements IRequestHandler { + /** Aggregate Record DAO */ + private final CoreDao dao = new CoreDao(DaoConfig.forClass("metadata", + AggregateRecord.class)); + + private static final String START_DATE = "startDate"; + + private static final String END_DATE = "endDate"; + + private static final String EVENT_TYPE = "eventType"; + + private static final String FIELD = "field"; + + private static final String COUNT = "COUNT"; + + /** + * Constructor. + */ + public GraphDataHandler() { + } + + /** + * {@inheritDoc} + */ + @Override + public GraphDataResponse handleRequest(GraphDataRequest request) + throws Exception { + GraphDataResponse response; + + if (request.isMetaDataRequest()) { + response = getMetaData(); + } else { + response = getGraphData(request); + } + + return response; + } + + /** + * Get the statistical configuration objects and add them to the response. + * + * @return GraphDataResponse + * + * @throws Exception + */ + private GraphDataResponse getMetaData() throws Exception { + ConfigLoader loader = ConfigLoader.getInstance(); + loader.load(); + List configList = loader.getConfigurations(); + GraphDataResponse response = new GraphDataResponse(); + response.setConfigList(configList); + + return response; + } + + /** + * Get the Graph Data object and add it to the response. + * + * @param request + * The request object + * @return GraphDataResponse + * @throws Exception + */ + private GraphDataResponse getGraphData(GraphDataRequest request) + throws Exception { + GraphDataResponse response = new GraphDataResponse(); + DatabaseQuery query = new DatabaseQuery(AggregateRecord.class.getName()); + Calendar start = convertToCalendar(request.getTimeRange().getStart()); + Calendar end = convertToCalendar(request.getTimeRange().getEnd()); + query.addQueryParam(START_DATE, start, QueryOperand.GREATERTHANEQUALS); + query.addQueryParam(END_DATE, end, QueryOperand.LESSTHANEQUALS); + + if (request.getEventType() != null) { + query.addQueryParam(EVENT_TYPE, request.getEventType(), + QueryOperand.EQUALS); + } + + if (request.getField() != null) { + query.addQueryParam(FIELD, request.getField(), QueryOperand.EQUALS); + } + + List results = dao.queryByCriteria(query); + + if (!results.isEmpty()) { + List arList = new ArrayList(); + for (int i = 0; i < results.size(); i++) { + if (results.get(i) instanceof AggregateRecord) { + arList.add((AggregateRecord) results.get(i)); + } + } + + String displayUnit = getDisplayUnit(request.getCategory(), + request.getEventType(), request.getDataType()); + + StatsDataAccumulator accum = new StatsDataAccumulator(); + accum.setRecords(arList.toArray(new AggregateRecord[arList.size()])); + accum.setDisplayUnits(displayUnit); + accum.setEventType(request.getEventType()); + accum.setDataType(request.getField()); + accum.setTimeRange(request.getTimeRange()); + accum.setTimeStep(request.getTimeStep()); + accum.setupGroupings(); + + GraphData graphData = accum.getGraphData(request.getGrouping()); + + response.setGraphData(graphData); + } + return response; + } + + /** + * Convert a Date object to Calendar object. + * + * @param date + * @return Calendar object + */ + private Calendar convertToCalendar(Date date) { + Calendar cal = TimeUtil.newCalendar(TimeZone.getTimeZone("GMT")); + cal.setTimeInMillis(date.getTime()); + + return cal; + } + + /** + * Get the display unit. + * + * @param dataType + * @param type + * @param category + * @return The display unit, NONE if no units + */ + private String getDisplayUnit(String category, String type, String dataType) + throws Exception { + ConfigLoader loader = ConfigLoader.getInstance(); + loader.load(); + List configList = loader.getConfigurations(); + + String unit = COUNT; + for (StatisticsConfig config : configList) { + for (String cat : config.getCategories()) { + if (cat.equals(category)) { + for (StatisticsEvent event : config.getEvents()) { + if (event.getType().equals(type)) { + for (StatisticsAggregate agg : event + .getAggregateList()) { + if (agg.getField().equals(dataType)) { + return agg.getDisplayUnit(); + } + } + } + } + } + } + } + + return unit; + } + +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/StatsHandler.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/StatsHandler.java new file mode 100644 index 0000000000..824b7a002e --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/handler/StatsHandler.java @@ -0,0 +1,133 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.handler; + +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import com.google.common.eventbus.AllowConcurrentEvents; +import com.google.common.eventbus.Subscribe; +import com.raytheon.uf.common.event.Event; +import com.raytheon.uf.common.serialization.SerializationException; +import com.raytheon.uf.common.serialization.SerializationUtil; +import com.raytheon.uf.common.stats.StatsRecord; +import com.raytheon.uf.common.stats.xml.StatisticsConfig; +import com.raytheon.uf.common.stats.xml.StatisticsEvent; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.edex.database.dao.CoreDao; +import com.raytheon.uf.edex.database.dao.DaoConfig; +import com.raytheon.uf.edex.event.EventBus; +import com.raytheon.uf.edex.stats.util.ConfigLoader; + +/** + * Subscribes to the event bus and stores them in the appropriate stats table + * + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez    Removed instance variable of event bus.
+ * Nov 07, 2012   1317     mpduff      Updated config files.
+ * 
+ * 
+ * + * @author jsanchez + * + */ +public class StatsHandler { + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(StatsHandler.class); + + private final CoreDao dao = new CoreDao(DaoConfig.forClass("metadata", + StatsRecord.class)); + + private static Set validEventTypes = new HashSet(); + + /** + * Set the valid event types. + * + * @param configurations + * List of StatisticsConfig objects + */ + public static void setValidEventTypes(List configurations) { + validEventTypes = new HashSet(); + for (StatisticsConfig config : configurations) { + for (StatisticsEvent event : config.getEvents()) { + validEventTypes.add(event.getType()); + } + } + } + + /** + * Registers StatsHandler with the event bus + */ + public StatsHandler() throws Exception { + loadEventValidTypes(); + EventBus.getInstance().register(this); + } + + /** + * Loads the stats configuration to determine the events to track. + * + * TODO: Update ConfigLoader to be instance and have file time checking to + * know if config needs to be reloaded. + * + * @throws Exception + */ + protected void loadEventValidTypes() throws Exception { + ConfigLoader configLoader = ConfigLoader.getInstance(); + configLoader.load(); + HashSet myValidEventTypes = new HashSet(); + + for (StatisticsConfig config : configLoader.getConfigurations()) { + for (StatisticsEvent event : config.getEvents()) { + myValidEventTypes.add(event.getType()); + } + } + + validEventTypes = Collections.unmodifiableSet(myValidEventTypes); + } + + @Subscribe + @AllowConcurrentEvents + public void eventListener(Event event) { + String clazz = String.valueOf(event.getClass().getName()); + + if (validEventTypes.contains(clazz)) { + try { + byte[] bytes = SerializationUtil.transformToThrift(event); + + StatsRecord record = new StatsRecord(); + record.setDate(event.getDate()); + record.setEventType(clazz); + record.setEvent(bytes); + dao.persist(record); + + } catch (SerializationException e) { + statusHandler.error("Error transforming to Thrift.", e); + } + } + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/util/Archiver.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/util/Archiver.java new file mode 100644 index 0000000000..9150f940a2 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/util/Archiver.java @@ -0,0 +1,272 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.util; + +import java.io.BufferedWriter; +import java.io.FileWriter; +import java.io.IOException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.regex.Pattern; + +import javax.xml.bind.JAXBException; + +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationLevel; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.stats.AggregateRecord; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.common.time.TimeRange; + +/** + * Archives the data in the aggregate_bucket table to an xml file. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Initial creation.
+ * Nov 09, 2012            dhladky      Changed to CSV output
+ * 
+ * 
+ * + * @author jsanchez + * + */ +public class Archiver { + + private class StatisticsKey { + public String eventType; + + public String grouping; + + public TimeRange timeRange; + + @Override + public boolean equals(Object o) { + if (o != null && o instanceof StatisticsKey) { + StatisticsKey other = (StatisticsKey) o; + + return eventType.equals(other.eventType) + && timeRange.getStart().equals( + other.timeRange.getStart()) + && timeRange.getEnd().equals(other.timeRange.getEnd()); + } + + return false; + } + + @Override + public int hashCode() { + return 1; + } + } + + private static final String COMMA = ","; + + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(Archiver.class); + + private final IPathManager pm = PathManagerFactory.getPathManager(); + + private final LocalizationContext context = pm.getContext( + LocalizationType.COMMON_STATIC, LocalizationLevel.SITE); + + private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss"; + + private static final String FILE_DATE_FORMAT = "yyyyMMdd_HHmm"; + + private static final Pattern PERIOD_PATTERN = Pattern.compile("\\."); + + public Archiver() { + + } + + /** + * Creates a filename in the format /stats/aggregates/group... + * /eventType.start-end.dat + * + * @param items + * @return + */ + private String createFilename(TimeRange tr, String eventType, String group) { + + SimpleDateFormat fileDateFormatter = new SimpleDateFormat( + FILE_DATE_FORMAT); + StringBuilder sb = new StringBuilder("stats/aggregates"); + String[] chunks = PERIOD_PATTERN.split(eventType); + sb.append("/"); + sb.append(group); + sb.append("/"); + sb.append(chunks[chunks.length - 1]); + sb.append("."); + sb.append(fileDateFormatter.format(tr.getStart())); + sb.append("-"); + sb.append(fileDateFormatter.format(tr.getEnd())); + sb.append(".csv"); + + return sb.toString(); + } + + /** + * Used for outputting the stats as CSV + * + * @return + */ + private String getCSVOutput(AggregateRecord agrec, + SimpleDateFormat dateFormat) { + + StringBuilder sb = new StringBuilder(); + + String eventType = agrec.getEventType(); + Calendar startDate = agrec.getStartDate(); + Calendar endDate = agrec.getEndDate(); + String grouping = agrec.getGrouping(); + String field = agrec.getField(); + double max = agrec.getMax(); + double min = agrec.getMin(); + double sum = agrec.getSum(); + double count = agrec.getCount(); + + if (eventType != null) { + sb.append(eventType).append(COMMA); + } + + if (startDate != null) { + sb.append(dateFormat.format(startDate.getTime())) + .append(COMMA); + } + + if (endDate != null) { + sb.append(dateFormat.format(endDate.getTime())).append( + COMMA); + } + if (grouping != null) { + sb.append(grouping).append(COMMA); + } + if (field != null) { + sb.append(field).append(COMMA); + } + + sb.append(max).append(COMMA); + sb.append(min).append(COMMA); + sb.append(sum).append(COMMA); + sb.append(count); + + return sb.toString(); + } + + /** + * Writes the aggregate records to disk. + * + * @param aggregateRecords + * @throws JAXBException + */ + public void writeToDisk(AggregateRecord[] aggregateRecords) { + + Map> statisticsMap = new HashMap>(); + + for (AggregateRecord record : aggregateRecords) { + StatisticsKey key = new StatisticsKey(); + key.eventType = record.getEventType(); + key.grouping = record.getGrouping(); + key.timeRange = new TimeRange(record.getStartDate(), + record.getEndDate()); + + List aggregateRecordList = statisticsMap.get(key); + if (aggregateRecordList == null) { + aggregateRecordList = new ArrayList(); + statisticsMap.put(key, aggregateRecordList); + } + + aggregateRecordList.add(record); + } + + for (StatisticsKey key : statisticsMap.keySet()) { + + String eventType = key.eventType; + String grouping = key.grouping; + List records = statisticsMap.get(key); + + String filename = createFilename(key.timeRange, eventType, grouping); + try { + writeToFile(filename, records); + } catch (JAXBException e) { + statusHandler.error("Unable to write statistics file " + + filename, e); + } + } + } + + /** + * Writes the statistics xml to disk. + * + * @param statistics + * @throws JAXBException + */ + public void writeToFile(String filename, List records) + throws JAXBException { + + BufferedWriter bw = null; + SimpleDateFormat dateFormatter = new SimpleDateFormat(DATE_FORMAT); + LocalizationFile siteLocalization = pm.getLocalizationFile(context, + filename); + String outputFilePath = siteLocalization.getFile().getAbsolutePath(); + // pre-create directories if necessary + siteLocalization.getFile().getParentFile().mkdirs(); + // Write this to output CSV + try { + bw = new BufferedWriter(new FileWriter( + outputFilePath)); + if (bw != null) { + for (AggregateRecord agrec : records) { + bw.write(getCSVOutput(agrec, dateFormatter)); + bw.newLine(); + } + } + + } catch (IOException e) { + + statusHandler.handle(Priority.ERROR, "Failed to write File: " + + outputFilePath, e); + } finally { + if (bw != null) { + try { + bw.close(); + } catch (IOException e) { + statusHandler.handle(Priority.PROBLEM, + "failed to close CSV output file stream. " + + filename, e); + } + } + } + + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/util/ConfigLoader.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/util/ConfigLoader.java new file mode 100644 index 0000000000..e4e6e01d29 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/util/ConfigLoader.java @@ -0,0 +1,285 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.util; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.raytheon.uf.common.event.Event; +import com.raytheon.uf.common.localization.IPathManager; +import com.raytheon.uf.common.localization.LocalizationContext; +import com.raytheon.uf.common.localization.LocalizationContext.LocalizationType; +import com.raytheon.uf.common.localization.LocalizationFile; +import com.raytheon.uf.common.localization.PathManagerFactory; +import com.raytheon.uf.common.serialization.JAXBManager; +import com.raytheon.uf.common.stats.xml.StatisticsAggregate; +import com.raytheon.uf.common.stats.xml.StatisticsConfig; +import com.raytheon.uf.common.stats.xml.StatisticsEvent; +import com.raytheon.uf.common.stats.xml.StatisticsGroup; +import com.raytheon.uf.common.status.IUFStatusHandler; +import com.raytheon.uf.common.status.UFStatus; +import com.raytheon.uf.common.util.ReflectionException; +import com.raytheon.uf.common.util.ReflectionUtil; + +/** + * Loads StatisticsConfig files from localization. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez    Updated error handling and validated config files.
+ * Nov 07, 2012   1317     mpduff      Update config files.
+ * Nov 29, 2012   1350     rjpeter     Updated to static, fixed localization, increased validation.
+ * 
+ * + * @author jsanchez + * + */ +public class ConfigLoader { + + private static final IUFStatusHandler statusHandler = UFStatus + .getHandler(ConfigLoader.class); + + private final JAXBManager jaxbManager; + + private static final ConfigLoader instance = new ConfigLoader(); + + private final IPathManager pm = PathManagerFactory.getPathManager(); + + private List configurations = Collections.emptyList(); + + private Map classToEventMap = Collections + .emptyMap(); + + private static final String STATS_DIR = "stats"; + + public static ConfigLoader getInstance() { + return instance; + } + + private ConfigLoader() { + try { + jaxbManager = new JAXBManager(StatisticsConfig.class); + load(); + } catch (Exception e) { + throw new ExceptionInInitializerError(e); + } + } + + /** + * Returns a list of all StatisticsConfig files. + * + * @return + */ + public List getConfigurations() { + return configurations; + } + + /** + * Returns a map of event type to statistics event. + * + * @return + */ + public Map getTypeView() { + return classToEventMap; + } + + /** + * Loads the StatisticsConfig files in the STATS_DIR directory. + */ + public void load() throws Exception { + LocalizationContext[] searchContext = pm + .getLocalSearchHierarchy(LocalizationType.EDEX_STATIC); + Map statConfs = new HashMap(); + + // grab all stats from contexts, allowing overwrite by name + for (LocalizationContext ctx : searchContext) { + LocalizationFile[] localizationFiles = pm.listFiles(ctx, STATS_DIR, + null, false, true); + for (LocalizationFile lf : localizationFiles) { + String name = lf.getName(); + if (!statConfs.containsKey(name)) { + statConfs.put(name, lf); + } + } + } + + if (!statConfs.isEmpty()) { + List myConfigurations = new ArrayList( + statConfs.size()); + Map myEvents = new HashMap(); + + for (LocalizationFile lf : statConfs.values()) { + StatisticsConfig config = lf.jaxbUnmarshal( + StatisticsConfig.class, jaxbManager); + if (config != null) { + validate(myEvents, config); + if (!config.getEvents().isEmpty()) { + myConfigurations.add(config); + } + } + } + + configurations = myConfigurations; + classToEventMap = myEvents; + } + } + + /** + * Validates the StatisticsConfig remove invalid + * events/aggregates/duplicates. + * + * @param config + */ + private void validate(Map eventMap, + StatisticsConfig config) { + for (Iterator iter = config.getEvents().iterator(); iter + .hasNext();) { + StatisticsEvent event = iter.next(); + String eventType = event.getType(); + if (!eventMap.containsKey(eventType)) { + try { + Class clazz = Class.forName(eventType); + // verify the type is an Event + clazz.asSubclass(Event.class); + + // validate groupBy fields can be found + List groups = event.getGroupList(); + if (groups != null) { + List groupByMethods = new ArrayList( + groups.size()); + Set currentFields = new HashSet(); + + for (Iterator groupIter = groups + .iterator(); groupIter.hasNext();) { + StatisticsGroup group = groupIter.next(); + String fieldName = group.getName(); + if (!currentFields.contains(fieldName)) { + try { + Method m = ReflectionUtil.getGetterMethod( + clazz, fieldName); + groupByMethods.add(m); + currentFields.add(fieldName); + } catch (ReflectionException e) { + groupIter.remove(); + statusHandler + .warn("'" + + fieldName + + "' does not have getter method. Group being removed"); + } + } else { + statusHandler + .warn("'" + + fieldName + + "' already defined. Duplicate group being removed."); + } + } + + event.setGroupByMethods(groupByMethods); + } + + // validate aggregate methods can be found and are primitive + List curAggregates = event + .getAggregateList(); + List aggregateMethods = new ArrayList( + curAggregates.size()); + Set currentFields = new HashSet(); + + for (Iterator aggrIter = curAggregates + .iterator(); aggrIter.hasNext();) { + StatisticsAggregate aggregate = aggrIter.next(); + String aggregateField = aggregate.getField(); + + try { + Field field = clazz + .getDeclaredField(aggregateField); + if (field.getType().isPrimitive()) { + if (!currentFields.contains(aggregateField)) { + try { + Method m = ReflectionUtil + .getGetterMethod(clazz, + aggregateField); + aggregateMethods.add(m); + currentFields.add(aggregateField); + } catch (ReflectionException e) { + aggrIter.remove(); + statusHandler + .warn("'" + + aggregateField + + "' does not have getter method. Aggregate being removed"); + } + } else { + aggrIter.remove(); + statusHandler + .warn("'" + + aggregateField + + "' already defined. Duplicate aggregate being removed. "); + } + } else { + aggrIter.remove(); + statusHandler + .warn("'" + + aggregateField + + "' not a primitive type. Aggregate being removed. "); + } + } catch (NoSuchFieldException e) { + aggrIter.remove(); + statusHandler + .warn("'" + + aggregateField + + "' not a valid field. Aggregate being removed. "); + } + } + + if (!curAggregates.isEmpty()) { + event.setAggregateMethods(aggregateMethods); + eventMap.put(eventType, event); + } else { + iter.remove(); + } + } catch (ClassNotFoundException e) { + iter.remove(); + statusHandler.warn("'" + eventType + + "' not a valid type. Type being removed. "); + } catch (ClassCastException e) { + iter.remove(); + statusHandler.warn("'" + eventType + + "' not an Event type. Type being removed. "); + } + } else { + iter.remove(); + statusHandler + .warn("'" + + eventType + + "' is already defined. StatisticsEvent being skipped."); + } + } + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Aggregate.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Aggregate.java new file mode 100644 index 0000000000..a6f88e52b0 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Aggregate.java @@ -0,0 +1,116 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.xml; + +import javax.measure.unit.Unit; +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; + +import com.raytheon.uf.common.serialization.adapters.UnitAdapter; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * + * + *
+ *
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Made serializable.
+ *
+ * 
+ * + * @author jsanchez + * + */ +@DynamicSerialize +@XmlAccessorType(XmlAccessType.NONE) +public class Aggregate { + /** the field to perform the function on. */ + @XmlAttribute + @DynamicSerializeElement + private String field; + + @XmlAttribute + @XmlJavaTypeAdapter(value = UnitAdapter.class) + @DynamicSerializeElement + private Unit unit = Unit.ONE; + + @XmlAttribute + @DynamicSerializeElement + private String displayName; + + /** the name of the statistic function */ + @XmlElement(name = "function") + @DynamicSerializeElement + private Item[] functions; + + public String getField() { + return field; + } + + public void setField(String field) { + this.field = field; + } + + /** + * @return the unit + */ + public Unit getUnit() { + return unit; + } + + /** + * @param unit + * the unit to set + */ + public void setUnit(Unit unit) { + this.unit = unit; + } + + public Item[] getFunctions() { + return functions; + } + + public void setFunctions(Item[] functions) { + this.functions = functions; + } + + /** + * @param displayName + * the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } + +} diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoverageRequest.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/GroupBy.java similarity index 68% rename from edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoverageRequest.java rename to edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/GroupBy.java index 9f1a63f1aa..bb50ded100 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.grib/src/com/raytheon/uf/common/dataplugin/grib/request/GetCoverageRequest.java +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/GroupBy.java @@ -17,38 +17,43 @@ * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.grib.request; +package com.raytheon.uf.edex.stats.xml; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; -import com.raytheon.uf.common.serialization.comm.IServerRequest; /** - * TODO Add Description + * * *
  * 
  * SOFTWARE HISTORY
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Jan 8, 2010            rjpeter     Initial creation
+ * Aug 21, 2012            jsanchez     Made serializable.
  * 
  * 
* - * @author rjpeter - * @version 1.0 + * @author jsanchez + * */ @DynamicSerialize -public class GetCoverageRequest implements IServerRequest { +@XmlAccessorType(XmlAccessType.NONE) +public class GroupBy { + @XmlElement(name = "attribute") @DynamicSerializeElement - private String modelName; + private Item[] attributes; - public String getModelName() { - return modelName; + public Item[] getAttributes() { + return attributes; } - public void setModelName(String modelName) { - this.modelName = modelName; + public void setAttributes(Item[] attributes) { + this.attributes = attributes; } } diff --git a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/Level.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Item.java similarity index 60% rename from edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/Level.java rename to edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Item.java index ab78f4d04f..882a908b76 100644 --- a/edexOsgi/com.raytheon.uf.common.dataplugin.level/src/com/raytheon/uf/common/dataplugin/level/xml/Level.java +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Item.java @@ -1,75 +1,89 @@ /** * This software was developed and / or modified by Raytheon Company, * pursuant to Contract DG133W-05-CQ-1067 with the US Government. - * + * * U.S. EXPORT CONTROLLED TECHNICAL DATA * This software product contains export-restricted data whose * export/transfer/disclosure is restricted by U.S. law. Dissemination * to non-U.S. persons whether in the United States or abroad requires * an export license or other authorization. - * + * * Contractor Name: Raytheon Company * Contractor Address: 6825 Pine Street, Suite 340 * Mail Stop B8 * Omaha, NE 68106 * 402.291.0100 - * + * * See the AWIPS II Master Rights File ("Master Rights File.pdf") for * further licensing information. **/ -package com.raytheon.uf.common.dataplugin.level.xml; +package com.raytheon.uf.edex.stats.xml; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; -import javax.xml.bind.annotation.XmlType; -import com.raytheon.uf.common.serialization.ISerializableObject; import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; /** - * Defines levels within a group - * + * + * *
+ *
  * SOFTWARE HISTORY
- * 
  * Date         Ticket#    Engineer    Description
  * ------------ ---------- ----------- --------------------------
- * Sep 03, 2009            rjpeter     Initial creation.
+ * Aug 21, 2012            jsanchez     Made serializable.
+ *
  * 
- * - * @author rjpeter - * @version 1.0 + * + * @author jsanchez + * */ @DynamicSerialize -@XmlRootElement(namespace = "group") @XmlAccessorType(XmlAccessType.NONE) -@XmlType(namespace = "group") -public class Level implements ISerializableObject { - @DynamicSerializeElement +public class Item { @XmlAttribute - private String id; - @DynamicSerializeElement - @XmlElement(name = "levelValue") - private LevelValue[] levelValues; + private String name; - public String getId() { - return id; + @XmlAttribute + @DynamicSerializeElement + private String result; + + @XmlAttribute + @DynamicSerializeElement + private String displayName; + + public String getName() { + return name; } - public void setId(String id) { - this.id = id; + public void setName(String name) { + this.name = name; } - public LevelValue[] getLevelValues() { - return levelValues; + public String getResult() { + return result; } - public void setLevelValues(LevelValue[] levelValues) { - this.levelValues = levelValues; + public void setResult(String result) { + this.result = result; } + + /** + * @param displayName the displayName to set + */ + public void setDisplayName(String displayName) { + this.displayName = displayName; + } + + /** + * @return the displayName + */ + public String getDisplayName() { + return displayName; + } + } diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Statistics.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Statistics.java new file mode 100644 index 0000000000..e9e652d2eb --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/Statistics.java @@ -0,0 +1,119 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.xml; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.ISerializableObject; + +/** + * + * + *
+ * 
+ * SOFTWARE HISTORY
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Aug 21, 2012            jsanchez     Made serializable.
+ * 
+ * 
+ * + * @author jsanchez + * + */ +@XmlRootElement(name = "statistics") +@XmlAccessorType(XmlAccessType.NONE) +public class Statistics implements ISerializableObject { + + /** the start time of the period YYYY-MM-DD HH:MM:SS */ + @XmlAttribute + private String start; + + /** the end time of the period YYYY-MM-DD HH:MM:SS */ + @XmlAttribute + private String end; + + /** the event type that will be monitored */ + @XmlElement(name = "eventType") + private String eventType; + + @XmlElement(name = "groupBy") + private GroupBy groupBy; + + @XmlElement(name = "aggregate") + private Aggregate[] aggregates; + + /** + * default constructor + */ + public Statistics() { + + } + + public Statistics(StatsConfig config) { + this.eventType = config.getEventType(); + this.groupBy = config.getGroupBy(); + this.aggregates = config.getAggregates(); + } + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public GroupBy getGroupBy() { + return groupBy; + } + + public void setGroupBy(GroupBy groupBy) { + this.groupBy = groupBy; + } + + public Aggregate[] getAggregates() { + return aggregates; + } + + public void setAggregates(Aggregate[] aggregates) { + this.aggregates = aggregates; + } + + public String getStart() { + return start; + } + + public void setStart(String start) { + this.start = start; + } + + public String getEnd() { + return end; + } + + public void setEnd(String end) { + this.end = end; + } +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/StatsConfig.java b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/StatsConfig.java new file mode 100644 index 0000000000..1467522773 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/src/com/raytheon/uf/edex/stats/xml/StatsConfig.java @@ -0,0 +1,85 @@ +/** + * This software was developed and / or modified by Raytheon Company, + * pursuant to Contract DG133W-05-CQ-1067 with the US Government. + * + * U.S. EXPORT CONTROLLED TECHNICAL DATA + * This software product contains export-restricted data whose + * export/transfer/disclosure is restricted by U.S. law. Dissemination + * to non-U.S. persons whether in the United States or abroad requires + * an export license or other authorization. + * + * Contractor Name: Raytheon Company + * Contractor Address: 6825 Pine Street, Suite 340 + * Mail Stop B8 + * Omaha, NE 68106 + * 402.291.0100 + * + * See the AWIPS II Master Rights File ("Master Rights File.pdf") for + * further licensing information. + **/ +package com.raytheon.uf.edex.stats.xml; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import com.raytheon.uf.common.serialization.ISerializableObject; +import com.raytheon.uf.common.serialization.annotations.DynamicSerialize; +import com.raytheon.uf.common.serialization.annotations.DynamicSerializeElement; + +/** + * The config file that will be used to set the specific parameters that + * statistic files can be aggregated against. + * + * SOFTWARE HISTORY + * Date Ticket# Engineer Description + * ------------ ---------- ----------- -------------------------- + * Aug 21, 2012 jsanchez Made serializable. + * + * @author jsanchez + * + */ +@DynamicSerialize +@XmlRootElement(name = "statsConfig") +@XmlAccessorType(XmlAccessType.NONE) +public class StatsConfig implements ISerializableObject { + + /** the event type that will be monitored */ + @XmlElement(name = "eventType") + @DynamicSerializeElement + private String eventType; + + @XmlElement(name = "groupBy") + @DynamicSerializeElement + private GroupBy groupBy; + + @XmlElement(name = "aggregate") + @DynamicSerializeElement + private Aggregate[] aggregates; + + public String getEventType() { + return eventType; + } + + public void setEventType(String eventType) { + this.eventType = eventType; + } + + public GroupBy getGroupBy() { + return groupBy; + } + + public void setGroupBy(GroupBy groupBy) { + this.groupBy = groupBy; + } + + public Aggregate[] getAggregates() { + return aggregates; + } + + public void setAggregates(Aggregate[] aggregates) { + this.aggregates = aggregates; + } + +} diff --git a/edexOsgi/com.raytheon.uf.edex.stats/utility/common_static/base/purge/aggregatePurgeRules.xml b/edexOsgi/com.raytheon.uf.edex.stats/utility/common_static/base/purge/aggregatePurgeRules.xml new file mode 100644 index 0000000000..71320c1422 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/utility/common_static/base/purge/aggregatePurgeRules.xml @@ -0,0 +1,6 @@ + + + + 30-00:00:00 + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/utility/common_static/base/purge/statsPurgeRules.xml b/edexOsgi/com.raytheon.uf.edex.stats/utility/common_static/base/purge/statsPurgeRules.xml new file mode 100644 index 0000000000..24714caf46 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/utility/common_static/base/purge/statsPurgeRules.xml @@ -0,0 +1,6 @@ + + + + 00-24:00:00 + + diff --git a/edexOsgi/com.raytheon.uf.edex.stats/utility/edex_static/base/stats/edexProcessStats.xml b/edexOsgi/com.raytheon.uf.edex.stats/utility/edex_static/base/stats/edexProcessStats.xml new file mode 100644 index 0000000000..ed85b9c2e7 --- /dev/null +++ b/edexOsgi/com.raytheon.uf.edex.stats/utility/edex_static/base/stats/edexProcessStats.xml @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/edexOsgi/com.raytheon.uf.tools.cli/impl/src/purgeallmodeldata/purgeAllModelData.py b/edexOsgi/com.raytheon.uf.tools.cli/impl/src/purgeallmodeldata/purgeAllModelData.py index 5d89d35b26..e2d8b5dab1 100644 --- a/edexOsgi/com.raytheon.uf.tools.cli/impl/src/purgeallmodeldata/purgeAllModelData.py +++ b/edexOsgi/com.raytheon.uf.tools.cli/impl/src/purgeallmodeldata/purgeAllModelData.py @@ -23,6 +23,7 @@ import logging from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.grib.request import DeleteAllModelDataRequest +from dynamicserialize.dstypes.com.raytheon.uf.common.dataplugin.grid.request import DeleteAllGridDataRequest from ufpy import ThriftClient from ufpy import UsageArgumentParser @@ -63,13 +64,20 @@ def main(): client = ThriftClient.ThriftClient(options.host, options.port) for model in options.models: + logger.info("Deleting all data for model [" + model + "]...") try: - logger.info("Deleting all data for model [" + model + "]...") req = DeleteAllModelDataRequest(model) client.sendRequest(req) - logger.info("Model data for model [" + model + "] successfully deleted...") + logger.info("Grib data for model [" + model + "] successfully deleted...") except Exception: - logger.exception("Could not purge data for model [" + model + "]:") + logger.exception("Could not purge grib data for model [" + model + "]:") + + try: + req = DeleteAllGridDataRequest(model) + client.sendRequest(req) + logger.info("Grid data for model [" + model + "] successfully deleted...") + except Exception: + logger.exception("Could not purge grid data for model [" + model + "]:") logger.info("purgeAllModelData is complete.") diff --git a/edexOsgi/com.raytheon.uf.tools.gfesuite.servicebackup/svcBackup/ServiceBackup/scripts/export_grids b/edexOsgi/com.raytheon.uf.tools.gfesuite.servicebackup/svcBackup/ServiceBackup/scripts/export_grids index d6efe8102a..b8c878c9b3 100644 --- a/edexOsgi/com.raytheon.uf.tools.gfesuite.servicebackup/svcBackup/ServiceBackup/scripts/export_grids +++ b/edexOsgi/com.raytheon.uf.tools.gfesuite.servicebackup/svcBackup/ServiceBackup/scripts/export_grids @@ -118,18 +118,13 @@ perform_export() { #check if the netcdf file is there;if not,exit if [ $? -ne 0 ] then + $LOGGER "ifpnetCDF failed. Export exits." + rm -f ${lockFile} + $LOGGER 100 NETCDF_SUCCESS=0 if [ $NATIONAL_CENTER != 1 ] && [ "$1" != "-c" ] then - netcdf_error=`grep "Some of the requested time ranges are not in the inventory" $logfile` - if [ "$netcdf_error" != "" ]; then - NETCDF_SUCCESS=1 - else - $LOGGER "ifpnetCDF failed. Export exits." - rm -f ${lockFile} - $LOGGER 100 - exit 1 - fi + exit 1 fi fi else @@ -141,18 +136,13 @@ perform_export() { #check if the netcdf file is there;if not,exit if [ $? -ne 0 ] then + $LOGGER "ifpnetCDF failed. Export exits." + rm -f ${lockFile} + $LOGGER 100 NETCDF_SUCCESS=0 if [ $NATIONAL_CENTER != 1 ] && [ "$1" != "-c" ] - then - netcdf_error=`grep "Some of the requested time ranges are not in the inventory" $logfile` - if [ "$netcdf_error" != "" ]; then - NETCDF_SUCCESS=1 - else - $LOGGER "ifpnetCDF failed. Export exits." - rm -f ${lockFile} - $LOGGER 100 - exit 1 - fi + then + exit 1 fi fi fi @@ -163,19 +153,14 @@ perform_export() { #check if the netcdf file is there;if not,exit before we call msg_send if [ $? -ne 0 ] then - NETCDF_SUCCESS=0 - if [ $NATIONAL_CENTER != 1 ] && [ "$1" != "-c" ] - then - netcdf_error=`grep "Some of the requested time ranges are not in the inventory" $logfile` - if [ "$netcdf_error" != "" ]; then - NETCDF_SUCCESS=1 - else - $LOGGER "ifpnetCDF failed." - rm -f ${lockFile} - $LOGGER 100 - exit 1 - fi - fi + $LOGGER ifpnetCDF failed. + rm -f ${lockFile} + $LOGGER 100 + NETCDF_SUCCESS=0 + if [ $NATIONAL_CENTER != 1 ] && [ "$1" != "-c" ] + then + exit 1 + fi fi fi diff --git a/msi/AWIPSII.CAVE/AWIPSII.CAVE/ipr.gif.orig b/msi/AWIPSII.CAVE/AWIPSII.CAVE/ipr.gif.orig deleted file mode 100644 index bf385e5e98..0000000000 Binary files a/msi/AWIPSII.CAVE/AWIPSII.CAVE/ipr.gif.orig and /dev/null differ diff --git a/msi/AWIPSII.CAVE/AWIPSII.CAVE/obj/x86/Release/_DELETE_ME_.orig b/msi/AWIPSII.CAVE/AWIPSII.CAVE/obj/x86/Release/_DELETE_ME_.orig deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/msi/build/A2Staging/Scripts/assembleCAVE.ps1 b/msi/build/A2Staging/Scripts/assembleCAVE.ps1 index 84484cddde..a8a6135b4b 100644 --- a/msi/build/A2Staging/Scripts/assembleCAVE.ps1 +++ b/msi/build/A2Staging/Scripts/assembleCAVE.ps1 @@ -8,75 +8,20 @@ function installCAVERepository([string]$feature_group, [string]$repo_zip) } pushd . + cd ${A2_PREPARE_CAVE_DIR}\cave echo "`n" -installCAVERepository -feature_group "com.raytheon.uf.viz.cots.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.cots.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.common.core.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.common.core.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.core.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.core.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.d2d.core.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.d2d.core.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.radar.feature.feature.group" ` - -repo_zip "com.raytheon.viz.radar.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.grib.feature.feature.group" ` - -repo_zip "com.raytheon.viz.grib.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.sounding.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.sounding.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.dataplugins.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.dataplugins.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.dataplugin.obs.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.dataplugin.obs.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.displays.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.displays.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.text.feature.feature.group" ` - -repo_zip "com.raytheon.viz.text.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.satellite.feature.feature.group" ` - -repo_zip "com.raytheon.viz.satellite.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.ncep.core.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.ncep.core.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.d2d.xy.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.d2d.xy.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.core.maps.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.core.maps.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.gfe.feature.feature.group" ` - -repo_zip "com.raytheon.viz.gfe.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.avnfps.feature.feature.group" ` - -repo_zip "com.raytheon.viz.avnfps.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.hydro.feature.feature.group" ` - -repo_zip "com.raytheon.viz.hydro.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.d2d.skewt.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.d2d.skewt.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.ncep.dataplugins.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.ncep.dataplugins.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.ncep.displays.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.ncep.displays.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.ncep.nsharp.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.ncep.nsharp.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.d2d.nsharp.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.d2d.nsharp.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.volumebrowser.feature.feature.group" ` - -repo_zip "com.raytheon.viz.volumebrowser.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.d2d.gfe.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.d2d.gfe.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.viz.warngen.feature.feature.group" ` - -repo_zip "com.raytheon.viz.warngen.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.ncep.perspective.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.ncep.perspective.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.nwsauth.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.nwsauth.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.thinclient.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.thinclient.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.dat.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.dat.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.localization.perspective.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.localization.perspective.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.alertviz.localization.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.alertviz.localization.feature-repo-win32.x86.zip" -installCAVERepository -feature_group "com.raytheon.uf.viz.npp.feature.feature.group" ` - -repo_zip "com.raytheon.uf.viz.npp.feature-repo-win32.x86.zip" - +$feature_list = Get-Content "${A2_PREPARE_CAVE_DIR}\features.txt" +Write-Host Feature Count = $feature_list.count +foreach ($feature in $feature_list) +{ + Write-Host Installing Feature: $feature + $feature_group = $feature + ".feature.group" + $repo_zip = $feature + "-repo-win32.x86.zip" + + installCAVERepository -feature_group "$feature_group" ` + -repo_zip "$repo_zip" +} popd EXIT 0 \ No newline at end of file diff --git a/nativeLib/dist.native/i386-pc-linux-gnu.tar.REMOVED.git-id b/nativeLib/dist.native/i386-pc-linux-gnu.tar.REMOVED.git-id index faa0930c95..95c4ce0043 100644 --- a/nativeLib/dist.native/i386-pc-linux-gnu.tar.REMOVED.git-id +++ b/nativeLib/dist.native/i386-pc-linux-gnu.tar.REMOVED.git-id @@ -1 +1 @@ -e0807c547d1d9fe1c96688bb0955467ab6fdb8e1 \ No newline at end of file +c15f83be0cbe4bfd6273d69cf9219f0ac8462b73 \ No newline at end of file diff --git a/nativeLib/rary.cots.jepp/jepp-2.3/windows/Release/_DELETE_ME_.orig b/nativeLib/rary.cots.jepp/jepp-2.3/windows/Release/_DELETE_ME_.orig deleted file mode 100644 index e69de29bb2..0000000000 diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/check_app_context b/nativeLib/rary.ohd.filesystem/awips/hydroapps/check_app_context new file mode 100644 index 0000000000..634aef96b8 --- /dev/null +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/check_app_context @@ -0,0 +1,80 @@ +#!/bin/sh +## +# 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. +## + +# Script: check_app_Context +# Script that determines and sets the APP_CONTEXT variable for the +# calling script, and checks if the setting for that value is set to 'ON' or 'OFF' +# If off, this script will exit the calling script. + +# get contextName from script name +oldIFS="$IFS" +IFS="/" +n=0 +for element in ${0} +do + n=`expr $n + 1` + eval pathPart$n="$element" +done +eval contextName='$pathPart'$n + +# parse off file extension if necessary +IFS="." +n=0 +for element in $contextName +do + n=`expr $n + 1` + eval contextName="$element" + break +done + +# if APP_CONTEXT is not set +if [ "${APP_CONTEXT:-NOTSET}" == "NOTSET" ] +then + eval APP_CONTEXT=${contextName} +else + # check if APP_CONTEXT ends with script's context + # if not, then append it + IFS="." + n=0 + for element in $APP_CONTEXT + do + n=`expr $n + 1` + eval currentContextName="$element" + done + if [ "${currentContextName}" != "${contextName}" ] + then + APP_CONTEXT=${APP_CONTEXT}'.'${contextName} + fi +fi +IFS="${oldIFS}" +export APP_CONTEXT + +# Determine if on or off from APP_CONTEXT. Default APP_CONTEXT is ON +eval APP_VAR=$(runso rary.ohd.util gad $APP_CONTEXT) +echo "App Execution Token for script ${contextName} with App Context ${APP_CONTEXT} is ${APP_VAR:-ON}" + +# if set to not run, exit the calling script +if [ "${APP_VAR:-ON}" == "OFF" ] +then + echo "Script ${contextName} will exit and not run." + exit +fi + diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/purge_mpe_files b/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/purge_mpe_files index 041fefef2d..c5b2f46dbe 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/purge_mpe_files +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/purge_mpe_files @@ -34,6 +34,8 @@ RUN_FROM_DIR=`dirname $0` # set up some environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export LIGHTNING_LOG_DIR=$(get_apps_defaults lightning_log_dir) export GAQ_LOG_DIR=$(get_apps_defaults gaq_log_dir) export MPE_QPE_SBN_DIR=$(get_apps_defaults mpe_qpe_sbn_dir) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_dqc_preprocessor b/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_dqc_preprocessor index 17529cb897..8529660e7f 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_dqc_preprocessor +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_dqc_preprocessor @@ -11,6 +11,8 @@ RUN_FROM_DIR=`dirname $0` # Set up SOME environmental variables. . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export MPE_EDITOR_LOGS_DIR=$(get_apps_defaults mpe_editor_logs_dir) export PPROC_BIN=$(get_apps_defaults pproc_bin) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_mpe_fieldgen b/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_mpe_fieldgen index be440efc6b..9ad7c3b4bf 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_mpe_fieldgen +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/precip_proc/bin/run_mpe_fieldgen @@ -6,6 +6,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export SSHP_INVOKE_MAP_PREPROCESS=$(get_apps_defaults sshp_invoke_map_preprocess) export SSHP_LOG_DIR=$(get_apps_defaults sshp_log_dir) export MPE_GAGE_QC=$(get_apps_defaults mpe_gage_qc) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/purge_files b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/purge_files index c949ed67fc..291e1dc3cb 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/purge_files +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/purge_files @@ -27,6 +27,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export GAGE_PP_DATA=$(get_apps_defaults gage_pp_data) export GAGE_PP_LOG=$(get_apps_defaults gage_pp_log) export SSHP_INGEST_XML_DIR=$(get_apps_defaults sshp_ingest_xml_dir) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_alarm_whfs b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_alarm_whfs index 7db67df67f..9ee99f28f9 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_alarm_whfs +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_alarm_whfs @@ -12,6 +12,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export WHFS_UTIL_LOG_DIR=$(get_apps_defaults whfs_util_log_dir) export WHFS_LOCAL_BIN_DIR=$(get_apps_defaults whfs_bin_dir) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_db_purge b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_db_purge index 70379cdc69..bc2dff514f 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_db_purge +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_db_purge @@ -7,6 +7,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export DB_PURGE_LOG_DIR=$(get_apps_defaults db_purge_log_dir) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_floodseq b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_floodseq index 99e2e4eb00..0542d173da 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_floodseq +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_floodseq @@ -6,6 +6,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export FLOODSEQ_LOG_DIR=$(get_apps_defaults floodseq_log_dir) export WHFS_BIN_DIR=$(get_apps_defaults whfs_bin_dir) export DB_NAME=$(get_apps_defaults db_name) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_pdc_pp b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_pdc_pp index 0a35bcc99d..a80357d546 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_pdc_pp +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_pdc_pp @@ -6,6 +6,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export PDC_PP_LOG_DIR=$(get_apps_defaults pdc_pp_log_dir) export SYS_JAVA_DIR=$(get_apps_defaults sys_java_dir) export WHFS_BIN_DIR=$(get_apps_defaults whfs_bin_dir) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_report_alarm b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_report_alarm index 065f4230e4..719032977e 100644 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_report_alarm +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_report_alarm @@ -15,6 +15,7 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications # Run from local bin dir . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context export EDEX_HOME=/awips2/edex export DB_NAME=$(get_apps_defaults db_name) diff --git a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_roc_checker b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_roc_checker index e037a18ab0..6e8de7d9d3 100755 --- a/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_roc_checker +++ b/nativeLib/rary.ohd.filesystem/awips/hydroapps/whfs/bin/run_roc_checker @@ -8,6 +8,8 @@ RUN_FROM_DIR=`dirname $0` # set up SOME environment variables for WHFS applications # Source set_hydro_env from local bin . $RUN_FROM_DIR/../../set_hydro_env +. $RUN_FROM_DIR/../../check_app_context + export WHFS_UTIL_LOG_DIR=$(get_apps_defaults whfs_util_log_dir) export WHFS_BIN_DIR=$(get_apps_defaults whfs_bin_dir) export DB_NAME=$(get_apps_defaults db_name) diff --git a/ncep/gov.noaa.nws.ncep.common.dataplugin.ncgrib/src/gov/noaa/nws/ncep/common/dataplugin/ncgrib/NcgribPathProvider.java b/ncep/gov.noaa.nws.ncep.common.dataplugin.ncgrib/src/gov/noaa/nws/ncep/common/dataplugin/ncgrib/NcgribPathProvider.java index fe2a0bc58f..8eb35afdc1 100644 --- a/ncep/gov.noaa.nws.ncep.common.dataplugin.ncgrib/src/gov/noaa/nws/ncep/common/dataplugin/ncgrib/NcgribPathProvider.java +++ b/ncep/gov.noaa.nws.ncep.common.dataplugin.ncgrib/src/gov/noaa/nws/ncep/common/dataplugin/ncgrib/NcgribPathProvider.java @@ -77,7 +77,7 @@ public class NcgribPathProvider extends DefaultPathProvider { @Override public String getHDFFileName(String pluginName, IPersistable persistable) { -// Integer partition = persistable.getHdfFileId(); + Integer partition = persistable.getHdfFileId(); if (persistable == null) { throw new IllegalArgumentException( @@ -89,22 +89,18 @@ public class NcgribPathProvider extends DefaultPathProvider { "Argument persistable is of wrong type. Expected " + NcgribRecord.class + " but got " + persistable.getClass()); + } + + if (partition == null) { + throw new IllegalArgumentException( + "Expected argument hdfFileId not set on object " + + persistable.toString()); } else if (pluginName == null) { throw new IllegalArgumentException( "Expected argument pluginName not set on object " + persistable.toString()); } -// if (partition == null) { -// throw new IllegalArgumentException( -// "Expected argument hdfFileId not set on object " -// + persistable.toString()); -// } else if (pluginName == null) { -// throw new IllegalArgumentException( -// "Expected argument pluginName not set on object " -// + persistable.toString()); -// } - NcgribRecord pdo = (NcgribRecord) persistable; StringBuffer sb = new StringBuffer(); diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.atcf/unit-test/gov/noaa/nws/ncep/edex/plugin/atcf/util/AtcfParserTest.java b/ncep/gov.noaa.nws.ncep.edex.plugin.atcf/unit-test/gov/noaa/nws/ncep/edex/plugin/atcf/util/AtcfParserTest.java index 5201e47eac..661d154428 100644 --- a/ncep/gov.noaa.nws.ncep.edex.plugin.atcf/unit-test/gov/noaa/nws/ncep/edex/plugin/atcf/util/AtcfParserTest.java +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.atcf/unit-test/gov/noaa/nws/ncep/edex/plugin/atcf/util/AtcfParserTest.java @@ -1,39 +1,36 @@ package gov.noaa.nws.ncep.edex.plugin.atcf.util; -import static org.junit.Assert.*; -import gov.noaa.nws.ncep.common.dataplugin.atcf.*; +import static org.junit.Assert.assertEquals; +import gov.noaa.nws.ncep.common.dataplugin.atcf.AtcfRecord; + import java.util.Calendar; -import org.junit.BeforeClass; import org.junit.Test; public class AtcfParserTest { - @BeforeClass - public static void setUpBeforeClass() throws Exception { - } + private static final double ALLOWABLE_DOUBLE_DELTA = 0.00001; @Test public void testProcessLatLon() { - Float latLon; - latLon = AtcfParser.processLatLon("975W"); - assertEquals (-97.5, latLon); + float latLon = AtcfParser.processLatLon("975W"); + assertEquals(-97.5F, latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon("1605E"); - assertEquals (160.5, latLon); + assertEquals(160.5, latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon("1605W"); - assertEquals (-160.5, latLon); + assertEquals(-160.5, latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon("623E"); - assertEquals (62.3, latLon); + assertEquals(62.3, latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon("62N"); - assertEquals (6.2, latLon); + assertEquals(6.2, latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon("847S"); - assertEquals (-84.7, latLon); + assertEquals(-84.7, latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon("847G"); - assertEquals (999999., latLon); + assertEquals(999999., latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon(""); - assertEquals (999999., latLon); + assertEquals(999999., latLon, ALLOWABLE_DOUBLE_DELTA); latLon = AtcfParser.processLatLon(" "); - assertEquals (999999., latLon); + assertEquals(999999., latLon, ALLOWABLE_DOUBLE_DELTA); } @Test @@ -95,19 +92,19 @@ public class AtcfParserTest { assertEquals (2, record.getTechniqueNum()); assertEquals ("ZGFS", record.getTechnique()); assertEquals (0, record.getFcstHour()); - assertEquals (999999., record.getClat()); - assertEquals (-96.6, record.getClon()); - assertEquals (25., record.getWindMax()); - assertEquals (1008., record.getMslp()); + assertEquals(999999., record.getClat(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(-96.6, record.getClon(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(25., record.getWindMax(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(1008., record.getMslp(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("XX", record.getIntensity()); - assertEquals (34., record.getRadWind()); + assertEquals(34., record.getRadWind(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("NEQ", record.getRadWindQuad()); - assertEquals (100., record.getQuad1WindRad()); - assertEquals (85., record.getQuad2WindRad()); - assertEquals (70., record.getQuad3WindRad()); - assertEquals (85., record.getQuad4WindRad()); - assertEquals (999999., record.getClosedP()); - assertEquals (999999., record.getRadClosedP()); + assertEquals(100., record.getQuad1WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(85., record.getQuad2WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(70., record.getQuad3WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(85., record.getQuad4WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(999999., record.getClosedP(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(999999., record.getRadClosedP(), ALLOWABLE_DOUBLE_DELTA); // theBulletin = "CP, 85, 2010053012, 03, OFCL, 3, 242N, 1568W, 100, 960, HU, 34, NEQ, 130, 132, 134, 135, 0, 0, 0, 120, 20, C, 0, RMT, 25, 9, HURCNAME, , 12, NEQ, 130, 131, 132, 133\n"; record = AtcfParser.processFields(theBulletin); @@ -121,35 +118,35 @@ public class AtcfParserTest { assertEquals (3, record.getTechniqueNum()); assertEquals ("OFCL", record.getTechnique()); assertEquals (3, record.getFcstHour()); - assertEquals (24.2, record.getClat()); - assertEquals (-156.8, record.getClon()); - assertEquals (100., record.getWindMax()); - assertEquals (960., record.getMslp()); + assertEquals(24.2, record.getClat(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(-156.8, record.getClon(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(100., record.getWindMax(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(960., record.getMslp(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("HU", record.getIntensity()); - assertEquals (34., record.getRadWind()); + assertEquals(34., record.getRadWind(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("NEQ", record.getRadWindQuad()); - assertEquals (130., record.getQuad1WindRad()); - assertEquals (132., record.getQuad2WindRad()); - assertEquals (134., record.getQuad3WindRad()); - assertEquals (135., record.getQuad4WindRad()); - assertEquals (0., record.getClosedP()); - assertEquals (0., record.getRadClosedP()); - assertEquals (0., record.getMaxWindRad()); - assertEquals (120., record.getGust()); - assertEquals (20., record.getEyeSize()); + assertEquals(130., record.getQuad1WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(132., record.getQuad2WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(134., record.getQuad3WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(135., record.getQuad4WindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(0., record.getClosedP(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(0., record.getRadClosedP(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(0., record.getMaxWindRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(120., record.getGust(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(20., record.getEyeSize(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("C", record.getSubRegion()); - assertEquals (0., record.getMaxSeas()); + assertEquals(0., record.getMaxSeas(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("RMT", record.getForecaster()); - assertEquals (25., record.getStormDrct()); - assertEquals (9., record.getStormSped()); + assertEquals(25., record.getStormDrct(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(9., record.getStormSped(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("HURCNAME", record.getStormName()); assertEquals (" ", record.getStormDepth()); - assertEquals (12., record.getRadWave()); + assertEquals(12., record.getRadWave(), ALLOWABLE_DOUBLE_DELTA); assertEquals ("NEQ", record.getRadWaveQuad()); - assertEquals (130., record.getQuad1WaveRad()); - assertEquals (131., record.getQuad2WaveRad()); - assertEquals (132., record.getQuad3WaveRad()); - assertEquals (133., record.getQuad4WaveRad()); + assertEquals(130., record.getQuad1WaveRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(131., record.getQuad2WaveRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(132., record.getQuad3WaveRad(), ALLOWABLE_DOUBLE_DELTA); + assertEquals(133., record.getQuad4WaveRad(), ALLOWABLE_DOUBLE_DELTA); } } diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/res/spring/ncgrib-ingest.xml b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/res/spring/ncgrib-ingest.xml index a5868c86b1..fe5b78b0eb 100644 --- a/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/res/spring/ncgrib-ingest.xml +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/res/spring/ncgrib-ingest.xml @@ -33,13 +33,29 @@ factory-method="register" depends-on="persistCamelRegistered">
- + + + + + + + + + + + + grid + + + + + diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/GridLookupFileName.java b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/GridLookupFileName.java new file mode 100644 index 0000000000..567d9f9eda --- /dev/null +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/GridLookupFileName.java @@ -0,0 +1,74 @@ +package gov.noaa.nws.ncep.edex.plugin.ncgrib; + +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + +public class GridLookupFileName { + /** The singleton instance of GridLookupFileName **/ + private static GridLookupFileName instance; + + private String[] modelNames = { "cmce", "gefs", "gww", "naefsBC", + "naefsUS", "naefsAK", "sref" }; + + private String[] template = { + "cmc_gep.*|cmce;cmc_gec.*|cmcec;cmc_geavg.*|cmceMean;cmc_gespr.*|cmceSpread", + "gec00.*bc.*|gefscBC;gec00.*anl|gefscAnal;gec00.*[0-9]|gefsc;gep.*anl|gefsAnal;gep.*bc.*|gefsBC;geavg.*bc.*|gefsMeanBC;gespr.*bc.*|gefsSpreadBC;gespr.*|gefsSpread", + "mean.*|gwwMean;probab.*|gwwProb;spread.*|gwwSpread", + "naefs_geavg.*bc.*|naefsMeanBC;naefs_geavg.*anv.*|naefsMean;naefs_gespr.*bc.*|naefsSpreadBC;naefs_ge10pt.*bc.*|naefs10ptBC;naefs_ge50pt.*bc.*|naefs50ptBC;naefs_ge90pt.*bc.*|naefs90ptBC;naefs_gemode.*bc.*|naefsModeBC", + "naefs_geavg.*conus.*grib2|naefsMeanUS;naefs_ge10pt.*conus.*grib2|naefs10ptUS;naefs_ge50pt.*conus.*grib2|naefs50ptUS;naefs_ge90pt.*conus.*grib2|naefs90ptUS;naefs_gemode.*conus.*grib2|naefsModeUS", + "naefs_geavg.*alaska.*grib2|naefsMeanAK;naefs_ge10pt.*alaska.*grib2|naefs10ptAK;naefs_ge50pt.*alaska.*grib2|naefs50ptAK;naefs_ge90pt.*alaska.*grib2|naefs90ptAK;naefs_gemode.*alaska.*grib2|naefsModeAK", + "nam.*.awip3d00.*tm00|nam40;sref_nam.*ctl1.*|srefNamCtl1;sref_nam.*ctl2.*|srefNamCtl2;sref_nam.*[pn][1-9].*|srefNam;sref_eta.*[pn][1-9].*|srefEta;sref_eta.*ctl1.*|srefEtaCtl1;sref_eta.*ctl2.*|srefEtaCtl2;sref_rsm.*ctl.*|srefRsmCtl;sref_rsm.*[pn][1-9].*|srefRsm;sref_nmm.*ctl.*|srefNmmCtl;sref_nmm.*[pn][1-9].*|srefNmm;sref_em.*ctl.*|srefEmCtl;sref_em.*[pn][1-9].*|srefEm" }; + + private final Map models; + + public static GridLookupFileName getInstance() { + if (instance == null) { + instance = new GridLookupFileName(); + } + return instance; + } + + private GridLookupFileName() { + models = new HashMap(); + + initModels(); + } + + private void initModels() { + for (int i = 0; i < modelNames.length; i++) { + models.put(modelNames[i].toUpperCase(), template[i]); + } + } + + public String getModelName(String filename) { + String modelname = null; + + // if (model.equalsIgnoreCase("gww") && gridId.equalsIgnoreCase("229")) + // { + // return modelname; + // } + // + // String template = models.get(model.toUpperCase()); + for (String template : this.template) { + String[] tokens = template.split(";"); + // System.out.println ( " CMC ensemble " + "!!!\n"); + + for (String token : tokens) { + String[] alias = token.split("\\|"); + if (Pattern.matches(alias[0], filename)) { + modelname = alias[1]; + + // perturbation number + // String[] pert = filename.split("\\."); + // if ( pert[3].startsWith("p") || pert[3].startsWith("n")) + // { + // nbm.setPerturbationNumber(pert[3]); + // } + break; + } + } + } + return modelname; + } +} diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribDecoder.java b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribDecoder.java index 5ca159b5f5..975d527495 100644 --- a/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribDecoder.java +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribDecoder.java @@ -19,8 +19,11 @@ **/ package gov.noaa.nws.ncep.edex.plugin.ncgrib; +import gov.noaa.nws.ncep.common.dataplugin.ncgrib.NcgribRecord; +import gov.noaa.nws.ncep.common.dataplugin.ncgrib.exception.GribException; +import gov.noaa.nws.ncep.edex.plugin.ncgrib.util.TableTimeStamp; + import java.io.File; -import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; @@ -33,16 +36,12 @@ import ucar.grib.grib2.Grib2Input; import ucar.grib.grib2.Grib2Record; import ucar.unidata.io.RandomAccessFile; - import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.status.IUFStatusHandler; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; +import com.raytheon.uf.edex.core.EDEXUtil; import com.raytheon.uf.edex.python.decoder.PythonDecoder; -import gov.noaa.nws.ncep.common.dataplugin.ncgrib.NcgribRecord; - -import gov.noaa.nws.ncep.common.dataplugin.ncgrib.exception.GribException; -import gov.noaa.nws.ncep.edex.plugin.ncgrib.util.TableTimeStamp; /** * Generic decoder for decoding grib files @@ -55,6 +54,7 @@ import gov.noaa.nws.ncep.edex.plugin.ncgrib.util.TableTimeStamp; * 10/13/10 276 llin Modified for NC GRIB. * 01/19/12 xguo Split large files * 05/23/12 xguo Split large file to each record file + * 06/12/12 00609 djohnson Use EDEXUtil for EDEX_HOME. * * * @author njensen @@ -193,7 +193,7 @@ public class NcgribDecoder { raf.read(transfer); try { - out = new FileOutputStream(System.getProperty("edex.home") + out = new FileOutputStream(EDEXUtil.EDEX_HOME + "/data/sbn/ncgrib/" + fileName + "_" + num); out.write(transfer); out.close(); @@ -224,7 +224,7 @@ public class NcgribDecoder { raf.read(transfer); try { - out = new FileOutputStream(System.getProperty("edex.home") + out = new FileOutputStream(EDEXUtil.EDEX_HOME + "/data/sbn/ncgrib/" + fileName + "_" + num); out.write(transfer); out.close(); @@ -245,7 +245,7 @@ public class NcgribDecoder { raf.read(transfer); try { - out = new FileOutputStream(System.getProperty("edex.home") + out = new FileOutputStream(EDEXUtil.EDEX_HOME + "/data/sbn/ncgrib/" + fileName + "_" + num); out.write(transfer); out.close(); diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribFileNameProcessor.java b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribFileNameProcessor.java new file mode 100644 index 0000000000..fa011bcc9c --- /dev/null +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.ncgrib/src/gov/noaa/nws/ncep/edex/plugin/ncgrib/NcgribFileNameProcessor.java @@ -0,0 +1,117 @@ +/** + * 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.edex.plugin.ncgrib; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.camel.Exchange; +import org.apache.camel.Processor; + +/** + * + * Processor for ncep grib files, this processor has lots of hard coded + * assumptions about file naming that need to be more generic based off ncep + * file names. + * + *
+ * 
+ * SOFTWARE HISTORY
+ * 
+ * Date         Ticket#    Engineer    Description
+ * ------------ ---------- ----------- --------------------------
+ * Mar 1, 2012            bsteffen     Initial creation
+ * 
+ * 
+ * + * @author bsteffen + * @version 1.0 + */ +public class NcgribFileNameProcessor implements Processor { + + // grab all known ensemble ids + private static final Pattern ENSEMBLE_ID_PATTERN = Pattern + .compile("^(p|n|ctl)\\d{0,2}$"); + + // anything that ends in nest is assumed to be a nested grid identifier + private static final Pattern FIREWXNEST_ID_PATTERN = Pattern + .compile("^firewxnest$"); + + // anything that ends in nest is assumed to be a nested grid identifier + private static final Pattern NEST_ID_PATTERN = Pattern.compile("^.*nest$"); + + // SREF gets special handling, does this apply to other models? + private static final Pattern SREF_PATTERN = Pattern.compile("^sref_.*$"); + + // This is the least generic pattern ever, are there any constraints on + // event names, who knows? + private static final Pattern HURRICANE_PATTERN = Pattern + .compile("^([a-z]*)\\d{1,2}[lewcs]$"); + + @Override + public void process(Exchange exchange) throws Exception { + String flName = (String) exchange.getIn() + .getHeader("CamelFileNameOnly"); + String datasetid = null; + String secondaryid = null; + String ensembleid = null; + String[] nameTokens = flName.split("\\."); + for (String token : nameTokens) { + if (ENSEMBLE_ID_PATTERN.matcher(token).find()) { + ensembleid = token; + } else if (FIREWXNEST_ID_PATTERN.matcher(token).find()) { + datasetid = "NAMFIREWX"; + secondaryid = token; + } else if (NEST_ID_PATTERN.matcher(token).find()) { + secondaryid = token; + } else if (SREF_PATTERN.matcher(token).find()) { + String[] tokens = token.split("_"); + datasetid = tokens[0].toUpperCase(); + secondaryid = tokens[1].toUpperCase(); + } else if (HURRICANE_PATTERN.matcher(token).find()) { + Matcher matcher = HURRICANE_PATTERN.matcher(token); + matcher.find(); + secondaryid = matcher.group(1); + datasetid = "GHM"; + if (nameTokens[2].equalsIgnoreCase("gribn3")) { + datasetid = "GHMNEST"; + } else if (nameTokens[2].equalsIgnoreCase("grib6th")) { + datasetid = "GHM6TH"; + } else if (nameTokens[2].equalsIgnoreCase("hwrfprs_n")) { + datasetid = "HWRFNEST"; + } else if (nameTokens[2].equalsIgnoreCase("hwrfprs_p")) { + datasetid = "HWRF"; + } + } + } + datasetid = GridLookupFileName.getInstance().getModelName(flName); + if (datasetid != null) { + exchange.getIn().setHeader("datasetid", datasetid); + } + if (secondaryid == null) { + secondaryid = nameTokens[0]; + } + exchange.getIn().setHeader("secondaryid", secondaryid); + if (ensembleid != null) { + exchange.getIn().setHeader("ensembleid", ensembleid); + } + } + +} diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.ncuair/unit-test/gov/noaa/nws/ncep/edex/plugin/ncuair/util/NcUairParserTest.java b/ncep/gov.noaa.nws.ncep.edex.plugin.ncuair/unit-test/gov/noaa/nws/ncep/edex/plugin/ncuair/util/NcUairParserTest.java index 7473710da0..95346b8f71 100644 --- a/ncep/gov.noaa.nws.ncep.edex.plugin.ncuair/unit-test/gov/noaa/nws/ncep/edex/plugin/ncuair/util/NcUairParserTest.java +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.ncuair/unit-test/gov/noaa/nws/ncep/edex/plugin/ncuair/util/NcUairParserTest.java @@ -5,32 +5,16 @@ * * L. Lin 04/09 Creation * S. Gurung 09/11 Renamed H5 to Nc and h5 to nc + * D. Johnson 08/12 Upgrade to JUnit 4.10. * * */ package gov.noaa.nws.ncep.edex.plugin.ncuair.util; -import static org.junit.Assert.*; -import java.util.Calendar; -import org.junit.Test; +import static org.junit.Assert.assertEquals; + import org.junit.Before; - -import gov.noaa.nws.ncep.common.dataplugin.ncuair.NcUairLiftedIndex; -import gov.noaa.nws.ncep.common.dataplugin.ncuair.NcUairMaxWind; -import gov.noaa.nws.ncep.common.dataplugin.ncuair.NcUairObsLevels; -import gov.noaa.nws.ncep.common.dataplugin.ncuair.NcUairTropopause; -import gov.noaa.nws.ncep.common.dataplugin.ncuair.NcUairRecord; -import gov.noaa.nws.ncep.edex.plugin.ncuair.util.NcUairParser; -import gov.noaa.nws.ncep.edex.plugin.ncuair.util.NcUairWindGroup; -import gov.noaa.nws.ncep.common.tools.IDecoderConstantsN; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.*; - -import gov.noaa.nws.ncep.edex.tools.decoder.MndTime; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.TimeZone; +import org.junit.Test; public class NcUairParserTest { String report = "USUS41 KLWX 190000\r\r\n" + @@ -68,7 +52,7 @@ public class NcUairParserTest { @Test public void testGetUairType() { Integer uairType = NcUairParser.getUairType("TTAA"); - assertEquals( 1, uairType); + assertEquals(1, uairType.intValue()); } } diff --git a/ncep/gov.noaa.nws.ncep.edex.plugin.stormtrack/unit-test/gov/noaa/nws/ncep/edex/plugin/stormtrack/util/StormTrackParserTest.java b/ncep/gov.noaa.nws.ncep.edex.plugin.stormtrack/unit-test/gov/noaa/nws/ncep/edex/plugin/stormtrack/util/StormTrackParserTest.java index b43c857f3c..478a29240a 100644 --- a/ncep/gov.noaa.nws.ncep.edex.plugin.stormtrack/unit-test/gov/noaa/nws/ncep/edex/plugin/stormtrack/util/StormTrackParserTest.java +++ b/ncep/gov.noaa.nws.ncep.edex.plugin.stormtrack/unit-test/gov/noaa/nws/ncep/edex/plugin/stormtrack/util/StormTrackParserTest.java @@ -1,8 +1,7 @@ package gov.noaa.nws.ncep.edex.plugin.stormtrack.util; -import static org.junit.Assert.*; -import gov.noaa.nws.ncep.common.dataplugin.stormtrack.*; -import gov.noaa.nws.ncep.edex.plugin.stormtrack.util.StormTrackParser; +import static org.junit.Assert.assertEquals; +import gov.noaa.nws.ncep.common.dataplugin.stormtrack.StormTrackRecord; import java.util.Calendar; @@ -19,23 +18,23 @@ public class StormTrackParserTest { public void testProcessLatLon() { Float latLon; latLon = StormTrackParser.processLatLon("975W"); - assertEquals (-97.5, latLon); + assertEquals(-97.5, latLon.doubleValue()); latLon = StormTrackParser.processLatLon("1605E"); - assertEquals (160.5, latLon); + assertEquals(160.5, latLon.doubleValue()); latLon = StormTrackParser.processLatLon("1605W"); - assertEquals (-160.5, latLon); + assertEquals(-160.5, latLon.doubleValue()); latLon = StormTrackParser.processLatLon("623E"); - assertEquals (62.3, latLon); + assertEquals(62.3, latLon.doubleValue()); latLon = StormTrackParser.processLatLon("62N"); - assertEquals (6.2, latLon); + assertEquals(6.2, latLon.doubleValue()); latLon = StormTrackParser.processLatLon("847S"); - assertEquals (-84.7, latLon); + assertEquals(-84.7, latLon.doubleValue()); latLon = StormTrackParser.processLatLon("847G"); - assertEquals (999999., latLon); + assertEquals(999999., latLon.doubleValue()); latLon = StormTrackParser.processLatLon(""); - assertEquals (999999., latLon); + assertEquals(999999., latLon.doubleValue()); latLon = StormTrackParser.processLatLon(" "); - assertEquals (999999., latLon); + assertEquals(999999., latLon.doubleValue()); } @Test diff --git a/ncep/gov.noaa.nws.ncep.edex.uengine/META-INF/MANIFEST.MF b/ncep/gov.noaa.nws.ncep.edex.uengine/META-INF/MANIFEST.MF index 23980f3bf8..0c4e5ccdbb 100644 --- a/ncep/gov.noaa.nws.ncep.edex.uengine/META-INF/MANIFEST.MF +++ b/ncep/gov.noaa.nws.ncep.edex.uengine/META-INF/MANIFEST.MF @@ -11,8 +11,9 @@ Require-Bundle: com.raytheon.edex.uengine, com.raytheon.uf.common.message;bundle-version="1.11.7", com.raytheon.edex.plugin.satellite;bundle-version="1.11.7", com.raytheon.edex.plugin.radar;bundle-version="1.11.7", - com.raytheon.edex.plugin.grib;bundle-version="1.11.22", - com.raytheon.uf.common.dataplugin.grib;bundle-version="1.11.22", + com.raytheon.uf.edex.plugin.grid, + com.raytheon.uf.common.dataplugin.grid, + com.raytheon.uf.common.parameter, com.raytheon.uf.common.datastorage.hdf5;bundle-version="1.11.22", gov.noaa.nws.ncep.edex.common;bundle-version="1.0.0", gov.noaa.nws.ncep.common.dataplugin.mcidas;bundle-version="1.0.0", @@ -24,7 +25,8 @@ Require-Bundle: com.raytheon.edex.uengine, com.raytheon.uf.common.dataplugin.level;bundle-version="1.12.1174", com.raytheon.uf.common.pointdata;bundle-version="1.12.1174", gov.noaa.nws.ncep.edex.plugin.ncgrib;bundle-version="1.0.0", - gov.noaa.nws.ncep.common.dataplugin.ncuair;bundle-version="1.0.0" + gov.noaa.nws.ncep.common.dataplugin.ncuair;bundle-version="1.0.0", + com.raytheon.uf.common.gridcoverage;bundle-version="1.0.0" Export-Package: gov.noaa.nws.ncep.edex.uengine.output, gov.noaa.nws.ncep.edex.uengine.tasks.radar, gov.noaa.nws.ncep.edex.uengine.tasks.response, diff --git a/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/tasks/profile/MdlSoundingQuery.java b/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/tasks/profile/MdlSoundingQuery.java index a9cf65cb20..17cdad73db 100644 --- a/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/tasks/profile/MdlSoundingQuery.java +++ b/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/tasks/profile/MdlSoundingQuery.java @@ -41,7 +41,8 @@ import com.raytheon.uf.edex.database.dao.CoreDao; import com.raytheon.uf.edex.database.dao.DaoConfig; import com.raytheon.uf.edex.database.query.DatabaseQuery; import com.raytheon.edex.uengine.tasks.query.TableQuery; -import com.raytheon.uf.common.dataplugin.grib.GribRecord; +import com.raytheon.uf.common.dataplugin.grid.GridConstants; +import com.raytheon.uf.common.dataplugin.grid.GridRecord; import java.awt.Point; import org.geotools.coverage.grid.GridGeometry2D; @@ -70,7 +71,7 @@ import com.vividsolutions.jts.geom.impl.CoordinateArraySequence; public class MdlSoundingQuery { private static final String NCGRIB_TBL_NAME = "ncgrib"; - private static final String D2DGRIB_TBL_NAME = "grib"; + private static final String D2DGRIB_TBL_NAME = "grid"; private static String NC_PARMS = "HGHT, UREL, VREL, TMPK, OMEG, RELH"; //private static String NC_PARMS = "HGHT, UREL, VREL, TMPK, DWPK, SPFH, OMEG, RELH"; @@ -104,12 +105,12 @@ public class MdlSoundingQuery { }else if(currentDBTblName.equals(D2DGRIB_TBL_NAME)){ TableQuery query; try { - query = new TableQuery("metadata", GribRecord.class.getName()); + query = new TableQuery("metadata", GridRecord.class.getName()); query.setDistinctField("dataTime.refTime"); - query.addParameter("modelInfo.modelName", mdlType); + query.addParameter(GridConstants.DATASET_ID, mdlType); query.setSortBy("dataTime.refTime", false); @SuppressWarnings("unchecked") - List recList = (List) query.execute(); + List recList = (List) query.execute(); tl.setTimeLines(recList.toArray()); } catch (DataAccessLayerException e) { // TODO Auto-generated catch block @@ -144,13 +145,13 @@ public class MdlSoundingQuery { else if(currentDBTblName.equals(D2DGRIB_TBL_NAME)){ TableQuery query; try { - query = new TableQuery("metadata", GribRecord.class.getName()); + query = new TableQuery("metadata", GridRecord.class.getName()); query.setDistinctField("dataTime.validPeriod.start"); - query.addParameter("modelInfo.modelName", mdlType); + query.addParameter(GridConstants.DATASET_ID, mdlType); query.addParameter("dataTime.refTime", refTimeStr + ":00:00"); query.setSortBy("dataTime.validPeriod.start", true); @SuppressWarnings("unchecked") - List recList = (List) query.execute(); + List recList = (List) query.execute(); tl.setTimeLines(recList.toArray()); } catch (DataAccessLayerException e) { // TODO Auto-generated catch block @@ -406,21 +407,21 @@ public class MdlSoundingQuery { } } else if (pluginName.equalsIgnoreCase(D2DGRIB_TBL_NAME)) { - CoreDao dao = new CoreDao(DaoConfig.forClass(GribRecord.class)); - DatabaseQuery query = new DatabaseQuery(GribRecord.class.getName()); + CoreDao dao = new CoreDao(DaoConfig.forClass(GridRecord.class)); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); query.setMaxResults(new Integer(1)); - query.addQueryParam("modelInfo.modelName", modelName); + query.addQueryParam(GridConstants.DATASET_ID, modelName); query.addQueryParam("dataTime.refTime", refTime); query.addQueryParam("dataTime.validPeriod.start", validTime); try { - List recList = ((List) dao + List recList = ((List) dao .queryByCriteria(query)); if (recList.size() == 0) { return false; } else { - GribRecord rec = recList.get(0); + GridRecord rec = recList.get(0); spatialArea = rec.getSpatialObject(); } @@ -517,21 +518,21 @@ public class MdlSoundingQuery { } } else if (pluginName.equalsIgnoreCase(D2DGRIB_TBL_NAME)) { - CoreDao dao = new CoreDao(DaoConfig.forClass(GribRecord.class)); - DatabaseQuery query = new DatabaseQuery(GribRecord.class.getName()); + CoreDao dao = new CoreDao(DaoConfig.forClass(GridRecord.class)); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); query.setMaxResults(new Integer(1)); - query.addQueryParam("modelInfo.modelName", modelName); + query.addQueryParam(GridConstants.DATASET_ID, modelName); query.addQueryParam("dataTime.refTime", refTime); query.addQueryParam("dataTime.validPeriod.start", validTime); try { - List recList = ((List) dao + List recList = ((List) dao .queryByCriteria(query)); if (recList.size() == 0) { return false; } else { - GribRecord rec = recList.get(0); + GridRecord rec = recList.get(0); spatialArea = rec.getSpatialObject(); } @@ -626,20 +627,20 @@ public class MdlSoundingQuery { } } else if (pluginName.equalsIgnoreCase(D2DGRIB_TBL_NAME)) { - CoreDao dao = new CoreDao(DaoConfig.forClass(GribRecord.class)); - DatabaseQuery query = new DatabaseQuery(GribRecord.class.getName()); + CoreDao dao = new CoreDao(DaoConfig.forClass(GridRecord.class)); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); - query.addQueryParam("modelInfo.level.levelonevalue", "0.0"); - query.addQueryParam("modelInfo.level.leveltwovalue", "-999999.0"); - query.addQueryParam("modelInfo.level.masterLevel.name", "MSL"); - query.addQueryParam("modelInfo.parameterAbbreviation", "PMSL"); - query.addQueryParam("modelInfo.modelName", modelName); + query.addQueryParam(GridConstants.LEVEL_ONE, "0.0"); + query.addQueryParam(GridConstants.LEVEL_TWO, "-999999.0"); + query.addQueryParam(GridConstants.MASTER_LEVEL_NAME, "MSL"); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "PMSL"); + query.addQueryParam(GridConstants.DATASET_ID, modelName); query.addQueryParam("dataTime.refTime", refTime); query.addQueryParam("dataTime.validPeriod.start", validTime); - GribRecord rec = null; + GridRecord rec = null; try { - List recList = ((List) dao + List recList = ((List) dao .queryByCriteria(query)); if (recList.size() == 0) { return null; @@ -817,19 +818,19 @@ public class MdlSoundingQuery { } } else if (pluginName.equalsIgnoreCase(D2DGRIB_TBL_NAME)) { - List recList = new ArrayList(); ; + List recList = new ArrayList(); ; TableQuery query; try { query = new TableQuery("metadata", - GribRecord.class.getName()); - query.addParameter("modelInfo.level.masterLevel.name", "MB"); - query.addParameter("modelInfo.modelName", modelName); - query.addList("modelInfo.parameterAbbreviation", + GridRecord.class.getName()); + query.addParameter(GridConstants.MASTER_LEVEL_NAME, "MB"); + query.addParameter(GridConstants.DATASET_ID, modelName); + query.addList(GridConstants.PARAMETER_ABBREVIATION, D2D_PARMS); query.addParameter("dataTime.refTime", refTime); query.addParameter("dataTime.validPeriod.start", validTime); - query.setSortBy("modelInfo.level.levelonevalue", false); - recList = (List) query.execute(); + query.setSortBy(GridConstants.LEVEL_ONE, false); + recList = (List) query.execute(); if (recList.size() != 0) { PointIn pointIn = new PointIn(pluginName, recList.get(0)); fdataArrayList = pointIn.getHDF5GroupDataPoints(recList.toArray(),points); @@ -858,10 +859,10 @@ public class MdlSoundingQuery { double pressure= (Double)level; soundingLy.setPressure( (float)pressure); for (int i=0; i < recArray.length; i++) { - GribRecord rec1 = (GribRecord)recArray[i]; + GridRecord rec1 = (GridRecord)recArray[i]; float fdata = fdataArray[i]; - if(rec1.getModelInfo().getLevelOneValue() == pressure){ - String prm = rec1.getModelInfo().getParameterAbbreviation(); + if(rec1.getLevel().getLevelonevalue() == pressure){ + String prm = rec1.getParameter().getAbbreviation(); switch (D2DParmNames.valueOf(prm)) { case GH: soundingLy.setGeoHeight(fdata); @@ -1160,16 +1161,16 @@ public class MdlSoundingQuery { } } else if (pluginName.equalsIgnoreCase(D2DGRIB_TBL_NAME)) { - CoreDao dao = new CoreDao(DaoConfig.forClass(GribRecord.class)); - DatabaseQuery query = new DatabaseQuery(GribRecord.class.getName()); - query.addDistinctParameter("modelInfo.level.levelonevalue"); - query.addQueryParam("modelInfo.parameterAbbreviation", "GH"); - query.addQueryParam("modelInfo.level.masterLevel.name", "MB"); + CoreDao dao = new CoreDao(DaoConfig.forClass(GridRecord.class)); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); + query.addDistinctParameter(GridConstants.LEVEL_ONE); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "GH"); + query.addQueryParam(GridConstants.MASTER_LEVEL_NAME, "MB"); - query.addQueryParam("modelInfo.modelName", modelName); + query.addQueryParam(GridConstants.DATASET_ID, modelName); query.addQueryParam("dataTime.refTime", refTime); query.addQueryParam("dataTime.validPeriod.start", validTime); - query.addOrder("modelInfo.level.levelonevalue", false); + query.addOrder(GridConstants.LEVEL_ONE, false); try { return (List) dao.queryByCriteria(query); @@ -1237,20 +1238,20 @@ public class MdlSoundingQuery { } else if (pluginName.equalsIgnoreCase(D2DGRIB_TBL_NAME)) { - CoreDao dao = new CoreDao(DaoConfig.forClass(GribRecord.class)); - DatabaseQuery query = new DatabaseQuery(GribRecord.class.getName()); + CoreDao dao = new CoreDao(DaoConfig.forClass(GridRecord.class)); + DatabaseQuery query = new DatabaseQuery(GridRecord.class.getName()); - query.addQueryParam("modelInfo.parameterAbbreviation", "GH"); - query.addQueryParam("modelInfo.level.masterLevel.name", "MB"); - query.addQueryParam("modelInfo.modelName", modelName); + query.addQueryParam(GridConstants.PARAMETER_ABBREVIATION, "GH"); + query.addQueryParam(GridConstants.MASTER_LEVEL_NAME, "MB"); + query.addQueryParam(GridConstants.DATASET_ID, modelName); query.addQueryParam("dataTime.refTime", refTime); query.addQueryParam("dataTime.validPeriod.start", validTime); - query.addQueryParam("modelInfo.level.levelonevalue", level); - query.addQueryParam("modelInfo.level.leveltwovalue", "-999999.0"); + query.addQueryParam(GridConstants.LEVEL_ONE, level); + query.addQueryParam(GridConstants.LEVEL_TWO, "-999999.0"); - GribRecord rec; + GridRecord rec; try { - List recList = ((List) dao + List recList = ((List) dao .queryByCriteria(query)); if (recList.size() == 0) { return null; diff --git a/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/utility/GempakConvert.java b/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/utility/GempakConvert.java index 12b8febed0..13a61d1330 100644 --- a/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/utility/GempakConvert.java +++ b/ncep/gov.noaa.nws.ncep.edex.uengine/src/gov/noaa/nws/ncep/edex/uengine/utility/GempakConvert.java @@ -14,6 +14,11 @@ import java.util.HashMap; import javax.xml.bind.JAXBException; import com.raytheon.uf.common.geospatial.ISpatialObject; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.LambertConformalGridCoverage; +import com.raytheon.uf.common.gridcoverage.LatLonGridCoverage; +import com.raytheon.uf.common.gridcoverage.MercatorGridCoverage; +import com.raytheon.uf.common.gridcoverage.PolarStereoGridCoverage; import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.datastorage.records.IDataRecord; import com.raytheon.uf.common.datastorage.records.ShortDataRecord; @@ -24,11 +29,6 @@ import com.raytheon.uf.common.serialization.DynamicSerializationManager; import com.raytheon.uf.common.serialization.SerializationException; import com.raytheon.uf.common.serialization.DynamicSerializationManager.SerializationType; import com.raytheon.uf.common.time.DataTime; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LambertConformalGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.MercatorGridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.PolarStereoGridCoverage; import com.raytheon.uf.common.dataplugin.satellite.SatMapCoverage; import com.raytheon.uf.common.dataquery.requests.RequestConstraint; diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/categorymap/CATMAPTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/categorymap/CATMAPTest.java index 39233cdec7..2cf173fd26 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/categorymap/CATMAPTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/categorymap/CATMAPTest.java @@ -1,30 +1,33 @@ package gov.noaa.nws.ncep.gempak.parameters.core.categorymap; -import static org.junit.Assert.*; -import gov.noaa.nws.ncep.gempak.parameters.core.categorymap.CatMap; - +import org.junit.Assert; import org.junit.Test; - -/**
-* SOFTWARE HISTORY
-* Date          Ticket#     Engineer     Description
-* ------------ ---------- ----------- --------------------------
-* 16-Nov-2009    194        Archana.S   Initial Creation
-* 20-Nov-2009    194        Archana.S   Updated per review comments:
-*                                         Added a test-case to retrieve the label
-*                                         given a value
-*                                         Updated method names per design changes in the class
-*                                         CATMAP
-*  
-* 
-* @author Archana.S -* @version 1

-{@link gov.noaa.nws.ncep.gempak.parameters.core.categorymap.CatMap}. -*/ +/** + *

+ * SOFTWARE HISTORY
+ * Date          Ticket#     Engineer     Description
+ * ------------ ---------- ----------- --------------------------
+ * 16-Nov-2009    194        Archana.S   Initial Creation
+ * 20-Nov-2009    194        Archana.S   Updated per review comments:
+ *                                         Added a test-case to retrieve the label
+ *                                         given a value
+ *                                         Updated method names per design changes in the class
+ *                                         CATMAP
+ * 25-Aug-2012    743        djohnson    Upgrade to JUnit 4.10.
+ * 
+ * 
+ * + * @author Archana.S + * @version 1 + *

+ * {@link gov.noaa.nws.ncep.gempak.parameters.core.categorymap.CatMap}. + */ public class CATMAPTest { private static int testCaseNumber; + private static final double ALLOWABLE_DOUBLE_DELTA = 0.0001; + /** *Test for valid label/value pair */ @@ -46,16 +49,25 @@ private static int testCaseNumber; } /** - *Test to retrieve matching label given a floating point value - */ + * @param val1 + * @param expected + */ + private void assertEquals(Float val1, double expected) { + Assert.assertEquals(expected, val1.doubleValue(), + ALLOWABLE_DOUBLE_DELTA); + } + + /** + * Test to retrieve matching label given a floating point value + */ @Test public void testGetLabelForValue() { CatMap catmap = new CatMap("ABC=4;acd=2;lmn=0.5;efg=2;hij=2"); - assertEquals(catmap.getMatchingLabelForValue(0.5f),"lmn"); - assertEquals(catmap.getMatchingLabelForValue(4f),"ABC"); - assertEquals(catmap.getMatchingLabelForValue(2f),"acd"); + Assert.assertEquals(catmap.getMatchingLabelForValue(0.5f), "lmn"); + Assert.assertEquals(catmap.getMatchingLabelForValue(4f), "ABC"); + Assert.assertEquals(catmap.getMatchingLabelForValue(2f), "acd"); System.out.println("=====================Test-Case "+testCaseNumber+" ========================"); System.out.println("Test for getting the matching label, given a floating point value"); @@ -75,7 +87,7 @@ private static int testCaseNumber; CatMap catmap = new CatMap("ABC=4;acd=2;lmn=0.5;efg=2;hij=2"); - assertEquals(catmap.getMatchingLabelForValue(0.00005f),null); + Assert.assertNull(catmap.getMatchingLabelForValue(0.00005f)); System.out.println("=====================Test-Case "+testCaseNumber+" ========================"); System.out.println("Test for getting the matching label, given a floating point value not in the list"); diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/contourinterval/CINTTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/contourinterval/CINTTest.java index fa6d889577..320fac04cc 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/contourinterval/CINTTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/contourinterval/CINTTest.java @@ -1,16 +1,13 @@ package gov.noaa.nws.ncep.gempak.parameters.core.contourinterval; -import gov.noaa.nws.ncep.gempak.parameters.core.contourinterval.CINT; - +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.List; - import org.junit.Test; -import static org.junit.Assert.*; /** *

@@ -30,6 +27,7 @@ import static org.junit.Assert.*;
 
 public class CINTTest {
 	
+    private static final double ALLOWABLE_DOUBLE_DELTA = 0.0001;
 	private static int testCaseNumber;
 	private List testList;
 	private List testList2;
@@ -47,10 +45,14 @@ public class CINTTest {
 		    testList = new ArrayList(Arrays.asList(0.5, 9.0));
 		    keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
 		    assertEquals(keySetList,testList);
-		    assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL).doubleValue(), 10);
-		    assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL).doubleValue(), 0.5);
-		    assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL).doubleValue(), 9);
-		    assertEquals(cint.getNumPaddingDigits(CINT.FIRST_ZOOM_LEVEL), 0);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 0.5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 9, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(
+                cint.getNumPaddingDigits(CINT.FIRST_ZOOM_LEVEL).intValue(), 0);
 		    System.out.println("=====================Test-Case "+testCaseNumber+"a ========================");
 		    System.out.println("The input string = " + cint.getUserInputString());
 			System.out.println("Is the contour data string parsed correctly? " + cint.isCINTStringParsed());
@@ -67,10 +69,14 @@ public class CINTTest {
                     20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0));
 		    keySetList = cint2.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
 		    assertEquals(testList2,keySetList);
-		    assertEquals(cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL).doubleValue(), 10);
-		    assertEquals(cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL).doubleValue(), -57);
-		    assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL).doubleValue(), 86);		    
-			assertEquals(cint2.getNumPaddingDigits(CINT.FIRST_ZOOM_LEVEL), 4);
+        assertEquals(cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), -57, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 86, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getNumPaddingDigits(CINT.FIRST_ZOOM_LEVEL)
+                .intValue(), 4);
 			System.out.println("=====================Test-Case "+testCaseNumber+"b ========================");
 			System.out.println("The input string = " + cint2.getUserInputString());
 		    System.out.println("Is the contour data string parsed correctly? " + cint2.isCINTStringParsed());
@@ -158,9 +164,12 @@ public class CINTTest {
 	/*Test for valid contour string of the form contourInterval/minContourValue/ */
 	public void testContourIntervalWithMinValueOnly(){
 		CINT cint = new CINT("-0.345/0/");
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),-0.345);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),0);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);	
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), -0.345, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 0, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
 		
 		System.out.println("=====================Test-Case "+testCaseNumber+" ========================");
 		System.out.println("The input string = " + cint.getUserInputString());
@@ -177,9 +186,12 @@ public class CINTTest {
 	/*Test for valid contour data string of the form contourInterval//maxContourValue */
 	public void testContourIntervalWithMaxValueOnly(){
 		CINT cint = new CINT("15//30");
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),15);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),30);	
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 15, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 30, ALLOWABLE_DOUBLE_DELTA);
 	
 		System.out.println("=====================Test-Case "+testCaseNumber+" ========================");
 		System.out.println("Is the contour data string parsed correctly? " + cint.isCINTStringParsed());
@@ -196,9 +208,12 @@ public class CINTTest {
 		
 		CINT cint = new CINT("-0.5/");
 		assertEquals(cint.isCINTStringParsed(),true);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),-0.5);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), -0.5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
 		
 	    System.out.println("=====================Test-Case "+testCaseNumber+"a ========================");
 	    System.out.println("The input string = " + cint.getUserInputString());
@@ -209,9 +224,12 @@ public class CINTTest {
 
 		CINT cint2 = new CINT("-.89//");
 		assertEquals(cint2.isCINTStringParsed(),true);
-		assertEquals(cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL),-0.89);
-		assertEquals(cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
+        assertEquals(cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), -0.89, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
 		
 	    System.out.println("=====================Test-Case "+testCaseNumber+"b ========================");
 	    System.out.println("The input string = " + cint2.getUserInputString());
@@ -229,9 +247,12 @@ public class CINTTest {
 	/*Test for valid contour data string of the form /minContourValue/maxContourValue */
 	public void testContourIntervalWithNoContourIntervalAndWithMinMaxValueOnly(){
 		CINT cint = new CINT("/10/30");
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),10);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),30);	
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 30, ALLOWABLE_DOUBLE_DELTA);
 	
 		System.out.println("=====================Test-Case "+testCaseNumber+" ========================");
 		System.out.println("The input string = " + cint.getUserInputString());
@@ -249,9 +270,12 @@ public class CINTTest {
 	/*Test for valid contour data string of the form /minContourValue/maxContourValue */
 	public void testContourIntervalWithMinValSameAsMaxValAndNoContourIntervalSpecified(){
 		CINT cint = new CINT("/10/10");
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),10);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),10);	
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
 	    testList = new ArrayList(Arrays.asList(10.0));
 	    keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
 	    assertEquals(keySetList,testList);
@@ -312,9 +336,12 @@ public class CINTTest {
 		
 		CINT cint = new CINT("20/10/70/30/40/500");
 		assertEquals(cint.isCINTStringParsed(), true);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),20);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),10);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),70);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 20, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 70, ALLOWABLE_DOUBLE_DELTA);
 		//
 		testList = new ArrayList(Arrays.asList(10.0, 30.0, 50.0, 60.0));
 	    keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
@@ -338,9 +365,12 @@ public class CINTTest {
 	public void testNonNumericContourIntervalString(){
 		CINT cint = new CINT("-def/abc/%^&/30/40");
 		assertEquals(cint.isCINTStringParsed(), false);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
 		
 		System.out.println("=====================Test-Case "+testCaseNumber+"========================");	
 		System.out.println("The input string      = "+cint.getUserInputString());
@@ -359,9 +389,12 @@ public class CINTTest {
 		
 		CINT cint = new CINT("5.10.60.9");
 		assertEquals(cint.isCINTStringParsed(), false);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),Double.NaN);		
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), Double.NaN, ALLOWABLE_DOUBLE_DELTA);
     	
 		System.out.println("=====================Test-Case "+testCaseNumber+"========================");
 		System.out.println("The input string      = "+cint.getUserInputString());
@@ -379,9 +412,12 @@ public class CINTTest {
 	public void testMinMaxValuesInterchangedContourIntervalString(){
 		CINT cint = new CINT("-5/20/5");
 		assertEquals(cint.isCINTStringParsed(), true);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),-5);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),5);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),20);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), -5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 20, ALLOWABLE_DOUBLE_DELTA);
 		
 	    testList = new ArrayList(Arrays.asList(5.0, 10.0, 15.0, 20.0));
 	    keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
@@ -398,9 +434,12 @@ public class CINTTest {
 		
 		CINT cint2 = new CINT("5/20/5");
 		assertEquals(cint2.isCINTStringParsed(), true);
-		assertEquals(cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL),5);
-		assertEquals(cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),5);
-		assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),20);		
+        assertEquals(cint2.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint2.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 20, ALLOWABLE_DOUBLE_DELTA);
 	    testList = new ArrayList(Arrays.asList(5.0, 10.0, 15.0, 20.0));
 //	    assertEquals(cint2.getContourValuesList(),testList);	
 		
@@ -492,9 +531,12 @@ public class CINTTest {
 	public void testSingleLabelledContourIntervalString(){
 		CINT cint = new CINT("5=good/5/5");
 		assertEquals(cint.isCINTStringParsed(), true);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),0);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),5);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),5);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 0, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 5, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 5, ALLOWABLE_DOUBLE_DELTA);
 		
 	    testList = new ArrayList(Arrays.asList(5.0));
 	    keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
@@ -540,10 +582,14 @@ public class CINTTest {
 		CINT cint = new CINT("1/2/10/3 > 4/2/18");
 		
 		assertEquals(cint.isCINTStringParsed(), true);
-		assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL),1);
-		assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL),2);
-		assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL),10);
-		assertEquals(cint.getNumPaddingDigits(CINT.FIRST_ZOOM_LEVEL),3);
+        assertEquals(cint.getContourInterval(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 1, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMinContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 2, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getMaxContourValue(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 10, ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(cint.getNumPaddingDigits(CINT.FIRST_ZOOM_LEVEL)
+                .doubleValue(), 3, ALLOWABLE_DOUBLE_DELTA);
 		
 	    testList = new ArrayList(Arrays.asList(2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0));
 	    keySetList = cint.getContourValuesListAsDouble(CINT.FIRST_ZOOM_LEVEL);
@@ -591,8 +637,11 @@ public class CINTTest {
 	 	testList = new ArrayList(Arrays.asList(60.0,80.0));
 	    keySetList = cint.getContourValuesListAsDouble(CINT.THIRD_ZOOM_LEVEL);
 	    assertEquals(testList,keySetList);
-	    assertEquals(0.00009999, cint.getContourInterval(CINT.FOURTH_ZOOM_LEVEL));
-	    assertEquals(0.0000001, cint.getContourInterval(CINT.FIFTH_ZOOM_LEVEL));
+        assertEquals(0.00009999, cint
+                .getContourInterval(CINT.FOURTH_ZOOM_LEVEL).doubleValue(),
+                ALLOWABLE_DOUBLE_DELTA);
+        assertEquals(0.0000001, cint.getContourInterval(CINT.FIFTH_ZOOM_LEVEL)
+                .doubleValue(), ALLOWABLE_DOUBLE_DELTA);
 //	 	testList = new ArrayList(Arrays.asList(0.00009999));
 //	    keySetList = cint.getContourValuesListAsDouble(CINT.FOURTH_ZOOM_LEVEL);
 //	    assertEquals(testList,keySetList);
diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/marshaller/garea/MapProjectionTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/marshaller/garea/MapProjectionTest.java
index 9fe3b10a8a..4262506624 100644
--- a/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/marshaller/garea/MapProjectionTest.java
+++ b/ncep/gov.noaa.nws.ncep.gempak.parameters.core/unit_test/gov/noaa/nws/ncep/gempak/parameters/core/marshaller/garea/MapProjectionTest.java
@@ -1,7 +1,6 @@
 package gov.noaa.nws.ncep.gempak.parameters.core.marshaller.garea;
 
-import static org.junit.Assert.*;
-import gov.noaa.nws.ncep.gempak.parameters.core.marshaller.garea.MapProjection;
+import static org.junit.Assert.assertEquals;
 
 import org.junit.Test;
 
@@ -16,14 +15,14 @@ public class MapProjectionTest {
 		MapProjection map_obj = new MapProjection("LCC");
 		assertEquals(map_obj.isProjectionStringValid(),true);
 		Integer[] margins = map_obj.getProjectionMargins();
-	    assertEquals(margins[0],0);
-	    assertEquals(margins[1],3);
-	    assertEquals(margins[2],0);
-	    assertEquals(margins[3],0);
+        assertEquals(margins[0].intValue(), 0);
+        assertEquals(margins[1].intValue(), 3);
+        assertEquals(margins[2].intValue(), 0);
+        assertEquals(margins[3].intValue(), 0);
 	    Float[] angles = map_obj.getProjectionAngles();
-	    assertEquals(angles[0],0);
-	    assertEquals(angles[1],0);
-	    assertEquals(angles[2],0);	    
+        assertEquals(angles[0].intValue(), 0);
+        assertEquals(angles[1].intValue(), 0);
+        assertEquals(angles[2].intValue(), 0);
 
 	}
 
diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/discrete/DiscreteTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/discrete/DiscreteTest.java
index bfc3e41605..88c1e0f1be 100644
--- a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/discrete/DiscreteTest.java
+++ b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/discrete/DiscreteTest.java
@@ -3,43 +3,45 @@
  */
 package gov.noaa.nws.ncep.gempak.parameters.discrete;
 
-import static org.junit.Assert.*;
-
-import gov.noaa.nws.ncep.gempak.parameters.discrete.Discrete;
+import static org.junit.Assert.assertEquals;
 
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.List;
 
-
 import org.junit.Test;
-/**
-* 
-* Junit test for {@link gov.noaa.nws.ncep.gempak.parameters.discrete.Discrete}.
-* 
-* 
-* SOFTWARE HISTORY
-* Date          Ticket#     Engineer     Description
-* ------------ ---------- ----------- --------------------------
-* 10-Dec-2009    205       Archana.S   Initial Creation
-* 18-Dec-2009    205       Archana.S   Updated per review comments:
-*                                      ----------------------------
-*                                      1. Removed all references to hard-coded tolerance value
-*                                         (0.000001) and replaced it with the method
-*                                         getTolerance(). Accordingly updated Javadoc for the corresponding
-*                                         tests. 
-*                                      2. Updated all test-cases, to replace the '-' delimiter in the
-*                                         input string with '~' 
-*                                      3. Added the following test-cases: 
-*                                      a. To parse negative numbers in the Discrete string.
-*                                      b. Test for extra arguments.
-* 
-* 
-* @author Archana.S -* @version 1 -*/ + +/** + *
+ * 
+ * Junit test for {@link gov.noaa.nws.ncep.gempak.parameters.discrete.Discrete}.
+ * 
+ * 
+ * SOFTWARE HISTORY
+ * Date          Ticket#     Engineer     Description
+ * ------------ ---------- ----------- --------------------------
+ * 10-Dec-2009    205       Archana.S   Initial Creation
+ * 18-Dec-2009    205       Archana.S   Updated per review comments:
+ *                                      ----------------------------
+ *                                      1. Removed all references to hard-coded tolerance value
+ *                                         (0.000001) and replaced it with the method
+ *                                         getTolerance(). Accordingly updated Javadoc for the corresponding
+ *                                         tests. 
+ *                                      2. Updated all test-cases, to replace the '-' delimiter in the
+ *                                         input string with '~' 
+ *                                      3. Added the following test-cases: 
+ *                                      a. To parse negative numbers in the Discrete string.
+ *                                      b. Test for extra arguments.
+ * 25-Aug-2012   743        djohnson    Upgrade to JUnit 4.10.
+ * 
+ * + * @author Archana.S + * @version 1 + */ public class DiscreteTest { - private static int testCaseNumber; + private static final double ALLOWABLE_DOUBLE_DELTA = 0.1; + + private static int testCaseNumber; private List testList; /** * Test valid input string with multiple start/end/discrete value strings. @@ -64,33 +66,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -121,33 +123,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -179,33 +181,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -238,33 +240,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -297,33 +299,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -356,33 +358,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -414,33 +416,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -461,7 +463,7 @@ public class DiscreteTest { System.out.println("Test input string with invalid delimiters\n"); System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Size of discrete data list = "+discreteObj.getDiscreteDataList().size()); - assertEquals(discreteObj.getDiscreteDataList().size(), 0); + assertEquals(discreteObj.getDiscreteDataList().size(), 0); testCaseNumber++; System.out.println("=========================================="); } @@ -493,33 +495,33 @@ public class DiscreteTest { System.out.println("Discrete value = "+discreteObj .getDiscreteDataList().get(i).getDiscreteValue()); if(i==0){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(0)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(1)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(2)); } else if(i==1){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(3)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(4)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(5)); } else if(i==2){ - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getStartValue(),testList.get(6)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getEndValue(),testList.get(7)); - assertEquals(discreteObj.getDiscreteDataList() + assertFloatComparison(discreteObj.getDiscreteDataList() .get(i).getDiscreteValue(),testList.get(8)); } } @@ -556,7 +558,7 @@ public class DiscreteTest { System.out.println("Test empty string\n"); System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Size of discrete data list = "+discreteObj.getDiscreteDataList().size()); - assertEquals(discreteObj.getDiscreteDataList().size(), 0); + assertEquals(discreteObj.getDiscreteDataList().size(), 0); Discrete discreteObj2 = new Discrete(null); @@ -565,7 +567,7 @@ public class DiscreteTest { System.out.println("Test empty string\n"); System.out.println("The input string is "+discreteObj2.getStrDiscrete()); System.out.println("Size of discrete data list = "+discreteObj2.getDiscreteDataList().size()); - assertEquals(discreteObj2.getDiscreteDataList().size(), 0); + assertEquals(discreteObj2.getDiscreteDataList().size(), 0); Discrete discreteObj3 = new Discrete(" "); @@ -573,7 +575,7 @@ public class DiscreteTest { System.out.println("Test empty string\n"); System.out.println("The input string is "+discreteObj3.getStrDiscrete()); System.out.println("Size of discrete data list = "+discreteObj3.getDiscreteDataList().size()); - assertEquals(discreteObj3.getDiscreteDataList().size(), 0); + assertEquals(discreteObj3.getDiscreteDataList().size(), 0); System.out.println("=========================================="); testCaseNumber++; @@ -591,7 +593,7 @@ public class DiscreteTest { System.out.println("Test input string with non numeric inputs\n"); System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Size of discrete data list = "+discreteObj.getDiscreteDataList().size()); - assertEquals(discreteObj.getDiscreteDataList().size(), 0); + assertEquals(discreteObj.getDiscreteDataList().size(), 0); testCaseNumber++; System.out.println("=========================================="); } @@ -609,19 +611,31 @@ public class DiscreteTest { System.out.println("Discrete Value to the left of 3.6 = "+discreteObj.getPrecedingDiscreteValue(3.6f)); System.out.println("Discrete Value to the left of 0.444 = "+discreteObj.getPrecedingDiscreteValue(0.444f)); - assertEquals(discreteObj.getPrecedingDiscreteValue(3.6f), 1.105f); - assertEquals(discreteObj.getPrecedingDiscreteValue(0.444f),0.444f); + assertFloatComparison(discreteObj.getPrecedingDiscreteValue(3.6f), + 1.105f); + assertFloatComparison(discreteObj.getPrecedingDiscreteValue(0.444f), + 0.444f); testCaseNumber++; System.out.println("=========================================="); } - - /** - * Test the method getDiscreteValueClosestToTwoContourLines() when the following conditions are satisfied: - * The absolute difference between the current start value and the first parameter in the function is - * less than the tolerance value and - * The absolute difference between the current end value and the second parameter in the function is - * less than the tolerance value - */ + + /** + * @param precedingDiscreteValue + * @param f + */ + private void assertFloatComparison(Float precedingDiscreteValue, float f) { + assertEquals(precedingDiscreteValue.floatValue(), f, + ALLOWABLE_DOUBLE_DELTA); + } + + /** + * Test the method getDiscreteValueClosestToTwoContourLines() when the + * following conditions are satisfied: The absolute difference between the + * current start value and the first parameter in the function is less than + * the tolerance value and The absolute difference between the current end + * value and the second parameter in the function is less than the tolerance + * value + */ @Test public void testGetDiscreteValueClosestToTwoContourLines1(){ Discrete discreteObj = new Discrete("0.1~.5=0.444;0.6~0.9=0.75;0.99~1.15=1.105;1.25~3.5=3.6"); @@ -635,7 +649,9 @@ public class DiscreteTest { System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Discrete Value between 0.99 and 1.15 = "+discreteObj.getDiscreteValueClosestToTwoContourLines(0.99f,1.15f)); - assertEquals(discreteObj.getDiscreteValueClosestToTwoContourLines(0.99f, 1.15f),1.105f); + assertFloatComparison( + discreteObj.getDiscreteValueClosestToTwoContourLines(0.99f, + 1.15f), 1.105f); testCaseNumber++; System.out.println("=========================================="); @@ -661,7 +677,9 @@ public class DiscreteTest { System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Discrete Value between 0.990001 and 1.15 = "+discreteObj.getDiscreteValueClosestToTwoContourLines(0.990001f,1.15f)); - assertEquals(discreteObj.getDiscreteValueClosestToTwoContourLines(0.990001f, 1.15f),Float.NaN); + assertFloatComparison( + discreteObj.getDiscreteValueClosestToTwoContourLines(0.990001f, + 1.15f), Float.NaN); testCaseNumber++; System.out.println("=========================================="); @@ -687,7 +705,9 @@ public class DiscreteTest { System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Discrete Value between 0.99 and 1.150001 = "+discreteObj.getDiscreteValueClosestToTwoContourLines(0.99f,1.150001f)); - assertEquals(discreteObj.getDiscreteValueClosestToTwoContourLines(0.99f, 1.150001f),Float.NaN); + assertFloatComparison( + discreteObj.getDiscreteValueClosestToTwoContourLines(0.99f, + 1.150001f), Float.NaN); testCaseNumber++; System.out.println("=========================================="); @@ -716,7 +736,9 @@ public class DiscreteTest { System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Discrete Value between Float.MAX-VALUE and 1.15 = "+discreteObj.getDiscreteValueClosestToTwoContourLines(Float.MAX_VALUE, 0.5f)); - assertEquals(discreteObj.getDiscreteValueClosestToTwoContourLines(Float.MAX_VALUE, 0.5f),0.444f); + assertFloatComparison( + discreteObj.getDiscreteValueClosestToTwoContourLines( + Float.MAX_VALUE, 0.5f), 0.444f); testCaseNumber++; System.out.println("=========================================="); @@ -744,7 +766,9 @@ public class DiscreteTest { System.out.println("The input string is "+discreteObj.getStrDiscrete()); System.out.println("Discrete Value between 1.25 and Float.MAX-VALUE = "+discreteObj.getDiscreteValueClosestToTwoContourLines(1.25f,Float.MAX_VALUE)); - assertEquals(discreteObj.getDiscreteValueClosestToTwoContourLines(1.25f,Float.MAX_VALUE),3.6f); + assertFloatComparison( + discreteObj.getDiscreteValueClosestToTwoContourLines(1.25f, + Float.MAX_VALUE), 3.6f); testCaseNumber++; System.out.println("=========================================="); @@ -765,10 +789,13 @@ public class DiscreteTest { System.out.println("The starting value="+discreteObj.getDiscreteDataList().get(0).getStartValue()); System.out.println("The ending value="+discreteObj.getDiscreteDataList().get(0).getEndValue()); System.out.println("The discrete value="+discreteObj.getDiscreteDataList().get(0).getDiscreteValue()); - assertEquals(discreteObj.getDiscreteDataList().size(),1); - assertEquals(discreteObj.getDiscreteDataList().get(0).getStartValue(), 0.1f); - assertEquals(discreteObj.getDiscreteDataList().get(0).getEndValue(), 0.5f); - assertEquals(discreteObj.getDiscreteDataList().get(0).getDiscreteValue(), 0.444f); + assertEquals(discreteObj.getDiscreteDataList().size(), 1); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getStartValue(), 0.1f); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getEndValue(), 0.5f); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getDiscreteValue(), 0.444f); testCaseNumber++; System.out.println("=========================================="); @@ -790,10 +817,13 @@ public class DiscreteTest { System.out.println("The starting value="+discreteObj.getDiscreteDataList().get(0).getStartValue()); System.out.println("The ending value="+discreteObj.getDiscreteDataList().get(0).getEndValue()); System.out.println("The discrete value="+discreteObj.getDiscreteDataList().get(0).getDiscreteValue()); - assertEquals(discreteObj.getDiscreteDataList().size(),1); - assertEquals(discreteObj.getDiscreteDataList().get(0).getStartValue(), 0.1f); - assertEquals(discreteObj.getDiscreteDataList().get(0).getEndValue(), 0.5f); - assertEquals(discreteObj.getDiscreteDataList().get(0).getDiscreteValue(), 0.444f); + assertEquals(discreteObj.getDiscreteDataList().size(), 1); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getStartValue(), 0.1f); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getEndValue(), 0.5f); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getDiscreteValue(), 0.444f); testCaseNumber++; System.out.println("=========================================="); } @@ -813,10 +843,13 @@ public class DiscreteTest { System.out.println("The starting value="+discreteObj.getDiscreteDataList().get(0).getStartValue()); System.out.println("The ending value="+discreteObj.getDiscreteDataList().get(0).getEndValue()); System.out.println("The discrete value="+discreteObj.getDiscreteDataList().get(0).getDiscreteValue()); - assertEquals(discreteObj.getDiscreteDataList().size(),1); - assertEquals(discreteObj.getDiscreteDataList().get(0).getStartValue(), -Float.MAX_VALUE); - assertEquals(discreteObj.getDiscreteDataList().get(0).getEndValue(), 0.5f); - assertEquals(discreteObj.getDiscreteDataList().get(0).getDiscreteValue(), 0.444f); + assertEquals(discreteObj.getDiscreteDataList().size(), 1); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getStartValue(), -Float.MAX_VALUE); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getEndValue(), 0.5f); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getDiscreteValue(), 0.444f); testCaseNumber++; System.out.println("=========================================="); } @@ -837,10 +870,13 @@ public class DiscreteTest { System.out.println("The starting value="+discreteObj.getDiscreteDataList().get(0).getStartValue()); System.out.println("The ending value="+discreteObj.getDiscreteDataList().get(0).getEndValue()); System.out.println("The discrete value="+discreteObj.getDiscreteDataList().get(0).getDiscreteValue()); - assertEquals(discreteObj.getDiscreteDataList().size(),1); - assertEquals(discreteObj.getDiscreteDataList().get(0).getStartValue(),0.5f ); - assertEquals(discreteObj.getDiscreteDataList().get(0).getEndValue(), Float.MAX_VALUE); - assertEquals(discreteObj.getDiscreteDataList().get(0).getDiscreteValue(), 0.444f); + assertEquals(discreteObj.getDiscreteDataList().size(), 1); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getStartValue(), 0.5f); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getEndValue(), Float.MAX_VALUE); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getDiscreteValue(), 0.444f); testCaseNumber++; System.out.println("=========================================="); } @@ -862,10 +898,13 @@ public class DiscreteTest { System.out.println("The starting value="+discreteObj.getDiscreteDataList().get(0).getStartValue()); System.out.println("The ending value="+discreteObj.getDiscreteDataList().get(0).getEndValue()); System.out.println("The discrete value="+discreteObj.getDiscreteDataList().get(0).getDiscreteValue()); - assertEquals(discreteObj.getDiscreteDataList().size(),1); - assertEquals(discreteObj.getDiscreteDataList().get(0).getStartValue(),-Float.MAX_VALUE ); - assertEquals(discreteObj.getDiscreteDataList().get(0).getEndValue(), Float.MAX_VALUE); - assertEquals(discreteObj.getDiscreteDataList().get(0).getDiscreteValue(), 0.444f); + assertEquals(discreteObj.getDiscreteDataList().size(), 1); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getStartValue(), -Float.MAX_VALUE); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getEndValue(), Float.MAX_VALUE); + assertFloatComparison(discreteObj.getDiscreteDataList().get(0) + .getDiscreteValue(), 0.444f); testCaseNumber++; System.out.println("=========================================="); } diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/dlines/DLINESTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/dlines/DLINESTest.java index 94b4ed4e01..c01e14cc79 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/dlines/DLINESTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/dlines/DLINESTest.java @@ -1,21 +1,23 @@ package gov.noaa.nws.ncep.gempak.parameters.dlines; -import static org.junit.Assert.*; -import gov.noaa.nws.ncep.gempak.parameters.dlines.DLines; +import static org.junit.Assert.assertEquals; import org.junit.Test; -/**
-*Junit test-case for DLINES and DLINEData
-*
-* SOFTWARE HISTORY
-* Date          Ticket#     Engineer     Description
-* ------------ ---------- ----------- --------------------------
-* 29-Dec-2009    211        Archana.S    Initial Creation
-* 
-* @author Archana.S -* @version 1 -*/ +/** + *
+ * Junit test-case for DLINES and DLINEData
+ * 
+ *  SOFTWARE HISTORY
+ *  Date          Ticket#     Engineer     Description
+ *  ------------ ---------- ----------- --------------------------
+ *  29-Dec-2009    211        Archana.S    Initial Creation
+ *  25-Aug-2012    743        djohnson     Upgrade to JUnit 4.10.
+ * 
+ * + * @author Archana.S + * @version 1 + */ public class DLINESTest { /** @@ -89,7 +91,8 @@ public class DLINESTest { .isRightOfContourLineGreater().booleanValue(),true); assertEquals("Contour values to the left of the current contour line should be greater",dlines.getDlineData() .isLeftOfContourLineGreater(),true); - assertEquals("Epsilon should be set to 0.25",dlines.getDlineData().getEpsilon(),0.25); + assertEquals("Epsilon should be set to 0.25", dlines + .getDlineData().getEpsilon(), 0.25, 0.01); break; case 1: @@ -98,7 +101,7 @@ public class DLINESTest { assertEquals("Contour values to the left of the current contour line should be greater",dlines.getDlineData() .isLeftOfContourLineGreater(),true); assertEquals("Epsilon should be undefined",dlines.getDlineData() - .getEpsilon(),Double.NaN); +.getEpsilon(), Double.NaN, 0.01); break; case 2: @@ -107,7 +110,7 @@ public class DLINESTest { assertEquals("Contour values to the left of the current contour line should be lesser",dlines.getDlineData() .isLeftOfContourLineGreater(),false); assertEquals("Epsilon should be undefined",dlines.getDlineData() - .getEpsilon(),Double.NaN); +.getEpsilon(), Double.NaN, 0.01); break; case 3: @@ -115,7 +118,8 @@ public class DLINESTest { .isRightOfContourLineGreater().booleanValue(),false); assertEquals("Contour values to the left of the current contour line should be lesser",dlines.getDlineData() .isLeftOfContourLineGreater(),false); - assertEquals("Epsilon should be set to 1.3",dlines.getDlineData().getEpsilon(),1.3); + assertEquals("Epsilon should be set to 1.3", dlines + .getDlineData().getEpsilon(), 1.3, 0.01); break; case 6: @@ -124,7 +128,7 @@ public class DLINESTest { assertEquals("Contour values to the left of the current contour line should be greater",dlines.getDlineData() .isLeftOfContourLineGreater(),true); assertEquals("Epsilon should be undefined",dlines.getDlineData() - .getEpsilon(), Double.NaN); +.getEpsilon(), Double.NaN, 0.01); break; case 7: @@ -133,7 +137,7 @@ public class DLINESTest { assertEquals("Contour values to the left of the current contour line should be lesser",dlines.getDlineData() .isLeftOfContourLineGreater(),false); assertEquals("Epsilon should be undefined",dlines.getDlineData() - .getEpsilon(), Double.NaN); +.getEpsilon(), Double.NaN, 0.01); break; case 8: @@ -142,7 +146,7 @@ public class DLINESTest { assertEquals("Contour values to the left of the current contour line should be greater",dlines.getDlineData() .isLeftOfContourLineGreater(),true); assertEquals("Epsilon should be undefined",dlines.getDlineData() - .getEpsilon(),Double.NaN); +.getEpsilon(), Double.NaN, 0.01); break; case 10: @@ -151,7 +155,7 @@ public class DLINESTest { assertEquals("Contour values to the left of the current contour line should be lesser",dlines.getDlineData() .isLeftOfContourLineGreater(),false); assertEquals("Epsilon should be undefined",dlines.getDlineData() - .getEpsilon(), Double.NaN); +.getEpsilon(), Double.NaN, 0.01); break; default: @@ -164,7 +168,7 @@ public class DLINESTest { dlines.getDlineData().isLeftOfContourLineGreater(), false); assertEquals("Epsilon should be undefined", dlines - .getDlineData().getEpsilon(), Double.NaN); + .getDlineData().getEpsilon(), Double.NaN, 0.01); }else{ assertEquals("DLINES should be null", dlines.getDlineData(), null); } diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/gridlimits/GGLIMSTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/gridlimits/GGLIMSTest.java index 3a67135f53..2d5fb7b841 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/gridlimits/GGLIMSTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/gridlimits/GGLIMSTest.java @@ -1,8 +1,6 @@ package gov.noaa.nws.ncep.gempak.parameters.gridlimits; -import static org.junit.Assert.*; -import gov.noaa.nws.ncep.gempak.parameters.gridlimits.GGLIMS; - +import org.junit.Assert; import org.junit.Test; public class GGLIMSTest { @@ -32,9 +30,17 @@ public class GGLIMSTest { testCaseNumber++; } - /** - * Test valid GGLIMS string of the form lowerLimit;minValue|upperLimit;maxValue + * @param lowerLimit + * @param d + */ + private static void assertEquals(Float lowerLimit, double d) { + Assert.assertEquals(d, lowerLimit.doubleValue(), 0.01); + } + + /** + * Test valid GGLIMS string of the form + * lowerLimit;minValue|upperLimit;maxValue */ @Test public void testGGLIMSStringWithoutDefaultValue() { diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/infill/FINTTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/infill/FINTTest.java index 6051945f86..203d6e98ca 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/infill/FINTTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/infill/FINTTest.java @@ -2,16 +2,18 @@ package gov.noaa.nws.ncep.gempak.parameters.infill; -import gov.noaa.nws.ncep.gempak.parameters.infill.FINT; +import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; + +import org.junit.Assert; import org.junit.Test; -import static org.junit.Assert.*; + /** - *
+ * 
  * SOFTWARE HISTORY
  * Date          Ticket#     Engineer     Description
  * ------------ ---------- ----------- --------------------------
@@ -20,7 +22,9 @@ import static org.junit.Assert.*;
  *                                                            updated code in FINT  
  * 03-Aug-2010     184       Archana.S   Updated test-cases to test
  *                                                            updated code in FINT
+ * 25-Aug-2012     743       djohnson    Upgrade to JUnit 4.10.
  * 
+ * * @author Archana.S * @version 1 */ @@ -76,7 +80,15 @@ public class FINTTest { testCaseNumber++; } - @Test + /** + * @param doubleValue + * @param i + */ + // private static void assertEquals(double doubleValue, int i) { + // Assert.assertEquals(doubleValue, i, 0.001); + // } + + @Test /* Test for valid FINT string of the form fillInterval/minFillValue/maxFillValue * with a negative contourInterval @@ -105,7 +117,7 @@ public class FINTTest { FINT fint = new FINT("66.1;0.1;5000;76;-.999;12233459390;0.00009988;1234.567890"); - assertEquals(fint.isFINTStringParsed(), true); + Assert.assertTrue(fint.isFINTStringParsed()); testList = new ArrayList(Arrays.asList(66.1, 0.1, 5000.0, 76.0, -0.999, 1.223345939E10, 9.988E-5, 1234.56789)); keySetList = fint.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); @@ -126,7 +138,7 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR FINT fint = new FINT(" 66.1 ; 0.1 ; 5000 "); - assertEquals(fint.isFINTStringParsed(), true); + Assert.assertTrue(fint.isFINTStringParsed()); testList = new ArrayList(Arrays.asList(66.1, 0.1, 5000.0)); keySetList = fint.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); assertEquals(keySetList,testList); @@ -146,9 +158,10 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR /*Test for valid FINT string of the form fillInterval/minFillValue/ */ public void testFillIntervalWithMinValueOnly(){ FINT fint = new FINT("-0.345/0/"); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),-0.345); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),0); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), -0.345); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), 0); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); System.out.println("=====================Test-Case "+testCaseNumber+" ========================"); System.out.println("The input string = " + fint.getUserInputString()); @@ -160,14 +173,23 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR testCaseNumber++; } - @Test + /** + * @param fillInterval + * @param d + */ + private void assertDoubleEquals(Double fillInterval, double d) { + Assert.assertEquals(d, fillInterval.doubleValue(), 0.01); + } + + @Test /*Test for valid FINT string of the form fillInterval//maxFillValue */ public void testFillIntervalWithMaxValueOnly(){ FINT fint = new FINT("15//30"); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),15); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),30); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), 15); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), 30); System.out.println("=====================Test-Case "+testCaseNumber+" ========================"); System.out.println("Is the FINT string parsed correctly? " + fint.isFINTStringParsed()); @@ -185,9 +207,11 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR FINT fint = new FINT("-0.5/"); assertEquals(fint.isFINTStringParsed(),true); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),-0.5); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), -0.5); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); System.out.println("=====================Test-Case "+testCaseNumber+"a ========================"); System.out.println("The input string = " + fint.getUserInputString()); @@ -198,9 +222,11 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR FINT fint2 = new FINT("-.89//"); assertEquals(fint2.isFINTStringParsed(),true); - assertEquals(fint2.getFillInterval(FINT.FIRST_ZOOM_LEVEL),-0.89); - assertEquals(fint2.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint2.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); + assertDoubleEquals(fint2.getFillInterval(FINT.FIRST_ZOOM_LEVEL), -0.89); + assertDoubleEquals(fint2.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint2.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); System.out.println("=====================Test-Case "+testCaseNumber+"b ========================"); System.out.println("The input string = " + fint2.getUserInputString()); @@ -218,9 +244,10 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR /*Test for valid FINT string of the form /minFillValue/maxFillValue */ public void testFillIntervalWithNoFillIntervalAndWithMinMaxValueOnly(){ FINT fint = new FINT("/10/30"); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),10); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),30); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), 10); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), 30); System.out.println("=====================Test-Case "+testCaseNumber+" ========================"); System.out.println("The input string = " + fint.getUserInputString()); @@ -239,9 +266,10 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR *and maxFillValue are the same*/ public void testFillIntervalWithMinValSameAsMaxValAndNoFillIntervalSpecified(){ FINT fint = new FINT("/10/10"); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),10); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),10); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), 10); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), 10); testList = new ArrayList(Arrays.asList(10.0)); keySetList = fint.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); assertEquals(keySetList,testList); @@ -292,10 +320,10 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR public void testExtraNumArgsFillIntervalString(){ FINT fint = new FINT("20/10/70/30/40/500"); - assertEquals(fint.isFINTStringParsed(), true); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),20); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),10); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),70); + Assert.assertTrue(fint.isFINTStringParsed()); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), 20); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), 10); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), 70); testList = new ArrayList(Arrays.asList(10.0,30.0,50.0,60.0)); keySetList = fint.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); @@ -318,9 +346,12 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR public void testNonNumericFillIntervalString(){ FINT fint = new FINT("-def/abc/%^&/30/40"); assertEquals(fint.isFINTStringParsed(), false); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); System.out.println("=====================Test-Case "+testCaseNumber+"========================"); System.out.println("The input string = "+fint.getUserInputString()); @@ -339,9 +370,12 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR FINT fint = new FINT("5.10.60.9"); assertEquals(fint.isFINTStringParsed(), false); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),Double.NaN); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), + Double.NaN); System.out.println("=====================Test-Case "+testCaseNumber+"========================"); System.out.println("The input string = "+fint.getUserInputString()); @@ -358,10 +392,10 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR /*Test FINT string by interchanging minFillValue and maxFillValue */ public void testMinMaxValuesInterchangedFillIntervalString(){ FINT fint = new FINT("-5/20/5"); - assertEquals(fint.isFINTStringParsed(), true); - assertEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL),-5); - assertEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),5); - assertEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),20); + Assert.assertTrue(fint.isFINTStringParsed()); + assertDoubleEquals(fint.getFillInterval(FINT.FIRST_ZOOM_LEVEL), -5); + assertDoubleEquals(fint.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), 5); + assertDoubleEquals(fint.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), 20); testList = new ArrayList(Arrays.asList(5.0, 10.0, 15.0, 20.0)); keySetList = fint.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); @@ -376,9 +410,9 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR FINT fint2 = new FINT("5/20/5"); assertEquals(fint2.isFINTStringParsed(), true); - assertEquals(fint2.getFillInterval(FINT.FIRST_ZOOM_LEVEL),5); - assertEquals(fint2.getMinFillValue(FINT.FIRST_ZOOM_LEVEL),5); - assertEquals(fint2.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL),20); + assertDoubleEquals(fint2.getFillInterval(FINT.FIRST_ZOOM_LEVEL), 5); + assertDoubleEquals(fint2.getMinFillValue(FINT.FIRST_ZOOM_LEVEL), 5); + assertDoubleEquals(fint2.getMaxFillValue(FINT.FIRST_ZOOM_LEVEL), 20); testList = new ArrayList(Arrays.asList(5.0, 10.0, 15.0, 20.0)); keySetList = fint2.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); assertEquals(testList,keySetList); @@ -471,7 +505,7 @@ System.out.println("Fill Values List = "+fint.getFillValuesListAsDouble(FINT.FIR @Test public void testFINTMultipleZoomLevels(){ FINT fint = new FINT("2/-6/6/3 > 30;50;80 > 60 ; 80 > 0.00009999 > 0.0000001;"); - assertEquals(fint.isFINTStringParsed(), true); + Assert.assertTrue(fint.isFINTStringParsed()); testList = new ArrayList(Arrays.asList(-6.0, -4.0,-2.0, 0.0, 2.0, 4.0, 6.0)); keySetList = fint.getFillValuesListAsDouble(FINT.FIRST_ZOOM_LEVEL); assertEquals(testList,keySetList); diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/inline/LineDataStringParserTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/inline/LineDataStringParserTest.java index af841b60f7..fe1cdc2dfd 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/inline/LineDataStringParserTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/inline/LineDataStringParserTest.java @@ -1,18 +1,23 @@ package gov.noaa.nws.ncep.gempak.parameters.inline; -import gov.noaa.nws.ncep.gempak.parameters.inline.LineDataStringParser; +import static org.junit.Assert.assertEquals; +import org.junit.Assert; import org.junit.Test; -import static org.junit.Assert.*; + /** - * *
+ * *
+ * 
+ * 
  * SOFTWARE HISTORY
  * Date          Ticket#     Engineer     Description
  * ------------ ---------- ----------- --------------------------
  * 30-Oct-2009    186       Archana.S   Initial Creation 
+ * 25-Aug-2012    743       djohnson    Upgrade to JUnit 4.10.
  * 
+ * * @author Archana.S - * @version 1 + * @version 1 */ @@ -27,9 +32,12 @@ private static Integer testCaseNumber=1; System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.5); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertDoubleComparison(ldsp1.getInstanceOfLineBuilder() + .getPointsFilter().doubleValue(), 0.5); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); System.out.println("List of line patterns: " +ldsp1.getInstanceOfLineBuilder().getLinePatternsList()); @@ -43,7 +51,15 @@ private static Integer testCaseNumber=1; } - @Test + /** + * @param pointsFilter + * @param d + */ + private static void assertDoubleComparison(Double pointsFilter, double d) { + Assert.assertEquals(d, pointsFilter.doubleValue(), 0.01); + } + + @Test public void testValidLineDataStringWithOnlyLineColorInput(){ System.out.println("------------------Test-case "+ testCaseNumber +"a----------------"); @@ -52,9 +68,12 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertDoubleComparison(ldsp1.getInstanceOfLineBuilder() + .getPointsFilter().doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"a? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -72,8 +91,10 @@ private static Integer testCaseNumber=1; if(ldsp2.isLineDataParsed()){ assertEquals(ldsp2.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp2.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp2.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp2.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp2.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp2.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"b? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp2.getInstanceOfLineBuilder().getLineColorsList()); @@ -90,8 +111,10 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp3 = new LineDataStringParser("5"); if(ldsp3.isLineDataParsed()){ assertEquals(ldsp3.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp3.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp3.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp3.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp3.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp3.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"c? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp3.getInstanceOfLineBuilder().getLineColorsList()); @@ -113,9 +136,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("3;2;16/0.67654"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.67654); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.67654); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -136,9 +162,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("3/0.67654"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.67654); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.67654); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -158,9 +187,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("7/0.5/true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.5); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.5); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -180,9 +212,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser(".7"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.7); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.7); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -202,9 +237,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("1.0/TRUE"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),1.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 1.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -226,9 +264,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("7/7"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -248,9 +289,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("8;9;10/2;4/3/2/2"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -270,9 +314,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -292,9 +339,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser(); if(!ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -314,9 +364,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser(""); if(!ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -336,9 +389,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser(" "); if(!ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -358,9 +414,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("132;240;255/4;4;4/5;5;5/3"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -380,9 +439,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("/4;10/6/1/1/0.65789/true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); System.out.println("List of line patterns: " +ldsp1.getInstanceOfLineBuilder().getLinePatternsList()); @@ -401,9 +463,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("144;110//6/1/1/0.65789/true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -423,9 +488,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("4;10/8;9//1/1/0.9999/true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.9999); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.9999); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -445,9 +513,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("4;10/8;9/6;7//1/0.65789/true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -467,9 +538,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("4;10/8;9/6;7/2//0.65789/true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -489,9 +563,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("4;10/8;9/6;7/2/2//true"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -511,9 +588,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("4;10/8;9/6;7/2/1/0.65789/"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -533,9 +613,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("4;10//6;7///0.65789/"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -555,9 +638,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("240;234/28;36/6/1/1/0.4477"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.4477); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.4477); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -577,9 +663,12 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp1 = new LineDataStringParser("2/4/6/1/1/3.65789"); if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -602,9 +691,12 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -626,9 +718,12 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.7); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.7); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -650,9 +745,12 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -674,9 +772,12 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -698,9 +799,12 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.6); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.6); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -722,9 +826,12 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), false); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -746,9 +853,12 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.5); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isSmallContourFlagSuppressed(), true); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.5); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -771,7 +881,8 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isBreakInLineForLabel(),false); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isBreakInLineForLabel(), false); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("Is there a break in the line for the label: " +ldsp1.getInstanceOfLineBuilder().isBreakInLineForLabel()); @@ -788,7 +899,8 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isBreakInLineForLabel(),true); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isBreakInLineForLabel(), true); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"a? "+ldsp1.isLineDataParsed()); System.out.println("Is there a break in the line for the label: " +ldsp1.getInstanceOfLineBuilder().isBreakInLineForLabel()); @@ -798,7 +910,8 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ - assertEquals(ldsp1.getInstanceOfLineBuilder().isBreakInLineForLabel(),true); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .isBreakInLineForLabel(), true); System.out.println("The input string : " +ldsp2.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"b? "+ldsp1.isLineDataParsed()); System.out.println("Is there a break in the line for the label: " +ldsp2.getInstanceOfLineBuilder().isBreakInLineForLabel()); diff --git a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/line/LineDataStringParserTest.java b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/line/LineDataStringParserTest.java index 453b036aa4..0a149ba04f 100644 --- a/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/line/LineDataStringParserTest.java +++ b/ncep/gov.noaa.nws.ncep.gempak.parameters/unit_test/gov/noaa/nws/ncep/gempak/parameters/line/LineDataStringParserTest.java @@ -1,17 +1,23 @@ package gov.noaa.nws.ncep.gempak.parameters.line; -import org.junit.Test; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; import gov.noaa.nws.ncep.viz.common.ui.color.GempakColor; + +import org.junit.Test; + /** - * *
+ * *
+ * 
+ * 
  * SOFTWARE HISTORY
  * Date          Ticket#     Engineer     Description
  * ------------ ---------- ----------- --------------------------
  * 30-Oct-2009    186       Archana.S   Initial Creation 
+ * 25-Aug-2012    743       djohnson    Upgrade to JUnit 4.10.
  * 
+ * * @author Archana.S - * @version 1 + * @version 1 */ @@ -27,8 +33,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.5); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.5); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); int firstColor = ldsp1.getInstanceOfLineBuilder().getLineColorsList().get(0); @@ -54,8 +62,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"a? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -73,8 +83,10 @@ private static Integer testCaseNumber=1; if(ldsp2.isLineDataParsed()){ assertEquals(ldsp2.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp2.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp2.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp2.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp2.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp2.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"b? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp2.getInstanceOfLineBuilder().getLineColorsList()); @@ -91,8 +103,10 @@ private static Integer testCaseNumber=1; LineDataStringParser ldsp3 = new LineDataStringParser("5"); if(ldsp3.isLineDataParsed()){ assertEquals(ldsp3.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp3.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp3.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp3.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp3.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp3.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"c? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp3.getInstanceOfLineBuilder().getLineColorsList()); @@ -115,8 +129,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.67654); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.67654); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -138,8 +154,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.67654); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.67654); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -160,8 +178,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.5); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.5); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -182,8 +202,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.7); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.7); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -204,8 +226,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),1.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 1.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -228,8 +252,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -250,8 +276,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -272,8 +300,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -294,8 +324,10 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -316,8 +348,10 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -338,8 +372,10 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -360,8 +396,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -382,8 +420,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); System.out.println("List of line patterns: " +ldsp1.getInstanceOfLineBuilder().getLineStyleList()); @@ -403,8 +443,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -425,8 +467,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.9999); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.9999); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -447,8 +491,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -469,8 +515,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -491,8 +539,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -513,8 +563,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -535,8 +587,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.65789); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.65789); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -557,8 +611,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.4477); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.4477); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -579,8 +635,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),1); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 1); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -604,8 +662,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -628,8 +688,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.7); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.7); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -652,8 +714,10 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -676,8 +740,10 @@ private static Integer testCaseNumber=1; if(!ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -700,8 +766,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.6); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),2); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.6); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 2); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -724,8 +792,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),false); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.0); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.0); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); @@ -748,8 +818,10 @@ private static Integer testCaseNumber=1; if(ldsp1.isLineDataParsed()){ assertEquals(ldsp1.getInstanceOfLineBuilder().isSmallContourFlagSuppressed(),true); - assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter(),0.5); - assertEquals(ldsp1.getInstanceOfLineBuilder().getLineSmoothingLevel(),0); + assertEquals(ldsp1.getInstanceOfLineBuilder().getPointsFilter() + .doubleValue(), 0.5); + assertEquals(ldsp1.getInstanceOfLineBuilder() + .getLineSmoothingLevel().intValue(), 0); System.out.println("The input string : " +ldsp1.getLineDataString()); System.out.println("Is line data parsed in test-case "+testCaseNumber+"? "+ldsp1.isLineDataParsed()); System.out.println("List of line colors: " +ldsp1.getInstanceOfLineBuilder().getLineColorsList()); diff --git a/ncep/gov.noaa.nws.ncep.ui.nsharp/.classpath b/ncep/gov.noaa.nws.ncep.ui.nsharp/.classpath index 44f12466f5..121e527a93 100644 --- a/ncep/gov.noaa.nws.ncep.ui.nsharp/.classpath +++ b/ncep/gov.noaa.nws.ncep.ui.nsharp/.classpath @@ -3,6 +3,5 @@ - diff --git a/ncep/gov.noaa.nws.ncep.ui.pgen/src/gov/noaa/nws/ncep/ui/pgen/display/SymbolSetElement.java b/ncep/gov.noaa.nws.ncep.ui.pgen/src/gov/noaa/nws/ncep/ui/pgen/display/SymbolSetElement.java index 04902f520a..df617f849e 100644 --- a/ncep/gov.noaa.nws.ncep.ui.pgen/src/gov/noaa/nws/ncep/ui/pgen/display/SymbolSetElement.java +++ b/ncep/gov.noaa.nws.ncep.ui.pgen/src/gov/noaa/nws/ncep/ui/pgen/display/SymbolSetElement.java @@ -7,7 +7,6 @@ */ package gov.noaa.nws.ncep.ui.pgen.display; -import com.raytheon.uf.viz.core.IExtent; import com.raytheon.uf.viz.core.IGraphicsTarget; import com.raytheon.uf.viz.core.PixelCoverage; import com.raytheon.uf.viz.core.drawables.IImage; @@ -15,30 +14,28 @@ import com.raytheon.uf.viz.core.drawables.PaintProperties; import com.raytheon.uf.viz.core.exception.VizException; import com.raytheon.viz.core.gl.images.GLImage; import com.vividsolutions.jts.geom.Coordinate; - /** - * Contains a raster image and information needed to readily display that image - * on a graphics target at one or more locations. + * Contains a raster image and information needed to readily display that image on a graphics target + * at one or more locations. *

- * Objects of this class are typically created from Symbol or SymbolLocationSet - * elements using the DisplayElementFactory class. - * + * Objects of this class are typically created from Symbol or SymbolLocationSet elements using the + * DisplayElementFactory class. * @author sgilbert - * + * */ public class SymbolSetElement implements IDisplayable { /* * The raster image to be displayed */ - private IImage raster; + private final IImage raster; /* * Array of plot locations in pixel coordinates */ - private double[][] locations; + private final double[][] locations; - private Coordinate ul = new Coordinate(), ur = new Coordinate(), + private final Coordinate ul = new Coordinate(), ur = new Coordinate(), lr = new Coordinate(), ll = new Coordinate(); /** @@ -51,12 +48,13 @@ public class SymbolSetElement implements IDisplayable { * @param locations * pixel coordinate locations to display the image */ - public SymbolSetElement(IImage raster, double[][] locations) { + public SymbolSetElement(IImage raster, + double[][] locations) { this.raster = raster; this.locations = locations; } - /** + /** * disposes the resources held by the raster image * * @see gov.noaa.nws.ncep.ui.pgen.display.IDisplayable#dispose() @@ -64,11 +62,11 @@ public class SymbolSetElement implements IDisplayable { @Override public void dispose() { - raster.dispose(); + raster.dispose(); - } + } - /** + /** * Plots the image to the specified graphics target at the various locations * * @see gov.noaa.nws.ncep.ui.pgen.display.IDisplayable#draw(com.raytheon.viz.core.IGraphicsTarget) @@ -76,29 +74,29 @@ public class SymbolSetElement implements IDisplayable { @Override public void draw(IGraphicsTarget target, PaintProperties paintProps) { - double[] loc = new double[3]; + double[] loc = new double[3]; - /* + /* * Scale image */ double halfWidth; double halfHeight; - - IExtent screenExtentInPixels = paintProps.getView().getExtent(); - double screenToWorldRatio = paintProps.getCanvasBounds().width / paintProps.getView().getExtent().getWidth(); double scale = 0.5 / screenToWorldRatio; - halfWidth = raster.getWidth() * scale; - halfHeight = raster.getHeight() * scale; + if (raster instanceof GLImage) { + halfWidth = ((GLImage) raster).getImage().getWidth() * scale; + halfHeight = ((GLImage) raster).getImage().getHeight() * scale; + } else { + halfWidth = raster.getWidth() * scale; + halfHeight = raster.getHeight() * scale; + } - /* + /* * draw raster image at each location */ for (int j = 0; j < locations.length; j++) { loc = locations[j]; - if (loc == null || !screenExtentInPixels.contains(loc)) - continue; ul.x = loc[0] - halfWidth; ul.y = loc[1] - halfHeight; ur.x = loc[0] + halfWidth; diff --git a/ncep/gov.noaa.nws.ncep.viz.common/src/gov/noaa/nws/ncep/viz/common/soundingQuery/NcSoundingQuery.java b/ncep/gov.noaa.nws.ncep.viz.common/src/gov/noaa/nws/ncep/viz/common/soundingQuery/NcSoundingQuery.java index 35e93191e3..3bae9053f2 100644 --- a/ncep/gov.noaa.nws.ncep.viz.common/src/gov/noaa/nws/ncep/viz/common/soundingQuery/NcSoundingQuery.java +++ b/ncep/gov.noaa.nws.ncep.viz.common/src/gov/noaa/nws/ncep/viz/common/soundingQuery/NcSoundingQuery.java @@ -40,7 +40,7 @@ import com.vividsolutions.jts.geom.Coordinate; public class NcSoundingQuery { public static int counter = 1; public static String NCGRIB_PLUGIN_NAME = "ncgrib"; - public static String GRIB_PLUGIN_NAME = "grib"; + public static String GRIB_PLUGIN_NAME = "grid"; public static long convertRefTimeStr(String refTimeStr) { int year, mon, date, hr; int index = refTimeStr.indexOf('-'); diff --git a/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/META-INF/MANIFEST.MF b/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/META-INF/MANIFEST.MF index b0265c9969..6055f59adf 100644 --- a/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/META-INF/MANIFEST.MF +++ b/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/META-INF/MANIFEST.MF @@ -56,9 +56,9 @@ Export-Package: gov.noaa.nws.ncep.viz.rsc.ncgrid, gov.noaa.nws.ncep.viz.rsc.ncgrid.rsc Import-Package: com.raytheon.edex.meteoLib, com.raytheon.uf.common.dataplugin.grib, - com.raytheon.uf.common.dataplugin.grib.spatial.projections, com.raytheon.uf.common.dataplugin.level, com.raytheon.uf.common.derivparam.tree, + com.raytheon.uf.common.gridcoverage, com.raytheon.uf.common.pointdata, com.raytheon.uf.viz.derivparam.data, com.raytheon.uf.viz.derivparam.inv, diff --git a/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/plugin.xml b/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/plugin.xml index de840f6837..6b0e4bc4e7 100644 --- a/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/plugin.xml +++ b/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/plugin.xml @@ -402,7 +402,7 @@ class="gov.noaa.nws.ncep.viz.rsc.ncgrid.NcgribLoggerPreferences" id="gov.noaa.nws.ncep.viz.rsc.ncgrid.NcgribLoggerPreferences" name="Ncgrid Logger" - category="gov.noaa.nws.ncep.viz.common.nceppreferences"> + category="org.eclipse.jface.Prerences"> diff --git a/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/src/gov/noaa/nws/ncep/viz/rsc/ncgrid/rsc/NcgridContourImageryResource.java b/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/src/gov/noaa/nws/ncep/viz/rsc/ncgrid/rsc/NcgridContourImageryResource.java index 4ae50f6a7d..825cfe6511 100644 --- a/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/src/gov/noaa/nws/ncep/viz/rsc/ncgrid/rsc/NcgridContourImageryResource.java +++ b/ncep/gov.noaa.nws.ncep.viz.rsc.ncgrid/src/gov/noaa/nws/ncep/viz/rsc/ncgrid/rsc/NcgridContourImageryResource.java @@ -24,10 +24,10 @@ import org.opengis.referencing.datum.PixelInCell; import com.raytheon.edex.meteoLib.Controller; import com.raytheon.uf.common.dataplugin.PluginDataObject; import com.raytheon.uf.common.dataplugin.grib.GribRecord; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.GridCoverage; -import com.raytheon.uf.common.dataplugin.grib.spatial.projections.LatLonGridCoverage; import com.raytheon.uf.common.geospatial.MapUtil; import com.raytheon.uf.common.geospatial.ReferencedCoordinate; +import com.raytheon.uf.common.gridcoverage.GridCoverage; +import com.raytheon.uf.common.gridcoverage.LatLonGridCoverage; import com.raytheon.uf.common.status.UFStatus; import com.raytheon.uf.common.status.UFStatus.Priority; import com.raytheon.uf.common.time.DataTime; diff --git a/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/__init__.py b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/__init__.py index f73c59de6b..6dd1feb5d1 100644 --- a/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/__init__.py +++ b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/__init__.py @@ -22,7 +22,8 @@ __all__ = [ 'gfe', - 'grib' + 'grib', + 'grid' ] diff --git a/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/__init__.py b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/__init__.py new file mode 100644 index 0000000000..eaa0c74aed --- /dev/null +++ b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/__init__.py @@ -0,0 +1,27 @@ +## +# 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. +## + +# File auto-generated by PythonFileGenerator + +__all__ = [ + 'request' + ] + + diff --git a/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapFiles.py b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/request/DeleteAllGridDataRequest.py similarity index 65% rename from cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapFiles.py rename to pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/request/DeleteAllGridDataRequest.py index 845fb16184..9c627ea874 100644 --- a/cave/com.raytheon.viz.gfe/help/EXAMPLElocalMapFiles.py +++ b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/request/DeleteAllGridDataRequest.py @@ -1,33 +1,33 @@ ## # 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 +# 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 -# +# 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. ## -# Example localMapFiles.py configuration file -# Example of adding a new shapefile. The variable name must match -# the variable names you use in the localMaps.py filename definitions. +# File auto-generated against equivalent DynamicSerialize Java class -TimeZoneMapName = "tz_13sep02" +class DeleteAllGridDataRequest(object): + def __init__(self, modelName=None): + self.modelName = modelName -# Example of overriding the definition in MapFiles.py. In this example, -# the zone shapefile has been updated to the September 13, 2002 version: - -ZoneMapName = 'z_13se02' + def getModelName(self): + return self.modelName + def setModelName(self, modelName): + self.modelName = modelName diff --git a/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/request/__init__.py b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/request/__init__.py new file mode 100644 index 0000000000..7b1a6ed5b5 --- /dev/null +++ b/pythonPackages/dynamicserialize/dstypes/com/raytheon/uf/common/dataplugin/grid/request/__init__.py @@ -0,0 +1,28 @@ +## +# 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. +## + +# File auto-generated by PythonFileGenerator + +__all__ = [ + 'DeleteAllGridDataRequest' + ] + +from DeleteAllGridDataRequest import DeleteAllGridDataRequest + diff --git a/pythonPackages/pypies/pypies/impl/H5pyDataStore.py b/pythonPackages/pypies/pypies/impl/H5pyDataStore.py index 83df964c08..82b2592022 100644 --- a/pythonPackages/pypies/pypies/impl/H5pyDataStore.py +++ b/pythonPackages/pypies/pypies/impl/H5pyDataStore.py @@ -1,19 +1,19 @@ ## # 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. ## @@ -21,17 +21,17 @@ # # h5py implementation of IDataStore -# -# +# +# # SOFTWARE HISTORY -# +# # Date Ticket# Engineer Description # ------------ ---------- ----------- -------------------------- # 06/16/10 njensen Initial Creation. # 05/03/11 9134 njensen Optimized for pointdata -# 10/09/12 rjpeter Optimized __getGroup for retrievals -# -# +# 10/09/12 rjpeter Optimized __getGroup for retrievals +# +# # import h5py, os, numpy, pypies, re, logging, shutil, time, types @@ -48,7 +48,7 @@ from dynamicserialize.dstypes.com.raytheon.uf.common.pypies.response import * logger = pypies.logger timeMap = pypies.timeMap - + vlen_str_type = h5py.new_vlen(str) dataRecordMap = { @@ -70,12 +70,12 @@ REQUEST_ALL.setType('ALL') PURGE_REGEX = re.compile('(/[a-zA-Z]{1,25})/([0-9]{4}-[0-9]{2}-[0-9]{2})_([0-9]{2}):[0-9]{2}:[0-9]{2}') class H5pyDataStore(IDataStore.IDataStore): - + def __init__(self): - pass - - def store(self, request): - fn = request.getFilename() + pass + + def store(self, request): + fn = request.getFilename() f, lock = self.__openFile(fn, 'w') try: recs = request.getRecords() @@ -94,18 +94,18 @@ class H5pyDataStore(IDataStore.IDataStore): except: logger.warn("Exception occurred on file " + fn + ":" + IDataStore._exc()) exc.append(IDataStore._exc()) - failRecs.append(r) - - if ss: + failRecs.append(r) + + if ss: status.setOperationPerformed(ss['op']) - if ss.has_key('index'): + if ss.has_key('index'): status.setIndexOfAppend(ss['index']) t1=time.time() timeMap['store']=t1-t0 resp = StoreResponse() resp.setStatus(status) resp.setExceptions(exc) - resp.setFailedRecords(failRecs) + resp.setFailedRecords(failRecs) return resp finally: t0=time.time() @@ -113,33 +113,34 @@ class H5pyDataStore(IDataStore.IDataStore): t1=time.time() timeMap['closeFile']=t1-t0 LockManager.releaseLock(lock) - - + + def __writeHDF(self, f, record, storeOp): props = record.getProps() if props and not props.getChunked() and props.getCompression() and \ - props.getCompression() != 'NONE': + props.getCompression() != 'NONE': raise StorageException('Data must be chunked to be compressed') - + data = record.retrieveDataObject() - group = self.__getGroup(f, record.getGroup(), create=True) + rootNode=f['/'] + group = self.__getNode(rootNode, record.getGroup(), None, create=True) if record.getMinIndex() is not None and len(record.getMinIndex()): - ss = self.__writePartialHDFDataset(f, data, record.getDimension(), record.getSizes(), record.getName(), - group, props, record.getMinIndex()) + ss = self.__writePartialHDFDataset(f, data, record.getDimension(), record.getSizes(), + group[record.getName()], props, record.getMinIndex()) else: ss = self.__writeHDFDataset(f, data, record.getDimension(), record.getSizes(), record.getName(), group, props, self.__getHdf5Datatype(record), storeOp, record) - - if props and props.getDownscaled(): + + if props and props.getDownscaled(): intName = record.getGroup() + '/' + record.getName() + '-interpolated' - self.__getGroup(f, intName, True) - self.__link(group, intName + '/0', group[record.getName()]) - + intGroup = self.__getNode(rootNode, intName, None, create=True) + self.__link(intGroup, '0', group[record.getName()]) + f.flush() if logger.isEnabledFor(logging.DEBUG): logger.debug("Stored group " + str(record.getGroup()) + " to group " + str(group)) - return ss - + return ss + def __writeHDFDataset(self, f, data, dims, szDims, dataset, group, props, dataType, storeOp, rec): nDims = len(szDims) szDims1 = [None,] * nDims @@ -150,16 +151,16 @@ class H5pyDataStore(IDataStore.IDataStore): if recMaxDims == None or recMaxDims[i] == 0: maxDims[i] = None else: - maxDims[i] = recMaxDims[i] - + maxDims[i] = recMaxDims[i] + if type(data) is numpy.ndarray and data.shape != tuple(szDims1): - data = data.reshape(szDims1) - + data = data.reshape(szDims1) + ss = {} - if dataset in group.keys(): + if dataset in group.keys(): ds = group[dataset] if storeOp == 'STORE_ONLY': - raise StorageException('Dataset ' + str(dataset) + ' already exists in group ' + str(group)) + raise StorageException('Dataset ' + str(dataset) + ' already exists in group ' + str(group)) elif storeOp == 'APPEND': if dims == 1: newSize = [ds.shape[0] + szDims1[0]] @@ -178,35 +179,35 @@ class H5pyDataStore(IDataStore.IDataStore): elif storeOp == 'REPLACE' or storeOp == 'OVERWRITE': if ds.shape != data.shape: ds.resize(data.shape) - ds[()] = data + ds[()] = data ss['op'] = 'REPLACE' - else: - chunk = self.__calculateChunk(nDims, dataType, storeOp, maxDims) + else: + chunk = self.__calculateChunk(nDims, dataType, storeOp, maxDims) compression = None if props: - compression = props.getCompression() + compression = props.getCompression() fillValue = rec.getFillValue() ds = self.__createDatasetInternal(group, dataset, dataType, szDims1, maxDims, chunk, compression, fillValue) #ds = group.create_dataset(dataset, szDims1, dataType, maxshape=maxDims, chunks=chunk, compression=compression) ds[()] = data ss['op'] = 'STORE_ONLY' - + self.__writeProperties(rec, ds) return ss - + def __getHdf5Datatype(self, record): dtype = dataRecordMap[record.__class__] if dtype == types.StringType: from h5py import h5t - size = record.getMaxLength() - if size > 0: - dtype = h5t.py_create('S' + str(size)) + size = record.getMaxLength() + if size > 0: + dtype = h5t.py_create('S' + str(size)) else: dtype = vlen_str_type #dtype.set_strpad(h5t.STR_NULLTERM) - return dtype - - + return dtype + + def __calculateChunk(self, nDims, dataType, storeOp, maxDims): if nDims == 1: chunk = [DEFAULT_CHUNK_SIZE] @@ -222,13 +223,13 @@ class H5pyDataStore(IDataStore.IDataStore): # So fixed dimension gets chunk size of: # blocksize / (fixed dimension size * bytesize) # For example, float of dimensions (infinite, 6) would be - # (int(4096 / (6 * 4)), 6) + # (int(4096 / (6 * 4)), 6) if dataType != vlen_str_type: sizeOfEntry = numpy.dtype(dataType).itemsize else: sizeOfEntry = None - - secondDim = maxDims[1] + + secondDim = maxDims[1] if sizeOfEntry: chunkSize = int(FILESYSTEM_BLOCK_SIZE / (secondDim * sizeOfEntry)) chunk = [chunkSize, secondDim] @@ -239,111 +240,113 @@ class H5pyDataStore(IDataStore.IDataStore): "data with mode " + storeOp + " not supported yet") chunk = tuple(chunk) return chunk - + def __writeProperties(self, dr, dataset): attrs = dr.getDataAttributes() if attrs: - for key in attrs: + for key in attrs: dataset.attrs[key] = attrs[key] - + def __storeInterpolated(self, f, rec, op): if op != 'REPLACE' and op != 'STORE_ONLY': raise StorageException("Only replace and store modes are supported with interpolation enabled") - + # store the base product - ss = self.__writeHDF(f, rec, op) - - sizes = rec.getSizes() + ss = self.__writeHDF(f, rec, op) + + sizes = rec.getSizes() newSzX = sizes[1] newSzY = sizes[0] originalName = rec.getName() originalGroup = rec.getGroup() level = 0 - + # avoid recursive links by turning off downscaling - rec.getProps().setDownscaled(False) + rec.getProps().setDownscaled(False) from PIL import Image import time - + while newSzX > DOWNSCALE_THRESHOLD or newSzY > DOWNSCALE_THRESHOLD: data = rec.retrieveDataObject() # data is potentially 1-dimensional from serialization, ensure it goes to correct 2 dimensions data = data.reshape([newSzX, newSzY]) newSzX = newSzX / 2 - newSzY = newSzY / 2 + newSzY = newSzY / 2 level += 1 rec.setName(str(level)) - rec.setGroup(originalGroup + '/' + originalName + '-interpolated') + rec.setGroup(originalGroup + '/' + originalName + '-interpolated') # satellite data comes in as signed bytes but pil requires unsigned bytes - data = numpy.array(data + 127, dtype=numpy.uint8) + data = numpy.array(data + 127, dtype=numpy.uint8) image = Image.fromarray(data) image = image.resize((newSzY, newSzX)) downsized = numpy.array(image) # transform back to signed bytes downsized = numpy.array(downsized - 127, dtype=numpy.int8) rec.putDataObject(downsized) - rec.setSizes([newSzY, newSzX]) + rec.setSizes([newSzY, newSzX]) self.__writeHDF(f, rec, op) - + return ss - - def __writePartialHDFDataset(self, f, data, dims, szDims, datasetName, group, props, - minIndex): + + def __writePartialHDFDataset(self, f, data, dims, szDims, ds, props, + minIndex): # reverse sizes for hdf5 szDims1 = [None, ] * len(szDims) for i in range(len(szDims)): - szDims1[i] = szDims[len(szDims) - i - 1] + szDims1[i] = szDims[len(szDims) - i - 1] offset = [None, ] * len(minIndex) for i in range(len(minIndex)): - offset[i] = minIndex[len(minIndex) - i - 1] - - ds = group[datasetName] - - # process chunking + offset[i] = minIndex[len(minIndex) - i - 1] + + # process chunking # chunkSize = None # if data.dtype != numpy._string and data.dtype != numpy._object: -# chunkSize = DEFAULT_CHUNK_SIZE +# chunkSize = DEFAULT_CHUNK_SIZE # else: # chunkSize = 1 # chunk = [chunkSize] * len(szDims) data = data.reshape(szDims1) - + endIndex = [offset[0] + szDims1[0], offset[1] + szDims1[1]] ds[offset[0]:endIndex[0], offset[1]:endIndex[1]] = data return {'op':'REPLACE'} - - + + def delete(self, request): fn = request.getFilename() f, lock = self.__openFile(fn, 'w') resp = DeleteResponse() resp.setSuccess(True) deleteFile = False - + try: locs = request.getLocations() for dataset in locs: - ds = self.__getGroup(f, dataset) + ds = self.__getNode(f, None, dataset) grp = ds.parent grp.id.unlink(ds.name) + finally: # check if file has any remaining data sets # if no data sets, flag file for deletion - f.flush() - deleteFile = not self.__hasDataSet(f) - finally: + deleteFile = False + try: + f.flush() + deleteFile = not self.__hasDataSet(f) + except Exception, e: + logger.error('Error occurred checking for dataSets in file [' + str(fn) + ']: ' + IDataStore._exc()) + t0=time.time() f.close() t1=time.time() timeMap['closeFile']=t1-t0 - if deleteFile: try: os.remove(fn) except Exception, e: logger.error('Error occurred deleting file [' + str(fn) + ']: ' + IDataStore._exc()) - + LockManager.releaseLock(lock) return resp @@ -358,18 +361,20 @@ class H5pyDataStore(IDataStore.IDataStore): if self.__hasDataSet(child): return True return False - + def retrieve(self, request): - fn = request.getFilename() + fn = request.getFilename() f, lock = self.__openFile(fn, 'r') try: - group = request.getGroup() + group = request.getGroup() req = request.getRequest() + rootNode=f['/'] if req: - grp = self.__getGroup(f, group) - result = [self.__retrieveInternal(grp, request.getDataset(), req)] + ds = self.__getNode(rootNode, group, request.getDataset()) + result = [self.__retrieveInternal(ds, req)] else: - result = self.__retrieve(f, group, request.getIncludeInterpolated()) + groupNode = self.__getNode(rootNode, group) + result = self.__retrieve(groupNode, request.getIncludeInterpolated()) resp = RetrieveResponse() resp.setRecords(result) return resp @@ -379,32 +384,29 @@ class H5pyDataStore(IDataStore.IDataStore): t1=time.time() timeMap['closeFile']=t1-t0 LockManager.releaseLock(lock) - - - - def __retrieve(self, f, group, includeInterpolated=False): + + + + def __retrieve(self, group, includeInterpolated=False): records = [] - if type(group) is str: - group = self.__getGroup(f, group) datasets = group.keys() for ds in datasets: interpDs = ds.endswith('-interpolated') if includeInterpolated and interpDs: - subresults = self.__retrieve(f, group.name + '/' + ds, False) + subresults = self.__retrieve(group[ds], False) if subresults: records += subresults - elif not interpDs: - rec = self.__retrieveInternal(group, ds, REQUEST_ALL) + elif not interpDs: + rec = self.__retrieveInternal(group[ds], REQUEST_ALL) records.append(rec) - + return records - - def __retrieveInternal(self, grp, dsName, req): - ds = grp[dsName] + + def __retrieveInternal(self, ds, req): rawData = HDF5OpManager.read(ds, req) rec = DataStoreFactory.createStorageRecord(rawData, ds) - return rec - + return rec + def retrieveDatasets(self, request): t6 = time.time() fn = request.getFilename() @@ -420,8 +422,9 @@ class H5pyDataStore(IDataStore.IDataStore): names = request.getDatasetGroupPath() req = request.getRequest() result = [] + rootNode=f['/'] for dsName in names: - ds = self.__getGroup(f, dsName) + ds = self.__getNode(rootNode, None, dsName) t2 = time.time() rawData = HDF5OpManager.read(ds, req) t3 = time.time() @@ -430,7 +433,7 @@ class H5pyDataStore(IDataStore.IDataStore): paramMap[dsName] = ('%.3f' % (diff)) rec = DataStoreFactory.createStorageRecord(rawData, ds) result.append(rec) - + resp = RetrieveResponse() resp.setRecords(result) return resp @@ -439,7 +442,7 @@ class H5pyDataStore(IDataStore.IDataStore): t4 = time.time() LockManager.releaseLock(lock) t5 = time.time() - if logger.isEnabledFor(logging.DEBUG): + if logger.isEnabledFor(logging.DEBUG): logger.debug("pid=" + str(os.getpid()) + " filename=" + fn + \ ", numberOfDatasets/Parameters=" + str(len(names)) + \ ", getLockTime=" + ('%.3f' % (t1-t0)) + \ @@ -447,7 +450,7 @@ class H5pyDataStore(IDataStore.IDataStore): ", releaseLockTime=" + ('%.3f' % (t5-t4)) + \ ", retrieveDatasetsTotal=" + ('%.3f' % (t4-t6)) + \ ", perParamRead=" + str(paramMap)) - + def retrieveGroups(self, request): fn = request.getFilename() f, lock = self.__openFile(fn, 'r') @@ -455,12 +458,14 @@ class H5pyDataStore(IDataStore.IDataStore): groups = request.getGroups() req = request.getRequest() recs = [] + rootNode=f['/'] for group in groups: - grp = self.__getGroup(f, group) + grp = self.__getNode(rootNode, group) datasets = grp.keys() for ds in datasets: - rawData = HDF5OpManager.read(grp[ds], req) - rec = DataStoreFactory.createStorageRecord(rawData, grp[ds]) + dsNode=grp[ds] + rawData = HDF5OpManager.read(dsNode, req) + rec = DataStoreFactory.createStorageRecord(rawData, dsNode) recs.append(rec) resp = RetrieveResponse() resp.setRecords(recs) @@ -471,13 +476,13 @@ class H5pyDataStore(IDataStore.IDataStore): t1=time.time() timeMap['closeFile']=t1-t0 LockManager.releaseLock(lock) - - def getDatasets(self, request): - fn = request.getFilename() + + def getDatasets(self, request): + fn = request.getFilename() f, lock = self.__openFile(fn, 'r') try: grpName = request.getGroup() - grp = self.__getGroup(f, grpName) + grp = self.__getNode(f['/'], grpName) ds = grp.keys() return ds finally: @@ -486,7 +491,7 @@ class H5pyDataStore(IDataStore.IDataStore): t1=time.time() timeMap['closeFile']=t1-t0 LockManager.releaseLock(lock) - + def deleteFiles(self, request): fn = request.getFilename() if os.path.exists(fn): @@ -494,40 +499,40 @@ class H5pyDataStore(IDataStore.IDataStore): self.__recursiveDeleteFiles(fn,request.getDatesToDelete()) else: self.__removeFile(fn) - + # if it didn't succeed, an exception will be thrown and therefore # an error response returned - resp = DeleteResponse() + resp = DeleteResponse() resp.setSuccess(True) return resp - + def createDataset(self, request): fn = request.getFilename() f, lock = self.__openFile(fn, 'w') try: - rec = request.getRecord() + rec = request.getRecord() props = rec.getProps() - if props and not props.getChunked() and props.getCompression != 'NONE': + if props and not props.getChunked() and props.getCompression != 'NONE': raise StorageException("Data must be chunked to be compressed") grp = rec.getGroup() - group = self.__getGroup(f, grp, create=True) - + group = self.__getNode(f['/'], grp, None, create=True) + # reverse sizes for hdf5 szDims = rec.getSizes() szDims1 = [None, ] * len(szDims) for i in range(len(szDims)): szDims1[i] = szDims[len(szDims) - i - 1] szDims = tuple(szDims1) - + chunks = None if props and props.getChunked(): chunks = (DEFAULT_CHUNK_SIZE,) * len(szDims) - + compression = None if props: - compression = props.getCompression() - - dtype = self.__getHdf5Datatype(rec) + compression = props.getCompression() + + dtype = self.__getHdf5Datatype(rec) datasetName = rec.getName() fillValue = rec.getFillValue() ds = self.__createDatasetInternal(group, datasetName, dtype, szDims, @@ -542,9 +547,9 @@ class H5pyDataStore(IDataStore.IDataStore): t1=time.time() timeMap['closeFile']=t1-t0 LockManager.releaseLock(lock) - + def __createDatasetInternal(self, group, datasetName, dtype, szDims, - maxDims=None, chunks=None, compression=None, fillValue=None): + maxDims=None, chunks=None, compression=None, fillValue=None): plc = h5py.h5p.create(h5py.h5p.DATASET_CREATE) if fillValue is not None: fVal = numpy.zeros(1, dtype) @@ -556,21 +561,21 @@ class H5pyDataStore(IDataStore.IDataStore): if compression == 'LZF': plc.set_shuffle() plc.set_filter(h5py.h5z.FILTER_LZF, h5py.h5z.FLAG_OPTIONAL) - + szDims = tuple(szDims) if maxDims is not None: - maxDims = tuple(x if x is not None else h5py.h5s.UNLIMITED for x in maxDims) + maxDims = tuple(x if x is not None else h5py.h5s.UNLIMITED for x in maxDims) space_id = h5py.h5s.create_simple(szDims, maxDims) type_id = h5py.h5t.py_create(dtype, logical=True) - + id = h5py.h5d.create(group.id, datasetName, type_id, space_id, plc) ds = group[datasetName] return ds - + def __recursiveDeleteFiles(self, dir, datesToDelete): if os.path.exists(dir) and os.path.isdir(dir): - + if datesToDelete is None: self.__removeDir(dir) else: @@ -598,11 +603,11 @@ class H5pyDataStore(IDataStore.IDataStore): if gotLock: os.remove(path) else: - raise StorageException('Unable to acquire lock on file ' + path + ' for deleting') + raise StorageException('Unable to acquire lock on file ' + path + ' for deleting') finally: if gotLock: - LockManager.releaseLock(lock) - + LockManager.releaseLock(lock) + def __removeDir(self, path): gotLock = False try: @@ -610,14 +615,14 @@ class H5pyDataStore(IDataStore.IDataStore): if gotLock: shutil.rmtree(path) else: - raise StorageException('Unable to acquire lock on file ' + path + ' for deleting') + raise StorageException('Unable to acquire lock on file ' + path + ' for deleting') finally: if gotLock: - LockManager.releaseLock(lock) - - def __openFile(self, filename, mode='r'): + LockManager.releaseLock(lock) + + def __openFile(self, filename, mode='r'): if mode == 'r' and not os.path.exists(filename): - raise StorageException('File ' + filename + ' does not exist') + raise StorageException('File ' + filename + ' does not exist') gotLock, fd = LockManager.getLock(filename, mode) t0=time.time() if not gotLock: @@ -635,39 +640,89 @@ class H5pyDataStore(IDataStore.IDataStore): t1=time.time() timeMap['openFile']=t1-t0 - return f, fd - - def __getGroup(self, f, name, create=False): + return f, fd + + def __getNode(self, rootNode, groupName, dsName=None, create=False): t0=time.time() - if create: - parts = name.split('/') - grp = None - for s in parts: - if not grp: - if not s: - s = '/' - if s == '/' or s in f.keys(): - grp = f[s] - else: - grp = f.create_group(s) - else: - if s: - if s in grp.keys(): - grp = grp[s] - else: - grp = grp.create_group(s) - else: - if name is None or len(name.strip()) == 0: - # if no group is specific default to base group - grp = f['/'] + + # expected output to be node for /group1::group2::group3/dataSet + # expected output of /group1::group2::group3/dataSet-interpolated/1 + if groupName: + if dsName: + toNormalize=groupName + '/' + dsName else: - try: - group=name - if not group.startswith('/'): - group = '/' + group - grp = f[group] - except: - raise StorageException("No group " + name + " found") + toNormalize=groupName + elif dsName: + toNormalize=dsName + else: + # both None, return root node as default + return rootNode + + tokens=toNormalize.split('/') + + # remove any empty tokens + tokens = filter(None, tokens) + + dsNameToken=None + if dsName: + # data set name was given, keep last token for ds name + dsNameToken = tokens.pop() + + # need to check final token for -interpolated + isInterpToken = None + if tokens: + isInterpToken = tokens[-1] + if isInterpToken.endswith('-interpolated'): + del tokens[-1] + if dsNameToken: + dsNameToken = isInterpToken + '/' + dsNameToken + else: + dsNameToken = isInterpToken + + if tokens: + basePath='::'.join(tokens) + else: + basePath=None + + node = None + if create: + if basePath is None: + node = rootNode + if basePath in rootNode.keys(): + node = rootNode[basePath] + else: + node = rootNode.create_group(basePath) + + if dsNameToken: + for token in dsNameToken.split('/'): + if token in node.keys(): + node = node[token] + else: + node = node.create_group(token) + else: + if dsNameToken: + if basePath: + basePath += '/' + dsNameToken + else: + basePath = dsNameToken + + + try: + if basePath: + node = rootNode[basePath] + else: + node = rootNode + except: + group = None + if groupName: + group = groupName + if dsName: + group += '/' + dsName + elif dsName: + group = dsName + + # check old group structure + node = self.__getGroup(rootNode, group) t1=time.time() if timeMap.has_key('getGroup'): @@ -675,16 +730,32 @@ class H5pyDataStore(IDataStore.IDataStore): else: timeMap['getGroup']=t1-t0 + return node + + # deprecated, should only be called in transition period + def __getGroup(self, rootNode, name): + if name is None or len(name.strip()) == 0: + # if no group is specific default to base group + grp = rootNode + else: + try: + group=name + if group.startswith('/'): + group = group[1:] + grp = rootNode[group] + except: + raise StorageException("No group " + name + " found") + return grp - + def __link(self, group, linkName, dataset): # this is a hard link group[linkName] = dataset - + # untested code, this would be if we went with symbolic links, this is unpublished h5py API #id = group.id #id.link(dataset.name, linkName, h5py.h5g.LINK_SOFT) - + def copy(self, request): resp = FileActionResponse() file = request.getFilename() @@ -693,12 +764,12 @@ class H5pyDataStore(IDataStore.IDataStore): action = self.__doCopy if not repack else self.__doRepack self.__doFileAction(file, pth, request.getOutputDir(), action, resp, request.getRepackCompression(), request.getTimestampCheck()) return resp - + def __doCopy(self, filepath, basePath, outputDir, compression): shutil.copy(filepath, outputDir) success = (os.path.isfile(os.path.join(outputDir, os.path.basename(filepath)))) return success - + def repack(self, request): resp = FileActionResponse() pth = request.getFilename() @@ -714,17 +785,17 @@ class H5pyDataStore(IDataStore.IDataStore): goodfiles = fnmatch.filter(files, '*.h5') results.extend(os.path.join(base, f) for f in goodfiles) return results - + def __doRepack(self, filepath, basePath, outDir, compression): t0=time.time() # call h5repack to repack the file if outDir is None: - repackedFullPath = filepath + '.repacked' + repackedFullPath = filepath + '.repacked' else: repackedFullPath = filepath.replace(basePath, outDir) cmd = ['h5repack', '-f', compression, filepath, repackedFullPath] ret = subprocess.call(cmd) - + success = (ret == 0) if success: # repack was successful, replace the old file if we did it in the @@ -747,7 +818,7 @@ class H5pyDataStore(IDataStore.IDataStore): else: timeMap['repack']=t1-t0 return success - + def __doFileAction(self, filepath, basePath, outputDir, fileAction, response, compression='NONE', timestampCheck=None): lock = None try: @@ -766,23 +837,23 @@ class H5pyDataStore(IDataStore.IDataStore): if timestampCheck: f.attrs[timestampCheck] = time.time() + 30 f.close() - + success = fileAction(filepath, basePath, outputDir, compression) - + # update response if success: getter = response.getSuccessfulFiles setter = response.setSuccessfulFiles else: getter = response.getFailedFiles - setter = response.setFailedFiles + setter = response.setFailedFiles responseList = getter() if responseList: responseList += [filepath] else: responseList = [filepath] setter(responseList) - except Exception, e: + except Exception, e: logger.warn("Error repacking file " + filepath + ": " + str(e)) failed = response.getFailedFiles() if failed: @@ -793,5 +864,3 @@ class H5pyDataStore(IDataStore.IDataStore): finally: if lock: LockManager.releaseLock(lock) - - diff --git a/rpms/awips2.cave/deploy.builder/build.sh b/rpms/awips2.cave/deploy.builder/build.sh index 21310ebdf9..2d2fad1967 100644 --- a/rpms/awips2.cave/deploy.builder/build.sh +++ b/rpms/awips2.cave/deploy.builder/build.sh @@ -172,29 +172,20 @@ function buildFeatureRPMs() local CONST_SETUP_DIR="Installer.cave-feature/feature.setup" local CONST_SETUP_DIR_FULL="${WORKSPACE}/rpms/awips2.cave/${CONST_SETUP_DIR}" local CONST_FEATURE_DIR="${WORKSPACE}/build/cave/p2/features" + local CONST_FEATURES_TXT="${WORKSPACE}/build/cave/p2/dist/features.txt" + + if [ ! -f ${CONST_FEATURES_TXT} ]; then + echo "ERROR: Unable to find the list of features - ${CONST_FEATURES_TXT}." + exit 1 + fi local PROCESS_FEATURE_JAR="${WORKSPACE}/build/tools/ProcessFeature.jar" - if [ -d ${CONST_FEATURE_DIR}/com.raytheon.viz.feature.awips ]; then - rm -rf ${CONST_FEATURE_DIR}/com.raytheon.viz.feature.awips - fi - if [ -d ${CONST_FEATURE_DIR}/com.raytheon.uf.viz.eclipse.feature ]; then - rm -rf ${CONST_FEATURE_DIR}/com.raytheon.uf.viz.eclipse.feature - fi - if [ -d ${CONST_FEATURE_DIR}/com.raytheon.uf.viz.feature.alertviz ]; then - rm -rf ${CONST_FEATURE_DIR}/com.raytheon.uf.viz.feature.alertviz - fi - if [ -d ${CONST_FEATURE_DIR}/com.raytheon.viz.feature.awips.developer ]; then - rm -rf ${CONST_FEATURE_DIR}/com.raytheon.viz.feature.awips.developer - fi - - # These are variables that will be placed into the environment by sourcing - # a shell script. - for feature_dir in `ls -1 ${CONST_FEATURE_DIR}`; + for feature in `cat ${CONST_FEATURES_TXT}`; do java -jar ${PROCESS_FEATURE_JAR} \ -p \ - ${CONST_FEATURE_DIR}/${feature_dir} \ + ${CONST_FEATURE_DIR}/${feature} \ ${CONST_SETUP_DIR_FULL} RC=$? if [ ${RC} -ne 0 ]; then @@ -208,6 +199,7 @@ function buildFeatureRPMs() fi source ${CONST_SETUP_DIR}/feature.setup + echo "Building Feature ... ${feature}" rpmbuild -ba --target=${TARGET_BUILD_ARCH} \ --define '_topdir %(echo ${AWIPSII_TOP_DIR})' \ --define '_component_name %(echo ${COMPONENT_NAME})' \ @@ -222,7 +214,7 @@ function buildFeatureRPMs() RC=$? if [ ${RC} -ne 0 ]; then exit 1 - fi + fi done } diff --git a/rpms/awips2.core/Installer.database/component.spec b/rpms/awips2.core/Installer.database/component.spec index bc733f9f17..6b2e1b461d 100644 --- a/rpms/awips2.core/Installer.database/component.spec +++ b/rpms/awips2.core/Installer.database/component.spec @@ -66,7 +66,7 @@ cp -r %{_baseline_workspace}/${EXPECTED_PATH_TO_CONFIG}/${CONFIG_FILE_TO_INCLUDE # Copy The SQL Scripts That The Database RPM Will Need To The # Temporary Directory. -DIRS_TO_COPY=('damcat' 'hmdb' 'migrated' 'setup' 'SHEF' 'vtec') +DIRS_TO_COPY=('damcat' 'hmdb' 'migrated' 'setup' 'SHEF' 'vtec' 'ebxml' 'events') for dir in ${DIRS_TO_COPY[*]}; do cp -r %{_baseline_workspace}/${PATH_TO_DDL}/${dir}/* \ @@ -166,6 +166,7 @@ IFHS=${AWIPS2_DATA_DIRECTORY}/pgdata_ihfs MAPS=${AWIPS2_DATA_DIRECTORY}/maps DAMCAT=${AWIPS2_DATA_DIRECTORY}/damcat HMDB=${AWIPS2_DATA_DIRECTORY}/hmdb +EBXML=${AWIPS2_DATA_DIRECTORY}/ebxml # Add The PostgreSQL Libraries And The PSQL Libraries To LD_LIBRARY_PATH. export LD_LIBRARY_PATH=${POSTGRESQL_INSTALL}/lib:$LD_LIBRARY_PATH @@ -271,6 +272,15 @@ function update_createDamcat() ${SQL_SHARE_DIR}/createDamcat.sql } +function update_createEbxml() +{ + echo ${AWIPS2_DATA_DIRECTORY} | sed 's/\//\\\//g' > .awips2_escape.tmp + AWIPS2_DATA_DIRECTORY_ESCAPED=`cat .awips2_escape.tmp` + rm -f .awips2_escape.tmp + perl -p -i -e "s/%{database_files_home}%/${AWIPS2_DATA_DIRECTORY_ESCAPED}/g" \ + ${SQL_SHARE_DIR}/createEbxml.sql +} + function update_createHMDB() { echo ${AWIPS2_DATA_DIRECTORY} | sed 's/\//\\\//g' > .awips2_escape.tmp @@ -334,6 +344,10 @@ echo "-------------------------------------------------------------------------- echo "\| Creating a Directory for the hmdb Tablespace..." echo "--------------------------------------------------------------------------------" create_sql_element ${HMDB} +echo "--------------------------------------------------------------------------------" +echo "\| Creating a Directory for the ebxml Tablespace..." +echo "--------------------------------------------------------------------------------" +create_sql_element ${EBXML} echo "" echo "--------------------------------------------------------------------------------" echo "\| Starting PostgreSQL..." @@ -371,6 +385,9 @@ execute_psql_sql_script ${SQL_SHARE_DIR}/bit_table.sql metadata execute_psql_sql_script ${SQL_SHARE_DIR}/collective.sql metadata execute_psql_sql_script ${SQL_SHARE_DIR}/national_category.sql metadata +# create the events schema +execute_psql_sql_script ${SQL_SHARE_DIR}/createEventsSchema.sql metadata + echo "--------------------------------------------------------------------------------" echo "\| Creating shef Tables..." echo "--------------------------------------------------------------------------------" @@ -387,6 +404,12 @@ execute_psql_sql_script ${SQL_SHARE_DIR}/populateDamcatDatabase.sql dc_ob7oax update_createHMDB su ${AWIPS_DEFAULT_USER} -c \ "${SQL_SHARE_DIR}/createHMDB.sh ${PSQL_INSTALL} ${AWIPS_DEFAULT_PORT} ${AWIPS_DEFAULT_USER} ${SQL_SHARE_DIR} ${SQL_LOG}" + +update_createEbxml +echo "--------------------------------------------------------------------------------" +echo "\| Creating ebxml Tables..." +echo "--------------------------------------------------------------------------------" +execute_psql_sql_script ${SQL_SHARE_DIR}/createEbxml.sql postgres echo "--------------------------------------------------------------------------------" echo "\| Creating VTEC Tables..." echo "--------------------------------------------------------------------------------" diff --git a/rpms/awips2.core/Installer.ldm/component.spec b/rpms/awips2.core/Installer.ldm/component.spec index 1649a25145..536a480d9a 100644 --- a/rpms/awips2.core/Installer.ldm/component.spec +++ b/rpms/awips2.core/Installer.ldm/component.spec @@ -5,7 +5,7 @@ Name: awips2-ldm Summary: AWIPS II LDM Distribution Version: 6.8.1 -Release: 26 +Release: 24 Group: AWIPSII BuildRoot: /tmp URL: N/A diff --git a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.gum b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.gum index 36cf110014..74ceead833 100644 --- a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.gum +++ b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.gum @@ -135,7 +135,6 @@ ALLOW NIMAGE ^.* .* TIT[EQ].* ALLOW HDS ^.* .* [IJ]UTX0[0-689].*|JUSX4[0-689].* ALLOW EXP ^.* .* ALLOW IDS|DDPLUS ^.* .* SXUS2[03-9].KWOH|SXUS[3-9].KWOH|SXUS8[0-3].KWOH|SRUS[2-8].KWOH -ALLOW NOTHER ^.* .* # # Give permission to the Unidata Program Center ALLOW ANY ^[a-z].*\.unidata\.ucar\.edu\.?$ .* diff --git a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.hfo b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.hfo index 36cf110014..74ceead833 100644 --- a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.hfo +++ b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.hfo @@ -135,7 +135,6 @@ ALLOW NIMAGE ^.* .* TIT[EQ].* ALLOW HDS ^.* .* [IJ]UTX0[0-689].*|JUSX4[0-689].* ALLOW EXP ^.* .* ALLOW IDS|DDPLUS ^.* .* SXUS2[03-9].KWOH|SXUS[3-9].KWOH|SXUS8[0-3].KWOH|SRUS[2-8].KWOH -ALLOW NOTHER ^.* .* # # Give permission to the Unidata Program Center ALLOW ANY ^[a-z].*\.unidata\.ucar\.edu\.?$ .* diff --git a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.pbp b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.pbp index 36cf110014..74ceead833 100644 --- a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.pbp +++ b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.pbp @@ -135,7 +135,6 @@ ALLOW NIMAGE ^.* .* TIT[EQ].* ALLOW HDS ^.* .* [IJ]UTX0[0-689].*|JUSX4[0-689].* ALLOW EXP ^.* .* ALLOW IDS|DDPLUS ^.* .* SXUS2[03-9].KWOH|SXUS[3-9].KWOH|SXUS8[0-3].KWOH|SRUS[2-8].KWOH -ALLOW NOTHER ^.* .* # # Give permission to the Unidata Program Center ALLOW ANY ^[a-z].*\.unidata\.ucar\.edu\.?$ .* diff --git a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.vrh b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.vrh index 64b763ce6d..42da2e133d 100644 --- a/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.vrh +++ b/rpms/awips2.core/Installer.ldm/patch/etc/ldmd.conf.vrh @@ -142,8 +142,6 @@ ALLOW EXP ^.* .* ALLOW IDS|DDPLUS ^.* .* SXUS2[03-9].KWOH|SXUS[3-9].KWOH|SXUS8[0-3].KWOH|SRUS[2-8].KWOH -ALLOW NOTHER ^.* .* - # # Give permission to the Unidata Program Center ALLOW ANY ^[a-z].*\.unidata\.ucar\.edu\.?$ .* diff --git a/rpms/awips2.core/Installer.ldm/patch/etc/pqact.conf.template b/rpms/awips2.core/Installer.ldm/patch/etc/pqact.conf.template index 42e800b6e4..fd895b2376 100644 --- a/rpms/awips2.core/Installer.ldm/patch/etc/pqact.conf.template +++ b/rpms/awips2.core/Installer.ldm/patch/etc/pqact.conf.template @@ -164,17 +164,15 @@ HDS ^(YVW[ABCDGJM][0-9][0-9]) KKCI (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/ FILE -overwrite -log -close -edex /data_store/\5/(\2:yyyy)(\2:mm)\2/\3/\6/GRID\7/\9Z_\(10)_\(11)-\1_KKCI_\2\3\4_(seq).\5.%Y%m%d%H # AWIPS1: GRID ^[LM].[ABDHMNRSTU].*KWB.* /Grid/SBN/rawGrib2 -# AWIPS1 OCONUS: GRID ^[LM].[ABCDGHMNORSTUVX].*KWB.* /Grid/SBN/rawGrib2 # LTHO70 KWBC 011800 !grib2/ncep/GFS/#213/201102011800F120/TMPK/700 hPa PRES -NGRID ^([LM].[ABCDGHMNORSTUVX].{1,3}) (KWB.) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) +NGRID ^([LM].[ABDHMNRSTU].{1,3}) (KWB.) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H # MosGuidance, perhaps others? # LVUC00 KWBQ 271200 !grib2/ncep/GFS/#197/FHRS//LVL # Maint : fixed pattern at F... -# OCONUS: Added CEFG -HDS ^([LM].[ABCDEFGHMNRSTU].{1,3}) (KWB.) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) +HDS ^([LM].[ABDHMNRSTU].{1,3}) (KWB.) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H # AWIPS1: GRID ^[LM].[MN].98.*KWNH /Grid/SBN/rawGrib2 @@ -185,15 +183,9 @@ NGRID ^([LM].[MN].98) (KWNH) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/] HDS ^([LM].[MN].98) (KWNH) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H -# AWIPS1 OCONUS: GRID ^L.R....*KWNH /Grid/SBN/rawGrib2 - -NGRID ^(L.R...) (KWNH) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) - FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H - # AWIPS1: GRID ^[LM].E.*KWBD* /Grid/SBN/rawGrib2 -# AWIPS1 OCONUS: GRID ^[LM].[EF].*KWBD* /Grid/SBN/rawGrib2 # MUEU98 KWBD 020600 !grib2/ncep/DGEX_115/#185/201102020600F090/UREL/10 m HGHT -NGRID ^([LM].[EF].{1,3}) (KWBD) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) +NGRID ^([LM].E.{1,3}) (KWBD) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H # AWIPS1: GRID ^L.U.*KWBN* /Grid/SBN/rawGrib2 @@ -252,24 +244,22 @@ NGRID ^(LAMA98) (KNES) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0 HDS ^([LM].Z.{1,3}) KWBX (..)(..)(..) PIPE -close /usr/local/ldm/decoders/decrypt_file - /data_store/grib2/(\2:yyyy)(\2:mm)\2/\3/ECMWF_HiRes/ecmwf_decrypted_\1_KWBX_\2\3\4_(seq).grib2.%Y%m%d%H + /data_store/grib2/(\2:yyyy)(\2:mm)\2/\3/ECMWF_HiRes/\1_KWBX_\2\3\4_(seq).grib2.%Y%m%d%H -EXP (.*ecmwf_decrypted.*) - FILE -overwrite -log -close -edex \1 +EXP ^/data_store/grib2/ECMWF_HiRes/ecmwf_raw/(ecmwf_decrypted.*) + FILE -overwrite -log -close -edex /data_store/grib2/(\2:yyyy)(\2:mm)\2/\3/ECMWF_HiRes/\1_KWBX_\2\3\4_(seq).grib2.%Y%m%d%H # AWIPS1: GRID ^E.[ABCGHI].*KWBJ /Grid/SBN/rawGrib2 -# AWIPS1 OCONUS: GRID ^E.[ABCDEFGHI].*KWBJ /Grid/SBN/rawGrib2 # EWAW88 KWBJ 021200 !grib2/ncep/GMGWM/#255/201102021200F180/WSTP/0 - NONE -NGRID ^(E.[ABCDEFGHI].{1,3}) (KWBJ) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) +NGRID ^(E.[ABCGHI].{1,3}) (KWBJ) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H # AWIPS1: GRID ^[LM].[AB].*KWBS* /Grid/SBN/rawGrib2 -# AWIPS1 OCONUS: GRID ^[LM].[ABCDE].*KWBS* /Grid/SBN/rawGrib2 # LMDA98 KWBS 160000 !grib2/ncep/WRF_EM/#130/201012160000F000/WXTZ/0 - NONE -ANY ^([LM].[ABCDE].{1,3}) (KWBS) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) +ANY ^([LM].[AB].{1,3}) (KWBS) (..)(..)(..)[^!]*!(grib|grib2)/[^/]*/([^/]*)/#([^/]*)/([0-9]{8})([0-9]{4})(F[0-9]{3})/([^/]*) FILE -overwrite -log -close -edex /data_store/\6/(\3:yyyy)(\3:mm)\3/\4/\7/GRID\8/\(10)Z_\(11)_\(12)-\1_\2_\3\4\5_(seq).\6.%Y%m%d%H # AWIPS1: GRID ^LGXT[0-2][0-9].*KNHC /Grid/SBN/rawGrib2 @@ -312,12 +302,11 @@ HDS ^(IUPT0[1-4]|IUPT40|IUAK01) (.{4}) (..)(..)(..) FILE -overwrite -log -close -edex /data_store/profiler/(\3:yyyy)(\3:mm)\3/\4/\1_\2_\3\4\5_(seq).bufr.%Y%m%d%H # AWIPS1: POINT ^IUSZ[4-9][0-9].* /ispan/bufr/raob -# AWIPS1 OCONUS: POINT ^IUSZ[0-9][0-9].* /ispan/bufr/raob # IUSZ53 KWBC 020205 # AWIPS1: POINT ^IUSY[4][0-9].* /ispan/bufr/raob # IUSY41 KWBC 020030 -HDS ^(IUS(Z[0-9]|Y4)[0-9]) ([A-Z]{4}) (..)(..)(..) +HDS ^(IUS(Z[4-9]|Y4)[0-9]) ([A-Z]{4}) (..)(..)(..) FILE -overwrite -log -close -edex /data_store/bufrua/(\4:yyyy)(\4:mm)\4/\5/\1_\3_\4\5\6_(seq).bufr.%Y%m%d%H # AWIPS1: TEXT ^SFUS41.* /ispan/binLightning @@ -556,9 +545,8 @@ IDS|DDPLUS ^(W[CSV]PN0[1-6]) (KKCI) (..)(..)(..) # JSML30 KWNO 021800 # AWIPS1: POINT ^JSMF1[1-6].KWNO.* /ispan/bufr/GFSLAMP -# AWIPS1 OCONUS: POINT ^JSMF1[0-7].KWNO.* /ispan/bufr/GFSLAMP # JSMF12 KWNO 022200 -HDS ^(JSM([TL]..|F1[0-7])) (....) (..)(..)(..) +HDS ^(JSM([TL]..|F1[1-6])) (....) (..)(..)(..) FILE -overwrite -log -close -edex /data_store/bufrmos/(\4:yyyy)(\4:mm)\4/\5/\1_\3_\4\5\6_(seq).bufr.%Y%m%d%H # AWIPS1: POINT ^IUAX0[12].* /ispan/bufr/acars @@ -637,7 +625,3 @@ HDS ^(JSXX(0[1-9]|10)) (.{4}) (..)(..)(..) # AWIPS2 distribution file bufrmthdw.xml: ^JUTX(([2-4]1)|53).* HDS ^(JUTX(([2-4]1)|53)) (.{4}) (..)(..)(..) FILE -overwrite -log -close -edex /data_store/bufrmthdw/(\5:yyyy)(\5:mm)\5/\6/\1_\4_\5\6\7_(seq).bufr.%Y%m%d%H - -# New NPP/VIIRS data -NOTHER ^(TIP...) (KNES) (..)(..)(..) - FILE -overwrite -log -close -edex /data_store/sat/%Y%m\(3)/\(4)/VIIRS/\1_\2_\3\4\5_(seq).%Y%m%d diff --git a/rpms/awips2.core/Installer.ncep-database/component.spec b/rpms/awips2.core/Installer.ncep-database/component.spec index 4aab090e9f..0c8b3a04a1 100644 --- a/rpms/awips2.core/Installer.ncep-database/component.spec +++ b/rpms/awips2.core/Installer.ncep-database/component.spec @@ -278,6 +278,9 @@ exit 0 %postun +%clean +rm -rf ${RPM_BUILD_ROOT} + %files %defattr(-,awips,fxalpha,-) %dir /awips2 @@ -383,4 +386,7 @@ exit 0 %attr(755,awips,fxalpha) /awips2/database/sqlScripts/share/sql/ncep/loadWrqpf.sql %attr(755,awips,fxalpha) /awips2/database/sqlScripts/share/sql/ncep/loadXrainsort.sql %attr(755,awips,fxalpha) /awips2/database/sqlScripts/share/sql/ncep/loadZones.sql +%attr(755,awips,fxalpha) /awips2/database/sqlScripts/share/sql/ncep/addUgcMzbnd.sql +%attr(755,awips,fxalpha) /awips2/database/sqlScripts/share/sql/ncep/fixMzbnds.sql +%attr(755,awips,fxalpha) /awips2/database/sqlScripts/share/sql/ncep/loadClimodata.sql /awips2/database/sqlScripts/share/sql/ncep/shapefiles diff --git a/rpms/awips2.edex/Installer.edex-base/scripts/init.d/edex_camel b/rpms/awips2.edex/Installer.edex-base/scripts/init.d/edex_camel index 7ac4db2294..fe65e20db0 100644 --- a/rpms/awips2.edex/Installer.edex-base/scripts/init.d/edex_camel +++ b/rpms/awips2.edex/Installer.edex-base/scripts/init.d/edex_camel @@ -200,4 +200,4 @@ case $func in ;; esac -exit $RETVAL \ No newline at end of file +exit $RETVAL diff --git a/rpms/awips2.edex/Installer.edex-configuration/component.spec b/rpms/awips2.edex/Installer.edex-configuration/component.spec index 614a158d47..079fc1e4b6 100644 --- a/rpms/awips2.edex/Installer.edex-configuration/component.spec +++ b/rpms/awips2.edex/Installer.edex-configuration/component.spec @@ -126,4 +126,4 @@ rm -rf ${RPM_BUILD_ROOT} %dir /awips2 %dir /awips2/edex %dir /awips2/edex/bin -%config(noreplace) /awips2/edex/bin/setup.env +%config(noreplace) /awips2/edex/bin/setup.env \ No newline at end of file diff --git a/rpms/awips2.edex/Installer.edex-datadelivery/component.spec b/rpms/awips2.edex/Installer.edex-datadelivery/component.spec new file mode 100644 index 0000000000..d1b47fe04c --- /dev/null +++ b/rpms/awips2.edex/Installer.edex-datadelivery/component.spec @@ -0,0 +1,70 @@ +# Turn off the brp-python-bytecompile script +%global __os_install_post %(echo '%{__os_install_post}' | sed -e 's!/usr/lib[^[:space:]]*/brp-python-bytecompile[[:space:]].*$!!g') +# Turn off the java jar repack +%global __os_install_post %(echo '%{__os_install_post}' | sed -e 's!/usr/lib[^[:space:]]*/brp-java-repack-jars[[:space:]].*$!!g') + +%define _component_name awips2-edex-datadelivery +%define _component_project_dir awips2.edex/Installer.edex-datadelivery +# +# AWIPS II Edex Datadelivery Spec File +# +Name: %{_component_name} +Summary: AWIPS II Edex Dat +Version: %{_component_version} +Release: %{_component_release} +Group: AWIPSII +BuildRoot: /tmp +Prefix: %{_component_default_prefix} +URL: N/A +License: N/A +Distribution: N/A +Vendor: Raytheon +Packager: Bryan Kowal + +AutoReq: no +provides: %{_component_name} +requires: awips2 +requires: awips2-edex-base +requires: awips2-python +requires: awips2-java +requires: awips2-psql + +%description +AWIPS II Edex Installation - Installs The AWIPS II Edex Datadelivery Plugins. + +%prep +# Verify That The User Has Specified A BuildRoot. +if [ "${RPM_BUILD_ROOT}" = "/tmp" ] +then + echo "An Actual BuildRoot Must Be Specified. Use The --buildroot Parameter." + echo "Unable To Continue ... Terminating" + exit 1 +fi + +mkdir -p ${RPM_BUILD_ROOT}/awips2/edex + +%install +DEPLOY_SCRIPT="build.edex/deploy-install.xml" + +# Deploy Edex To Our Temporary Build Directory. +/awips2/ant/bin/ant -file ${WORKSPACE_DIR}/${DEPLOY_SCRIPT} \ + -Dinstall.dir=${RPM_BUILD_ROOT}/awips2/edex \ + -Dinstaller=true -Dlocal.build=false \ + -Dcomponent.to.deploy=edex-datadelivery +if [ $? -ne 0 ]; then + exit 1 +fi + +%pre +%post +%preun +%postun + +%clean +rm -rf ${RPM_BUILD_ROOT} + +%files +%defattr(644,awips,fxalpha,755) +%dir /awips2 +%dir /awips2/edex +/awips2/edex/* \ No newline at end of file diff --git a/rpms/awips2.qpid/SOURCES/queueCreator.sh b/rpms/awips2.qpid/SOURCES/queueCreator.sh index c8ccf29261..7dda8e76a6 100644 --- a/rpms/awips2.qpid/SOURCES/queueCreator.sh +++ b/rpms/awips2.qpid/SOURCES/queueCreator.sh @@ -52,4 +52,12 @@ do qpid-config add queue $queue --durable --file-count 16 --file-size 24 done +#define 24 Meg persistence queues for HPE ingest +QUEUES=('Ingest.dhr' 'dhrProcess') +for queue in ${QUEUES[*]}; +do + echo "Creating queue $queue" + qpid-config add queue $queue --durable --file-count 16 --file-size 24 +done + diff --git a/rpms/common/yum/arch.x86/comps.xml b/rpms/common/yum/arch.x86/comps.xml index 47a6940237..60b08cb3c5 100644 --- a/rpms/common/yum/arch.x86/comps.xml +++ b/rpms/common/yum/arch.x86/comps.xml @@ -36,6 +36,7 @@ awips2-edex-configuration awips2-edex-npp awips2-edex-ncep + awips2-edex-datadelivery awips2-gfesuite-server awips2-httpd-pypies @@ -129,6 +130,8 @@ awips2-cave-viz-npp awips2-cave-viz-kml-export awips2-cave-viz-collaboration + awips2-cave-viz-kml-export + awips2-cave-viz-datadelivery awips2-gfesuite-client awips2-alertviz @@ -193,6 +196,7 @@ awips2-edex-text awips2-edex-ncep awips2-edex-npp + awips2-edex-datadelivery awips2-gfesuite-server awips2-hydroapps-shared @@ -467,6 +471,8 @@ awips2-cave-viz-npp awips2-cave-viz-kml-export awips2-cave-viz-collaboration + awips2-cave-viz-kml-export + awips2-cave-viz-datadelivery awips2-localapps-environment diff --git a/rpms/common/yum/arch.x86_64/comps.xml b/rpms/common/yum/arch.x86_64/comps.xml index 3229a222d7..f6b4f6c05c 100644 --- a/rpms/common/yum/arch.x86_64/comps.xml +++ b/rpms/common/yum/arch.x86_64/comps.xml @@ -125,6 +125,7 @@ awips2-cave-viz-npp awips2-cave-viz-kml-export awips2-cave-viz-collaboration + awips2-cave-viz-datadelivery awips2-gfesuite-client awips2-alertviz