Input:
parsing the product information into netcdf dataset [CODESPLIT] void setProductInfo ( int prod_type , Pinfo pinfo ) { /* memo field                */ String [ ] cmode = new String [ ] { "Maintenance" , "Clear Air" , "Precip Mode" } ; short prod_max = pinfo . p4 ; short prod_min = 0 ; int prod_elevation = 0 ; //int prod_info;
 int prod_top ; int radial = 0 ; String summary = null ; java . util . Date endDate ; java . util . Date startDate ; String dstring ; double t1 = 124.0 * 1.853 / 111.26 ; double t2 = 230 / ( 111.26 * Math . cos ( Math . toRadians ( latitude ) ) ) ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; //* Math.cos(Math.toRadians(lat_min));
 lon_max = longitude - t2 ; //* Math.cos(Math.toRadians(lat_min));
 startDate = getDate ( volumeScanDate , volumeScanTime * 1000 ) ; endDate = getDate ( volumeScanDate , volumeScanTime * 1000 ) ; if ( prod_type == SPECTRUM ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Base Specturm Width " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( pcode , prod_elevation / 10 ) ; ctitle = "BREF: Base Spectrum Width" ; cunit = "Knots" ; cname = "SpectrumWidth" ; summary = ctilt + " is a radial image of base reflectivity at tilt " + ( prod_elevation / 10 + 1 ) + " and range 124 nm" ; if ( pcode == 28 ) { t1 = t1 * 0.25 ; t2 = t2 * 0.25 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; //* Math.cos(Math.toRadians(lat_min));
 lon_max = longitude - t2 ; //* Math.cos(Math.toRadians(lat_min));
 summary = ctilt + " is a radial image of base reflectivity at tilt " + ( prod_elevation / 10 + 1 ) + " and range 32 nm" ; } } else if ( prod_type == DigitalDifferentialReflectivity ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Differential Reflectivity " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 15 , pLevel ) ; ctitle = "Dualpol: Digital Differential Reflectivity" ; cunit = "dBz" ; cname = "DifferentialReflectivity" ; summary = ctilt + " is a radial image of dual pol differential reflectivity field and its range 162 nm" ; } else if ( prod_type == DigitalCorrelationCoefficient ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Correlation Coefficient " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 16 , pLevel ) ; ctitle = "Dualpol: Digital Correlation Coefficient" ; cunit = " " ; cname = "CorrelationCoefficient" ; summary = ctilt + " is a radial image of dual pol Correlation Coefficient field and its range 162 nm" ; } else if ( prod_type == DigitalDifferentialPhase ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Differential Phase " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 17 , pLevel ) ; ctitle = "Dualpol: Digital Differential Phase" ; cunit = "Degree/km" ; cname = "DifferentialPhase" ; summary = ctilt + " is a radial image of dual pol Differential Phase field and its range 162 nm" ; } else if ( prod_type == HydrometeorClassification ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Hydrometeor Classification " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 18 , pLevel ) ; ctitle = "Dualpol: Hydrometeor Classification" ; cunit = " " ; cname = "HydrometeorClassification" ; summary = ctilt + " is a radial image of dual pol Hydrometeor Classification field and its range 162 nm" ; } else if ( prod_type == HypridHydrometeorClassification ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Hyprid Hydrometeor Classification " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 18 , pLevel ) ; ctitle = "Dualpol: Hyprid Hydrometeor Classification" ; cunit = " " ; cname = "HypridHydrometeorClassification" ; summary = ctilt + " is a radial image of dual pol Hyprid Hydrometeor Classification field and its range 162 nm" ; } else if ( prod_type == OneHourAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "One Hour Accumulation " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; ctilt = "OHA" ; ctitle = "Dualpol: One Hour Accumulation" ; cunit = "IN" ; cname = "OneHourAccumulation" ; summary = ctilt + " is a radial image of dual pol One Hour Accumulation field and its range 124 nm" ; } else if ( prod_type == DigitalAccumulationArray ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital Accumulation Array " + cmode [ pinfo . opmode ] ; ctilt = "DAA" ; ctitle = "Dualpol: Digital Accumulation Array" ; cunit = "IN" ; cname = "DigitalAccumulationArray" ; summary = ctilt + " is a radial image of dual pol Digital Accumulation Array field and its range 124 nm" ; } else if ( prod_type == StormTotalAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Storm Total Accumulation " + cmode [ pinfo . opmode ] ; ctilt = "PTA" ; ctitle = "Dualpol: Storm Total Accumulation" ; cunit = "IN" ; cname = "StormTotalAccumulation" ; summary = ctilt + " is a radial image of dual pol Storm Total Accumulation field and its range 124 nm" ; } else if ( prod_type == DigitalStormTotalAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital Storm Total Accumulation  " + cmode [ pinfo . opmode ] ; ctilt = "DTA" ; ctitle = "Dualpol: Digital Storm Total Accumulation" ; cunit = "IN" ; cname = "DigitalStormTotalAccumulation" ; summary = ctilt + " is a radial image of dual pol Digital StormTotal Accumulation field and its range 124 nm" ; } else if ( prod_type == Accumulation3Hour ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Hyprid Hydrometeor Classification " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 18 , pLevel ) ; ctitle = "Dualpol: 3-hour Accumulation" ; cunit = "IN" ; cname = "Accumulation3Hour" ; summary = ctilt + " is a radial image of dual pol 3-hour Accumulation field and its range 124 nm" ; } else if ( prod_type == Digital1HourDifferenceAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital One Hour Difference Accumulation " + cmode [ pinfo . opmode ] ; ctilt = "DOD" ; ctitle = "Dualpol: Digital One Hour Difference Accumulation" ; cunit = "IN" ; cname = "Digital1HourDifferenceAccumulation" ; summary = ctilt + " is a radial image of dual pol Digital One Hour Difference Accumulation field and its range 124 nm" ; } else if ( prod_type == DigitalTotalDifferenceAccumulation ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital Total Difference Accumulation " + cmode [ pinfo . opmode ] ; ctilt = "DSD" ; ctitle = "Dualpol: Digital Total Difference Accumulation" ; cunit = "IN" ; cname = "DigitalTotalDifferenceAccumulation" ; summary = ctilt + " is a radial image of dual pol Digital Total Difference Accumulation field and its range 124 nm" ; } else if ( prod_type == DigitalInstantaneousPrecipitationRate ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital Instantaneous Precipitation Rate " + cmode [ pinfo . opmode ] ; ctilt = "DPR" ; ctitle = "Dualpol: Digital Instantaneous Precipitation Rate" ; cunit = "IN/Hour" ; cname = "DigitalInstantaneousPrecipitationRate" ; summary = ctilt + " is a radial image of dual pol Digital Instantaneous Precipitation Rate field and its range 124 nm" ; } else if ( prod_type == BaseReflectivityDR ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Base Reflectivity DR " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 94 , pLevel ) ; ctitle = "HighResolution: Base Reflectivity" ; cunit = "dBz" ; cname = "BaseReflectivityDR" ; summary = ctilt + " is a radial image of base reflectivity field and its range 248 nm" ; } else if ( prod_type == BaseVelocityDV ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Base Velocity DR " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; int pLevel = getProductLevel ( prod_elevation ) ; ctilt = pname_lookup ( 99 , pLevel ) ; ctitle = "HighResolution: Base Velocity" ; cunit = "m/s" ; cname = "BaseVelocityDV" ; summary = ctilt + " is a radial image of base velocity field and its range 124 nm" ; } else if ( prod_type == DigitalVert_Liquid ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital Hybrid Reflect " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 134 , prod_elevation / 10 ) ; ctitle = "Digital: Vertical Integ Liquid" ; cunit = "kg/m^2" ; cname = "DigitalIntegLiquid" ; summary = ctilt + " is a radial image high resolution vertical integral liquid and range 248 nm" ; } else if ( prod_type == DigitalHybridReflect ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Digital Hybrid Reflect " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 19 , prod_elevation / 10 ) ; ctitle = "DigitalHybrid: Reflectivity" ; cunit = "dBz" ; cname = "DigitalHybridReflectivity" ; summary = ctilt + " is a radial image of base reflectivity at tilt " + ( prod_elevation / 10 + 1 ) + " and range 124 nm" ; } else if ( prod_type == Base_Reflect || prod_type == Reflect1 ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Base Reflct " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; if ( prod_type == Reflect1 ) { ctilt = "R" + prod_elevation / 10 ; summary = ctilt + " is a radial image of base reflectivity at tilt " + ( prod_elevation / 10 + 1 ) ; } else { ctilt = pname_lookup ( 19 , prod_elevation / 10 ) ; summary = ctilt + " is a radial image of base reflectivity at tilt " + ( prod_elevation / 10 + 1 ) + " and range 124 nm" ; } ctitle = "BREF: Base Reflectivity" ; cunit = "dBz" ; cname = "BaseReflectivity" ; } else if ( prod_type == BaseReflect248 ) { radial = 1 ; prod_elevation = pinfo . p3 ; cmemo = "Base Reflct 248 " + prod_elevation / 10 + " DEG " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 20 , prod_elevation / 10 ) ; ctitle = "BREF: 248 nm Base Reflectivity" ; cunit = "dBz" ; cname = "BaseReflectivity248" ; summary = ctilt + " is a radial image of base reflectivity at tilt " + ( prod_elevation / 10 + 1 ) + " and range 248 nm" ; t1 = 248.0 * 1.853 / 111.26 ; t2 = 460 / ( 111.26 * Math . cos ( Math . toRadians ( latitude ) ) ) ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Comp_Reflect ) { radial = 3 ; prod_elevation = - 1 ; ctilt = pname_lookup ( pinfo . pcode , elevationNumber ) ; if ( pinfo . pcode == 36 || pinfo . pcode == 38 ) { t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } summary = ctilt + "is a raster image of composite reflectivity" ; cmemo = "Composite Reflectivity at " + cmode [ pinfo . opmode ] ; ctitle = "CREF Composite Reflectivity" + ctilt ; cunit = "dBz" ; cname = "BaseReflectivityComp" ; } else if ( prod_type == Layer_Reflect_Avg || prod_type == Layer_Reflect_Max ) { radial = 3 ; prod_elevation = pinfo . p5 ; prod_top = pinfo . p6 ; ctilt = pname_lookup ( pcode , 0 ) ; summary = ctilt + " is a raster image of composite reflectivity at range 124 nm" ; cmemo = "Layer Reflct " + prod_elevation + " - " + prod_top + cmode [ pinfo . opmode ] ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; ctitle = "LREF: Layer Composite Reflectivity" ; cunit = "dBz" ; cname = "LayerCompReflect" ; } else if ( prod_type == EnhancedEcho_Tops ) { radial = 1 ; prod_elevation = - 1 ; summary = "EET is a radial image of echo tops at range 186 nm" ; cmemo = "Enhanced Echo Tops [K FT] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 135 , elevationNumber ) ; ctitle = "TOPS: Enhanced Echo Tops" ; cunit = "K FT" ; cname = "EnhancedEchoTop" ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Echo_Tops ) { radial = 3 ; prod_elevation = - 1 ; summary = "NET is a raster image of echo tops at range 124 nm" ; cmemo = "Echo Tops [K FT] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 41 , elevationNumber ) ; ctitle = "TOPS: Echo Tops" ; cunit = "K FT" ; cname = "EchoTop" ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_1 ) { radial = 1 ; prod_elevation = - 1 ; prod_max /= 10 ; endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = "N1P is a raster image of 1 hour surface rainfall accumulation at range 124 nm" ; cmemo = "1-hr Rainfall [IN] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 78 , elevationNumber ) ; ctitle = "PRE1: Surface 1-hour Rainfall Total" ; cunit = "IN" ; cname = "Precip1hr" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_3 ) { radial = 1 ; prod_elevation = - 1 ; prod_max /= 10 ; endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = "N3P is a raster image of 3 hour surface rainfall accumulation at range 124 nm" ; cmemo = "3-hr Rainfall [IN] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 79 , elevationNumber ) ; ctitle = "PRE3: Surface 3-hour Rainfall Total" ; cunit = "IN" ; cname = "Precip3hr" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == DigitalStormTotalPrecip ) { radial = 1 ; prod_elevation = - 1 ; //startDate = getDate( pinfo.p5, pinfo.p6 * 60 * 1000);
 endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = "DSP is a radial image of digital storm total rainfall" ; cmemo = "Digital Strm Total Precip [IN] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 80 , elevationNumber ) ; ctitle = "DPRE: Digital Storm Total Rainfall" ; cunit = "IN" ; cname = "DigitalPrecip" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_Accum ) { radial = 1 ; prod_elevation = - 1 ; //startDate = getDate( pinfo.p5, pinfo.p6 * 60 * 1000);
 endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; summary = "NTP is a raster image of storm total rainfall accumulation at range 124 nm" ; cmemo = "Strm Tot Rain [IN] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 80 , elevationNumber ) ; ctitle = "PRET: Surface Storm Total Rainfall" ; cunit = "IN" ; cname = "PrecipAccum" ; t1 = t1 * 2 ; t2 = t2 * 2 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Precip_Array ) { radial = 3 ; prod_elevation = - 1 ; summary = "DPA is a raster image of hourly digital precipitation array at range 124 nm" ; endDate = getDate ( pinfo . p7 , pinfo . p8 * 60 * 1000 ) ; cmemo = "Precip Array [IN] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 81 , elevationNumber ) ; ctitle = "PRET: Hourly Digital Precipitation Array" ; cunit = "dBA" ; cname = "PrecipArray" ; } else if ( prod_type == Vert_Liquid ) { radial = 3 ; prod_elevation = - 1 ; summary = "NVL is a raster image of verticalintegrated liguid at range 124 nm" ; cmemo = "Vert Int Lq H2O [mm] " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 57 , elevationNumber ) ; ctitle = "VIL: Vertically-integrated Liquid Water" ; cunit = "kg/m^2" ; cname = "VertLiquid" ; t1 = t1 * 4 ; t2 = t2 * 4 ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; } else if ( prod_type == Velocity || prod_type == Velocity1 ) { radial = 1 ; prod_elevation = pinfo . p3 ; prod_min = pinfo . p4 ; prod_max = pinfo . p5 ; if ( prod_type == Velocity ) { ctilt = pname_lookup ( pinfo . pcode , prod_elevation / 10 ) ; } else { ctilt = "V" + prod_elevation / 10 ; } if ( pinfo . pcode == 25 ) { t1 = 32.0 * 1.853 / 111.26 ; t2 = 64 / ( 111.26 * Math . cos ( Math . toRadians ( latitude ) ) ) ; lat_min = latitude - t1 ; lat_max = latitude + t1 ; lon_min = longitude + t2 ; lon_max = longitude - t2 ; summary = ctilt + " is a radial image of base velocity" + ( prod_elevation / 10 + 1 ) + " and  range 32 nm" ; cunit = "m/s" ; } else { summary = ctilt + " is a radial image of base velocity at tilt " + ( prod_elevation / 10 + 1 ) ; cunit = "m/s" ; } cmemo = "Rad Vel " + prod_elevation / 10. + " DEG " + cmode [ pinfo . opmode ] ; ctitle = "VEL: Radial Velocity" ; cname = "RadialVelocity" ; } else if ( prod_type == StrmRelMeanVel ) { radial = 1 ; prod_elevation = pinfo . p3 ; prod_min = pinfo . p4 ; prod_max = pinfo . p5 ; ctilt = pname_lookup ( 56 , prod_elevation / 10 ) ; summary = ctilt + " is a radial image of storm relative mean radial velocity at tilt " + ( prod_elevation / 10 + 1 ) + " and  range 124 nm" ; cmemo = "StrmRelMnVl " + prod_elevation / 10. + " DEG " + cmode [ pinfo . opmode ] ; ctitle = "SRMV: Storm Relative Mean Velocity" ; cunit = "KT" ; cname = "StormMeanVelocity" ; } else if ( prod_type == VAD ) { radial = 0 ; prod_elevation = pinfo . p3 ; prod_min = pinfo . p4 ; prod_max = pinfo . p5 ; summary = "NVW is VAD wind profile which contains wind barbs and alpha numeric data" ; cmemo = "StrmRelMnVl " + prod_elevation / 10. + " DEG " + cmode [ pinfo . opmode ] ; ctilt = pname_lookup ( 48 , elevationNumber ) ; ctitle = "SRMV: Velocity Azimuth Display" ; cunit = "KT" ; cname = "VADWindSpeed" ; lat_min = latitude ; lat_max = latitude ; lon_min = longitude ; lon_max = longitude ; } else { ctilt = "error" ; ctitle = "error" ; cunit = "error" ; cname = "error" ; } /* add geo global att  */ ncfile . addAttribute ( null , new Attribute ( "summary" , "Nexrad level 3 data are WSR-88D radar products." + summary ) ) ; ncfile . addAttribute ( null , new Attribute ( "keywords_vocabulary" , ctilt ) ) ; ncfile . addAttribute ( null , new Attribute ( "conventions" , _Coordinate . Convention ) ) ; ncfile . addAttribute ( null , new Attribute ( "format" , "Level3/NIDS" ) ) ; ncfile . addAttribute ( null , new Attribute ( "geospatial_lat_min" , new Float ( lat_min ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "geospatial_lat_max" , new Float ( lat_max ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "geospatial_lon_min" , new Float ( lon_min ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "geospatial_lon_max" , new Float ( lon_max ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "geospatial_vertical_min" , new Float ( height ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "geospatial_vertical_max" , new Float ( height ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "RadarElevationNumber" , new Integer ( prod_elevation ) ) ) ; dstring = formatter . toDateTimeStringISO ( startDate ) ; ncfile . addAttribute ( null , new Attribute ( "time_coverage_start" , dstring ) ) ; dstring = formatter . toDateTimeStringISO ( endDate ) ; ncfile . addAttribute ( null , new Attribute ( "time_coverage_end" , dstring ) ) ; ncfile . addAttribute ( null , new Attribute ( "data_min" , new Float ( prod_min ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "data_max" , new Float ( prod_max ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "isRadial" , new Integer ( radial ) ) ) ; }


Input:
uncompress the TDWR products [CODESPLIT] byte [ ] uncompressed ( ByteBuffer buf , int offset , int uncomplen ) throws IOException { byte [ ] header = new byte [ offset ] ; buf . position ( 0 ) ; buf . get ( header ) ; byte [ ] out = new byte [ offset + uncomplen ] ; System . arraycopy ( header , 0 , out , 0 , offset ) ; CBZip2InputStream cbzip2 = new CBZip2InputStream ( ) ; int numCompBytes = buf . remaining ( ) ; byte [ ] bufc = new byte [ numCompBytes ] ; buf . get ( bufc , 0 , numCompBytes ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( bufc , 2 , numCompBytes - 2 ) ; //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis);
 cbzip2 . setStream ( bis ) ; int total = 0 ; int nread ; byte [ ] ubuff = new byte [ 40000 ] ; byte [ ] obuff = new byte [ 40000 ] ; try { while ( ( nread = cbzip2 . read ( ubuff ) ) != - 1 ) { if ( total + nread > obuff . length ) { byte [ ] temp = obuff ; obuff = new byte [ temp . length * 2 ] ; System . arraycopy ( temp , 0 , obuff , 0 , temp . length ) ; } System . arraycopy ( ubuff , 0 , obuff , total , nread ) ; total += nread ; } if ( obuff . length >= 0 ) System . arraycopy ( obuff , 0 , out , offset , total ) ; } catch ( BZip2ReadException ioe ) { log . warn ( "Nexrad2IOSP.uncompress " + raf . getLocation ( ) , ioe ) ; } return out ; }


Input: / * * Name : read_dividlen * * Purpose : Read divider ID header from NEXRAD Level III product * [CODESPLIT] Sinfo read_dividlen ( ByteBuffer buf , int offset ) { byte [ ] b2 = new byte [ 2 ] ; byte [ ] b4 = new byte [ 4 ] ; short D_divider ; short D_id ; Short tShort ; buf . position ( offset ) ; buf . get ( b2 , 0 , 2 ) ; tShort = ( Short ) convert ( b2 , DataType . SHORT , - 1 ) ; D_divider = tShort . shortValue ( ) ; buf . get ( b2 , 0 , 2 ) ; D_id = ( short ) getInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; block_length = getInt ( b4 , 4 ) ; buf . get ( b2 , 0 , 2 ) ; number_layers = ( short ) getInt ( b2 , 2 ) ; return new Sinfo ( D_divider , D_id , block_length , number_layers ) ; }


Input:
/ * * Name : read_msghead * * Purpose : Read message header from NEXRAD Level III product * * [CODESPLIT] int read_msghead ( ByteBuffer buf , int offset ) { byte [ ] b2 = new byte [ 2 ] ; byte [ ] b4 = new byte [ 4 ] ; buf . position ( 0 ) ; buf . get ( b2 , 0 , 2 ) ; mcode = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; mdate = ( short ) getInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; mtime = getInt ( b4 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; //out.println( "product date is " + dstring);
 mlength = getInt ( b4 , 4 ) ; buf . get ( b2 , 0 , 2 ) ; msource = ( short ) getInt ( b2 , 2 ) ; if ( stationId == null || stationName == null ) { try { NexradStationDB . init ( ) ; // make sure database is initialized
 NexradStationDB . Station station = NexradStationDB . getByIdNumber ( "000" + Short . toString ( msource ) ) ; if ( station != null ) { stationId = station . id ; stationName = station . name ; } } catch ( IOException ioe ) { log . error ( "NexradStationDB.init " + raf . getLocation ( ) , ioe ) ; } } buf . get ( b2 , 0 , 2 ) ; mdestId = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; mNumOfBlock = ( short ) getInt ( b2 , 2 ) ; return 1 ; }


Input:
get unsigned integer from byte array [CODESPLIT] int getUInt ( byte [ ] b , int num ) { int base = 1 ; int i ; int word = 0 ; int bv [ ] = new int [ num ] ; for ( i = 0 ; i < num ; i ++ ) { bv [ i ] = convertunsignedByte2Short ( b [ i ] ) ; } /*
        ** Calculate the integer value of the byte sequence
        */ for ( i = num - 1 ; i >= 0 ; i -- ) { word += base * bv [ i ] ; base *= 256 ; } return word ; }


Input:
get signed integer from bytes [CODESPLIT] int getInt ( byte [ ] b , int num ) { int base = 1 ; int i ; int word = 0 ; int bv [ ] = new int [ num ] ; for ( i = 0 ; i < num ; i ++ ) { bv [ i ] = convertunsignedByte2Short ( b [ i ] ) ; } if ( bv [ 0 ] > 127 ) { bv [ 0 ] -= 128 ; base = - 1 ; } /*
        ** Calculate the integer value of the byte sequence
        */ for ( i = num - 1 ; i >= 0 ; i -- ) { word += base * bv [ i ] ; base *= 256 ; } return word ; }


Input:
/ * * Name : read_proddesc * * Purpose : Read product description header from NEXRAD Level III product * * [CODESPLIT] Pinfo read_proddesc ( ByteBuffer buf , int offset ) { byte [ ] b2 = new byte [ 2 ] ; byte [ ] b4 = new byte [ 4 ] ; int off = offset ; Short tShort ; Integer tInt ; //Double tDouble = null;
 /* thredds global att */ ncfile . addAttribute ( null , new Attribute ( "title" , "Nexrad Level 3 Data" ) ) ; ncfile . addAttribute ( null , new Attribute ( "keywords" , "WSR-88D; NIDS" ) ) ; ncfile . addAttribute ( null , new Attribute ( "creator_name" , "NOAA/NWS" ) ) ; ncfile . addAttribute ( null , new Attribute ( "creator_url" , "http://www.ncdc.noaa.gov/oa/radar/radarproducts.html" ) ) ; ncfile . addAttribute ( null , new Attribute ( "naming_authority" , "NOAA/NCDC" ) ) ; //      ncfile.addAttribute(null, new Attribute("keywords_vocabulary", cname));
 //out.println( "offset of buffer is " + off);
 buf . position ( offset ) ; buf . get ( b2 , 0 , 2 ) ; tShort = ( Short ) convert ( b2 , DataType . SHORT , - 1 ) ; divider = tShort . shortValue ( ) ; ncfile . addAttribute ( null , new Attribute ( "Divider" , tShort ) ) ; buf . get ( b4 , 0 , 4 ) ; tInt = ( Integer ) convert ( b4 , DataType . INT , - 1 ) ; latitude = tInt . intValue ( ) / 1000.0 ; buf . get ( b4 , 0 , 4 ) ; tInt = ( Integer ) convert ( b4 , DataType . INT , - 1 ) ; longitude = tInt . intValue ( ) / 1000.0 ; buf . get ( b2 , 0 , 2 ) ; height = getInt ( b2 , 2 ) * 0.3048 ; // LOOK now in units of meters
 if ( useStationDB ) { // override by station table for more accuracy
 try { NexradStationDB . init ( ) ; // make sure database is initialized
 NexradStationDB . Station station = NexradStationDB . get ( "K" + stationId ) ; if ( station != null ) { latitude = station . lat ; longitude = station . lon ; height = station . elev ; stationName = station . name ; } } catch ( IOException ioe ) { log . error ( "NexradStationDB.init " + raf . getLocation ( ) , ioe ) ; } } ncfile . addAttribute ( null , new Attribute ( "RadarLatitude" , new Double ( latitude ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "RadarLongitude" , new Double ( longitude ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "RadarAltitude" , new Double ( height ) ) ) ; buf . get ( b2 , 0 , 2 ) ; pcode = ( short ) getInt ( b2 , 2 ) ; if ( stationId != null ) ncfile . addAttribute ( null , new Attribute ( "ProductStation" , stationId ) ) ; if ( stationName != null ) ncfile . addAttribute ( null , new Attribute ( "ProductStationName" , stationName ) ) ; buf . get ( b2 , 0 , 2 ) ; opmode = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( "OperationalMode" , new Short ( opmode ) ) ) ; buf . get ( b2 , 0 , 2 ) ; volumnScanPattern = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( "VolumeCoveragePatternName" , new Short ( volumnScanPattern ) ) ) ; buf . get ( b2 , 0 , 2 ) ; sequenceNumber = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( "SequenceNumber" , new Short ( sequenceNumber ) ) ) ; buf . get ( b2 , 0 , 2 ) ; volumeScanNumber = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( "VolumeScanNumber" , new Short ( volumeScanNumber ) ) ) ; buf . get ( b2 , 0 , 2 ) ; volumeScanDate = ( short ) getUInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; volumeScanTime = getUInt ( b4 , 4 ) ; buf . get ( b2 , 0 , 2 ) ; productDate = ( short ) getUInt ( b2 , 2 ) ; buf . get ( b4 , 0 , 4 ) ; productTime = getUInt ( b4 , 4 ) ; java . util . Date pDate = getDate ( productDate , productTime * 1000 ) ; String dstring = formatter . toDateTimeStringISO ( pDate ) ; ncfile . addAttribute ( null , new Attribute ( "DateCreated" , dstring ) ) ; buf . get ( b2 , 0 , 2 ) ; p1 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p2 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; elevationNumber = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( "ElevationNumber" , new Short ( elevationNumber ) ) ) ; buf . get ( b2 , 0 , 2 ) ; p3 = ( short ) getInt ( b2 , 2 ) ; off += 40 ; if ( pcode == 182 || pcode == 186 || pcode == 32 || pcode == 94 || pcode == 99 ) { for ( int i = 0 ; i < 16 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) bytesToInt ( b2 [ 0 ] , b2 [ 1 ] , false ) ; } } else if ( pcode == 159 || pcode == 161 || pcode == 163 || pcode == 170 || pcode == 172 || pcode == 173 || pcode == 174 || pcode == 175 ) { // Scale hw 31 32
 buf . get ( b4 , 0 , 4 ) ; byte [ ] b44 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 0 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b44 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) * 100 ) ; // offset  hw 33 34
 buf . get ( b4 , 0 , 4 ) ; byte [ ] b45 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 1 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b45 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) * 100 ) ; //  hw 35 reserve
 buf . get ( b2 , 0 , 2 ) ; threshold [ 2 ] = 0 ; // hw 36, 37, 38
 for ( int i = 3 ; i < 6 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) bytesToInt ( b2 [ 0 ] , b2 [ 1 ] , false ) ; } buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; } else if ( pcode == 176 ) { // Scale hw 31 32
 buf . get ( b4 , 0 , 4 ) ; byte [ ] b44 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 0 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b44 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) ) ; // offset  hw 33 34
 buf . get ( b4 , 0 , 4 ) ; byte [ ] b45 = { b4 [ 3 ] , b4 [ 2 ] , b4 [ 1 ] , b4 [ 0 ] } ; threshold [ 1 ] = ( short ) ( java . nio . ByteBuffer . wrap ( b45 ) . order ( java . nio . ByteOrder . LITTLE_ENDIAN ) . getFloat ( ) ) ; //  hw 35 reserve
 buf . get ( b2 , 0 , 2 ) ; threshold [ 2 ] = 0 ; // hw 36, 37, 38
 for ( int i = 3 ; i < 6 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) bytesToInt ( b2 [ 0 ] , b2 [ 1 ] , false ) ; } buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; buf . get ( b4 , 0 , 4 ) ; } else { for ( int i = 0 ; i < 16 ; i ++ ) { buf . get ( b2 , 0 , 2 ) ; threshold [ i ] = ( short ) getInt ( b2 , 2 ) ; } } off += 32 ; buf . get ( b2 , 0 , 2 ) ; p4 = ( short ) getInt ( b2 , 2 ) ; //int t1 = getUInt(b2, 2);
 buf . get ( b2 , 0 , 2 ) ; p5 = ( short ) getInt ( b2 , 2 ) ; //t1 = getUInt(b2, 2);
 buf . get ( b2 , 0 , 2 ) ; p6 = ( short ) getInt ( b2 , 2 ) ; //t1 = getUInt(b2, 2);
 buf . get ( b2 , 0 , 2 ) ; p7 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p8 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p9 = ( short ) getInt ( b2 , 2 ) ; buf . get ( b2 , 0 , 2 ) ; p10 = ( short ) getUInt ( b2 , 2 ) ; //bytesToInt(b2[0], b2[1], true); //       getInt(b2, 2); //
 off += 14 ; buf . get ( b2 , 0 , 2 ) ; numberOfMaps = ( short ) getInt ( b2 , 2 ) ; ncfile . addAttribute ( null , new Attribute ( "NumberOfMaps" , new Short ( numberOfMaps ) ) ) ; off += 2 ; buf . get ( b4 , 0 , 4 ) ; //tInt = (Integer)convert(b4, DataType.INT, -1);
 offsetToSymbologyBlock = getInt ( b4 , 4 ) ; //ncfile.addAttribute(null, new Attribute("offset_symbology_block",new Integer(offsetToSymbologyBlock)));
 off += 4 ; buf . get ( b4 , 0 , 4 ) ; //tInt = (Integer)convert(b4, DataType.INT, -1);
 offsetToGraphicBlock = getInt ( b4 , 4 ) ; //ncfile.addAttribute(null, new Attribute("offset_graphic_block",new Integer(offsetToGraphicBlock)));
 off += 4 ; buf . get ( b4 , 0 , 4 ) ; //tInt = (Integer)convert(b4, DataType.INT, -1);
 offsetToTabularBlock = getInt ( b4 , 4 ) ; //ncfile.addAttribute(null, new Attribute("offset_tabular_block",new Integer(offsetToTabularBlock)));
 off += 4 ; return new Pinfo ( divider , latitude , longitude , height , pcode , opmode , threshold , sequenceNumber , volumeScanNumber , volumeScanDate , volumeScanTime , productDate , productTime , p1 , p2 , p3 , p4 , p5 , p6 , p7 , p8 , p9 , p10 , elevationNumber , numberOfMaps , offsetToSymbologyBlock , offsetToGraphicBlock , offsetToTabularBlock ) ; //return pinfo;
 }


Input: this converts a byte array to another primitive array [CODESPLIT] protected Object convert ( byte [ ] barray , DataType dataType , int nelems , int byteOrder ) { if ( dataType == DataType . BYTE ) { return barray ; } if ( dataType == DataType . CHAR ) { return IospHelper . convertByteToChar ( barray ) ; } ByteBuffer bbuff = ByteBuffer . wrap ( barray ) ; if ( byteOrder >= 0 ) bbuff . order ( byteOrder == ucar . unidata . io . RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; if ( dataType == DataType . SHORT ) { ShortBuffer tbuff = bbuff . asShortBuffer ( ) ; short [ ] pa = new short [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . INT ) { IntBuffer tbuff = bbuff . asIntBuffer ( ) ; int [ ] pa = new int [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . FLOAT ) { FloatBuffer tbuff = bbuff . asFloatBuffer ( ) ; float [ ] pa = new float [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . DOUBLE ) { DoubleBuffer tbuff = bbuff . asDoubleBuffer ( ) ; double [ ] pa = new double [ nelems ] ; tbuff . get ( pa ) ; return pa ; } throw new IllegalStateException ( ) ; }


Input: this converts a byte array to a wrapped primitive ( Byte Short Integer Double Float Long ) [CODESPLIT] protected Object convert ( byte [ ] barray , DataType dataType , int byteOrder ) { if ( dataType == DataType . BYTE ) { return new Byte ( barray [ 0 ] ) ; } if ( dataType == DataType . CHAR ) { return new Character ( ( char ) barray [ 0 ] ) ; } ByteBuffer bbuff = ByteBuffer . wrap ( barray ) ; if ( byteOrder >= 0 ) bbuff . order ( byteOrder == ucar . unidata . io . RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; if ( dataType == DataType . SHORT ) { ShortBuffer tbuff = bbuff . asShortBuffer ( ) ; return new Short ( tbuff . get ( ) ) ; } else if ( dataType == DataType . INT ) { IntBuffer tbuff = bbuff . asIntBuffer ( ) ; return new Integer ( tbuff . get ( ) ) ; } else if ( dataType == DataType . LONG ) { LongBuffer tbuff = bbuff . asLongBuffer ( ) ; return new Long ( tbuff . get ( ) ) ; } else if ( dataType == DataType . FLOAT ) { FloatBuffer tbuff = bbuff . asFloatBuffer ( ) ; return new Float ( tbuff . get ( ) ) ; } else if ( dataType == DataType . DOUBLE ) { DoubleBuffer tbuff = bbuff . asDoubleBuffer ( ) ; return new Double ( tbuff . get ( ) ) ; } throw new IllegalStateException ( ) ; }


Input: Name : IsZlibed [CODESPLIT] int isZlibHed ( byte [ ] buf ) { short b0 = convertunsignedByte2Short ( buf [ 0 ] ) ; short b1 = convertunsignedByte2Short ( buf [ 1 ] ) ; if ( ( b0 & 0xf ) == Z_DEFLATED ) { if ( ( b0 >> 4 ) + 8 <= DEF_WBITS ) { if ( ( ( ( b0 << 8 ) + b1 ) % 31 ) == 0 ) { return 1 ; } } } return 0 ; }


Input:
/ * * Name : IsEncrypt * * Purpose : Check a two - byte sequence to see if it indicates the start of * an encrypted image . * [CODESPLIT] int IsEncrypt ( byte [ ] buf ) { /*
        ** These tests were deduced from inspection from encrypted NOAAPORT files.
        */ String b = new String ( buf , CDM . utf8Charset ) ; if ( b . startsWith ( "R3" ) ) { return 1 ; } return 0 ; }


Input:
/ * * Name : GetZlibedNexr * * Purpose : Read bytes from a NEXRAD Level III product into a buffer * This routine reads compressed image data for Level III formatted file . * We referenced McIDAS GetNexrLine function [CODESPLIT] byte [ ] GetZlibedNexr ( byte [ ] buf , int buflen , int hoff ) throws IOException { //byte[]  uncompr = new byte[ZLIB_BUF_LEN ]; /* decompression buffer          */
 //long    uncomprLen = ZLIB_BUF_LEN;        /* length of decompress space    */
 int doff ; /* # bytes offset to image       */ int numin ; /* # input bytes processed       */ numin = buflen - hoff ; if ( numin <= 0 ) { log . warn ( " No compressed data to inflate " + raf . getLocation ( ) ) ; return null ; } //byte[]  compr = new byte[numin-4];  /* compressed portion */
 /*
      ** Uncompress first portion of the image.  This should include:
      **
      **     SHO\r\r\n             <--+
      **     SEQ#\r\r\n               |  hoff bytes long
      **     WMO header\r\r\n         |
      **     PIL\r\r\n             <--+
      **
      **  -> CCB
      **     WMO header
      **     PIL
      **     portion of the image
      **
      */ /* a new copy of buff with only compressed bytes */ System . arraycopy ( buf , hoff , buf , hoff , numin - 4 ) ; // decompress the bytes
 int resultLength ; int result = 0 ; // byte[] inflateData = null;
 byte [ ] tmp ; int uncompLen = 24500 ; /* length of decompress space    */ byte [ ] uncomp = new byte [ uncompLen ] ; Inflater inflater = new Inflater ( false ) ; inflater . setInput ( buf , hoff , numin - 4 ) ; int offset = 0 ; int limit = 20000 ; while ( inflater . getRemaining ( ) > 0 ) { try { resultLength = inflater . inflate ( uncomp , offset , 4000 ) ; } catch ( DataFormatException ex ) { //System.out.println("ERROR on inflation "+ex.getMessage());
 //ex.printStackTrace();
 log . error ( "nids Inflater" , ex ) ; throw new IOException ( ex . getMessage ( ) , ex ) ; } offset = offset + resultLength ; result = result + resultLength ; if ( result > limit ) { // when uncomp data larger then limit, the uncomp need to increase size
 tmp = new byte [ result ] ; System . arraycopy ( uncomp , 0 , tmp , 0 , result ) ; uncompLen = uncompLen + 10000 ; uncomp = new byte [ uncompLen ] ; System . arraycopy ( tmp , 0 , uncomp , 0 , result ) ; } if ( resultLength == 0 ) { int tt = inflater . getRemaining ( ) ; byte [ ] b2 = new byte [ 2 ] ; System . arraycopy ( buf , hoff + numin - 4 - tt , b2 , 0 , 2 ) ; if ( result + tt > uncompLen ) { tmp = new byte [ result ] ; System . arraycopy ( uncomp , 0 , tmp , 0 , result ) ; uncompLen = uncompLen + 10000 ; uncomp = new byte [ uncompLen ] ; System . arraycopy ( tmp , 0 , uncomp , 0 , result ) ; } if ( isZlibHed ( b2 ) == 0 ) { System . arraycopy ( buf , hoff + numin - 4 - tt , uncomp , result , tt ) ; result = result + tt ; break ; } inflater . reset ( ) ; inflater . setInput ( buf , hoff + numin - 4 - tt , tt ) ; } } inflater . end ( ) ; /*
      ** Find out how long CCB is.  This is done by using the lower order
      ** 6 bits from the first uncompressed byte and all 8 bits of the
      ** second uncompressed byte.
      */ doff = 2 * ( ( ( uncomp [ 0 ] & 0x3f ) << 8 ) | ( uncomp [ 1 ] & 0xFF ) ) ; for ( int i = 0 ; i < 2 ; i ++ ) { /* eat WMO and PIL */ while ( ( doff < result ) && ( uncomp [ doff ] != ' ' ) ) doff ++ ; doff ++ ; } byte [ ] data = new byte [ result - doff ] ; System . arraycopy ( uncomp , doff , data , 0 , result - doff ) ; //
 /*
      ** Copy header bytes to decompression buffer.  The objective is to
      ** create an output buffer that looks like an uncompressed NOAAPORT
      ** NEXRAD product:
      **
      **   Section               Product               Example             End
      **            +--------------------------------+
      **            |                                |
      **      1     |        start of product        | CTRL-A              \r\r\n
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      2     |        sequence number         | 237                 \r\r\n
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      3     |          WMO header            | SDUS53 KARX 062213  \r\r\n
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      4     |             PIL                | N0RARX              \r\r\n
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      5     |                                | AAO130006R2 CH-1
      **            |                                | Interface Control
      **            |             CCB                | Document (ICD)
      **            |                                | for the NWS NWSTG
      **            |                                | Figure 7-1 p 38
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      6     |          WMO header            | SDUS53 KARX 062213  \r\r\n
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      7     |             PIL                | N0RARX              \r\r\n
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **            |                                |
      **            |                                |
      **            |                                |
      **      8     |            image               |
      **            |                                |
      **            |                                |
      **            |                                |
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **      9     |            trailer             | \r\r\nETX
      **            |                                |
      **            +--------------------------------+
      **            |                                |
      **     10     |     Unidata floater trailer    | \0\0
      **            |                                |
      **            +--------------------------------+
      **
      ** Sections 5-8 are zlib compressed.  They must be uncompressed and
      ** read to find out where the image begins.  When this is done, sections
      ** 5-7 are thrown away and 8 is returned immediately following 4.
      ** Section 9 and, if it is there, section 10 are also thrown away.
      **
      */ return data ; }


Input: / * * Name : code_lookup * * Purpose : Derive some derivable metadata * [CODESPLIT] static int code_typelookup ( int code ) { int type ; final int [ ] types = { Other , Other , Other , Other , Other , /*   0-  9 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /*  10- 19 */ Other , Base_Reflect , Base_Reflect , Base_Reflect , Base_Reflect , BaseReflect248 , Base_Reflect , Velocity , /*  20- 29 */ Velocity , Velocity , Velocity , Velocity , Velocity , SPECTRUM , SPECTRUM , SPECTRUM , Other , DigitalHybridReflect , Other , Other , /*  30- 39 */ Comp_Reflect , Comp_Reflect , Comp_Reflect , Comp_Reflect , Other , Other , Echo_Tops , Other , Other , Other , /*  40- 49 */ Other , Other , Other , VAD , Other , Other , Other , Other , Other , Other , /*  50- 59 */ StrmRelMeanVel , StrmRelMeanVel , Vert_Liquid , Other , Other , Other , Other , Other , Layer_Reflect_Avg , /*  60- 69 */ Layer_Reflect_Avg , Layer_Reflect_Max , Layer_Reflect_Max , Other , Other , Other , Other , Other , Other , Other , Other , /*  70- 79 */ Other , Other , Other , Precip_1 , Precip_3 , Precip_Accum , Precip_Array , Other , /*  80- 89 */ Other , Other , Other , Other , Other , Other , Layer_Reflect_Avg , Layer_Reflect_Max , Other , Other , Other , /*  90- 99 */ BaseReflectivityDR , Other , Other , Other , Other , BaseVelocityDV , Other , Other , Other , Other , Other , /* 100-109 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /* 110-119 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /* 120-129 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , DigitalVert_Liquid , /* 130-139 */ EnhancedEcho_Tops , Other , Other , DigitalStormTotalPrecip , Other , Other , Other , Other , Other , Other , /* 140-149 */ Other , Other , Other , Other , Other , Other , Other , Other , Other , Other , /* 150-159 */ Other , Other , Other , Other , DigitalDifferentialReflectivity , Other , DigitalCorrelationCoefficient , Other , DigitalDifferentialPhase , Other , /* 160-169 */ HydrometeorClassification , Other , Other , Other , OneHourAccumulation , DigitalAccumulationArray , StormTotalAccumulation , DigitalStormTotalAccumulation , Accumulation3Hour , Digital1HourDifferenceAccumulation , /* 170-179 */ DigitalTotalDifferenceAccumulation , DigitalInstantaneousPrecipitationRate , HypridHydrometeorClassification , Other , Other , Reflect1 , Reflect1 , Velocity1 , Velocity1 , Other , /* 180-189 */ SPECTRUM1 , Reflect1 , Reflect1 , Other , Other , } ; if ( code < 0 || code > 189 ) type = Other ; else type = types [ code ] ; return type ; }


Input: / * product id table [CODESPLIT] static String pname_lookup ( int code , int elevation ) { String pname = null ; switch ( code ) { case 15 : if ( elevation == 1 ) pname = "NAX" ; else if ( elevation == 3 ) pname = "NBX" ; else pname = "N" + elevation / 2 + "X" ; break ; case 16 : if ( elevation == 1 ) pname = "NAC" ; else if ( elevation == 3 ) pname = "NBC" ; else pname = "N" + elevation / 2 + "C" ; break ; case 17 : if ( elevation == 1 ) pname = "NAK" ; else if ( elevation == 3 ) pname = "NBK" ; else pname = "N" + elevation / 2 + "K" ; break ; case 18 : if ( elevation == 1 ) pname = "NAH" ; else if ( elevation == 3 ) pname = "NBH" ; else pname = "N" + elevation / 2 + "H" ; break ; case 19 : pname = "N" + elevation + "R" ; break ; case 20 : pname = "N0Z" ; break ; case 25 : pname = "N0W" ; break ; case 27 : pname = "N" + elevation + "V" ; break ; case 28 : pname = "NSP" ; break ; case 30 : pname = "NSW" ; break ; case 36 : pname = "NCO" ; break ; case 37 : pname = "NCR" ; break ; case 38 : pname = "NCZ" ; break ; case 41 : pname = "NET" ; break ; case 48 : pname = "NVW" ; break ; case 56 : pname = "N" + elevation + "S" ; break ; case 57 : pname = "NVL" ; break ; case 65 : pname = "NLL" ; break ; case 66 : pname = "NML" ; break ; case 78 : pname = "N1P" ; break ; case 79 : pname = "N3P" ; break ; case 80 : pname = "NTP" ; break ; case 81 : pname = "DPA" ; break ; case 90 : pname = "NHL" ; break ; case 94 : if ( elevation == 1 ) pname = "NAQ" ; else if ( elevation == 3 ) pname = "NBQ" ; else pname = "N" + elevation / 2 + "Q" ; break ; case 99 : if ( elevation == 1 ) pname = "NAU" ; else if ( elevation == 3 ) pname = "NBU" ; else pname = "N" + elevation / 2 + "U" ; break ; case 134 : pname = "DVL" ; break ; case 135 : pname = "EET" ; break ; case 182 : pname = "DV" ; break ; case 187 : case 181 : pname = "R" ; break ; case 186 : case 180 : pname = "DR" ; break ; case 183 : pname = "V" ; break ; case 185 : pname = "SW" ; break ; default : break ; } return pname ; }


Input: / * product resolution [CODESPLIT] static double code_reslookup ( int code ) { double data_res ; final double [ ] res = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*   0-  9 */ 0 , 0 , 0 , 0 , 0 , 0 , 1 , 2 , 4 , 1 , /*  10- 19 */ 2 , 4 , 0.25 , 0.5 , 1 , 0.25 , 0.5 , 1 , 0.25 , 0 , /*  20- 29 */ 1 , 0 , 1 , 0 , 0 , 1 , 4 , 1 , 4 , 0 , /*  30- 39 */ 0 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*  40- 49 */ 0 , 0 , 0 , 0 , 0 , 0.5 , 1 , 4 , 0 , 0 , /*  50- 59 */ 0 , 0 , 0 , 4 , 4 , 4 , 4 , 0 , 0 , 0 , /*  60- 69 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 1 , /*  70- 79 */ 1 , 4 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 4 , /*  80- 89 */ 4 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0.25 , /*  90- 99 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 100-109 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 110-119 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 120-129 */ 0 , 0 , 0 , 0 , 1 , 1 , 0 , 0 , 1 , 0 , /* 130-139 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 140-149 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0.25 , /* 150-159 */ 0 , 0.25 , 0 , 0.25 , 0 , 0.25 , 0 , 0 , 0 , 2 , /* 160-169 */ 0.25 , 2 , 0.25 , 0.25 , 0.25 , 0.25 , 0.25 , 0.25 , 0 , 0 , /* 170-179 */ 0 , 150.0 , 150.0 , 0 , 0 , 0 , 300.0 , 0 , 0 , 0 , /* 180-189 */ } ; if ( code < 0 || code > 189 ) data_res = 0 ; else data_res = res [ code ] ; return data_res ; }


Input: / * product level tabel [CODESPLIT] static int code_levelslookup ( int code ) { int level ; final int [ ] levels = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*   0-  9 */ 0 , 0 , 0 , 0 , 0 , 0 , 8 , 8 , 8 , 16 , /*  10- 19 */ 16 , 16 , 8 , 8 , 8 , 16 , 16 , 16 , 8 , 0 , /*  20- 29 */ 8 , 0 , 256 , 0 , 0 , 8 , 8 , 16 , 16 , 0 , /*  30- 39 */ 0 , 16 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /*  40- 49 */ 0 , 0 , 0 , 0 , 0 , 16 , 16 , 16 , 0 , 0 , /*  50- 59 */ 0 , 0 , 0 , 8 , 8 , 8 , 8 , 0 , 0 , 0 , /*  60- 69 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 16 , 16 , /*  70- 79 */ 16 , 256 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 8 , /*  80- 89 */ 8 , 0 , 0 , 0 , 256 , 0 , 0 , 0 , 0 , 256 , /*  90- 99 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 100-109 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 110-119 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 120-129 */ 0 , 0 , 0 , 0 , 256 , 199 , 0 , 0 , 256 , 0 , /* 130-139 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , /* 140-149 */ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 256 , /* 150-159 */ 0 , 256 , 0 , 256 , 0 , 256 , 0 , 0 , 0 , 16 , /* 160-169 */ 256 , 16 , 256 , 256 , 0 , 0 , 0 , 16 , 0 , 0 , /* 170-179 */ 0 , 16 , 256 , 0 , 0 , 0 , 256 , 0 , 0 , 0 , /* 180-189 */ } ; if ( code < 0 || code > 189 ) level = 0 ; else level = levels [ code ] ; return level ; }


Input: //////////////////////////////////////////////////////// [CODESPLIT] public void init ( ) throws ServletException { org . slf4j . Logger logServerStartup = org . slf4j . LoggerFactory . getLogger ( "serverStartup" ) ; logServerStartup . info ( getClass ( ) . getName ( ) + " initialization start" ) ; try { System . setProperty ( "file.encoding" , "UTF-8" ) ; Field charset = Charset . class . getDeclaredField ( "defaultCharset" ) ; charset . setAccessible ( true ) ; charset . set ( null , null ) ; initialize ( ) ; } catch ( Exception e ) { throw new ServletException ( e ) ; } }


Input: Primary Controller Entry Point [CODESPLIT] public void handleRequest ( HttpServletRequest req , HttpServletResponse res ) throws IOException { DapLog . debug ( "doGet(): User-Agent = " + req . getHeader ( "User-Agent" ) ) ; if ( ! this . initialized ) initialize ( ) ; DapRequest daprequest = getRequestState ( req , res ) ; String url = daprequest . getOriginalURL ( ) ; StringBuilder info = new StringBuilder ( "doGet():" ) ; info . append ( " dataset = " ) ; info . append ( " url = " ) ; info . append ( url ) ; if ( DEBUG ) { System . err . println ( "DAP4 Servlet: processing url: " + daprequest . getOriginalURL ( ) ) ; } DapContext dapcxt = new DapContext ( ) ; // Add entries to the context dapcxt . put ( HttpServletRequest . class , req ) ; dapcxt . put ( HttpServletResponse . class , res ) ; dapcxt . put ( DapRequest . class , daprequest ) ; ByteOrder order = daprequest . getOrder ( ) ; ChecksumMode checksummode = daprequest . getChecksumMode ( ) ; dapcxt . put ( Dap4Util . DAP4ENDIANTAG , order ) ; dapcxt . put ( Dap4Util . DAP4CSUMTAG , checksummode ) ; // Transfer all other queries Map < String , String > queries = daprequest . getQueries ( ) ; for ( Map . Entry < String , String > entry : queries . entrySet ( ) ) { if ( dapcxt . get ( entry . getKey ( ) ) == null ) { dapcxt . put ( entry . getKey ( ) , entry . getValue ( ) ) ; } } if ( url . endsWith ( FAVICON ) ) { doFavicon ( FAVICON , dapcxt ) ; return ; } String datasetpath = DapUtil . nullify ( DapUtil . canonicalpath ( daprequest . getDataset ( ) ) ) ; try { if ( datasetpath == null ) { // This is the case where a request was made without a dataset; // According to the spec, I think we should return the // services/capabilities document doCapabilities ( daprequest , dapcxt ) ; } else { RequestMode mode = daprequest . getMode ( ) ; if ( mode == null ) throw new DapException ( "Unrecognized request extension" ) . setCode ( HttpServletResponse . SC_BAD_REQUEST ) ; switch ( mode ) { case DMR : doDMR ( daprequest , dapcxt ) ; break ; case DAP : doData ( daprequest , dapcxt ) ; break ; case DSR : doDSR ( daprequest , dapcxt ) ; break ; default : throw new DapException ( "Unrecognized request extension" ) . setCode ( HttpServletResponse . SC_BAD_REQUEST ) ; } } } catch ( Throwable t ) { t . printStackTrace ( ) ; int code = HttpServletResponse . SC_BAD_REQUEST ; if ( t instanceof DapException ) { DapException e = ( DapException ) t ; code = e . getCode ( ) ; if ( code <= 0 ) code = DapCodes . SC_BAD_REQUEST ; e . setCode ( code ) ; } else if ( t instanceof FileNotFoundException ) code = DapCodes . SC_NOT_FOUND ; else if ( t instanceof UnsupportedOperationException ) code = DapCodes . SC_FORBIDDEN ; else if ( t instanceof MalformedURLException ) code = DapCodes . SC_NOT_FOUND ; else if ( t instanceof IOException ) code = DapCodes . SC_BAD_REQUEST ; else code = DapCodes . SC_INTERNAL_SERVER_ERROR ; senderror ( daprequest , code , t ) ; } //catch }


Input: Process a DSR request . * [CODESPLIT] protected void doDSR ( DapRequest drq , DapContext cxt ) throws IOException { try { DapDSR dsrbuilder = new DapDSR ( ) ; String dsr = dsrbuilder . generate ( drq . getURL ( ) ) ; OutputStream out = drq . getOutputStream ( ) ; addCommonHeaders ( drq ) ; // Add relevant headers // Wrap the outputstream with a Chunk writer ByteOrder order = ( ByteOrder ) cxt . get ( Dap4Util . DAP4ENDIANTAG ) ; ChunkWriter cw = new ChunkWriter ( out , RequestMode . DSR , order ) ; cw . writeDSR ( dsr ) ; cw . close ( ) ; } catch ( IOException ioe ) { throw new DapException ( "DSR generation error" , ioe ) . setCode ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } }


Input: Process a DMR request . [CODESPLIT] protected void doDMR ( DapRequest drq , DapContext cxt ) throws IOException { // Convert the url to an absolute path String realpath = getResourcePath ( drq , drq . getDatasetPath ( ) ) ; DSP dsp = DapCache . open ( realpath , cxt ) ; DapDataset dmr = dsp . getDMR ( ) ; /* Annotate with our endianness */ ByteOrder order = ( ByteOrder ) cxt . get ( Dap4Util . DAP4ENDIANTAG ) ; setEndianness ( dmr , order ) ; // Process any constraint view CEConstraint ce = null ; String sce = drq . queryLookup ( DapProtocol . CONSTRAINTTAG ) ; ce = CEConstraint . compile ( sce , dmr ) ; setConstraint ( dmr , ce ) ; // Provide a PrintWriter for capturing the DMR. StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; // Get the DMR as a string DMRPrinter dapprinter = new DMRPrinter ( dmr , ce , pw , drq . getFormat ( ) ) ; if ( cxt . get ( Dap4Util . DAP4TESTTAG ) != null ) dapprinter . testprint ( ) ; else dapprinter . print ( ) ; pw . close ( ) ; sw . close ( ) ; String sdmr = sw . toString ( ) ; if ( DEBUG ) System . err . println ( "Sending: DMR:\n" + sdmr ) ; addCommonHeaders ( drq ) ; // Add relevant headers // Wrap the outputstream with a Chunk writer OutputStream out = drq . getOutputStream ( ) ; ChunkWriter cw = new ChunkWriter ( out , RequestMode . DMR , order ) ; cw . cacheDMR ( sdmr ) ; cw . close ( ) ; }


Input:
Process a DataDMR request . Note that if this throws an exception then it has not yet started to output a response . It a response had been initiated then the exception would produce an error chunk . <p > * [CODESPLIT] protected void doData ( DapRequest drq , DapContext cxt ) throws IOException { // Convert the url to an absolute path String realpath = getResourcePath ( drq , drq . getDatasetPath ( ) ) ; DSP dsp = DapCache . open ( realpath , cxt ) ; if ( dsp == null ) throw new DapException ( "No such file: " + drq . getResourceRoot ( ) ) ; DapDataset dmr = dsp . getDMR ( ) ; if ( DUMPDMR ) { printDMR ( dmr ) ; System . err . println ( printDMR ( dmr ) ) ; System . err . flush ( ) ; } /* Annotate with our endianness */ ByteOrder order = ( ByteOrder ) cxt . get ( Dap4Util . DAP4ENDIANTAG ) ; setEndianness ( dmr , order ) ; // Process any constraint CEConstraint ce = null ; String sce = drq . queryLookup ( DapProtocol . CONSTRAINTTAG ) ; ce = CEConstraint . compile ( sce , dmr ) ; setConstraint ( dmr , ce ) ; StringWriter sw = new StringWriter ( ) ; PrintWriter pw = new PrintWriter ( sw ) ; // Get the DMR as a string DMRPrinter dapprinter = new DMRPrinter ( dmr , ce , pw , drq . getFormat ( ) ) ; dapprinter . print ( ) ; pw . close ( ) ; sw . close ( ) ; String sdmr = sw . toString ( ) ; if ( DEBUG || DUMPDMR ) System . err . println ( "Sending: Data DMR:\n" + sdmr ) ; // Wrap the outputstream with a Chunk writer OutputStream out = drq . getOutputStream ( ) ; ChunkWriter cw = new ChunkWriter ( out , RequestMode . DAP , order ) ; cw . setWriteLimit ( getBinaryWriteLimit ( ) ) ; cw . cacheDMR ( sdmr ) ; cw . flush ( ) ; addCommonHeaders ( drq ) ; // Dump the databuffer part switch ( drq . getFormat ( ) ) { case TEXT : case XML : case HTML : throw new IOException ( "Unsupported return format: " + drq . getFormat ( ) ) ; /*
            sw = new StringWriter();
            DAPPrint dp = new DAPPrint(sw);
            dp.print(dsp.getDataset(), ce);
            break;
                */ case NONE : default : DapSerializer writer = new DapSerializer ( dsp , ce , cw , order , drq . getChecksumMode ( ) ) ; writer . write ( dsp . getDMR ( ) ) ; cw . flush ( ) ; cw . close ( ) ; break ; } // Should we dump data? if ( DUMPDATA ) { byte [ ] data = cw . getDump ( ) ; if ( data != null ) DapDump . dumpbytestream ( data , cw . getWriteOrder ( ) , "ChunkWriter.write" ) ; } }


Input: Utility Methods [CODESPLIT] protected void addCommonHeaders ( DapRequest drq ) throws IOException { // Add relevant headers ResponseFormat format = drq . getFormat ( ) ; if ( format == null ) format = ResponseFormat . NONE ; DapProtocol . ContentType contentheaders = DapProtocol . contenttypes . get ( drq . getMode ( ) ) ; String header = contentheaders . getFormat ( format ) ; if ( header != null ) { header = header + "; charset=utf-8" ; drq . setResponseHeader ( "Content-Type" , header ) ; } else DapLog . error ( "Cannot determine response Content-Type" ) ; // Not sure what this should be yet //setHeader("Content-Description","?"); // Again, not sure what value to use //setHeader("Content-Disposition","?"); //not legal drq.setResponseHeader("Content-Encoding", IS_BIG_ENDIAN ? BIG_ENDIAN : LITTLE_ENDIAN); }


Input: Merge the servlet inputs into a single object for easier transport as well as adding value . [CODESPLIT] protected DapRequest getRequestState ( HttpServletRequest rq , HttpServletResponse rsp ) throws IOException { return new DapRequest ( this , rq , rsp ) ; }


Input: Generate an error based on the parameters [CODESPLIT] protected void senderror ( DapRequest drq , int httpcode , Throwable t ) throws IOException { if ( httpcode == 0 ) httpcode = HttpServletResponse . SC_BAD_REQUEST ; ErrorResponse err = new ErrorResponse ( ) ; err . setCode ( httpcode ) ; if ( t == null ) { err . setMessage ( "Servlet error: " + drq . getURL ( ) ) ; } else { StringWriter sw = new StringWriter ( ) ; PrintWriter p = new PrintWriter ( sw ) ; t . printStackTrace ( p ) ; p . close ( ) ; sw . close ( ) ; err . setMessage ( sw . toString ( ) ) ; } err . setContext ( drq . getURL ( ) ) ; String errormsg = err . buildXML ( ) ; drq . getResponse ( ) . sendError ( httpcode , errormsg ) ; }


Input: Set special attribute : endianness : overwrite exiting value [CODESPLIT] void setEndianness ( DapDataset dmr , ByteOrder order ) throws DapException { DapAttribute a = dmr . findAttribute ( DapUtil . LITTLEENDIANATTRNAME ) ; if ( a == null ) { a = new DapAttribute ( DapUtil . LITTLEENDIANATTRNAME , DapType . UINT8 ) ; dmr . addAttribute ( a ) ; } //ByteOrder order = (ByteOrder) cxt.get(Dap4Util.DAP4ENDIANTAG); String oz = ( order == ByteOrder . BIG_ENDIAN ? "0" : "1" ) ; a . setValues ( new String [ ] { oz } ) ; }


Input: Set special attribute : constraint : overwrite exiting value [CODESPLIT] void setConstraint ( DapDataset dmr , CEConstraint ce ) throws DapException { if ( ce == null ) return ; if ( ce . isUniversal ( ) ) return ; DapAttribute a = dmr . findAttribute ( DapUtil . CEATTRNAME ) ; if ( a == null ) { a = new DapAttribute ( DapUtil . CEATTRNAME , DapType . STRING ) ; dmr . addAttribute ( a ) ; } String sce = ce . toConstraintString ( ) ; a . setValues ( new String [ ] { sce } ) ; }


Input: Set the anchor point . [CODESPLIT] public boolean anchor ( Point p ) { firstStretch = true ; anchorPt . x = p . x ; anchorPt . y = p . y ; stretchedPt . x = lastPt . x = anchorPt . x ; stretchedPt . y = lastPt . y = anchorPt . y ; return true ; }


Input: Erase the last rectangle and draw a new one from the anchor point to this point . [CODESPLIT] public void stretch ( Point p ) { lastPt . x = stretchedPt . x ; lastPt . y = stretchedPt . y ; stretchedPt . x = p . x ; stretchedPt . y = p . y ; Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; if ( firstStretch == true ) firstStretch = false ; else drawLast ( g ) ; drawNext ( g ) ; } finally { g . dispose ( ) ; } // try } // if }


Input: Last point done with drawing . [CODESPLIT] public void end ( Point p ) { lastPt . x = endPt . x = p . x ; lastPt . y = endPt . y = p . y ; Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; drawLast ( g ) ; } finally { g . dispose ( ) ; } } }


Input: Last point done with drawing . [CODESPLIT] public void done ( ) { Graphics2D g = ( Graphics2D ) component . getGraphics ( ) ; if ( g != null ) { try { g . setXORMode ( component . getBackground ( ) ) ; drawLast ( g ) ; } finally { g . dispose ( ) ; } } }


Input: Get current Bounds [CODESPLIT] public Rectangle getBounds ( ) { return new Rectangle ( stretchedPt . x < anchorPt . x ? stretchedPt . x : anchorPt . x , stretchedPt . y < anchorPt . y ? stretchedPt . y : anchorPt . y , Math . abs ( stretchedPt . x - anchorPt . x ) , Math . abs ( stretchedPt . y - anchorPt . y ) ) ; }


Input: Get previous Bounds [CODESPLIT] public Rectangle lastBounds ( ) { return new Rectangle ( lastPt . x < anchorPt . x ? lastPt . x : anchorPt . x , lastPt . y < anchorPt . y ? lastPt . y : anchorPt . y , Math . abs ( lastPt . x - anchorPt . x ) , Math . abs ( lastPt . y - anchorPt . y ) ) ; }


Input:
Parse the text in W3C profile of ISO 8601 format . @param text parse this text @return equivalent Date or null if failure @see <a href = http : // www . w3 . org / TR / NOTE - datetime > W3C profile of ISO 8601< / a > [CODESPLIT] @ Deprecated public Date getISODate ( String text ) { Date result ; // try "yyyy-MM-dd HH:mm:ss"
 try { result = stdDateTimeFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try  "yyyy-MM-dd'T'HH:mm:ss"
 try { result = isoDateTimeFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try "yyyy-MM-dd'T'HH:mm"
 try { result = isoDateNoSecsFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try "yyyy-MM-dd HH:mm"
 try { result = stdDateNoSecsFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } // now try "yyyy-MM-dd"
 try { result = dateOnlyFormat ( text ) ; return result ; } catch ( java . text . ParseException e ) { } return null ; }


Input: Parse text in the format yyyy - MM - dd HH : mm : ss [CODESPLIT] private Date stdDateTimeFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? "" : text . trim ( ) ; stdDateTimeFormat ( ) ; return stdDateTimeFormat . parse ( text ) ; }


Input: Parse text in the format yyyy - MM - dd HH : mm [CODESPLIT] private Date stdDateNoSecsFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? "" : text . trim ( ) ; stdDateNoSecsFormat ( ) ; return stdDateNoSecsFormat . parse ( text ) ; }


Input: Parse text in the format yyyy - MM - dd T HH : mm : ss [CODESPLIT] private Date isoDateTimeFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? "" : text . trim ( ) ; isoDateTimeFormat ( ) ; return isoDateTimeFormat . parse ( text ) ; }


Input: Parse text in the format yyyy - MM - dd T HH : mm [CODESPLIT] private Date isoDateNoSecsFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? "" : text . trim ( ) ; isoDateNoSecsFormat ( ) ; return isoDateNoSecsFormat . parse ( text ) ; }


Input: Parse text in the format yyyy - MM - dd [CODESPLIT] private Date dateOnlyFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? "" : text . trim ( ) ; dateOnlyFormat ( ) ; return dateOnlyFormat . parse ( text ) ; }


Input: standard date format = yyyy - MM - dd HH : mm : ssZ [CODESPLIT] public String toDateTimeString ( Date date ) { if ( date == null ) return "Unknown" ; stdDateTimeFormat ( ) ; return stdDateTimeFormat . format ( date ) + "Z" ; }


Input:
change shape of the data variables [CODESPLIT] protected void replaceDataVars ( StructureMembers sm ) { for ( StructureMembers . Member m : sm . getMembers ( ) ) { VariableSimpleIF org = this . cols . get ( m . getName ( ) ) ; int rank = org . getRank ( ) ; List < Dimension > orgDims = org . getDimensions ( ) ; // only keep the last n
 int n = m . getShape ( ) . length ; List < Dimension > dims = orgDims . subList ( rank - n , rank ) ; VariableSimpleImpl result = new VariableSimpleImpl ( org . getShortName ( ) , org . getDescription ( ) , org . getUnitsString ( ) , org . getDataType ( ) , dims ) ; for ( Attribute att : org . getAttributes ( ) ) result . ( att ) ; this . cols . put ( m . getName ( ) , result ) ; } }


Input: Even if JavaBits is 64 the limit on an array size is Integer . MAX_VALUE . [CODESPLIT] public static void ensureArraySizeOkay ( long tSize , String attributeTo ) { if ( tSize >= Integer . MAX_VALUE ) throw new RuntimeException ( memoryTooMuchData + "  " + MessageFormat . format ( memoryArraySize , "" + tSize , "" + Integer . MAX_VALUE ) + ( attributeTo == null || attributeTo . length ( ) == 0 ? "" : " (" + attributeTo + ")" ) ) ; }


Input: Safely rounds a double to an int . ( Math . round but rounds to a long and not safely . ) [CODESPLIT] public static int roundToInt ( double d ) { return d > Integer . MAX_VALUE || d <= Integer . MIN_VALUE - 0.5 || ! isFinite ( d ) ? Integer . MAX_VALUE : ( int ) Math . round ( d ) ; //safe since checked for larger values above }


Input: see http : // www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2_doc . shtml [CODESPLIT] private void initLocalTable ( ) { String tablePath = config . getPath ( ) ; ClassLoader cl = KmaLocalTables . class . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( tablePath ) ) { if ( is == null ) throw new IllegalStateException ( "Cant find " + tablePath ) ; List < TableParser . Record > recs = TableParser . readTable ( is , "41,112,124i,136i,148i,160" , 1000 ) ; for ( TableParser . Record record : recs ) { String name = ( String ) record . get ( 0 ) ; int disc = ( Integer ) record . get ( 2 ) ; int cat = ( Integer ) record . get ( 3 ) ; int param = ( Integer ) record . get ( 4 ) ; String unit = ( String ) record . get ( 5 ) ; Grib2Parameter s = new Grib2Parameter ( disc , cat , param , name , unit , null , null ) ; local . put ( makeParamId ( disc , cat , param ) , s ) ; } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } }


Input: Convert 2 bytes into a signed integer . [CODESPLIT] public static int int2 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; return int2 ( a , b ) ; }


Input: Convert unsigned bytes into an integer . [CODESPLIT] public static int uint ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; return ( int ) DataType . unsignedByteToShort ( ( byte ) a ) ; }


Input: Convert 3 bytes into a signed integer . [CODESPLIT] public static int int3 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; return int3 ( a , b , c ) ; }


Input: Convert 2 bytes into an unsigned integer . [CODESPLIT] public static int uint2 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; return uint2 ( a , b ) ; }


Input: Convert 3 bytes into an unsigned integer . [CODESPLIT] public static int uint3 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; return uint3 ( a , b , c ) ; }


Input: Convert 4 bytes into a float value . [CODESPLIT] public static float float4 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; int d = raf . read ( ) ; return float4 ( a , b , c , d ) ; }


Input: Convert 4 bytes to a float . [CODESPLIT] public static float float4 ( int a , int b , int c , int d ) { int sgn , mant , exp ; mant = b << 16 | c << 8 | d ; if ( mant == 0 ) { return 0.0f ; } sgn = - ( ( ( a & 128 ) >> 6 ) - 1 ) ; exp = ( a & 127 ) - 64 ; return ( float ) ( sgn * Math . pow ( 16.0 , exp - 6 ) * mant ) ; }


Input: Convert 8 bytes into a signed long . [CODESPLIT] public static long int8 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; int d = raf . read ( ) ; int e = raf . read ( ) ; int f = raf . read ( ) ; int g = raf . read ( ) ; int h = raf . read ( ) ; return ( 1 - ( ( a & 128 ) >> 6 ) ) * ( ( long ) ( a & 127 ) << 56 | ( long ) b << 48 | ( long ) c << 40 | ( long ) d << 32 | e << 24 | f << 16 | g << 8 | h ) ; }


Input: count number of bits on in bitmap [CODESPLIT] public static int countBits ( byte [ ] bitmap ) { int bits = 0 ; for ( byte b : bitmap ) { short s = DataType . unsignedByteToShort ( b ) ; bits += Long . bitCount ( s ) ; } return bits ; }


Input: lon naught ?? [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new LambertConformal ( getOriginLat ( ) , getOriginLon ( ) , getParallelOne ( ) , getParallelTwo ( ) , getFalseEasting ( ) , getFalseNorthing ( ) , earth_radius ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }


Input:
Precalculate some stuff [CODESPLIT] private void precalculate ( ) { if ( Math . abs ( lat0 ) > PI_OVER_2 ) { throw new IllegalArgumentException ( "LambertConformal lat0 outside range (-90,90)" ) ; } if ( Math . abs ( par1 ) >= 90.0 ) { throw new IllegalArgumentException ( "LambertConformal abs(par1) >= 90" ) ; } if ( Math . abs ( par2 ) >= 90.0 ) { throw new IllegalArgumentException ( "LambertConformal abs(par2) >= 90" ) ; } if ( Math . abs ( par1 - 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( "LambertConformal par1 = 90" ) ; } if ( Math . abs ( par1 + 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( "LambertConformal par1 = -90" ) ; } if ( Math . abs ( par2 - 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( "LambertConformal par2 = 90" ) ; } if ( Math . abs ( par2 + 90.0 ) < TOLERANCE ) { throw new IllegalArgumentException ( "LambertConformal par2 = -90" ) ; } double par1r = Math . toRadians ( this . par1 ) ; double par2r = Math . toRadians ( this . par2 ) ; double t1 = Math . tan ( Math . PI / 4 + par1r / 2 ) ; double t2 = Math . tan ( Math . PI / 4 + par2r / 2 ) ; if ( Math . abs ( par2 - par1 ) < TOLERANCE ) { // single parallel
 n = Math . sin ( par1r ) ; } else { n = Math . log ( Math . cos ( par1r ) / Math . cos ( par2r ) ) / Math . log ( t2 / t1 ) ; } double t1n = Math . pow ( t1 , n ) ; F = Math . cos ( par1r ) * t1n / n ; earthRadiusTimesF = earth_radius * F ; double t0n = Math . pow ( Math . tan ( Math . PI / 4 + lat0 / 2 ) , n ) ; rho = earthRadiusTimesF / t0n ; lon0Degrees = Math . toDegrees ( lon0 ) ; // need to know the pole value for crossSeam
 //Point2D pt = latLonToProj( 90.0, 0.0);
 //maxY = pt.getY();
 //System.out.println("LC = " +pt);
 }


Input:
Create a WKS string [CODESPLIT] public String toWKS ( ) { StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( "PROJCS[\"" ) . append ( getName ( ) ) . append ( "\"," ) ; if ( true ) { sbuff . append ( "GEOGCS[\"Normal Sphere (r=6371007)\"," ) ; sbuff . append ( "DATUM[\"unknown\"," ) ; sbuff . append ( "SPHEROID[\"sphere\",6371007,0]]," ) ; } else { sbuff . append ( "GEOGCS[\"WGS 84\"," ) ; sbuff . append ( "DATUM[\"WGS_1984\"," ) ; sbuff . append ( "SPHEROID[\"WGS 84\",6378137,298.257223563]," ) ; sbuff . append ( "TOWGS84[0,0,0,0,0,0,0]]," ) ; } sbuff . append ( "PRIMEM[\"Greenwich\",0]," ) ; sbuff . append ( "UNIT[\"degree\",0.0174532925199433]]," ) ; sbuff . append ( "PROJECTION[\"Lambert_Conformal_Conic_1SP\"]," ) ; sbuff . append ( "PARAMETER[\"latitude_of_origin\"," ) . append ( getOriginLat ( ) ) . append ( "]," ) ; // LOOK assumes getOriginLat = getParellel
 sbuff . append ( "PARAMETER[\"central_meridian\"," ) . append ( getOriginLon ( ) ) . append ( "]," ) ; sbuff . append ( "PARAMETER[\"scale_factor\",1]," ) ; sbuff . append ( "PARAMETER[\"false_easting\"," ) . append ( falseEasting ) . append ( "]," ) ; sbuff . append ( "PARAMETER[\"false_northing\"," ) . append ( falseNorthing ) . append ( "]," ) ; return sbuff . toString ( ) ; }


Input: Get the scale at the given lat . [CODESPLIT] public double getScale ( double lat ) { lat = Math . toRadians ( lat ) ; double t = Math . tan ( Math . PI / 4 + lat / 2 ) ; double tn = Math . pow ( t , n ) ; double r1 = n * F ; double r2 = Math . cos ( lat ) * tn ; return r1 / r2 ; }


Input: Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; double dlon = LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ; double theta = n * Math . toRadians ( dlon ) ; double tn = Math . pow ( Math . tan ( PI_OVER_4 + fromLat / 2 ) , n ) ; double r = earthRadiusTimesF / tn ; toX = r * Math . sin ( theta ) ; toY = rho - r * Math . cos ( theta ) ; result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }


Input: Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double rhop = rho ; if ( n < 0 ) { rhop *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = ( rhop - fromY ) ; double theta = Math . atan2 ( fromX , yd ) ; double r = Math . sqrt ( fromX * fromX + yd * yd ) ; if ( n < 0.0 ) { r *= - 1.0 ; } toLon = ( Math . toDegrees ( theta / n + lon0 ) ) ; if ( Math . abs ( r ) < TOLERANCE ) { toLat = ( ( n < 0.0 ) ? - 90.0 : 90.0 ) ; } else { double rn = Math . pow ( earth_radius * F / r , 1 / n ) ; toLat = Math . toDegrees ( 2.0 * Math . atan ( rn ) - Math . PI / 2 ) ; } result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double dlon = LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ; double theta = n * Math . toRadians ( dlon ) ; double tn = Math . pow ( Math . tan ( PI_OVER_4 + fromLat / 2 ) , n ) ; double r = earthRadiusTimesF / tn ; toX = r * Math . sin ( theta ) ; toY = rho - r * Math . cos ( theta ) ; resultXA [ i ] = ( float ) ( toX + falseEasting ) ; resultYA [ i ] = ( float ) ( toY + falseNorthing ) ; } return to ; }


Input: Convert projection coordinates to lat / lon coordinate . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] - falseEasting ; double fromY = fromYA [ i ] - falseNorthing ; double rhop = rho ; if ( n < 0 ) { rhop *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = ( rhop - fromY ) ; double theta = Math . atan2 ( fromX , yd ) ; double r = Math . sqrt ( fromX * fromX + yd * yd ) ; if ( n < 0.0 ) { r *= - 1.0 ; } toLon = ( Math . toDegrees ( theta / n + lon0 ) ) ; if ( Math . abs ( r ) < TOLERANCE ) { toLat = ( ( n < 0.0 ) ? - 90.0 : 90.0 ) ; } else { double rn = Math . pow ( earth_radius * F / r , 1 / n ) ; toLat = Math . toDegrees ( 2.0 * Math . atan ( rn ) - Math . PI / 2 ) ; } toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }


Input: Escape selected characters in a string using XML entities [CODESPLIT] static public String entityEscape ( String s , String wrt ) { if ( wrt == null ) wrt = ENTITYESCAPES ; StringBuilder escaped = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; int index = wrt . indexOf ( c ) ; if ( index < 0 ) escaped . append ( c ) ; else switch ( c ) { case ' ' : escaped . append ( ' ' + ENTITY_AMP + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_LT + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_GT + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_QUOT + ' ' ) ; break ; case ' ' : escaped . append ( ' ' + ENTITY_APOS + ' ' ) ; break ; case ' ' : case ' ' : case ' ' : escaped . append ( c ) ; // These are the only legal control chars break ; case ' ' : // What to do about nul? currrently we suppress it break ; default : if ( c >= ' ' ) escaped . append ( c ) ; break ; } } return escaped . toString ( ) ; }


Input: Escape control chars plus selected other characters in a string using backslash The definitive list is in netcdf - c / ncgen / ncgen . l . [CODESPLIT] static public String backslashEscape ( String s , String wrt ) { if ( wrt == null ) wrt = BACKSLASHESCAPE ; StringBuilder escaped = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c < ' ' || c == 127 ) { escaped . append ( ' ' ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : escaped . append ( ' ' ) ; escaped . append ( Escape . toHex ( ( int ) c ) ) ; continue ; /* since this is a string */ } } else if ( c == ' ' || wrt . indexOf ( c ) >= 0 ) escaped . append ( ' ' ) ; escaped . append ( c ) ; } return escaped . toString ( ) ; }


Input: Remove backslashed characters in a string [CODESPLIT] static public String backslashUnescape ( String s ) { StringBuilder clear = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; ) { char c = s . charAt ( i ++ ) ; if ( c == ' ' ) { c = s . charAt ( i ++ ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : break ; } clear . append ( c ) ; } else clear . append ( c ) ; } return clear . toString ( ) ; }


Input: Split a string with respect to a separator character and taking backslashes into consideration . [CODESPLIT] static public List < String > backslashsplit ( String s , char sep ) { List < String > path = new ArrayList < String > ( ) ; int len = s . length ( ) ; StringBuilder piece = new StringBuilder ( ) ; int i = 0 ; for ( ; i <= len - 1 ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' && i < ( len - 1 ) ) { piece . append ( c ) ; // keep escapes in place piece . append ( s . charAt ( ++ i ) ) ; } else if ( c == sep ) { path . add ( piece . toString ( ) ) ; piece . setLength ( 0 ) ; } else piece . append ( c ) ; } path . add ( piece . toString ( ) ) ; return path ; }


Input: Clean up a string : currently means : 1 . strip off everything after the first nul character [CODESPLIT] static public String cleanString ( String s ) { int index = s . indexOf ( ( char ) 0 ) ; if ( index >= 0 ) s = s . substring ( 0 , index ) ; return s ; }


Input: ////////////////////////////////////////////////////////////////// [CODESPLIT] @ RequestMapping ( value = "/**" , method = RequestMethod . GET , params = "req=featureType" ) public ResponseEntity < String > handleFeatureTypeRequest ( HttpServletRequest request , HttpServletResponse response ) throws IOException { if ( ! allowedServices . isAllowed ( StandardService . cdmrFeatureGrid ) ) throw new ServiceNotAllowed ( StandardService . cdmrFeatureGrid . toString ( ) ) ; String datasetPath = TdsPathUtils . extractPath ( request , StandardService . cdmrFeatureGrid . getBase ( ) ) ; try ( CoverageCollection cc = TdsRequestedDataset . getCoverageCollection ( request , response , datasetPath ) ) { if ( cc == null ) return null ; // return new ResponseEntity<>("", HttpStatus.NOT_FOUND); HttpHeaders responseHeaders = new HttpHeaders ( ) ; responseHeaders . set ( ContentType . HEADER , ContentType . text . getContentHeader ( ) ) ; return new ResponseEntity <> ( cc . getCoverageType ( ) . toString ( ) , responseHeaders , HttpStatus . OK ) ; } }


Input: Factory method [CODESPLIT] public static Fmrc open ( String collection , Formatter errlog ) throws IOException { if ( collection . startsWith ( MFileCollectionManager . CATALOG ) ) { CollectionManagerCatalog manager = new CollectionManagerCatalog ( collection , collection , null , errlog ) ; return new Fmrc ( manager , new FeatureCollectionConfig ( ) ) ; } else if ( collection . endsWith ( ".ncml" ) ) { NcmlCollectionReader ncmlCollection = NcmlCollectionReader . open ( collection , errlog ) ; if ( ncmlCollection == null ) return null ; Fmrc fmrc = new Fmrc ( ncmlCollection . getCollectionManager ( ) , new FeatureCollectionConfig ( ) ) ; fmrc . setNcml ( ncmlCollection . getNcmlOuter ( ) , ncmlCollection . getNcmlInner ( ) ) ; return fmrc ; } return new Fmrc ( collection , errlog ) ; }


Input:
scan has been done create FmrcInv [CODESPLIT] private FmrcInv makeFmrcInv ( Formatter debug ) throws IOException { try { Map < CalendarDate , FmrInv > fmrMap = new HashMap <> ( ) ; // all files are grouped by run date in an FmrInv
 List < FmrInv > fmrList = new ArrayList <> ( ) ; // an fmrc is a collection of fmr
 // get the inventory, sorted by path
 for ( MFile f : manager . getFilesSorted ( ) ) { Map < String , String > filesRunDateMap = ( ( MFileCollectionManager ) manager ) . getFilesRunDateMap ( ) ; CalendarDate runDate ; if ( ! filesRunDateMap . isEmpty ( ) ) { // run time has been defined in NcML FMRC agg by the coord attribute,
 // so explicitly set it in the dataset using the _Coordinate.ModelBaseDate
 // global attribute, otherwise the run time offsets might be incorrectly
 // computed if the incorrect run date is found in GridDatasetInv.java (line
 // 177 with comment // Look: not really right )
 runDate = CalendarDate . parseISOformat ( null , filesRunDateMap . get ( f . getPath ( ) ) ) ; Element element = new Element ( "netcdf" , ncNSHttps ) ; Element runDateAttr = ncmlWriter . makeAttributeElement ( new Attribute ( _Coordinate . ModelRunDate , runDate . toString ( ) ) ) ; config . innerNcml = element . addContent ( runDateAttr ) ; } GridDatasetInv inv ; try { inv = GridDatasetInv . open ( manager , f , config . innerNcml ) ; // inventory is discovered for each GDS
 } catch ( IOException ioe ) { logger . warn ( "Error opening " + f . getPath ( ) + "(skipped)" , ioe ) ; continue ; // skip
 } runDate = inv . getRunDate ( ) ; if ( debug != null ) debug . format ( "  opened %s rundate = %s%n" , f . getPath ( ) , inv . getRunDateString ( ) ) ; // add to fmr for that rundate
 FmrInv fmr = fmrMap . get ( runDate ) ; if ( fmr == null ) { fmr = new FmrInv ( runDate ) ; fmrMap . put ( runDate , fmr ) ; fmrList . add ( fmr ) ; } fmr . addDataset ( inv , debug ) ; } if ( debug != null ) debug . format ( "%n" ) ; // finish the FmrInv
 Collections . sort ( fmrList ) ; for ( FmrInv fmr : fmrList ) { fmr . finish ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Fmrc:" + config . name + ": made fmr with rundate=" + fmr . getRunDate ( ) + " nfiles= " + fmr . getFiles ( ) . size ( ) ) ; } return new FmrcInv ( "fmrc:" + manager . getCollectionName ( ) , fmrList , config . fmrcConfig . regularize ) ; } catch ( Throwable t ) { logger . error ( "makeFmrcInv" , t ) ; throw new RuntimeException ( t ) ; } }


Input: the ones that dont start with thredds [CODESPLIT] static public String getServiceSpecial ( String path ) { String ss = null ; if ( path . startsWith ( "/dqcServlet" ) ) ss = "dqcServlet" ; else if ( path . startsWith ( "/cdmvalidator" ) ) ss = "cdmvalidator" ; return ss ; }


Input: This implementation requires the path to be relative to the root directory and a descendant of the root directory . It also requires the relative path at each path segment to be a descendant of the root directory i . e . it cannot start with .. / or contain .. / path segments such that once normalized it would start with .. / ( e . g . dir1 / .. / .. / dir2 once normalized would be .. / dir2 ) . [CODESPLIT] public File getFile ( String path ) { if ( path == null ) return null ; String workPath = StringUtils . cleanPath ( path ) ; if ( workPath . startsWith ( "../" ) ) return null ; if ( new File ( workPath ) . isAbsolute ( ) ) return null ; File file = new File ( this . rootDirectory , workPath ) ; if ( file . exists ( ) ) return file ; else return null ; }


Input:
Returns the number of variables contained in this object . For simple and vector type variables it always returns 1 . To count the number of simple - type variable in the variable tree rooted at this variable set <code > leaves< / code > to <code > true< / code > . [CODESPLIT] public int elementCount ( boolean leaves ) { if ( ! leaves ) return mapVars . size ( ) + 1 ; // Number of Maps plus 1 Array component
 else { int count = 0 ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; count += bt . elementCount ( leaves ) ; } count += arrayVar . elementCount ( leaves ) ; return count ; } }


Input: Adds a variable to the container . [CODESPLIT] public void addVariable ( BaseType v , int part ) { if ( ! ( v instanceof DArray ) ) throw new IllegalArgumentException ( "Grid `" + getEncodedName ( ) + "'s' member `" + arrayVar . getEncodedName ( ) + "' must be an array" ) ; v . setParent ( this ) ; switch ( part ) { case ARRAY : arrayVar = ( DArray ) v ; return ; case MAPS : mapVars . addElement ( v ) ; return ; default : throw new IllegalArgumentException ( "addVariable(): Unknown Grid part" ) ; } }


Input: Gets the indexed variable . For a DGrid the index 0 returns the <code > DArray< / code > and indexes 1 and higher return the associated map <code > Vector< / code > s . [CODESPLIT] public BaseType getVar ( int index ) throws NoSuchVariableException { if ( index == 0 ) { return ( arrayVar ) ; } else { int i = index - 1 ; if ( i < mapVars . size ( ) ) return ( ( BaseType ) mapVars . elementAt ( i ) ) ; else throw new NoSuchVariableException ( "DGrid.getVariable() No Such variable: " + index + " - 1" ) ; } }


Input:
Checks for internal consistency . For <code > DGrid< / code > verify that the map variables have unique names and match the number of dimensions of the array variable . [CODESPLIT] public void checkSemantics ( boolean all ) throws BadSemanticsException { super . checkSemantics ( all ) ; Util . uniqueNames ( mapVars , getEncodedName ( ) , getTypeName ( ) ) ; if ( arrayVar == null ) throw new BadSemanticsException ( "DGrid.checkSemantics(): Null grid base array in `" + getEncodedName ( ) + "'" ) ; // check semantics of array variable
 arrayVar . checkSemantics ( all ) ; // enough maps?
 if ( mapVars . size ( ) != arrayVar . numDimensions ( ) ) throw new BadSemanticsException ( "DGrid.checkSemantics(): The number of map variables for grid `" + getEncodedName ( ) + "' does not match the number of dimensions of `" + arrayVar . getEncodedName ( ) + "'" ) ; //----- I added this next test 12/3/99. As soon as I did I questioned whether or not
 //----- it adds any value. ie: Can it ever happen that this test fails? I don't think
 //----- so now that I have written it...  ndp 12/3/99
 // Is the size of the maps equal to the size of the cooresponding dimensions?
 Enumeration emap = mapVars . elements ( ) ; Enumeration edims = arrayVar . getDimensions ( ) ; int dim = 0 ; while ( emap . hasMoreElements ( ) && edims . hasMoreElements ( ) ) { DArray thisMapArray = ( DArray ) emap . nextElement ( ) ; Enumeration ema = thisMapArray . getDimensions ( ) ; DArrayDimension thisMapDim = ( DArrayDimension ) ema . nextElement ( ) ; DArrayDimension thisArrayDim = ( DArrayDimension ) edims . nextElement ( ) ; if ( thisMapDim . getSize ( ) != thisArrayDim . getSize ( ) ) { throw new BadSemanticsException ( "In grid '" + getEncodedName ( ) + " The size of dimension " + dim + " in the array component '" + arrayVar . getEncodedName ( ) + "is not equal to the size of the coresponding map vector '" + thisMapArray . getEncodedName ( ) + "." ) ; } dim ++ ; } //----- end  ndp 12/3/99
 }


Input: Coverity [ CALL_SUPER ] [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { os . println ( space + getTypeName ( ) + " {" ) ; os . println ( space + " ARRAY:" ) ; arrayVar . printDecl ( os , space + "    " , true ) ; os . println ( space + " MAPS:" ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printDecl ( os , space + "    " , true ) ; } os . print ( space + "} " + getEncodedName ( ) ) ; if ( print_semi ) os . println ( ";" ) ; }


Input: Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { arrayVar . externalize ( sink ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . externalize ( sink ) ; } }


Input: How many prohected components of this Grid object? [CODESPLIT] public int projectedComponents ( boolean constrained ) { int comp ; if ( constrained ) { comp = ( ( DArray ) arrayVar ) . isProject ( ) ? 1 : 0 ; Enumeration e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { if ( ( ( DArray ) e . nextElement ( ) ) . isProject ( ) ) comp ++ ; } } else { comp = 1 + mapVars . size ( ) ; } return comp ; }


Input:
When projected ( using whatever the current constraint provides in the way of a projection ) am I still a Grid? [CODESPLIT] public boolean projectionYieldsGrid ( boolean constrained ) { if ( ! constrained ) return true ; // For each dimension in the Array part, check the corresponding Map
 // vector to make sure it is present in the projected Grid. If for each
 // projected dimension in the Array component, there is a matching Map
 // vector, then the Grid is valid.
 boolean valid = true ; // Don't bother checking if the Array component is not included.
 if ( ! ( ( SDArray ) arrayVar ) . isProject ( ) ) return false ; int nadims = arrayVar . numDimensions ( ) ; int nmaps = getVarCount ( ) - 1 ; //Enumeration aDims = arrayVar.getDimensions();
 //Enumeration e = mapVars.elements();
 //while (valid && e.hasMoreElements() && aDims.hasMoreElements()) {
 if ( nadims != nmaps ) valid = false ; else for ( int d = 0 ; d < nadims ; d ++ ) { try { DArrayDimension thisDim = arrayVar . getDimension ( d ) ; //(DArrayDimension) aDims.nextElement();
 SDArray mapArray = ( SDArray ) getVar ( d + 1 ) ; //e.nextElement();
 DArrayDimension mapDim = mapArray . getFirstDimension ( ) ; if ( thisDim . getSize ( ) > 0 ) { // LogStream.out.println("Dimension Contains Data.");
 if ( mapArray . isProject ( ) ) { // This map vector better be projected!
 // LogStream.out.println("Map Vector Projected, checking projection image...");
 // Check the matching Map vector; the Map projection must equal
 // the Array dimension projection
 // wrong: valid at this point might have been false: valid = true;
 valid = valid && mapDim . getStart ( ) == thisDim . getStart ( ) ; valid = valid && mapDim . getStop ( ) == thisDim . getStop ( ) ; valid = valid && mapDim . getStride ( ) == thisDim . getStride ( ) ; } else { // LogStream.out.println("Map Vector not Projected.");
 valid = false ; } } else { // LogStream.out.println("Dimension empty. Verifying corresponding Map vector not projected...");
 // Corresponding Map vector must be excluded from the
 // projection or it's not a grid.
 valid = ! mapArray . isProject ( ) ; } } catch ( Exception e ) { Util . check ( e ) ; valid = false ; break ; } } //if (e.hasMoreElements() != aDims.hasMoreElements()) valid = false;
 return valid ; }


Input: Returns a clone of this <code > DGrid< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DGrid g = ( DGrid ) super . cloneDAG ( map ) ; g . arrayVar = ( DArray ) cloneDAG ( map , arrayVar ) ; g . mapVars = new Vector ( ) ; for ( int i = 0 ; i < mapVars . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) mapVars . elementAt ( i ) ; BaseType btclone = ( BaseType ) cloneDAG ( map , bt ) ; g . mapVars . addElement ( btclone ) ; } return g ; }


Input:
Make the level values from the specifications [CODESPLIT] protected double [ ] makeLevelValues ( ) { if ( levels == null ) { return null ; } if ( levels . size ( ) != size ) { // do someting
 } double [ ] vals = new double [ size ] ; if ( mapping . equalsIgnoreCase ( LEVELS ) ) { for ( int i = 0 ; i < vals . length ; i ++ ) { vals [ i ] = Double . parseDouble ( levels . get ( i ) ) ; } } else if ( mapping . equalsIgnoreCase ( LINEAR ) ) { double start = 0 ; double inc = 0 ; start = Double . parseDouble ( levels . get ( 0 ) ) ; inc = Double . parseDouble ( levels . get ( 1 ) ) ; for ( int i = 0 ; i < size ; i ++ ) { vals [ i ] = start + i * inc ; } // TODO: figure out a better way to do this in case they don't start with gaus (e.g. MOM32)
 } else if ( mapping . toLowerCase ( ) . startsWith ( "gaus" ) ) { vals = GradsUtil . getGaussianLatitudes ( mapping , ( int ) Double . parseDouble ( levels . get ( 0 ) ) , size ) ; } // sanity check on z units
 if ( name . equals ( GradsDataDescriptorFile . ZDEF ) ) { for ( int i = 0 ; i < vals . length ; i ++ ) { double val = vals [ i ] ; if ( val > 1050 ) { unitName = "Pa" ; break ; } else if ( val < 10 ) { // sometimes it's just a level number
 // probably should be something else, but dimensionless
 unitName = "" ; break ; } } } return vals ; }


Input: Parser primary actions [CODESPLIT] @ Override CEAST constraint ( CEAST . NodeList clauses ) throws ParseException { CEAST node = new CEAST ( CEAST . Sort . CONSTRAINT ) ; node . clauses = clauses ; node . dimdefs = dimdefs ; // save for constructing the DMR this . constraint = node ; return node ; }


Input: Selection actions [CODESPLIT] @ Override CEAST selection ( CEAST projection , CEAST filter ) throws ParseException { CEAST node = new CEAST ( CEAST . Sort . SELECTION ) ; node . projection = projection ; node . filter = filter ; return node ; }


Input: Parser list support [CODESPLIT] @ Override CEAST . NodeList nodelist ( CEAST . NodeList list , CEAST ast ) { if ( list == null ) list = new CEAST . NodeList ( ) ; if ( ast != null ) list . add ( ast ) ; return list ; }


Input: return record header time as a CalendarDate [CODESPLIT] public final CalendarDate getReferenceTime ( ) { int sec = ( second < 0 || second > 59 ) ? 0 : second ; return CalendarDate . of ( null , year , month , day , hour , minute , sec ) ; }


Input: Make a section of an ArrayStructureBB [CODESPLIT] static public ArrayStructureBB factory ( ArrayStructureBB org , Section section ) { if ( section == null || section . computeSize ( ) == org . getSize ( ) ) return org ; return new ArrayStructureBBsection ( org . getStructureMembers ( ) , org . getShape ( ) , org . getByteBuffer ( ) , section ) ; }


Input: Makes a document for a File . <p / > The document has three fields : <ul > <li > <code > path< / code > -- containing the pathname of the file as a stored untokenized field ; <li > <code > modified< / code > -- containing the last modified date of the file as a field as created by <a href = lucene . document . DateTools . html > DateTools< / a > ; and <li > <code > contents< / code > -- containing the full contents of the file as a Reader field ; [CODESPLIT] public Document makeDocument ( File f ) throws java . io . FileNotFoundException { // make a new, empty document Document doc = new Document ( ) ; // Add the path of the file as a field named "path".  Use a field that is // indexed (i.e. searchable), but don't tokenize the field into words. doc . add ( new Field ( "path" , f . getPath ( ) , Field . Store . YES , Field . Index . UN_TOKENIZED ) ) ; // Add the last modified date of the file a field named "modified".  Use // a field that is indexed (i.e. searchable), but don't tokenize the field // into words. doc . add ( new Field ( "modified" , DateTools . timeToString ( f . lastModified ( ) , DateTools . Resolution . MINUTE ) , Field . Store . YES , Field . Index . UN_TOKENIZED ) ) ; // Add the contents of the file to a field named "contents".  Specify a Reader, // so that the text of the file is tokenized and indexed, but not stored. // Note that FileReader expects the file to be in the system's default encoding. // If that's not the case searching for special characters will fail. // doc.add(new Field("contents", new FileReader(f))); // return the document return doc ; }


Input: Index all text files under a directory . [CODESPLIT] public static void main1 ( String [ ] args ) { if ( INDEX_DIR . exists ( ) ) { System . out . println ( "Cannot save index to '" + INDEX_DIR + "' directory, please delete it first" ) ; System . exit ( 1 ) ; } LuceneIndexer indexer = new LuceneIndexer ( ) ; Date start = new Date ( ) ; try { IndexWriter writer = new IndexWriter ( INDEX_DIR , new StandardAnalyzer ( ) , true ) ; System . out . println ( "Indexing to directory '" + INDEX_DIR + "'..." ) ; indexer . indexDocs ( writer , DOC_DIR ) ; System . out . println ( "Optimizing..." ) ; writer . optimize ( ) ; writer . close ( ) ; Date end = new Date ( ) ; System . out . println ( end . getTime ( ) - start . getTime ( ) + " total milliseconds" ) ; } catch ( IOException e ) { System . out . println ( " caught a " + e . getClass ( ) + "\n with message: " + e . getMessage ( ) ) ; } }