Input: see http : // www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2_doc . shtml [CODESPLIT] private Map < String , String > initCodes ( ) { codeMap . put ( "3.1.204" , "Curvilinear_Orthogonal" ) ; codeMap . put ( "4.3.192" , "Forecast Confidence Indicator" ) ; codeMap . put ( "4.3.193" , "Bias Corrected Ensemble Forecast" ) ; codeMap . put ( "4.5.200" , "Entire atmosphere layer" ) ; codeMap . put ( "4.5.201" , "Entire ocean layer" ) ; codeMap . put ( "4.5.204" , "Highest tropospheric freezing level" ) ; codeMap . put ( "4.5.206" , "Grid scale cloud bottom level" ) ; codeMap . put ( "4.5.207" , "Grid scale cloud top level" ) ; codeMap . put ( "4.5.209" , "Boundary layer cloud bottom level" ) ; codeMap . put ( "4.5.210" , "Boundary layer cloud top level" ) ; codeMap . put ( "4.5.211" , "Boundary layer cloud layer" ) ; codeMap . put ( "4.5.212" , "Low cloud bottom level" ) ; codeMap . put ( "4.5.213" , "Low cloud top level" ) ; codeMap . put ( "4.5.214" , "Low cloud layer" ) ; codeMap . put ( "4.5.215" , "Cloud ceiling" ) ; codeMap . put ( "4.5.220" , "Planetary Boundary Layer" ) ; codeMap . put ( "4.5.221" , "Layer Between Two Hybrid Levels" ) ; codeMap . put ( "4.5.222" , "Middle cloud bottom level" ) ; codeMap . put ( "4.5.223" , "Middle cloud top level" ) ; codeMap . put ( "4.5.224" , "Middle cloud layer" ) ; codeMap . put ( "4.5.232" , "High cloud bottom level" ) ; codeMap . put ( "4.5.233" , "High cloud top level" ) ; codeMap . put ( "4.5.234" , "High cloud layer" ) ; codeMap . put ( "4.5.235" , "Ocean isotherm level" ) ; codeMap . put ( "4.5.236" , "Layer between two depths below ocean surface" ) ; codeMap . put ( "4.5.237" , "Bottom of ocean mixed layer" ) ; codeMap . put ( "4.5.238" , "Bottom of ocean isothermal layer" ) ; codeMap . put ( "4.5.239" , "Layer Ocean Surface and 26C Ocean Isothermal Level" ) ; codeMap . put ( "4.5.240" , "Ocean Mixed Layer" ) ; codeMap . put ( "4.5.241" , "Ordered Sequence of Data" ) ; codeMap . put ( "4.5.242" , "Convective cloud bottom level" ) ; codeMap . put ( "4.5.243" , "Convective cloud top level" ) ; codeMap . put ( "4.5.244" , "Convective cloud layer" ) ; codeMap . put ( "4.5.245" , "Lowest level of the wet bulb zero" ) ; codeMap . put ( "4.5.246" , "Maximum equivalent potential temperature level" ) ; codeMap . put ( "4.5.247" , "Equilibrium level" ) ; codeMap . put ( "4.5.248" , "Shallow convective cloud bottom level" ) ; codeMap . put ( "4.5.249" , "Shallow convective cloud top level" ) ; codeMap . put ( "4.5.251" , "Deep convective cloud bottom level" ) ; codeMap . put ( "4.5.252" , "Deep convective cloud top level" ) ; codeMap . put ( "4.5.253" , "Lowest bottom level of supercooled liquid water layer" ) ; codeMap . put ( "4.5.254" , "Highest top level of supercooled liquid water layer" ) ; codeMap . put ( "4.6.192" , "Perturbed Ensemble Member" ) ; codeMap . put ( "4.7.192" , "Unweighted Mode of All Members" ) ; codeMap . put ( "4.7.193" , "Percentile value (10%) of All Members" ) ; codeMap . put ( "4.7.194" , "Percentile value (50%) of All Members" ) ; codeMap . put ( "4.7.195" , "Percentile value (90%) of All Members" ) ; codeMap . put ( "4.10.192" , "Climatological Mean Value" ) ; codeMap . put ( "4.10.193" , "Average of N forecasts" ) ; codeMap . put ( "4.10.194" , "Average of N uninitialized analyses" ) ; codeMap . put ( "4.10.195" , "Average of forecast accumulations" ) ; codeMap . put ( "4.10.196" , "Average of successive forecast accumulations" ) ; codeMap . put ( "4.10.197" , "Average of forecast averages" ) ; codeMap . put ( "4.10.198" , "Average of successive forecast averages" ) ; codeMap . put ( "4.10.199" , "Climatological Average of N analyses, each a year apart" ) ; codeMap . put ( "4.10.200" , "Climatological Average of N forecasts, each a year apart" ) ; codeMap . put ( "4.10.201" , "Climatological Root Mean Square difference between N forecasts and their verifying analyses, each a year apart" ) ; codeMap . put ( "4.10.202" , "Climatological Standard Deviation of N forecasts from the mean of the same N forecasts, for forecasts one year apart" ) ; codeMap . put ( "4.10.203" , "Climatological Standard Deviation of N analyses from the mean of the same N analyses, for analyses one year apart" ) ; codeMap . put ( "4.10.204" , "Average of forecast accumulations" ) ; codeMap . put ( "4.10.205" , "Average of forecast averages" ) ; codeMap . put ( "4.10.206" , "Average of forecast accumulations" ) ; codeMap . put ( "4.10.207" , "Average of forecast averages" ) ; return codeMap ; }


Input: Need a few test cases : 1 ) Anne s TDR case - catalog a collection of TDS served data . 2 ) Catalog a collection of local data files . 3 ) [CODESPLIT] public static void main1 ( String [ ] args ) { // Test case 2: local data files. String collectionPath = "C:/Ethan/data/mlode" ; String startPath = "grid/NCEP" ; String catWriteDirPath = "C:/Ethan/data/tmpTest" ; if ( args . length == 3 ) { collectionPath = args [ 0 ] ; startPath = args [ 1 ] ; catWriteDirPath = args [ 2 ] ; } File catWriteDir = new File ( catWriteDirPath ) ; File collectionFile = new File ( collectionPath ) ; CrawlableDataset collectionCrDs = new CrawlableDatasetFile ( collectionFile ) ; InvService service = new InvService ( "myServer" , "File" , collectionCrDs . getPath ( ) + "/" , null , null ) ; CrawlableDatasetFilter filter = null ; CrawlableDataset topCatCrDs = collectionCrDs . getDescendant ( startPath ) ; CatGenAndWrite cgaw = new CatGenAndWrite ( "DATA" , "My data" , "" , service , collectionCrDs , topCatCrDs , filter , null , catWriteDir ) ; try { cgaw . genCatAndSubCats ( topCatCrDs ) ; } catch ( IOException e ) { log . error ( "I/O error generating and writing catalogs at and under \"" + topCatCrDs . getPath ( ) + "\": " + e . getMessage ( ) ) ; return ; } }


Input: Factory method for constructing a base unit . [CODESPLIT] private static BaseUnit bu ( final String name , final String symbol , final BaseQuantity quantity ) throws NameException , UnitExistsException { return BaseUnit . getOrCreate ( UnitName . newUnitName ( name , null , symbol ) , quantity ) ; }


Input: Factory method for constructing a derived unit . [CODESPLIT] private static Unit du ( final String name , final String symbol , final Unit definition ) throws NameException { return definition . clone ( UnitName . newUnitName ( name , null , symbol ) ) ; }


Input: Returns the base unit database of the SI . [CODESPLIT] private static UnitDBImpl baseUnitDB ( ) throws NameException , UnitExistsException , NoSuchUnitException { final UnitDBImpl db = new UnitDBImpl ( 9 , 9 ) ; db . addUnit ( AMPERE ) ; db . addUnit ( CANDELA ) ; db . addUnit ( KELVIN ) ; db . addUnit ( KILOGRAM ) ; db . addUnit ( METER ) ; db . addUnit ( MOLE ) ; db . addUnit ( SECOND ) ; db . addUnit ( RADIAN ) ; db . addUnit ( STERADIAN ) ; db . addAlias ( "metre" , "meter" ) ; return db ; }


Input: Returns the derived unit database of the SI . [CODESPLIT] private static UnitDBImpl derivedUnitDB ( ) throws NameException , UnitExistsException , NoSuchUnitException { final UnitDBImpl db = new UnitDBImpl ( 42 , 43 ) ; db . addUnit ( HERTZ ) ; db . addUnit ( NEWTON ) ; db . addUnit ( PASCAL ) ; db . addUnit ( JOULE ) ; db . addUnit ( WATT ) ; db . addUnit ( COULOMB ) ; db . addUnit ( VOLT ) ; db . addUnit ( FARAD ) ; db . addUnit ( OHM ) ; db . addUnit ( SIEMENS ) ; db . addUnit ( WEBER ) ; db . addUnit ( TESLA ) ; db . addUnit ( HENRY ) ; db . addUnit ( DEGREE_CELSIUS ) ; db . addUnit ( LUMEN ) ; db . addUnit ( LUX ) ; db . addUnit ( BECQUEREL ) ; db . addUnit ( GRAY ) ; db . addUnit ( SIEVERT ) ; db . addUnit ( MINUTE ) ; db . addUnit ( HOUR ) ; db . addUnit ( DAY ) ; db . addUnit ( ARC_DEGREE ) ; db . addUnit ( ARC_MINUTE ) ; db . addUnit ( ARC_SECOND ) ; db . addUnit ( LITER ) ; db . addUnit ( METRIC_TON ) ; db . addUnit ( NAUTICAL_MILE ) ; db . addUnit ( KNOT ) ; db . addUnit ( ANGSTROM ) ; db . addUnit ( ARE ) ; db . addUnit ( HECTARE ) ; db . addUnit ( BARN ) ; db . addUnit ( BAR ) ; db . addUnit ( GAL ) ; db . addUnit ( CURIE ) ; db . addUnit ( ROENTGEN ) ; db . addUnit ( RAD ) ; db . addUnit ( REM ) ; db . addAlias ( "litre" , "liter" , "l" ) ; db . addAlias ( "tonne" , "metric ton" ) ; db . addSymbol ( "tne" , "tonne" ) ; return db ; }


Input: Returns an instance of the SI system of units . [CODESPLIT] public static synchronized SI instance ( ) throws UnitSystemException { if ( si == null ) { try { si = new SI ( ) ; } catch ( final UnitException e ) { throw new UnitSystemException ( "Couldn't initialize class SI" , e ) ; } } return si ; }


Input: / * [CODESPLIT] protected void update ( CollectionUpdateType force ) throws IOException { // this may be called from a background thread, or from checkState() request thread logger . debug ( "update {} force={}" , name , force ) ; boolean changed ; MFileCollectionManager dcm ; switch ( force ) { case always : case test : dcm = ( MFileCollectionManager ) getDatasetCollectionManager ( ) ; changed = dcm . scan ( false ) ; if ( changed ) super . update ( force ) ; break ; case never : return ; default : super . update ( force ) ; } }


Input: called by DataRootHandler . makeDynamicCatalog () when the catref is requested [CODESPLIT] @ Override public CatalogBuilder makeCatalog ( String match , String orgPath , URI catURI ) throws IOException { logger . debug ( "FMRC make catalog for " + match + " " + catURI ) ; State localState = checkState ( ) ; try { if ( ( match == null ) || ( match . length ( ) == 0 ) ) { return makeCatalogTop ( catURI , localState ) ; } else if ( match . equals ( RUNS ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Runs ) ) return makeCatalogRuns ( catURI , localState ) ; else if ( match . equals ( OFFSET ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantOffsets ) ) return makeCatalogOffsets ( catURI , localState ) ; else if ( match . equals ( FORECAST ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantForecasts ) ) return makeCatalogForecasts ( catURI , localState ) ; else if ( match . startsWith ( FILES ) && wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Files ) ) { return makeCatalogFiles ( catURI , localState , datasetCollection . getFilenames ( ) , true ) ; } } catch ( Exception e ) { logger . error ( "Error making catalog for " + configPath , e ) ; } return null ; }


Input: /////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override protected DatasetBuilder makeDatasetTop ( URI catURI , State localState ) { DatasetBuilder top = new DatasetBuilder ( null ) ; top . transferInheritedMetadata ( parent ) ; // make all inherited metadata local top . setName ( name ) ; top . addServiceToCatalog ( virtualService ) ; ThreddsMetadata tmi = top . getInheritableMetadata ( ) ; // LOOK allow to change ?? tmi . set ( Dataset . FeatureType , FeatureType . GRID . toString ( ) ) ; // override GRIB tmi . set ( Dataset . ServiceName , virtualService . getName ( ) ) ; if ( localState . coverage != null ) tmi . set ( Dataset . GeospatialCoverage , localState . coverage ) ; if ( localState . dateRange != null ) tmi . set ( Dataset . TimeCoverage , localState . dateRange ) ; if ( localState . vars != null ) tmi . set ( Dataset . VariableGroups , localState . vars ) ; if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . TwoD ) ) { DatasetBuilder twoD = new DatasetBuilder ( top ) ; twoD . setName ( "Forecast Model Run Collection (2D time coordinates)" ) ; String myname = name + "_" + FMRC ; myname = StringUtil2 . replace ( myname , ' ' , "_" ) ; twoD . put ( Dataset . UrlPath , this . configPath + "/" + myname ) ; twoD . put ( Dataset . Id , this . configPath + "/" + myname ) ; twoD . addToList ( Dataset . Documentation , new Documentation ( null , null , null , "summary" , "Forecast Model Run Collection (2D time coordinates)." ) ) ; top . addDataset ( twoD ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Best ) ) { DatasetBuilder best = new DatasetBuilder ( top ) ; best . setName ( "Best Time Series" ) ; String myname = name + "_" + BEST ; myname = StringUtil2 . replace ( myname , ' ' , "_" ) ; best . put ( Dataset . UrlPath , this . configPath + "/" + myname ) ; best . put ( Dataset . Id , this . configPath + "/" + myname ) ; best . addToList ( Dataset . Documentation , new Documentation ( null , null , null , "summary" , "Best time series, taking the data from the most recent run available." ) ) ; top . addDataset ( best ) ; } if ( config . fmrcConfig . getBestDatasets ( ) != null ) { for ( FeatureCollectionConfig . BestDataset bd : config . fmrcConfig . getBestDatasets ( ) ) { DatasetBuilder ds = new DatasetBuilder ( top ) ; ds . setName ( bd . name ) ; String myname = name + "_" + bd . name ; myname = StringUtil2 . replace ( myname , ' ' , "_" ) ; ds . put ( Dataset . UrlPath , this . configPath + "/" + myname ) ; ds . put ( Dataset . Id , this . configPath + "/" + myname ) ; ds . addToList ( Dataset . Documentation , new Documentation ( null , null , null , "summary" , "Best time series, excluding offset hours less than " + bd . greaterThan ) ) ; top . addDataset ( ds ) ; } } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Runs ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( RUN_TITLE ) ; ds . setHref ( getCatalogHref ( RUNS ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantForecasts ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( FORECAST_TITLE ) ; ds . setHref ( getCatalogHref ( FORECAST ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . ConstantOffsets ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( OFFSET_TITLE ) ; ds . setHref ( getCatalogHref ( OFFSET ) ) ; top . addDataset ( ds ) ; } if ( wantDatasets . contains ( FeatureCollectionConfig . FmrcDatasetType . Files ) && ( topDirectory != null ) ) { CatalogRefBuilder ds = new CatalogRefBuilder ( top ) ; ds . setTitle ( FILES ) ; ds . setHref ( getCatalogHref ( FILES ) ) ; top . addDataset ( ds ) ; } return top ; }


Input: Given a coordinate interval find what grid element matches it . [CODESPLIT] int findCoordElement ( double [ ] target , boolean bounded ) { switch ( axis . getSpacing ( ) ) { case regularInterval : // can use midpoint return findCoordElementRegular ( ( target [ 0 ] + target [ 1 ] ) / 2 , bounded ) ; case contiguousInterval : // can use midpoint return findCoordElementContiguous ( ( target [ 0 ] + target [ 1 ] ) / 2 , bounded ) ; case discontiguousInterval : // cant use midpoint return findCoordElementDiscontiguousInterval ( target , bounded ) ; } throw new IllegalStateException ( "unknown spacing" + axis . getSpacing ( ) ) ; }


Input: same contract as findCoordElement () [CODESPLIT] private int findCoordElementRegular ( double coordValue , boolean bounded ) { int n = axis . getNcoords ( ) ; if ( n == 1 && bounded ) return 0 ; double distance = coordValue - axis . getCoordEdge1 ( 0 ) ; double exactNumSteps = distance / axis . getResolution ( ) ; //int index = (int) Math.round(exactNumSteps); // ties round to +Inf int index = ( int ) exactNumSteps ; // truncate down if ( bounded && index < 0 ) return 0 ; if ( bounded && index >= n ) return n - 1 ; // check that found point is within interval if ( index >= 0 && index < n ) { double lower = axis . getCoordEdge1 ( index ) ; double upper = axis . getCoordEdge2 ( index ) ; if ( axis . isAscending ( ) ) { assert lower <= coordValue : lower + " should be le " + coordValue ; assert upper >= coordValue : upper + " should be ge " + coordValue ; } else { assert lower >= coordValue : lower + " should be ge " + coordValue ; assert upper <= coordValue : upper + " should be le " + coordValue ; } } return index ; }


Input: Performs a binary search to find the index of the element of the array whose value is contained in the contiguous intervals . irregularPoint // irregular spaced points ( values npts ) edges halfway between coords contiguousInterval // irregular contiguous spaced intervals ( values npts ) values are the edges and there are npts + 1 coord halfway between edges <p > same contract as findCoordElement () [CODESPLIT] private int findCoordElementContiguous ( double target , boolean bounded ) { int n = axis . getNcoords ( ) ; //double resolution = (values[n-1] - values[0]) / (n - 1); //int startGuess = (int) Math.round((target - values[0]) / resolution); int low = 0 ; int high = n - 1 ; if ( axis . isAscending ( ) ) { // Check that the point is within range if ( target < axis . getCoordEdge1 ( 0 ) ) return bounded ? 0 : - 1 ; else if ( target > axis . getCoordEdgeLast ( ) ) return bounded ? n - 1 : n ; // do a binary search to find the nearest index int mid ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; // binary search if ( contains ( target , mid , true ) ) return mid ; else if ( axis . getCoordEdge2 ( mid ) < target ) low = mid ; else high = mid ; } return contains ( target , low , true ) ? low : high ; } else { // descending // Check that the point is within range if ( target > axis . getCoordEdge1 ( 0 ) ) return bounded ? 0 : - 1 ; else if ( target < axis . getCoordEdgeLast ( ) ) return bounded ? n - 1 : n ; // do a binary search to find the nearest index int mid ; while ( high > low + 1 ) { mid = ( low + high ) / 2 ; // binary search if ( contains ( target , mid , false ) ) return mid ; else if ( axis . getCoordEdge2 ( mid ) < target ) high = mid ; else low = mid ; } return contains ( target , low , false ) ? low : high ; } }


Input: LOOK not using bounded [CODESPLIT] private int findCoordElementDiscontiguousInterval ( double target , boolean bounded ) { int idx = findSingleHit ( target ) ; if ( idx >= 0 ) return idx ; if ( idx == - 1 ) return - 1 ; // no hits // multiple hits = choose closest to the midpoint return findClosest ( target ) ; }


Input: LOOK not using bounded [CODESPLIT] private int findCoordElementDiscontiguousInterval ( double [ ] target , boolean bounded ) { for ( int i = 0 ; i < axis . getNcoords ( ) ; i ++ ) { double edge1 = axis . getCoordEdge1 ( i ) ; double edge2 = axis . getCoordEdge2 ( i ) ; if ( Misc . nearlyEquals ( edge1 , target [ 0 ] ) && Misc . nearlyEquals ( edge2 , target [ 1 ] ) ) return i ; } return - 1 ; }


Input: return index if only one match if no matches return - 1 if > 1 match return - nhits [CODESPLIT] private int findSingleHit ( double target ) { int hits = 0 ; int idxFound = - 1 ; int n = axis . getNcoords ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( contains ( target , i ) ) { hits ++ ; idxFound = i ; } } if ( hits == 1 ) return idxFound ; if ( hits == 0 ) return - 1 ; return - hits ; }


Input: if its a tie use the larger one [CODESPLIT] private int findClosest ( double target ) { double minDiff = Double . MAX_VALUE ; double useValue = Double . MIN_VALUE ; int idxFound = - 1 ; for ( int i = 0 ; i < axis . getNcoords ( ) ; i ++ ) { double coord = axis . getCoordMidpoint ( i ) ; double diff = Math . abs ( coord - target ) ; if ( diff < minDiff || ( diff == minDiff && coord > useValue ) ) { minDiff = diff ; idxFound = i ; useValue = coord ; } } return idxFound ; }


Input: //////////////////////////////////////////////////////////// [CODESPLIT] public Optional < CoverageCoordAxisBuilder > subset ( double minValue , double maxValue , int stride ) { return subsetValues ( minValue , maxValue , stride ) ; }


Input: look must handle discon interval different [CODESPLIT] private Optional < CoverageCoordAxisBuilder > subsetValues ( double minValue , double maxValue , int stride ) { if ( axis . getSpacing ( ) == CoverageCoordAxis . Spacing . discontiguousInterval ) return subsetValuesDiscontinuous ( minValue , maxValue , stride ) ; double lower = axis . isAscending ( ) ? Math . min ( minValue , maxValue ) : Math . max ( minValue , maxValue ) ; double upper = axis . isAscending ( ) ? Math . max ( minValue , maxValue ) : Math . min ( minValue , maxValue ) ; int minIndex = findCoordElement ( lower , false ) ; int maxIndex = findCoordElement ( upper , false ) ; if ( minIndex >= axis . getNcoords ( ) ) return Optional . empty ( String . format ( "no points in subset: lower %f > end %f" , lower , axis . getEndValue ( ) ) ) ; if ( maxIndex < 0 ) return Optional . empty ( String . format ( "no points in subset: upper %f < start %f" , upper , axis . getStartValue ( ) ) ) ; if ( minIndex < 0 ) minIndex = 0 ; if ( maxIndex >= axis . getNcoords ( ) ) maxIndex = axis . getNcoords ( ) - 1 ; int count = maxIndex - minIndex + 1 ; if ( count <= 0 ) throw new IllegalArgumentException ( "no points in subset" ) ; try { return Optional . of ( subsetByIndex ( new Range ( minIndex , maxIndex , stride ) ) ) ; } catch ( InvalidRangeException e ) { return Optional . empty ( e . getMessage ( ) ) ; } }


Input: Range must be contained in this range [CODESPLIT] @ Nonnull CoverageCoordAxisBuilder subsetByIndex ( Range range ) throws InvalidRangeException { int ncoords = range . length ( ) ; if ( range . last ( ) >= axis . getNcoords ( ) ) throw new InvalidRangeException ( "range.last() >= axis.getNcoords()" ) ; double resolution = 0.0 ; int count2 = 0 ; double [ ] values = axis . getValues ( ) ; // will be null for regular double [ ] subsetValues = null ; switch ( axis . getSpacing ( ) ) { case regularInterval : case regularPoint : resolution = range . stride ( ) * axis . getResolution ( ) ; break ; case irregularPoint : subsetValues = new double [ ncoords ] ; for ( int i : range ) subsetValues [ count2 ++ ] = values [ i ] ; break ; case contiguousInterval : subsetValues = new double [ ncoords + 1 ] ; // need npts+1 for ( int i : range ) subsetValues [ count2 ++ ] = values [ i ] ; subsetValues [ count2 ] = values [ range . last ( ) + 1 ] ; break ; case discontiguousInterval : subsetValues = new double [ 2 * ncoords ] ; // need 2*npts for ( int i : range ) { subsetValues [ count2 ++ ] = values [ 2 * i ] ; subsetValues [ count2 ++ ] = values [ 2 * i + 1 ] ; } break ; } // subset(int ncoords, double start, double end, double[] values) CoverageCoordAxisBuilder builder = new CoverageCoordAxisBuilder ( axis ) ; builder . subset ( ncoords , axis . getCoordMidpoint ( range . first ( ) ) , axis . getCoordMidpoint ( range . last ( ) ) , resolution , subsetValues ) ; builder . setRange ( range ) ; return builder ; }


Input:
/ * http : // stackoverflow . com / questions / 24660408 / how - can - i - get - intellij - debugger - to - allow - my - apps - shutdown - hooks - to - run?lq = 1 Unfortunately you can t use breakpoints in your shutdown hook body when you use Stop button : these breakpoints are silently ignored . [CODESPLIT] @ Override public void destroy ( ) { System . out . printf ( "TdsInit.destroy() is called%n" ) ; // prefs try { store . save ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; startupLog . error ( "TdsInit: Prefs save failed" , ioe ) ; } // background threads if ( cdmDiskCacheTimer != null ) cdmDiskCacheTimer . cancel ( ) ; FileCache . shutdown ( ) ; // this handles background threads for all instances of FileCache DiskCache2 . exit ( ) ; // this handles background threads for all instances of DiskCache2 thredds . inventory . bdb . MetadataManager . closeAll ( ) ; executor . shutdownNow ( ) ; /* try {
      catalogWatcher.close();
    } catch (IOException ioe) {
      ioe.printStackTrace();
      startupLog.error("catalogWatcher close failed", ioe);
    } */ // open file caches RandomAccessFile . shutdown ( ) ; NetcdfDataset . shutdown ( ) ; // memory caches GribCdmIndex . shutdown ( ) ; datasetManager . setDatasetTracker ( null ) ; // closes the existing tracker collectionUpdater . shutdown ( ) ; startupLog . info ( "TdsInit shutdown" ) ; MDC . clear ( ) ; }


Input: ///////////////////////////////////// [CODESPLIT] void writeNetcdf ( NetcdfOutputChooser . Data data ) { if ( data . version == NetcdfFileWriter . Version . ncstream ) { writeNcstream ( data . outputFilename ) ; return ; } try { FileWriter2 writer = new FileWriter2 ( ds , data . outputFilename , data . version , Nc4ChunkingStrategy . factory ( data . chunkerType , data . deflate , data . shuffle ) ) ; NetcdfFile result = writer . write ( ) ; result . close ( ) ; JOptionPane . showMessageDialog ( this , "File successfully written" ) ; } catch ( Exception ioe ) { JOptionPane . showMessageDialog ( this , "ERROR: " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( ) ; } }


Input: / * public void showTreeViewWindow () { if ( treeWindow == null ) { datasetTree = new DatasetTreeView () ; treeWindow = new IndependentWindow ( TreeView datasetTree ) ; treeWindow . setIconImage ( thredds . ui . BAMutil . getImage ( netcdfUI )) ; treeWindow . setBounds ( ( Rectangle ) prefs . getBean ( treeWindow new Rectangle ( 150 100 400 700 ))) ; } [CODESPLIT] private void showDeclaration ( BeanTable from , boolean isNcml ) { Variable v = getCurrentVariable ( from ) ; if ( v == null ) return ; infoTA . clear ( ) ; if ( isNcml ) { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; ncmlWriter . setNamespace ( null ) ; ncmlWriter . getXmlFormat ( ) . setOmitDeclaration ( true ) ; Element varElement = ncmlWriter . makeVariableElement ( v , false ) ; infoTA . appendLine ( ncmlWriter . writeToString ( varElement ) ) ; } else { infoTA . appendLine ( v . toString ( ) ) ; } if ( Debug . isSet ( "Xdeveloper" ) ) { infoTA . appendLine ( "\n" ) ; infoTA . appendLine ( "FULL NAME = " + v . getFullName ( ) ) ; infoTA . appendLine ( "\n" ) ; infoTA . appendLine ( v . toStringDebug ( ) ) ; } infoTA . gotoTop ( ) ; infoWindow . setTitle ( "Variable Info" ) ; infoWindow . show ( ) ; }


Input: / * private void showMissingData ( BeanTable from ) { VariableBean vb = ( VariableBean ) from . getSelectedBean () ; if ( vb == null ) return ; Variable v = vb . vs ; if (( v ! = null ) && ( v . getDataType () == ucar . nc2 . DataType . STRUCTURE )) { showMissingStructureData ( ( Structure ) v ) ; } if ( !vb . vs . hasMissing () ) return ; [CODESPLIT] private void dataTable ( BeanTable from ) { VariableBean vb = ( VariableBean ) from . getSelectedBean ( ) ; if ( vb == null ) return ; Variable v = vb . vs ; if ( v instanceof Structure ) { try { dataTable . setStructure ( ( Structure ) v ) ; } catch ( Exception ex ) { ex . printStackTrace ( ) ; } dataWindow . setComponent ( dataTable ) ; } else { List < VariableBean > l = from . getSelectedBeans ( ) ; List < Variable > vl = new ArrayList <> ( ) ; for ( VariableBean vb1 : l ) { if ( vb1 == null ) return ; v = vb1 . vs ; if ( v != null ) { vl . add ( v ) ; } else return ; } variableTable . setDataset ( ds ) ; variableTable . setVariableList ( vl ) ; variableTable . createTable ( ) ; dataWindow . setComponent ( variableTable ) ; } Rectangle r = ( Rectangle ) prefs . getBean ( "dataWindowBounds" , new Rectangle ( 50 , 300 , 1000 , 1200 ) ) ; dataWindow . setBounds ( r ) ; dataWindow . show ( ) ; }


Input: /////////////////////////////////////////////////////////////// [CODESPLIT] private void doGribIndex ( Formatter f , MCollection dcm , boolean eachFile ) throws IOException { Counters counters = new Counters ( ) ; // must open collection again without gbx filtering try ( MCollection dcm2 = getCollectionUnfiltered ( spec , f ) ) { for ( MFile mfile : dcm2 . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; f . format ( " %s%n" , path ) ; doGribIndex ( f , mfile , counters , eachFile ) ; } } counters . show ( f ) ; }


Input: ///////////////////////////////////////////// [CODESPLIT] private void doCheckLocalParams ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( "Check Grib-1 Parameter Tables for local entries%n" ) ; int [ ] accum = new int [ 4 ] ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; f . format ( "%n %s%n" , path ) ; try { doCheckLocalParams ( mfile , f , accum ) ; } catch ( Throwable t ) { System . out . printf ( "FAIL on %s%n" , mfile . getPath ( ) ) ; t . printStackTrace ( ) ; } } f . format ( "%nGrand total=%d local = %d missing = %d%n" , accum [ 0 ] , accum [ 2 ] , accum [ 3 ] ) ; }


Input: Look through the collection and find what GDS templates are used . [CODESPLIT] private void doCheckTables ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { Counters counters = new Counters ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; f . format ( " %s%n" , path ) ; if ( useIndex ) doCheckTablesWithIndex ( f , mfile , counters ) ; else doCheckTablesNoIndex ( f , mfile , counters ) ; } f . format ( "Check Parameter Tables%n" ) ; counters . show ( f ) ; }


Input: /////////////////////////////////////////////////////////////// [CODESPLIT] private void doScanIssues ( Formatter f , MCollection dcm , boolean useIndex , boolean eachFile , boolean extraInfo ) throws IOException { Counters countersAll = new Counters ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { Counters countersOneFile = countersAll . makeSubCounters ( ) ; String path = mfile . getPath ( ) ; f . format ( " %s%n" , path ) ; if ( useIndex ) doScanIssuesWithIndex ( f , mfile , extraInfo , countersOneFile ) ; else doScanIssuesNoIndex ( f , mfile , extraInfo , countersOneFile ) ; if ( eachFile ) { countersOneFile . show ( f ) ; } countersAll . addTo ( countersOneFile ) ; } f . format ( "ScanIssues - all files%n" ) ; countersAll . show ( f ) ; }


Input: /////////////////////////////////////////////////////////////// [CODESPLIT] private void doShowEncoding ( Formatter f , MCollection dcm ) throws IOException { Counters countersAll = new Counters ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( " %s%n" , mfile . getPath ( ) ) ; // need dataRaf, so cant useIndex doShowEncodingNoIndex ( f , mfile , countersAll ) ; } countersAll . show ( f ) ; }


Input: Look through the collection and find what GDS templates are used . [CODESPLIT] private void doUniqueGds ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( "Show Unique GDS%n" ) ; Map < Integer , GdsList > gdsSet = new HashMap <> ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( " %s%n" , mfile . getPath ( ) ) ; doUniqueGds ( mfile , gdsSet , f ) ; } List < GdsList > sorted = new ArrayList <> ( gdsSet . values ( ) ) ; Collections . sort ( sorted ) ; for ( GdsList gdsl : sorted ) { f . format ( "%nGDS %s template= %d %n" , gdsl . gds . getNameShort ( ) , gdsl . gds . template ) ; for ( FileCount fc : gdsl . fileList ) { f . format ( "  %5d %s %n" , fc . countRecords , fc . f . getPath ( ) ) ; } } }


Input: Open a FeatureDataset from a URL location string . Example URLS : <ul > <li > http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : file : c : / test / data / catalog / addeStationDataset . xml#AddeSurfaceData ( absolute file ) <li > thredds : resolve : resolveURL < / ul > [CODESPLIT] public DataFactory . Result openFeatureDataset ( String urlString , ucar . nc2 . util . CancelTask task ) throws IOException { DataFactory . Result result = new DataFactory . Result ( ) ; Dataset dataset = openCatalogFromLocation ( urlString , task , result ) ; if ( result . fatalError || dataset == null ) return result ; return openFeatureDataset ( null , dataset , task , result ) ; }


Input: Open a FeatureDataset from an Dataset object deciding on which Access to use . [CODESPLIT] @ Nonnull public DataFactory . Result openFeatureDataset ( Dataset Dataset , ucar . nc2 . util . CancelTask task ) throws IOException { return openFeatureDataset ( null , Dataset , task , new Result ( ) ) ; }


Input: Open a FeatureDataset from an Access object . [CODESPLIT] public DataFactory . Result openFeatureDataset ( Access access , ucar . nc2 . util . CancelTask task ) throws IOException { Dataset ds = access . getDataset ( ) ; DataFactory . Result result = new Result ( ) ; if ( ds . getFeatureType ( ) == null ) { result . errLog . format ( "InvDatasert must specify a FeatureType%n" ) ; result . fatalError = true ; return result ; } return openFeatureDataset ( ds . getFeatureType ( ) , access , task , result ) ; }


Input: Open a NetcdfDataset from a URL location string . Example URLS : <ul > <li > http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : file : c : / dev / netcdf - java - 2 . 2 / test / data / catalog / addeStationDataset . xml#AddeSurfaceData ( absolute file ) <li > thredds : resolve : resolveURL < / ul > [CODESPLIT] public NetcdfDataset openDataset ( String location , boolean acquire , ucar . nc2 . util . CancelTask task , Formatter log ) throws IOException { Result result = new Result ( ) ; Dataset dataset = openCatalogFromLocation ( location , task , result ) ; if ( result . fatalError || dataset == null ) { if ( log != null ) log . format ( "%s" , result . errLog ) ; result . close ( ) ; return null ; } return openDataset ( dataset , acquire , task , result ) ; }


Input:
Find the best access in case theres more than one based on what the CDM knows how to open and use . [CODESPLIT] public Access chooseDatasetAccess ( List < Access > accessList ) { if ( accessList . size ( ) == 0 ) return null ; Access access = null ; if ( preferAccess != null ) { for ( ServiceType type : preferAccess ) { access = findAccessByServiceType ( accessList , type ) ; if ( access != null ) break ; } } // the order indicates preference if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . CdmRemote ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DODS ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . OPENDAP ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DAP4 ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . File ) ; // should mean that it can be opened through netcdf API if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . HTTPServer ) ; // should mean that it can be opened through netcdf API /* look for HTTP with format we can read
    if (access == null) {
      Access tryAccess = findAccessByServiceType(accessList, ServiceType.HTTPServer);

      if (tryAccess != null) {
        DataFormatType format = tryAccess.getDataFormatType();

        // these are the file types we can read
        if ((DataFormatType.NCML == format) || (DataFormatType.NETCDF == format)) {   // removed 4/4/2015 jc
        //if ((DataFormatType.BUFR == format) || (DataFormatType.GINI == format) || (DataFormatType.GRIB1 == format)
        //        || (DataFormatType.GRIB2 == format) || (DataFormatType.HDF5 == format) || (DataFormatType.NCML == format)
       //         || (DataFormatType.NETCDF == format) || (DataFormatType.NEXRAD2 == format) || (DataFormatType.NIDS == format)) {
          access = tryAccess;
        }
      }
    } */ // ADDE if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . ADDE ) ; // RESOLVER if ( access == null ) { access = findAccessByServiceType ( accessList , ServiceType . Resolver ) ; } return access ; }


Input:
Add information from the Dataset to the NetcdfDataset . [CODESPLIT] public static void annotate ( Dataset ds , NetcdfDataset ncDataset ) { ncDataset . setTitle ( ds . getName ( ) ) ; ncDataset . setId ( ds . getId ( ) ) ; // add properties as global attributes for ( Property p : ds . getProperties ( ) ) { String name = p . getName ( ) ; if ( null == ncDataset . findGlobalAttribute ( name ) ) { ncDataset . addAttribute ( null , new Attribute ( name , p . getValue ( ) ) ) ; } } /* ThreddsMetadata.GeospatialCoverage geoCoverage = ds.getGeospatialCoverage();
   if (geoCoverage != null) {
     if ( null != geoCoverage.getNorthSouthRange()) {
       ncDataset.addAttribute(null, new Attribute("geospatial_lat_min", new Double(geoCoverage.getLatSouth())));
       ncDataset.addAttribute(null, new Attribute("geospatial_lat_max", new Double(geoCoverage.getLatNorth())));
     }
     if ( null != geoCoverage.getEastWestRange()) {
       ncDataset.addAttribute(null, new Attribute("geospatial_lon_min", new Double(geoCoverage.getLonWest())));
       ncDataset.addAttribute(null, new Attribute("geospatial_lon_max", new Double(geoCoverage.getLonEast())));
     }
     if ( null != geoCoverage.getUpDownRange()) {
       ncDataset.addAttribute(null, new Attribute("geospatial_vertical_min", new Double(geoCoverage.getHeightStart())));
       ncDataset.addAttribute(null, new Attribute("geospatial_vertical_max", new Double(geoCoverage.getHeightStart() + geoCoverage.getHeightExtent())));
     }
   }

   DateRange timeCoverage = ds.getTimeCoverage();
   if (timeCoverage != null) {
     ncDataset.addAttribute(null, new Attribute("time_coverage_start", timeCoverage.getStart().toDateTimeStringISO()));
     ncDataset.addAttribute(null, new Attribute("time_coverage_end", timeCoverage.getEnd().toDateTimeStringISO()));
   } */ ncDataset . finish ( ) ; }


Input: look for an access method for an image datatype [CODESPLIT] private Access getImageAccess ( Dataset ds , ucar . nc2 . util . CancelTask task , Result result ) throws IOException { List < Access > accessList = new ArrayList <> ( ds . getAccess ( ) ) ; // a list of all the accesses while ( accessList . size ( ) > 0 ) { Access access = chooseImageAccess ( accessList ) ; if ( access == null ) { result . errLog . format ( "No access that could be used for Image Type %s %n" , ds ) ; return null ; } // deal with RESOLVER type String datasetLocation = access . getStandardUrlName ( ) ; Dataset rds = openResolver ( datasetLocation , task , result ) ; if ( rds == null ) return null ; // use the access list from the resolved dataset accessList = new ArrayList <> ( ds . getAccess ( ) ) ; } return null ; }


Input: works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private Access findAccessByServiceType ( List < Access > accessList , ServiceType type ) { for ( Access a : accessList ) { ServiceType stype = a . getService ( ) . getType ( ) ; if ( stype != null && stype . toString ( ) . equalsIgnoreCase ( type . toString ( ) ) ) return a ; } return null ; }


Input: works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private Access findAccessByDataFormatType ( List < Access > accessList , DataFormatType type ) { for ( Access a : accessList ) { DataFormatType has = a . getDataFormatType ( ) ; if ( has != null && type . toString ( ) . equalsIgnoreCase ( has . toString ( ) ) ) return a ; } return null ; }


Input: /////////////////////////////// [CODESPLIT] public String getDetailInfo ( ) { StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( "PointObsDataset\n" ) ; sbuff . append ( "  adapter   = " ) . append ( getClass ( ) . getName ( ) ) . append ( "\n" ) ; sbuff . append ( "  timeUnit  = " ) . append ( getTimeUnits ( ) ) . append ( "\n" ) ; sbuff . append ( "  dataClass = " ) . append ( getDataClass ( ) ) . append ( "\n" ) ; sbuff . append ( "  dataCount = " ) . append ( getDataCount ( ) ) . append ( "\n" ) ; sbuff . append ( super . getDetailInfo ( ) ) ; return sbuff . toString ( ) ; }


Input: UnsupportedOperation [CODESPLIT] @ Override public ArrayStructure readStructure ( int start , int count ) throws IOException , ucar . ma2 . InvalidRangeException { throw new UnsupportedOperationException ( ) ; }


Input: isolate dependencies here - in case we have a minimal I / O mode where not all fields are available [CODESPLIT] public float [ ] readData ( RandomAccessFile raf , GribData . InterpolationMethod method ) throws IOException { Grib1Gds gds = getGDS ( ) ; Grib1DataReader reader = new Grib1DataReader ( pdss . getDecimalScale ( ) , gds . getScanMode ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , gds . getNpts ( ) , dataSection . getStartingPosition ( ) ) ; byte [ ] bm = ( bitmap == null ) ? null : bitmap . getBitmap ( raf ) ; float [ ] data = reader . getData ( raf , bm ) ; if ( gdss . isThin ( ) ) { data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , method ) ; } lastRecordRead = this ; return data ; }


Input: Read data array by first reading in GribRecord . All sections are read in so scanMode is from the datafile not the index . [CODESPLIT] public static float [ ] readData ( RandomAccessFile raf , long startPos ) throws IOException { raf . seek ( startPos ) ; Grib1Record gr = new Grib1Record ( raf ) ; return gr . readData ( raf ) ; }


Input:
/ * Read data array : use when you want to be independent of the GribRecord [CODESPLIT] public GribData . Info getBinaryDataInfo ( RandomAccessFile raf ) throws IOException { GribData . Info info = dataSection . getBinaryDataInfo ( raf ) ; info . decimalScaleFactor = pdss . getDecimalScale ( ) ; info . bitmapLength = ( bitmap == null ) ? 0 : bitmap . getLength ( raf ) ; info . nPoints = getGDS ( ) . getNpts ( ) ; info . msgLength = is . getMessageLength ( ) ; if ( bitmap == null ) { info . ndataPoints = info . nPoints ; } else { byte [ ] bm = bitmap . getBitmap ( raf ) ; if ( bm == null ) { info . ndataPoints = info . nPoints ; } else { // have to count the bits to see how many data values are stored
 info . ndataPoints = GribNumbers . countBits ( bm ) ; } } return info ; }


Input: debugging - do not use [CODESPLIT] public int [ ] readRawData ( RandomAccessFile raf ) throws IOException { Grib1Gds gds = getGDS ( ) ; Grib1DataReader reader = new Grib1DataReader ( pdss . getDecimalScale ( ) , gds . getScanMode ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , gds . getNpts ( ) , dataSection . getStartingPosition ( ) ) ; byte [ ] bm = ( bitmap == null ) ? null : bitmap . getBitmap ( raf ) ; return reader . getDataRaw ( raf , bm ) ; }


Input: e . g . of server with problem ( 2 - Nov - 2006 ) : http : // acdisc . sci . gsfc . nasa . gov / opendap - bin / nph - dods / OPENDAP / Giovanni / [CODESPLIT] private String forceChild ( String url ) { String prefix = path ; if ( prefix . endsWith ( "/" ) ) prefix = path . substring ( 0 , path . length ( ) - 1 ) ; // because the url also contains a '/' that we will use			 int j = url . substring ( 0 , url . length ( ) - 1 ) . lastIndexOf ( ' ' ) ; // url.length() - 1 was intentional .. if the last char is a '/', we're interested in the previous one. if ( j >= 0 ) { String ret = prefix + url . substring ( j ) ; return ret ; } else // relative paths .. leave intact return url ; }


Input: Reassemble the url using the specified parts [CODESPLIT] public String assemble ( EnumSet < Parts > parts ) { StringBuilder uri = new StringBuilder ( ) ; // Note that format and base may be same, so case it out int useformat = ( parts . contains ( Parts . FORMAT ) ? 1 : 0 ) ; int usebase = ( parts . contains ( Parts . BASE ) ? 2 : 0 ) ; switch ( useformat + usebase ) { case 0 + 0 : // neither break ; case 1 + 0 : // FORMAT only uri . append ( this . formatprotocol + ":" ) ; break ; case 2 + 0 : // BASE only uri . append ( this . baseprotocol + ":" ) ; break ; case 2 + 1 : // both uri . append ( this . formatprotocol + ":" ) ; if ( ! this . baseprotocol . equals ( this . formatprotocol ) ) uri . append ( this . formatprotocol + ":" ) ; break ; } uri . append ( this . baseprotocol . equals ( "file" ) ? "/" : "//" ) ; if ( userinfo != null && parts . contains ( Parts . PWD ) ) uri . append ( this . userinfo + ":" ) ; if ( this . host != null && parts . contains ( Parts . HOST ) ) uri . append ( this . host ) ; if ( this . path != null && parts . contains ( Parts . PATH ) ) uri . append ( this . path ) ; if ( this . query != null && parts . contains ( Parts . QUERY ) ) uri . append ( "?" + this . query ) ; if ( this . frag != null && parts . contains ( Parts . FRAG ) ) uri . append ( "#" + this . frag ) ; return uri . toString ( ) ; }


Input: Canonicalize a part of a URL [CODESPLIT] static public String canonical ( String s ) { if ( s != null ) { s = s . trim ( ) ; if ( s . length ( ) == 0 ) s = null ; } return s ; }


Input:
} [CODESPLIT] public static boolean isMine ( NetcdfFile ncfile ) { if ( null == ncfile . findDimension ( "south_north" ) ) return false ; // ARW only
 Attribute att = ncfile . findGlobalAttribute ( "DYN_OPT" ) ; if ( att != null ) { if ( att . getNumericValue ( ) . intValue ( ) != 2 ) return false ; } else { att = ncfile . findGlobalAttribute ( "GRIDTYPE" ) ; if ( att != null ) { if ( ! att . getStringValue ( ) . equalsIgnoreCase ( "C" ) && ! att . getStringValue ( ) . equalsIgnoreCase ( "E" ) ) return false ; } } att = ncfile . findGlobalAttribute ( "MAP_PROJ" ) ; return att != null ; }


Input:
/ * ARW Users Guide p 3 - 19 <pre > 7 . MAP_PROJ_NAME : Character string specifying type of map projection . Valid entries are : polar - > Polar stereographic lambert - > Lambert conformal ( secant and tangent ) mercator - > Mercator [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) { if ( null != ds . findVariable ( "x" ) ) return ; // check if its already been done - aggregating enhanced datasets.
 Attribute att = ds . findGlobalAttribute ( "GRIDTYPE" ) ; gridE = att != null && att . getStringValue ( ) . equalsIgnoreCase ( "E" ) ; // kludge in fixing the units
 List < Variable > vlist = ds . getVariables ( ) ; for ( Variable v : vlist ) { att = v . findAttributeIgnoreCase ( CDM . UNITS ) ; if ( att != null ) { String units = att . getStringValue ( ) ; if ( units != null ) v . addAttribute ( new Attribute ( CDM . UNITS , normalize ( units ) ) ) ; // removes the old
 } } // make projection transform
 att = ds . findGlobalAttribute ( "MAP_PROJ" ) ; int projType = att . getNumericValue ( ) . intValue ( ) ; boolean isLatLon = false ; if ( projType == 203 ) { /* centerX = centralLon;
      centerY = centralLat;
      ds.addCoordinateAxis( makeLonCoordAxis( ds, "longitude", ds.findDimension("west_east")));
      ds.addCoordinateAxis( makeLatCoordAxis( ds, "latitude", ds.findDimension("south_north")));  */ Variable glat = ds . findVariable ( "GLAT" ) ; if ( glat == null ) { parseInfo . format ( "Projection type 203 - expected GLAT variable not found%n" ) ; } else { glat . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; if ( gridE ) glat . addAttribute ( new Attribute ( _Coordinate . Stagger , CDM . ARAKAWA_E ) ) ; glat . setDimensions ( "south_north west_east" ) ; glat . setCachedData ( convertToDegrees ( glat ) , false ) ; glat . addAttribute ( new Attribute ( CDM . UNITS , CDM . LAT_UNITS ) ) ; } Variable glon = ds . findVariable ( "GLON" ) ; if ( glon == null ) { parseInfo . format ( "Projection type 203 - expected GLON variable not found%n" ) ; } else { glon . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; if ( gridE ) glon . addAttribute ( new Attribute ( _Coordinate . Stagger , CDM . ARAKAWA_E ) ) ; glon . setDimensions ( "south_north west_east" ) ; glon . setCachedData ( convertToDegrees ( glon ) , false ) ; glon . addAttribute ( new Attribute ( CDM . UNITS , CDM . LON_UNITS ) ) ; } VariableDS v = new VariableDS ( ds , null , null , "LatLonCoordSys" , DataType . CHAR , "" , null , null ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , "GLAT GLON Time" ) ) ; Array data = Array . factory ( DataType . CHAR , new int [ ] { } , new char [ ] { ' ' } ) ; v . setCachedData ( data , true ) ; ds . addVariable ( null , v ) ; Variable dataVar = ds . findVariable ( "LANDMASK" ) ; dataVar . addAttribute ( new Attribute ( _Coordinate . Systems , "LatLonCoordSys" ) ) ; } else { double lat1 = findAttributeDouble ( ds , "TRUELAT1" ) ; double lat2 = findAttributeDouble ( ds , "TRUELAT2" ) ; double centralLat = findAttributeDouble ( ds , "CEN_LAT" ) ; // center of grid
 double centralLon = findAttributeDouble ( ds , "CEN_LON" ) ; // center of grid
 double standardLon = findAttributeDouble ( ds , "STAND_LON" ) ; // true longitude
 double standardLat = findAttributeDouble ( ds , "MOAD_CEN_LAT" ) ; ProjectionImpl proj = null ; switch ( projType ) { case 0 : // for diagnostic runs with no georeferencing
 proj = new FlatEarth ( ) ; projCT = new ProjectionCT ( "flat_earth" , "FGDC" , proj ) ; // System.out.println(" using LC "+proj.paramsToString());
 break ; case 1 : proj = new LambertConformal ( standardLat , standardLon , lat1 , lat2 , 0.0 , 0.0 , 6370 ) ; projCT = new ProjectionCT ( "Lambert" , "FGDC" , proj ) ; // System.out.println(" using LC "+proj.paramsToString());
 break ; case 2 : // Thanks to Heiko Klein for figuring out WRF Stereographic
 double lon0 = ( Double . isNaN ( standardLon ) ) ? centralLon : standardLon ; double lat0 = ( Double . isNaN ( centralLat ) ) ? lat2 : centralLat ; // ?? 7/20/2010
 double scaleFactor = ( 1 + Math . abs ( Math . sin ( Math . toRadians ( lat1 ) ) ) ) / 2. ; // R Schmunk 9/10/07
 // proj = new Stereographic(lat2, lon0, scaleFactor);
 proj = new Stereographic ( lat0 , lon0 , scaleFactor , 0.0 , 0.0 , 6370 ) ; projCT = new ProjectionCT ( "Stereographic" , "FGDC" , proj ) ; break ; case 3 : proj = new Mercator ( standardLon , lat1 , 0.0 , 0.0 , 6370 ) ; // thanks to Robert Schmunk with edits for non-MOAD grids
 projCT = new ProjectionCT ( "Mercator" , "FGDC" , proj ) ; // proj = new TransverseMercator(standardLat, standardLon, 1.0);
 //projCT = new ProjectionCT("TransverseMercator", "FGDC", proj);
 break ; case 6 : // version 3 "lat-lon", including global
 // http://www.mmm.ucar.edu/wrf/users/workshops/WS2008/presentations/1-2.pdf
 // use 2D XLAT, XLONG
 isLatLon = true ; for ( Variable v : vlist ) { if ( v . getShortName ( ) . startsWith ( "XLAT" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; removeConstantTimeDim ( ds , v ) ; } else if ( v . getShortName ( ) . startsWith ( "XLONG" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; removeConstantTimeDim ( ds , v ) ; } else if ( v . getShortName ( ) . equals ( "T" ) ) { // ANOTHER MAJOR KLUDGE to pick up 4D fields
 v . addAttribute ( new Attribute ( _Coordinate . Axes , "Time XLAT XLONG z" ) ) ; } else if ( v . getShortName ( ) . equals ( "U" ) ) { v . addAttribute ( new Attribute ( _Coordinate . Axes , "Time XLAT_U XLONG_U z" ) ) ; } else if ( v . getShortName ( ) . equals ( "V" ) ) { v . addAttribute ( new Attribute ( _Coordinate . Axes , "Time XLAT_V XLONG_V z" ) ) ; } else if ( v . getShortName ( ) . equals ( "W" ) ) { v . addAttribute ( new Attribute ( _Coordinate . Axes , "Time XLAT XLONG z_stag" ) ) ; } } break ; default : parseInfo . format ( "ERROR: unknown projection type = %s%n" , projType ) ; break ; } if ( proj != null ) { LatLonPointImpl lpt1 = new LatLonPointImpl ( centralLat , centralLon ) ; // center of the grid
 ProjectionPoint ppt1 = proj . latLonToProj ( lpt1 , new ProjectionPointImpl ( ) ) ; centerX = ppt1 . getX ( ) ; centerY = ppt1 . getY ( ) ; if ( debug ) { System . out . println ( "centerX=" + centerX ) ; System . out . println ( "centerY=" + centerY ) ; } } // make axes
 if ( ! isLatLon ) { ds . addCoordinateAxis ( makeXCoordAxis ( ds , "x" , ds . findDimension ( "west_east" ) ) ) ; ds . addCoordinateAxis ( makeXCoordAxis ( ds , "x_stag" , ds . findDimension ( "west_east_stag" ) ) ) ; ds . addCoordinateAxis ( makeYCoordAxis ( ds , "y" , ds . findDimension ( "south_north" ) ) ) ; ds . addCoordinateAxis ( makeYCoordAxis ( ds , "y_stag" , ds . findDimension ( "south_north_stag" ) ) ) ; } ds . addCoordinateAxis ( makeZCoordAxis ( ds , "z" , ds . findDimension ( "bottom_top" ) ) ) ; ds . addCoordinateAxis ( makeZCoordAxis ( ds , "z_stag" , ds . findDimension ( "bottom_top_stag" ) ) ) ; if ( projCT != null ) { VariableDS v = makeCoordinateTransformVariable ( ds , projCT ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisTypes , "GeoX GeoY" ) ) ; if ( gridE ) v . addAttribute ( new Attribute ( _Coordinate . Stagger , CDM . ARAKAWA_E ) ) ; ds . addVariable ( null , v ) ; } } // time coordinate variations
 if ( ds . findVariable ( "Time" ) == null ) { // Can skip this if its already there, eg from NcML
 CoordinateAxis taxis = makeTimeCoordAxis ( ds , "Time" , ds . findDimension ( "Time" ) ) ; if ( taxis == null ) taxis = makeTimeCoordAxis ( ds , "Time" , ds . findDimension ( "Times" ) ) ; if ( taxis != null ) ds . addCoordinateAxis ( taxis ) ; } ds . addCoordinateAxis ( makeSoilDepthCoordAxis ( ds , "ZS" ) ) ; ds . finish ( ) ; }


Input: pretty much WRF specific [CODESPLIT] private String normalize ( String units ) { switch ( units ) { case "fraction" : units = "" ; break ; case "dimensionless" : units = "" ; break ; case "NA" : units = "" ; break ; case "-" : units = "" ; break ; default : units = StringUtil2 . substitute ( units , "**" , "^" ) ; units = StringUtil2 . remove ( units , ' ' ) ; units = StringUtil2 . remove ( units , ' ' ) ; break ; } return units ; }


Input: //////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private CoordinateAxis makeLonCoordAxis ( NetcdfDataset ds , String axisName , Dimension dim ) { if ( dim == null ) return null ; double dx = 4 * findAttributeDouble ( ds , "DX" ) ; int nx = dim . getLength ( ) ; double startx = centerX - dx * ( nx - 1 ) / 2 ; CoordinateAxis v = new CoordinateAxis1D ( ds , null , axisName , DataType . DOUBLE , dim . getShortName ( ) , "degrees_east" , "synthesized longitude coordinate" ) ; v . setValues ( nx , startx , dx ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , "Lon" ) ) ; if ( ! axisName . equals ( dim . getShortName ( ) ) ) v . addAttribute ( new Attribute ( _Coordinate . AliasForDimension , dim . getShortName ( ) ) ) ; return v ; }


Input:
Assign CoordinateTransform objects to Coordinate Systems . [CODESPLIT] protected void assignCoordinateTransforms ( NetcdfDataset ncDataset ) { super . assignCoordinateTransforms ( ncDataset ) ; // any cs whose got a vertical coordinate with no units
 List < CoordinateSystem > csys = ncDataset . getCoordinateSystems ( ) ; for ( CoordinateSystem cs : csys ) { if ( cs . getZaxis ( ) != null ) { String units = cs . getZaxis ( ) . getUnitsString ( ) ; if ( ( units == null ) || ( units . trim ( ) . length ( ) == 0 ) ) { VerticalCT vct = makeWRFEtaVerticalCoordinateTransform ( ncDataset , cs ) ; if ( vct != null ) cs . addCoordinateTransform ( vct ) ; parseInfo . format ( "***Added WRFEta verticalCoordinateTransform to %s%n" , cs . getName ( ) ) ; } } } }


Input: A path is file if it has no base protocol or is file : [CODESPLIT] static public boolean dspMatch ( String path , DapContext context ) { for ( String s : EXTENSIONS ) { if ( path . endsWith ( s ) ) return true ; } return false ; }


Input: Main entry point [CODESPLIT] public DapDataset compile ( ) throws DapException { // create and fill the root group buildrootgroup ( this . ncid ) ; if ( this . dmr != null ) dmr . finish ( ) ; return this . dmr ; }


Input: //////////////////////////////////////////////// [CODESPLIT] protected void buildrootgroup ( int ncid ) throws DapException { int ret ; byte [ ] namep = new byte [ NC_MAX_NAME + 1 ] ; errcheck ( ret = nc4 . nc_inq_grpname ( ncid , namep ) ) ; String [ ] pieces = DapUtil . canonicalpath ( this . path ) . split ( "[/]" ) ; DapDataset g = factory . newDataset ( pieces [ pieces . length - 1 ] ) ; GroupNotes gi = ( GroupNotes ) Nc4Notes . factory ( NoteSort . GROUP , ncid , ncid , this . dsp ) ; gi . set ( g ) ; this . dsp . note ( gi ) ; this . dmr = g ; fillgroup ( ncid ) ; }


Input: //////////////////////////////////////////////// [CODESPLIT] int [ ] getGroups ( int gid ) throws DapException { int ret , n ; IntByReference ip = new IntByReference ( ) ; errcheck ( ret = nc4 . nc_inq_grps ( gid , ip , null ) ) ; n = ip . getValue ( ) ; int [ ] grpids = null ; if ( n > 0 ) { grpids = new int [ n ] ; errcheck ( ret = nc4 . nc_inq_grps ( gid , ip , grpids ) ) ; } else grpids = new int [ 0 ] ; return grpids ; }


Input: / * Object [] convert ( int count Object src TypeNotes basetype ) throws DapException { boolean isenum = isenumtype ( basetype ) ; boolean isopaque = basetype . isOpaque () ; TypeNotes truetype = basetype ; if ( isenum ) truetype = enumbasetype ( basetype ) ; [CODESPLIT] protected void errcheck ( int ret ) throws DapException { if ( ret != 0 ) { String msg = String . format ( "TestNetcdf: errno=%d; %s" , ret , nc4 . nc_strerror ( ret ) ) ; if ( DEBUG ) System . err . println ( msg ) ; throw new DapException ( msg ) ; } }


Input: Finish getting the metadata if necessary . If this is an XLink this will trigger a read of the href the first time called . [CODESPLIT] public void finish ( ) { if ( init ) return ; init = true ; if ( xlinkHref == null ) return ; xlinkHref = xlinkHref . trim ( ) ; try { this . xlinkUri = dataset . getParentCatalog ( ) . resolveUri ( xlinkHref ) ; } catch ( java . net . URISyntaxException e ) { log . append ( " ** Error: Bad URL in metadata href = " ) . append ( xlinkHref ) . append ( "\n" ) ; return ; } // open and read the referenced catalog XML try { if ( converter == null ) { log . append ( "  **InvMetadata on = (" ) . append ( this ) . append ( "): has no converter\n" ) ; return ; } contentObject = converter . readMetadataContentFromURL ( dataset , xlinkUri ) ; if ( isThreddsMetadata ) tm = ( ThreddsMetadata ) contentObject ; } catch ( java . io . IOException e ) { log . append ( "  **InvMetadata on = (" ) . append ( xlinkUri ) . append ( "): Exception (" ) . append ( e . getMessage ( ) ) . append ( ")\n" ) ; // e.printStackTrace(); } }


Input: Returns the value to which the key is mapped in this table . [CODESPLIT] public synchronized Object get ( Object key ) { int index = keys . indexOf ( key ) ; if ( index != - 1 ) return elements . elementAt ( index ) ; else return null ; }


Input: Maps the specified key to the specified value in this table . [CODESPLIT] public synchronized Object put ( Object key , Object value ) throws NullPointerException { if ( key == null || value == null ) throw new NullPointerException ( ) ; int index = keys . indexOf ( key ) ; if ( index != - 1 ) { Object prev = elements . elementAt ( index ) ; elements . setElementAt ( value , index ) ; return prev ; } else { keys . addElement ( key ) ; elements . addElement ( value ) ; return null ; } }


Input: Removes the key ( and its corresponding value ) from this table . If the key is not in the table do nothing . [CODESPLIT] public synchronized Object remove ( Object key ) { int index = keys . indexOf ( key ) ; if ( index != - 1 ) { Object prev = elements . elementAt ( index ) ; keys . removeElementAt ( index ) ; elements . removeElementAt ( index ) ; return prev ; } else { return null ; } }


Input: Return this as a java Date object [CODESPLIT] public Date getDate ( ) { Calendar calendar = Calendar . getInstance ( TimeZone . getTimeZone ( "GMT" ) ) ; calendar . set ( Calendar . YEAR , year ) ; calendar . set ( Calendar . MONTH , month - 1 ) ; // MONTH is zero based calendar . set ( Calendar . DAY_OF_MONTH , day ) ; calendar . set ( Calendar . HOUR_OF_DAY , hour ) ; calendar . set ( Calendar . MINUTE , minute ) ; calendar . set ( Calendar . SECOND , 0 ) ; calendar . set ( Calendar . MILLISECOND , 0 ) ; return calendar . getTime ( ) ; }


Input: Print a DapDataset : - as DMR - optionally constrained [CODESPLIT] public void print ( ) throws IOException { if ( this . ce == null ) this . ce = CEConstraint . getUniversal ( dmr ) ; assert ( this . ce != null ) ; this . printer . setIndent ( 0 ) ; printNode ( dmr ) ; // start printing at the root printer . eol ( ) ; }


Input: Print an arbitrary DapNode and its subnodes as if it is being sent to a client with optional constraint ; inclusions are determined by the view . <p > Handling newlines is a bit tricky because they may be embedded for e . g . groups enums etc . So the rule is that the last newline is elided and left for the caller to print . Exceptions : printMetadata printDimrefs printMaps [CODESPLIT] public void printNode ( DapNode node ) throws IOException { if ( node == null ) return ; DapSort sort = node . getSort ( ) ; String dmrname = sort . getName ( ) ; switch ( sort ) { case DATASET : // treat like group case GROUP : if ( ! this . ce . references ( node ) ) break ; DapGroup group = ( DapGroup ) node ; printer . marginPrint ( "<" + dmrname ) ; int flags = ( sort == DapSort . DATASET ? PERLINE : NILFLAGS ) ; printXMLAttributes ( node , ce , flags ) ; printer . println ( ">" ) ; printer . indent ( ) ; // Make the output order conform to the spec if ( group . getDimensions ( ) . size ( ) > 0 ) { for ( DapNode subnode : group . getDimensions ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } } if ( group . getEnums ( ) . size ( ) > 0 ) { for ( DapNode subnode : group . getEnums ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } } if ( group . getVariables ( ) . size ( ) > 0 ) for ( DapNode subnode : group . getVariables ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } printMetadata ( node ) ; if ( group . getGroups ( ) . size ( ) > 0 ) for ( DapNode subnode : group . getGroups ( ) ) { if ( ! this . ce . references ( subnode ) ) continue ; printNode ( subnode ) ; printer . eol ( ) ; } printer . outdent ( ) ; printer . marginPrint ( "</" + dmrname + ">" ) ; break ; case DIMENSION : if ( ! this . ce . references ( node ) ) break ; DapDimension dim = ( DapDimension ) node ; if ( ! dim . isShared ( ) ) break ; // ignore, here, anonymous dimensions printer . marginPrint ( "<" + dmrname ) ; printXMLAttributes ( node , ce , NILFLAGS ) ; if ( dim . isUnlimited ( ) ) printXMLAttribute ( AbstractDSP . UCARTAGUNLIMITED , "1" , NILFLAGS ) ; if ( hasMetadata ( node ) ) { printer . println ( ">" ) ; printMetadata ( node ) ; printer . marginPrint ( "</" + dmrname + ">" ) ; } else { printer . print ( "/>" ) ; } break ; case ENUMERATION : if ( ! this . ce . references ( node ) ) break ; DapEnumeration en = ( DapEnumeration ) node ; printer . marginPrint ( "<" + dmrname ) ; printXMLAttributes ( en , ce , NILFLAGS ) ; printer . println ( ">" ) ; printer . indent ( ) ; List < String > econstnames = en . getNames ( ) ; for ( String econst : econstnames ) { DapEnumConst value = en . lookup ( econst ) ; assert ( value != null ) ; printer . marginPrintln ( String . format ( "<EnumConst name=\"%s\" value=\"%d\"/>" , Escape . entityEscape ( econst , null ) , value . getValue ( ) ) ) ; } printMetadata ( node ) ; printer . outdent ( ) ; printer . marginPrint ( "</" + dmrname + ">" ) ; break ; case VARIABLE : if ( ! this . ce . references ( node ) ) break ; DapVariable var = ( DapVariable ) node ; DapType type = var . getBaseType ( ) ; printer . marginPrint ( "<" + type . getTypeSort ( ) . name ( ) ) ; printXMLAttributes ( node , ce , NILFLAGS ) ; if ( type . isAtomic ( ) ) { if ( ( hasMetadata ( node ) || hasDimensions ( var ) || hasMaps ( var ) ) ) { printer . println ( ">" ) ; printer . indent ( ) ; if ( hasDimensions ( var ) ) printDimrefs ( var ) ; if ( hasMetadata ( var ) ) printMetadata ( var ) ; if ( hasMaps ( var ) ) printMaps ( var ) ; printer . outdent ( ) ; printer . marginPrint ( "</" + type . getTypeSort ( ) . name ( ) + ">" ) ; } else printer . print ( "/>" ) ; } else if ( type . getTypeSort ( ) . isCompound ( ) ) { DapStructure struct = ( DapStructure ) type ; printer . println ( ">" ) ; printer . indent ( ) ; for ( DapVariable field : struct . getFields ( ) ) { if ( ! this . ce . references ( field ) ) continue ; printNode ( field ) ; printer . eol ( ) ; } printDimrefs ( var ) ; printMetadata ( var ) ; printMaps ( var ) ; printer . outdent ( ) ; printer . marginPrint ( "</" + type . getTypeSort ( ) . name ( ) + ">" ) ; } else assert false : "Illegal variable base type" ; break ; default : assert ( false ) : "Unexpected sort: " + sort . name ( ) ; break ; } }


Input: Print info from the node that needs to be in the form of xml attributes [CODESPLIT] void printXMLAttributes ( DapNode node , CEConstraint ce , int flags ) throws IOException { if ( ( flags & PERLINE ) != 0 ) printer . indent ( 2 ) ; // Print name first, if non-null and !NONAME // Note that the short name needs to use // entity escaping (which is done by printXMLattribute), // but backslash escaping is not required. String name = node . getShortName ( ) ; if ( name != null && ( flags & NONAME ) == 0 ) { name = node . getShortName ( ) ; printXMLAttribute ( "name" , name , flags ) ; } switch ( node . getSort ( ) ) { case DATASET : DapDataset dataset = ( DapDataset ) node ; printXMLAttribute ( "dapVersion" , dataset . getDapVersion ( ) , flags ) ; printXMLAttribute ( "dmrVersion" , dataset . getDMRVersion ( ) , flags ) ; // boilerplate printXMLAttribute ( "xmlns" , "http://xml.opendap.org/ns/DAP/4.0#" , flags ) ; printXMLAttribute ( "xmlns:dap" , "http://xml.opendap.org/ns/DAP/4.0#" , flags ) ; break ; case DIMENSION : DapDimension orig = ( DapDimension ) node ; if ( orig . isShared ( ) ) { //not Anonymous // name will have already been printed // Now, we need to get the size as defined by the constraint DapDimension actual = this . ce . getRedefDim ( orig ) ; if ( actual == null ) actual = orig ; long size = actual . getSize ( ) ; printXMLAttribute ( "size" , Long . toString ( size ) , flags ) ; } break ; case ENUMERATION : printXMLAttribute ( "basetype" , ( ( DapEnumeration ) node ) . getBaseType ( ) . getTypeName ( ) , flags ) ; break ; case VARIABLE : DapVariable var = ( DapVariable ) node ; DapType basetype = var . getBaseType ( ) ; if ( basetype . isEnumType ( ) ) { printXMLAttribute ( "enum" , basetype . getTypeName ( ) , flags ) ; } break ; case ATTRIBUTE : DapAttribute attr = ( DapAttribute ) node ; basetype = attr . getBaseType ( ) ; printXMLAttribute ( "type" , basetype . getTypeName ( ) , flags ) ; if ( attr . getBaseType ( ) . isEnumType ( ) ) { printXMLAttribute ( "enum" , basetype . getTypeName ( ) , flags ) ; } break ; default : break ; // node either has no attributes or name only } //switch if ( ! this . testing ) printReserved ( node ) ; if ( ( flags & PERLINE ) != 0 ) { printer . outdent ( 2 ) ; } }


Input: PrintXMLAttributes helper function [CODESPLIT] protected void printXMLAttribute ( String name , String value , int flags ) throws DapException { if ( name == null ) return ; if ( ( flags & NONNIL ) == 0 && ( value == null || value . length ( ) == 0 ) ) return ; if ( ( flags & PERLINE ) != 0 ) { printer . eol ( ) ; printer . margin ( ) ; } printer . print ( " " + name + "=" ) ; printer . print ( "\"" ) ; if ( value != null ) { // add xml entity escaping if ( ( flags & XMLESCAPED ) == 0 ) value = Escape . entityEscape ( value , "\"" ) ; printer . print ( value ) ; } printer . print ( "\"" ) ; }


Input: Special here is not the same as reserved [CODESPLIT] static boolean isSpecial ( DapAttribute attr ) { if ( attr . getParent ( ) . getSort ( ) == DapSort . DATASET ) { for ( String s : GROUPSPECIAL ) { if ( s . equals ( attr . getShortName ( ) ) ) return true ; } } else if ( attr . getParent ( ) . getSort ( ) == DapSort . VARIABLE ) { for ( String s : VARSPECIAL ) { if ( s . equals ( attr . getShortName ( ) ) ) return true ; } } return false ; }


Input: Print the dimrefs for a variable s dimensions . If the variable has a non - whole projection then use size else use the dimension name . [CODESPLIT] void printDimrefs ( DapVariable var ) throws DapException { if ( var . getRank ( ) == 0 ) return ; List < DapDimension > dimset = this . ce . getConstrainedDimensions ( var ) ; if ( dimset == null ) throw new DapException ( "Unknown variable: " + var ) ; assert var . getRank ( ) == dimset . size ( ) ; for ( int i = 0 ; i < var . getRank ( ) ; i ++ ) { DapDimension dim = dimset . get ( i ) ; printer . marginPrint ( "<Dim" ) ; if ( dim . isShared ( ) ) { String fqn = dim . getFQN ( ) ; assert ( fqn != null ) : "Illegal Dimension reference" ; fqn = fqnXMLEscape ( fqn ) ; printXMLAttribute ( "name" , fqn , XMLESCAPED ) ; } else { long size = dim . getSize ( ) ; // the size for printing purposes printXMLAttribute ( "size" , Long . toString ( size ) , NILFLAGS ) ; } printer . println ( "/>" ) ; } }


Input: XML escape a dap fqn and converting to &quot ; Assumes backslash escapes are in effect for / and . [CODESPLIT] static public String fqnXMLEscape ( String fqn ) { // Split the fqn into pieces StringBuilder xml = new StringBuilder ( ) ; String segment = null ; List < String > segments = Escape . backslashsplit ( fqn , ' ' ) ; for ( int i = 1 ; i < segments . size ( ) - 1 ; i ++ ) { // skip leading / segment = segments . get ( i ) ; segment = Escape . backslashUnescape ( segment ) ; // get to raw name segment = Escape . entityEscape ( segment , "\"" ) ; // '"' -> " segment = Escape . backslashEscape ( segment , "/." ) ; // re-escape xml . append ( "/" ) ; xml . append ( segment ) ; } // Last segment might be structure path, so similar processing, // but worry about '.' segment = segments . get ( segments . size ( ) - 1 ) ; segments = Escape . backslashsplit ( segment , ' ' ) ; xml . append ( "/" ) ; for ( int i = 0 ; i < segments . size ( ) ; i ++ ) { segment = segments . get ( i ) ; segment = Escape . backslashUnescape ( segment ) ; // get to raw name segment = Escape . entityEscape ( segment , "\"" ) ; // '"' -> " segment = Escape . backslashEscape ( segment , "/." ) ; // re-escape if ( i > 0 ) xml . append ( "." ) ; xml . append ( segment ) ; } return xml . toString ( ) ; }


Input:
initialize ; note that the file is reopened here [CODESPLIT] public boolean init ( String location , NetcdfFile ncfile ) throws AreaFileException { af = new AreaFile ( location ) ; //read metadata
 dirBlock = af . getDir ( ) ; ad = af . getAreaDirectory ( ) ; int numElements = ad . getElements ( ) ; int numLines = ad . getLines ( ) ; int numBands = ad . getNumberOfBands ( ) ; bandMap = ad . getBands ( ) ; navBlock = af . getNav ( ) ; Date nomTime = ad . getNominalTime ( ) ; DateFormatter df = new DateFormatter ( ) ; try { nav = AREAnav . makeAreaNav ( navBlock , af . getAux ( ) ) ; } catch ( McIDASException me ) { throw new AreaFileException ( me . getMessage ( ) ) ; } int sensor = dirBlock [ AreaFile . AD_SENSORID ] ; String calName = McIDASUtil . intBitsToString ( dirBlock [ AreaFile . AD_CALTYPE ] ) ; int calType = getCalType ( calName ) ; // TODO:  Need to support calibrated data.
 if ( ( af . getCal ( ) != null ) && CalibratorFactory . hasCalibrator ( sensor ) ) { //System.out.println("can calibrate");
 try { calibrator = CalibratorFactory . getCalibrator ( sensor , calType , af . getCal ( ) ) ; } catch ( CalibratorException ce ) { // System.out.println("can't make calibrator");
 calibrator = null ; } //System.out.println("calibrator = " + calibrator);
 } calUnit = ad . getCalibrationUnitName ( ) ; calScale = ( 1.0f / ad . getCalibrationScaleFactor ( ) ) ; // make the dimensions
 Dimension elements = new Dimension ( "elements" , numElements , true ) ; Dimension lines = new Dimension ( "lines" , numLines , true ) ; Dimension bands = new Dimension ( "bands" , numBands , true ) ; Dimension time = new Dimension ( "time" , 1 , true ) ; Dimension dirDim = new Dimension ( "dirSize" , AreaFile . AD_DIRSIZE , true ) ; Dimension navDim = new Dimension ( "navSize" , navBlock . length , true ) ; List < Dimension > image = new ArrayList <> ( ) ; image . add ( time ) ; image . add ( bands ) ; image . add ( lines ) ; image . add ( elements ) ; ncfile . addDimension ( null , elements ) ; ncfile . addDimension ( null , lines ) ; ncfile . addDimension ( null , bands ) ; ncfile . addDimension ( null , time ) ; ncfile . addDimension ( null , dirDim ) ; ncfile . addDimension ( null , navDim ) ; Array varArray ; // make the variables
 // time
 Variable timeVar = new Variable ( ncfile , null , null , "time" ) ; timeVar . setDataType ( DataType . INT ) ; timeVar . setDimensions ( "time" ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , "seconds since " + df . toDateTimeString ( nomTime ) ) ) ; timeVar . addAttribute ( new Attribute ( "long_name" , "time" ) ) ; varArray = new ArrayInt . D1 ( 1 , false ) ; ( ( ArrayInt . D1 ) varArray ) . set ( 0 , 0 ) ; timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; // lines and elements
 Variable lineVar = new Variable ( ncfile , null , null , "lines" ) ; lineVar . setDataType ( DataType . INT ) ; lineVar . setDimensions ( "lines" ) ; //lineVar.addAttribute(new Attribute(CDM.UNITS, "km"));
 lineVar . addAttribute ( new Attribute ( "standard_name" , "projection_y_coordinate" ) ) ; varArray = new ArrayInt . D1 ( numLines , false ) ; for ( int i = 0 ; i < numLines ; i ++ ) { int pos = nav . isFlippedLineCoordinates ( ) ? i : numLines - i - 1 ; ( ( ArrayInt . D1 ) varArray ) . set ( i , pos ) ; } lineVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , lineVar ) ; Variable elementVar = new Variable ( ncfile , null , null , "elements" ) ; elementVar . setDataType ( DataType . INT ) ; elementVar . setDimensions ( "elements" ) ; //elementVar.addAttribute(new Attribute(CDM.UNITS, "km"));
 elementVar . addAttribute ( new Attribute ( "standard_name" , "projection_x_coordinate" ) ) ; varArray = new ArrayInt . D1 ( numElements , false ) ; for ( int i = 0 ; i < numElements ; i ++ ) { ( ( ArrayInt . D1 ) varArray ) . set ( i , i ) ; } elementVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , elementVar ) ; // TODO: handle bands and calibrations
 Variable bandVar = new Variable ( ncfile , null , null , "bands" ) ; bandVar . setDataType ( DataType . INT ) ; bandVar . setDimensions ( "bands" ) ; bandVar . addAttribute ( new Attribute ( "long_name" , "spectral band number" ) ) ; bandVar . addAttribute ( new Attribute ( "axis" , "Z" ) ) ; Array bandArray = new ArrayInt . D1 ( numBands , false ) ; for ( int i = 0 ; i < numBands ; i ++ ) { ( ( ArrayInt . D1 ) bandArray ) . set ( i , bandMap [ i ] ) ; } bandVar . setCachedData ( bandArray , false ) ; ncfile . addVariable ( null , bandVar ) ; // the image
 Variable imageVar = new Variable ( ncfile , null , null , "image" ) ; imageVar . setDataType ( DataType . INT ) ; imageVar . setDimensions ( image ) ; setCalTypeAttributes ( imageVar , getCalType ( calName ) ) ; imageVar . addAttribute ( new Attribute ( getADDescription ( AreaFile . AD_CALTYPE ) , calName ) ) ; imageVar . addAttribute ( new Attribute ( "bands" , bandArray ) ) ; imageVar . addAttribute ( new Attribute ( "grid_mapping" , "AREAnav" ) ) ; ncfile . addVariable ( null , imageVar ) ; Variable dirVar = new Variable ( ncfile , null , null , "areaDirectory" ) ; dirVar . setDataType ( DataType . INT ) ; dirVar . setDimensions ( "dirSize" ) ; setAreaDirectoryAttributes ( dirVar ) ; ArrayInt . D1 dirArray = new ArrayInt . D1 ( AreaFile . AD_DIRSIZE , false ) ; for ( int i = 0 ; i < AreaFile . AD_DIRSIZE ; i ++ ) { dirArray . set ( i , dirBlock [ i ] ) ; } dirVar . setCachedData ( dirArray , false ) ; ncfile . addVariable ( null , dirVar ) ; Variable navVar = new Variable ( ncfile , null , null , "navBlock" ) ; navVar . setDataType ( DataType . INT ) ; navVar . setDimensions ( "navSize" ) ; setNavBlockAttributes ( navVar ) ; ArrayInt . D1 navArray = new ArrayInt . D1 ( navBlock . length , false ) ; for ( int i = 0 ; i < navBlock . length ; i ++ ) { navArray . set ( i , navBlock [ i ] ) ; } navVar . setCachedData ( navArray , false ) ; ncfile . addVariable ( null , navVar ) ; // projection variable
 ProjectionImpl projection = new McIDASAreaProjection ( af ) ; Variable proj = new Variable ( ncfile , null , null , "AREAnav" ) ; proj . setDataType ( DataType . CHAR ) ; proj . setDimensions ( "" ) ; for ( Parameter p : projection . getProjectionParameters ( ) ) { proj . addAttribute ( new Attribute ( p ) ) ; } // For now, we have to overwrite the parameter versions of thes
 proj . addAttribute ( new Attribute ( "grid_mapping_name" , McIDASAreaProjection . GRID_MAPPING_NAME ) ) ; /*
        proj.addAttribute(new Attribute(McIDASAreaProjection.ATTR_AREADIR,
                                        dirArray));
        proj.addAttribute(new Attribute(McIDASAreaProjection.ATTR_NAVBLOCK,
                                        navArray));
        */ varArray = new ArrayChar . D0 ( ) ; ( ( ArrayChar . D0 ) varArray ) . set ( ' ' ) ; proj . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , proj ) ; // add global attributes
 ncfile . addAttribute ( null , new Attribute ( "Conventions" , "CF-1.0" ) ) ; ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , FeatureType . GRID . toString ( ) ) ) ; ncfile . addAttribute ( null , new Attribute ( "nominal_image_time" , df . toDateTimeString ( nomTime ) ) ) ; String encStr = "netCDF encoded on " + df . toDateTimeString ( new Date ( ) ) ; ncfile . addAttribute ( null , new Attribute ( "history" , encStr ) ) ; //Lastly, finish the file
 ncfile . finish ( ) ; return true ; }


Input:
Check to see if this is a valid AREA file . [CODESPLIT] public static boolean isValidFile ( RandomAccessFile raf ) { String fileName = raf . getLocation ( ) ; AreaFile af = null ; try { af = new AreaFile ( fileName ) ; // LOOK opening again not ok for isValidFile
 return true ; } catch ( AreaFileException e ) { return false ; // barfola
 } finally { if ( af != null ) af . close ( ) ; // LOOK need to look at this code
 } }


Input:
Read the values for a variable [CODESPLIT] public Array readVariable ( Variable v2 , Section section ) throws IOException , InvalidRangeException { // not sure why timeRange isn't used...will comment out
 // for now
 // TODO: use timeRange in readVariable
 //Range timeRange = null;
 Range bandRange = null ; Range geoXRange = null ; Range geoYRange = null ; Array dataArray ; if ( section == null ) { dataArray = Array . factory ( v2 . getDataType ( ) , v2 . getShape ( ) ) ; } else if ( section . getRank ( ) > 0 ) { if ( section . getRank ( ) > 3 ) { //timeRange = (Range) section.getRange(0);
 bandRange = section . getRange ( 1 ) ; geoYRange = section . getRange ( 2 ) ; geoXRange = section . getRange ( 3 ) ; } else if ( section . getRank ( ) > 2 ) { //timeRange = (Range) section.getRange(0);
 geoYRange = section . getRange ( 1 ) ; geoXRange = section . getRange ( 2 ) ; } else if ( section . getRank ( ) > 1 ) { geoYRange = section . getRange ( 0 ) ; geoXRange = section . getRange ( 1 ) ; } dataArray = Array . factory ( v2 . getDataType ( ) , section . getShape ( ) ) ; } else { String strRank = Integer . toString ( section . getRank ( ) ) ; String msg = "Invalid Rank: " + strRank + ". Must be > 0." ; throw new IndexOutOfBoundsException ( msg ) ; } String varname = v2 . getFullName ( ) ; Index dataIndex = dataArray . getIndex ( ) ; if ( varname . equals ( "latitude" ) || varname . equals ( "longitude" ) ) { double [ ] [ ] pixel = new double [ 2 ] [ 1 ] ; double [ ] [ ] latLon ; assert geoXRange != null ; assert geoYRange != null ; // Use Range object, which calculates requested i, j
 // values and incorporates stride
 for ( int i = 0 ; i < geoXRange . length ( ) ; i ++ ) { for ( int j = 0 ; j < geoYRange . length ( ) ; j ++ ) { pixel [ 0 ] [ 0 ] = ( double ) geoXRange . element ( i ) ; pixel [ 1 ] [ 0 ] = ( double ) geoYRange . element ( j ) ; latLon = nav . toLatLon ( pixel ) ; if ( varname . equals ( "lat" ) ) { dataArray . setFloat ( dataIndex . set ( j , i ) , ( float ) ( latLon [ 0 ] [ 0 ] ) ) ; } else { dataArray . setFloat ( dataIndex . set ( j , i ) , ( float ) ( latLon [ 1 ] [ 0 ] ) ) ; } } } } if ( varname . equals ( "image" ) ) { try { int [ ] [ ] pixelData ; if ( bandRange != null ) { for ( int k = 0 ; k < bandRange . length ( ) ; k ++ ) { int bandIndex = bandRange . element ( k ) + 1 ; // band numbers in McIDAS are 1 based
 for ( int j = 0 ; j < geoYRange . length ( ) ; j ++ ) { for ( int i = 0 ; i < geoXRange . length ( ) ; i ++ ) { pixelData = af . getData ( geoYRange . element ( j ) , geoXRange . element ( i ) , 1 , 1 , bandIndex ) ; dataArray . setInt ( dataIndex . set ( 0 , k , j , i ) , ( pixelData [ 0 ] [ 0 ] ) ) ; } } } } else { assert geoXRange != null ; assert geoYRange != null ; for ( int j = 0 ; j < geoYRange . length ( ) ; j ++ ) { for ( int i = 0 ; i < geoXRange . length ( ) ; i ++ ) { pixelData = af . getData ( geoYRange . element ( j ) , geoXRange . element ( i ) , 1 , 1 ) ; dataArray . setInt ( dataIndex . set ( 0 , j , i ) , ( pixelData [ 0 ] [ 0 ] ) ) ; } } } } catch ( AreaFileException afe ) { throw new IOException ( afe . toString ( ) ) ; } } return dataArray ; }


Input: Set the area directory attributes on the variable [CODESPLIT] private void setAreaDirectoryAttributes ( Variable v ) { if ( ( dirBlock == null ) || ( ad == null ) ) { return ; } for ( int i = 1 ; i < 14 ; i ++ ) { if ( i == 7 ) { continue ; } v . addAttribute ( new Attribute ( getADDescription ( i ) , dirBlock [ i ] ) ) ; } }


Input: Set the navigation block attributes on the variable [CODESPLIT] private void setNavBlockAttributes ( Variable v ) { if ( ( navBlock == null ) || ( ad == null ) ) { return ; } v . addAttribute ( new Attribute ( "navigation_type" , McIDASUtil . intBitsToString ( navBlock [ 0 ] ) ) ) ; }


Input: Get a description for a particular Area Directory entry [CODESPLIT] private String getADDescription ( int index ) { String desc = "dir(" + index + ")" ; switch ( index ) { case AreaFile . AD_STATUS : desc = "relative position of the image object in the ADDE dataset" ; break ; case AreaFile . AD_VERSION : desc = "AREA version" ; break ; case AreaFile . AD_SENSORID : desc = "SSEC sensor source number" ; break ; case AreaFile . AD_IMGDATE : desc = "nominal year and Julian day of the image (yyyddd)" ; break ; case AreaFile . AD_IMGTIME : desc = "nominal time of the image (hhmmss)" ; break ; case AreaFile . AD_STLINE : desc = "upper-left image line coordinate" ; break ; case AreaFile . AD_STELEM : desc = "upper-left image element coordinate" ; break ; case AreaFile . AD_NUMLINES : desc = "number of lines in the image" ; break ; case AreaFile . AD_NUMELEMS : desc = "number of data points per line" ; break ; case AreaFile . AD_DATAWIDTH : desc = "number of bytes per data point" ; break ; case AreaFile . AD_LINERES : desc = "line resolution" ; break ; case AreaFile . AD_ELEMRES : desc = "element resolution" ; break ; case AreaFile . AD_NUMBANDS : desc = "number of spectral bands" ; break ; case AreaFile . AD_PFXSIZE : desc = "length of the line prefix" ; break ; case AreaFile . AD_PROJNUM : desc = "SSEC project number used when creating the file" ; break ; case AreaFile . AD_CRDATE : desc = "year and Julian day the image file was created (yyyddd)" ; break ; case AreaFile . AD_CRTIME : desc = "image file creation time (hhmmss)" ; break ; case AreaFile . AD_BANDMAP : desc = "spectral band map: bands 1-32" ; break ; case AreaFile . AD_DATAOFFSET : desc = "byte offset to the start of the data block" ; break ; case AreaFile . AD_NAVOFFSET : desc = "byte offset to the start of the navigation block" ; break ; case AreaFile . AD_VALCODE : desc = "validity code" ; break ; case AreaFile . AD_STARTDATE : desc = "actual image start year and Julian day (yyyddd)" ; break ; case AreaFile . AD_STARTTIME : desc = "actual image start time (hhmmss) in milliseconds for POES data" ; break ; case AreaFile . AD_STARTSCAN : desc = "actual image start scan" ; break ; case AreaFile . AD_DOCLENGTH : desc = "length of the prefix documentation" ; break ; case AreaFile . AD_CALLENGTH : desc = "length of the prefix calibration" ; break ; case AreaFile . AD_LEVLENGTH : desc = "length of the prefix band list" ; break ; case AreaFile . AD_SRCTYPE : desc = "source type" ; break ; case AreaFile . AD_CALTYPE : desc = "calibration type" ; break ; case AreaFile . AD_SRCTYPEORIG : desc = "original source type" ; break ; case AreaFile . AD_CALTYPEUNIT : desc = "calibration unit" ; break ; case AreaFile . AD_CALTYPESCALE : desc = "calibration scaling" ; break ; case AreaFile . AD_AUXOFFSET : desc = "byte offset to the supplemental block" ; break ; case AreaFile . AD_CALOFFSET : desc = "byte offset to the calibration block" ; break ; case AreaFile . AD_NUMCOMMENTS : desc = "number of comment cards" ; break ; } desc = desc . replaceAll ( "\\s" , "_" ) ; return desc ; }


Input: Get the calibration type from the name [CODESPLIT] private int getCalType ( String calName ) { int calTypeOut = Calibrator . CAL_NONE ; if ( calName . trim ( ) . equals ( "ALB" ) ) { calTypeOut = Calibrator . CAL_ALB ; } else if ( calName . trim ( ) . equals ( "BRIT" ) ) { calTypeOut = Calibrator . CAL_BRIT ; } else if ( calName . trim ( ) . equals ( "RAD" ) ) { calTypeOut = Calibrator . CAL_RAD ; } else if ( calName . trim ( ) . equals ( "RAW" ) ) { calTypeOut = Calibrator . CAL_RAW ; } else if ( calName . trim ( ) . equals ( "TEMP" ) ) { calTypeOut = Calibrator . CAL_TEMP ; } return calTypeOut ; }


Input:
Set the long name and units for the calibration type [CODESPLIT] private void setCalTypeAttributes ( Variable image , int calType ) { String longName = "image values" ; //String unit     = "";
 switch ( calType ) { case Calibrator . CAL_ALB : longName = "albedo" ; //unit     = "%";
 break ; case Calibrator . CAL_BRIT : longName = "brightness values" ; break ; case Calibrator . CAL_TEMP : longName = "temperature" ; //unit     = "K";
 break ; case Calibrator . CAL_RAD : longName = "pixel radiance values" ; //unit     = "mW/m2/sr/cm-1";
 break ; case Calibrator . CAL_RAW : longName = "raw image values" ; break ; default : break ; } image . addAttribute ( new Attribute ( "long_name" , longName ) ) ; if ( calUnit != null ) { image . addAttribute ( new Attribute ( CDM . UNITS , calUnit ) ) ; } if ( calScale != 1.f ) { image . addAttribute ( new Attribute ( "scale_factor" , calScale ) ) ; } }


Input: search for Axis by Type assign to TableConfig if found . search for Lat Lon Time Height . [CODESPLIT] static public void findCoords ( TableConfig nt , NetcdfDataset ds , Predicate p ) { nt . lat = findCoordShortNameByType ( ds , AxisType . Lat , p ) ; nt . lon = findCoordShortNameByType ( ds , AxisType . Lon , p ) ; nt . time = findCoordShortNameByType ( ds , AxisType . Time , p ) ; nt . elev = findCoordShortNameByType ( ds , AxisType . Height , p ) ; if ( nt . elev == null ) nt . elev = findCoordShortNameByType ( ds , AxisType . Pressure , p ) ; }


Input: search for Axis by Type . [CODESPLIT] static public String findCoordNameByType ( NetcdfDataset ds , AxisType atype ) { CoordinateAxis coordAxis = findCoordByType ( ds , atype ) ; return coordAxis == null ? null : coordAxis . getFullName ( ) ; }


Input: Search for Axis by Type . [CODESPLIT] static public CoordinateAxis findCoordByType ( NetcdfDataset ds , AxisType atype ) { return findCoordByType ( ds , atype , null ) ; }


Input:
search for Axis by Type and test against a predicate [CODESPLIT] static public CoordinateAxis findCoordByType ( NetcdfDataset ds , AxisType atype , Predicate p ) { // try the "best" coordinate system
 CoordinateSystem use = findBestCoordinateSystem ( ds ) ; if ( use == null ) return null ; CoordinateAxis result = findCoordByType ( use . getCoordinateAxes ( ) , atype , p ) ; if ( result != null ) return result ; // try all the axes
 return findCoordByType ( ds . getCoordinateAxes ( ) , atype , p ) ; }


Input: search for Dimension used by axis of given by Type . [CODESPLIT] static public Dimension findDimensionByType ( NetcdfDataset ds , AxisType atype ) { CoordinateAxis axis = findCoordByType ( ds , atype ) ; if ( axis == null ) return null ; if ( axis . isScalar ( ) ) return null ; return axis . getDimension ( 0 ) ; }


Input:
Find the CoordinateSystem with the most number of CoordinateAxes [CODESPLIT] static private CoordinateSystem findBestCoordinateSystem ( NetcdfDataset ds ) { // find coordinate system with highest rank (largest number of axes)
 CoordinateSystem use = null ; for ( CoordinateSystem cs : ds . getCoordinateSystems ( ) ) { if ( use == null ) use = cs ; else if ( cs . getCoordinateAxes ( ) . size ( ) > use . getCoordinateAxes ( ) . size ( ) ) use = cs ; } return use ; }


Input: find the dependent axis that depend on independentAxis [CODESPLIT] private CoverageCoordAxis1D findDependent ( CoverageCoordAxis independentAxis , AxisType axisType ) { for ( CoverageCoordAxis axis : axes ) { if ( axis . getDependenceType ( ) == CoverageCoordAxis . DependenceType . dependent ) { for ( String axisName : axis . dependsOn ) { if ( axisName . equalsIgnoreCase ( independentAxis . getName ( ) ) && axis . getAxisType ( ) == axisType ) return ( CoverageCoordAxis1D ) axis ; } } } return null ; }


Input: Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] @ Override public void setProject ( boolean state , boolean all ) { super . setProject ( state , all ) ; if ( all ) for ( Enumeration e = vars . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; sm . setProject ( state , all ) ; } }


Input: Get the row vector for into which to read a row os data for this sequence . When serving sequence data to clients the prefered method is to read one row of the sequence at a time in to this vector evaluate the constraint expression clauses on the current data and then send it to the client if it satisfies the constraint . The NOT recomended way is to read the ENTIRE sequence into memory prior to sending it ( that would be most inefficient ) . [CODESPLIT] public Vector getRowVector ( ) throws NoSuchVariableException { if ( getRowCount ( ) == 0 ) { if ( _Debug ) System . out . println ( "This sequence has " + getRowCount ( ) + " rows." ) ; Vector rv = new Vector ( ) ; for ( int i = 0 ; i < elementCount ( false ) ; i ++ ) { if ( _Debug ) System . out . println ( "Building variable " + i + ": " + getVar ( i ) . getEncodedName ( ) ) ; rv . add ( getVar ( i ) ) ; } if ( _Debug ) System . out . println ( "Adding row to sequence..." ) ; addRow ( rv ) ; } return ( getRow ( 0 ) ) ; }


Input: Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType // and all of the different signatures of printDecl() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. // Also, since printDecl()is (multiple) overloaded in BaseType and // all of the different signatures of printDecl() in BaseType lead to // the signature we are overriding here, we MUST call the printDecl // with the SAME signature THROUGH the super class reference // (assuming we want the super class functionality). If we do // otherwise, we will create an infinte call loop. OOPS! // If we are constrained, make sure some part of this thing is projected if ( constrained && ! isProject ( ) ) return ; super . printDecl ( os , space , print_semi , constrained ) ; }


Input:
Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl .

 Important Note
 This method overrides the BaseType method of the same name and type signature and it significantly changes the behavior for all versions of  printVal ()  for this type :   All the various versions of printVal () will only print a value or a value with declaration if the variable is in the projection .

 In other words if a call to  isProject ()  for a particular variable returns  true then  printVal ()  will print a value ( or a declaration and a value ) .

 If  isProject ()  for a particular variable returns  false then  printVal ()  is basically a No - Op .

 [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; if ( print_decl_p ) { printDecl ( os , space , false , true ) ; os . print ( " = " ) ; } os . print ( "{ " ) ; try { boolean firstPass = true ; Vector v = getRowVector ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable BaseType bt = ( BaseType ) e2 . nextElement ( ) ; if ( ( ( ServerMethods ) bt ) . isProject ( ) ) { if ( ! firstPass ) os . print ( ", " ) ; bt . printVal ( os , "" , false ) ; firstPass = false ; } } } catch ( NoSuchVariableException e ) { os . println ( "Very Bad Things Happened When I Tried To Print " + "A Row Of The Sequence: " + getEncodedName ( ) ) ; } os . print ( " }" ) ; if ( print_decl_p ) os . println ( ";" ) ; }


Input: Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] @ Override public void setProject ( boolean state , boolean all ) { setProjected ( state ) ; if ( all ) for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; sm . setProject ( state ) ; } }


Input: Set the Read property . A normal variable is read using the <code > read () < / code > method . Once read the <em > Read< / em > property is <code > true< / code > . Use this function to manually set the property value . By default this property is false . [CODESPLIT] public void setAllReadFlags ( boolean state ) { ReadMe = state ; for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; //System.out.println("Setting Read Flag for "+((BaseType)sm).getName()+" to "+state); sm . setRead ( state ) ; } }


Input: Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . <p > <p / > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { boolean moreToRead = true ; while ( moreToRead ) { if ( ! isRead ( ) ) { // ************* Pulled out the getLevel() check in order to support the "new" // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp //                if(getLevel() != 0 )  // Read only the outermost level //                    return; moreToRead = read ( dataset , specialO ) ; } //System.out.println("Evaluating Clauses..."); if ( ce . evalClauses ( specialO ) ) { //System.out.println("Clauses evaluated true"); // ************* Pulled out the getLevel() check in order to support the "new" // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp //                if(getLevel() == 0){ writeMarker ( sink , START_OF_INSTANCE ) ; //                } for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; if ( sm . isProject ( ) ) { if ( _Debug ) System . out . println ( "Sending variable: " + ( ( BaseType ) sm ) . getEncodedName ( ) ) ; sm . serialize ( dataset , sink , ce , specialO ) ; } } } if ( moreToRead ) setAllReadFlags ( false ) ; } // ************* Pulled out the getLevel() check in order to support the "new" // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp //        if(getLevel() == 0){ writeMarker ( sink , END_OF_SEQUENCE ) ; //        } return ; }


Input: Adds a variable to the container . [CODESPLIT] public void addVariable ( BaseType v , int part ) { v . setParent ( this ) ; varTemplate . addElement ( v ) ; if ( v instanceof DSequence ) ( ( DSequence ) v ) . setLevel ( getLevel ( ) + 1 ) ; }


Input:
Returns the named variable . <b > Note : < / b > In <code > DSequence< / code > this method returns the template variable which holds no data . If you need to get a variable containing data use <code > getRow< / code > or the <code > getVariable< / code > method which takes a row number parameter . [CODESPLIT] public BaseType getVariable ( String name ) throws NoSuchVariableException { int dotIndex = name . indexOf ( ' ' ) ; if ( dotIndex != - 1 ) { // name contains "."
 String aggregate = name . substring ( 0 , dotIndex ) ; String field = name . substring ( dotIndex + 1 ) ; BaseType aggRef = getVariable ( aggregate ) ; if ( aggRef instanceof DConstructor ) return ( ( DConstructor ) aggRef ) . getVariable ( field ) ; // recurse
 else ; // fall through to throw statement
 } else { for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType v = ( BaseType ) e . nextElement ( ) ; if ( v . getEncodedName ( ) . equals ( name ) ) return v ; } } throw new NoSuchVariableException ( "DSequence: getVariable()" ) ; }


Input: Gets the indexed variable . For a DSrquence this returns the <code > BaseType< / code > from the <code > index< / code > th column from the internal map <code > Vector< / code > . [CODESPLIT] public BaseType getVar ( int index ) throws NoSuchVariableException { if ( index < varTemplate . size ( ) ) return ( ( BaseType ) varTemplate . elementAt ( index ) ) ; else throw new NoSuchVariableException ( "DSequence.getVariable(" + index + " - 1)" ) ; }


Input:
Returns the named variable in the given row of the sequence . [CODESPLIT] public BaseType getVariable ( int row , String name ) throws NoSuchVariableException { int dotIndex = name . indexOf ( ' ' ) ; if ( dotIndex != - 1 ) { // name contains "."
 String aggregate = name . substring ( 0 , dotIndex ) ; String field = name . substring ( dotIndex + 1 ) ; BaseType aggRef = getVariable ( aggregate ) ; if ( aggRef instanceof DConstructor ) return ( ( DConstructor ) aggRef ) . getVariable ( field ) ; // recurse
 else ; // fall through to throw statement
 } else { Vector selectedRow = ( Vector ) allValues . elementAt ( row ) ; for ( Enumeration e = selectedRow . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType v = ( BaseType ) e . nextElement ( ) ; if ( v . getEncodedName ( ) . equals ( name ) ) return v ; } } throw new NoSuchVariableException ( "DSequence: getVariable()" ) ; }