signature:
public class FileCache { /** * Acquire a FileCacheable , and lock it so no one else can use it .
 * call FileCacheable . close when done .
 * @ param factory use this factory to open the file ; may not be null
 * @ param durl file location , also used as the cache name , will be passed to the NetcdfFileFactory
 * @ param cancelTask user can cancel , ok to be null .
 * @ return NetcdfFile corresponding to location .
 * @ throws IOException on error */
public FileCacheable acquire ( FileFactory factory , DatasetUrl durl , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { } }

implementation: return acquire ( factory , durl . trueurl , durl , - 1 , cancelTask , null ) ;


signature:
public class FileCache { /** * Acquire a FileCacheable from the cache , and lock it so no one else can use it .
 * If not already in cache , open it the FileFactory , and put in cache .
 * App should call FileCacheable . close when done , and the file is then released instead of closed .
 * If cache size goes over maxElement , then immediately ( actually in 100 msec ) schedule a cleanup in a background thread .
 * This means that the cache should never get much larger than maxElement , unless you have them all locked .
 * @ param factory use this factory to open the file if not in the cache ; may not be null
 * @ param hashKey unique key for this file . If null , the location will be used
 * @ param location file location , may also used as the cache name , will be passed to the NetcdfFileFactory
 * @ param buffer _ size RandomAccessFile buffer size , if < = 0 , use default size
 * @ param cancelTask user can cancel , ok to be null .
 * @ param spiObject passed to the factory if object needs to be recreated
 * @ return FileCacheable corresponding to location .
 * @ throws IOException on error */
@ Override public FileCacheable acquire ( FileFactory factory , Object hashKey , DatasetUrl location , int buffer_size , CancelTask cancelTask , Object spiObject ) throws IOException { } }

implementation:
if ( null == hashKey ) hashKey = location . trueurl ; if ( null == hashKey ) throw new IllegalArgumentException ( ) ; Tracker t = null ; if ( trackAll ) { t = new Tracker ( hashKey ) ; Tracker prev = track . putIfAbsent ( hashKey , t ) ; if ( prev != null ) t = prev ; } FileCacheable ncfile = acquireCacheOnly ( hashKey ) ; if ( ncfile != null ) { hits . incrementAndGet ( ) ; if ( t != null ) t . hit ++ ; return ncfile ; } miss . incrementAndGet ( ) ; if ( t != null ) t . miss ++ ; // open the file
ncfile = factory . open ( location , buffer_size , cancelTask , spiObject ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCache " + name + " acquire " + hashKey + " " + ncfile . getLocation ( ) ) ; if ( debugPrint ) System . out . println ( "  FileCache " + name + " acquire " + hashKey + " " + ncfile . getLocation ( ) ) ; // user may have canceled
if ( ( cancelTask != null ) && ( cancelTask . isCancel ( ) ) ) { if ( ncfile != null ) ncfile . close ( ) ; // LOOK ? ?
return null ; } if ( disabled . get ( ) ) return ncfile ; // see if cache element already exists
// cant use putIfAbsent , because we cant create the CacheElement until we know if doesnt exist
CacheElement elem ; synchronized ( cache ) { elem = cache . get ( hashKey ) ; if ( elem == null ) cache . put ( hashKey , new CacheElement ( ncfile , hashKey ) ) ; // new element
} // already exists , add to list
if ( elem != null ) { synchronized ( elem ) { elem . addFile ( ncfile ) ; // add to existing list
} } // increment the number of files in the cache
// int count = counter . incrementAndGet ( ) ;
// do we need a cleanup ? ?
boolean needHard = false ; boolean needSoft = false ; synchronized ( hasScheduled ) { if ( ! hasScheduled . get ( ) ) { int count = files . size ( ) ; if ( ( count > hardLimit ) && ( hardLimit > 0 ) ) { needHard = true ; hasScheduled . getAndSet ( true ) ; // tell other threads not to schedule another cleanup
} else if ( ( count > softLimit ) && ( softLimit > 0 ) ) { // & & wantsCleanup ) { / /
hasScheduled . getAndSet ( true ) ; // tell other threads not to schedule another cleanup
needSoft = true ; } } } if ( needHard ) { if ( debugCleanup ) System . out . println ( "CleanupTask due to hard limit time=" + new Date ( ) . getTime ( ) ) ; // + " Thread = " + Thread . currentThread ( ) . hashCode ( )
cleanup ( hardLimit ) ; } else if ( needSoft ) { schedule ( new CleanupTask ( ) , 100 ) ; // immediate cleanup in 100 msec
if ( debugCleanup ) System . out . println ( "CleanupTask scheduled due to soft limit time=" + new Date ( ) ) ; } return ncfile ;


signature:
public class FileCache { /** * Try to find a file in the cache .
 * @ param hashKey used as the key .
 * @ return file if its in the cache , null otherwise . */
private FileCacheable acquireCacheOnly ( Object hashKey ) { } }

implementation:
if ( disabled . get ( ) ) return null ; // see if its in the cache
CacheElement wantCacheElem = cache . get ( hashKey ) ; if ( wantCacheElem == null ) return null ; // not found in cache
CacheElement . CacheFile want = null ; synchronized ( wantCacheElem ) { // synch in order to traverse the list
for ( CacheElement . CacheFile file : wantCacheElem . list ) { if ( file . isLocked . compareAndSet ( false , true ) ) { want = file ; break ; } } } if ( want == null ) return null ; // no unlocked file in cache
// check if modified , remove if so
if ( want . ncfile != null ) { long lastModified = want . ncfile . getLastModified ( ) ; boolean changed = lastModified != want . lastModified ; if ( cacheLog . isDebugEnabled ( ) && changed ) cacheLog . debug ( "FileCache " + name + ": acquire from cache " + hashKey + " " + want . ncfile . getLocation ( ) + " was changed; discard" ) ; if ( changed ) { remove ( want ) ; } } if ( want . ncfile != null ) { try { want . ncfile . reacquire ( ) ; // rehydrate
} catch ( IOException ioe ) { if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCache " + name + " acquire from cache " + hashKey + " " + want . ncfile . getLocation ( ) + " failed: " + ioe . getMessage ( ) ) ; remove ( want ) ; // failed
} } if ( debugPrint && want . ncfile != null ) { System . out . printf ( "  FileCache %s found in cache %s (countLocks %d)%n" , name , hashKey , countLocked ( ) ) ; } return want . ncfile ;


signature:
public class FileCache { /** * LOOK should you remove the entire CacheElement ? */
private void remove ( CacheElement . CacheFile want ) { } }

implementation:
want . remove ( ) ; files . remove ( want . ncfile ) ; try { want . ncfile . setFileCache ( null ) ; // unhook the caching
want . ncfile . close ( ) ; } catch ( IOException e ) { log . error ( "close failed on " + want . ncfile . getLocation ( ) , e ) ; } want . ncfile = null ;


signature:
public class FileCache { /** * Remove all instances of object from the cache
 * @ param hashKey the object */
@ Override public void eject ( Object hashKey ) { } }

implementation:
if ( disabled . get ( ) ) return ; // see if its in the cache
CacheElement wantCacheElem = cache . get ( hashKey ) ; if ( wantCacheElem == null ) return ; synchronized ( wantCacheElem ) { // synch in order to traverse the list
for ( CacheElement . CacheFile want : wantCacheElem . list ) { // LOOK can we use remove ( want ) ; ? ?
files . remove ( want . ncfile ) ; try { want . ncfile . setFileCache ( null ) ; // unhook the caching
want . ncfile . close ( ) ; // really close the file
log . debug ( "close " + want . ncfile . getLocation ( ) ) ; } catch ( IOException e ) { log . error ( "close failed on " + want . ncfile . getLocation ( ) , e ) ; } want . ncfile = null ; if ( debugPrint ) System . out . println ( "  FileCache " + name + " eject " + hashKey ) ; } wantCacheElem . list . clear ( ) ; } cache . remove ( hashKey ) ;


signature:
public class FileCache { /** * Release the file . This unlocks it , updates its lastAccessed date .
 * Normally applications need not call this , just close the file as usual .
 * The FileCacheable has to do tricky stuff .
 * @ param ncfile release this file .
 * @ return true if file was in cache , false if it was not */
@ Override public boolean release ( FileCacheable ncfile ) throws IOException { } }

implementation:
if ( ncfile == null ) return false ; if ( disabled . get ( ) ) { ncfile . setFileCache ( null ) ; // prevent infinite loops
ncfile . close ( ) ; return false ; } // find it in the file cache
CacheElement . CacheFile file = files . get ( ncfile ) ; // using hashCode of the FileCacheable
if ( file != null ) { if ( ! file . isLocked . get ( ) ) { cacheLog . warn ( "FileCache " + name + " release " + ncfile . getLocation ( ) + " not locked; hash= " + ncfile . hashCode ( ) ) ; } file . lastAccessed = System . currentTimeMillis ( ) ; file . countAccessed ++ ; file . isLocked . set ( false ) ; file . ncfile . release ( ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCache " + name + " release " + ncfile . getLocation ( ) + "; hash= " + ncfile . hashCode ( ) ) ; if ( debugPrint ) System . out . printf ( "  FileCache %s release %s lock=%s count=%d%n" , name , ncfile . getLocation ( ) , file . isLocked . get ( ) , countLocked ( ) ) ; return true ; } return false ; // throw new IOException ( " FileCache " + name + " release does not have file in cache = " + ncfile . getLocation ( ) ) ;


signature:
public class FileCache { /** * debug */
public String getInfo ( FileCacheable ncfile ) throws IOException { } }

implementation:
if ( ncfile == null ) return "" ; // find it in the file cache
CacheElement . CacheFile file = files . get ( ncfile ) ; if ( file != null ) { return "File is in cache= " + file ; } return "File not in cache" ;


signature:
public class FileCache { /** * Show individual cache entries , add to formatter .
 * @ param format add to this */
@ Override public void showCache ( Formatter format ) { } }

implementation:
ArrayList < CacheElement . CacheFile > allFiles = new ArrayList < > ( files . size ( ) ) ; for ( CacheElement elem : cache . values ( ) ) { synchronized ( elem ) { allFiles . addAll ( elem . list ) ; } } Collections . sort ( allFiles ) ; // sort so oldest are on top
format . format ( "%nFileCache %s (min=%d softLimit=%d hardLimit=%d scour=%d secs):%n" , name , minElements , softLimit , hardLimit , period / 1000 ) ; format . format ( " isLocked  accesses lastAccess                   location %n" ) ; for ( CacheElement . CacheFile file : allFiles ) { String loc = file . ncfile != null ? file . ncfile . getLocation ( ) : "null" ; format . format ( "%8s %9d %s == %s %n" , file . isLocked , file . countAccessed , CalendarDateFormatter . toDateTimeStringISO ( file . lastAccessed ) , loc ) ; } showStats ( format ) ;


signature:
public class FileCache { /** * Add stat report ( hits , misses , etc ) to formatter .
 * @ param format add to this */
public void showStats ( Formatter format ) { } }

implementation: format . format ( "  hits= %d miss= %d nfiles= %d elems= %d%n" , hits . get ( ) , miss . get ( ) , files . size ( ) , cache . values ( ) . size ( ) ) ;


signature:
public class FileCache { /** * Cleanup the cache , bringing it down to minimum number .
 * Will close the LRU ( least recently used ) ones first . Will not close locked files .
 * Normally this is done in a background thread , you dont need to call .
 * We have to synchronize because of clearCache ( ) */
synchronized void cleanup ( int maxElements ) { } }

implementation:
try { /* int size = counter . get ( ) ;
 int fsize = files . size ( ) ;
 if ( debug & & ( size ! = fsize ) ) {
 log . warn ( " FileCache " + name + " counter " + size + " doesnt match files ( ) . size = " + fsize ) ; */
int size = files . size ( ) ; if ( size <= minElements ) return ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCache {} cleanup started at {} for maxElements={}" , name , CalendarDate . present ( ) , maxElements ) ; if ( debugCleanup ) System . out . printf ( " FileCache %s cleanup started at %s for maxElements=%d%n" , name , CalendarDate . present ( ) , maxElements ) ; cleanups . incrementAndGet ( ) ; // add unlocked files to the all list
List < CacheElement . CacheFile > allFiles = new ArrayList < > ( size + 10 ) ; for ( CacheElement . CacheFile file : files . values ( ) ) { if ( ! file . isLocked . get ( ) ) allFiles . add ( file ) ; } Collections . sort ( allFiles ) ; // sort so oldest are on top
// take oldest ones and put on delete list
int need2delete = size - minElements ; int minDelete = size - maxElements ; List < CacheElement . CacheFile > deleteList = new ArrayList < > ( need2delete ) ; int count = 0 ; Iterator < CacheElement . CacheFile > iter = allFiles . iterator ( ) ; while ( iter . hasNext ( ) && ( count < need2delete ) ) { CacheElement . CacheFile file = iter . next ( ) ; if ( file . isLocked . compareAndSet ( false , true ) ) { // lock it so it isnt used anywhere else
file . remove ( ) ; // remove from the containing element
deleteList . add ( file ) ; count ++ ; } } if ( count < minDelete ) { cacheLog . warn ( "FileCache " + name + " cleanup couldnt remove enough to keep under the maximum= " + maxElements + " due to locked files; currently at = " + ( size - count ) ) ; if ( debugCleanup ) System . out . println ( "FileCache " + name + " cleanup couldnt remove enough to keep under the maximum= " + maxElements + " due to locked files; currently at = " + ( size - count ) ) ; } // remove empty cache elements
synchronized ( cache ) { for ( CacheElement elem : cache . values ( ) ) { synchronized ( elem ) { if ( elem . list . size ( ) == 0 ) cache . remove ( elem . hashKey ) ; } } } // now actually close the files
long start = System . currentTimeMillis ( ) ; for ( CacheElement . CacheFile file : deleteList ) { // counter . decrementAndGet ( ) ;
if ( null == files . remove ( file . ncfile ) ) { if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( " FileCache {} cleanup failed to remove {}%n" , name , file . ncfile . getLocation ( ) ) ; } try { file . ncfile . setFileCache ( null ) ; file . ncfile . close ( ) ; file . ncfile = null ; // help the gc
} catch ( IOException e ) { log . error ( "FileCache " + name + " close failed on " + file . getCacheName ( ) ) ; } } long took = System . currentTimeMillis ( ) - start ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( " FileCache {} cleanup had={} removed={} took={} msecs%n" , name , size , deleteList . size ( ) , took ) ; if ( debugCleanup ) System . out . printf ( " FileCache %s cleanup had=%d removed=%d took=%d msecs%n" , name , size , deleteList . size ( ) , took ) ; } finally { // allow scheduling again
hasScheduled . set ( false ) ; }


signature:
public class BufrNumbers { /** * Convert 4 bytes into a signed integer .
 * @ param a
 * @ param b
 * @ param c
 * @ param d
 * @ return int */
private static int int4 ( int a , int b , int c , int d ) { } }


signature:
public class FileCacheARC { /** * Acquire a FileCacheable , and lock it so no one else can use it .
 * call FileCacheable . close ( ) when done .
 * @ param factory use this factory to open the file ; may not be null
 * @ param location file location , also used as the cache name , will be passed to the NetcdfFileFactory
 * @ return NetcdfFile corresponding to location .
 * @ throws IOException on error */
@ Override public FileCacheable acquire ( FileFactory factory , DatasetUrl location ) throws IOException { } }

implementation: return acquire ( factory , location . trueurl , location , - 1 , null , null ) ;


signature:
public class FileCacheARC { /** * Acquire a FileCacheable from the cache , and lock it so no one else can use it .
 * If not already in cache , open it with FileFactory , and put in cache .
 * Call FileCacheable . close ( ) when done , ( rather than FileCacheIF . release ( ) directly ) and the file is then released instead of closed .
 * If cache size goes over maxElement , then immediately ( actually in 100 msec ) schedule a cleanup in a background thread .
 * This means that the cache should never get much larger than maxElement , unless you have them all locked .
 * @ param factory use this factory to open the file if not in the cache ; may not be null
 * @ param hashKey unique key for this file . If null , the location will be used
 * @ param location file location , may also used as the cache name , will be passed to the NetcdfFileFactory
 * @ param buffer _ size RandomAccessFile buffer size , if < = 0 , use default size
 * @ param cancelTask user can cancel , ok to be null .
 * @ param spiObject sent to iosp . setSpecial ( ) if not null
 * @ return FileCacheable corresponding to location .
 * @ throws IOException on error */
@ Override public FileCacheable acquire ( FileFactory factory , Object hashKey , DatasetUrl location , int buffer_size , CancelTask cancelTask , Object spiObject ) throws IOException { } }

implementation:
if ( null == hashKey ) hashKey = location . trueurl ; if ( null == hashKey ) throw new IllegalArgumentException ( ) ; Tracker t = null ; if ( trackAll ) { t = new Tracker ( hashKey ) ; Tracker prev = track . putIfAbsent ( hashKey , t ) ; if ( prev != null ) t = prev ; } FileCacheable ncfile = acquireCacheOnly ( hashKey ) ; if ( ncfile != null ) { hits . incrementAndGet ( ) ; if ( t != null ) t . hit ++ ; return ncfile ; } miss . incrementAndGet ( ) ; if ( t != null ) t . miss ++ ; // open the file
ncfile = factory . open ( location , buffer_size , cancelTask , spiObject ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCacheARC " + name + " acquire " + hashKey + " " + ncfile . getLocation ( ) ) ; if ( debugPrint ) System . out . println ( "  FileCacheARC " + name + " acquire " + hashKey + " " + ncfile . getLocation ( ) ) ; // user may have canceled
if ( ( cancelTask != null ) && ( cancelTask . isCancel ( ) ) ) { if ( ncfile != null ) ncfile . close ( ) ; return null ; } if ( disabled . get ( ) ) return ncfile ; addToCache ( hashKey , ncfile ) ; return ncfile ;


signature:
public class FileCacheARC { /** * Try to find a file in the cache .
 * @ param hashKey used as the key .
 * @ return file if its in the cache , null otherwise . */
private FileCacheable acquireCacheOnly ( Object hashKey ) { } }

implementation:
if ( disabled . get ( ) ) return null ; // see if its in the cache
CacheElement wantCacheElem = cache . get ( hashKey ) ; if ( wantCacheElem == null ) return null ; // not found in cache
CacheElement . CacheFile want = null ; for ( CacheElement . CacheFile file : wantCacheElem . list ) { if ( file . isLocked . compareAndSet ( false , true ) ) { want = file ; break ; } } if ( want == null ) return null ; // no unlocked file in cache
// check if modified , remove if so
if ( want . ncfile != null ) { long lastModified = want . ncfile . getLastModified ( ) ; boolean changed = lastModified != wantCacheElem . lastModified . get ( ) ; if ( changed ) { // underlying file was modified
if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCacheARC " + name + ": acquire from cache " + hashKey + " " + want . ncfile . getLocation ( ) + " was changed; discard" ) ; expireFromCache ( wantCacheElem ) ; return null ; } } updateInCache ( wantCacheElem ) ; return want . ncfile ;


signature:
public class FileCacheARC { /** * get CacheElement specified by hashKey . If found , update lastUsed in shadowCache . */
private CacheElement updateInCache ( CacheElement elem ) { } }

implementation:
if ( shadowCache . firstKey ( ) == elem ) return elem ; elem . updateAccessed ( ) ; CacheElement prev = shadowCache . put ( elem , elem ) ; // faster if we could just insert at the top of the list . maybe we need to use LinkedList ?
if ( prev != null && ( elem != prev ) ) { CacheElementComparator cc = new CacheElementComparator ( ) ; System . out . printf ( "elem != prev compare=%d%n" , cc . compare ( elem , prev ) ) ; System . out . printf ( "hash elem =%d prev=%d%n" , elem . hashCode ( ) , prev . hashCode ( ) ) ; } return elem ;


signature:
public class FileCacheARC { /** * if ( disabled . get ( ) ) return ;
 * see if its in the cache
 * CacheElement wantCacheElem = cache . get ( hashKey ) ;
 * if ( wantCacheElem = = null ) return ;
 * synchronized ( wantCacheElem ) { / / synch in order to traverse the list
 * for ( CacheElement . CacheFile want : wantCacheElem . list ) {
 * files . remove ( want . ncfile ) ;
 * want . ncfile . setFileCache ( null ) ; / / unhook the caching
 * try {
 * want . ncfile . close ( ) ; / / really close the file
 * log . debug ( " close " + want . ncfile . getLocation ( ) ) ;
 * } catch ( IOException e ) {
 * log . error ( " close failed on " + want . ncfile . getLocation ( ) , e ) ;
 * want . ncfile = null ;
 * wantCacheElem . list . clear ( ) ;
 * cache . remove ( hashKey ) ; */
private void addToCache ( Object hashKey , FileCacheable ncfile ) { } }

implementation:
CacheElement newCacheElem = new CacheElement ( hashKey ) ; CacheElement previous = cache . putIfAbsent ( hashKey , newCacheElem ) ; // add new element if doesnt exist
CacheElement elem = ( previous != null ) ? previous : newCacheElem ; // use previous if it exists
elem . addFile ( ncfile ) ; // add to existing list
shadowCache . put ( newCacheElem , newCacheElem ) ; int size = cacheSize . getAndIncrement ( ) ; if ( size > softLimit ) { removeFromCache ( size - softLimit ) ; }


signature:
public class FileCacheARC { /** * Release the file . This unlocks it , updates its lastAccessed date .
 * FileCacheable . close ( ) needs to call this instead of actually closing .
 * @ param ncfile release the lock on this FileCacheable object .
 * @ throws IOException if file not in cache . */
@ Override public boolean release ( FileCacheable ncfile ) throws IOException { } }

implementation:
if ( ncfile == null ) return false ; if ( disabled . get ( ) ) { ncfile . setFileCache ( null ) ; // prevent infinite loops
ncfile . close ( ) ; return false ; } // find it in the file cache
int hashcode = System . identityHashCode ( ncfile ) ; // using Object hashCode of the FileCacheable
CacheElement . CacheFile file = files . get ( hashcode ) ; if ( file != null ) { if ( ! file . isLocked . get ( ) ) { Exception e = new Exception ( "Stack trace" ) ; cacheLog . warn ( "FileCacheARC " + name + " release " + ncfile . getLocation ( ) + " not locked; hash= " + ncfile . hashCode ( ) , e ) ; } // file . lastAccessed = System . currentTimeMillis ( ) ;
// file . countAccessed + + ;
file . isLocked . set ( false ) ; if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "FileCacheARC " + name + " release " + ncfile . getLocation ( ) + "; hash= " + ncfile . hashCode ( ) ) ; if ( debugPrint ) System . out . println ( "  FileCacheARC " + name + " release " + ncfile . getLocation ( ) ) ; return true ; } return false ; // throw new IOException ( " FileCacheARC " + name + " release does not have file in cache = " + ncfile . getLocation ( ) ) ;


signature:
public class FileCacheARC { /** * debug */
public String getInfo ( FileCacheable ncfile ) throws IOException { } }

implementation:
if ( ncfile == null ) return "" ; // find it in the file cache
int hashcode = System . identityHashCode ( ncfile ) ; CacheElement . CacheFile file = files . get ( hashcode ) ; if ( file != null ) { return "File is in cache= " + file ; } return "File not in cache" ;


signature:
public class FileCacheARC { /** * Remove all cache entries .
 * @ param force if true , remove them even if they are currently locked . */
public synchronized void clearCache ( boolean force ) { } }

implementation:
List < CacheElement . CacheFile > deleteList = new ArrayList < > ( 2 * cache . size ( ) ) ; if ( force ) { cache . clear ( ) ; // deletes everything from the cache
deleteList . addAll ( files . values ( ) ) ; // add everything to the delete list
files . clear ( ) ; // counter . set ( 0 ) ;
} else { // add unlocked files to the delete list , remove from files hash
Iterator < CacheElement . CacheFile > iter = files . values ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { CacheElement . CacheFile file = iter . next ( ) ; if ( file . isLocked . compareAndSet ( false , true ) ) { file . remove ( ) ; // remove from the containing CacheElement
deleteList . add ( file ) ; iter . remove ( ) ; } } // remove empty cache elements
for ( CacheElement elem : cache . values ( ) ) { if ( elem . list . size ( ) == 0 ) cache . remove ( elem . hashKey ) ; } } // close all files in deleteList
for ( CacheElement . CacheFile file : deleteList ) { if ( force && file . isLocked . get ( ) ) cacheLog . warn ( "FileCacheARC " + name + " force close locked file= " + file ) ; // counter . decrementAndGet ( ) ;
if ( file . ncfile == null ) continue ; try { file . ncfile . setFileCache ( null ) ; file . ncfile . close ( ) ; file . ncfile = null ; // help the gc
} catch ( IOException e ) { log . error ( "FileCacheARC " + name + " close failed on " + file ) ; } } if ( cacheLog . isDebugEnabled ( ) ) cacheLog . debug ( "*FileCacheARC " + name + " clearCache force= " + force + " deleted= " + deleteList . size ( ) + " left=" + files . size ( ) ) ; // System . out . println ( " \ n * NetcdfFileCache . clearCache force = " + force + " deleted = " + deleteList . size ( ) + " left = " + counter . get ( ) ) ;


signature:
public class FileCacheARC { /** * Show individual cache entries , add to formatter .
 * @ param format add to this */
@ Override public void showCache ( Formatter format ) { } }

implementation:
ArrayList < CacheElement . CacheFile > allFiles = new ArrayList < > ( files . size ( ) ) ; for ( CacheElement elem : cache . values ( ) ) { allFiles . addAll ( elem . list ) ; } Collections . sort ( allFiles ) ; // sort so oldest are on top
format . format ( "%nFileCacheARC %s (min=%d softLimit=%d hardLimit=%d scour=%d):%n" , name , minElements , softLimit , hardLimit , period ) ; format . format ( "isLocked  accesses lastAccess                   location %n" ) ; for ( CacheElement . CacheFile file : allFiles ) { String loc = file . ncfile != null ? file . ncfile . getLocation ( ) : "null" ; CalendarDate cd = CalendarDate . of ( file . getLastAccessed ( ) ) ; format . format ( "%8s %9d %s %s %n" , file . isLocked , file . getCountAccessed ( ) , CalendarDateFormatter . toTimeUnits ( cd ) , loc ) ; } showStats ( format ) ;


signature: public class FileCacheARC { public void showTracking ( Formatter format ) { } }

implementation:
if ( track == null ) return ; List < Tracker > all = new ArrayList < > ( track . size ( ) ) ; for ( Tracker val : track . values ( ) ) all . add ( val ) ; Collections . sort ( all ) ; // LOOK what should we sort by ? ?
int count = 0 ; int countAll = 0 ; format . format ( "%nTrack of all files in FileCacheARC%n" ) ; format . format ( "   seq  accum   hit   miss  file%n" ) ; for ( Tracker t : all ) { count ++ ; countAll += t . hit + t . miss ; format . format ( "%6d  %6d : %5d %5d %s%n" , count , countAll , t . hit , t . miss , t . key ) ; } format . format ( "%n" ) ;


signature:
public class Dap2Parser { /** * / * the parse function allows the specification of a
 * new stream in case one is reusing the parser */
public boolean parse ( String input ) throws ParseException { } }

implementation: ( ( Dap2Lex ) yylexer ) . reset ( parsestate ) ; ( ( Dap2Lex ) yylexer ) . setText ( input ) ; return parse ( ) ;


signature:
public class GridCoordSys { /** * Determine if this CoordinateSystem can be made into a GridCoordSys . Optionally for a given variable .
 * This currently assumes that the CoordinateSystem :
 * < ol >
 * < li > is georeferencing ( cs . isGeoReferencing ( ) )
 * < li > x , y are 1 or 2 - dimensional axes .
 * < li > z , t , if they exist , are 1 - dimensional axes .
 * < li > domain rank > 1
 * < / ol >
 * @ param sbuff place information messages here , may be null
 * @ param cs the CoordinateSystem to test
 * @ param v can it be used for this variable ; v may be null
 * @ return true if it can be made into a GridCoordSys .
 * @ see CoordinateSystem # isGeoReferencing */
public static boolean isGridCoordSys ( Formatter sbuff , CoordinateSystem cs , VariableEnhanced v ) { } }

implementation:
// must be at least 2 axes
if ( cs . getRankDomain ( ) < 2 ) { if ( sbuff != null ) { sbuff . format ( "%s: domain rank < 2%n" , cs . getName ( ) ) ; } return false ; } // must be lat / lon or have x , y and projecction
if ( ! cs . isLatLon ( ) ) { // do check for GeoXY ourself
if ( ( cs . getXaxis ( ) == null ) || ( cs . getYaxis ( ) == null ) ) { if ( sbuff != null ) { sbuff . format ( "%s: NO Lat,Lon or X,Y axis%n" , cs . getName ( ) ) ; } return false ; } if ( null == cs . getProjection ( ) ) { if ( sbuff != null ) { sbuff . format ( "%s: NO projection found%n" , cs . getName ( ) ) ; } return false ; } } // obtain the x , y or lat / lon axes . x , y normally must be convertible to km
CoordinateAxis xaxis , yaxis ; if ( cs . isGeoXY ( ) ) { xaxis = cs . getXaxis ( ) ; yaxis = cs . getYaxis ( ) ; // change to warning
ProjectionImpl p = cs . getProjection ( ) ; if ( ! ( p instanceof RotatedPole ) ) { if ( ! SimpleUnit . kmUnit . isCompatible ( xaxis . getUnitsString ( ) ) ) { if ( sbuff != null ) { sbuff . format ( "%s: X axis units are not convertible to km%n" , cs . getName ( ) ) ; } // return false ;
} if ( ! SimpleUnit . kmUnit . isCompatible ( yaxis . getUnitsString ( ) ) ) { if ( sbuff != null ) { sbuff . format ( "%s: Y axis units are not convertible to km%n" , cs . getName ( ) ) ; } // return false ;
} } } else { xaxis = cs . getLonAxis ( ) ; yaxis = cs . getLatAxis ( ) ; } // check x , y rank < = 2
if ( ( xaxis . getRank ( ) > 2 ) || ( yaxis . getRank ( ) > 2 ) ) { if ( sbuff != null ) sbuff . format ( "%s: X or Y axis rank must be <= 2%n" , cs . getName ( ) ) ; return false ; } // check that the x , y have at least 2 dimensions between them ( this eliminates point data )
int xyDomainSize = CoordinateSystem . countDomain ( new CoordinateAxis [ ] { xaxis , yaxis } ) ; if ( xyDomainSize < 2 ) { if ( sbuff != null ) sbuff . format ( "%s: X and Y axis must have 2 or more dimensions%n" , cs . getName ( ) ) ; return false ; } List < CoordinateAxis > testAxis = new ArrayList < > ( ) ; testAxis . add ( xaxis ) ; testAxis . add ( yaxis ) ; // int countRangeRank = 2;
CoordinateAxis z = cs . getHeightAxis ( ) ; if ( ( z == null ) || ! ( z instanceof CoordinateAxis1D ) ) z = cs . getPressureAxis ( ) ; if ( ( z == null ) || ! ( z instanceof CoordinateAxis1D ) ) z = cs . getZaxis ( ) ; if ( ( z != null ) && ! ( z instanceof CoordinateAxis1D ) ) { if ( sbuff != null ) { sbuff . format ( "%s: Z axis must be 1D%n" , cs . getName ( ) ) ; } return false ; } if ( z != null ) testAxis . add ( z ) ; // tom margolis 3/2/2010
// allow runtime independent of time
CoordinateAxis t = cs . getTaxis ( ) ; CoordinateAxis rt = cs . findAxis ( AxisType . RunTime ) ; // A runtime axis must be scalar or one - dimensional
if ( rt != null ) { if ( ! rt . isScalar ( ) && ! ( rt instanceof CoordinateAxis1D ) ) { if ( sbuff != null ) sbuff . format ( "%s: RunTime axis must be 1D%n" , cs . getName ( ) ) ; return false ; } } // If time axis is two - dimensional . . .
if ( ( t != null ) && ! ( t instanceof CoordinateAxis1D ) && ( t . getRank ( ) != 0 ) ) { if ( rt != null ) { if ( rt . getRank ( ) != 1 ) { if ( sbuff != null ) sbuff . format ( "%s: Runtime axis must be 1D%n" , cs . getName ( ) ) ; return false ; } // time first dimension must agree with runtime
if ( ! rt . getDimension ( 0 ) . equals ( t . getDimension ( 0 ) ) ) { if ( sbuff != null ) sbuff . format ( "%s: 2D Time axis first dimension must be runtime%n" , cs . getName ( ) ) ; return false ; } } } if ( t != null ) testAxis . add ( t ) ; if ( rt != null ) testAxis . add ( rt ) ; CoordinateAxis ens = cs . getEnsembleAxis ( ) ; if ( ens != null ) testAxis . add ( ens ) ; if ( v != null ) { // test to see that v doesnt have extra dimensions . LOOK RELAX THIS
List < Dimension > testDomain = new ArrayList < > ( ) ; for ( CoordinateAxis axis : testAxis ) { for ( Dimension dim : axis . getDimensions ( ) ) { if ( ! testDomain . contains ( dim ) ) testDomain . add ( dim ) ; } } if ( ! CoordinateSystem . isSubset ( v . getDimensionsAll ( ) , testDomain ) ) { if ( sbuff != null ) sbuff . format ( " NOT complete%n" ) ; return false ; } } return true ;


signature:
public class GridCoordSys { /** * Determine if the CoordinateSystem cs can be made into a GridCoordSys for the Variable v .
 * @ param sbuff put debug information into this StringBuffer ; may be null .
 * @ param cs CoordinateSystem to check .
 * @ param v Variable to check .
 * @ return the GridCoordSys made from cs , else null . */
public static GridCoordSys makeGridCoordSys ( Formatter sbuff , CoordinateSystem cs , VariableEnhanced v ) { } }

implementation: if ( sbuff != null ) { sbuff . format ( " " ) ; v . getNameAndDimensions ( sbuff , false , true ) ; sbuff . format ( " check CS %s: " , cs . getName ( ) ) ; } if ( isGridCoordSys ( sbuff , cs , v ) ) { GridCoordSys gcs = new GridCoordSys ( cs , sbuff ) ; if ( sbuff != null ) sbuff . format ( " OK%n" ) ; return gcs ; } return null ;


signature:
public class GridCoordSys { /** * we have to delay making these , since we dont identify the dimensions specifically until now */
void makeVerticalTransform ( GridDataset gds , Formatter parseInfo ) { } }

implementation:
if ( vt != null ) return ; // already done
if ( vCT == null ) return ; // no vt
vt = vCT . makeVerticalTransform ( gds . getNetcdfDataset ( ) , timeDim ) ; if ( vt == null ) { if ( parseInfo != null ) parseInfo . format ( "  - ERR can't make VerticalTransform = %s%n" , vCT . getVerticalTransformType ( ) ) ; } else { if ( parseInfo != null ) parseInfo . format ( "  - VerticalTransform = %s%n" , vCT . getVerticalTransformType ( ) ) ; }


signature:
public class GridCoordSys { /** * Is this a global coverage over longitude ?
 * @ return true if isLatLon and longitude wraps */
@ Override public boolean isGlobalLon ( ) { } }

implementation: if ( ! isLatLon ) return false ; if ( ! ( horizXaxis instanceof CoordinateAxis1D ) ) return false ; CoordinateAxis1D lon = ( CoordinateAxis1D ) horizXaxis ; double first = lon . getCoordEdge ( 0 ) ; double last = lon . getCoordEdge ( ( int ) lon . getSize ( ) ) ; double min = Math . min ( first , last ) ; double max = Math . max ( first , last ) ; return ( max - min ) >= 360 ;


signature:
public class GridCoordSys { /** * true if increasing z coordinate values means " up " in altitude */
@ Override public boolean isZPositive ( ) { } }

implementation: if ( vertZaxis == null ) return false ; if ( vertZaxis . getPositive ( ) != null ) { return vertZaxis . getPositive ( ) . equalsIgnoreCase ( ucar . nc2 . constants . CF . POSITIVE_UP ) ; } if ( vertZaxis . getAxisType ( ) == AxisType . Height ) return true ; return vertZaxis . getAxisType ( ) != AxisType . Pressure ;


signature:
public class GridCoordSys { /** * Given a point in x , y coordinate space , find the x , y index in the coordinate system .
 * @ param x _ coord position in x coordinate space .
 * @ param y _ coord position in y coordinate space .
 * @ param result put result ( x , y ) index in here , may be null
 * @ return int [ 2 ] , 0 = x , 1 = y indices in the coordinate system of the point . These will be - 1 if out of range . */
@ Override public int [ ] findXYindexFromCoord ( double x_coord , double y_coord , int [ ] result ) { } }

implementation:
if ( result == null ) result = new int [ 2 ] ; if ( ( horizXaxis instanceof CoordinateAxis1D ) && ( horizYaxis instanceof CoordinateAxis1D ) ) { result [ 0 ] = ( ( CoordinateAxis1D ) horizXaxis ) . findCoordElement ( x_coord ) ; result [ 1 ] = ( ( CoordinateAxis1D ) horizYaxis ) . findCoordElement ( y_coord ) ; return result ; } else if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { if ( g2d == null ) g2d = new GridCoordinate2D ( ( CoordinateAxis2D ) horizYaxis , ( CoordinateAxis2D ) horizXaxis ) ; int [ ] result2 = new int [ 2 ] ; boolean found = g2d . findCoordElement ( y_coord , x_coord , result2 ) ; if ( found ) { result [ 0 ] = result2 [ 1 ] ; result [ 1 ] = result2 [ 0 ] ; } else { result [ 0 ] = - 1 ; result [ 1 ] = - 1 ; } return result ; } // cant happen
throw new IllegalStateException ( "GridCoordSystem.findXYindexFromCoord" ) ;


signature:
public class GridCoordSys { /** * Given a point in x , y coordinate space , find the x , y index in the coordinate system .
 * If outside the range , the closest point is returned , eg , 0 or n - 1 depending on if the coordinate is too small or too large .
 * @ param x _ coord position in x coordinate space .
 * @ param y _ coord position in y coordinate space .
 * @ param result put result in here , may be null
 * @ return int [ 2 ] , 0 = x , 1 = y indices in the coordinate system of the point . */
@ Override public int [ ] findXYindexFromCoordBounded ( double x_coord , double y_coord , int [ ] result ) { } }

implementation:
if ( result == null ) result = new int [ 2 ] ; if ( ( horizXaxis instanceof CoordinateAxis1D ) && ( horizYaxis instanceof CoordinateAxis1D ) ) { result [ 0 ] = ( ( CoordinateAxis1D ) horizXaxis ) . findCoordElementBounded ( x_coord ) ; result [ 1 ] = ( ( CoordinateAxis1D ) horizYaxis ) . findCoordElementBounded ( y_coord ) ; return result ; } else if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { if ( g2d == null ) g2d = new GridCoordinate2D ( ( CoordinateAxis2D ) horizYaxis , ( CoordinateAxis2D ) horizXaxis ) ; int [ ] result2 = new int [ 2 ] ; g2d . findCoordElement ( y_coord , x_coord , result2 ) ; // returns best guess
result [ 0 ] = result2 [ 1 ] ; result [ 1 ] = result2 [ 0 ] ; return result ; } // cant happen
throw new IllegalStateException ( "GridCoordSystem.findXYindexFromCoord" ) ;


signature:
public class GridCoordSys { /** * Given a lat , lon point , find the x , y index in the coordinate system .
 * @ param lat latitude position .
 * @ param lon longitude position .
 * @ param result put result in here , may be null
 * @ return int [ 2 ] , 0 = x , 1 = y indices in the coordinate system of the point . These will be - 1 if out of range . */
@ Override public int [ ] findXYindexFromLatLon ( double lat , double lon , int [ ] result ) { } }

implementation: Projection dataProjection = getProjection ( ) ; ProjectionPoint pp = dataProjection . latLonToProj ( new LatLonPointImpl ( lat , lon ) , new ProjectionPointImpl ( ) ) ; return findXYindexFromCoord ( pp . getX ( ) , pp . getY ( ) , result ) ;


signature:
public class GridCoordSys { /** * Given a lat , lon point , find the x , y index in the coordinate system .
 * If outside the range , the closest point is returned
 * @ param lat latitude position .
 * @ param lon longitude position .
 * @ param result put result in here , may be null
 * @ return int [ 2 ] , 0 = x , 1 = y indices in the coordinate system of the point . */
@ Override public int [ ] findXYindexFromLatLonBounded ( double lat , double lon , int [ ] result ) { } }

implementation: Projection dataProjection = getProjection ( ) ; ProjectionPoint pp = dataProjection . latLonToProj ( new LatLonPointImpl ( lat , lon ) , new ProjectionPointImpl ( ) ) ; return findXYindexFromCoordBounded ( pp . getX ( ) , pp . getY ( ) , result ) ;


signature:
public class GridCoordSys { /** * Get the x , y bounding box in projection coordinates . */
@ Override public ProjectionRect getBoundingBox ( ) { } }

implementation:
if ( mapArea == null ) { if ( ( horizXaxis == null ) || ! horizXaxis . isNumeric ( ) || ( horizYaxis == null ) || ! horizYaxis . isNumeric ( ) ) return null ; // impossible
// x , y may be 2D
if ( ! ( horizXaxis instanceof CoordinateAxis1D ) || ! ( horizYaxis instanceof CoordinateAxis1D ) ) { /* could try to optimize this - just get cord = ners or something
 CoordinateAxis2D xaxis2 = ( CoordinateAxis2D ) horizXaxis ;
 CoordinateAxis2D yaxis2 = ( CoordinateAxis2D ) horizYaxis ;
 MAMath . MinMax */
mapArea = new ProjectionRect ( horizXaxis . getMinValue ( ) , horizYaxis . getMinValue ( ) , horizXaxis . getMaxValue ( ) , horizYaxis . getMaxValue ( ) ) ; } else { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) horizXaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) horizYaxis ; /* add one percent on each side if its a projection . WHY ?
 double dx = 0.0 , dy = 0.0;
 if ( ! isLatLon ( ) ) {
 dx = . 01 * ( xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) - xaxis1 . getCoordEdge ( 0 ) ) ;
 dy = . 01 * ( yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) - yaxis1 . getCoordEdge ( 0 ) ) ;
 mapArea = new ProjectionRect ( xaxis1 . getCoordEdge ( 0 ) - dx , yaxis1 . getCoordEdge ( 0 ) - dy ,
 xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) + dx ,
 yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) + dy ) ; */
mapArea = new ProjectionRect ( xaxis1 . getCoordEdge ( 0 ) , yaxis1 . getCoordEdge ( 0 ) , xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) , yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) ) ; } } return mapArea ;


signature:
public class GridCoordSys { /** * Get the Lat / Lon coordinates of the midpoint of a grid cell , using the x , y indices
 * @ param xindex x index
 * @ param yindex y index
 * @ return lat / lon coordinate of the midpoint of the cell */
@ Override public LatLonPoint getLatLon ( int xindex , int yindex ) { } }

implementation: double x , y ; if ( horizXaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizXaxis ; x = horiz1D . getCoordValue ( xindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizXaxis ; x = horiz2D . getCoordValue ( yindex , xindex ) ; } if ( horizYaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizYaxis ; y = horiz1D . getCoordValue ( yindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizYaxis ; y = horiz2D . getCoordValue ( yindex , xindex ) ; } return isLatLon ( ) ? new LatLonPointImpl ( y , x ) : getLatLon ( x , y ) ;


signature:
public class GridCoordSys { /** * Get Index Ranges for the given lat , lon bounding box .
 * For projection , only an approximation based on latlon corners .
 * Must have CoordinateAxis1D or 2D for x and y axis .
 * @ param rect the requested lat / lon bounding box
 * @ return list of 2 Range objects , first y then x . */
@ Override public List < Range > getRangesFromLatLonRect ( LatLonRect rect ) throws InvalidRangeException { } }

implementation:
double minx , maxx , miny , maxy ; ProjectionImpl proj = getProjection ( ) ; if ( proj != null && ! ( proj instanceof VerticalPerspectiveView ) && ! ( proj instanceof MSGnavigation ) && ! ( proj instanceof Geostationary ) ) { // LOOK kludge - how to do this generrally ? ?
// first clip the request rectangle to the bounding box of the grid
LatLonRect bb = getLatLonBoundingBox ( ) ; LatLonRect rect2 = bb . intersect ( rect ) ; if ( null == rect2 ) throw new InvalidRangeException ( "Request Bounding box does not intersect Grid " ) ; rect = rect2 ; } CoordinateAxis xaxis = getXHorizAxis ( ) ; CoordinateAxis yaxis = getYHorizAxis ( ) ; if ( isLatLon ( ) ) { LatLonPointImpl llpt = rect . getLowerLeftPoint ( ) ; LatLonPointImpl urpt = rect . getUpperRightPoint ( ) ; LatLonPointImpl lrpt = rect . getLowerRightPoint ( ) ; LatLonPointImpl ulpt = rect . getUpperLeftPoint ( ) ; minx = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; miny = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; maxx = getMinOrMaxLon ( urpt . getLongitude ( ) , lrpt . getLongitude ( ) , false ) ; maxy = Math . min ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // normalize to [ minLon , minLon + 360]
double minLon = xaxis . getMinValue ( ) ; minx = LatLonPointImpl . lonNormalFrom ( minx , minLon ) ; maxx = LatLonPointImpl . lonNormalFrom ( maxx , minLon ) ; } else { ProjectionRect prect = getProjection ( ) . latLonToProjBB ( rect ) ; // allow projection to override
minx = prect . getMinPoint ( ) . getX ( ) ; miny = prect . getMinPoint ( ) . getY ( ) ; maxx = prect . getMaxPoint ( ) . getX ( ) ; maxy = prect . getMaxPoint ( ) . getY ( ) ; /* see ProjectionImpl . latLonToProjBB2 ( )
 Projection dataProjection = getProjection ( ) ;
 ProjectionPoint ll = dataProjection . latLonToProj ( llpt , new ProjectionPointImpl ( ) ) ;
 ProjectionPoint ur = dataProjection . latLonToProj ( urpt , new ProjectionPointImpl ( ) ) ;
 ProjectionPoint lr = dataProjection . latLonToProj ( lrpt , new ProjectionPointImpl ( ) ) ;
 ProjectionPoint ul = dataProjection . latLonToProj ( ulpt , new ProjectionPointImpl ( ) ) ;
 minx = Math . min ( ll . getX ( ) , ul . getX ( ) ) ;
 miny = Math . min ( ll . getY ( ) , lr . getY ( ) ) ;
 maxx = Math . max ( ur . getX ( ) , lr . getX ( ) ) ;
 maxy = Math . max ( ul . getY ( ) , ur . getY ( ) ) ; */
} if ( ( xaxis instanceof CoordinateAxis1D ) && ( yaxis instanceof CoordinateAxis1D ) ) { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) xaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) yaxis ; int minxIndex = xaxis1 . findCoordElementBounded ( minx ) ; int minyIndex = yaxis1 . findCoordElementBounded ( miny ) ; int maxxIndex = xaxis1 . findCoordElementBounded ( maxx ) ; int maxyIndex = yaxis1 . findCoordElementBounded ( maxy ) ; List < Range > list = new ArrayList < > ( ) ; list . add ( new Range ( Math . min ( minyIndex , maxyIndex ) , Math . max ( minyIndex , maxyIndex ) ) ) ; list . add ( new Range ( Math . min ( minxIndex , maxxIndex ) , Math . max ( minxIndex , maxxIndex ) ) ) ; return list ; } else if ( ( xaxis instanceof CoordinateAxis2D ) && ( yaxis instanceof CoordinateAxis2D ) && isLatLon ( ) ) { CoordinateAxis2D lon_axis = ( CoordinateAxis2D ) xaxis ; CoordinateAxis2D lat_axis = ( CoordinateAxis2D ) yaxis ; int shape [ ] = lon_axis . getShape ( ) ; int nj = shape [ 0 ] ; int ni = shape [ 1 ] ; int mini = Integer . MAX_VALUE , minj = Integer . MAX_VALUE ; int maxi = - 1 , maxj = - 1 ; // margolis 2/18/2010
// minx = LatLonPointImpl . lonNormal ( minx ) ; / / < - - THIS IS NEW
// maxx = LatLonPointImpl . lonNormal ( maxx ) ; / / < - - THIS IS NEW
// brute force , examine every point LOOK BAD
for ( int j = 0 ; j < nj ; j ++ ) { for ( int i = 0 ; i < ni ; i ++ ) { double lat = lat_axis . getCoordValue ( j , i ) ; double lon = lon_axis . getCoordValue ( j , i ) ; // lon = LatLonPointImpl . lonNormal ( lon ) ; / / < - - THIS IS NEW
if ( ( lat >= miny ) && ( lat <= maxy ) && ( lon >= minx ) && ( lon <= maxx ) ) { if ( i > maxi ) maxi = i ; if ( i < mini ) mini = i ; if ( j > maxj ) maxj = j ; if ( j < minj ) minj = j ; // System . out . println ( j + " " + i + " lat = " + lat + " lon = " + lon ) ;
} } } // this is the case where no points are included
if ( ( mini > maxi ) || ( minj > maxj ) ) { mini = 0 ; minj = 0 ; maxi = - 1 ; maxj = - 1 ; } ArrayList < Range > list = new ArrayList < > ( ) ; list . add ( new Range ( minj , maxj ) ) ; list . add ( new Range ( mini , maxi ) ) ; return list ; } else { throw new IllegalArgumentException ( "must be 1D or 2D/LatLon " ) ; }


signature: public class GridCoordSys { @ Override public List < CalendarDate > getCalendarDates ( ) { } }

implementation: if ( timeTaxis != null ) return timeTaxis . getCalendarDates ( ) ; else if ( getRunTimeAxis ( ) != null ) return makeCalendarDates2D ( ) ; else return new ArrayList < > ( ) ;


signature:
public class MyTextField { /** * return slider indicator position for currently selected item */
protected int getItemPos ( ) { } }

implementation:
if ( nitems < 1 ) return - arrow_size ; // dont show indicator
else if ( nitems == 1 ) return b . width / 2 ; // indicator in center
int item = table . getSelectedRowIndex ( ) ; // selected item
int eff_width = b . width - 2 * arrow_size ; // effective width
int pixel = ( item * eff_width ) / ( nitems - 1 ) ; // divided into n - 1 intervals
return pixel + arrow_size ;


signature:
public class MyTextField { /** * return item selected by this pixel position */
protected int getItem ( int pixel ) { } }

implementation:
if ( nitems < 2 ) return 0 ; int eff_width = b . width - 2 * arrow_size ; // effective width
double fitem = ( ( double ) ( pixel - arrow_size ) * ( nitems - 1 ) ) / eff_width ; int item = ( int ) ( fitem + .5 ) ; item = Math . max ( Math . min ( item , nitems - 1 ) , 0 ) ; return item ;


signature:
public class DirectoryCollection { /** * Create standard name = topCollectionName + last directory
 * @ param topCollectionName from config , name of the collection
 * @ param dir directory for this
 * @ return standard collection name , to name the index file */
public static String makeCollectionName ( String topCollectionName , Path dir ) { } }

implementation: int last = dir . getNameCount ( ) - 1 ; Path lastDir = dir . getName ( last ) ; String lastDirName = lastDir . toString ( ) ; return topCollectionName + "-" + lastDirName ;


signature:
public class DirectoryCollection { /** * Create standard name = topCollectionName + last directory
 * @ param topCollectionName from config , name of the collection
 * @ param dir directory for this
 * @ return standard collection name , to name the index file */
public static Path makeCollectionIndexPath ( String topCollectionName , Path dir , String suffix ) { } }

implementation: String collectionName = makeCollectionName ( topCollectionName , dir ) ; return Paths . get ( dir . toString ( ) , collectionName + suffix ) ;


signature:
public class DirectoryCollection { /** * this idiom keeps the iterator from escaping , so that we can use try - with - resource , and ensure DirectoryStream closes . like + + */
public void iterateOverMFileCollection ( Visitor visit ) throws IOException { } }

implementation:
if ( debug ) System . out . printf ( " iterateOverMFileCollection %s " , collectionDir ) ; int count = 0 ; try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( collectionDir , new MyStreamFilter ( ) ) ) { for ( Path p : ds ) { try { BasicFileAttributes attr = Files . readAttributes ( p , BasicFileAttributes . class ) ; if ( ! attr . isDirectory ( ) ) visit . consume ( new MFileOS7 ( p ) ) ; if ( debug ) System . out . printf ( "%d " , count ++ ) ; } catch ( IOException ioe ) { // catch error and skip file
logger . error ( "Failed to read attributes from file found in Files.newDirectoryStream " , ioe ) ; } } } if ( debug ) System . out . printf ( "%d%n" , count ) ;


signature:
public class TdsDownloader { /** * copy remote files to localDir */
public void getRemoteFiles ( final CancelTask _cancel ) { } }

implementation:
this . cancel = _cancel ; String urls = config . getServerPrefix ( ) + "/thredds/admin/log/" + type + "/" ; ta . append ( String . format ( "Download URL = %s%n" , urls ) ) ; String contents = null ; try ( HTTPMethod method = HTTPFactory . Get ( session , urls ) ) { int statusCode = method . execute ( ) ; if ( statusCode == 200 ) contents = method . getResponseAsString ( ) ; if ( ( contents == null ) || ( contents . length ( ) == 0 ) ) { ta . append ( String . format ( "Failed to get logs at URL = %s%n%n" , urls ) ) ; return ; } else { ta . append ( String . format ( "Logs at URL = %s%n%s%n" , urls , contents ) ) ; } } catch ( Throwable t ) { ta . append ( String . format ( "Failed to get logs at URL = %s error = %s%n%n" , urls , t . getMessage ( ) ) ) ; t . printStackTrace ( ) ; return ; } // update text area in background http : / / technobuz . com / 2009/05 / update - jtextarea - dynamically /
final String list = contents ; SwingWorker worker = new SwingWorker < String , Void > ( ) { @ Override protected String doInBackground ( ) throws Exception { try { ta . append ( String . format ( "Local log files stored in = %s%n%n" , localDir ) ) ; String [ ] lines = list . split ( "\n" ) ; for ( String line : lines ) { new RemoteLog ( line . trim ( ) ) ; if ( cancel . isCancel ( ) ) { break ; } } } catch ( Throwable t ) { t . printStackTrace ( ) ; } return null ; } public void done ( ) { if ( cancel . isCancel ( ) ) ta . append ( String . format ( "Download was cancelled for %s%n" , type ) ) ; else ta . append ( String . format ( "Download complete for %s%n" , type ) ) ; } } ; // do in background
worker . execute ( ) ;


signature:
public class PointIteratorFiltered { /** * PointFeatureIterator . hasNext ( ) doesn ' t guarantee idempotency , but we do . */
@ Override public boolean hasNext ( ) { } }

implementation:
if ( pointFeature != null ) { return true ; // pointFeature hasn ' t yet been consumed .
} pointFeature = nextFilteredDataPoint ( ) ; if ( pointFeature == null ) { close ( ) ; return false ; } else { return true ; }


signature:
public class PointIteratorFiltered { /** * but we can define a stronger contract . */
@ Override public PointFeature next ( ) throws NoSuchElementException { } }

implementation:
if ( ! hasNext ( ) ) { throw new NoSuchElementException ( "This iterator has no more elements." ) ; } assert pointFeature != null ; PointFeature ret = pointFeature ; calcBounds ( ret ) ; pointFeature = null ; // Feature has been consumed .
return ret ;


signature:
public class PointIteratorFiltered { /** * Returns the next point that satisfies the filter , or { @ code null } if no such point exists .
 * @ return the next point that satisfies the filter , or { @ code null } if no such point exists . */
private PointFeature nextFilteredDataPoint ( ) { } }

implementation: while ( origIter . hasNext ( ) ) { PointFeature pointFeat = origIter . next ( ) ; if ( filter . filter ( pointFeat ) ) { return pointFeat ; } } return null ;


signature:
public class FslHrrrLocalTables { /** * LOOK maybe combine grib1 , grib2 and bufr ? ? */
@ Override public String getSubCenterName ( int center , int subcenter ) { } }

implementation: switch ( subcenter ) { case 0 : return null ; case 1 : return "FSL/FRD Regional Analysis and Prediction Branch" ; case 2 : return "FSL/FRD Local Analysis and Prediction Branch" ; } return super . getSubCenterName ( center , subcenter ) ;


signature:
public class CalendarPeriod { /** * Convert a period string into a CalendarPeriod . Field .
 * @ param udunit period string
 * @ return CalendarPeriod . Field enum
 * @ throws IllegalArgumentException if not valid format */
public static CalendarPeriod . Field fromUnitString ( String udunit ) { } }

implementation:
udunit = udunit . trim ( ) ; udunit = udunit . toLowerCase ( ) ; if ( udunit . equals ( "s" ) ) return Field . Second ; if ( udunit . equals ( "ms" ) ) return Field . Millisec ; // eliminate plurals
if ( udunit . endsWith ( "s" ) ) udunit = udunit . substring ( 0 , udunit . length ( ) - 1 ) ; switch ( udunit ) { case "second" : case "sec" : return Field . Second ; case "millisecond" : case "millisec" : case "msec" : return Field . Millisec ; case "minute" : case "min" : return Field . Minute ; case "hour" : case "hr" : case "h" : return Field . Hour ; case "day" : case "d" : return Field . Day ; case "month" : case "mon" : return Field . Month ; case "year" : case "yr" : return Field . Year ; default : throw new IllegalArgumentException ( "cant convert " + udunit + " to CalendarPeriod" ) ; }


signature:
public class CalendarPeriod { /** * minimize memory use by interning . wacko shit in GribPartitionBuilder TimeCoordinate , whoduhthunk ? */
public static CalendarPeriod of ( int value , Field field ) { } }

implementation: CalendarPeriod want = new CalendarPeriod ( value , field ) ; if ( cache == null ) return want ; CalendarPeriod got = cache . getIfPresent ( want ) ; if ( got != null ) return got ; cache . put ( want , want ) ; return want ;


signature:
public class CalendarPeriod { /** * Convert a udunit period string into a CalendarPeriod
 * @ param udunit period string : " [ val ] unit "
 * @ return CalendarPeriod or null if illegal */
public static CalendarPeriod of ( String udunit ) { } }

implementation: int value ; String units ; String [ ] split = StringUtil2 . splitString ( udunit ) ; if ( split . length == 1 ) { value = 1 ; units = split [ 0 ] ; } else if ( split . length == 2 ) { try { value = Integer . parseInt ( split [ 0 ] ) ; } catch ( Throwable t ) { return null ; } units = split [ 1 ] ; } else return null ; CalendarPeriod . Field unit = CalendarPeriod . fromUnitString ( units ) ; return CalendarPeriod . of ( value , unit ) ;


signature:
public class CalendarPeriod { /** * Subtract two dates , return difference in units of this period .
 * If not even , will round down and log a warning
 * @ param start start date
 * @ param end end date
 * @ return difference in units of this period */
public int subtract ( CalendarDate start , CalendarDate end ) { } }

implementation: long diff = end . getDifferenceInMsecs ( start ) ; int thislen = millisecs ( ) ; if ( ( diff % thislen != 0 ) ) log . warn ( "roundoff error" ) ; return ( int ) ( diff / thislen ) ;


signature:
public class CalendarPeriod { /** * Get the conversion factor of the other CalendarPeriod to this one
 * @ param from convert from this
 * @ return conversion factor , so that getConvertFactor ( from ) * from = this */
public double getConvertFactor ( CalendarPeriod from ) { } }

implementation: if ( field == CalendarPeriod . Field . Month || field == CalendarPeriod . Field . Year ) { log . warn ( " CalendarDate.convert on Month or Year" ) ; } return ( double ) from . millisecs ( ) / millisecs ( ) ;


signature:
public class CalendarPeriod { /** * Get the duration in milliseconds - +
 * @ return the duration in seconds
 * @ deprecated dont use because these are fixed length and thus approximate . */
public double getValueInMillisecs ( ) { } }

implementation: if ( field == CalendarPeriod . Field . Month ) return 30.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value ; else if ( field == CalendarPeriod . Field . Year ) return 365.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value ; else return millisecs ( ) ;


signature:
public class CalendarPeriod { /** * start + offset = end */
public int getOffset ( CalendarDate start , CalendarDate end ) { } }

implementation:
if ( start . equals ( end ) ) return 0 ; long start_millis = start . getDateTime ( ) . getMillis ( ) ; long end_millis = end . getDateTime ( ) . getMillis ( ) ; // 5 second slop
Period p ; if ( start_millis < end_millis ) p = new Period ( start_millis , end_millis + 5000 , getPeriodType ( ) ) ; else p = new Period ( start_millis + 5000 , end_millis , getPeriodType ( ) ) ; return p . get ( getDurationFieldType ( ) ) ;


signature:
public class GempakGridServiceProvider { /** * Is this a valid file ?
 * @ param raf RandomAccessFile to check
 * @ return true if a valid GEMPAK grid file
 * @ throws IOException problem reading file */
public boolean isValidFile ( RandomAccessFile raf ) throws IOException { } }

implementation: try { gemreader = new GempakGridReader ( raf . getLocation ( ) ) ; return gemreader . init ( raf , false ) ; } catch ( Exception ioe ) { return false ; }


signature:
public class GempakGridServiceProvider { /** * Open the service provider for reading .
 * @ param raf file to read from
 * @ param ncfile netCDF file we are writing to ( memory )
 * @ param cancelTask task for cancelling
 * @ throws IOException problem reading file */
public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { } }

implementation:
super . open ( raf , ncfile , cancelTask ) ; // debugProj = true ;
long start = System . currentTimeMillis ( ) ; if ( gemreader == null ) { gemreader = new GempakGridReader ( raf . getLocation ( ) ) ; } initTables ( ) ; gemreader . init ( raf , true ) ; GridIndex index = gemreader . getGridIndex ( ) ; open ( index , cancelTask ) ; if ( debugOpen ) { System . out . println ( " GridServiceProvider.open " + ncfile . getLocation ( ) + " took " + ( System . currentTimeMillis ( ) - start ) ) ; }


signature:
public class GempakGridServiceProvider { /** * Open the index and create the netCDF file from that
 * @ param index GridIndex to use
 * @ param cancelTask cancel task
 * @ throws IOException problem reading the file */
protected void open ( GridIndex index , CancelTask cancelTask ) throws IOException { } }

implementation:
GempakLookup lookup = new GempakLookup ( ( GempakGridRecord ) index . getGridRecords ( ) . get ( 0 ) ) ; GridIndexToNC delegate = new GridIndexToNC ( index . filename ) ; // delegate . setUseDescriptionForVariableName ( false ) ;
delegate . open ( index , lookup , 4 , ncfile , cancelTask ) ; ncfile . finish ( ) ;


signature:
public class GempakGridServiceProvider { /** * Sync the file
 * @ return true if needed to sync
 * @ throws IOException problem synching the file */
public boolean sync ( ) throws IOException { } }

implementation:
if ( ( gemreader . getInitFileSize ( ) < raf . length ( ) ) && extendIndex ) { gemreader . init ( true ) ; GridIndex index = gemreader . getGridIndex ( ) ; // reconstruct the ncfile objects
ncfile . empty ( ) ; open ( index , null ) ; return true ; } return false ;


signature:
public class GempakGridServiceProvider { /** * Initialize the parameter tables . */
private void initTables ( ) { } }

implementation: try { GempakGridParameterTable . addParameters ( "resources/nj22/tables/gempak/wmogrib3.tbl" ) ; GempakGridParameterTable . addParameters ( "resources/nj22/tables/gempak/ncepgrib2.tbl" ) ; } catch ( Exception e ) { System . out . println ( "unable to init tables" ) ; }


signature:
public class DataRootPathMatcher { /** * Add a dataRootExt to in - memory tree .
 * @ return true if not already exist */
private boolean put ( DataRootExt dateRootExt ) { } }

implementation: map . put ( dateRootExt . getPath ( ) , dateRootExt ) ; return treeSet . add ( dateRootExt . getPath ( ) ) ;


signature:
public class DataRootPathMatcher { /** * Find the longest path match .
 * @ param reqPath find object with longest match where reqPath . startsWith ( key )
 * @ return the value whose key is the longest that matches path , or null if none */
public String findLongestPathMatch ( String reqPath ) { } }

implementation:
SortedSet < String > tail = treeSet . tailSet ( reqPath ) ; if ( tail . isEmpty ( ) ) return null ; String after = tail . first ( ) ; if ( reqPath . startsWith ( after ) ) // common case
return tail . first ( ) ; // have to check more , until no common starting chars
for ( String key : tail ) { if ( reqPath . startsWith ( key ) ) return key ; // terminate when there ' s no match at all .
if ( StringUtil2 . match ( reqPath , key ) == 0 ) break ; } return null ;


signature:
public class DataRootPathMatcher { /** * Find the longest DataRoot match .
 * @ param reqPath find object with longest match where reqPath . startsWith ( key )
 * @ return the value whose key is the longest that matches path , or null if none */
public DataRoot findDataRoot ( String reqPath ) { } }

implementation: String path = findLongestPathMatch ( reqPath ) ; if ( path == null ) return null ; DataRootExt dataRootExt = map . get ( path ) ; if ( dataRootExt == null ) { logger . error ( "DataRootPathMatcher found path {} but not in map" , path ) ; return null ; } return convert2DataRoot ( dataRootExt ) ;


signature:
public class DataRootPathMatcher { /** * convert a dataRootExt to a dataRoot */
public @ Nonnull DataRoot convert2DataRoot ( DataRootExt dataRootExt ) { } }

implementation:
DataRoot dataRoot = dataRootExt . getDataRoot ( ) ; if ( dataRoot != null ) return dataRoot ; // otherwise must read the catalog that its in
dataRoot = readDataRootFromCatalog ( dataRootExt ) ; dataRootExt . setDataRoot ( dataRoot ) ; return dataRoot ;


signature:
public class DataRootPathMatcher { /** * Finds datasetScan , datasetFmrc
 * Look for duplicate Ids ( give message ) .
 * Dont follow catRefs .
 * @ param dsList the list of Dataset */
public void extractDataRoots ( String catalogRelPath , List < Dataset > dsList , boolean checkDups , Map < String , String > idMap ) { } }

implementation:
for ( Dataset dataset : dsList ) { if ( dataset instanceof DatasetScan ) { DatasetScan ds = ( DatasetScan ) dataset ; addRoot ( ds , catalogRelPath , checkDups ) ; } else if ( dataset instanceof FeatureCollectionRef ) { FeatureCollectionRef fc = ( FeatureCollectionRef ) dataset ; addRoot ( fc , catalogRelPath , checkDups ) ; if ( idMap != null ) { String catWithSameFc = idMap . get ( fc . getCollectionName ( ) ) ; if ( catWithSameFc != null ) logCatalogInit . warn ( "*** ERROR: Duplicate featureCollection name {} in catalogs '{}' and '{}'" , fc . getCollectionName ( ) , catalogRelPath , catWithSameFc ) ; else idMap . put ( fc . getCollectionName ( ) , catalogRelPath ) ; } } else if ( dataset instanceof CatalogScan ) { CatalogScan catScan = ( CatalogScan ) dataset ; addRoot ( catScan , catalogRelPath , checkDups ) ; } if ( ! ( dataset instanceof CatalogRef ) ) { // recurse
extractDataRoots ( catalogRelPath , dataset . getDatasetsLocal ( ) , checkDups , idMap ) ; } }


signature:
public class NcssParamsBean { /** * return requested CalendarDateRange . */
public CalendarDateRange getCalendarDateRange ( Calendar cal ) { } }

implementation:
if ( dateRange == null ) return null ; if ( cal . equals ( Calendar . getDefault ( ) ) ) return dateRange ; // otherwise must reparse
return makeCalendarDateRange ( cal ) ;


signature:
public class CoordinateSharerBest { /** * redo the variables against the shared coordinates */
public List < Integer > reindex ( List < Coordinate > coords ) { } }

implementation:
List < Integer > result = new ArrayList < > ( ) ; for ( Coordinate coord : coords ) { Coordinate sub = swap . get ( coord ) ; Coordinate use = ( sub == null ) ? coord : sub ; Integer idx = indexMap . get ( use ) ; // index into unionCoords
if ( idx == null ) { throw new IllegalStateException ( ) ; } result . add ( idx ) ; } return result ;


signature:
public class NetcdfFileWriter { /** * Open an existing Netcdf file for writing data . Fill mode is true .
 * Cannot add new objects , you can only read / write data to existing Variables .
 * @ param location name of existing file to open .
 * @ return existing file that can be written to
 * @ throws java . io . IOException on I / O error */
static public NetcdfFileWriter openExisting ( String location ) throws IOException { } }

implementation: return new NetcdfFileWriter ( null , location , true , null ) ; // dont know the version yet


signature:
public class NetcdfFileWriter { /** * Create a new Netcdf file , with fill mode true .
 * @ param version netcdf - 3 or 4
 * @ param location name of new file to open ; if it exists , will overwrite it .
 * @ param chunker used only for netcdf4 , or null for default chunking algorithm
 * @ return new NetcdfFileWriter
 * @ throws IOException on I / O error */
static public NetcdfFileWriter createNew ( Version version , String location , Nc4Chunking chunker ) throws IOException { } }

implementation: return new NetcdfFileWriter ( version , location , false , chunker ) ;


signature:
public class NetcdfFileWriter { /** * / / use these calls in define mode */
public Dimension addDimension ( String dimName , int length ) { } }

implementation: return addDimension ( null , dimName , length , false , false ) ;


signature:
public class NetcdfFileWriter { /** * Add a shared Dimension to the file . Must be in define mode .
 * @ param dimName name of dimension
 * @ param length size of dimension .
 * @ return the created dimension */
public Dimension addDimension ( Group g , String dimName , int length ) { } }

implementation: return addDimension ( g , dimName , length , false , false ) ;


signature:
public class NetcdfFileWriter { /** * Add a shared Dimension to the file . Must be in define mode .
 * @ param dimName name of dimension
 * @ param length size of dimension .
 * @ param isUnlimited if dimension is unlimited
 * @ param isVariableLength if dimension is variable length
 * @ return the created dimension */
public Dimension addDimension ( Group g , String dimName , int length , boolean isUnlimited , boolean isVariableLength ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( dimName ) ) throw new IllegalArgumentException ( "illegal dimension name " + dimName ) ; Dimension dim = new Dimension ( dimName , length , true , isUnlimited , isVariableLength ) ; ncfile . addDimension ( g , dim ) ; return dim ;


signature:
public class NetcdfFileWriter { /** * Rename a Dimension . Must be in define mode .
 * @ param oldName existing dimension has this name
 * @ param newName rename to this
 * @ return renamed dimension , or null if not found */
public Dimension renameDimension ( Group g , String oldName , String newName ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( newName ) ) throw new IllegalArgumentException ( "illegal dimension name " + newName ) ; if ( g == null ) g = ncfile . getRootGroup ( ) ; Dimension dim = g . findDimension ( oldName ) ; if ( null != dim ) dim . setName ( newName ) ; return dim ;


signature:
public class NetcdfFileWriter { /** * Add a Group to the file . Must be in define mode .
 * If pass in null as the parent then the root group is returned and the name is ignored .
 * This is how you get the root group . Note this is different from other uses of parent group .
 * @ param parent the parent of this group , if null then returns the root group .
 * @ param name the name of this group , unique within parent
 * @ return the created group */
public Group addGroup ( Group parent , String name ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( parent == null ) return ncfile . getRootGroup ( ) ; Group result = new Group ( ncfile , parent , name ) ; parent . addGroup ( result ) ; return result ;


signature:
public class NetcdfFileWriter { /** * Add a Global attribute to the file . Must be in define mode .
 * @ param g the group to add to . if null , use root group
 * @ param att the attribute .
 * @ return the created attribute */
public Attribute addGroupAttribute ( Group g , Attribute att ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( att . getShortName ( ) ) ) { String attName = createValidObjectName ( att . getShortName ( ) ) ; log . warn ( "illegal attribute name= " + att . getShortName ( ) + " change to " + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } return ncfile . addAttribute ( g , att ) ;


signature:
public class NetcdfFileWriter { /** * Add a EnumTypedef to the file . Must be in define mode .
 * @ param g the group to add to . if null , use root group
 * @ param td the EnumTypedef .
 * @ return the created attribute */
public EnumTypedef addTypedef ( Group g , EnumTypedef td ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! version . isExtendedModel ( ) ) throw new IllegalArgumentException ( "Enum type only supported in extended model, this version is=" + version ) ; g . addEnumeration ( td ) ; return td ;


signature:
public class NetcdfFileWriter { /** * Delete a group Attribute . Must be in define mode .
 * @ param g the group to add to . if null , use root group
 * @ param attName existing Attribute has this name
 * @ return deleted Attribute , or null if not found */
public Attribute deleteGroupAttribute ( Group g , String attName ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( g == null ) g = ncfile . getRootGroup ( ) ; Attribute att = g . findAttribute ( attName ) ; if ( null == att ) return null ; g . remove ( att ) ; return att ;


signature:
public class NetcdfFileWriter { /** * Rename a group Attribute . Must be in define mode .
 * @ param g the group to add to . if null , use root group
 * @ param oldName existing Attribute has this name
 * @ param newName rename to this
 * @ return renamed Attribute , or null if not found */
public Attribute renameGroupAttribute ( Group g , String oldName , String newName ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( newName ) ) { String newnewName = createValidObjectName ( newName ) ; log . warn ( "illegal attribute name= " + newName + " change to " + newnewName ) ; newName = newnewName ; } if ( g == null ) g = ncfile . getRootGroup ( ) ; Attribute att = g . findAttribute ( oldName ) ; if ( null == att ) return null ; g . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; g . addAttribute ( att ) ; return att ;


signature:
public class NetcdfFileWriter { /** * Add a variable to the file . Must be in define mode .
 * @ param g the group to add to . if null , use root group
 * @ param shortName name of Variable , must be unique with the file .
 * @ param dataType type of underlying element
 * @ param dimString names of Dimensions for the variable , blank separated .
 * Must already have been added . Use an empty string for a scalar variable .
 * @ return the Variable that has been added */
public Variable addVariable ( Group g , String shortName , DataType dataType , String dimString ) { } }

implementation: Group parent = ( g == null ) ? ncfile . getRootGroup ( ) : g ; return addVariable ( g , null , shortName , dataType , Dimension . makeDimensionsList ( parent , dimString ) ) ;


signature:
public class NetcdfFileWriter { /** * Add a variable to the file . Must be in define mode .
 * @ param g add to this group in the new file
 * @ param shortName name of Variable , must be unique with the file .
 * @ param dataType type of underlying element
 * @ param dims list of Dimensions for the variable in the new file , must already have been added .
 * Use a list of length 0 for a scalar variable .
 * @ return the Variable that has been added , or null if a Variable with shortName already exists in the group */
public Variable addVariable ( Group g , String shortName , DataType dataType , List < Dimension > dims ) { } }

implementation: if ( g == null ) g = ncfile . getRootGroup ( ) ; Variable oldVar = g . findVariable ( shortName ) ; if ( oldVar != null ) return null ; return addVariable ( g , null , shortName , dataType , dims ) ;


signature:
public class NetcdfFileWriter { /** * Add a variable to the file . Must be in define mode .
 * @ param g add to this group in the new file
 * @ param parent parent Structure ( netcdf4 only ) , or null if not a member of a Structure
 * @ param shortName name of Variable , must be unique with the file .
 * @ param dataType type of underlying element
 * @ param dims list of Dimensions for the variable in the new file , must already have been added .
 * Use a list of length 0 for a scalar variable .
 * @ return the Variable that has been added */
public Variable addVariable ( Group g , Structure parent , String shortName , DataType dataType , List < Dimension > dims ) { } }

implementation:
if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; DataType writeType = version . isExtendedModel ( ) ? dataType : dataType . withSignedness ( DataType . Signedness . SIGNED ) ; // use signed type for netcdf3
boolean usingSignForUnsign = writeType != dataType ; if ( ! isValidDataType ( writeType ) ) throw new IllegalArgumentException ( "illegal dataType: " + dataType + " not supported in netcdf-3" ) ; // check unlimited if classic model
if ( ! version . isExtendedModel ( ) ) { for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { Dimension d = dims . get ( i ) ; if ( d . isUnlimited ( ) && ( i != 0 ) ) throw new IllegalArgumentException ( "Unlimited dimension " + d . getShortName ( ) + " must be first (outermost) in netcdf-3 " ) ; } } shortName = makeValidObjectName ( shortName ) ; Variable v ; if ( dataType == DataType . STRUCTURE ) { v = new Structure ( ncfile , g , parent , shortName ) ; } else { v = new Variable ( ncfile , g , parent , shortName ) ; } v . setDataType ( writeType ) ; v . setDimensions ( dims ) ; if ( usingSignForUnsign ) v . addAttribute ( new Attribute ( CDM . UNSIGNED , "true" ) ) ; long size = v . getSize ( ) * v . getElementSize ( ) ; if ( version == Version . netcdf3 && size > N3iosp . MAX_VARSIZE ) throw new IllegalArgumentException ( "Variable size in bytes " + size + " may not exceed " + N3iosp . MAX_VARSIZE ) ; // System . out . printf ( " Variable size in bytes " + size + " may not exceed " + N3iosp . MAX _ VARSIZE ) ;
ncfile . addVariable ( g , v ) ; return v ;


signature:
public class NetcdfFileWriter { /** * Adds a copy of the specified structure to the file ( netcdf4 only ) . DO NOT USE YET
 * @ param g add to this group in the new file
 * @ param original the structure to make a copy of in the new file .
 * @ param shortName name of Variable , must be unique with the file .
 * @ param dims list of Dimensions for the variable in the new file , must already have been added .
 * Use a list of length 0 for a scalar variable .
 * @ return the Structure variable that has been added */
public Structure addCopyOfStructure ( Group g , @ Nonnull Structure original , String shortName , List < Dimension > dims ) { } }

implementation:
if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( original == null ) throw new NullPointerException ( "Original structure must be non-null" ) ; shortName = makeValidObjectName ( shortName ) ; if ( ! version . isExtendedModel ( ) ) throw new IllegalArgumentException ( "Structure type only supported in extended model, version=" + version ) ; Structure s = new Structure ( ncfile , g , null , shortName ) ; s . setDimensions ( dims ) ; for ( Variable m : original . getVariables ( ) ) { // LOOK no nested structs
Variable nest = new Variable ( ncfile , g , s , m . getShortName ( ) ) ; nest . setDataType ( m . getDataType ( ) ) ; nest . setDimensions ( m . getDimensions ( ) ) ; nest . addAll ( m . getAttributes ( ) ) ; s . addMemberVariable ( nest ) ; } ncfile . addVariable ( g , s ) ; return s ;


signature:
public class NetcdfFileWriter { /** * Add a variable with DataType = String to a netCDF - 3 file . Must be in define mode .
 * The variable will be stored in the file as a CHAR variable .
 * A new dimension with name " stringVar . getShortName ( ) _ strlen " is automatically
 * added , with length max _ strlen , as determined from the data contained in the
 * stringVar .
 * @ param g add to this group in the new file
 * @ param stringVar string variable .
 * @ param dims list of Dimensions for the string variable .
 * @ return the CHAR variable generated from stringVar */
public Variable addStringVariable ( Group g , Variable stringVar , List < Dimension > dims ) { } }

implementation:
if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( stringVar . getShortName ( ) ) ) throw new IllegalArgumentException ( "illegal netCDF-3 variable name: " + stringVar . getShortName ( ) ) ; // convert STRING to CHAR
int max_strlen = 0 ; Array data ; try { data = stringVar . read ( ) ; IndexIterator ii = data . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . getObjectNext ( ) ; max_strlen = Math . max ( max_strlen , s . length ( ) ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; String err = "No data found for Variable " + stringVar . getShortName ( ) + ". Cannot determine the lentgh of the new CHAR variable." ; log . error ( err ) ; System . out . println ( err ) ; } return addStringVariable ( g , stringVar . getShortName ( ) , dims , max_strlen ) ;


signature:
public class NetcdfFileWriter { /** * Add a variable with DataType = String to the file . Must be in define mode .
 * The variable will be stored in the file as a CHAR variable .
 * A new dimension with name " varName _ strlen " is automatically added , with length max _ strlen .
 * @ param shortName name of Variable , must be unique within the file .
 * @ param dims list of Dimensions for the variable , must already have been added . Use a list of length 0
 * for a scalar variable . Do not include the string length dimension .
 * @ param max _ strlen maximum string length .
 * @ return the Variable that has been added */
public Variable addStringVariable ( Group g , String shortName , List < Dimension > dims , int max_strlen ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; shortName = makeValidObjectName ( shortName ) ; Variable v = new Variable ( ncfile , g , null , shortName ) ; v . setDataType ( DataType . CHAR ) ; Dimension d = addDimension ( g , shortName + "_strlen" , max_strlen ) ; List < Dimension > sdims = new ArrayList < > ( dims ) ; sdims . add ( d ) ; v . setDimensions ( sdims ) ; ncfile . addVariable ( g , v ) ; return v ;


signature:
public class NetcdfFileWriter { /** * Rename a Variable . Must be in define mode .
 * @ param oldName existing Variable has this name
 * @ param newName rename to this
 * @ return renamed Variable , or null if not found */
public Variable renameVariable ( String oldName , String newName ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Variable v = ncfile . findVariable ( oldName ) ; if ( null != v ) { String fullOldNameEscaped = v . getFullNameEscaped ( ) ; v . setName ( newName ) ; varRenameMap . put ( v . getFullNameEscaped ( ) , fullOldNameEscaped ) ; } return v ;


signature:
public class NetcdfFileWriter { /** * Add an attribute to the named Variable . Must be in define mode .
 * @ param v Variable to add attribute to
 * @ param att Attribute to add .
 * @ return true if attribute was added , false if not allowed by CDM . */
public boolean addVariableAttribute ( Variable v , Attribute att ) { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( att . getShortName ( ) ) ) { String attName = createValidObjectName ( att . getShortName ( ) ) ; log . warn ( "illegal netCDF-3 attribute name= " + att . getShortName ( ) + " change to " + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } v . addAttribute ( att ) ; return true ;


signature:
public class NetcdfFileWriter { /** * After you have added all of the Dimensions , Variables , and Attributes ,
 * call create ( ) to actually create the file . You must be in define mode .
 * After this call , you are no longer in define mode .
 * @ throws java . io . IOException if I / O error */
public void create ( ) throws java . io . IOException { } }

implementation: if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isNewFile ) throw new UnsupportedOperationException ( "can only call create on a new file" ) ; ncfile . finish ( ) ; spiw . setFill ( fill ) ; spiw . create ( location , ncfile , extraHeader , preallocateSize , isLargeFile ) ; defineMode = false ;


signature:
public class NetcdfFileWriter { /** * Set the redefine mode .
 * Designed to emulate nc _ redef ( redefineMode = true ) and
 * nc _ enddef ( redefineMode = false )
 * @ param redefineMode start or end define mode
 * @ return true if it had to rewrite the entire file , false if it wrote the header in place
 * @ throws java . io . IOException on read / write error */
public boolean setRedefineMode ( boolean redefineMode ) throws IOException { } }

implementation:
if ( redefineMode && ! defineMode ) { defineMode = true ; } else if ( ! redefineMode && defineMode ) { defineMode = false ; ncfile . finish ( ) ; // try to rewrite header , if it fails , then we have to rewrite entire file
boolean ok = spiw . rewriteHeader ( isLargeFile ) ; // LOOK seems like we should be using isNewFile
if ( ! ok ) rewrite ( ) ; return ! ok ; } return false ;


signature:
public class NetcdfFileWriter { /** * rewrite entire file */
private void rewrite ( ) throws IOException { } }

implementation:
// close existing file , rename and open as read - only
spiw . flush ( ) ; spiw . close ( ) ; File prevFile = new File ( location ) ; if ( ! prevFile . exists ( ) ) { return ; } File tmpFile = new File ( location + ".tmp" ) ; if ( tmpFile . exists ( ) ) { boolean ok = tmpFile . delete ( ) ; if ( ! ok ) log . warn ( "rewrite unable to delete {}" , tmpFile . getPath ( ) ) ; } if ( ! prevFile . renameTo ( tmpFile ) ) { System . out . println ( prevFile . getPath ( ) + " prevFile.exists " + prevFile . exists ( ) + " canRead = " + prevFile . canRead ( ) ) ; System . out . println ( tmpFile . getPath ( ) + " tmpFile.exists " + tmpFile . exists ( ) + " canWrite " + tmpFile . canWrite ( ) ) ; throw new RuntimeException ( "Cant rename " + prevFile . getAbsolutePath ( ) + " to " + tmpFile . getAbsolutePath ( ) ) ; } NetcdfFile oldFile = NetcdfFile . open ( tmpFile . getPath ( ) ) ; /* use record dimension if it has one
 Structure recordVar = null ;
 if ( oldFile . hasUnlimitedDimension ( ) ) {
 oldFile . sendIospMessage ( NetcdfFile . IOSP _ MESSAGE _ ADD _ RECORD _ STRUCTURE ) ;
 recordVar = ( Structure ) oldFile . findVariable ( " record " ) ;
 / * if ( recordVar ! = null ) {
 Boolean result = ( Boolean ) spiw . sendIospMessage ( NetcdfFile . IOSP _ MESSAGE _ ADD _ RECORD _ STRUCTURE ) ;
 if ( ! result )
 recordVar = null ; */
// create new file with current set of objects
spiw . create ( location , ncfile , extraHeader , preallocateSize , isLargeFile ) ; spiw . setFill ( fill ) ; // isClosed = false ;
/* wait till header is written before adding the record variable to the file
 if ( recordVar ! = null ) {
 Boolean result = ( Boolean ) spiw . sendIospMessage ( NetcdfFile . IOSP _ MESSAGE _ ADD _ RECORD _ STRUCTURE ) ;
 if ( ! result )
 recordVar = null ; */
FileWriter2 fileWriter2 = new FileWriter2 ( this ) ; for ( Variable v : ncfile . getVariables ( ) ) { String oldVarName = v . getFullName ( ) ; Variable oldVar = oldFile . findVariable ( oldVarName ) ; if ( oldVar != null ) { fileWriter2 . copyAll ( oldVar , v ) ; } else if ( varRenameMap . containsKey ( oldVarName ) ) { // var name has changed in ncfile - use the varRenameMap to find
// the correct variable name to request from oldFile
String realOldVarName = varRenameMap . get ( oldVarName ) ; oldVar = oldFile . findVariable ( realOldVarName ) ; if ( oldVar != null ) { fileWriter2 . copyAll ( oldVar , v ) ; } } else { String message = "Cannot find variable " + oldVarName + " to copy to new file." ; log . warn ( message ) ; System . out . println ( message ) ; } } // delete old
oldFile . close ( ) ; if ( ! tmpFile . delete ( ) ) throw new RuntimeException ( "Cant delete " + tmpFile . getAbsolutePath ( ) ) ;


signature:
public class NetcdfFileWriter { /** * For netcdf3 only , take all unlimited variables and make them into a structure .
 * @ return the record Structure , or null if not done . */
public Structure addRecordStructure ( ) { } }

implementation: if ( version != Version . netcdf3 ) return null ; boolean ok = ( Boolean ) ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ! ok ) throw new IllegalStateException ( "can't add record variable" ) ; return ( Structure ) ncfile . findVariable ( "record" ) ;


signature:
public class NetcdfFileWriter { /** * / / use these calls to write data to the file */
public void write ( String varname , Array values ) throws java . io . IOException , InvalidRangeException { } }

implementation: write ( findVariable ( varname ) , values ) ;


signature:
public class NetcdfFileWriter { /** * Write data to the named variable , origin assumed to be 0 . Must not be in define mode .
 * @ param v variable to write to
 * @ param values write this array ; must be same type and rank as Variable
 * @ throws IOException if I / O error
 * @ throws ucar . ma2 . InvalidRangeException if values Array has illegal shape */
public void write ( Variable v , Array values ) throws java . io . IOException , InvalidRangeException { } }

implementation: if ( ncfile != v . getNetcdfFile ( ) ) throw new IllegalArgumentException ( "Variable is not owned by this writer." ) ; write ( v , new int [ values . getRank ( ) ] , values ) ;


signature:
public class NetcdfFileWriter { /** * Write data to the named variable . Must not be in define mode .
 * @ param v variable to write to
 * @ param origin offset within the variable to start writing .
 * @ param values write this array ; must be same type and rank as Variable
 * @ throws IOException if I / O error
 * @ throws ucar . ma2 . InvalidRangeException if values Array has illegal shape */
public void write ( Variable v , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { } }

implementation: if ( defineMode ) throw new UnsupportedOperationException ( "in define mode" ) ; spiw . writeData ( v , new Section ( origin , values . getShape ( ) ) , values ) ; v . invalidateCache ( ) ;


signature:
public class NetcdfFileWriter { /** * Write String data to a CHAR variable , origin assumed to be 0 . Must not be in define mode .
 * @ param v variable to write to
 * @ param values write this array ; must be ArrayObject of String
 * @ throws IOException if I / O error
 * @ throws ucar . ma2 . InvalidRangeException if values Array has illegal shape */
public void writeStringData ( Variable v , Array values ) throws java . io . IOException , InvalidRangeException { } }

implementation: writeStringData ( v , new int [ values . getRank ( ) ] , values ) ;


signature:
public class NetcdfFileWriter { /** * Write String data to a CHAR variable . Must not be in define mode .
 * @ param v variable to write to
 * @ param origin offset to start writing , ignore the strlen dimension .
 * @ param values write this array ; must be ArrayObject of String
 * @ throws IOException if I / O error
 * @ throws ucar . ma2 . InvalidRangeException if values Array has illegal shape */
public void writeStringData ( Variable v , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { } }

implementation:
if ( values . getElementType ( ) != String . class ) throw new IllegalArgumentException ( "Must be ArrayObject of String " ) ; if ( v . getDataType ( ) != DataType . CHAR ) throw new IllegalArgumentException ( "variable " + v . getFullName ( ) + " is not type CHAR" ) ; int rank = v . getRank ( ) ; int strlen = v . getShape ( rank - 1 ) ; // turn it into an ArrayChar
ArrayChar cvalues = ArrayChar . makeFromStringArray ( ( ArrayObject ) values , strlen ) ; int [ ] corigin = new int [ rank ] ; System . arraycopy ( origin , 0 , corigin , 0 , rank - 1 ) ; write ( v , corigin , cvalues ) ;


signature:
public class NetcdfFileWriter { /** * close the file .
 * @ throws IOException if I / O error */
public synchronized void close ( ) throws java . io . IOException { } }

implementation: if ( spiw != null ) { setRedefineMode ( false ) ; flush ( ) ; spiw . close ( ) ; spiw = null ; }


signature:
public class NetcdfFileWriter { /** * Abort writing to this file . The file is closed .
 * @ throws java . io . IOException */
public void abort ( ) throws java . io . IOException { } }

implementation: if ( spiw != null ) { spiw . close ( ) ; spiw = null ; }


signature:
public class Bean { /** * write XML using the bean properties of the contained object */
public void writeProperties ( PrintWriter out ) throws IOException { } }

implementation: if ( p == null ) p = BeanParser . getParser ( o . getClass ( ) ) ; p . writeProperties ( o , out ) ;


signature:
public class ThreddsMetadataExtractor { /** * extract info from underlying feature dataset
 * @ param threddsDataset call DataFactory ( ) . openFeatureDataset ( ) to open it
 * @ return results in ThreddsMetadata object
 * @ throws IOException */
public ThreddsMetadata extract ( Dataset threddsDataset ) throws IOException { } }

implementation:
ThreddsMetadata metadata = new ThreddsMetadata ( ) ; Map < String , Object > flds = metadata . getFlds ( ) ; try ( DataFactory . Result result = new DataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ) { if ( result . fatalError ) { logger . warn ( " openFeatureDataset failed, errs=%s%n" , result . errLog ) ; return null ; } if ( result . featureType . isCoverageFeatureType ( ) ) { GridDataset gridDataset = ( GridDataset ) result . featureDataset ; // LOOK wrong
flds . put ( Dataset . GeospatialCoverage , extractGeospatial ( gridDataset ) ) ; CalendarDateRange tc = extractCalendarDateRange ( gridDataset ) ; if ( tc != null ) flds . put ( Dataset . TimeCoverage , tc ) ; ThreddsMetadata . VariableGroup vars = extractVariables ( threddsDataset . getDataFormatName ( ) , gridDataset ) ; if ( vars != null ) flds . put ( Dataset . VariableGroups , vars ) ; } else if ( result . featureType . isPointFeatureType ( ) ) { PointDatasetImpl pobsDataset = ( PointDatasetImpl ) result . featureDataset ; LatLonRect llbb = pobsDataset . getBoundingBox ( ) ; if ( null != llbb ) flds . put ( Dataset . GeospatialCoverage , new ThreddsMetadata . GeospatialCoverage ( llbb , null , 0.0 , 0.0 ) ) ; CalendarDateRange tc = extractCalendarDateRange ( pobsDataset ) ; if ( tc != null ) flds . put ( Dataset . TimeCoverage , tc ) ; ThreddsMetadata . VariableGroup vars = extractVariables ( pobsDataset ) ; if ( vars != null ) flds . put ( Dataset . VariableGroups , vars ) ; } } catch ( IOException ioe ) { logger . error ( "Error opening dataset " + threddsDataset . getName ( ) , ioe ) ; } return metadata ;


signature: public class ThreddsMetadataExtractor { public ThreddsMetadata . GeospatialCoverage extractGeospatial ( FeatureDatasetPoint fd ) { } }

implementation: LatLonRect llbb = fd . getBoundingBox ( ) ; if ( llbb != null ) { return new ThreddsMetadata . GeospatialCoverage ( llbb , null , 0.0 , 0.0 ) ; } return null ;


signature: public class ThreddsMetadataExtractor { public CalendarDateRange extractCalendarDateRange ( GridDataset gridDataset ) { } }

implementation:
CalendarDateRange maxDateRange = null ; for ( GridDataset . Gridset gridset : gridDataset . getGridsets ( ) ) { GridCoordSystem gsys = gridset . getGeoCoordSystem ( ) ; CalendarDateRange dateRange ; CoordinateAxis1DTime time1D = gsys . getTimeAxis1D ( ) ; if ( time1D != null ) { dateRange = time1D . getCalendarDateRange ( ) ; } else { CoordinateAxis time = gsys . getTimeAxis ( ) ; if ( time == null ) continue ; try { CalendarDateUnit du = CalendarDateUnit . of ( null , time . getUnitsString ( ) ) ; // LOOK no calendar
CalendarDate minDate = du . makeCalendarDate ( time . getMinValue ( ) ) ; CalendarDate maxDate = du . makeCalendarDate ( time . getMaxValue ( ) ) ; dateRange = CalendarDateRange . of ( minDate , maxDate ) ; } catch ( Exception e ) { logger . warn ( "Illegal Date Unit " + time . getUnitsString ( ) ) ; continue ; } } if ( maxDateRange == null ) maxDateRange = dateRange ; else maxDateRange = maxDateRange . extend ( dateRange ) ; } return maxDateRange ;


signature:
public class GribVariableRenamer { /** * Look for possible matches of old ( 4.2 ) grib names in new ( 4.3 ) dataset .
 * @ param gds check existence in this dataset . Must be from a GRIB1 or GRIB2 dataset .
 * @ param oldName old name from 4.2 dataset
 * @ return list of possible matches ( as grid short name ) , each exists in the dataset */
List < String > matchNcepNames ( GridDataset gds , String oldName ) { } }

implementation:
List < String > result = new ArrayList < > ( ) ; // look for exact match
if ( contains ( gds , oldName ) ) { result . add ( oldName ) ; return result ; } Attribute att = gds . findGlobalAttributeIgnoreCase ( CDM . FILE_FORMAT ) ; boolean isGrib1 = ( att != null ) && att . getStringValue ( ) . startsWith ( "GRIB-1" ) ; boolean isGrib2 = ( att != null ) && att . getStringValue ( ) . startsWith ( "GRIB-2" ) ; HashMap < String , Renamer > map ; if ( isGrib1 ) { if ( map1 == null ) initMap1 ( ) ; map = map1 ; } else if ( isGrib2 ) { if ( map2 == null ) initMap2 ( ) ; map = map2 ; } else { return result ; // empty list
} // look in our renamer map
Renamer mbean = map . get ( oldName ) ; if ( mbean != null && mbean . newName != null && contains ( gds , mbean . newName ) ) { result . add ( mbean . newName ) ; // if its unique , then we are done
return result ; } // not unique - match against NCEP dataset
if ( mbean != null ) { String dataset = extractDatasetFromLocation ( gds . getLocation ( ) ) ; for ( VariableRenamerBean r : mbean . newVars ) { if ( r . getDatasetType ( ) . equals ( dataset ) && contains ( gds , r . newName ) ) result . add ( r . newName ) ; } if ( result . size ( ) == 1 ) return result ; // return if unique
} // not unique , no unique match against dataset - check existence in the dataset
result . clear ( ) ; if ( mbean != null ) { for ( VariableRenamerBean r : mbean . newVarsMap . values ( ) ) { if ( contains ( gds , r . newName ) ) result . add ( r . newName ) ; } if ( result . size ( ) > 0 ) return result ; } // try to map oldName - > new prefix
result . clear ( ) ; String oldMunged = munge ( oldName ) ; for ( GridDatatype grid : gds . getGrids ( ) ) { String newMunged = munge ( grid . getShortName ( ) ) ; if ( newMunged . startsWith ( oldMunged ) ) result . add ( grid . getShortName ( ) ) ; } if ( result . size ( ) > 0 ) return result ; // return empty list
return result ;


signature: public class GribVariableRenamer { private HashMap < String , Renamer > makeMapBeans ( List < VariableRenamerBean > vbeans ) { } }

implementation:
HashMap < String , Renamer > map = new HashMap < > ( 3000 ) ; for ( VariableRenamerBean vbean : vbeans ) { // construct the old - > new mapping
Renamer mbean = map . get ( vbean . getOldName ( ) ) ; if ( mbean == null ) { mbean = new Renamer ( vbean . getOldName ( ) ) ; map . put ( vbean . getOldName ( ) , mbean ) ; } mbean . add ( vbean ) ; } for ( Renamer rmap : map . values ( ) ) { rmap . finish ( ) ; } return map ;


signature:
public class NcMeasurementTimeseriesType { /** * wml2 : Collection / wml2 : observationMember / om : OM _ Observation / om : result / wml2 : MeasurementTimeseries */
public static MeasurementTimeseriesType initMeasurementTimeseries ( MeasurementTimeseriesType measurementTimeseries , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { } }

implementation:
// @ gml : id
String id = MarshallingUtil . createIdForType ( MeasurementTimeseriesType . class ) ; measurementTimeseries . setId ( id ) ; // wml2 : defaultPointMetadata
NcTVPDefaultMetadataPropertyType . initDefaultPointMetadata ( measurementTimeseries . addNewDefaultPointMetadata ( ) , dataVar ) ; // wml2 : point [ 0 . . * ]
for ( PointFeature pf : stationFeat ) { // wml2 : point
Point . initPoint ( measurementTimeseries . addNewPoint ( ) , pf , dataVar ) ; } return measurementTimeseries ;


signature:
public class OffsetUnit { /** * Multiply this unit by another unit .
 * @ param that
 * The unit to multiply this unit by .
 * @ return The product of this unit and < code > that < / code > . The offset of
 * this unit will be ignored ; thus , for example
 * " celsius . myMultiplyBy ( day ) " is equivalent to
 * " kelvin . myMultiplyBy ( day ) " .
 * @ throws MultiplyException
 * Can ' t multiply these units together . */
@ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { } }

implementation: return that instanceof OffsetUnit ? getUnit ( ) . multiplyBy ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . multiplyBy ( that ) ;