signature:
public class PicturePane { /** * method that moves the image left by 10 % of the pixels shown on the screen .
 * This method
 * calls < code > repaint ( ) < / code > directly since no time consuming image operations need to take place .
 * works just liks { @ link # scrollUp ( ) } .
 * @ see # scrollUp ( )
 * @ see # scrollDown ( )
 * @ see # scrollLeft ( )
 * @ see # scrollRight ( ) */
public void scrollLeft ( ) { } }

implementation:
// if the bottom edge of the picture is visible , do not scroll
if ( ( ( sclPic . getOriginalWidth ( ) - focusPoint . x ) * sclPic . getScaleFactor ( ) ) + getSize ( ) . width / 2 > getSize ( ) . width ) { focusPoint . x = focusPoint . x + ( int ) ( getSize ( ) . width * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( "Scrollup rejected because right edge of picture is already showing." ) ; }


signature:
public class PicturePane { /** * method that moves the image right by 10 % of the pixels shown on the screen .
 * This method
 * calls < code > repaint ( ) < / code > directly since no time consuming image operations need to take place .
 * works just liks { @ link # scrollDown ( ) } .
 * @ see # scrollUp ( )
 * @ see # scrollDown ( )
 * @ see # scrollLeft ( )
 * @ see # scrollRight ( ) */
public void scrollRight ( ) { } }

implementation: if ( getSize ( ) . width / 2 - focusPoint . x * sclPic . getScaleFactor ( ) < 0 ) { focusPoint . x = focusPoint . x - ( int ) ( getSize ( ) . width * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( "Scroll left rejected because left edge is aready visible" ) ; }


signature:
public class PicturePane { /** * method to set the center of the image to the true coordinates in the picture but doesn ' t call < code > repaint ( ) < / code > */
public void setCenterLocation ( int Xparameter , int Yparameter ) { } }

implementation: Tools . log ( "setCenterLocation invoked with " + Xparameter + " x " + Yparameter ) ; focusPoint . setLocation ( Xparameter , Yparameter ) ;


signature:
public class PicturePane { /** * we are overriding the default paintComponent method , grabbing the Graphics
 * handle and doing our own drawing here . Esentially this method draws a large
 * black rectangle . A drawRenderedImage is then painted doing an affine transformation
 * on the scaled image to position it so the the desired point is in the middle of the
 * Graphics object . The picture is not scaled here because this is a slow operation
 * and only needs to be done once , while moving the image is something the user is
 * likely to do more often . */
public void paintComponent ( Graphics g ) { } }

implementation:
int WindowWidth = getSize ( ) . width ; int WindowHeight = getSize ( ) . height ; Tools . log ( "paintComponent called" ) ; if ( Dragging == false ) { // otherwise it ' s already a move Cursor
setCursor ( new Cursor ( Cursor . WAIT_CURSOR ) ) ; } if ( sclPic . getScaledPicture ( ) != null ) { Graphics2D g2d = ( Graphics2D ) g ; int X_Offset = ( int ) ( ( double ) ( WindowWidth / 2 ) - ( focusPoint . x * sclPic . getScaleFactor ( ) ) ) ; int Y_Offset = ( int ) ( ( double ) ( WindowHeight / 2 ) - ( focusPoint . y * sclPic . getScaleFactor ( ) ) ) ; // clear damaged component area
Rectangle clipBounds = g2d . getClipBounds ( ) ; g2d . setColor ( Color . black ) ; // getBackground ( ) ) ;
g2d . fillRect ( clipBounds . x , clipBounds . y , clipBounds . width , clipBounds . height ) ; g2d . drawRenderedImage ( sclPic . getScaledPicture ( ) , AffineTransform . getTranslateInstance ( X_Offset , Y_Offset ) ) ; // g2d . drawImage ( sclPic . getScaledPicture ( ) , null , 0 , 0 ) ;
if ( showInfo ) { g2d . setColor ( Color . white ) ; g2d . drawString ( legend , infoPoint . x , infoPoint . y ) ; g2d . drawString ( "Size: " + Integer . toString ( sclPic . getOriginalWidth ( ) ) + " x " + Integer . toString ( sclPic . getOriginalHeight ( ) ) + " Offset: " + X_Offset + " x " + Y_Offset + " Mid: " + Integer . toString ( focusPoint . x ) + " x " + Integer . toString ( focusPoint . y ) + " Scale: " + twoDecimalFormatter . format ( sclPic . getScaleFactor ( ) ) , infoPoint . x , infoPoint . y + lineSpacing ) ; /* g2d . drawString ( " File : " + sclPic . getFilename ( )
 , infoPoint . x
 , infoPoint . y + ( 2 * lineSpacing ) ) ;
 g2d . drawString ( " Loaded in : "
 + twoDecimalFormatter . format ( sclPic . getSourcePicture ( ) . loadTime / 1000F )
 + " Seconds "
 , infoPoint . x
 , infoPoint . y + ( 3 * lineSpacing ) ) ;
 g2d . drawString ( " Free memory : "
 + Long . toString ( Runtime . getRuntime ( ) . freeMemory ( ) / 1024/1024 , 0 )
 + " MB "
 , infoPoint . x
 , infoPoint . y + ( 4 * lineSpacing ) ) ; */
} } else { // paint a black square
g . setClip ( 0 , 0 , WindowWidth , WindowHeight ) ; g . setColor ( Color . black ) ; g . fillRect ( 0 , 0 , WindowWidth , WindowHeight ) ; } if ( Dragging == false ) { // otherwise a move Cursor and should remain
setCursor ( new Cursor ( Cursor . DEFAULT_CURSOR ) ) ; }


signature:
public class PicturePane { /** * method that gets invoked from the ScalablePicture object to notify of status changes .
 * The ScalablePicture goes through several statusses : UNINITIALISED , GARBAGE _ COLLECTION ,
 * LOADING , SCALING , READY , ERROR . < p >
 * Each status is passed to the listener upon receipt . < p >
 * When the ScalablePicture signals that it is READY the legend of the picture is sent
 * to the listener . The method { @ link # centerImage } is called and a repaint is requested . */
public void scalableStatusChange ( int pictureStatusCode , String pictureStatusMessage ) { } }

implementation: Tools . log ( "PicturePane.scalableStatusChange: got a status change: " + pictureStatusMessage ) ; if ( pictureStatusCode == ScalablePicture . READY ) { Tools . log ( "PicturePane.scalableStatusChange: a READY status" ) ; pictureStatusMessage = legend ; if ( centerWhenScaled ) { Tools . log ( "PicturePane.scalableStatusChange: centering image" ) ; centerImage ( ) ; } Tools . log ( "PicturePane.scalableStatusChange: forcing Panel repaint" ) ; repaint ( ) ; } Enumeration e = picturePaneListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . scalableStatusChange ( pictureStatusCode , pictureStatusMessage ) ; }


signature:
public class GempakUtil { /** * This subroutine converts the two integers stored in a grid file
 * into three integers containing the date , time and forecast time .
 * @ param iftime input time array
 * @ param start offset into the array
 * @ return int [ 3 ] with date time and forecast time */
public static int [ ] TG_FTOI ( int [ ] iftime , int start ) { } }

implementation:
int [ ] intdtf = new int [ 3 ] ; // If there is no forecast information , the string is stored as
// date and time .
if ( iftime [ start ] < 100000000 ) { intdtf [ 0 ] = iftime [ start ] ; intdtf [ 1 ] = iftime [ start + 1 ] ; intdtf [ 2 ] = 0 ; // Otherwise , decode date / time and forecast info from the
// two integers .
} else { // The first word contains MMDDYYHHMM . This must be turned
// into YYMMDD and HHMM .
intdtf [ 0 ] = iftime [ start ] / 10000 ; intdtf [ 1 ] = iftime [ start ] - intdtf [ 0 ] * 10000 ; int mmdd = intdtf [ 0 ] / 100 ; int iyyy = intdtf [ 0 ] - mmdd * 100 ; intdtf [ 0 ] = iyyy * 10000 + mmdd ; // The forecast time remains the same .
intdtf [ 2 ] = iftime [ start + 1 ] ; } return intdtf ;


signature:
public class GempakUtil { /** * This subroutine converts an integer time array containing the date ,
 * time and forecast time into a GEMPAK grid time .
 * @ param intdtf integer array of date , time and forecast time
 * @ return formatted string */
public static String TG_ITOC ( int [ ] intdtf ) { } }

implementation:
String gdattim = "" ; // Check for the blank time which may be found .
if ( ( intdtf [ 0 ] == 0 ) && ( intdtf [ 1 ] == 0 ) && ( intdtf [ 2 ] == 0 ) ) { return gdattim ; } // Put the date and time into the character time .
gdattim = TI_CDTM ( intdtf [ 0 ] , intdtf [ 1 ] ) ; // Decode the forecast information if there is any .
if ( intdtf [ 2 ] != 0 ) { String [ ] timeType = TG_CFTM ( intdtf [ 2 ] ) ; String ftype = timeType [ 0 ] ; String ftime = timeType [ 1 ] ; // Combine two parts into string .
gdattim = gdattim . substring ( 0 , 11 ) + ftype + ftime ; } return gdattim ;


signature:
public class GempakUtil { /** * This subroutine converts an integer grid forecast time into
 * the character forecast type and time . The forecast type
 * is A ( analysis ) , F ( forecast ) , G ( guess ) or I ( initialize ) .
 * If the forecast time is less than 100 and the minutes are 00,
 * only hh is returned .
 * @ param ifcast integer forecast time
 * @ return type and time . */
public static String [ ] TG_CFTM ( int ifcast ) { } }

implementation:
String ftype = "" ; String ftime = "" ; // Check for negative times .
if ( ifcast < 0 ) { return new String [ ] { ftype , ftime } ; } // Get the number representing forecast type and convert to a
// character .
int iftype = ifcast / 100000 ; if ( iftype == 0 ) { ftype = "A" ; } else if ( iftype == 1 ) { ftype = "F" ; } else if ( iftype == 2 ) { ftype = "G" ; } else if ( iftype == 3 ) { ftype = "I" ; } // Convert the time to a character . Add 100000 so that leading
// zeros will be encoded .
int iftime = ifcast - iftype * 100000 ; int ietime = iftime + 100000 ; String fff = ST_INCH ( ietime ) ; // If the forecast time has minutes , set the character output
// to all five digits . Otherwise , use only the first three digits ,
// which represent hours .
if ( ietime % 100 == 0 ) { ftime = fff . substring ( 1 , 4 ) ; } else { ftime = fff . substring ( 1 ) ; } return new String [ ] { ftype , ftime } ;


signature:
public class GempakUtil { /** * This subroutine converts an integer date ( YYMMDD ) and time ( HHMM )
 * @ param idate integer date
 * @ param itime integer time
 * @ return string date / time */
public static String TI_CDTM ( int idate , int itime ) { } }

implementation: String dattim ; int [ ] idtarr = new int [ 5 ] ; idtarr [ 0 ] = idate / 10000 ; idtarr [ 1 ] = ( idate - idtarr [ 0 ] * 10000 ) / 100 ; idtarr [ 2 ] = idate % 100 ; idtarr [ 3 ] = itime / 100 ; idtarr [ 4 ] = itime % 100 ; dattim = TI_ITOC ( idtarr ) ; return dattim ;


signature:
public class GempakUtil { /** * This subroutine converts an integer time array into a standard
 * GEMPAK time . The integers are checked for validity .
 * @ param idtarr Time array ( YYYY , MM , DD , HH , MM )
 * @ return time as a string */
public static String TI_ITOC ( int [ ] idtarr ) { } }

implementation:
String dattim ; String date , time ; // Put array values into variables .
int iyear = idtarr [ 0 ] ; int imonth = idtarr [ 1 ] ; int iday = idtarr [ 2 ] ; int ihour = idtarr [ 3 ] ; int iminut = idtarr [ 4 ] ; // Check for leap year .
// int ndays = TI _ DAYM ( iyear , imonth ) ;
iyear = iyear % 100 ; // Check that each of these values is valid .
/* TODO : Check these
 IF ( iyear . lt . 0 ) iret = - 7
 IF ( ( imonth . lt . 1 ) . or . ( imonth . gt . 12 ) ) iret = - 8
 IF ( ( iday . lt . 1 ) . or . ( iday . gt . ndays ) )
 + iret = - 9
 IF ( ( ihour . lt . 0 ) . or . ( ihour . gt . 24 ) ) iret = - 10
 IF ( ( iminut . lt . 0 ) . or . ( iminut . gt . 60 ) ) iret = - 11
 IF ( iret . ne . 0 ) RETURN */
// Get the date and time .
int idate = iyear * 10000 + imonth * 100 + iday ; int itime = ihour * 100 + iminut ; // Convert date and time to character strings .
// Fill in blanks with zeroes .
date = StringUtil2 . padZero ( idate , 6 ) ; time = StringUtil2 . padZero ( itime , 4 ) ; dattim = date + "/" + time ; return dattim ;


signature:
public class GempakUtil { /** * This subroutine returns the number of days in the given month .
 * The year must be a full four - digit year .
 * @ param iyear integer year
 * @ param imon integer month
 * @ return number of days */
public static int TI_DAYM ( int iyear , int imon ) { } }

implementation:
int iday = 0 ; if ( ( imon > 0 ) && ( imon < 13 ) ) { // Pick the number of days for the given month .
iday = month [ imon - 1 ] ; if ( ( imon == 2 ) && LEAP ( iyear ) ) { iday = iday + 1 ; } } return iday ;


signature:
public class GempakUtil { /** * Convert the int bits to a string
 * @ param value value to convert
 * @ return string representation */
public static String ST_ITOC ( int value ) { } }

implementation: byte [ ] bval = new byte [ 4 ] ; bval [ 0 ] = ( byte ) ( ( value & 0xff000000 ) >>> 24 ) ; bval [ 1 ] = ( byte ) ( ( value & 0x00ff0000 ) >>> 16 ) ; bval [ 2 ] = ( byte ) ( ( value & 0x0000ff00 ) >>> 8 ) ; bval [ 3 ] = ( byte ) ( ( value & 0x000000ff ) ) ; return new String ( bval , CDM . utf8Charset ) ;


signature:
public class GempakUtil { /** * Convert the int bits to a string
 * @ param values array of values to convert
 * @ return string representation */
public static String ST_ITOC ( int [ ] values ) { } }

implementation: StringBuilder sb = new StringBuilder ( ) ; for ( int value : values ) { sb . append ( ST_ITOC ( value ) ) ; } return sb . toString ( ) ;


signature:
public class GempakUtil { /** * This subroutine translates a numeric value for IVCORD into its
 * character value in VCOORD .
 * @ param ivcord integer coordinate value
 * @ return string coordinate name */
public static String LV_CCRD ( int ivcord ) { } }

implementation:
// Translate known vertical coordinates or look for parameter name .
String vcoord = "" ; // Check for numeric vertical coordinates .
if ( ( ivcord >= 0 ) && ( ivcord < vertCoords . length ) ) { vcoord = vertCoords [ ivcord ] ; } else if ( ivcord > 100 ) { // Check for character name as vertical coordinate . Check that
// each character is an alphanumeric character .
vcoord = ST_ITOC ( ivcord ) ; /* Check for bad values
 DO i = 1 , 4
 v = vcoord ( i : i )
 IF ( ( ( v . lt . ' A ' ) . or . ( v . gt . ' Z ' ) ) . and .
 + ( ( v . lt . ' 0 ' ) . or . ( v . gt . ' 9 ' ) ) ) THEN
 ier = - 1
 END IF
 END DO
 END IF */
} return vcoord ;


signature:
public class GempakUtil { /** * Swap the order of the integers in place .
 * @ param values array of int values
 * @ param startIndex starting index of the array
 * @ param number of bytes
 * @ return input array with values swapped */
public static int [ ] swp4 ( int [ ] values , int startIndex , int number ) { } }

implementation: for ( int i = startIndex ; i < startIndex + number ; i ++ ) { values [ i ] = Integer . reverseBytes ( values [ i ] ) ; } return values ;


signature:
public class GempakUtil { /** * Get a name for the grid packing type
 * @ param pktyp packing type
 * @ return String version of packing type */
public static String getGridPackingName ( int pktyp ) { } }

implementation: String packingType = "UNKNOWN" ; switch ( pktyp ) { case GempakConstants . MDGNON : packingType = "MDGNON" ; break ; case GempakConstants . MDGGRB : packingType = "MDGGRB" ; break ; case GempakConstants . MDGNMC : packingType = "MDGNMC" ; break ; case GempakConstants . MDGDIF : packingType = "MDGDIF" ; break ; case GempakConstants . MDGDEC : packingType = "MDGDEC" ; break ; case GempakConstants . MDGRB2 : packingType = "MDGRB2" ; break ; default : break ; } return packingType ;


signature:
public class GempakUtil { /** * Get a name for the data packing type
 * @ param typrt data type
 * @ return String version of data type */
public static String getDataType ( int typrt ) { } }

implementation: String dataType = "" + typrt ; switch ( typrt ) { case GempakConstants . MDREAL : dataType = "MDREAL" ; break ; case GempakConstants . MDINTG : dataType = "MDINTG" ; break ; case GempakConstants . MDCHAR : dataType = "MDCHAR" ; break ; case GempakConstants . MDRPCK : dataType = "MDRPCK" ; break ; case GempakConstants . MDGRID : dataType = "MDGRID" ; break ; default : break ; } return dataType ;


signature:
public class DataDDS { /** * Read the data stream from the given InputStream . In the C + + version ,
 * this code was in Connect .
 * @ param is the InputStream to read from
 * @ param statusUI the StatusUI object to use , or null
 * @ throws EOFException if EOF is found before the variable is completely
 * deserialized .
 * @ throws IOException thrown on any other InputStream exception .
 * @ throws DataReadException when invalid data is read , or if the user
 * cancels the download .
 * @ throws DAP2Exception if the OPeNDAP server returned an error . */
public void readData ( InputStream is , StatusUI statusUI ) throws IOException , EOFException , DAP2Exception { } }

implementation:
/* ByteArrayOutputStream bout = new ByteArrayOutputStream ( 50 * 1000 ) ;
 copy ( is , bout ) ;
 LogStream . dbg . printf ( " readData size = % d % n " , bout . size ( ) ) ;
 LogStream . dbg . logflush ( ) ;
 ByteArrayInputStream bufferedIS = new ByteArrayInputStream ( bout . toByteArray ( ) ) ; */
// statusUI = new Counter ( ) ;
// Buffer the input stream for better performance
BufferedInputStream bufferedIS = new BufferedInputStream ( is ) ; // Use a DataInputStream for deserialize
DataInputStream dataIS = new DataInputStream ( bufferedIS ) ; for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( "User cancelled" ) ; ClientIO bt = ( ClientIO ) e . nextElement ( ) ; /* if ( true ) {
 BaseType btt = ( BaseType ) bt ;
 System . out . printf ( " Deserializing : % s ( % s ) % n " , btt . getEncodedName ( ) , ( ( BaseType ) bt ) . getTypeName ( ) ) ; */
bt . deserialize ( dataIS , ver , statusUI ) ; } // LogStream . out . printf ( " Deserializing : total size = % s % n " , counter ) ;
// notify GUI of finished download
if ( statusUI != null ) statusUI . finished ( ) ;


signature:
public class DataDDS { /** * debug */
private long copy ( InputStream in , OutputStream out ) throws IOException { } }

implementation: long totalBytesRead = 0 ; byte [ ] buffer = new byte [ 8000 ] ; while ( true ) { int bytesRead = in . read ( buffer ) ; if ( bytesRead == - 1 ) break ; out . write ( buffer , 0 , bytesRead ) ; totalBytesRead += bytesRead ; } return totalBytesRead ;


signature:
public class DataDDS { /** * Print the dataset just read . In the C + + version , this code was in
 * < code > geturl < / code > .
 * @ param pw the < code > PrintWriter < / code > to use . */
public void printVal ( PrintWriter pw ) { } }

implementation: for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printVal ( pw , "" , true ) ; pw . flush ( ) ; } pw . println ( ) ;


signature:
public class DataDDS { /** * Dump the dataset using externalize methods . This should create
 * a multipart Mime document with the binary representation of the
 * DDS that is currently in memory .
 * @ param os the < code > OutputStream < / code > to use .
 * @ param compress < code > true < / code > if we should compress the output .
 * @ param headers < code > true < / code > if we should print HTTP headers .
 * @ throws IOException thrown on any < code > OutputStream < / code > exception . */
public final void externalize ( OutputStream os , boolean compress , boolean headers ) throws IOException { } }

implementation:
// First , print headers
if ( headers ) { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( os , Util . UTF8 ) ) ; pw . println ( "HTTP/1.0 200 OK" ) ; pw . println ( "XDAP: " + ServerVersion . DAP2_PROTOCOL_VERSION ) ; pw . println ( "XDODS-Server: DODS/" + ServerVersion . DAP2_PROTOCOL_VERSION ) ; pw . println ( "Content-type: application/octet-stream" ) ; pw . println ( "Content-Description: dods-data" ) ; if ( compress ) { pw . println ( "Content-Encoding: deflate" ) ; } pw . println ( ) ; pw . flush ( ) ; } // Buffer the output stream for better performance
OutputStream bufferedOS ; if ( compress ) { // need a BufferedOutputStream - 3X performance - LOOK : why ? ?
bufferedOS = new BufferedOutputStream ( new DeflaterOutputStream ( os ) ) ; } else { bufferedOS = new BufferedOutputStream ( os ) ; } // Redefine PrintWriter here , so the DDS is also compressed if necessary
PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( bufferedOS , Util . UTF8 ) ) ; print ( pw ) ; // pw . println ( " Data : " ) ; / / JCARON CHANGED
pw . flush ( ) ; bufferedOS . write ( "\nData:\n" . getBytes ( CDM . utf8Charset ) ) ; // JCARON CHANGED
bufferedOS . flush ( ) ; // Use a DataOutputStream for serialize
DataOutputStream dataOS = new DataOutputStream ( bufferedOS ) ; for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . externalize ( dataOS ) ; } // Note : for DeflaterOutputStream , flush ( ) is not sufficient to flush
// all buffered data
dataOS . close ( ) ;


signature:
public class TagEnum { /** * Find the Tag that matches the code .
 * @ param code find Tag with this code .
 * @ return Tag or null if no match . */
public static TagEnum getTag ( short code ) { } }

implementation: TagEnum te = hash . get ( code ) ; if ( te == null ) te = new TagEnum ( "UNKNOWN" , "UNKNOWN" , code ) ; return te ;


signature:
public class Getopts { /** * method for class testing .
 * Invocation :
 * < PRE >
 * java Getopts " option set " arg0 arg1 . . . argn
 * < / PRE >
 * @ param args arguments passed */
public static void main ( String args [ ] ) { } }

implementation: int i ; String args1 [ ] = new String [ args . length - 1 ] ; System . arraycopy ( args , 1 , args1 , 0 , args . length - 1 ) ; for ( i = 0 ; i < args . length ; i ++ ) { System . out . println ( "args[" + i + "] : " + args [ i ] ) ; } try { Getopts opts = new Getopts ( args [ 0 ] , args1 ) ; Enumeration names = opts . swList ( ) ; i = 0 ; while ( names . hasMoreElements ( ) ) { OptSwitch cs = opts . getSwitch ( ( Character ) names . nextElement ( ) ) ; System . out . println ( "args[" + i + "] : " + ( char ) cs . sw + " " + cs . type + " " + cs . set + " " + cs . val ) ; i ++ ; } String argp [ ] = opts . argList ( ) ; for ( i = 0 ; i < argp . length ; i ++ ) { System . out . println ( "argv[" + i + "] : " + argp [ i ] ) ; } } catch ( InvalidSwitch e ) { System . out . print ( e ) ; }


signature:
public class ImageDatasetFactory { /** * Open from a URL :
 * adde : use AddeImage . factory ( )
 * http : use javax . imageio . ImageIO . read ( )
 * file : javax . imageio . ImageIO . read ( )
 * @ param location open from this location
 * @ return a BufferedImage
 * @ throws java . io . IOException on read error */
public BufferedImage open ( String location ) throws java . io . IOException { } }

implementation:
log = new StringBuffer ( ) ; if ( location . startsWith ( "http:" ) ) { try { URL url = new URL ( location ) ; currentFile = null ; return javax . imageio . ImageIO . read ( url ) ; } catch ( MalformedURLException e ) { log . append ( e . getMessage ( ) ) ; // e . printStackTrace ( ) ;
return null ; } catch ( IOException e ) { log . append ( e . getMessage ( ) ) ; // e . printStackTrace ( ) ;
return null ; } } else { if ( location . startsWith ( "file:)" ) ) location = location . substring ( 5 ) ; try { File f = new File ( location ) ; if ( ! f . exists ( ) ) { return null ; } currentFile = f ; currentDir = null ; return javax . imageio . ImageIO . read ( f ) ; } catch ( MalformedURLException e ) { log . append ( e . getMessage ( ) ) ; // e . printStackTrace ( ) ;
return null ; } catch ( IOException e ) { log . append ( e . getMessage ( ) ) ; // e . printStackTrace ( ) ;
return null ; } }


signature:
public class ImageDatasetFactory { /** * This assumes you have opened a file . looks in the parent directory .
 * @ param forward if true got to next , else previous
 * @ return next file in the directory , as a BufferedImage . */
public BufferedImage getNextImage ( boolean forward ) { } }

implementation:
if ( grid != null ) { if ( forward ) { this . time ++ ; if ( this . time >= this . ntimes ) this . time = 0 ; } else { this . time -- ; if ( this . time < 0 ) this . time = this . ntimes - 1 ; } Array data ; try { data = grid . readDataSlice ( this . time , 0 , - 1 , - 1 ) ; return ImageArrayAdapter . makeGrayscaleImage ( data , grid ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return null ; } } if ( currentFile == null ) return null ; if ( currentDir == null ) { currentDirFileNo = 0 ; currentDir = currentFile . getParentFile ( ) ; currentDirFileList = new ArrayList < > ( ) ; addToList ( currentDir , currentDirFileList ) ; // Arrays . asList ( currentDir . listFiles ( ) ) ;
// Collections . sort ( currentDirFileList ) ;
for ( int i = 0 ; i < currentDirFileList . size ( ) ; i ++ ) { File file = currentDirFileList . get ( i ) ; if ( file . equals ( currentFile ) ) currentDirFileNo = i ; } } if ( forward ) { currentDirFileNo ++ ; if ( currentDirFileNo >= currentDirFileList . size ( ) ) currentDirFileNo = 0 ; } else { currentDirFileNo -- ; if ( currentDirFileNo < 0 ) currentDirFileNo = currentDirFileList . size ( ) - 1 ; } File nextFile = currentDirFileList . get ( currentDirFileNo ) ; try { System . out . println ( "Open image " + nextFile ) ; return javax . imageio . ImageIO . read ( nextFile ) ; } catch ( IOException e ) { System . out . println ( "Failed to open image " + nextFile ) ; return getNextImage ( forward ) ; }


signature:
public class LibTypeFcns { /** * Conmpute the size , in databuffer ,
 * of the daptype wrt to a serialization ;
 * 0 if undefined .
 * @ param type The type of interest
 * @ return the size , in databuffer */
static public int size ( DapType type ) { } }

implementation:
switch ( type . getTypeSort ( ) ) { case Char : // remember serial size is 1 , not 2.
case UInt8 : case Int8 : return 1 ; case Int16 : case UInt16 : return 2 ; case Int32 : case UInt32 : case Float32 : return 4 ; case Int64 : case UInt64 : case Float64 : return 8 ; case Enum : return size ( ( ( DapEnumeration ) type ) . getBaseType ( ) ) ; default : break ; } return 0 ;


signature:
public class LibTypeFcns { /** * Convert an array of one type of values to another type
 * @ param dsttype target type
 * @ param srctype source type
 * @ param src array of values to convert
 * @ return resulting array of converted values as an object */
static public Object convertVector ( DapType dsttype , DapType srctype , Object src ) throws DapException { } }

implementation:
int i ; TypeSort srcatomtype = srctype . getAtomicType ( ) ; TypeSort dstatomtype = dsttype . getAtomicType ( ) ; if ( srcatomtype == dstatomtype ) return src ; if ( srcatomtype . isIntegerType ( ) && TypeSort . getSignedVersion ( srcatomtype ) == TypeSort . getSignedVersion ( dstatomtype ) ) return src ; Object result = null ; boolean ok = true ; int len = 0 ; char [ ] csrc ; byte [ ] bsrc ; short [ ] shsrc ; int [ ] isrc ; long [ ] lsrc ; float [ ] fsrc ; double [ ] dsrc ; char [ ] cresult ; byte [ ] bresult ; short [ ] shresult ; int [ ] iresult ; long [ ] lresult ; float [ ] fresult ; double [ ] dresult ; BigInteger bi ; boolean srcunsigned = srcatomtype . isUnsigned ( ) ; boolean dstunsigned = dstatomtype . isUnsigned ( ) ; // Do a double switch src X dst ( ugh ! )
switch ( srcatomtype ) { case Char : // Char - >
csrc = ( char [ ] ) src ; len = csrc . length ; switch ( dstatomtype ) { case Int8 : // char - > int8
case UInt8 : // char - > uint8
return src ; case Int16 : // char - > Int16
case UInt16 : // char - > UInt16;
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Int32 : // char - > Int32
case UInt32 : // char - > UInt32;
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Int64 : // char - > Int64
case UInt64 : // char - > UInt64;
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Float32 : result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( ( int ) csrc [ i ] ) & 0xFF ) ; } break ; default : ok = false ; break ; } break ; case Int8 : // Int8 - >
bsrc = ( byte [ ] ) src ; len = bsrc . length ; switch ( dstatomtype ) { case Char : // int8 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) bsrc [ i ] ) & 0xFF ) ; } break ; case Int16 : // int8 - > Int16
case UInt16 : // int8 - > UInt16;
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) bsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] &= ( short ) 0xFF ; } } break ; case Int32 : // int8 - > Int32
case UInt32 : // int8 - > UInt32;
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) bsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] &= 0xFF ; } } break ; case Int64 : // int8 - > Int64
case UInt64 : // int8 - > UInt64;
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) bsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFL ; } } break ; case Float32 : // int8 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) bsrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) bsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt8 : // UInt8 - >
bsrc = ( byte [ ] ) src ; len = bsrc . length ; switch ( dstatomtype ) { case Char : // Byte - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) bsrc [ i ] ) & 0xFF ) ; } break ; case Int16 : // Byte - > Int16
case UInt16 : // Byte - > UInt16;
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) ( ( ( int ) bsrc [ i ] ) & 0xFF ) ; } break ; case Int32 : // Byte - > Int32
case UInt32 : // Byte - > UInt32;
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( ( int ) bsrc [ i ] ) & 0xFF ; } break ; case Int64 : // Byte - > Int64
case UInt64 : // Byte - > UInt64;
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( ( long ) bsrc [ i ] ) & 0xFFL ; } break ; case Float32 : // Byte - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( int ) bsrc [ i ] & 0xFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( int ) bsrc [ i ] & 0xFF ) ; } break ; default : ok = false ; break ; } break ; case Int16 : // Int16 - >
shsrc = ( short [ ] ) src ; len = shsrc . length ; switch ( dstatomtype ) { case Char : // int16 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) shsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : // int16 - > Int8
case UInt8 : // int16 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) shsrc [ i ] ; } break ; case Int32 : // int16 - > Int32
case UInt32 : // int16 - > UInt32;
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) shsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] &= 0xFFFF ; } } break ; case Int64 : // int16 - > Int64
case UInt64 : // int16 - > UInt64;
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) shsrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFFFL ; } } break ; case Float32 : // int16 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) shsrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) shsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt16 : // UInt16 - >
shsrc = ( short [ ] ) src ; len = shsrc . length ; switch ( dstatomtype ) { case Char : // UInt16 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) shsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : // UInt16 - > Int8
case UInt8 : // UInt16 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) shsrc [ i ] ; } break ; case Int32 : // UInt16 - > Int32
case UInt32 : // UInt16 - > UInt32;
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( ( int ) shsrc [ i ] ) & 0xFFFF ; } break ; case Int64 : // UInt16 - > Int64
case UInt64 : // UInt16 - > UInt64;
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( ( long ) shsrc [ i ] ) & 0xFFFFL ; } break ; case Float32 : // UInt16 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( int ) shsrc [ i ] & 0xFFFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( int ) shsrc [ i ] & 0xFFFF ) ; } break ; default : ok = false ; break ; } break ; case Int32 : // Int32 - >
isrc = ( int [ ] ) src ; len = isrc . length ; switch ( dstatomtype ) { case Char : // int32 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( isrc [ i ] & 0xFF ) ; } break ; case Int8 : // Int32 - > Int8
case UInt8 : // Int32 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) isrc [ i ] ; } break ; case Int16 : // Int32 - > Int16
case UInt16 : // Int32 - > UInt16;
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) isrc [ i ] ; } break ; case Int64 : // Int32 - > Int64
case UInt64 : // Int32 - > UInt64
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) isrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFFFL ; } } break ; case Float32 : // int32 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) isrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) isrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt32 : // UInt32 - >
isrc = ( int [ ] ) src ; len = isrc . length ; switch ( dstatomtype ) { case Char : // UInt32 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) isrc [ i ] ) & 0xFF ) ; } break ; case Int8 : // Int32 - > Int8
case UInt8 : // UInt32 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) isrc [ i ] ; } break ; case Int16 : // Int32 - > Int16
case UInt16 : // UInt32 - > UInt16
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) isrc [ i ] ; } break ; case Int64 : // Int32 - > Int64
case UInt64 : // UInt32 - > UInt64;
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] = ( long ) isrc [ i ] ; } if ( dstunsigned ) { for ( i = 0 ; i < len ; i ++ ) { lresult [ i ] &= 0xFFFFFFFFL ; } } break ; case Float32 : // UInt32 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) ( ( int ) isrc [ i ] & 0xFFFF ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) ( ( int ) isrc [ i ] & 0xFFFF ) ; } break ; default : ok = false ; break ; } break ; case Int64 : // Int64 - >
lsrc = ( long [ ] ) src ; len = lsrc . length ; switch ( dstatomtype ) { case Char : // Int64 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( lsrc [ i ] & 0xFF ) ; } break ; case Int8 : // Int64 - > Int8
case UInt8 : // Int64 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) lsrc [ i ] ; } break ; case Int16 : // Int64 - > Int16
case UInt16 : // Int64 - > UInt16;
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) lsrc [ i ] ; } break ; case Int32 : // Int64 - > Int32
case UInt32 : // Int64 - > UInt32;
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) lsrc [ i ] ; } break ; case Float32 : // Int64 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) lsrc [ i ] ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) lsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case UInt64 : // UInt64 - >
lsrc = ( long [ ] ) src ; len = lsrc . length ; switch ( dstatomtype ) { case Char : // UInt64 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( lsrc [ i ] & 0xFFL ) ; } break ; case Int8 : // Int64 - > Int8
case UInt8 : // UInt64 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) lsrc [ i ] ; } break ; case Int16 : // Int64 - > Int16
case UInt16 : // UInt64 - > UInt16
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) lsrc [ i ] ; } break ; case Int32 : // Int64 - > Int32
case UInt32 : // UInt64 - > UInt32
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) lsrc [ i ] ; } break ; case Float32 : // UInt64 - > float
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bi = BigInteger . valueOf ( lsrc [ i ] ) ; bi = bi . and ( DapUtil . BIG_UMASK64 ) ; fresult [ i ] = bi . floatValue ( ) ; } break ; case Float64 : result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bi = BigInteger . valueOf ( lsrc [ i ] ) ; bi = bi . and ( DapUtil . BIG_UMASK64 ) ; dresult [ i ] = bi . doubleValue ( ) ; } break ; default : ok = false ; break ; } break ; case Float32 : // Float32 - >
fsrc = ( float [ ] ) src ; len = fsrc . length ; switch ( dstatomtype ) { case Char : // Float32 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) fsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : // Float32 - > Int8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) fsrc [ i ] ; } break ; case UInt8 : // Float32 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } bresult [ i ] = ( byte ) fsrc [ i ] ; } break ; case Int16 : // Float32 - > Int16
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) fsrc [ i ] ; } break ; case UInt16 : // Float32 - > UInt16
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } shresult [ i ] = ( short ) fsrc [ i ] ; } break ; case Int32 : // Float32 - > Int32
case UInt32 : // Float32 - > UInt32
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } iresult [ i ] = ( int ) fsrc [ i ] ; } break ; case Int64 : // Float32 - > Int64
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { BigDecimal bd = new BigDecimal ( fsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case UInt64 : // Float32 - > UInt64
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( fsrc [ i ] < 0 ) { ok = false ; break ; } // not convertible
BigDecimal bd = new BigDecimal ( fsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case Float64 : // Float32 - > Float64
result = ( dresult = new double [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { dresult [ i ] = ( double ) fsrc [ i ] ; } break ; default : ok = false ; break ; } break ; case Float64 : // Float64 - >
dsrc = ( double [ ] ) src ; len = dsrc . length ; switch ( dstatomtype ) { case Char : // Float64 - > char
result = ( cresult = new char [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { cresult [ i ] = ( char ) ( ( ( int ) dsrc [ i ] ) & 0xFF ) ; } break ; case Int8 : // Float64 - > Int8
case UInt8 : // Float64 - > UInt8
result = ( bresult = new byte [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { bresult [ i ] = ( byte ) dsrc [ i ] ; } break ; case Int16 : // Float64 - > Int16
case UInt16 : // Float64 - > UInt16
result = ( shresult = new short [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { shresult [ i ] = ( short ) dsrc [ i ] ; } break ; case Int32 : // Float64 - > Int32
case UInt32 : // Float64 - > UInt32
result = ( iresult = new int [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { iresult [ i ] = ( int ) dsrc [ i ] ; } break ; case Int64 : // Float64 - > Int64
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { BigDecimal bd = new BigDecimal ( dsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case UInt64 : // Float64 - > UInt64
result = ( lresult = new long [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { if ( dsrc [ i ] < 0 ) { ok = false ; break ; } // not convertible
BigDecimal bd = new BigDecimal ( dsrc [ i ] ) ; lresult [ i ] = bd . toBigInteger ( ) . longValue ( ) ; } break ; case Float32 : // Float32 - > Float64
result = ( fresult = new float [ len ] ) ; for ( i = 0 ; i < len ; i ++ ) { fresult [ i ] = ( float ) dsrc [ i ] ; } break ; default : ok = false ; break ; } break ; default : throw new DapException ( String . format ( "Illegal Conversion: %s->%s" , srctype , dsttype ) ) ; } if ( ! ok ) throw new DapException ( String . format ( "Illegal Conversion: %s->%s" , srctype , dsttype ) ) ; return result ;


signature:
public class FixedYearVariableMonthChronology { /** * Calculates the sum of the values in the given array .
 * @ throws NullPointerException if arr is null
 * @ throws IllegalArgumentException if arr is empty or contains
 * zero or negative values . */
private static int sumArray ( int [ ] arr ) { } }

implementation: if ( arr == null ) throw new NullPointerException ( "null array" ) ; if ( arr . length == 0 ) throw new IllegalArgumentException ( "Zero-length array" ) ; int sum = 0 ; for ( int i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] <= 0 ) { throw new IllegalArgumentException ( "All array values must be > 0" ) ; } sum += arr [ i ] ; } return sum ;


signature:
public class SpatialGrid { /** * Set the grid scale .
 * @ param bbox bounding box : we are only interested in points inside of this
 * @ param width : divide the bounding box into cells of this width .
 * @ param height : divide the bounding box into cells of this height .
 * maximum number of grid cells is nx x ny */
public void setGrid ( Rectangle2D bbox , double width , double height ) { } }

implementation:
offsetX = bbox . getX ( ) ; offsetY = bbox . getY ( ) ; // number of grid cells
countX = Math . min ( nx , ( int ) ( bbox . getWidth ( ) / ( scaleOverlap * width ) ) ) ; countY = Math . min ( ny , ( int ) ( bbox . getHeight ( ) / ( scaleOverlap * height ) ) ) ; gridWidth = bbox . getWidth ( ) / countX ; gridHeight = bbox . getHeight ( ) / countY ; if ( debug ) System . out . println ( "SpatialGrid size " + gridWidth + " " + gridHeight + " = " + countX + " by " + countY + " scaleOverlap= " + scaleOverlap ) ;


signature:
public class SpatialGrid { /** * Set how much the data may overlap .
 * @ param overlap : percent overlap */
public void setOverlap ( int overlap ) { } }

implementation:
// overlap limited to [ 0 , 50 % ]
double dover = Math . max ( 0.0 , Math . min ( .01 * overlap , .50 ) ) ; scaleOverlap = 1.0 - dover ;


signature:
public class SpatialGrid { /** * clear all the grid cells */
public void clear ( ) { } }

implementation: for ( int y = 0 ; y < countY ; y ++ ) for ( int x = 0 ; x < countX ; x ++ ) gridArray [ y ] [ x ] . used = false ;


signature:
public class SpatialGrid { /** * Check if the given rect intersects an already drawn one .
 * If not , set the corresponding cell as marked , store object , return true ,
 * meaning " ok to draw " .
 * @ param rect the bounding box of the thing we want to draw
 * @ param o store this object
 * @ return true if inside the bounding box and no intersection */
public boolean markIfClear ( Rectangle2D rect , Object o ) { } }

implementation:
double centerX = rect . getX ( ) + rect . getWidth ( ) / 2 ; double centerY = rect . getY ( ) + rect . getHeight ( ) / 2 ; int indexX = ( int ) ( ( centerX - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( centerY - offsetY ) / gridHeight ) ; if ( debugMark ) System . out . println ( "markIfClear " + rect + " " + indexX + " " + indexY ) ; if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) // outside box
return false ; GridCell gwant = gridArray [ indexY ] [ indexX ] ; if ( gwant . used ) // already taken
return false ; if ( null != findIntersection ( rect ) ) return false ; // its ok to use
gwant . used = true ; gwant . objectBB = rect ; gwant . o = o ; return true ;


signature:
public class SpatialGrid { /** * Check if the given rect intersects an already drawn object
 * @ param rect the bounding box of the thing we want to draw
 * @ return object that intersects , or null if no intersection */
public Object findIntersection ( Rectangle2D rect ) { } }

implementation:
double centerX = rect . getX ( ) + rect . getWidth ( ) / 2 ; double centerY = rect . getY ( ) + rect . getHeight ( ) / 2 ; int indexX = ( int ) ( ( centerX - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( centerY - offsetY ) / gridHeight ) ; // outside box
if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) return null ; // check the surrounding points
for ( int y = Math . max ( 0 , indexY - 1 ) ; y <= Math . min ( countY - 1 , indexY + 1 ) ; y ++ ) { for ( int x = Math . max ( 0 , indexX - 1 ) ; x <= Math . min ( countX - 1 , indexX + 1 ) ; x ++ ) { GridCell gtest = gridArray [ y ] [ x ] ; if ( ! gtest . used ) continue ; if ( intersectsOverlap ( rect , gtest . objectBB ) ) // hits an adjacent rectangle
return gtest . o ; } } return null ;


signature:
public class SpatialGrid { /** * Check if the given point is contained in already drawn object
 * @ param p the point to check
 * @ return object that intersects , or null if no intersection */
public Object findIntersection ( Point2D p ) { } }

implementation:
int indexX = ( int ) ( ( p . getX ( ) - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( p . getY ( ) - offsetY ) / gridHeight ) ; // outside box
if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) return null ; // check the surrounding points
for ( int y = Math . max ( 0 , indexY - 1 ) ; y <= Math . min ( countY - 1 , indexY + 1 ) ; y ++ ) { for ( int x = Math . max ( 0 , indexX - 1 ) ; x <= Math . min ( countX - 1 , indexX + 1 ) ; x ++ ) { GridCell gtest = gridArray [ y ] [ x ] ; if ( ! gtest . used ) continue ; if ( gtest . objectBB . contains ( p . getX ( ) , p . getY ( ) ) ) return gtest . o ; } } return null ;


signature:
public class SpatialGrid { /** * Find the closest marked cell to the given point
 * @ param pt find the closest marked cell to this point
 * @ return the object associated with the closest cell , or null if none */
public Object findClosest ( Point2D pt ) { } }

implementation:
Object o = null ; int indexX = ( int ) ( ( pt . getX ( ) - offsetX ) / gridWidth ) ; int indexY = ( int ) ( ( pt . getY ( ) - offsetY ) / gridHeight ) ; if ( debugClosest ) System . out . println ( "findClosest " + pt + " " + indexX + " " + indexY ) ; if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) // outside box
return null ; GridCell gwant = gridArray [ indexY ] [ indexX ] ; if ( gwant . used ) // that was easy
return gwant . o ; // check the surrounding points along perimeter of increasing diameter
for ( int p = 1 ; p < Math . max ( countX - 1 , countY - 1 ) ; p ++ ) if ( null != ( o = findClosestAlongPerimeter ( pt , indexX , indexY , p ) ) ) return o ; return null ; // nothing found


signature:
public class SpatialGrid { /** * with center cell [ x , y ] and side of length 2 * perimeter + 1 */
private Object findClosestAlongPerimeter ( Point2D pt , int centerX , int centerY , int perimeter ) { } }

implementation:
Object closestO = null ; double closestD = MAX_DOUBLE ; // top and bottom row
for ( int y = centerY - perimeter ; y <= centerY + perimeter ; y += 2 * perimeter ) for ( int x = centerX - perimeter ; x <= centerX + perimeter ; x ++ ) { double distance = distanceSq ( pt , x , y ) ; if ( distance < closestD ) { closestO = gridArray [ y ] [ x ] . o ; closestD = distance ; if ( debugClosest ) System . out . println ( "   closest " + gridArray [ y ] [ x ] ) ; } } // middle rows
for ( int y = centerY - perimeter + 1 ; y <= centerY + perimeter - 1 ; y ++ ) for ( int x = centerX - perimeter ; x <= centerX + perimeter ; x += 2 * perimeter ) { double distance = distanceSq ( pt , x , y ) ; if ( distance < closestD ) { closestO = gridArray [ y ] [ x ] . o ; closestD = distance ; if ( debugClosest ) System . out . println ( "   closest " + gridArray [ y ] [ x ] ) ; } } return closestO ;


signature:
public class SpatialGrid { /** * if out of bbox or cell not marked , return MAX _ DOUBLE */
private double distanceSq ( Point2D pt , int indexX , int indexY ) { } }

implementation:
if ( ( indexX < 0 ) || ( indexX >= countX ) || ( indexY < 0 ) || ( indexY >= countY ) ) // outside bounding box
return MAX_DOUBLE ; GridCell gtest = gridArray [ indexY ] [ indexX ] ; if ( ! gtest . used ) // nothing in this cell
return MAX_DOUBLE ; // get distance from center of cell
Rectangle2D rect = gtest . objectBB ; double dx = rect . getX ( ) + rect . getWidth ( ) / 2 - pt . getX ( ) ; double dy = rect . getY ( ) + rect . getHeight ( ) / 2 - pt . getY ( ) ; return ( dx * dx + dy * dy ) ;


signature:
public class MultiTrajectoryObsDataset { /** * Setup needed for all MultiTrajectoryObsDatatypes .
 * Units of time varible must be udunits time units .
 * Units of latitude variable must be convertible to " degrees _ north " by udunits .
 * Units of longitude variable must be convertible to " degrees _ east " by udunits .
 * Units of altitude variable must be convertible to " meters " by udunits .
 * @ throws IllegalArgumentException if units of time , latitude , longitude , or altitude variables are not as required . */
public void setTrajectoryInfo ( Dimension trajDim , Variable trajVar , Dimension timeDim , Variable timeVar , Variable latVar , Variable lonVar , Variable elevVar ) throws IOException { } }

implementation:
this . trajDim = trajDim ; this . trajVar = trajVar ; this . timeDim = timeDim ; this . timeVar = timeVar ; this . latVar = latVar ; this . lonVar = lonVar ; this . elevVar = elevVar ; trajectoryNumPoint = this . timeDim . getLength ( ) ; timeVarUnitsString = this . timeVar . findAttribute ( "units" ) . getStringValue ( ) ; // Check that time , lat , lon , elev units are acceptable .
if ( DateUnit . getStandardDate ( timeVarUnitsString ) == null ) throw new IllegalArgumentException ( "Units of time variable <" + timeVarUnitsString + "> not a date unit." ) ; String latVarUnitsString = this . latVar . findAttribute ( "units" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( latVarUnitsString , "degrees_north" ) ) throw new IllegalArgumentException ( "Units of lat var <" + latVarUnitsString + "> not compatible with \"degrees_north\"." ) ; String lonVarUnitsString = this . lonVar . findAttribute ( "units" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( lonVarUnitsString , "degrees_east" ) ) throw new IllegalArgumentException ( "Units of lon var <" + lonVarUnitsString + "> not compatible with \"degrees_east\"." ) ; String elevVarUnitsString = this . elevVar . findAttribute ( "units" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( elevVarUnitsString , "meters" ) ) throw new IllegalArgumentException ( "Units of elev var <" + elevVarUnitsString + "> not compatible with \"meters\"." ) ; try { elevVarUnitsConversionFactor = getMetersConversionFactor ( elevVarUnitsString ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Exception on getMetersConversionFactor() for the units of elev var <" + elevVarUnitsString + ">." ) ; } if ( this . netcdfDataset . hasUnlimitedDimension ( ) && this . netcdfDataset . getUnlimitedDimension ( ) . equals ( timeDim ) ) { this . netcdfDataset . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; this . recordVar = ( Structure ) this . netcdfDataset . getRootGroup ( ) . findVariable ( "record" ) ; } else { this . recordVar = new StructurePseudo ( this . netcdfDataset , null , "record" , timeDim ) ; } // @ todo HACK , HACK , HACK - remove once addRecordStructure ( ) deals with ncd attribute changes .
Variable latVarInRecVar = this . recordVar . findVariable ( this . latVar . getFullNameEscaped ( ) ) ; Attribute latVarUnitsAtt = latVarInRecVar . findAttribute ( "units" ) ; if ( latVarUnitsAtt != null && ! latVarUnitsString . equals ( latVarUnitsAtt . getStringValue ( ) ) ) latVarInRecVar . addAttribute ( new Attribute ( "units" , latVarUnitsString ) ) ; Variable lonVarInRecVar = this . recordVar . findVariable ( this . lonVar . getFullNameEscaped ( ) ) ; Attribute lonVarUnitsAtt = lonVarInRecVar . findAttribute ( "units" ) ; if ( lonVarUnitsAtt != null && ! lonVarUnitsString . equals ( lonVarUnitsAtt . getStringValue ( ) ) ) lonVarInRecVar . addAttribute ( new Attribute ( "units" , lonVarUnitsString ) ) ; Variable elevVarInRecVar = this . recordVar . findVariable ( this . elevVar . getFullNameEscaped ( ) ) ; Attribute elevVarUnitsAtt = elevVarInRecVar . findAttribute ( "units" ) ; if ( elevVarUnitsAtt != null && ! elevVarUnitsString . equals ( elevVarUnitsAtt . getStringValue ( ) ) ) elevVarInRecVar . addAttribute ( new Attribute ( "units" , elevVarUnitsString ) ) ; trajectoryVarsMap = new HashMap ( ) ; for ( Iterator it = this . netcdfDataset . getRootGroup ( ) . getVariables ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Variable curVar = ( Variable ) it . next ( ) ; if ( curVar . getRank ( ) >= 2 && // ! curVar . equals ( this . trajVar ) & & / / These two are both one dimensional arrays
// ! curVar . equals ( this . timeVar ) & & / /
! curVar . equals ( this . latVar ) && ! curVar . equals ( this . lonVar ) && ! curVar . equals ( this . elevVar ) && ( this . recordVar == null ? true : ! curVar . equals ( this . recordVar ) ) ) { MyTypedDataVariable typedVar = new MyTypedDataVariable ( new VariableDS ( null , curVar , true ) ) ; dataVariables . add ( typedVar ) ; trajectoryVarsMap . put ( typedVar . getShortName ( ) , typedVar ) ; } } Range startPointRange = null ; Range endPointRange = null ; try { startPointRange = new Range ( 0 , 0 ) ; endPointRange = new Range ( trajectoryNumPoint - 1 , trajectoryNumPoint - 1 ) ; } catch ( InvalidRangeException e ) { IOException ioe = new IOException ( "Start or end point range invalid: " + e . getMessage ( ) ) ; ioe . initCause ( e ) ; throw ( ioe ) ; } List section0 = new ArrayList ( 1 ) ; List section1 = new ArrayList ( 1 ) ; section0 . add ( startPointRange ) ; section1 . add ( endPointRange ) ; Array startTimeArray ; Array endTimeArray ; try { startTimeArray = this . timeVar . read ( section0 ) ; endTimeArray = this . timeVar . read ( section1 ) ; } catch ( InvalidRangeException e ) { IOException ioe = new IOException ( "Invalid range during read of start or end point: " + e . getMessage ( ) ) ; ioe . initCause ( e ) ; throw ( ioe ) ; } String startTimeString ; String endTimeString ; if ( this . timeVar . getDataType ( ) . equals ( DataType . DOUBLE ) ) { startTimeString = startTimeArray . getDouble ( startTimeArray . getIndex ( ) ) + " " + timeVarUnitsString ; endTimeString = endTimeArray . getDouble ( endTimeArray . getIndex ( ) ) + " " + timeVarUnitsString ; } else if ( this . timeVar . getDataType ( ) . equals ( DataType . FLOAT ) ) { startTimeString = startTimeArray . getFloat ( startTimeArray . getIndex ( ) ) + " " + timeVarUnitsString ; endTimeString = endTimeArray . getFloat ( endTimeArray . getIndex ( ) ) + " " + timeVarUnitsString ; } else if ( this . timeVar . getDataType ( ) . equals ( DataType . INT ) ) { startTimeString = startTimeArray . getInt ( startTimeArray . getIndex ( ) ) + " " + timeVarUnitsString ; endTimeString = endTimeArray . getInt ( endTimeArray . getIndex ( ) ) + " " + timeVarUnitsString ; } else { String tmpMsg = "Time var <" + this . timeVar . getFullName ( ) + "> is not a double, float, or integer <" + timeVar . getDataType ( ) . toString ( ) + ">." ; // log . error ( tmpMsg ) ;
throw new IllegalArgumentException ( tmpMsg ) ; } startDate = DateUnit . getStandardDate ( startTimeString ) ; endDate = DateUnit . getStandardDate ( endTimeString ) ; trajectoryIds = new ArrayList ( ) ; trajectories = new ArrayList ( ) ; trajectoriesMap = new HashMap ( ) ; Array trajArray = this . trajVar . read ( ) ; Index index = trajArray . getIndex ( ) ; for ( int i = 0 ; i < trajArray . getSize ( ) ; i ++ ) { String curTrajId ; if ( this . trajVar . getDataType ( ) . equals ( DataType . STRING ) ) { curTrajId = ( String ) trajArray . getObject ( index . set ( i ) ) ; } else if ( this . trajVar . getDataType ( ) . equals ( DataType . DOUBLE ) ) { curTrajId = String . valueOf ( trajArray . getDouble ( index . set ( i ) ) ) ; } else if ( this . trajVar . getDataType ( ) . equals ( DataType . FLOAT ) ) { curTrajId = String . valueOf ( trajArray . getFloat ( index . set ( i ) ) ) ; } else if ( this . trajVar . getDataType ( ) . equals ( DataType . INT ) ) { curTrajId = String . valueOf ( trajArray . getInt ( index . set ( i ) ) ) ; } else { String tmpMsg = "Trajectory var <" + this . trajVar . getFullName ( ) + "> is not a string, double, float, or integer <" + this . trajVar . getDataType ( ) . toString ( ) + ">." ; // log . error ( tmpMsg ) ;
throw new IllegalStateException ( tmpMsg ) ; } MultiTrajectory curTraj = new MultiTrajectory ( curTrajId , i , trajectoryNumPoint , startDate , endDate , this . trajVar , this . timeVar , timeVarUnitsString , this . latVar , this . lonVar , this . elevVar , dataVariables , trajectoryVarsMap ) ; trajectoryIds . add ( curTrajId ) ; trajectories . add ( curTraj ) ; trajectoriesMap . put ( curTrajId , curTraj ) ; }


signature:
public class CdmRemote { /** * Create the canonical form of the URL .
 * If the urlName starts with " http : " , change it to start with " cdmremote : " , otherwise
 * leave it alone .
 * @ param urlName the url string
 * @ return canonical form */
public static String canonicalURL ( String urlName ) { } }

implementation: if ( urlName . startsWith ( "http:" ) ) return SCHEME + urlName . substring ( 5 ) ; return urlName ;


signature:
public class CdmRemote { /** * session may be null , if so , will be closed on method . close ( ) */
public static InputStream sendQuery ( HTTPSession session , String remoteURI , String query ) throws IOException { } }

implementation:
long start = System . currentTimeMillis ( ) ; StringBuilder sbuff = new StringBuilder ( remoteURI ) ; sbuff . append ( "?" ) ; sbuff . append ( query ) ; if ( showRequest ) System . out . printf ( " CdmRemote sendQuery= %s" , sbuff ) ; HTTPMethod method = HTTPFactory . Get ( session , sbuff . toString ( ) ) ; try { int statusCode = method . execute ( ) ; if ( statusCode == 404 ) { throw new FileNotFoundException ( method . getPath ( ) + " " + method . getStatusLine ( ) ) ; } else if ( statusCode >= 400 ) { throw new IOException ( method . getPath ( ) + " " + method . getStatusLine ( ) ) ; } InputStream stream = method . getResponseBodyAsStream ( ) ; if ( showRequest ) System . out . printf ( " took %d msecs %n" , System . currentTimeMillis ( ) - start ) ; // Leave the stream open . We must also leave the HTTPMethod open because the two are linked :
// calling close ( ) on one object causes the other object to be closed as well .
return stream ; } catch ( IOException e ) { // Close the HTTPMethod if there was an exception ; otherwise leave it open .
method . close ( ) ; throw e ; }


signature:
public class OceanSigma { /** * Get the 3D vertical coordinate array for this time step .
 * @ param timeIndex the time index . Ignored if ! isTimeDependent ( ) .
 * @ return vertical coordinate array
 * @ throws IOException problem reading data
 * @ throws InvalidRangeException _ more _ */
public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { } }

implementation: Array eta = readArray ( etaVar , timeIndex ) ; Array sigma = readArray ( sVar , timeIndex ) ; Array depth = readArray ( depthVar , timeIndex ) ; int nz = ( int ) sigma . getSize ( ) ; Index sIndex = sigma . getIndex ( ) ; int [ ] shape2D = eta . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index etaIndex = eta . getIndex ( ) ; Index depthIndex = depth . getIndex ( ) ; ArrayDouble . D3 height = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int z = 0 ; z < nz ; z ++ ) { double sigmaVal = sigma . getDouble ( sIndex . set ( z ) ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { double etaVal = eta . getDouble ( etaIndex . set ( y , x ) ) ; double depthVal = depth . getDouble ( depthIndex . set ( y , x ) ) ; height . set ( z , y , x , etaVal + sigmaVal * ( depthVal + etaVal ) ) ; } } } return height ;


signature:
public class OceanSigma { /** * Get the 1D vertical coordinate array for this time step and point
 * @ param timeIndex the time index . Ignored if ! isTimeDependent ( ) .
 * @ param xIndex the x index
 * @ param yIndex the y index
 * @ return vertical coordinate array
 * @ throws java . io . IOException problem reading data
 * @ throws ucar . ma2 . InvalidRangeException _ more _ */
public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { } }

implementation: Array eta = readArray ( etaVar , timeIndex ) ; Array sigma = readArray ( sVar , timeIndex ) ; Array depth = readArray ( depthVar , timeIndex ) ; int nz = ( int ) sigma . getSize ( ) ; Index sIndex = sigma . getIndex ( ) ; Index etaIndex = eta . getIndex ( ) ; Index depthIndex = depth . getIndex ( ) ; ArrayDouble . D1 height = new ArrayDouble . D1 ( nz ) ; for ( int z = 0 ; z < nz ; z ++ ) { double sigmaVal = sigma . getDouble ( sIndex . set ( z ) ) ; double etaVal = eta . getDouble ( etaIndex . set ( yIndex , xIndex ) ) ; double depthVal = depth . getDouble ( depthIndex . set ( yIndex , xIndex ) ) ; height . set ( z , etaVal + sigmaVal * ( depthVal + etaVal ) ) ; } return height ;


signature:
public class BaseUnit { /** * Factory method for creating a new BaseUnit or obtaining a
 * previously - created one .
 * @ param id
 * The identifier for the base unit . < code >
 * id . getSymbol ( ) < / code >
 * shall not return < code >
 * null < / code > .
 * @ param baseQuantity
 * The base quantity of the base unit .
 * @ throws NameException
 * < code > id . getSymbol ( ) < / code > returned < code >
 * null < / code > .
 * @ throws UnitExistsException
 * Attempt to incompatibly redefine an existing base unit . */
public static synchronized BaseUnit getOrCreate ( final UnitName id , final BaseQuantity baseQuantity ) throws NameException , UnitExistsException { } }

implementation: BaseUnit baseUnit ; final BaseUnit nameUnit = nameMap . get ( id ) ; final BaseUnit quantityUnit = quantityMap . get ( baseQuantity ) ; if ( nameUnit != null || quantityUnit != null ) { baseUnit = nameUnit != null ? nameUnit : quantityUnit ; if ( ( nameUnit != null && ! baseQuantity . equals ( nameUnit . getBaseQuantity ( ) ) ) || ( quantityUnit != null && ! id . equals ( quantityUnit . getUnitName ( ) ) ) ) { throw new UnitExistsException ( "Attempt to incompatibly redefine base unit \"" + baseUnit + '"' ) ; } } else { baseUnit = new BaseUnit ( id , baseQuantity ) ; quantityMap . put ( baseQuantity , baseUnit ) ; nameMap . put ( id , baseUnit ) ; } return baseUnit ;


signature:
public class BaseUnit { /** * Tests this class . */
public static void main ( final String [ ] args ) throws Exception { } }

implementation: final BaseUnit meter = new BaseUnit ( UnitName . newUnitName ( "meter" , null , "m" ) , BaseQuantity . LENGTH ) ; System . out . println ( "meter.getBaseQuantity()=" + meter . getBaseQuantity ( ) ) ; System . out . println ( "meter.toDerivedUnit(1.)=" + meter . toDerivedUnit ( 1. ) ) ; System . out . println ( "meter.toDerivedUnit(new float[] {2})[0]=" + meter . toDerivedUnit ( new float [ ] { 2 } , new float [ 1 ] ) [ 0 ] ) ; System . out . println ( "meter.fromDerivedUnit(1.)=" + meter . fromDerivedUnit ( 1. ) ) ; System . out . println ( "meter.fromDerivedUnit(new float[] {3})[0]=" + meter . fromDerivedUnit ( new float [ ] { 3 } , new float [ 1 ] ) [ 0 ] ) ; System . out . println ( "meter.isCompatible(meter)=" + meter . isCompatible ( meter ) ) ; final BaseUnit radian = new BaseUnit ( UnitName . newUnitName ( "radian" , null , "rad" ) , BaseQuantity . PLANE_ANGLE ) ; System . out . println ( "meter.isCompatible(radian)=" + meter . isCompatible ( radian ) ) ; System . out . println ( "meter.isDimensionless()=" + meter . isDimensionless ( ) ) ; System . out . println ( "radian.isDimensionless()=" + radian . isDimensionless ( ) ) ;


signature:
public class CollectionManagerAbstract { /** * called from Aggregation , Fmrc , FeatureDatasetFactoryManager */
static public CollectionManager open ( String collectionName , String collectionSpec , String olderThan , Formatter errlog ) throws IOException { } }

implementation: if ( collectionSpec . startsWith ( CATALOG ) ) return new CollectionManagerCatalog ( collectionName , collectionSpec , olderThan , errlog ) ; else return MFileCollectionManager . open ( collectionName , collectionSpec , olderThan , errlog ) ;


signature:
public class CollectionManagerAbstract { /** * / * clean up deleted files in metadata manager
 * protected void deleteOld ( Map < String , MFile > newMap ) {
 * if ( store = = null & & enableMetadataManager ) initMM ( ) ;
 * if ( store ! = null ) store . delete ( newMap ) ; */
public void putMetadata ( MFile file , String key , byte [ ] value ) { } }

implementation: if ( store == null ) initMM ( ) ; if ( store != null ) store . put ( file . getPath ( ) + "#" + key , value ) ;


signature:
public class DatasetUrl { /** * Return the set of leading protocols for a url ; may be more than one .
 * Watch out for Windows paths starting with a drive letter = > protocol
 * names must all have a length > 1.
 * Watch out for ' : : '
 * Each captured protocol is saved without trailing ' : '
 * Assume : the protocols MUST be terminated by the occurrence of ' / ' .
 * @ param url the url whose protocols to return
 * @ return list of leading protocols without the trailing : */
static public List < String > getProtocols ( String url ) { } }

implementation:
List < String > allprotocols = new ArrayList < > ( ) ; // all leading protocols upto path or host
// Note , we cannot use split because of the context sensitivity
// This code is quite ugly because of all the confounding cases
// ( e . g . windows path , embedded colons , etc . ) .
// Specifically , the ' file : ' protocol is a problem because
// it has no many non - standard forms such as file : x / y file : / / x / y file : / / / x / y .
StringBuilder buf = new StringBuilder ( url ) ; // If there are any leading protocols , then they must stop at the first ' / ' .
int slashpos = buf . indexOf ( "/" ) ; // Check special case of file : < path > with no slashes after file :
if ( url . startsWith ( "file:" ) && "/\\" . indexOf ( url . charAt ( 5 ) ) < 0 ) { allprotocols . add ( "file" ) ; } else if ( slashpos >= 0 ) { // Remove everything after the first slash
buf . delete ( slashpos + 1 , buf . length ( ) ) ; for ( ; ; ) { int index = buf . indexOf ( ":" ) ; if ( index < 0 ) break ; // no more protocols
// Validate protocol
if ( ! validateprotocol ( url , 0 , index ) ) break ; String protocol = buf . substring ( 0 , index ) ; // not including trailing ' : '
allprotocols . add ( protocol ) ; buf . delete ( 0 , index + 1 ) ; // remove the leading protocol
} } return allprotocols ;


signature: public class DatasetUrl { static public DatasetUrl findDatasetUrl ( String orgLocation ) throws IOException { } }

implementation:
ServiceType svctype = null ; // Canonicalize the location
String location = StringUtil2 . replace ( orgLocation . trim ( ) , '\\' , "/" ) ; List < String > allprotocols = DatasetUrl . getProtocols ( location ) ; String trueurl = location ; String leadprotocol ; if ( allprotocols . size ( ) == 0 ) { leadprotocol = "file" ; // The location has no leading protocols , assume file :
} else { leadprotocol = allprotocols . get ( 0 ) ; } // Priority in deciding
// the service type is as follows .
// 1 . " protocol " tag in fragment
// 2 . specific protocol in fragment
// 3 . leading protocol
// 4 . path extension
// 5 . contact the server ( if defined )
// temporarily remove any trailing query or fragment
String fragment = null ; int pos = trueurl . lastIndexOf ( '#' ) ; if ( pos >= 0 ) { fragment = trueurl . substring ( pos + 1 , trueurl . length ( ) ) ; trueurl = trueurl . substring ( 0 , pos ) ; } pos = location . lastIndexOf ( '?' ) ; String query = null ; if ( pos >= 0 ) { query = trueurl . substring ( pos + 1 , trueurl . length ( ) ) ; trueurl = trueurl . substring ( 0 , pos ) ; } if ( fragment != null ) svctype = searchFragment ( fragment ) ; if ( svctype == null ) // See if leading protocol tells us how to interpret
svctype = decodeLeadProtocol ( leadprotocol ) ; if ( svctype == null ) // See if path tells us how to interpret
svctype = searchPath ( trueurl ) ; if ( svctype == null ) { // There are several possibilities at this point ; all of which
// require further info to disambiguate
// - we have file : / / < path > or file : < path > ; we need to see if
// the extension can help , otherwise , start defaulting .
// - we have a simple url : e . g . http : / / . . . ; contact the server
if ( leadprotocol . equals ( "file" ) ) { svctype = decodePathExtension ( trueurl ) ; // look at the path extension
if ( svctype == null && checkIfNcml ( new File ( location ) ) ) { svctype = ServiceType . NCML ; } } else { svctype = disambiguateHttp ( trueurl ) ; // special cases
if ( ( svctype == null || svctype == ServiceType . HTTPServer ) ) { // ncml file being served over http ?
if ( checkIfRemoteNcml ( trueurl ) ) { svctype = ServiceType . NCML ; } } } } if ( svctype == ServiceType . NCML ) { // If lead protocol was null and then pretend it was a file
// Note that technically , this should be ' file : / / '
trueurl = ( allprotocols . size ( ) == 0 ? "file:" + trueurl : location ) ; } // Add back the query and fragment ( if any )
if ( query != null || fragment != null ) { StringBuilder buf = new StringBuilder ( trueurl ) ; if ( query != null ) { buf . append ( '?' ) ; buf . append ( query ) ; } if ( fragment != null ) { buf . append ( '#' ) ; buf . append ( fragment ) ; } trueurl = buf . toString ( ) ; } return new DatasetUrl ( svctype , trueurl ) ;


signature:
public class DatasetUrl { /** * Given a location , find markers indicated which protocol to use
 * LOOK what use case is this handling ?
 * @ param fragment the fragment is to be examined
 * @ return The discovered ServiceType , or null */
static private ServiceType searchFragment ( String fragment ) { } }

implementation: if ( fragment . length ( ) == 0 ) return null ; Map < String , String > map = parseFragment ( fragment ) ; if ( map == null ) return null ; String protocol = map . get ( "protocol" ) ; if ( protocol == null ) { for ( String p : FRAGPROTOCOLS ) { if ( map . get ( p ) != null ) { protocol = p ; break ; } } } if ( protocol != null ) { if ( protocol . equalsIgnoreCase ( "dap" ) || protocol . equalsIgnoreCase ( "dods" ) ) return ServiceType . OPENDAP ; if ( protocol . equalsIgnoreCase ( "dap4" ) ) return ServiceType . DAP4 ; if ( protocol . equalsIgnoreCase ( "cdmremote" ) ) return ServiceType . CdmRemote ; if ( protocol . equalsIgnoreCase ( "thredds" ) ) return ServiceType . THREDDS ; if ( protocol . equalsIgnoreCase ( "ncml" ) ) return ServiceType . NCML ; } return null ;


signature:
public class DatasetUrl { /** * Given the fragment part of a url , see if it
 * parses as name = value pairs separated by ' & '
 * ( same as query part ) .
 * @ param fragment the fragment part of a url
 * @ return a map of the name value pairs ( possibly empty ) ,
 * or null if the fragment does not parse . */
static private Map < String , String > parseFragment ( String fragment ) { } }

implementation:
Map < String , String > map = new HashMap < > ( ) ; if ( fragment != null && fragment . length ( ) >= 0 ) { if ( fragment . charAt ( 0 ) == '#' ) fragment = fragment . substring ( 1 ) ; String [ ] pairs = fragment . split ( "[ \t]*[&][ \t]*" ) ; for ( String pair : pairs ) { String [ ] pieces = pair . split ( "[ \t]*[=][ \t]*" ) ; switch ( pieces . length ) { case 1 : map . put ( EscapeStrings . unescapeURL ( pieces [ 0 ] ) . toLowerCase ( ) , "true" ) ; break ; case 2 : map . put ( EscapeStrings . unescapeURL ( pieces [ 0 ] ) . toLowerCase ( ) , EscapeStrings . unescapeURL ( pieces [ 1 ] ) . toLowerCase ( ) ) ; break ; default : return null ; // does not parse
} } } return map ;


signature:
public class DatasetUrl { /** * Given a url , search the path to look for protocol indicators
 * @ param url the url is to be examined
 * @ return The discovered ServiceType , or null */
static private ServiceType searchPath ( String url ) { } }

implementation:
if ( false ) { // Disable for now
if ( url == null || url . length ( ) == 0 ) return null ; url = url . toLowerCase ( ) ; // for matching purposes
for ( int i = 0 ; i < FRAGPROTOCOLS . length ; i ++ ) { String p = FRAGPROTOCOLS [ i ] ; if ( url . indexOf ( "/thredds/" + p . toLowerCase ( ) + "/" ) >= 0 ) { return FRAGPROTOSVCTYPE [ i ] ; } } } return null ;


signature:
public class DatasetUrl { /** * Check path extension ; assumes no query or fragment
 * @ param path the path to examine for extension
 * @ return ServiceType inferred from the extension or null */
static private ServiceType decodePathExtension ( String path ) { } }

implementation:
// Look at the path extensions
if ( path . endsWith ( ".dds" ) || path . endsWith ( ".das" ) || path . endsWith ( ".dods" ) ) return ServiceType . OPENDAP ; if ( path . endsWith ( ".dmr" ) || path . endsWith ( ".dap" ) || path . endsWith ( ".dsr" ) ) return ServiceType . DAP4 ; if ( path . endsWith ( ".xml" ) || path . endsWith ( ".ncml" ) ) return ServiceType . NCML ; return null ;


signature:
public class DatasetUrl { /** * Attempt to map a leading url protocol url to a service type ( see thredds . catalog . ServiceType ) .
 * Possible service types should include at least the following .
 * < ol >
 * < li > OPENDAP ( DAP2 protocol )
 * < li > DAP4 ( DAP4 protocol )
 * < li > CdmRemote ( remote ncstream )
 * < / ol >
 * @ param protocol The leading protocol
 * @ return ServiceType indicating how to handle the url , or null . */
@ Urlencoded static private ServiceType decodeLeadProtocol ( String protocol ) throws IOException { } }

implementation:
if ( protocol . equals ( "dods" ) ) return ServiceType . OPENDAP ; else if ( protocol . equals ( "dap4" ) ) return ServiceType . DAP4 ; else if ( protocol . equals ( "httpserver" ) || protocol . equals ( "nodods" ) ) return ServiceType . HTTPServer ; else if ( protocol . equals ( CdmRemote . PROTOCOL ) ) return ServiceType . CdmRemote ; else if ( protocol . equals ( DataFactory . PROTOCOL ) ) // thredds
return ServiceType . THREDDS ; return null ;


signature:
public class DatasetUrl { /** * If the URL alone is not sufficient to disambiguate the location ,
 * then this method will attempt to do a specific kind of request on
 * the server , typically a HEAD call using the URL .
 * It finds the header " Content - Description "
 * and uses it value ( e . g . " ncstream " or " dods " , etc )
 * in order to disambiguate .
 * @ param location the url to disambiguate
 * @ return ServiceType indicating how to handle the url */
@ Urlencoded static private ServiceType disambiguateHttp ( String location ) throws IOException { } }

implementation:
boolean checkDap2 = false , checkDap4 = false , checkCdmr = false ; // some TDS specific tests
if ( location . contains ( "cdmremote" ) ) { ServiceType result = checkIfCdmr ( location ) ; if ( result != null ) return result ; checkCdmr = true ; } if ( location . contains ( "dodsC" ) ) { ServiceType result = checkIfDods ( location ) ; if ( result != null ) return result ; checkDap2 = true ; } if ( location . contains ( "dap4" ) ) { ServiceType result = checkIfDap4 ( location ) ; if ( result != null ) return result ; checkDap4 = true ; } if ( ! checkDap2 ) { ServiceType result = checkIfDods ( location ) ; if ( result != null ) return result ; } if ( ! checkDap4 ) { ServiceType result = checkIfDap4 ( location ) ; if ( result != null ) return result ; } if ( ! checkCdmr ) { ServiceType result = checkIfCdmr ( location ) ; if ( result != null ) return result ; } return null ;


signature:
public class DatasetUrl { /** * cdmremote */
static private ServiceType checkIfCdmr ( String location ) throws IOException { } }

implementation: try ( HTTPMethod method = HTTPFactory . Head ( location + "?req=header" ) ) { int statusCode = method . execute ( ) ; if ( statusCode >= 300 ) { if ( statusCode == HttpStatus . SC_UNAUTHORIZED || statusCode == HttpStatus . SC_FORBIDDEN ) throw new IOException ( "Unauthorized to open dataset " + location ) ; else throw new IOException ( location + " is not a valid URL, return status=" + statusCode ) ; } Header h = method . getResponseHeader ( "Content-Description" ) ; if ( ( h != null ) && ( h . getValue ( ) != null ) ) { String v = h . getValue ( ) ; if ( v . equalsIgnoreCase ( "ncstream" ) ) return ServiceType . CdmRemote ; } } return null ;


signature:
public class DatasetUrl { /** * not sure what other opendap servers do , so fall back on check for dds */
static private ServiceType checkIfDods ( String location ) throws IOException { } }

implementation:
int len = location . length ( ) ; // Strip off any trailing . dds , . das , or . dods
if ( location . endsWith ( ".dds" ) ) location = location . substring ( 0 , len - ".dds" . length ( ) ) ; if ( location . endsWith ( ".das" ) ) location = location . substring ( 0 , len - ".das" . length ( ) ) ; if ( location . endsWith ( ".dods" ) ) location = location . substring ( 0 , len - ".dods" . length ( ) ) ; // Opendap assumes that the caller has properly escaped the url
try ( // For some reason , the head method is not using credentials
// method = session . newMethodHead ( location + " . dds " ) ;
HTTPMethod method = HTTPFactory . Get ( location + ".dds" ) ) { int status = method . execute ( ) ; if ( status == 200 ) { Header h = method . getResponseHeader ( "Content-Description" ) ; if ( ( h != null ) && ( h . getValue ( ) != null ) ) { String v = h . getValue ( ) ; if ( v . equalsIgnoreCase ( "dods-dds" ) || v . equalsIgnoreCase ( "dods_dds" ) ) return ServiceType . OPENDAP ; else throw new IOException ( "OPeNDAP Server Error= " + method . getResponseAsString ( ) ) ; } } if ( status == HttpStatus . SC_UNAUTHORIZED || status == HttpStatus . SC_FORBIDDEN ) throw new IOException ( "Unauthorized to open dataset " + location ) ; // not dods
return null ; }


signature:
public class DatasetUrl { /** * check for dmr */
static private ServiceType checkIfDap4 ( String location ) throws IOException { } }

implementation:
// Strip off any trailing DAP4 prefix
if ( location . endsWith ( ".dap" ) ) location = location . substring ( 0 , location . length ( ) - ".dap" . length ( ) ) ; else if ( location . endsWith ( ".dmr" ) ) location = location . substring ( 0 , location . length ( ) - ".dmr" . length ( ) ) ; else if ( location . endsWith ( ".dmr.xml" ) ) location = location . substring ( 0 , location . length ( ) - ".dmr.xml" . length ( ) ) ; else if ( location . endsWith ( ".dsr" ) ) location = location . substring ( 0 , location . length ( ) - ".dsr" . length ( ) ) ; try ( HTTPMethod method = HTTPFactory . Get ( location + ".dmr.xml" ) ) { int status = method . execute ( ) ; if ( status == 200 ) { Header h = method . getResponseHeader ( "Content-Type" ) ; if ( ( h != null ) && ( h . getValue ( ) != null ) ) { String v = h . getValue ( ) ; if ( v . startsWith ( "application/vnd.opendap.org" ) ) return ServiceType . DAP4 ; } } if ( status == HttpStatus . SC_UNAUTHORIZED || status == HttpStatus . SC_FORBIDDEN ) throw new IOException ( "Unauthorized to open dataset " + location ) ; // not dods
return null ; }


signature:
public class NcStreamWriter { /** * LOOK compression not used */
public long sendData2 ( Variable v , Section section , OutputStream out , NcStreamCompression compress ) throws IOException , InvalidRangeException { } }

implementation:
if ( show ) System . out . printf ( " %s section=%s%n" , v . getFullName ( ) , section ) ; boolean isVlen = v . isVariableLength ( ) ; // & & v . getRank ( ) > 1;
if ( isVlen ) v . read ( section ) ; NcStreamDataCol encoder = new NcStreamDataCol ( ) ; NcStreamProto . DataCol dataProto = encoder . encodeData2 ( v . getFullName ( ) , isVlen , section , v . read ( section ) ) ; // LOOK trap error , write error message ? ?
// dataProto . writeDelimitedTo ( out ) ;
long size = 0 ; size += writeBytes ( out , NcStream . MAGIC_DATA2 ) ; // data version 3
byte [ ] datab = dataProto . toByteArray ( ) ; size += NcStream . writeVInt ( out , datab . length ) ; // dataProto len
size += writeBytes ( out , datab ) ; // dataProto
return size ;


signature:
public class DapUtil { /** * return last name part of an fqn ; result will be escaped . */
static public String fqnSuffix ( String fqn ) { } }

implementation: int structindex = fqn . lastIndexOf ( '.' ) ; int groupindex = fqn . lastIndexOf ( '/' ) ; if ( structindex >= 0 ) return fqn . substring ( structindex + 1 , fqn . length ( ) ) ; else return fqn . substring ( groupindex + 1 , fqn . length ( ) ) ;


signature:
public class DapUtil { /** * return prefix name part of an fqn ; result will be escaped . */
static public String fqnPrefix ( String fqn ) { } }

implementation: int structindex = fqn . lastIndexOf ( '.' ) ; int groupindex = fqn . lastIndexOf ( '/' ) ; if ( structindex >= 0 ) return fqn . substring ( 0 , structindex ) ; else return fqn . substring ( 0 , groupindex ) ;


signature:
public class DapUtil { /** * Walk the specified subtree dir tree to try to locate file | dir named filename .
 * Use breadth first search .
 * @ param filename Name of the file | dir to locate
 * @ param abspath Absolute path from which to start search
 * @ param wantdir True if we are looking for a directory ,
 * false if we are looking for a file
 * @ return absolute path of the file or null */
static public String locateFile ( String filename , String abspath , boolean wantdir ) { } }

implementation:
Deque < String > q = new ArrayDeque < String > ( ) ; // clean up the path and filename
filename = filename . trim ( ) . replace ( '\\' , '/' ) ; abspath = abspath . trim ( ) . replace ( '\\' , '/' ) ; if ( filename . charAt ( 0 ) == '/' ) filename = filename . substring ( 1 ) ; if ( filename . endsWith ( "/" ) ) filename = filename . substring ( 0 , filename . length ( ) - 1 ) ; if ( abspath . endsWith ( "/" ) ) abspath = abspath . substring ( 0 , abspath . length ( ) - 1 ) ; q . addFirst ( abspath ) ; // prime the search queue
for ( ; ; ) { // breadth first search
String currentpath = q . poll ( ) ; if ( currentpath == null ) break ; // done searching
File current = new File ( currentpath ) ; File [ ] contents = current . listFiles ( ) ; if ( contents != null ) { for ( File subfile : contents ) { if ( ! subfile . getName ( ) . equals ( filename ) ) continue ; if ( ( wantdir && subfile . isDirectory ( ) ) || ( ! wantdir && subfile . isFile ( ) ) ) { // Assume this is it
return DapUtil . canonicalpath ( subfile . getAbsolutePath ( ) ) ; } } for ( File subfile : contents ) { if ( subfile . isDirectory ( ) ) q . addFirst ( currentpath + "/" + subfile . getName ( ) ) ; } } } return null ;


signature:
public class DapUtil { /** * Walk the specified dir tree to locate file specified by relative path .
 * Use breadth first search .
 * @ param relpath Name of the file | dir to locate
 * @ param abspath Absolute path from which to start search
 * @ param wantdir True if we are looking for a directory ,
 * false if we are looking for a file
 * @ return absolute path of the file | dir wrt to abspath */
static public String locateRelative ( String relpath , String abspath , boolean wantdir ) { } }

implementation:
// clean up the path and filename
relpath = relpath . trim ( ) . replace ( '\\' , '/' ) ; if ( relpath . charAt ( 0 ) == '/' ) relpath = relpath . substring ( 1 ) ; if ( relpath . endsWith ( "/" ) ) relpath = relpath . substring ( 0 , relpath . length ( ) - 1 ) ; String [ ] pieces = relpath . split ( "[/]" ) ; String partial = abspath ; for ( int i = 0 ; i < pieces . length - 1 ; i ++ ) { String nextdir = locateFile ( pieces [ i ] , abspath , true ) ; if ( nextdir == null ) return null ; partial = nextdir ; } // See if the final file | dir exists in this dir
String finalpath = locateFile ( pieces [ pieces . length - 1 ] , partial , wantdir ) ; return finalpath ;


signature:
public class DapUtil { /** * Convert path to :
 * 1 . use ' / ' consistently
 * 2 . remove any trailing ' / '
 * 3 . trim blanks
 * 4 . Be aware of possible windows drive letter
 * @ param path convert this path
 * @ return canonicalized version */
static public String canonicalpath ( String path ) { } }

implementation:
if ( path == null ) return null ; path = path . trim ( ) ; path = path . replace ( '\\' , '/' ) ; if ( path . endsWith ( "/" ) ) path = path . substring ( 0 , path . length ( ) - 1 ) ; boolean abs = ( path . length ( ) > 0 && path . charAt ( 0 ) == '/' ) ; if ( abs ) path = path . substring ( 1 ) ; // temporary
if ( DapUtil . hasDriveLetter ( path ) ) { // As a last step , lowercase the drive letter , if any
path = path . substring ( 0 , 1 ) . toLowerCase ( ) + path . substring ( 1 ) ; } else if ( abs ) path = "/" + path ; return path ;


signature:
public class DapUtil { /** * Properly extract the byte contents of a ByteBuffer
 * @ param buf The buffer whose content is to be extracted
 * as defined by the buffer limit .
 * @ return The byte array contents of the buffer */
static public byte [ ] extract ( ByteBuffer buf ) { } }

implementation: int len = buf . limit ( ) ; byte [ ] bytes = new byte [ len ] ; buf . rewind ( ) ; buf . get ( bytes ) ; return bytes ;


signature:
public class DapUtil { /** * Given a dap variable , get the path from the
 * top - level variable to and including the given variable
 * such that all but the last element is a structure . */
static public List < DapVariable > getStructurePath ( DapVariable var ) { } }

implementation: List < DapNode > path = var . getPath ( ) ; List < DapVariable > structpath = new ArrayList < DapVariable > ( ) ; for ( int i = 0 ; i < path . size ( ) ; i ++ ) { DapNode node = path . get ( i ) ; switch ( node . getSort ( ) ) { case DATASET : case GROUP : break ; case VARIABLE : structpath . add ( ( DapVariable ) node ) ; break ; default : assert false : "Internal error" ; } } return structpath ;


signature:
public class DapUtil { /** * Convert " " paths to null
 * @ param path
 * @ return path or null */
static public String nullify ( String path ) { } }

implementation: return ( path != null && path . length ( ) == 0 ? null : path ) ;


signature:
public class DapUtil { /** * Test a List < Slice > against set of DapDimensions
 * to see if the list is whole wrt the dimensions
 * @ param slices the set of slices
 * @ param dimset the list of DapDimension
 * @ result true if slices is whole wrt dimset ; false otherwise */
static public boolean isWhole ( List < Slice > slices , List < DapDimension > dimset ) { } }

implementation: if ( slices . size ( ) != dimset . size ( ) ) return false ; for ( int i = 0 ; i < slices . size ( ) ; i ++ ) { Slice slice = slices . get ( i ) ; DapDimension dim = dimset . get ( i ) ; if ( slice . getStride ( ) != 1 || slice . getFirst ( ) != 0 || slice . getCount ( ) != dim . getSize ( ) ) return false ; } return true ;


signature:
public class DapUtil { /** * Given an Array of Strings and a separator and a count ,
 * concat the first count elements of an array with separator
 * between them . A null string is treated like " " .
 * @ param array the array to concat
 * @ param sep the separator
 * @ param from start point for join ( inclusive )
 * @ param upto end point for join ( exclusive )
 * @ return the join */
static public String join ( String [ ] array , String sep , int from , int upto ) { } }

implementation: if ( sep == null ) sep = "" ; if ( from < 0 || upto > array . length ) throw new IndexOutOfBoundsException ( ) ; if ( upto <= from ) return "" ; StringBuilder result = new StringBuilder ( ) ; boolean first = true ; for ( int i = from ; i < upto ; i ++ , first = false ) { if ( ! first ) result . append ( sep ) ; result . append ( array [ i ] ) ; } return result . toString ( ) ;


signature:
public class DapUtil { /** * return true if this path appears to start with a windows drive letter
 * @ param path
 * @ return */
static public boolean hasDriveLetter ( String path ) { } }

implementation: boolean hasdr = false ; if ( path != null && path . length ( ) >= 2 ) { hasdr = ( DRIVELETTERS . indexOf ( path . charAt ( 0 ) ) >= 0 && path . charAt ( 1 ) == ':' ) ; } return hasdr ;


signature:
public class DapUtil { /** * Return the set of leading protocols for a url ; may be more than one .
 * @ param url the url whose protocols to return
 * @ param breakpoint return the index past last protocol
 * @ return list of leading protocols without the trailing : */
static public List < String > getProtocols ( String url , int [ ] breakpoint ) { } }

implementation:
// break off any leading protocols ;
// there may be more than one .
// Watch out for Windows paths starting with a drive letter .
// Each protocol has trailing ' : ' removed
List < String > allprotocols = new ArrayList < > ( ) ; // all leading protocols upto path or host
// Note , we cannot use split because of the context sensitivity
StringBuilder buf = new StringBuilder ( url ) ; int protosize = 0 ; for ( ; ; ) { int index = buf . indexOf ( ":" ) ; if ( index < 0 ) break ; // no more protocols
String protocol = buf . substring ( 0 , index ) ; // Check for windows drive letter
if ( index == 1 // = > | protocol | = = 1 = > windows drive letter
&& "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" . indexOf ( buf . charAt ( 0 ) ) >= 0 ) break ; allprotocols . add ( protocol ) ; buf . delete ( 0 , index + 1 ) ; // remove the leading protocol
protosize += ( index + 1 ) ; if ( buf . indexOf ( "/" ) == 0 ) break ; // anything after this is not a protocol
} breakpoint [ 0 ] = protosize ; return allprotocols ;


signature:
public class DapUtil { /** * Provide a helper function to convert an Index object to
 * a slice list .
 * @ param indices indicate value to read
 * @ param template variable template
 * @ return corresponding List < Slice >
 * @ throws DapException */
static public List < Slice > indexToSlices ( Index indices , DapVariable template ) throws dap4 . core . util . DapException { } }

implementation: List < DapDimension > dims = template . getDimensions ( ) ; List < Slice > slices = indexToSlices ( indices , dims ) ; return slices ;


signature:
public class DapUtil { /** * Provide a helper function to convert an offset to
 * a slice list .
 * @ param offset
 * @ param template variable template
 * @ return
 * @ throws dap4 . core . util . DapException */
static public List < Slice > offsetToSlices ( long offset , DapVariable template ) throws DapException { } }

implementation: List < DapDimension > dims = template . getDimensions ( ) ; long [ ] dimsizes = DapUtil . getDimSizes ( dims ) ; return indexToSlices ( offsetToIndex ( offset , dimsizes ) , template ) ;


signature:
public class DapUtil { /** * Given an offset ( single index ) and a set of dimensions
 * compute the set of dimension indices that correspond
 * to the offset . */
static public Index offsetToIndex ( long offset , long [ ] dimsizes ) { } }

implementation:
// offset = d3 * ( d2 * ( d1 * ( x1 ) ) + x2 ) + x3
long [ ] indices = new long [ dimsizes . length ] ; for ( int i = dimsizes . length - 1 ; i >= 0 ; i -- ) { indices [ i ] = offset % dimsizes [ i ] ; offset = ( offset - indices [ i ] ) / dimsizes [ i ] ; } return new Index ( indices , dimsizes ) ;


signature:
public class DapUtil { /** * Given an offset ( single index ) and a set of dimensions
 * compute the set of dimension indices that correspond
 * to the offset . */
static public List < Slice > indexToSlices ( Index indices ) throws DapException { } }

implementation:
// short circuit the scalar case
if ( indices . getRank ( ) == 0 ) return Slice . SCALARSLICES ; // offset = d3 * ( d2 * ( d1 * ( x1 ) ) + x2 ) + x3
List < Slice > slices = new ArrayList < > ( indices . rank ) ; for ( int i = 0 ; i < indices . rank ; i ++ ) { long isize = indices . indices [ i ] ; slices . add ( new Slice ( isize , isize + 1 , 1 , indices . dimsizes [ i ] ) ) ; } return slices ;


signature:
public class DapUtil { /** * Test if a set of slices represent a contiguous region
 * This is equivalent to saying all strides are one
 * @ param slices
 * @ return */
static public boolean isContiguous ( List < Slice > slices ) { } }

implementation: for ( Slice sl : slices ) { if ( sl . getStride ( ) != 1 ) return false ; } return true ;


signature:
public class DapUtil { /** * Test if a set of slices represent a single position
 * @ param slices
 * @ return */
static public boolean isSinglePoint ( List < Slice > slices ) { } }

implementation: for ( Slice sl : slices ) { if ( sl . getCount ( ) != 1 ) return false ; } return true ;


signature:
public class DapUtil { /** * If a set of slices refers to a single position ,
 * then return the corresponding Index . Otherwise ,
 * throw Exception .
 * @ param slices
 * @ return Index corresponding to slices
 * @ throws DapException */
static public Index slicesToIndex ( List < Slice > slices ) throws DapException { } }

implementation: long [ ] positions = new long [ slices . size ( ) ] ; long [ ] dimsizes = new long [ slices . size ( ) ] ; for ( int i = 0 ; i < positions . length ; i ++ ) { Slice s = slices . get ( i ) ; if ( s . getCount ( ) != 1 ) throw new DapException ( "Attempt to convert non-singleton sliceset to index" ) ; positions [ i ] = s . getFirst ( ) ; dimsizes [ i ] = s . getMax ( ) ; } return new Index ( positions , dimsizes ) ;


signature:
public class NcStreamReader { /** * Read the result of a data request . Only one variable at a time .
 * @ param is read from input stream
 * @ param ncfile need the metadata from here to interpret structure data
 * @ return DataResult
 * @ throws IOException on read error */
public DataResult readData ( InputStream is , NetcdfFile ncfile , String location ) throws IOException { } }

implementation: byte [ ] b = new byte [ 4 ] ; int bytesRead = NcStream . readFully ( is , b ) ; if ( bytesRead < b . length ) throw new EOFException ( location ) ; if ( NcStream . test ( b , NcStream . MAGIC_DATA ) ) return readData1 ( is , ncfile ) ; if ( NcStream . test ( b , NcStream . MAGIC_DATA2 ) ) return readData2 ( is ) ; throw new IOException ( "Data transfer corrupted on " + location ) ;


signature:
public class NcStreamReader { /** * LOOK */
public StructureDataIterator getStructureIterator ( InputStream is , NetcdfFile ncfile ) throws IOException { } }

implementation:
if ( ! NcStream . readAndTest ( is , NcStream . MAGIC_DATA ) ) throw new IOException ( "Data transfer corrupted on " + ncfile . getLocation ( ) ) ; int psize = NcStream . readVInt ( is ) ; if ( debug ) System . out . println ( "  readData data message len= " + psize ) ; byte [ ] dp = new byte [ psize ] ; NcStream . readFully ( is , dp ) ; NcStreamProto . Data dproto = NcStreamProto . Data . parseFrom ( dp ) ; // if ( debug ) System . out . println ( " readData proto = " + dproto ) ;
Structure s = ( Structure ) ncfile . findVariable ( dproto . getVarName ( ) ) ; StructureMembers members = s . makeStructureMembers ( ) ; ArrayStructureBB . setOffsets ( members ) ; ByteOrder bo = NcStream . decodeDataByteOrder ( dproto ) ; return new StreamDataIterator ( is , members , bo ) ;


signature: public class NcStreamReader { private NetcdfFile proto2nc ( NcStreamProto . Header proto , NetcdfFile ncfile ) throws InvalidProtocolBufferException { } }

implementation:
if ( ncfile == null ) ncfile = new NetcdfFileSubclass ( ) ; // not used i think
ncfile . setLocation ( proto . getLocation ( ) ) ; if ( proto . getId ( ) . length ( ) > 0 ) ncfile . setId ( proto . getId ( ) ) ; if ( proto . getTitle ( ) . length ( ) > 0 ) ncfile . setTitle ( proto . getTitle ( ) ) ; NcStreamProto . Group root = proto . getRoot ( ) ; NcStream . readGroup ( root , ncfile , ncfile . getRootGroup ( ) ) ; ncfile . finish ( ) ; return ncfile ;


signature:
public class PointConfigXML { /** * Create an XML document from this info
 * @ return netcdfDatasetInfo XML document */
public Document makeDocument ( ) { } }

implementation: Element rootElem = new Element ( "pointConfig" ) ; Document doc = new Document ( rootElem ) ; if ( tableConfigurerClass != null ) rootElem . addContent ( new Element ( "tableConfigurer" ) . setAttribute ( "class" , tableConfigurerClass ) ) ; if ( tc . featureType != null ) rootElem . setAttribute ( "featureType" , tc . featureType . toString ( ) ) ; rootElem . addContent ( writeTable ( tc ) ) ; return doc ;