signature:
public class GempakSoundingFileReader { /** * Make the header for the text report
 * @ param stn the station
 * @ param date the date
 * @ return the header */
private String makeHeader ( GempakStation stn , String date ) { } }

implementation: StringBuilder builder = new StringBuilder ( ) ; builder . append ( "STID = " ) ; builder . append ( StringUtil2 . padRight ( ( stn . getSTID ( ) . trim ( ) + stn . getSTD2 ( ) . trim ( ) ) , 8 ) ) ; builder . append ( "\t" ) ; builder . append ( "STNM = " ) ; builder . append ( Format . i ( stn . getSTNM ( ) , 6 ) ) ; builder . append ( "\t" ) ; builder . append ( "TIME = " ) ; builder . append ( date ) ; builder . append ( "\n" ) ; builder . append ( "SLAT = " ) ; builder . append ( Format . d ( stn . getLatitude ( ) , 5 ) ) ; builder . append ( "\t" ) ; builder . append ( "SLON = " ) ; builder . append ( Format . d ( stn . getLongitude ( ) , 5 ) ) ; builder . append ( "\t" ) ; builder . append ( "SELV = " ) ; builder . append ( Format . d ( stn . getAltitude ( ) , 5 ) ) ; builder . append ( "\n" ) ; return builder . toString ( ) ;


signature:
public class GempakSoundingFileReader { /** * This subroutine checks the parts in a sounding data set for the
 * unmerged data types .
 * @ return list of part names */
private List < String > SN_CKUA ( ) { } }

implementation:
List < String > types = new ArrayList < > ( ) ; boolean above = false ; boolean done = false ; String partToCheck ; while ( ! done ) { // check for mandatory groups
for ( int group = 0 ; group < belowGroups . length ; group ++ ) { if ( above ) { partToCheck = aboveGroups [ group ] ; } else { partToCheck = belowGroups [ group ] ; } if ( checkForValidGroup ( partToCheck , parmLists [ group ] ) ) { types . add ( partToCheck ) ; } } if ( ! above ) { above = true ; } else { done = true ; } } return types ;


signature:
public class GempakSoundingFileReader { /** * Check for valid groups
 * @ param partToCheck the part name
 * @ param params the parameters that are supposed to be there
 * @ return true if the part is there and has the right params */
private boolean checkForValidGroup ( String partToCheck , String [ ] params ) { } }

implementation: DMPart part = getPart ( partToCheck ) ; if ( part == null ) { return false ; } int i = 0 ; for ( DMParam parm : part . params ) { if ( ! ( parm . kprmnm . equals ( params [ i ++ ] ) ) ) { return false ; } } return true ;


signature:
public class GempakSoundingFileReader { /** * Run the program
 * @ param args [ 0 ] filename ( required ) ,
 * [ 1 ] variable name ( X for default ) ,
 * [ 2 ] X to not list grids
 * @ throws IOException problem reading the file */
public static void main ( String [ ] args ) throws IOException { } }

implementation: if ( args . length == 0 ) { System . out . println ( "need to supply a GEMPAK sounding file name" ) ; System . exit ( 1 ) ; } try { GempakParameters . addParameters ( "resources/nj22/tables/gempak/params.tbl" ) ; } catch ( Exception e ) { System . out . println ( "unable to init param tables" ) ; } GempakSoundingFileReader gsfr = getInstance ( getFile ( args [ 0 ] ) , true ) ; System . out . println ( "Type = " + gsfr . getFileType ( ) ) ; gsfr . printFileLabel ( ) ; gsfr . printKeys ( ) ; gsfr . printHeaders ( ) ; gsfr . printParts ( ) ; gsfr . printDates ( ) ; gsfr . printStations ( false ) ; int row = 1 ; int col = 1 ; if ( args . length > 1 ) { row = Integer . parseInt ( args [ 1 ] ) ; } if ( args . length > 2 ) { try { col = Integer . parseInt ( args [ 2 ] ) ; } catch ( Exception npe ) { col = gsfr . findStationIndex ( args [ 2 ] ) ; if ( col == - 1 ) { System . out . println ( "couldn't find station " + args [ 2 ] ) ; System . exit ( 1 ) ; } System . out . println ( "found station at column " + col ) ; } } gsfr . printOb ( row , col ) ;


signature:
public class DiskCache { /** * Set the cache root directory . Create it if it doesnt exist .
 * @ param cacheDir the cache directory */
static public void setRootDirectory ( String cacheDir ) { } }

implementation:
if ( ! cacheDir . endsWith ( "/" ) ) cacheDir = cacheDir + "/" ; root = StringUtil2 . replace ( cacheDir , '\\' , "/" ) ; // no nasty backslash
makeRootDirectory ( ) ;


signature:
public class DiskCache { /** * Make sure that the current root directory exists . */
static public void makeRootDirectory ( ) { } }

implementation: File dir = new File ( root ) ; if ( ! dir . exists ( ) ) if ( ! dir . mkdirs ( ) ) throw new IllegalStateException ( "DiskCache.setRootDirectory(): could not create root directory <" + root + ">." ) ; checkExist = true ;


signature:
public class DiskCache { /** * Get a File if it exists . If not , get a File that can be written to .
 * If alwaysInCache , look only in the cache , otherwise , look in the " normal " location first ,
 * then in the cache .
 * @ param fileLocation normal file location
 * @ param alwaysInCache true if you want to look only in the cache
 * @ return a File that either exists or is writeable . */
static public File getFile ( String fileLocation , boolean alwaysInCache ) { } }

implementation:
if ( alwaysInCache ) { return getCacheFile ( fileLocation ) ; } else { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; // now comes the tricky part to make sure we can open and write to it
try { if ( ! simulateUnwritableDir && f . createNewFile ( ) ) { boolean ret = f . delete ( ) ; assert ret ; return f ; } } catch ( IOException e ) { // cant write to it - drop through
} return getCacheFile ( fileLocation ) ; }


signature:
public class DiskCache { /** * Get a file in the cache .
 * File may or may not exist . We assume its always writeable .
 * If it does exist , set its LastModifiedDate to current time .
 * @ param fileLocation normal file location
 * @ return equivalent File in the cache . */
static public File getCacheFile ( String fileLocation ) { } }

implementation: File f = new File ( makeCachePath ( fileLocation ) ) ; if ( f . exists ( ) ) { if ( ! f . setLastModified ( System . currentTimeMillis ( ) ) ) logger . warn ( "Failed to setLastModified on " + f . getPath ( ) ) ; } if ( ! checkExist ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) logger . warn ( "Failed to mkdirs on " + dir . getPath ( ) ) ; checkExist = true ; } return f ;


signature:
public class DiskCache { /** * Make the cache filename
 * @ param fileLocation normal file location
 * @ return cache filename */
static private String makeCachePath ( String fileLocation ) { } }

implementation:
Escaper urlPathEscaper = UrlEscapers . urlPathSegmentEscaper ( ) ; fileLocation = fileLocation . replace ( '\\' , '/' ) ; // LOOK - use better normalization code eg Spring StringUtils
String cachePath = urlPathEscaper . escape ( fileLocation ) ; return root + cachePath ;


signature:
public class DiskCache { /** * Remove all files with date < cutoff .
 * @ param cutoff earliest date to allow
 * @ param sbuff write results here , null is ok . */
static public void cleanCache ( Date cutoff , StringBuilder sbuff ) { } }

implementation: if ( sbuff != null ) sbuff . append ( "CleanCache files before " ) . append ( cutoff ) . append ( "\n" ) ; File dir = new File ( root ) ; File [ ] children = dir . listFiles ( ) ; if ( children == null ) return ; for ( File file : children ) { Date lastMod = new Date ( file . lastModified ( ) ) ; if ( lastMod . before ( cutoff ) ) { boolean ret = file . delete ( ) ; if ( sbuff != null ) { sbuff . append ( " delete " ) . append ( file ) . append ( " (" ) . append ( lastMod ) . append ( ")\n" ) ; if ( ! ret ) sbuff . append ( "Error deleting " ) . append ( file ) . append ( "\n" ) ; } } }


signature:
public class DiskCache { /** * Remove files if needed to make cache have less than maxBytes bytes file sizes .
 * This will remove files in sort order defined by fileComparator .
 * The first files in the sort order are kept , until the max bytes is exceeded , then they are deleted .
 * @ param maxBytes max number of bytes in cache .
 * @ param fileComparator sort files first with this
 * @ param sbuff write results here , null is ok . */
static public void cleanCache ( long maxBytes , Comparator < File > fileComparator , StringBuilder sbuff ) { } }

implementation: if ( sbuff != null ) sbuff . append ( "DiskCache clean maxBytes= " ) . append ( maxBytes ) . append ( "on dir " ) . append ( root ) . append ( "\n" ) ; File dir = new File ( root ) ; long total = 0 , total_delete = 0 ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) { List < File > fileList = Arrays . asList ( files ) ; Collections . sort ( fileList , fileComparator ) ; for ( File file : fileList ) { if ( file . length ( ) + total > maxBytes ) { total_delete += file . length ( ) ; if ( sbuff != null ) sbuff . append ( " delete " ) . append ( file ) . append ( " (" ) . append ( file . length ( ) ) . append ( ")\n" ) ; if ( ! file . delete ( ) && sbuff != null ) sbuff . append ( "Error deleting " ) . append ( file ) . append ( "\n" ) ; } else { total += file . length ( ) ; } } } if ( sbuff != null ) { sbuff . append ( "Total bytes deleted= " ) . append ( total_delete ) . append ( "\n" ) ; sbuff . append ( "Total bytes left in cache= " ) . append ( total ) . append ( "\n" ) ; }


signature:
public class DiskCache { /** * debug
 * @ param filename look for this file
 * @ throws java . io . IOException if read error */
static void make ( String filename ) throws IOException { } }

implementation: File want = DiskCache . getCacheFile ( filename ) ; System . out . println ( "make=" + want . getPath ( ) + "; exists = " + want . exists ( ) ) ; if ( ! want . exists ( ) ) { boolean ret = want . createNewFile ( ) ; assert ret ; } System . out . println ( " canRead= " + want . canRead ( ) + " canWrite = " + want . canWrite ( ) + " lastMod = " + new Date ( want . lastModified ( ) ) ) ; System . out . println ( " original=" + filename ) ;


signature:
public class BAMutil { /** * Get the named Icon from the default resource ( jar file ) .
 * @ param name name of the Icon ( will look for < name > . gif )
 * @ param errMsg true = print error message if not found
 * @ return the Icon or null if not found */
public static ImageIcon getIcon ( String name , boolean errMsg ) { } }

implementation: ImageIcon ii = Resource . getIcon ( defaultResourcePath + name + ".gif" , errMsg ) ; if ( ii == null ) Resource . getIcon ( defaultResourcePath + name + ".png" , errMsg ) ; return ii ;


signature:
public class BAMutil { /** * Get the named Image from the default resource ( jar file ) .
 * @ param name name of the Image ( will look for < name > . gif )
 * @ return the Image or null if not found */
public static Image getImage ( String name ) { } }

implementation: Image ii ; if ( name . endsWith ( ".png" ) || name . endsWith ( ".jpg" ) || name . endsWith ( ".gif" ) ) ii = Resource . getImage ( defaultResourcePath + name ) ; else ii = Resource . getImage ( defaultResourcePath + name + ".gif" ) ; return ii ;


signature:
public class BAMutil { /** * Make a " buttcon " = button with an Icon
 * @ param icon the normal Icon
 * @ param selected the selected Icon
 * @ param tooltip the tooltip
 * @ param is _ toggle if true , make JToggleButton , else JButton
 * @ return the buttcon ( JButton or JToggleButton ) */
public static AbstractButton makeButtcon ( Icon icon , Icon selected , String tooltip , boolean is_toggle ) { } }

implementation:
AbstractButton butt ; if ( is_toggle ) butt = new JToggleButton ( ) ; else butt = new JButton ( ) ; if ( debug ) System . out . println ( "   makeButtcon" + icon + " " + selected + " " + tooltip + " " + is_toggle ) ; if ( icon != null ) butt . setIcon ( icon ) ; if ( selected != null ) { if ( is_toggle ) { butt . setSelectedIcon ( selected ) ; } else { butt . setRolloverIcon ( selected ) ; butt . setRolloverSelectedIcon ( selected ) ; butt . setPressedIcon ( selected ) ; butt . setRolloverEnabled ( true ) ; } } butt . setMaximumSize ( new Dimension ( 28 , 28 ) ) ; // kludge
butt . setPreferredSize ( new Dimension ( 28 , 28 ) ) ; butt . setToolTipText ( tooltip ) ; butt . setFocusPainted ( false ) ; return butt ;


signature:
public class BAMutil { /** * Make a " buttcon " = button with an Icon
 * @ param iconName name of the Icon ( will look for < name > . gif )
 * @ param tooltip the tooltip
 * @ param is _ toggle if true , make JToggleButton , else JButton
 * @ return the buttcon ( JButton or JToggleButton ) */
public static AbstractButton makeButtcon ( String iconName , String tooltip , boolean is_toggle ) { } }

implementation: Icon icon = getIcon ( iconName , false ) ; Icon iconSel = getIcon ( iconName + "Sel" , false ) ; return makeButtcon ( icon , iconSel , tooltip , is_toggle ) ;


signature:
public class BAMutil { /** * NB : doesnt add action to MenuItem */
private static JMenuItem makeMenuItemFromAction ( Action act ) { } }

implementation:
// this prevents null pointer exception if user didnt call setProperties ( )
Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; Integer mnu = ( Integer ) act . getValue ( BAMutil . MNEMONIC ) ; int mnemonic = ( tog == null ) ? - 1 : mnu . intValue ( ) ; Integer acc = ( Integer ) act . getValue ( BAMutil . ACCEL ) ; int accel = ( acc == null ) ? 0 : acc . intValue ( ) ; return makeMenuItem ( ( Icon ) act . getValue ( Action . SMALL_ICON ) , ( Icon ) act . getValue ( BAMutil . SELECTED_ICON ) , ( String ) act . getValue ( Action . SHORT_DESCRIPTION ) , is_toggle , mnemonic , accel < 0 ? 0 : accel ) ;


signature:
public class BAMutil { /** * creates a MenuItem using the given Action and adds it to the given Menu .
 * Uses Properties that have been set on the Action ( see setActionProperties ( ) ) . All
 * are optional except for Action . SHORT _ DESCRIPTION : < pre >
 * Action . SHORT _ DESCRIPTION String MenuItem text ( required )
 * Action . SMALL _ ICON Icon the Icon to Use
 * BAMutil . SELECTED _ ICON Icon the Icon when selected ( optional )
 * BAMutil . TOGGLE Boolean true if its a toggle
 * BAMutil . MNEMONIC Integer menu item shortcut
 * BAMutil . ACCEL Integer menu item global keyboard accelerator
 * < / pre > < br >
 * The Action is triggered when the MenuItem is selected . Enabling and disabling the Action
 * does the same for the MenuItem . For toggles , state is maintained in the Action ,
 * and MenuItem state changes when the Action state changes . < br > < br >
 * The point of all this is that once you set it up , you work exclusively with the action object ,
 * and all changes are automatically reflected in the UI .
 * @ param menu add to this menu
 * @ param act the Action to make it out of
 * @ param menuPos if > = 0 , add at this position , otherwise append
 * @ return the MenuItem created */
public static JMenuItem addActionToMenu ( JMenu menu , Action act , int menuPos ) { } }

implementation:
JMenuItem mi = makeMenuItemFromAction ( act ) ; if ( menuPos >= 0 ) menu . add ( mi , menuPos ) ; else menu . add ( mi ) ; Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; // set state for toggle buttons
if ( is_toggle ) { if ( debugToggle ) System . out . println ( "addActionToMenu: " + act . getValue ( Action . SHORT_DESCRIPTION ) + " " + act . getValue ( BAMutil . STATE ) ) ; Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; if ( state == null ) state = Boolean . FALSE ; act . putValue ( BAMutil . STATE , state ) ; mi . setSelected ( state . booleanValue ( ) ) ; } // add event listeners
Action myAct = is_toggle ? new ToggleAction ( act ) : act ; mi . addActionListener ( myAct ) ; act . addPropertyChangeListener ( new myActionChangedListener ( mi ) ) ; return mi ;


signature:
public class BAMutil { /** * NB : doesnt add action to button */
private static AbstractButton _makeButtconFromAction ( Action act ) { } }

implementation:
// this prevents null pointer exception if user didnt call setProperties ( )
Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; return makeButtcon ( ( Icon ) act . getValue ( Action . SMALL_ICON ) , ( Icon ) act . getValue ( BAMutil . SELECTED_ICON ) , ( String ) act . getValue ( Action . SHORT_DESCRIPTION ) , is_toggle ) ;


signature:
public class BAMutil { /** * creates an AbstractButton using the given Action and adds it to the given Container at the position . .
 * Uses Properties that have been set on the Action ( see setActionProperties ( ) ) . All
 * are optional except for Action . SMALL _ ICON : < pre >
 * Action . SMALL _ ICON Icon the Icon to Use ( required )
 * BAMutil . SELECTED _ ICON Icon the Icon when selected ( optional )
 * Action . SHORT _ DESCRIPTION String tooltip
 * BAMutil . TOGGLE Boolean true if its a toggle
 * < / pre > < br >
 * The Action is triggered when the Button is selected . Enabling and disabling the Action
 * does the same for the Button . For toggles , state is maintained in the Action ,
 * and the Button state changes when the Action state changes . < br > < br >
 * The point of all this is that once you set it up , you work exclusively with the action object ,
 * and all changes are automatically reflected in the UI .
 * @ param c add to this Container
 * @ param act the Action to make it out of
 * @ param pos add to the container at this position ( if pos < 0 , add at the end )
 * @ return the AbstractButton created ( JButton or JToggleButton ) */
public static AbstractButton addActionToContainerPos ( Container c , Action act , int pos ) { } }

implementation:
AbstractButton butt = _makeButtconFromAction ( act ) ; if ( pos < 0 ) c . add ( butt ) ; else c . add ( butt , pos ) ; if ( debug ) System . out . println ( " addActionToContainerPos " + act + " " + butt + " " + pos ) ; Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; // set state for toggle buttons
if ( is_toggle ) { if ( debugToggle ) System . out . println ( "addActionToContainerPos: " + act . getValue ( Action . SHORT_DESCRIPTION ) + " " + act . getValue ( BAMutil . STATE ) ) ; Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; if ( state == null ) state = Boolean . FALSE ; act . putValue ( BAMutil . STATE , state ) ; butt . setSelected ( state . booleanValue ( ) ) ; } // add event listsners
Action myAct = is_toggle ? new ToggleAction ( act ) : act ; butt . addActionListener ( myAct ) ; act . addPropertyChangeListener ( new myActionChangedListener ( butt ) ) ; return butt ;


signature:
public class BAMutil { /** * Standard way to set Properties for Actions .
 * This also looks for an Icon " < icon _ name > Sel " and if it exists :
 * 1 ) sets SelectedIcon if its a toggle , or
 * 2 ) sets the Icon when selected ( optional ) if its not a toggle
 * If is _ toggle , a toggle button is created ( in addActionToContainer ( ) ) , default state false
 * To get or set the state of the toggle button :
 * Boolean state = ( Boolean ) action . getValue ( BAMutil . STATE ) ;
 * action . putValue ( BAMutil . STATE , new Boolean ( true / false ) ) ;
 * @ param act add properties to this action
 * @ param icon _ name name of icon ( or null ) .
 * @ param action _ name menu name / tooltip
 * @ param is _ toggle true if its a toggle
 * @ param mnemonic menu item shortcut
 * @ param accel menu item global keyboard accelerator */
public static void setActionProperties ( AbstractAction act , String icon_name , String action_name , boolean is_toggle , int mnemonic , int accel ) { } }

implementation: if ( icon_name != null ) { act . putValue ( Action . SMALL_ICON , getIcon ( icon_name , true ) ) ; act . putValue ( BAMutil . SELECTED_ICON , getIcon ( icon_name + "Sel" , false ) ) ; } act . putValue ( Action . SHORT_DESCRIPTION , action_name ) ; act . putValue ( Action . LONG_DESCRIPTION , action_name ) ; act . putValue ( BAMutil . TOGGLE , new Boolean ( is_toggle ) ) ; act . putValue ( BAMutil . MNEMONIC , new Integer ( mnemonic ) ) ; act . putValue ( BAMutil . ACCEL , new Integer ( accel ) ) ;


signature:
public class BAMutil { /** * Standard way to set Properties and state for " Toggle " Actions . *
 * @ param act add properties to this action
 * @ param icon _ name name of icon ( or null ) .
 * @ param action _ name menu name / tooltip
 * @ param toggleValue default value of toggle
 * @ param mnemonic menu item shortcut
 * @ param accel menu item global keyboard accelerator */
public static void setActionPropertiesToggle ( AbstractAction act , String icon_name , String action_name , boolean toggleValue , int mnemonic , int accel ) { } }

implementation: setActionProperties ( act , icon_name , action_name , true , mnemonic , accel ) ; act . putValue ( BAMutil . STATE , new Boolean ( toggleValue ) ) ;


signature:
public class AbstractStationSubsetWriter { /** * LOOK could do better : " all " , and maybe HashSet < Name > */
public static List < StationFeature > getStationsInSubset ( StationTimeSeriesFeatureCollection stationFeatCol , SubsetParams ncssParams ) throws IOException { } }

implementation:
List < StationFeature > wantedStations ; // verify SpatialSelection has some stations
if ( ncssParams . getStations ( ) != null ) { List < String > stnNames = ncssParams . getStations ( ) ; if ( stnNames . get ( 0 ) . equals ( "all" ) ) { wantedStations = stationFeatCol . getStationFeatures ( ) ; } else { wantedStations = stationFeatCol . getStationFeatures ( stnNames ) ; } } else if ( ncssParams . getLatLonBoundingBox ( ) != null ) { LatLonRect llrect = ncssParams . getLatLonBoundingBox ( ) ; wantedStations = stationFeatCol . getStationFeatures ( llrect ) ; } else if ( ncssParams . getLatLonPoint ( ) != null ) { Station closestStation = findClosestStation ( stationFeatCol , ncssParams . getLatLonPoint ( ) ) ; List < String > stnList = new ArrayList < > ( ) ; stnList . add ( closestStation . getName ( ) ) ; wantedStations = stationFeatCol . getStationFeatures ( stnList ) ; } else { // Want all .
wantedStations = stationFeatCol . getStationFeatures ( ) ; } return wantedStations ;


signature:
public class AbstractStationSubsetWriter { /** * Find the station closest to the specified point .
 * The metric is ( lat - lat0 ) * * 2 + ( cos ( lat0 ) * ( lon - lon0 ) ) * * 2
 * @ param lat latitude value
 * @ param lon longitude value
 * @ return name of station closest to the specified point
 * @ throws IOException if read error */
public static Station findClosestStation ( StationTimeSeriesFeatureCollection stationFeatCol , LatLonPoint pt ) throws IOException { } }

implementation: double lat = pt . getLatitude ( ) ; double lon = pt . getLongitude ( ) ; double cos = Math . cos ( Math . toRadians ( lat ) ) ; List < StationFeature > stations = stationFeatCol . getStationFeatures ( ) ; Station min_station = stations . get ( 0 ) ; double min_dist = Double . MAX_VALUE ; for ( Station s : stations ) { double lat1 = s . getLatitude ( ) ; double lon1 = LatLonPointImpl . lonNormal ( s . getLongitude ( ) , lon ) ; double dy = Math . toRadians ( lat - lat1 ) ; double dx = cos * Math . toRadians ( lon - lon1 ) ; double dist = dy * dy + dx * dx ; if ( dist < min_dist ) { min_dist = dist ; min_station = s ; } } return min_station ;


signature:
public class Descriptor { /** * contains a BUFR table entry */
static public boolean isBufrTable ( short fxy ) { } }


signature:
public class CoordinateAxis { /** * Create a coordinate axis from an existing Variable .
 * @ param ncd the containing dataset
 * @ param vds an existing Variable in dataset .
 * @ return CoordinateAxis or one of its subclasses ( CoordinateAxis1D , CoordinateAxis2D , or CoordinateAxis1DTime ) . */
static public CoordinateAxis factory ( NetcdfDataset ncd , VariableDS vds ) { } }

implementation: if ( ( vds . getRank ( ) == 0 ) || ( vds . getRank ( ) == 1 ) || ( vds . getRank ( ) == 2 && vds . getDataType ( ) == DataType . CHAR ) ) { return new CoordinateAxis1D ( ncd , vds ) ; } else if ( vds . getRank ( ) == 2 ) return new CoordinateAxis2D ( ncd , vds ) ; else return new CoordinateAxis ( ncd , vds ) ;


signature:
public class CoordinateAxis { /** * Make a copy , with an independent cache .
 * @ return copy of this CoordinateAxis */
public CoordinateAxis copyNoCache ( ) { } }

implementation:
CoordinateAxis axis = new CoordinateAxis ( ncd , getParentGroup ( ) , getShortName ( ) , getDataType ( ) , getDimensionsString ( ) , getUnitsString ( ) , getDescription ( ) ) ; // other state
axis . axisType = this . axisType ; axis . boundaryRef = this . boundaryRef ; axis . isContiguous = this . isContiguous ; axis . positive = this . positive ; axis . cache = new Variable . Cache ( ) ; // decouple cache
return axis ;


signature:
public class CoordinateAxis { /** * Does the axis have numeric values .
 * @ return true if the CoordAxis is numeric , false if its string valued ( " nominal " ) . */
public boolean isNumeric ( ) { } }

implementation: return ( getDataType ( ) != DataType . CHAR ) && ( getDataType ( ) != DataType . STRING ) && ( getDataType ( ) != DataType . STRUCTURE ) ;


signature:
public class CoordinateAxis { /** * Get a string representation
 * @ param buf place info here */
public void getInfo ( Formatter buf ) { } }

implementation:
buf . format ( "%-30s" , getNameAndDimensions ( ) ) ; buf . format ( "%-20s" , getUnitsString ( ) ) ; if ( axisType != null ) { buf . format ( "%-10s" , axisType . toString ( ) ) ; } buf . format ( "%s" , getDescription ( ) ) ; /* if ( isNumeric ) {
 boolean debugCoords = ucar . util . prefs . ui . Debug . isSet ( " Dataset / showCoordValues " ) ;
 int ndigits = debugCoords ? 9 : 4;
 for ( int i = 0 ; i < getNumElements ( ) ; i + + ) {
 buf . append ( Format . d ( getCoordValue ( i ) , ndigits ) ) ;
 buf . append ( " " ) ;
 if ( debugCoords ) {
 buf . append ( " \ n " ) ;
 for ( int i = 0 ; i < = getNumElements ( ) ; i + + ) {
 buf . append ( Format . d ( getCoordEdge ( i ) , ndigits ) ) ;
 buf . append ( " " ) ;
 } else {
 for ( int i = 0 ; i < getNumElements ( ) ; i + + ) {
 buf . append ( getCoordName ( i ) ) ;
 buf . append ( " " ) ; */
// buf . append ( " \ n " ) ;


signature:
public class CoordinateAxis { /** * needed by time coordinates */
public ucar . nc2 . time . Calendar getCalendarFromAttribute ( ) { } }

implementation:
Attribute cal = findAttribute ( CF . CALENDAR ) ; String s = ( cal == null ) ? null : cal . getStringValue ( ) ; if ( s == null ) { // default for CF and COARDS
Attribute convention = ( ncd == null ) ? null : ncd . getRootGroup ( ) . findAttribute ( CDM . CONVENTIONS ) ; if ( convention != null ) { String hasName = convention . getStringValue ( ) ; int version = CF1Convention . getVersion ( hasName ) ; if ( version >= 0 ) { return Calendar . gregorian ; // if ( version < 7 ) return Calendar . gregorian ;
// if ( version > = 7 ) return Calendar . proleptic _ gregorian ; / /
} if ( COARDSConvention . isMine ( hasName ) ) return Calendar . gregorian ; } } return ucar . nc2 . time . Calendar . get ( s ) ;


signature:
public class JTableSorted { /** * Sort the rowList : note rowList changed , not a copy of it .
 * @ param colNo sort on this column
 * @ param reverse if true , reverse sort */
public void sort ( int colNo , boolean reverse ) { } }

implementation: model . sort ( colNo , reverse ) ; jtable . setRowSelectionInterval ( 0 , 0 ) ; ensureRowIsVisible ( 0 ) ;


signature:
public class JTableSorted { /** * Replace the rowList with this one .
 * @ param rowList list of rows */
public void setList ( ArrayList rowList ) { } }

implementation: this . list = rowList ; if ( list . size ( ) > 0 ) jtable . setRowSelectionInterval ( 0 , 0 ) ; else jtable . clearSelection ( ) ; model . sort ( ) ; jtable . revalidate ( ) ;


signature:
public class JTableSorted { /** * Remove elem from rowList , update the table .
 * Searches for match using object identity ( = = )
 * @ param elem which element */
public void removeRow ( Object elem ) { } }

implementation: Iterator iter = list . iterator ( ) ; while ( iter . hasNext ( ) ) { Object row = iter . next ( ) ; if ( row == elem ) { iter . remove ( ) ; break ; } } jtable . revalidate ( ) ;


signature:
public class JTableSorted { /** * Get the currently selected row .
 * @ return selected TableRow */
public TableRow getSelected ( ) { } }

implementation: if ( list . size ( ) == 0 ) return null ; int sel = jtable . getSelectedRow ( ) ; if ( sel >= 0 ) return ( TableRow ) list . get ( sel ) ; else return null ;


signature:
public class JTableSorted { /** * Set the current selection to this row .
 * @ param row index into rowList */
public void setSelected ( int row ) { } }

implementation: if ( ( row < 0 ) || ( row >= list . size ( ) ) ) return ; if ( debug ) System . out . println ( "JTableSorted setSelected " + row ) ; jtable . setRowSelectionInterval ( row , row ) ; ensureRowIsVisible ( row ) ;


signature:
public class JTableSorted { /** * Increment or decrement the current selection by one row .
 * @ param increment true = increment , false = decrement */
public void incrSelected ( boolean increment ) { } }

implementation: if ( list . size ( ) == 0 ) return ; int curr = jtable . getSelectedRow ( ) ; if ( increment && ( curr < list . size ( ) - 1 ) ) setSelected ( curr + 1 ) ; else if ( ! increment && ( curr > 0 ) ) setSelected ( curr - 1 ) ;


signature:
public class JTableSorted { /** * for each column , get the model index */
public int [ ] getModelIndex ( ) { } }

implementation: int [ ] modelIndex = new int [ colName . length ] ; TableColumnModel tcm = jtable . getColumnModel ( ) ; for ( int i = 0 ; i < colName . length ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; modelIndex [ i ] = tc . getModelIndex ( ) ; } return modelIndex ;


signature: public class JTableSorted { private void ensureRowIsVisible ( int nRow ) { } }

implementation: Rectangle visibleRect = jtable . getCellRect ( nRow , 0 , true ) ; if ( visibleRect != null ) { visibleRect . x = scrollPane . getViewport ( ) . getViewPosition ( ) . x ; jtable . scrollRectToVisible ( visibleRect ) ; jtable . repaint ( ) ; }


signature:
public class RadarDataInventory { /** * this . */
private CalendarPeriod findRangeAdjustment ( String fmtString ) { } }

implementation: if ( fmtString . contains ( "H" ) || fmtString . contains ( "k" ) ) return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Hour ) ; else if ( fmtString . contains ( "d" ) ) return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Day ) ; else if ( fmtString . contains ( "M" ) ) return CalendarPeriod . of ( 31 , CalendarPeriod . Field . Day ) ; else return CalendarPeriod . of ( 366 , CalendarPeriod . Field . Day ) ;


signature:
public class BufrFeatureDatasetFactory { /** * LOOK fake */
@ Override public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { } }

implementation: IOServiceProvider iosp = ncd . getIosp ( ) ; return ( iosp != null && iosp instanceof BufrIosp2 ) ? true : null ;


signature:
public class VertScaleSlider { /** * set current value - no event */
private void setSelectedIndex ( int idx ) { } }

implementation: if ( zAxis == null ) return ; eventOK = false ; currentIdx = idx ; slider . setValue ( world2slider ( zAxis . getCoordValue ( currentIdx ) ) ) ; eventOK = true ;


signature:
public class Dap4BisonParser { /** * Push Parse input from external lexer
 * @ param yylextoken current token
 * @ param yylexval current lval
 * @ return < tt > YYACCEPT , YYABORT , YYPUSH _ MORE < / tt > */
public int push_parse ( int yylextoken , Object yylexval ) throws DapException , DapException { } }

implementation:
if ( ! this . push_parse_initialized ) { push_parse_initialize ( ) ; yycdebug ( "Starting parse\n" ) ; yyerrstatus_ = 0 ; } else label = YYGETTOKEN ; boolean push_token_consumed = true ; for ( ; ; ) switch ( label ) { /* New state . Unlike in the C / C + + skeletons , the state is already
 pushed when we come here . */
case YYNEWSTATE : yycdebug ( "Entering state " + yystate + "\n" ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; /* Accept ? */
if ( yystate == yyfinal_ ) { label = YYACCEPT ; break ; } /* Take a decision . First try without lookahead . */
yyn = yypact_ [ yystate ] ; if ( yy_pact_value_is_default_ ( yyn ) ) { label = YYDEFAULT ; break ; } /* Fall Through */
case YYGETTOKEN : /* Read a lookahead token . */
if ( yychar == yyempty_ ) { if ( ! push_token_consumed ) return YYPUSH_MORE ; yycdebug ( "Reading a token: " ) ; yychar = yylextoken ; yylval = yylexval ; push_token_consumed = false ; } /* Convert token to internal form . */
if ( yychar <= Lexer . EOF ) { yychar = yytoken = Lexer . EOF ; yycdebug ( "Now at end of input.\n" ) ; } else { yytoken = yytranslate_ ( yychar ) ; yy_symbol_print ( "Next token is" , yytoken , yylval ) ; } /* If the proper action on seeing token YYTOKEN is to reduce or to
 detect an error , take that action . */
yyn += yytoken ; if ( yyn < 0 || yylast_ < yyn || yycheck_ [ yyn ] != yytoken ) label = YYDEFAULT ; /* < = 0 means reduce or error . */
else if ( ( yyn = yytable_ [ yyn ] ) <= 0 ) { if ( yy_table_value_is_error_ ( yyn ) ) label = YYERRLAB ; else { yyn = - yyn ; label = YYREDUCE ; } } else { /* Shift the lookahead token . */
yy_symbol_print ( "Shifting" , yytoken , yylval ) ; /* Discard the token being shifted . */
yychar = yyempty_ ; /* Count tokens shifted since error ; after three , turn off error
 status . */
if ( yyerrstatus_ > 0 ) -- yyerrstatus_ ; yystate = yyn ; yystack . push ( yystate , yylval ) ; label = YYNEWSTATE ; } break ; /* | yydefault - - do the default action for the current state . | */
case YYDEFAULT : yyn = yydefact_ [ yystate ] ; if ( yyn == 0 ) label = YYERRLAB ; else label = YYREDUCE ; break ; /* | yyreduce - - Do a reduction . | */
case YYREDUCE : yylen = yyr2_ [ yyn ] ; label = yyaction ( yyn , yystack , yylen ) ; yystate = yystack . stateAt ( 0 ) ; break ; /* | yyerrlab - - here on detecting error | */
case YYERRLAB : /* If not already recovering from an error , report this error . */
if ( yyerrstatus_ == 0 ) { ++ yynerrs_ ; if ( yychar == yyempty_ ) yytoken = yyempty_ ; yyerror ( yysyntax_error ( yystate , yytoken ) ) ; } if ( yyerrstatus_ == 3 ) { /* If just tried and failed to reuse lookahead token after an
 error , discard it . */
if ( yychar <= Lexer . EOF ) { /* Return failure if at end of input . */
if ( yychar == Lexer . EOF ) { label = YYABORT ; break ; } } else yychar = yyempty_ ; } /* Else will try to reuse lookahead token after shifting the error
 token . */
label = YYERRLAB1 ; break ; /* | errorlab - - error raised explicitly by YYERROR . | */
case YYERROR : /* Do not reclaim the symbols of the rule which action triggered
 this YYERROR . */
yystack . pop ( yylen ) ; yylen = 0 ; yystate = yystack . stateAt ( 0 ) ; label = YYERRLAB1 ; break ; /* | yyerrlab1 - - common code for both syntax error and YYERROR . | */
case YYERRLAB1 : yyerrstatus_ = 3 ; /* Each real token shifted decrements this . */
for ( ; ; ) { yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { yyn += yyterror_ ; if ( 0 <= yyn && yyn <= yylast_ && yycheck_ [ yyn ] == yyterror_ ) { yyn = yytable_ [ yyn ] ; if ( 0 < yyn ) break ; } } /* Pop the current state because it cannot handle the
 * error token . */
if ( yystack . height == 0 ) { label = YYABORT ; break ; } yystack . pop ( ) ; yystate = yystack . stateAt ( 0 ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; } if ( label == YYABORT ) /* Leave the switch . */
break ; /* Shift the error token . */
yy_symbol_print ( "Shifting" , yystos_ [ yyn ] , yylval ) ; yystate = yyn ; yystack . push ( yyn , yylval ) ; label = YYNEWSTATE ; break ; /* Accept . */
case YYACCEPT : this . push_parse_initialized = false ; return YYACCEPT ; /* Abort . */
case YYABORT : this . push_parse_initialized = false ; return YYABORT ; }


signature:
public class Dap4BisonParser { /** * ( Re - ) Initialize the state of the push parser . */
public void push_parse_initialize ( ) { } }

implementation:
/* Lookahead and lookahead in internal form . */
this . yychar = yyempty_ ; this . yytoken = 0 ; /* State . */
this . yyn = 0 ; this . yylen = 0 ; this . yystate = 0 ; this . yystack = new YYStack ( ) ; this . label = YYNEWSTATE ; /* Error handling . */
this . yynerrs_ = 0 ; /* Semantic value of the lookahead . */
this . yylval = null ; yystack . push ( this . yystate , this . yylval ) ; this . push_parse_initialized = true ;


signature:
public class Util { /** * Compares elements in a < code > Vector < / code > of < code > BaseType < / code > s and
 * throw a < code > BadSemanticsException < / code > if there are any
 * duplicate elements .
 * @ param v The < code > Vector < / code > to check
 * @ param varName the name of the variable which called us
 * @ param typeName the type name of the variable which called us
 * @ throws BadSemanticsException if there are duplicate elements
 * @ throws IndexOutOfBoundsException if size doesn ' t match the number
 * of elements in the < code > Enumeration < / code > */
static void uniqueNames ( Vector v , String varName , String typeName ) throws BadSemanticsException { } }

implementation:
String [ ] names = sortedNames ( v ) ; // DEBUG : print out names
// for ( int i = 0 ; i < names . length ; i + + ) {
// LogStream . err . println ( " names [ " + i + " ] = " + names [ i ] ) ;
// look for any instance of consecutive names that are = =
for ( int i = 1 ; i < names . length ; i ++ ) { if ( names [ i - 1 ] . equals ( names [ i ] ) ) { throw new BadSemanticsException ( "The variable `" + names [ i ] + "' is used more than once in " + typeName + " `" + varName + "'" ) ; } }


signature:
public class Util { /** * Takes a < code > Vector < / code > of < code > BaseType < / code > s , retrieves their
 * names into an array of < code > String < / code > s , and performs a Quick Sort
 * on that array .
 * @ param v The Vector to check
 * @ return a sorted array of < code > String < / code >
 * @ throws BadSemanticsException if there is an element with no name */
static String [ ] sortedNames ( Vector v ) throws BadSemanticsException { } }

implementation:
String [ ] names = new String [ v . size ( ) ] ; int count = 0 ; for ( Enumeration e = v . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; String tempName = bt . getEncodedName ( ) ; if ( tempName == null ) throw new BadSemanticsException ( bt . getClass ( ) . getName ( ) + " variable with no name" ) ; names [ count ++ ] = tempName ; } // DEBUG : print out names
// for ( int i = 0 ; i < names . length ; i + + ) {
// LogStream . err . println ( " names [ " + i + " ] = " + names [ i ] ) ;
// assert that size is correct
if ( count != names . length ) throw new IndexOutOfBoundsException ( "Vector size changed unexpectedly" ) ; quickSort ( names , 0 , names . length - 1 ) ; return names ;


signature:
public class Util { /** * Internal recursive method to perform Quick Sort on name array .
 * @ param a an array of < code > String < / code > .
 * @ param lo0 the low index to sort .
 * @ param hi0 the high index to sort . */
static private void quickSort ( String a [ ] , int lo0 , int hi0 ) { } }

implementation:
int lo = lo0 ; int hi = hi0 ; String mid ; if ( hi0 > lo0 ) { // Arbitrarily establishing partition element as the array midpoint * /
// Coverity [ FB . IM _ AVERAGE _ COMPUTATION _ COULD _ OVERFLOW ]
mid = a [ ( lo0 + hi0 ) / 2 ] ; // loop through the array until indices cross
while ( lo <= hi ) { // find the first element that is > = the partition element
// starting from the left index .
while ( ( lo < hi0 ) && ( a [ lo ] . compareTo ( mid ) < 0 ) ) ++ lo ; // find an element that is < = the partition element
// starting from the right index .
while ( ( hi > lo0 ) && ( a [ hi ] . compareTo ( mid ) > 0 ) ) -- hi ; // if the indexes have not crossed , swap
if ( lo <= hi ) { swap ( a , lo , hi ) ; ++ lo ; -- hi ; } } // If the right index has not reached the left side of array ,
// sort the left partition .
if ( lo0 < hi ) quickSort ( a , lo0 , hi ) ; // If the left index has not reached the right side of array ,
// sort the right partition .
if ( lo < hi0 ) quickSort ( a , lo , hi0 ) ; }


signature:
public class Util { /** * Private method to swap two elements in the array
 * @ param a an array of < code > String < / code > .
 * @ param i the index of the first element .
 * @ param j the index of the second element . */
static private void swap ( String a [ ] , int i , int j ) { } }

implementation: String T ; T = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = T ;


signature:
public class Util { /** * This function escapes non - printable characters and quotes . This is used
 * to make < code > printVal < / code > output < code > DString < / code > data in the
 * same way as the C + + version . Since Java supports Unicode , this will
 * need to be altered if it ' s desired to print < code > DString < / code > as
 * UTF - 8 or some other character encoding .
 * @ param s the input < code > String < / code > .
 * @ return the escaped < code > String < / code > . */
static String escattr ( String s ) { } }

implementation:
StringBuffer buf = new StringBuffer ( s . length ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' || ( c >= '!' && c <= '~' ) ) { // printable ASCII character
buf . append ( c ) ; } else { // non - printable ASCII character : print as unsigned octal integer
// padded with leading zeros
buf . append ( '\\' ) ; String numVal = Integer . toString ( ( int ) c & 0xFF , 8 ) ; for ( int pad = 0 ; pad < ( 3 - numVal . length ( ) ) ; pad ++ ) buf . append ( '0' ) ; buf . append ( numVal ) ; } } return buf . toString ( ) ;


signature:
public class MFileOS { /** * Make MFileOS if file exists , otherwise return null
 * @ param filename
 * @ return MFileOS or null */
static public MFileOS getExistingFile ( String filename ) { } }

implementation: if ( filename == null ) return null ; File file = new File ( filename ) ; if ( file . exists ( ) ) return new MFileOS ( file ) ; return null ;


signature:
public class RotatedLatLon { /** * Transform a " real " longitude and latitude into the rotated longitude ( X ) and
 * rotated latitude ( Y ) . */
public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl destPoint ) { } }

implementation:
/* Tor ' s algorithm
 public double [ ] fwd ( double [ ] lonlat )
 return transform ( lonlat , lonpole , polerotate , sinDlat ) ; */
double [ ] lonlat = new double [ 2 ] ; lonlat [ 0 ] = latlon . getLongitude ( ) ; lonlat [ 1 ] = latlon . getLatitude ( ) ; double [ ] rlonlat = rotate ( lonlat , lonpole , polerotate , sinDlat ) ; if ( destPoint == null ) destPoint = new ProjectionPointImpl ( rlonlat [ 0 ] , rlonlat [ 1 ] ) ; else destPoint . setLocation ( rlonlat [ 0 ] , rlonlat [ 1 ] ) ; if ( show ) System . out . println ( "LatLon= " + latlon + " proj= " + destPoint ) ; return destPoint ;


signature:
public class RotatedLatLon { /** * Transform a rotated longitude ( X ) and rotated latitude ( Y ) into a " real "
 * longitude - latitude pair . */
public LatLonPoint projToLatLon ( ProjectionPoint ppt , LatLonPointImpl destPoint ) { } }

implementation:
/* Tor ' s algorithm
 public double [ ] inv ( double [ ] lonlat )
 return rotate ( lonlat , - polerotate , - lonpole , - sinDlat ) ; */
double [ ] lonlat = new double [ 2 ] ; lonlat [ 0 ] = ppt . getX ( ) ; lonlat [ 1 ] = ppt . getY ( ) ; double [ ] rlonlat = rotate ( lonlat , - polerotate , - lonpole , - sinDlat ) ; if ( destPoint == null ) destPoint = new LatLonPointImpl ( rlonlat [ 1 ] , rlonlat [ 0 ] ) ; else destPoint . set ( rlonlat [ 1 ] , rlonlat [ 0 ] ) ; if ( show ) System . out . println ( "Proj= " + ppt + " latlon= " + destPoint ) ; return destPoint ;


signature:
public class RotatedLatLon { /** * Tor ' s transform algorithm renamed to rotate for clarity */
private double [ ] rotate ( double [ ] lonlat , double rot1 , double rot2 , double s ) { } }

implementation:
/* original code
 double e = DEG2RAD * ( lonlat [ 0 ] - rot1 ) ; / / east
 double n = DEG2RAD * lonlat [ 1 ] ; / / north
 double cn = Math . cos ( n ) ;
 double x = cn * Math . cos ( e ) ;
 double y = cn * Math . sin ( e ) ;
 double z = Math . sin ( n ) ;
 double x2 = cosDlat * x + s * z ;
 double z2 = - s * x + cosDlat * z ;
 double R = Math . sqrt ( x2 * x2 + y * y ) ;
 double e2 = Math . atan2 ( y , x2 ) ;
 double n2 = Math . atan2 ( z2 , R ) ;
 double rlon = RAD2DEG * e2 - rot2;
 double rlat = RAD2DEG * n2;
 return new double [ ] { rlon , rlat } ; */
double e = Math . toRadians ( lonlat [ 0 ] - rot1 ) ; // east
double n = Math . toRadians ( lonlat [ 1 ] ) ; // north
double cn = Math . cos ( n ) ; double x = cn * Math . cos ( e ) ; double y = cn * Math . sin ( e ) ; double z = Math . sin ( n ) ; double x2 = cosDlat * x + s * z ; double z2 = - s * x + cosDlat * z ; double R = Math . sqrt ( x2 * x2 + y * y ) ; double e2 = Math . atan2 ( y , x2 ) ; double n2 = Math . atan2 ( z2 , R ) ; double rlon = Math . toDegrees ( e2 ) - rot2 ; double rlat = Math . toDegrees ( n2 ) ; return new double [ ] { rlon , rlat } ;


signature:
public class XMLStore { /** * Create an XMLStore reading from the specified filename .
 * @ param fileName The XMLStore is stored in this files .
 * @ param storedDefaults This contains the " stored defaults " , or null if none .
 * @ return new XMLStore object
 * @ throws java . io . IOException on error */
static public XMLStore createFromFile ( String fileName , XMLStore storedDefaults ) throws java . io . IOException { } }

implementation:
File prefsFile = new File ( fileName ) ; // open file if it exists
InputStream primIS = null , objIS = null ; if ( prefsFile . exists ( ) && prefsFile . length ( ) > 0 ) { primIS = new BufferedInputStream ( new FileInputStream ( prefsFile ) ) ; objIS = new BufferedInputStream ( new FileInputStream ( prefsFile ) ) ; } if ( debugWhichStore ) System . out . println ( "XMLStore read from file " + fileName ) ; XMLStore store = new XMLStore ( primIS , objIS , storedDefaults ) ; store . prefsFile = prefsFile ; return store ;


signature:
public class XMLStore { /** * Create an XMLStore reading from an input stream . Because of some peculiariteis , you must open the
 * input stream wtice , and pass both in .
 * @ param is1 the first copy of the input stream .
 * @ param is2 the second copy of the input stream .
 * @ param storedDefaults This contains the " stored defaults " , or null if none .
 * @ return new XMLStore object
 * @ throws java . io . IOException on error */
static public XMLStore createFromInputStream ( InputStream is1 , InputStream is2 , XMLStore storedDefaults ) throws java . io . IOException { } }

implementation: if ( debugWhichStore ) System . out . println ( "XMLStore read from input stream " + is1 ) ; return new XMLStore ( is1 , is2 , storedDefaults ) ;


signature:
public class XMLStore { /** * Create a read - only XMLStore reading from the specified resource , opened as a Resource stream using the
 * XMLStore ClassLoader . This allows you to find files that are in jar files on
 * the application CLASSPATH .
 * @ param resourceName The XMLStore is stored in this resource . By convention it has . xml suffix .
 * @ param storedDefaults This contains the " stored defaults " , or null if none .
 * @ throws java . io . IOException if Resource not found or error reading it
 * @ return new XMLStore object */
static public XMLStore createFromResource ( String resourceName , XMLStore storedDefaults ) throws java . io . IOException { } }

implementation:
// open files if exist
Class c = XMLStore . class ; InputStream primIS = c . getResourceAsStream ( resourceName ) ; InputStream objIS = c . getResourceAsStream ( resourceName ) ; // debug
// InputStream debugIS = c . getResourceAsStream ( fileName ) ;
// System . out . println ( " Resource stream = " + fileName ) ;
// thredds . util . IO . copy ( debugIS , System . out ) ;
if ( primIS == null ) { // System . out . println ( " classLoader = " + new XMLStore ( ) . getClass ( ) . getClassLoader ( ) ) ;
throw new java . io . IOException ( "XMLStore.createFromResource cant find <" + resourceName + ">" ) ; } if ( debugWhichStore ) System . out . println ( "XMLStore read from resource " + resourceName ) ; return new XMLStore ( primIS , objIS , storedDefaults ) ;


signature:
public class XMLStore { /** * Convenience routine for creating an XMLStore file in a standard place .
 * < p > Initialize :
 * < ol >
 * < li > $ user . home = System . getProperty ( " user . home " ) , if not exist , use " . "
 * < li > create directory " $ ( user _ home ) / appName / " , if not exist , create it
 * < li > return " $ ( user _ home ) / appName / storeName " for use in createFromFile ( )
 * < / ol >
 * @ param appName application name
 * @ param storeName store name
 * @ return standard file name */
static public String makeStandardFilename ( String appName , String storeName ) { } }

implementation:
// the directory
String userHome = null ; try { userHome = System . getProperty ( "user.home" ) ; } catch ( Exception e ) { System . out . println ( "XMLStore.makeStandardFilename: error System.getProperty(user.home) " + e ) ; } if ( null == userHome ) userHome = "." ; String dirFilename = userHome + "/" + appName ; File f = new File ( dirFilename ) ; if ( ! f . exists ( ) ) { boolean ok = f . mkdirs ( ) ; // now ready for file creation in writeXML
if ( ! ok ) System . out . println ( "Error creating directories: " + f . getAbsolutePath ( ) ) ; } return dirFilename + "/" + storeName ;


signature:
public class XMLStore { /** * Save the current state of the Preferences tree to disk , using the
 * original filename . The XMLStore must have been constructed from a
 * writeable XML file .
 * @ throws UnsupportedOperationException : if XMLStore was created from createFromResource .
 * @ throws java . io . IOException on read error */
public void save ( ) throws java . io . IOException { } }

implementation:
if ( prefsFile == null ) throw new UnsupportedOperationException ( "XMLStore is read-only" ) ; // get temporary file to write to
File prefTemp ; String parentFilename = prefsFile . getParent ( ) ; if ( parentFilename == null ) { prefTemp = File . createTempFile ( "pref" , ".xml" ) ; } else { File parentFile = new File ( parentFilename ) ; prefTemp = File . createTempFile ( "pref" , ".xml" , parentFile ) ; } prefTemp . deleteOnExit ( ) ; // save to the temp file
FileOutputStream fos = new FileOutputStream ( prefTemp , false ) ; save ( fos ) ; fos . close ( ) ; // success - rename files
Path xmlBackup = Paths . get ( prefsFile . getAbsolutePath ( ) + ".bak" ) ; Path prefsPath = prefsFile . toPath ( ) ; if ( Files . exists ( prefsPath ) ) Files . move ( prefsPath , xmlBackup , StandardCopyOption . REPLACE_EXISTING ) ; Files . move ( prefTemp . toPath ( ) , prefsFile . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ;


signature:
public class XMLStore { /** * Save the current state of the Preferences tree to the given OutputStream . */
public void save ( OutputStream out ) throws java . io . IOException { } }

implementation:
outputExceptionMessage = null ; // the OutputMunger strips off the XMLEncoder header
OutputMunger bos = new OutputMunger ( out ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( bos , CDM . utf8Charset ) ) ; XMLEncoder beanEncoder = new XMLEncoder ( bos ) ; beanEncoder . setExceptionListener ( new ExceptionListener ( ) { public void exceptionThrown ( Exception exception ) { System . out . println ( "XMLStore.save() got Exception: abort saving the preferences!" ) ; exception . printStackTrace ( ) ; outputExceptionMessage = exception . getMessage ( ) ; } } ) ; pw . printf ( "<?xml version='1.0' encoding='UTF-8'?>%n" ) ; pw . printf ( "<preferences EXTERNAL_XML_VERSION='1.0'>%n" ) ; if ( ! rootPrefs . isUserNode ( ) ) pw . printf ( "  <root type='system'>%n" ) ; else pw . printf ( "  <root type='user'>%n" ) ; Indent indent = new Indent ( 2 ) ; indent . incr ( ) ; writeXmlNode ( bos , pw , rootPrefs , beanEncoder , indent ) ; if ( outputExceptionMessage != null ) throw new IOException ( outputExceptionMessage ) ; pw . printf ( "  </root>%n" ) ; pw . printf ( "</preferences>%n" ) ; pw . flush ( ) ;


signature:
public class DapSerializer { /** * Write out an atomic variable .
 * @ param data
 * @ param dst
 * @ throws dap4 . core . util . DapException */
protected void writeAtomicVariable ( DataCursor data , SerialWriter dst ) throws IOException { } }

implementation:
DapVariable template = ( DapVariable ) data . getTemplate ( ) ; assert ( this . ce . references ( template ) ) ; DapType basetype = template . getBaseType ( ) ; // get the slices from constraint
List < Slice > slices = ce . getConstrainedSlices ( template ) ; if ( slices == null ) throw new DapException ( "Unknown variable: " + template . getFQN ( ) ) ; Object values = data . read ( slices ) ; dst . writeAtomicArray ( basetype , values ) ;


signature:
public class DapSerializer { /** * Write out a scalar or array structure instance
 * @ param data
 * @ param dst - where to write
 * @ throws dap4 . core . util . DapException */
protected void writeStructure ( DataCursor data , SerialWriter dst ) throws IOException { } }

implementation: DapVariable template = ( DapVariable ) data . getTemplate ( ) ; DapStructure ds = ( DapStructure ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; List < Slice > slices = ce . getConstrainedSlices ( template ) ; Odometer odom = Odometer . factory ( slices ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; DataCursor [ ] instance = ( DataCursor [ ] ) data . read ( index ) ; writeStructure1 ( instance [ 0 ] , dst ) ; }


signature:
public class DapSerializer { /** * Write out a single structure instance
 * @ param instance
 * @ param dst - where to write
 * @ throws dap4 . core . util . DapException */
protected void writeStructure1 ( DataCursor instance , SerialWriter dst ) throws IOException { } }

implementation:
assert instance . getScheme ( ) == DataCursor . Scheme . STRUCTURE ; DapVariable template = ( DapVariable ) instance . getTemplate ( ) ; assert ( this . ce . references ( template ) ) ; DapStructure ds = ( DapStructure ) template . getBaseType ( ) ; List < DapVariable > fields = ds . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; if ( ! this . ce . references ( field ) ) continue ; // not in the view
DataCursor df = ( DataCursor ) instance . readField ( i ) ; writeVariable ( df , dst ) ; }


signature:
public class DapSerializer { /** * Write out a single or array sequence instance
 * @ param data
 * @ param dst - where to write
 * @ throws dap4 . core . util . DapException */
protected void writeSequence ( DataCursor data , SerialWriter dst ) throws IOException { } }

implementation: DapVariable template = ( DapVariable ) data . getTemplate ( ) ; DapSequence ds = ( DapSequence ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; List < Slice > slices = ce . getConstrainedSlices ( template ) ; Odometer odom = Odometer . factory ( slices ) ; if ( false ) while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; DataCursor [ ] instance = ( DataCursor [ ] ) data . read ( index ) ; writeSequence1 ( instance [ 0 ] , dst ) ; } else { DataCursor [ ] instances = ( DataCursor [ ] ) data . read ( slices ) ; for ( int i = 0 ; i < instances . length ; i ++ ) { writeSequence1 ( instances [ i ] , dst ) ; } }


signature:
public class DapSerializer { /** * Write out a single Sequence of records
 * ( Eventually use any filter in the DapVariable )
 * @ param instance the sequence instance
 * @ param dst write target
 * @ throws dap4 . core . util . DapException */
protected void writeSequence1 ( DataCursor instance , SerialWriter dst ) throws IOException { } }

implementation: DapVariable template = ( DapVariable ) instance . getTemplate ( ) ; DapSequence seq = ( DapSequence ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; long nrecs = instance . getRecordCount ( ) ; dst . writeCount ( nrecs ) ; for ( long i = 0 ; i < nrecs ; i ++ ) { DataCursor record = instance . readRecord ( i ) ; writeRecord ( record , dst ) ; }


signature:
public class DapSerializer { /** * Write out a single Record instance .
 * @ param record the record data cursor
 * @ param dst to which to write
 * @ throws dap4 . core . util . DapException */
protected void writeRecord ( DataCursor record , SerialWriter dst ) throws IOException { } }

implementation:
DapVariable template = ( DapVariable ) record . getTemplate ( ) ; DapSequence seq = ( DapSequence ) template . getBaseType ( ) ; List < DapVariable > fields = seq . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; if ( ! this . ce . references ( field ) ) continue ; // not in the view
DataCursor df = ( DataCursor ) record . readField ( i ) ; writeVariable ( df , dst ) ; }


signature:
public class asciiSeq { /** * Returns a string representation of the variables value . This
 * is really foreshadowing functionality for Server types , but
 * as it may come in useful for clients it is added here . Simple
 * types ( example : DFloat32 ) will return a single value . DConstuctor
 * and DVector types will be flattened . DStrings and DURL ' s will
 * have double quotes around them .
 * @ param addName is a flag indicating if the variable name should
 * appear at the begining of the returned string . */
public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { } }

implementation:
if ( _Debug ) System . out . println ( "asciiSeq.toASCII(" + addName + ",'" + rootName + "')  getName(): " + getEncodedName ( ) ) ; // System . out . println ( " this : " + this + " Has " + allValues . size ( ) + " elements . " ) ;
if ( rootName != null ) rootName += "." + getEncodedName ( ) ; else rootName = getEncodedName ( ) ; pw . print ( toASCIIFlatName ( rootName ) ) ; /* for ( Enumeration e1 = allValues . elements ( ) ; e1 . hasMoreElements ( ) ; ) {
 / / get next instance vector
 Vector v = ( Vector ) e1 . nextElement ( ) ;
 for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) {
 / / get next instance variable
 BaseType bt = ( BaseType ) e2 . nextElement ( ) ;
 pw . print ( bt . toASCIIFlatName ( rootName ) + " , " ) ;
 break ; */
pw . println ( "" ) ; int i = 0 ; for ( Enumeration e1 = allValues . elements ( ) ; e1 . hasMoreElements ( ) ; ) { int j = 0 ; // get next instance vector
Vector v = ( Vector ) e1 . nextElement ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable
toASCII ta = ( toASCII ) e2 . nextElement ( ) ; if ( j > 0 ) pw . print ( ", " ) ; ta . toASCII ( pw , false , rootName , false ) ; j ++ ; } pw . println ( "" ) ; } if ( newLine ) pw . print ( "\n" ) ;


signature: public class CoverageCoordAxisBuilder { CoverageCoordAxisBuilder subset ( String dependsOn , CoverageCoordAxis . Spacing spacing , int ncoords , double [ ] values ) { } }

implementation: assert values != null ; if ( dependsOn != null ) { this . dependenceType = CoverageCoordAxis . DependenceType . dependent ; setDependsOn ( dependsOn ) ; } this . spacing = spacing ; this . ncoords = ncoords ; this . reader = null ; this . values = values ; this . isSubset = true ; return this ;


signature:
public class MessageScanner { /** * is this a valid BUFR file .
 * @ param raf check this file
 * @ return true if its a BUFR file
 * @ throws IOException on read error */
static public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { } }

implementation:
raf . seek ( 0 ) ; if ( ! raf . searchForward ( matcher , 40 * 1000 ) ) return false ; // must find " BUFR " in first 40k
raf . skipBytes ( 4 ) ; BufrIndicatorSection is = new BufrIndicatorSection ( raf ) ; if ( is . getBufrEdition ( ) > 4 ) return false ; // if ( is . getBufrLength ( ) > MAX _ MESSAGE _ SIZE ) return false ;
return ! ( is . getBufrLength ( ) > raf . length ( ) ) ;


signature:
public class GempakStation { /** * Get the WMO Station ID as a string
 * @ return the WMO id */
public String getWmoId ( ) { } }

implementation: String wmoID = "" ; if ( ! ( stnm == GempakConstants . IMISSD ) ) { wmoID = String . valueOf ( ( int ) ( stnm / 10 ) ) ; } return wmoID ;


signature:
public class DArray { /** * Write the variable ' s declaration in a C - style syntax . This
 * function is used to create textual representation of the Data
 * Descriptor Structure ( DDS ) . See < em > The OPeNDAP User Manual < / em > for
 * information about this structure .
 * @ param os The < code > PrintWriter < / code > on which to print the
 * declaration .
 * @ param space Each line of the declaration will begin with the
 * characters in this string . Usually used for leading spaces .
 * @ param print _ semi a boolean value indicating whether to print a
 * semicolon at the end of the declaration .
 * @ see BaseType # printDecl ( PrintWriter , String , boolean ) */
public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { } }

implementation:
// BEWARE ! Since printDecl ( ) is ( multiplely ) overloaded in BaseType and
// all of the different signatures of printDecl ( ) in BaseType lead to
// one signature , we must be careful to override that SAME signature
// here . That way all calls to printDecl ( ) for this object lead to
// this implementation .
// os . println ( " DArray . printDecl ( ) " ) ;
getPrimitiveVector ( ) . printDecl ( os , space , false , constrained ) ; for ( Enumeration e = dimVector . elements ( ) ; e . hasMoreElements ( ) ; ) { DArrayDimension d = ( DArrayDimension ) e . nextElement ( ) ; os . print ( "[" ) ; String name = d . getEncodedName ( ) ; if ( name != null && name . length ( ) > 0 ) os . print ( d . getEncodedName ( ) + " = " ) ; os . print ( d . getSize ( ) + "]" ) ; } if ( print_semi ) os . println ( ";" ) ;


signature:
public class DArray { /** * Prints the value of the variable , with its declaration . This
 * function is primarily intended for debugging OPeNDAP applications and
 * text - based clients such as geturl .
 * @ param pw the < code > PrintWriter < / code > on which to print the value .
 * @ param space this value is passed to the < code > printDecl < / code > method ,
 * and controls the leading spaces of the output .
 * @ param print _ decl _ p a boolean value controlling whether the
 * variable declaration is printed as well as the value .
 * @ see BaseType # printVal ( PrintWriter , String , boolean ) */
public void printVal ( PrintWriter pw , String space , boolean print_decl_p ) { } }

implementation:
// print the declaration if print decl is true .
// for each dimension ,
// for each element ,
// print the array given its shape , number of dimensions .
// Add the ` ; '
if ( print_decl_p ) { printDecl ( pw , space , false ) ; pw . print ( " = " ) ; } int dims = numDimensions ( ) ; int shape [ ] = new int [ dims ] ; int i = 0 ; for ( Enumeration e = dimVector . elements ( ) ; e . hasMoreElements ( ) ; ) { DArrayDimension d = ( DArrayDimension ) e . nextElement ( ) ; shape [ i ++ ] = d . getSize ( ) ; } printArray ( pw , 0 , dims , shape , 0 ) ; if ( print_decl_p ) pw . println ( ";" ) ; pw . flush ( ) ;


signature:
public class DArray { /** * Print an array . This is a private member function .
 * @ param os is the stream used for writing
 * @ param index is the index of VEC to start printing
 * @ param dims is the number of dimensions in the array
 * @ param shape holds the size of the dimensions of the array .
 * @ param offset holds the current offset into the dimension array .
 * @ return the number of elements written . */
private int printArray ( PrintWriter os , int index , int dims , int shape [ ] , int offset ) { } }

implementation: if ( dims == 1 ) { os . print ( "{" ) ; for ( int i = 0 ; i < shape [ offset ] - 1 ; i ++ ) { getPrimitiveVector ( ) . printSingleVal ( os , index ++ ) ; os . print ( ", " ) ; } getPrimitiveVector ( ) . printSingleVal ( os , index ++ ) ; os . print ( "}" ) ; return index ; } else { os . print ( "{" ) ; for ( int i = 0 ; i < shape [ offset ] - 1 ; i ++ ) { index = printArray ( os , index , dims - 1 , shape , offset + 1 ) ; os . print ( "," ) ; } index = printArray ( os , index , dims - 1 , shape , offset + 1 ) ; os . print ( "}" ) ; return index ; }


signature:
public class DArray { /** * Given a size and a name , this function adds a dimension to the
 * array . For example , if the < code > DArray < / code > is already 10 elements
 * long , calling < code > appendDim < / code > with a size of 5 will transform the
 * array into a 10x5 matrix . Calling it again with a size of 2 will
 * create a 10x5x2 array , and so on .
 * @ param size the size of the desired new dimension .
 * @ param name the name of the new dimension . */
public void appendDim ( int size , String name ) { } }

implementation: DArrayDimension newDim = new DArrayDimension ( size , name ) ; dimVector . addElement ( newDim ) ; newDim . setContainer ( this ) ;


signature:
public class DArray { /** * Use this method to " squeeze " out all of the array dimensions whose
 * size is equal to 1.
 * < br >
 * Many queries that contstrain Arrays return an Array that has dimensions
 * whose size has been reduced to 1 . In effect that the dimension no longer
 * really exists , except as a notational convention for tracking the
 * hyperslab that the array represents . Since many clients have difficulty
 * handling n - dimensional arrays this method was added to allow the client
 * to easily " squeeze " the " extra " dimensions out of the array . */
public void squeeze ( ) { } }

implementation:
if ( dimVector . size ( ) == 1 ) return ; Vector < DArrayDimension > squeezeCandidates = new Vector < DArrayDimension > ( ) ; for ( DArrayDimension dim : dimVector ) { if ( dim . getSize ( ) == 1 ) squeezeCandidates . add ( dim ) ; } if ( squeezeCandidates . size ( ) == dimVector . size ( ) ) squeezeCandidates . remove ( squeezeCandidates . size ( ) - 1 ) ; // LogStream . out . println ( " DArray . squeeze ( ) : Removing " +
// squeezeCandidates . size ( ) + " dimensions of size 1 . " ) ;
dimVector . removeAll ( squeezeCandidates ) ;


signature:
public class DArray { /** * Returns the < code > DArrayDimension < / code > object for
 * the dimension requested . It makes sure that the dimension requested
 * exists . */
public DArrayDimension getDimension ( int dimension ) throws InvalidDimensionException { } }

implementation:
// QC the passed dimension
if ( dimension < dimVector . size ( ) ) return dimVector . get ( dimension ) ; else throw new InvalidDimensionException ( "DArray.getDimension(): Bad dimension request: dimension > # of dimensions" ) ;


signature:
public class DArray { /** * Returns a clone of this < code > Array < / code > .
 * See DAPNode . cloneDag ( )
 * @ param map track previously cloned nodes
 * @ return a clone of this object . */
public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { } }

implementation: DArray a = ( DArray ) super . cloneDAG ( map ) ; a . dimVector = new Vector < DArrayDimension > ( ) ; for ( int i = 0 ; i < dimVector . size ( ) ; i ++ ) { DArrayDimension d = dimVector . elementAt ( i ) ; DArrayDimension dclone = ( DArrayDimension ) cloneDAG ( map , d ) ; dclone . setContainer ( a ) ; a . dimVector . addElement ( dclone ) ; } return a ;


signature:
public class EcmwfCodeTableCompare { /** * Compare 2 tables , print report . */
public static void compareTables ( Grib2CodeTableInterface t1 , Grib2CodeTableInterface t2 , Formatter f ) { } }

implementation: int extra = 0 ; int conflict = 0 ; f . format ( "%s%n" , t2 . getName ( ) ) ; for ( Grib2CodeTableInterface . Entry p1 : t1 . getEntries ( ) ) { if ( t1 . getEntry ( p1 . getCode ( ) ) == null ) { f . format ( " ERROR %s missing own code %d%n" , t1 . getShortName ( ) , p1 . getCode ( ) ) ; } Grib2CodeTableInterface . Entry p2 = t2 . getEntry ( p1 . getCode ( ) ) ; if ( p2 == null ) { extra ++ ; if ( verbose ) { f . format ( "  %s missing %s%n" , t2 . getShortName ( ) , p1 ) ; } } else { if ( ! Util . equivilantName ( p1 . getName ( ) , p2 . getName ( ) ) ) { f . format ( "  p1=%10s %s%n" , p1 . getCode ( ) , p1 . getName ( ) ) ; f . format ( "  p2=%10s %s%n" , p2 . getCode ( ) , p2 . getName ( ) ) ; conflict ++ ; } } } int missing = 0 ; for ( Grib2CodeTableInterface . Entry p2 : t2 . getEntries ( ) ) { if ( t2 . getEntry ( p2 . getCode ( ) ) == null ) { f . format ( " ERROR %s missing own code %d%n" , t2 . getShortName ( ) , p2 . getCode ( ) ) ; } Grib2CodeTableInterface . Entry p1 = t1 . getEntry ( p2 . getCode ( ) ) ; if ( p1 == null ) { missing ++ ; f . format ( "  %s missing %s%n" , t1 . getShortName ( ) , p2 ) ; t1 . getEntry ( p2 . getCode ( ) ) ; } } if ( conflict > 0 || missing > 0 ) { f . format ( " ***Conflicts=%d extra=%d missing=%s%n" , conflict , extra , missing ) ; }


signature:
public class SDArray { /** * Set the state of this variable ' s projection . < code > true < / code > means
 * that this variable is part of the current projection as defined by
 * the current constraint expression , otherwise the current projection
 * for this variable should be < code > false < / code > .
 * @ param state < code > true < / code > if the variable is part of the current
 * projection , < code > false < / code > otherwise .
 * @ param all This parameter has no effect for this type of variable .
 * @ see CEEvaluator */
public void setProject ( boolean state , boolean all ) { } }

implementation: setProjected ( state ) ; PrimitiveVector vals = getPrimitiveVector ( ) ; ( ( ServerMethods ) ( vals . getTemplate ( ) ) ) . setProject ( state , all ) ;


signature:
public class SDArray { /** * Server - side serialization for OPeNDAP variables ( sub - classes of
 * < code > BaseType < / code > ) . This does not send the entire class as the Java
 * < code > Serializable < / code > interface does , rather it sends only the
 * binary data values . Other software is responsible for sending variable
 * type information ( see < code > DDS < / code > ) .
 * < / p > < p >
 * Writes data to a < code > DataOutputStream < / code > . This method is used
 * on the server side of the OPeNDAP client / server connection , and possibly
 * by GUI clients which need to download OPeNDAP data , manipulate it , and
 * then re - save it as a binary file .
 * < h2 > Caution : < / h2 >
 * When serializing arrays of sequences ( children of DSequence ) it is crucial
 * that it be handled with great care . Sequences have been implemented so that
 * only one instance ( or row if you will ) is retained in memory at a given time .
 * In order to correctly serialize an array of sequences the read ( ) method for the
 * array must create an instance of the sequence for each member of the array , typically
 * by repeatedly cloning the template variable in the PrimitiveVector . The important next
 * step is to NOT attempt to read any data into the sequences from within the read ( )
 * method of the parent array . The sequence ' s data will get read , and constraint expressions
 * applied when the serialze ( ) method of the array calls the serialize method of the
 * sequence . Good Luck !
 * @ param sink a < code > DataOutputStream < / code > to write to .
 * @ param ce a < code > CEEvaluator < / code > containing constraint Clauses .
 * @ param specialO a < code > Object < / code > to be used by < code > ServerMethods . read ( ) < / code >
 * @ throws IOException thrown on any < code > OutputStream < / code >
 * exception .
 * @ see BaseType
 * @ see DDS
 * @ see ServerDDS */
public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { } }

implementation:
PrimitiveVector vals = getPrimitiveVector ( ) ; if ( ! isRead ( ) ) read ( dataset , specialO ) ; if ( vals . getTemplate ( ) instanceof DSequence || ce . evalClauses ( specialO ) ) { // Because arrays of primitive types ( ie int32 , float32 , byte ,
// etc ) are handled in the C + + core using the XDR package we must
// write the length twice for those types . For BaseType vectors ,
// we should write it only once . This is in effect a work around
// for a bug in the C + + core as the C + + core does not consume 2
// length values for thge BaseType vectors . Bummer . . .
int length = vals . getLength ( ) ; sink . writeInt ( length ) ; // Gotta check for this to make sure that DConstructor types
// ( Especially SDSequence ) get handled correctly ! ! !
if ( vals instanceof BaseTypePrimitiveVector ) { for ( int i = 0 ; i < length ; i ++ ) { ServerMethods sm = ( ServerMethods ) ( ( BaseTypePrimitiveVector ) vals ) . getValue ( i ) ; sm . serialize ( dataset , sink , ce , specialO ) ; } } else { // Because both XDR and OPeNDAP read the length , we must write
// it twice .
sink . writeInt ( length ) ; vals . externalize ( sink ) ; } }


signature:
public class SDArray { /** * Set the projection information for this dimension . The
 * < code > DArrayDimension < / code > associated with the
 * < code > dimension < / code > specified is retrieved and the
 * < code > start < / code > < code > stride < / code > and < code > stop < / code >
 * parameters are passed to its < code > setProjection ( ) < / code > method .
 * @ param dimension The dimension that is to be modified .
 * @ param start The starting point for the projection of this
 * < code > DArrayDimension < / code > .
 * @ param stride The size of the stride for the projection of this
 * < code > DArrayDimension < / code > .
 * @ param stop The stopping point for the projection of this
 * < code > DArrayDimension < / code > .
 * @ see DArray
 * @ see DArrayDimension */
public void setProjection ( int dimension , int start , int stride , int stop ) throws InvalidDimensionException { } }

implementation: DArrayDimension d = getDimension ( dimension ) ; d . setProjection ( start , stride , stop ) ;


signature:
public class DbaseData { /** * Method to read an entry from the data stream . The stream is assumed to be
 * in the right spot for reading . This method should be called from something
 * controlling the reading of the entire file .
 * @ see DbaseFile */
int readRowN ( DataInputStream ds , int n ) { } }

implementation:
if ( n > nrec ) return - 1 ; /* the assumption here is that the DataInputStream ( ds )
 * is already pointing at the right spot ! */
try { ds . readFully ( field , 0 , desc . FieldLength ) ; } catch ( java . io . IOException e ) { return - 1 ; } switch ( desc . Type ) { case 'C' : case 'D' : character [ n ] = new String ( field , CDM . utf8Charset ) ; break ; case 'N' : numeric [ n ] = Double . valueOf ( new String ( field , CDM . utf8Charset ) ) ; break ; case 'F' : /* binary floating point */
if ( desc . FieldLength == 4 ) { numeric [ n ] = ( double ) Swap . swapFloat ( field , 0 ) ; } else { numeric [ n ] = Swap . swapDouble ( field , 0 ) ; } break ; case 'L' : switch ( field [ 0 ] ) { case 't' : case 'T' : case 'Y' : case 'y' : logical [ n ] = true ; break ; default : logical [ n ] = false ; break ; } default : return - 1 ; } return 0 ;


signature:
public class DbaseData { /** * Method to retrieve data for this field
 * @ param i index of desired String , assumes 0 < i < getNumRec ( )
 * @ return either a Double , Boolean , or String with the data */
public Object getData ( int i ) { } }

implementation: switch ( type ) { case TYPE_CHAR : return character [ i ] ; case TYPE_NUMERIC : return numeric [ i ] ; case TYPE_BOOLEAN : return logical [ i ] ; } return null ;


signature:
public class WmoCodeFlagTables { /** * Param Table :
 * < GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * < No > 524 < / No >
 * < Title _ en > Code table 4.2 - Parameter number by product discipline and parameter category < / Title _ en >
 * < SubTitle _ en > Product discipline 0 - Meteorological products , parameter category 1 : moisture < / SubTitle _ en >
 * < CodeFlag > 101 < / CodeFlag >
 * < MeaningParameterDescription _ en > Specific number concentration of snow < / MeaningParameterDescription _ en >
 * < UnitComments _ en > kg - 1 < / UnitComments _ en >
 * < ElementDescription _ en > Number of particles per unit mass of air < / ElementDescription _ en >
 * < Status > Operational < / Status >
 * < / GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * Code Table :
 * < GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * < No > 2 < / No >
 * < Title _ en > Code table 0.0 - Discipline of processed data in the GRIB message , number of GRIB Master table < / Title _ en >
 * < CodeFlag > 1 < / CodeFlag >
 * < MeaningParameterDescription _ en > Hydrological products < / MeaningParameterDescription _ en >
 * < Status > Operational < / Status >
 * < / GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * FlagTable :
 * < GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * < No > 168 < / No >
 * < Title _ en > Flag table 3.4 - Scanning mode < / Title _ en >
 * < CodeFlag > 1 < / CodeFlag >
 * < Value > 0 < / Value >
 * < MeaningParameterDescription _ en > Points of first row or column scan in the + i ( + x ) direction < / MeaningParameterDescription _ en >
 * < Status > Operational < / Status >
 * < / GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * < GRIB2_22_0_0 _ CodeFlag _ exp _ en >
 * < No > 169 < / No >
 * < Title _ en > Flag table 3.4 - Scanning mode < / Title _ en >
 * < CodeFlag > 1 < / CodeFlag >
 * < Value > 1 < / Value >
 * < MeaningParameterDescription _ en > Points of first row or column scan in the - i ( - x ) direction < / MeaningParameterDescription _ en >
 * < Status > Operational < / Status >
 * < / GRIB2_22_0_0 _ CodeFlag _ exp _ en > */
private void readGribCodes ( Version version ) throws IOException { } }

implementation:
String [ ] elems = version . getElemNames ( ) ; if ( elems == null ) { throw new IllegalStateException ( "unknown version = " + version ) ; } try ( InputStream ios = WmoCodeFlagTables . class . getResourceAsStream ( version . getResourceName ( ) ) ) { if ( ios == null ) { logger . error ( "cant open WmoCodeTable=" + version . getResourceName ( ) ) ; throw new IOException ( "cant open WmoCodeTable=" + version . getResourceName ( ) ) ; } org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( ios ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } Element root = doc . getRootElement ( ) ; Map < String , WmoTable > map = new HashMap < > ( ) ; List < Element > featList = root . getChildren ( elems [ 0 ] ) ; // main element
for ( Element elem : featList ) { String line = elem . getChildTextNormalize ( "No" ) ; String tableName = elem . getChildTextNormalize ( elems [ 1 ] ) ; // Title _ en
Element subtableElem = elem . getChild ( elems [ 2 ] ) ; // " SubTitle _ en "
TableType type ; if ( tableName . startsWith ( "Code table 4.1 " ) ) { type = TableType . cat ; } else if ( tableName . startsWith ( "Code table 4.2 " ) ) { type = TableType . param ; } else if ( tableName . startsWith ( "Flag" ) ) { type = TableType . flag ; } else if ( tableName . startsWith ( "Code" ) ) { type = TableType . code ; } else { logger . warn ( "Unknown wmo table entry = '%s'" , tableName ) ; continue ; } if ( subtableElem != null ) { tableName = subtableElem . getTextNormalize ( ) ; } TableType finalType = type ; WmoTable wmoTable = map . computeIfAbsent ( tableName , name -> new WmoTable ( name , finalType ) ) ; String code = elem . getChildTextNormalize ( "CodeFlag" ) ; String value = elem . getChildTextNormalize ( "Value" ) ; // Flag table only
String meaning = elem . getChildTextNormalize ( elems [ 3 ] ) ; // MeaningParameterDescription _ en
Element unitElem = elem . getChild ( elems [ 4 ] ) ; // " UnitComments _ en "
String unit = ( unitElem == null ) ? null : unitElem . getTextNormalize ( ) ; Element statusElem = elem . getChild ( "Status" ) ; String status = ( statusElem == null ) ? null : statusElem . getTextNormalize ( ) ; wmoTable . addEntry ( line , code , value , meaning , unit , status ) ; } ios . close ( ) ; this . wmoTables = map . values ( ) . stream ( ) . sorted ( ) . collect ( ImmutableList . toImmutableList ( ) ) ; ImmutableMap . Builder < String , WmoTable > builder = ImmutableMap . builder ( ) ; map . values ( ) . forEach ( t -> builder . put ( t . getId ( ) , t ) ) ; this . wmoTableMap = builder . build ( ) ; }


signature:
public class Grib2DataReader { /** * Code Table Code table 5.0 - Data representation template number ( 5.0)
 * 0 : Grid point data - simple packing
 * 1 : Matrix value at grid point - simple packing
 * 2 : Grid point data - complex packing
 * 3 : Grid point data - complex packing and spatial differencing
 * 4 : Grid point data - IEEE floating point data
 * 40 : Grid point data - JPEG 2000 code stream format
 * 41 : Grid point data - Portable Network Graphics ( PNG )
 * 50 : Spectral data - simple packing
 * 51 : Spherical harmonics data - complex packing
 * 61 : Grid point data - simple packing with logarithm pre - processing
 * 200 : Run length packing with level values
 * 65535 : Missing */
public float [ ] getData ( RandomAccessFile raf , Grib2SectionBitMap bitmapSection , Grib2Drs gdrs ) throws IOException { } }

implementation:
this . bitmap = bitmapSection . getBitmap ( raf ) ; this . bitmapIndicator = bitmapSection . getBitMapIndicator ( ) ; if ( bitmap != null ) { // is bitmap ok ?
if ( bitmap . length * 8 < totalNPoints ) { // gdsNumberPoints = = nx * ny ? ?
logger . warn ( "Bitmap section length = {} != grid length {} ({},{})" , bitmap . length , totalNPoints , nx , totalNPoints / nx ) ; throw new IllegalStateException ( "Bitmap section length!= grid length" ) ; } } raf . seek ( startPos + 5 ) ; // skip past first 5 bytes in data section , now ready to read
float [ ] data ; switch ( dataTemplate ) { case 0 : data = getData0 ( raf , ( Grib2Drs . Type0 ) gdrs ) ; break ; case 2 : data = getData2 ( raf , ( Grib2Drs . Type2 ) gdrs ) ; break ; case 3 : data = getData3 ( raf , ( Grib2Drs . Type3 ) gdrs ) ; break ; case 40 : data = getData40 ( raf , ( Grib2Drs . Type40 ) gdrs ) ; break ; case 41 : data = getData41 ( raf , ( Grib2Drs . Type0 ) gdrs ) ; break ; case 50002 : data = getData50002 ( raf , ( Grib2Drs . Type50002 ) gdrs ) ; break ; default : throw new UnsupportedOperationException ( "Unsupported DRS type = " + dataTemplate ) ; } // int scanMode = gds . getGds ( ) . getScanMode ( ) ;
// int nx = gds . getGds ( ) . getNx ( ) ; / / needs some smarts for different type Grids
scanningModeCheck ( data , scanMode , nx ) ; return data ;


signature:
public class Grib2DataReader { /** * Grid point data - simple packing */
private float [ ] getData0 ( RandomAccessFile raf , Grib2Drs . Type0 gdrs ) throws IOException { } }

implementation:
int nb = gdrs . numberOfBits ; int D = gdrs . decimalScaleFactor ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) D ) ; float R = gdrs . referenceValue ; int E = gdrs . binaryScaleFactor ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) E ) ; // LOOK : can # datapoints differ from bitmap and data ?
// dataPoints are number of points encoded , it could be less than the
// totalNPoints in the grid record if bitMap is used , otherwise equal
float [ ] data = new float [ totalNPoints ] ; // Y * 10 * * D = R + ( X1 + X2 ) * 2 * * E
// E = binary scale factor
// D = decimal scale factor
// R = reference value
// X1 = 0
// X2 = scaled encoded value
// data [ i ] = ( R + ( X1 + X2 ) * EE ) / DD ;
BitReader reader = new BitReader ( raf , startPos + 5 ) ; if ( bitmap == null ) { for ( int i = 0 ; i < totalNPoints ; i ++ ) { // data [ i ] = ( R + ( X1 + X2 ) * EE ) / DD ;
data [ i ] = ( R + reader . bits2UInt ( nb ) * EE ) / DD ; } } else { for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { data [ i ] = ( R + reader . bits2UInt ( nb ) * EE ) / DD ; } else { data [ i ] = staticMissingValue ; // data [ i ] = R / DD ;
} } } return data ;


signature:
public class Grib2DataReader { /** * Data template 7.2 – Grid point data – complex packing
 * Note : For most templates , details of the packing process are described in Regulation 92.9.4.
 * Octet No . Contents
 * 6 – xx NG group reference values ( X1 in the decoding formula ) , each of which is encoded using
 * the number of bits specified in octet 20 of data representation template 5.0 . Bits set to zero
 * shall be appended as necessary to ensure this sequence of numbers ends on an octet boundary
 * [ xx + 1 ] – yy NG group widths , each of which is encoded using the number of bits specified in octet 37
 * of data representation template 5.2 . Bits set to zero shall be appended as necessary to
 * ensure this sequence of numbers ends on an octet boundary
 * [ yy + 1 ] – zz NG scaled group lengths , each of which is encoded using the number of bits specified in
 * octet 47 of data representation template 5.2 . Bits set to zero shall be appended as necessary
 * to ensure this sequence of numbers ends on an octet boundary ( see Note 14 of data
 * representation template 5.2)
 * [ zz + 1 ] – nn Packed values ( X2 in the decoding formula ) , where each value is a deviation from its respective
 * group reference value
 * Notes :
 * ( 1 ) Group descriptors mentioned above may not be physically present ; if associated field width is 0.
 * ( 2 ) Group lengths have no meaning for row by row packing ; for consistency , associated field width should then be
 * encoded as 0 . So no specific test for row by row case is mandatory at decoding software level to handle
 * encoding / decoding of group descriptors .
 * ( 3 ) Scaled group lengths , if present , are encoded for each group . But the true last group length ( unscaled ) should be taken
 * from data representation template .
 * ( 4 ) For groups with a constant value , associated field width is 0 , and no incremental data are physically present . */
private float [ ] getData2 ( RandomAccessFile raf , Grib2Drs . Type2 gdrs ) throws IOException { } }

implementation:
int mvm = gdrs . missingValueManagement ; float mv = getMissingValue ( gdrs ) ; float DD = ( float ) java . lang . Math . pow ( ( double ) 10 , ( double ) gdrs . decimalScaleFactor ) ; float R = gdrs . referenceValue ; float EE = ( float ) java . lang . Math . pow ( 2.0 , ( double ) gdrs . binaryScaleFactor ) ; float ref_val = R / DD ; int NG = gdrs . numberOfGroups ; if ( NG == 0 ) { return nGroups0 ( bitmapIndicator , ref_val , mv ) ; } BitReader reader = new BitReader ( raf , startPos + 5 ) ; // 6 - xx Get reference values for groups ( X1 ' s )
int [ ] X1 = new int [ NG ] ; int nb = gdrs . numberOfBits ; if ( nb != 0 ) { for ( int i = 0 ; i < NG ; i ++ ) { X1 [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } // [ xx + 1 ] - yy Get number of bits used to encode each group
int [ ] NB = new int [ NG ] ; nb = gdrs . bitsGroupWidths ; if ( nb != 0 ) { reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { NB [ i ] = ( int ) reader . bits2UInt ( nb ) ; } } // [ yy + 1 ] - zz Get the scaled group lengths using formula
// Ln = ref + Kn * len _ inc , where n = 1 - NG ,
// ref = referenceGroupLength , and len _ inc = lengthIncrement
int [ ] L = new int [ NG ] ; int ref = gdrs . referenceGroupLength ; int len_inc = gdrs . lengthIncrement ; nb = gdrs . bitsScaledGroupLength ; reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { L [ i ] = ref + ( int ) reader . bits2UInt ( nb ) * len_inc ; } L [ NG - 1 ] = gdrs . lengthLastGroup ; // enter Length of Last Group
float [ ] data = new float [ totalNPoints ] ; // [ zz + 1 ] - nn get X2 values and calculate the results Y using formula
// Y = R + [ ( X1 + X2 ) * ( 2 * * E ) * ( 10 * * D ) ]
// WHERE :
// Y = THE VALUE WE ARE UNPACKING
// R = THE REFERENCE VALUE ( FIRST ORDER MINIMA )
// X1 = THE PACKED VALUE
// X2 = THE SECOND ORDER MINIMA
// E = THE BINARY SCALE FACTOR
// D = THE DECIMAL SCALE FACTOR
int count = 0 ; reader . incrByte ( ) ; for ( int i = 0 ; i < NG ; i ++ ) { for ( int j = 0 ; j < L [ i ] ; j ++ ) { if ( NB [ i ] == 0 ) { if ( mvm == 0 ) { // X2 = 0
data [ count ++ ] = ( R + X1 [ i ] * EE ) / DD ; } else { // if ( mvm = = 1 ) | | ( mvm = = 2 )
data [ count ++ ] = mv ; } } else { int X2 = ( int ) reader . bits2UInt ( NB [ i ] ) ; if ( mvm == 0 ) { data [ count ++ ] = ( R + ( X1 [ i ] + X2 ) * EE ) / DD ; } else { // if ( mvm = = 1 ) | | ( mvm = = 2 )
// X2 is also set to missing value if all bits set to 1 ' s
if ( X2 == bitsmv1 [ NB [ i ] ] ) { data [ count ++ ] = mv ; } else { data [ count ++ ] = ( R + ( X1 [ i ] + X2 ) * EE ) / DD ; } } } } // end for j
} // end for i
if ( bitmap != null ) { int idx = 0 ; float [ ] tmp = new float [ totalNPoints ] ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( GribNumbers . testBitIsSet ( bitmap [ i / 8 ] , i % 8 ) ) { tmp [ i ] = data [ idx ++ ] ; } else { tmp [ i ] = mv ; } } data = tmp ; } return data ;


signature:
public class Grib2DataReader { /** * / * from wgrib unpk _ complex ( ) :
 * p = sec [ 5 ] ; / / drs
 * ref _ val = ieee2flt ( p + 11 ) ; / / R
 * factor _ 2 = Int _ Power ( 2.0 , int2 ( p + 15 ) ) ; / / 2 ^ E
 * factor _ 10 = Int _ Power ( 10.0 , - int2 ( p + 17 ) ) ; / / 10 ^ - D
 * ref _ val * = factor _ 10 ; / / R / 10 ^ D
 * factor = factor _ 2 * factor _ 10 ; / / 2 ^ E * 10 ^ - D
 * nbits = p [ 19 ] ; / / NB
 * ngroups = uint4 ( p + 31 ) ; / / NG
 * bitmap _ flag = code _ table _ 6_0 ( sec ) ; / / bitmap - > indicator
 * ctable _ 5_6 = code _ table _ 5_6 ( sec ) ;
 * bitmap _ flag = code _ table _ 6_0 ( sec ) ; / / = = gr . getBitmapSection ( ) . getBitMapIndicator ( ) ;
 * if ( ngroups = = 0 ) {
 * if ( bitmap _ flag = = 255 ) {
 * for ( i = 0 ; i < ndata ; i + + ) data [ i ] = ref _ val ;
 * return 0;
 * if ( bitmap _ flag = = 0 | | bitmap _ flag = = 254 ) {
 * mask _ pointer = sec [ 6 ] + 6 ; / / probably bitmask is here ? ?
 * mask = 0;
 * for ( i = 0 ; i < ndata ; i + + ) {
 * if ( ( i & 7 ) = = 0 ) mask = * mask _ pointer + + ; / / get next byte ? ?
 * data [ i ] = ( mask & 128 ) ? ref _ val : UNDEFINED ; / / bit 7 set
 * mask < < = 1 ; / / shift
 * return 0;
 * fatal _ error ( " unknown bitmap " , " " ) ; */
private float [ ] nGroups0 ( int bitmap_flag , float ref , float mv1 ) { } }

implementation: float [ ] data = new float [ totalNPoints ] ; if ( bitmap_flag == 255 ) { for ( int i = 0 ; i < totalNPoints ; i ++ ) { data [ i ] = ref ; } } else if ( bitmap_flag == 0 || bitmap_flag == 254 ) { int mask = 0 ; int mask_pointer = 0 ; for ( int i = 0 ; i < totalNPoints ; i ++ ) { if ( ( i & 7 ) == 0 ) { mask = bitmap [ mask_pointer ] ; mask_pointer ++ ; } data [ i ] = ( ( mask & 128 ) == 0 ) ? ref : mv1 ; mask <<= 1 ; } } else { throw new IllegalArgumentException ( "unknown bitmap type =" + bitmap_flag ) ; } return data ;