Input:
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 . [CODESPLIT] public final void externalize ( OutputStream os , boolean compress , boolean headers ) throws IOException { // 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 ( ) ; }


Input: Find the Tag that matches the code . [CODESPLIT] public static TagEnum getTag ( short code ) { TagEnum te = hash . get ( code ) ; if ( te == null ) te = new TagEnum ( "UNKNOWN" , "UNKNOWN" , code ) ; return te ; }


Input: method for class testing . <p / > Invocation : <PRE > java Getopts option set arg0 arg1 ... argn < / PRE > [CODESPLIT] public static void main ( String args [ ] ) { 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 ) ; } }


Input: Open from a URL : adde : use AddeImage . factory () http : use javax . imageio . ImageIO . read () file : javax . imageio . ImageIO . read () [CODESPLIT] public BufferedImage open ( String location ) throws java . io . IOException { 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 ; } } }


Input: This assumes you have opened a file . looks in the parent directory . [CODESPLIT] public BufferedImage getNextImage ( boolean forward ) { 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 ) ; } }


Input: Conmpute the size in databuffer of the daptype wrt to a serialization ; 0 if undefined . [CODESPLIT] static public int size ( DapType type ) { 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 ; }


Input: Convert an array of one type of values to another type [CODESPLIT] static public Object convertVector ( DapType dsttype , DapType srctype , Object src ) throws DapException { 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 ] &= 0xFF L ; } } 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 ] ) & 0xFF L ; } 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 ] &= 0xFFFF L ; } } 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 ] ) & 0xFFFF L ; } 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 ] &= 0xFFFF L ; } } 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 ] &= 0xFFFFFFFF  L ; } } 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 ] & 0xFF L ) ; } 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 ; }


Input: Calculates the sum of the values in the given array . [CODESPLIT] private static int sumArray ( int [ ] arr ) { 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 ; }


Input: Set the grid scale . [CODESPLIT] public void setGrid ( Rectangle2D bbox , double width , double height ) { 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 ) ; }


Input: Set how much the data may overlap . [CODESPLIT] public void setOverlap ( int overlap ) { // overlap limited to [0, 50%] double dover = Math . max ( 0.0 , Math . min ( .01 * overlap , .50 ) ) ; scaleOverlap = 1.0 - dover ; }


Input: clear all the grid cells [CODESPLIT] public void clear ( ) { for ( int y = 0 ; y < countY ; y ++ ) for ( int x = 0 ; x < countX ; x ++ ) gridArray [ y ] [ x ] . used = false ; }


Input: 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 . [CODESPLIT] public boolean markIfClear ( Rectangle2D rect , Object o ) { 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 ; }


Input: Check if the given rect intersects an already drawn object [CODESPLIT] public Object findIntersection ( Rectangle2D rect ) { 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 ; }


Input: Check if the given point is contained in already drawn object [CODESPLIT] public Object findIntersection ( Point2D p ) { 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 ; }


Input: Find the closest marked cell to the given point [CODESPLIT] public Object findClosest ( Point2D pt ) { 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 }


Input: with center cell [ x y ] and side of length 2 * perimeter + 1 [CODESPLIT] private Object findClosestAlongPerimeter ( Point2D pt , int centerX , int centerY , int perimeter ) { 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 ; }


Input: if out of bbox or cell not marked return MAX_DOUBLE [CODESPLIT] private double distanceSq ( Point2D pt , int indexX , int indexY ) { 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 ) ; }


Input: Setup needed for all MultiTrajectoryObsDatatypes . [CODESPLIT] public void setTrajectoryInfo ( Dimension trajDim , Variable trajVar , Dimension timeDim , Variable timeVar , Variable latVar , Variable lonVar , Variable elevVar ) throws IOException { 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 ) ; } }


Input: Create the canonical form of the URL . If the urlName starts with http : change it to start with cdmremote : otherwise leave it alone . [CODESPLIT] public static String canonicalURL ( String urlName ) { if ( urlName . startsWith ( "http:" ) ) return SCHEME + urlName . substring ( 5 ) ; return urlName ; }


Input: session may be null if so will be closed on method . close () [CODESPLIT] public static InputStream sendQuery ( HTTPSession session , String remoteURI , String query ) throws IOException { 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 ; } }


Input: Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { 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 ; }


Input: Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { 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 ; }


Input: Factory method for creating a new BaseUnit or obtaining a previously - created one . [CODESPLIT] public static synchronized BaseUnit getOrCreate ( final UnitName id , final BaseQuantity baseQuantity ) throws NameException , UnitExistsException { 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 ; }


Input: Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { 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 ( ) ) ; }


Input: called from Aggregation Fmrc FeatureDatasetFactoryManager [CODESPLIT] static public CollectionManager open ( String collectionName , String collectionSpec , String olderThan , Formatter errlog ) throws IOException { if ( collectionSpec . startsWith ( CATALOG ) ) return new CollectionManagerCatalog ( collectionName , collectionSpec , olderThan , errlog ) ; else return MFileCollectionManager . open ( collectionName , collectionSpec , olderThan , errlog ) ; }


Input: / * 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 ) ; } [CODESPLIT] public void putMetadata ( MFile file , String key , byte [ ] value ) { if ( store == null ) initMM ( ) ; if ( store != null ) store . put ( file . getPath ( ) + "#" + key , value ) ; }


Input: 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 / . [CODESPLIT] static public List < String > getProtocols ( String url ) { 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 ; }


Input: /////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static public DatasetUrl findDatasetUrl ( String orgLocation ) throws IOException { 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 ) ; }


Input: Given a location find markers indicated which protocol to use LOOK what use case is this handling ? [CODESPLIT] static private ServiceType searchFragment ( String fragment ) { 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 ; }


Input: Given the fragment part of a url see if it parses as name = value pairs separated by & ( same as query part ) . [CODESPLIT] static private Map < String , String > parseFragment ( String fragment ) { 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 ; }


Input: Given a url search the path to look for protocol indicators [CODESPLIT] static private ServiceType searchPath ( String url ) { 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 ; }


Input: Check path extension ; assumes no query or fragment [CODESPLIT] static private ServiceType decodePathExtension ( String path ) { // 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 ; }


Input: / * 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 > [CODESPLIT] @ Urlencoded static private ServiceType decodeLeadProtocol ( String protocol ) throws IOException { 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 ; }


Input: 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 . [CODESPLIT] @ Urlencoded static private ServiceType disambiguateHttp ( String location ) throws IOException { 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 ; }


Input: cdmremote [CODESPLIT] static private ServiceType checkIfCdmr ( String location ) throws IOException { 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 ; }


Input: not sure what other opendap servers do so fall back on check for dds [CODESPLIT] static private ServiceType checkIfDods ( String location ) throws IOException { 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 ; } }


Input: check for dmr [CODESPLIT] static private ServiceType checkIfDap4 ( String location ) throws IOException { // 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 ; } }


Input:
LOOK compression not used [CODESPLIT] public long sendData2 ( Variable v , Section section , OutputStream out , NcStreamCompression compress ) throws IOException , InvalidRangeException { 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 ; }


Input: return last name part of an fqn ; result will be escaped . [CODESPLIT] static public String fqnSuffix ( String fqn ) { 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 ( ) ) ; }


Input: return prefix name part of an fqn ; result will be escaped . [CODESPLIT] static public String fqnPrefix ( String fqn ) { int structindex = fqn . lastIndexOf ( ' ' ) ; int groupindex = fqn . lastIndexOf ( ' ' ) ; if ( structindex >= 0 ) return fqn . substring ( 0 , structindex ) ; else return fqn . substring ( 0 , groupindex ) ; }


Input: Walk the specified subtree dir tree to try to locate file|dir named filename . Use breadth first search . [CODESPLIT] static public String locateFile ( String filename , String abspath , boolean wantdir ) { 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 ; }


Input: Walk the specified dir tree to locate file specified by relative path . Use breadth first search . [CODESPLIT] static public String locateRelative ( String relpath , String abspath , boolean wantdir ) { // 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 ; }


Input: Convert path to : 1 . use / consistently 2 . remove any trailing / 3 . trim blanks 4 . Be aware of possible windows drive letter [CODESPLIT] static public String canonicalpath ( String path ) { 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 ; }


Input: Properly extract the byte contents of a ByteBuffer [CODESPLIT] static public byte [ ] extract ( ByteBuffer buf ) { int len = buf . limit ( ) ; byte [ ] bytes = new byte [ len ] ; buf . rewind ( ) ; buf . get ( bytes ) ; return bytes ; }


Input: 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 . [CODESPLIT] static public List < DapVariable > getStructurePath ( DapVariable var ) { 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 ; }


Input: Convert paths to null [CODESPLIT] static public String nullify ( String path ) { return ( path != null && path . length ( ) == 0 ? null : path ) ; }


Input: Test a List<Slice > against set of DapDimensions to see if the list is whole wrt the dimensions [CODESPLIT] static public boolean isWhole ( List < Slice > slices , List < DapDimension > dimset ) { 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 ; }


Input: 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 . [CODESPLIT] static public String join ( String [ ] array , String sep , int from , int upto ) { 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 ( ) ; }


Input: return true if this path appears to start with a windows drive letter [CODESPLIT] static public boolean hasDriveLetter ( String path ) { boolean hasdr = false ; if ( path != null && path . length ( ) >= 2 ) { hasdr = ( DRIVELETTERS . indexOf ( path . charAt ( 0 ) ) >= 0 && path . charAt ( 1 ) == ' ' ) ; } return hasdr ; }


Input: Return the set of leading protocols for a url ; may be more than one . [CODESPLIT] static public List < String > getProtocols ( String url , int [ ] breakpoint ) { // 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 ; }


Input: Provide a helper function to convert an Index object to a slice list . [CODESPLIT] static public List < Slice > indexToSlices ( Index indices , DapVariable template ) throws dap4 . core . util . DapException { List < DapDimension > dims = template . getDimensions ( ) ; List < Slice > slices = indexToSlices ( indices , dims ) ; return slices ; }


Input: Provide a helper function to convert an offset to a slice list . [CODESPLIT] static public List < Slice > offsetToSlices ( long offset , DapVariable template ) throws DapException { List < DapDimension > dims = template . getDimensions ( ) ; long [ ] dimsizes = DapUtil . getDimSizes ( dims ) ; return indexToSlices ( offsetToIndex ( offset , dimsizes ) , template ) ; }


Input: Given an offset ( single index ) and a set of dimensions compute the set of dimension indices that correspond to the offset . [CODESPLIT] static public Index offsetToIndex ( long offset , long [ ] dimsizes ) { // 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 ) ; }


Input: Given an offset ( single index ) and a set of dimensions compute the set of dimension indices that correspond to the offset . [CODESPLIT] static public List < Slice > indexToSlices ( Index indices ) throws DapException { // 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 ; }


Input: Test if a set of slices represent a contiguous region This is equivalent to saying all strides are one [CODESPLIT] static public boolean isContiguous ( List < Slice > slices ) { for ( Slice sl : slices ) { if ( sl . getStride ( ) != 1 ) return false ; } return true ; }


Input: Test if a set of slices represent a single position [CODESPLIT] static public boolean isSinglePoint ( List < Slice > slices ) { for ( Slice sl : slices ) { if ( sl . getCount ( ) != 1 ) return false ; } return true ; }


Input: If a set of slices refers to a single position then return the corresponding Index . Otherwise throw Exception . [CODESPLIT] static public Index slicesToIndex ( List < Slice > slices ) throws DapException { 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 ) ; }


Input: Read the result of a data request . Only one variable at a time . [CODESPLIT] public DataResult readData ( InputStream is , NetcdfFile ncfile , String location ) throws IOException { 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 ) ; }


Input:
LOOK [CODESPLIT] public StructureDataIterator getStructureIterator ( InputStream is , NetcdfFile ncfile ) throws IOException { 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 ) ; }


Input:
/////////////////////////////////////////////////////////////////// [CODESPLIT] private NetcdfFile proto2nc ( NcStreamProto . Header proto , NetcdfFile ncfile ) throws InvalidProtocolBufferException { 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 ; }


Input: Create an XML document from this info [CODESPLIT] public Document makeDocument ( ) { 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 ; }


Input: / * MAGIC_START version sizeIndex BufrCdmIndexProto ( sizeIndex bytes ) [CODESPLIT] private boolean writeIndex2 ( String bufrFilename , BufrConfig config , File indexFile ) throws IOException { if ( indexFile . exists ( ) ) { if ( ! indexFile . delete ( ) ) log . warn ( " BufrCdmIndex cant delete index file {}" , indexFile . getPath ( ) ) ; } log . debug ( " createIndex for {}" , indexFile . getPath ( ) ) ; try ( RandomAccessFile raf = new RandomAccessFile ( indexFile . getPath ( ) , "rw" ) ) { raf . order ( RandomAccessFile . BIG_ENDIAN ) ; //// header message raf . write ( MAGIC_START . getBytes ( CDM . utf8Charset ) ) ; raf . writeInt ( version ) ; // build it BufrCdmIndexProto . BufrIndex . Builder indexBuilder = BufrCdmIndexProto . BufrIndex . newBuilder ( ) ; indexBuilder . setFilename ( bufrFilename ) ; root = buildField ( config . getRootConverter ( ) ) ; indexBuilder . setRoot ( root ) ; indexBuilder . setStart ( config . getStart ( ) ) ; indexBuilder . setEnd ( config . getEnd ( ) ) ; indexBuilder . setNobs ( config . getNobs ( ) ) ; Map < String , BufrConfig . BufrStation > smaps = config . getStationMap ( ) ; if ( smaps != null ) { List < BufrConfig . BufrStation > stations = new ArrayList < BufrConfig . BufrStation > ( smaps . values ( ) ) ; Collections . sort ( stations ) ; for ( BufrConfig . BufrStation s : stations ) { indexBuilder . addStations ( buildStation ( s ) ) ; } } // write it BufrCdmIndexProto . BufrIndex index = indexBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( raf , b . length ) ; // message size raf . write ( b ) ; // message  - all in one gulp log . debug ( "  file size =  %d bytes" , raf . length ( ) ) ; return true ; } }


Input: / * Create new ArrayDouble with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayDouble factory ( Index index , double [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayDouble . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayDouble . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayDouble . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayDouble . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayDouble . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayDouble . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayDouble . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayDouble . D7 ( index , storage ) ; } else { return new ArrayDouble ( index , storage ) ; } }


Input: copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { double [ ] ja = ( double [ ] ) javaArray ; for ( double aJa : ja ) iter . setDoubleNext ( aJa ) ; }


Input: Set extra information used by station obs datasets . Use stnIdVName or stnIndexVName . [CODESPLIT] public void setStationInfo ( String stnIdVName , String stnDescVName , String stnIndexVName , StationHelper stationHelper ) { this . stnIdVName = stnIdVName ; this . stnDescVName = stnDescVName ; this . stnIndexVName = stnIndexVName ; this . stationHelper = stationHelper ; if ( stnIdVName != null ) { Variable stationVar = ncfile . findVariable ( stnIdVName ) ; stationIdType = stationVar . getDataType ( ) ; } }


Input: access it members [CODESPLIT] public void setShortNames ( String latVName , String lonVName , String altVName , String obsTimeVName , String nomTimeVName ) { this . latVName = latVName ; this . lonVName = lonVName ; this . zcoordVName = altVName ; this . obsTimeVName = obsTimeVName ; this . nomTimeVName = nomTimeVName ; }


Input: //////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public PointFeature factory ( StationImpl s , StructureData sdata , int recno ) { if ( s == null ) return new RecordPointObs ( sdata , recno ) ; else return new RecordStationObs ( s , sdata , recno ) ; }


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

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

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

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

 [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; PrimitiveVector pv = getPrimitiveVector ( ) ; if ( pv instanceof BaseTypePrimitiveVector ) { BaseTypePrimitiveVector vals = ( BaseTypePrimitiveVector ) pv ; if ( print_decl_p ) { printDecl ( os , space , false , true ) ; os . print ( " = " ) ; } os . print ( "{ " ) ; //vals.printVal(os, ""); ServerMethods sm ; int len = vals . getLength ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { sm = ( ServerMethods ) vals . getValue ( i ) ; if ( sm . isProject ( ) ) { ( ( BaseType ) sm ) . printVal ( os , "" , false ) ; os . print ( ", " ) ; } } // print last value, if any, without trailing comma if ( len > 0 ) { sm = ( ServerMethods ) vals . getValue ( len - 1 ) ; if ( sm . isProject ( ) ) { ( ( BaseType ) sm ) . printVal ( os , "" , false ) ; } } os . print ( "}" ) ; if ( print_decl_p ) os . println ( ";" ) ; } else { super . printVal ( os , space , print_decl_p ) ; } }


Input:
Read NCEP mnemonic BUFR tables . [CODESPLIT] public static boolean read ( InputStream ios , BufrTables . Tables tables ) throws IOException { if ( ios == null ) return false ; if ( tables . b == null ) tables . b = new TableB ( "fake" , "fake" ) ; if ( tables . d == null ) tables . d = new TableD ( "fake" , "fake" ) ; HashMap < String , String > number = new HashMap <> ( ) ; // key = mnemonic value = fxy
 HashMap < String , String > desc = new HashMap <> ( ) ; // key = mnemonic value = description
 HashMap < String , String > mnseq = new HashMap <> ( ) ; try { BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( ios , CDM . utf8Charset ) ) ; // read  mnemonic table
 Matcher m ; // read header info and disregard
 while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) throw new RuntimeException ( "Bad NCEP mnemonic BUFR table " ) ; if ( line . contains ( "MNEMONIC" ) ) break ; } // read mnemonic, number, and description
 //| HEADR    | 362001 | TABLE D ENTRY - PROFILE COORDINATES                      |
 while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; if ( line . contains ( "MNEMONIC" ) ) break ; if ( line . contains ( "----" ) ) continue ; if ( line . startsWith ( "*" ) ) continue ; if ( line . startsWith ( "|       " ) ) continue ; m = fields3 . matcher ( line ) ; if ( m . find ( ) ) { String mnu = m . group ( 1 ) . trim ( ) ; String fxy = m . group ( 2 ) . trim ( ) ; if ( fxy . startsWith ( "3" ) ) { number . put ( mnu , fxy ) ; desc . put ( mnu , m . group ( 3 ) . replace ( "TABLE D ENTRY - " , "" ) . trim ( ) ) ; } else if ( fxy . startsWith ( "0" ) ) { number . put ( mnu , fxy ) ; desc . put ( mnu , m . group ( 3 ) . replace ( "TABLE B ENTRY - " , "" ) . trim ( ) ) ; } else if ( fxy . startsWith ( "A" ) ) { number . put ( mnu , fxy ) ; desc . put ( mnu , m . group ( 3 ) . replace ( "TABLE A ENTRY - " , "" ) . trim ( ) ) ; } } else if ( debugTable ) { System . out . println ( "bad mnemonic, number, and description: " + line ) ; } } // read in sequences using mnemonics
 //| ETACLS1  | HEADR {PROFILE} SURF FLUX HYDR D10M {SLYR} XTRA                   |
 while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; if ( line . contains ( "MNEMONIC" ) ) break ; if ( line . contains ( "----" ) ) continue ; if ( line . startsWith ( "|       " ) ) continue ; if ( line . startsWith ( "*" ) ) continue ; m = fields2 . matcher ( line ) ; if ( m . find ( ) ) { String mnu = m . group ( 1 ) . trim ( ) ; if ( mnseq . containsKey ( mnu ) ) { // concat lines with same mnu
 String value = mnseq . get ( mnu ) ; value = value + " " + m . group ( 2 ) ; mnseq . put ( mnu , value ) ; } else { mnseq . put ( mnu , m . group ( 2 ) ) ; } } else if ( debugTable ) { System . out . println ( "bad sequence mnemonic: " + line ) ; } } // create sequences, replacing mnemonics with numbers
 for ( Map . Entry < String , String > ent : mnseq . entrySet ( ) ) { String seq = ent . getValue ( ) ; seq = seq . replaceAll ( "\\<" , "1-1-0 0-31-0 " ) ; seq = seq . replaceAll ( "\\>" , "" ) ; seq = seq . replaceAll ( "\\{" , "1-1-0 0-31-1 " ) ; seq = seq . replaceAll ( "\\}" , "" ) ; seq = seq . replaceAll ( "\\(" , "1-1-0 0-31-2 " ) ; seq = seq . replaceAll ( "\\)" , "" ) ; StringTokenizer stoke = new StringTokenizer ( seq , " " ) ; List < Short > list = new ArrayList <> ( ) ; while ( stoke . hasMoreTokens ( ) ) { String mn = stoke . nextToken ( ) ; if ( mn . charAt ( 1 ) == ' ' ) { list . add ( Descriptor . getFxy ( mn ) ) ; continue ; } // element descriptor needs hyphens
 m = ints6 . matcher ( mn ) ; if ( m . find ( ) ) { String F = mn . substring ( 0 , 1 ) ; String X = removeLeading0 ( mn . substring ( 1 , 3 ) ) ; String Y = removeLeading0 ( mn . substring ( 3 ) ) ; list . add ( Descriptor . getFxy ( F + "-" + X + "-" + Y ) ) ; continue ; } if ( mn . startsWith ( "\"" ) ) { int idx = mn . lastIndexOf ( ' ' ) ; String count = mn . substring ( idx + 1 ) ; list . add ( Descriptor . getFxy ( "1-1-" + count ) ) ; mn = mn . substring ( 1 , idx ) ; } if ( mn . startsWith ( "." ) ) { String des = mn . substring ( mn . length ( ) - 4 ) ; mn = mn . replace ( des , "...." ) ; } String fxy = number . get ( mn ) ; String F = fxy . substring ( 0 , 1 ) ; String X = removeLeading0 ( fxy . substring ( 1 , 3 ) ) ; String Y = removeLeading0 ( fxy . substring ( 3 ) ) ; list . add ( Descriptor . getFxy ( F + "-" + X + "-" + Y ) ) ; } String fxy = number . get ( ent . getKey ( ) ) ; String X = removeLeading0 ( fxy . substring ( 1 , 3 ) ) ; String Y = removeLeading0 ( fxy . substring ( 3 ) ) ; // these are in latest tables
 if ( XlocalCutoff > Integer . parseInt ( X ) && YlocalCutoff > Integer . parseInt ( Y ) ) continue ; //key = F + "-" + X + "-" + Y;
 short seqX = Short . parseShort ( X . trim ( ) ) ; short seqY = Short . parseShort ( Y . trim ( ) ) ; tables . d . addDescriptor ( seqX , seqY , ent . getKey ( ) , list ) ; //short id = Descriptor.getFxy(key);
 //sequences.put(Short.valueOf(id), tableD);
 } // add some static repetition sequences
 // LOOK why?
 List < Short > list = new ArrayList <> ( ) ; // 16 bit delayed repetition
 list . add ( Descriptor . getFxy ( "1-1-0" ) ) ; list . add ( Descriptor . getFxy ( "0-31-2" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 1 , "" , list ) ; //tableD = new DescriptorTableD("", "3-60-1", list, false);
 //tableD.put( "3-60-1", d);
 //short id = Descriptor.getFxy("3-60-1");
 //sequences.put(Short.valueOf(id), tableD);
 list = new ArrayList <> ( ) ; // 8 bit delayed repetition
 list . add ( Descriptor . getFxy ( "1-1-0" ) ) ; list . add ( Descriptor . getFxy ( "0-31-1" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 2 , "" , list ) ; //tableD = new DescriptorTableD("", "3-60-2", list, false);
 //tableD.put( "3-60-2", d);
 //id = Descriptor.getFxy("3-60-2");
 //sequences.put(Short.valueOf(id), tableD);
 list = new ArrayList <> ( ) ; // 8 bit delayed repetition
 list . add ( Descriptor . getFxy ( "1-1-0" ) ) ; list . add ( Descriptor . getFxy ( "0-31-1" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 3 , "" , list ) ; //tableD = new DescriptorTableD("", "3-60-3", list, false);
 //tableD.put( "3-60-3", d);
 //id = Descriptor.getFxy("3-60-3");
 //sequences.put(Short.valueOf(id), tableD);
 list = new ArrayList <> ( ) ; // 1 bit delayed repetition
 list . add ( Descriptor . getFxy ( "1-1-0" ) ) ; list . add ( Descriptor . getFxy ( "0-31-0" ) ) ; tables . d . addDescriptor ( ( short ) 60 , ( short ) 4 , "" , list ) ; //tableD = new DescriptorTableD("", "3-60-4", list, false);
 //tableD.put( "3-60-4", d);
 //id = Descriptor.getFxy("3-60-4");
 //sequences.put(Short.valueOf(id), tableD);
 // add in element descriptors
 //  MNEMONIC | SCAL | REFERENCE   | BIT | UNITS
 //| FTIM     |    0 |           0 |  24 | SECONDS                  |-------------|
 //tableB = new TableB(tablename, tablename);
 while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; if ( line . contains ( "MNEMONIC" ) ) break ; if ( line . startsWith ( "|       " ) ) continue ; if ( line . startsWith ( "*" ) ) continue ; m = fields5 . matcher ( line ) ; if ( m . find ( ) ) { if ( m . group ( 1 ) . equals ( "" ) ) { continue ; } else if ( number . containsKey ( m . group ( 1 ) . trim ( ) ) ) { // add descriptor to tableB
 String fxy = number . get ( m . group ( 1 ) . trim ( ) ) ; String X = fxy . substring ( 1 , 3 ) ; String Y = fxy . substring ( 3 ) ; String mnu = m . group ( 1 ) . trim ( ) ; String descr = desc . get ( mnu ) ; short x = Short . parseShort ( X . trim ( ) ) ; short y = Short . parseShort ( Y . trim ( ) ) ; // these are in latest tables so skip  LOOK WHY
 if ( XlocalCutoff > x && YlocalCutoff > y ) continue ; int scale = Integer . parseInt ( m . group ( 2 ) . trim ( ) ) ; int refVal = Integer . parseInt ( m . group ( 3 ) . trim ( ) ) ; int width = Integer . parseInt ( m . group ( 4 ) . trim ( ) ) ; String units = m . group ( 5 ) . trim ( ) ; tables . b . addDescriptor ( x , y , scale , refVal , width , mnu , units , descr ) ; } else if ( debugTable ) { System . out . println ( "bad element descriptors: " + line ) ; } } } } finally { ios . close ( ) ; } // LOOK why ?
 // default for NCEP
 // 0; 63; 0; 0; 0; 16; Numeric; Byte count
 tables . b . addDescriptor ( ( short ) 63 , ( short ) 0 , 0 , 0 , 16 , "Byte count" , "Numeric" , null ) ; return true ; }


Input:
Read NCEP mnemonic BUFR tables . [CODESPLIT] private static void readSubCategories ( String fileIn , PrintStream out , String token ) throws IOException { System . out . printf ( "%s%n" , fileIn ) ; try ( FileInputStream in = new FileInputStream ( fileIn ) ) { BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( in , CDM . utf8Charset ) ) ; while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) break ; int posb = line . indexOf ( "DISCONTINUED" ) ; if ( posb > 0 ) continue ; posb = line . indexOf ( "NO LONGER" ) ; if ( posb > 0 ) continue ; posb = line . indexOf ( "WAS REPLACED" ) ; if ( posb > 0 ) continue ; int pos = line . indexOf ( token ) ; if ( pos < 0 ) continue ; System . out . printf ( "%s%n" , line ) ; boolean is31 = token . equals ( "031-" ) ; String subline = is31 ? line . substring ( pos ) : line . substring ( pos + token . length ( ) ) ; //if (is31) System.out.printf(" '%s'%n", subline);
 int pos2 = subline . indexOf ( ' ' ) ; String catS = subline . substring ( 0 , pos2 ) ; String desc = subline . substring ( pos2 + 1 ) ; //System.out.printf("   cat='%s'%n", catS);
 //System.out.printf("  desc='%s'%n", desc);
 int cat = Integer . parseInt ( catS . substring ( 0 , 3 ) ) ; int subcat = Integer . parseInt ( catS . substring ( 4 , 7 ) ) ; desc = StringUtil2 . remove ( desc , ' ' ) . trim ( ) ; //System.out.printf("  cat=%d subcat=%d%n", cat,subcat);
 //System.out.printf("  desc='%s'%n", desc);
 //System.out.printf("%d, %d, %s%n", cat, subcat, desc);
 out . printf ( "%d; %d; %s%n" , cat , subcat , desc ) ; } } }


Input: Field construction [CODESPLIT] public HTTPFormBuilder add ( String fieldname , String text ) throws HTTPException { if ( fieldname == null || text == null || fieldname . length ( ) == 0 ) throw new IllegalArgumentException ( ) ; Field f = new Field ( Sort . TEXT , fieldname , text , null ) ; parts . put ( fieldname , f ) ; return this ; }


Input: input is xml file with just the <featureCollection > [CODESPLIT] public FeatureCollectionConfig readConfigFromFile ( String filename ) { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( filename ) ; } catch ( Exception e ) { System . out . printf ( "Error parsing featureCollection %s err = %s" , filename , e . getMessage ( ) ) ; return null ; } return readConfig ( doc . getRootElement ( ) ) ; }


Input: Read a catalog and extract a FeatureCollectionConfig from it [CODESPLIT] public FeatureCollectionConfig readConfigFromCatalog ( String catalogAndPath ) { String catFilename ; String fcName = null ; int pos = catalogAndPath . indexOf ( "#" ) ; if ( pos > 0 ) { catFilename = catalogAndPath . substring ( 0 , pos ) ; fcName = catalogAndPath . substring ( pos + 1 ) ; } else { catFilename = catalogAndPath ; } File cat = new File ( catFilename ) ; org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( cat ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } try { List < Element > fcElems = new ArrayList <> ( ) ; findFeatureCollection ( doc . getRootElement ( ) , fcName , fcElems ) ; if ( fcElems . size ( ) > 0 ) return readConfig ( fcElems . get ( 0 ) ) ; } catch ( IllegalStateException e ) { e . printStackTrace ( ) ; } return null ; }


Input: Add single declaration [CODESPLIT] public void addDecl ( DapNode newdecl ) throws DapException { DapSort newsort = newdecl . getSort ( ) ; String newname = newdecl . getShortName ( ) ; boolean suppress = false ; // Look for name conflicts (ignore anonymous dimensions) if ( newsort != DapSort . DIMENSION || newname != null ) { for ( DapNode decl : decls ) { if ( newsort == decl . getSort ( ) && newname . equals ( decl . getShortName ( ) ) ) throw new DapException ( "DapGroup: attempt to add duplicate decl: " + newname ) ; } } else { // Anonymous DapDimension anon = ( DapDimension ) newdecl ; assert ( newsort == DapSort . DIMENSION && newname == null ) ; // Search for matching anonymous dimension boolean found = false ; for ( DapDimension dim : dimensions ) { if ( ! dim . isShared ( ) && dim . getSize ( ) == anon . getSize ( ) ) { found = true ; break ; } } // Define the anondecl in root group if ( ! found && ! isTopLevel ( ) ) getDataset ( ) . addDecl ( anon ) ; suppress = found || ! isTopLevel ( ) ; } if ( ! suppress ) { decls . add ( newdecl ) ; newdecl . setParent ( this ) ; // Cross link } switch ( newdecl . getSort ( ) ) { case ATTRIBUTE : case ATTRIBUTESET : case OTHERXML : super . addAttribute ( ( DapAttribute ) newdecl ) ; break ; case DIMENSION : if ( ! suppress ) dimensions . add ( ( DapDimension ) newdecl ) ; break ; case ENUMERATION : enums . add ( ( DapEnumeration ) newdecl ) ; break ; case ATOMICTYPE : break ; // do nothing case STRUCTURE : case SEQUENCE : compounds . add ( ( DapStructure ) newdecl ) ; break ; case VARIABLE : variables . add ( ( DapVariable ) newdecl ) ; break ; case GROUP : case DATASET : if ( this != ( DapGroup ) newdecl ) groups . add ( ( DapGroup ) newdecl ) ; break ; default : throw new ClassCastException ( newdecl . getShortName ( ) ) ; } }


Input: We will need to re - order the groups [CODESPLIT] void updateGroups ( List < DapGroup > groups ) { // Verify that the incoming groups are all and only in the list of groups. assert ( groups . size ( ) == this . groups . size ( ) ) : "Update groups: not same size" ; for ( DapGroup g : groups ) { if ( ! this . groups . contains ( g ) ) assert ( false ) : "Update groups: attempt to add new group" ; } }


Input: Parse an FQN and use it to trace to a specific object in a dataset . Absolute FQN paths are passed to DapDataset . findByFQN () . Relative FQNs are assumed to be WRT to the FQN of this node [CODESPLIT] public DapNode findByFQN ( String fqn , DapSort ... sortset ) throws DapException { fqn = fqn . trim ( ) ; if ( fqn == null ) return null ; if ( fqn . charAt ( 0 ) != ' ' ) { String prefix = this . getFQN ( ) ; fqn = prefix + ' ' + fqn ; } return getDataset ( ) . lookup ( fqn , sortset ) ; }


Input: Locate a variable in this group [CODESPLIT] public DapVariable findVariable ( String name ) { DapNode var = findInGroup ( name , DapSort . VARIABLE ) ; return ( DapVariable ) var ; }


Input:
/ * private boolean compare ( List<Dimension > dims1 List<Dimension > dims2 ) { if ( dims1 . size () ! = dims2 . size () ) return false ; for ( int i = 0 ; i < dims1 . size () ; i ++ ) { Dimension dim1 = dims1 . get ( i ) ; Dimension dim2 = dims2 . get ( i ) ; if ( !dim1 . getName () . equals ( dim2 . getName () )) return false ; if ( dim1 . getLength () ! = dim2 . getLength () ) return false ; } return true ; } [CODESPLIT] private boolean compareGroups ( Group org , Group copy , ObjFilter filter ) { if ( showCompare ) f . format ( "compare Group %s to %s %n" , org . getShortName ( ) , copy . getShortName ( ) ) ; boolean ok = true ; if ( ! org . getShortName ( ) . equals ( copy . getShortName ( ) ) ) { f . format ( " ** names are different %s != %s %n" , org . getShortName ( ) , copy . getShortName ( ) ) ; ok = false ; } // dimensions
 ok &= checkDimensions ( org . getDimensions ( ) , copy . getDimensions ( ) ) ; ok &= checkDimensions ( copy . getDimensions ( ) , org . getDimensions ( ) ) ; // attributes
 ok &= checkAttributes ( null , org . getAttributes ( ) , copy . getAttributes ( ) , filter ) ; // enums
 ok &= checkEnums ( org , copy ) ; // variables
 // cant use object equality, just match on short name
 for ( Variable orgV : org . getVariables ( ) ) { Variable copyVar = copy . findVariable ( orgV . getShortName ( ) ) ; if ( copyVar == null ) { f . format ( " ** cant find variable %s in 2nd file%n" , orgV . getFullName ( ) ) ; ok = false ; } else { ok &= compareVariables ( orgV , copyVar , filter , compareData , true ) ; } } for ( Variable copyV : copy . getVariables ( ) ) { Variable orgV = org . findVariable ( copyV . getShortName ( ) ) ; if ( orgV == null ) { f . format ( " ** cant find variable %s in 1st file%n" , copyV . getFullName ( ) ) ; ok = false ; } } // nested groups
 List groups = new ArrayList ( ) ; String name = org . isRoot ( ) ? "root" : org . getFullName ( ) ; ok &= checkAll ( name , org . getGroups ( ) , copy . getGroups ( ) , groups ) ; for ( int i = 0 ; i < groups . size ( ) ; i += 2 ) { Group orgGroup = ( Group ) groups . get ( i ) ; Group copyGroup = ( Group ) groups . get ( i + 1 ) ; ok &= compareGroups ( orgGroup , copyGroup , filter ) ; } return ok ; }


Input: return an arrayList of paired objects . [CODESPLIT] private boolean checkAttributes ( Variable v , List < Attribute > list1 , List < Attribute > list2 , ObjFilter filter ) { boolean ok = true ; String name = v == null ? "global" : "variable " + v . getFullName ( ) ; for ( Attribute att1 : list1 ) { if ( filter == null || filter . attCheckOk ( v , att1 ) ) ok &= checkEach ( name , att1 , "file1" , list1 , "file2" , list2 , null ) ; } for ( Attribute att2 : list2 ) { if ( filter == null || filter . attCheckOk ( v , att2 ) ) ok &= checkEach ( name , att2 , "file2" , list2 , "file1" , list1 , null ) ; } return ok ; }


Input: return an arrayList of paired objects . [CODESPLIT] private boolean checkEnums ( Group org , Group copy ) { boolean ok = true ; for ( EnumTypedef enum1 : org . getEnumTypedefs ( ) ) { if ( showCompare ) f . format ( "compare Enum %s%n" , enum1 . getShortName ( ) ) ; EnumTypedef enum2 = copy . findEnumeration ( enum1 . getShortName ( ) ) ; if ( enum2 == null ) { f . format ( "  ** Enum %s not in file2 %n" , enum1 . getShortName ( ) ) ; ok = false ; continue ; } if ( ! enum1 . equals ( enum2 ) ) { f . format ( "  ** Enum %s not equal%n  %s%n  %s%n" , enum1 . getShortName ( ) , enum1 , enum2 ) ; ok = false ; } } for ( EnumTypedef enum2 : copy . getEnumTypedefs ( ) ) { EnumTypedef enum1 = org . findEnumeration ( enum2 . getShortName ( ) ) ; if ( enum1 == null ) { f . format ( "  ** Enum %s not in file1 %n" , enum2 . getShortName ( ) ) ; ok = false ; } } return ok ; }


Input: return an arrayList of paired objects . [CODESPLIT] private boolean checkAll ( String what , List list1 , List list2 , List result ) { boolean ok = true ; for ( Object aList1 : list1 ) { ok &= checkEach ( what , aList1 , "file1" , list1 , "file2" , list2 , result ) ; } for ( Object aList2 : list2 ) { ok &= checkEach ( what , aList2 , "file2" , list2 , "file1" , list1 , null ) ; } return ok ; }


Input:
check that want is in both list1 and list2 using object . equals () [CODESPLIT] private boolean checkEach ( String what , Object want1 , String name1 , List list1 , String name2 , List list2 , List result ) { boolean ok = true ; try { int index2 = list2 . indexOf ( want1 ) ; if ( index2 < 0 ) { f . format ( "  ** %s: %s 0x%x (%s) not in %s %n" , what , want1 , want1 . hashCode ( ) , name1 , name2 ) ; ok = false ; } else { // found it in second list
 Object want2 = list2 . get ( index2 ) ; int index1 = list1 . indexOf ( want2 ) ; if ( index1 < 0 ) { // can this happen ??
 f . format ( "  ** %s: %s 0x%x (%s) not in %s %n" , what , want2 , want2 . hashCode ( ) , name2 , name1 ) ; ok = false ; } else { // found it in both lists
 Object want = list1 . get ( index1 ) ; if ( ! want . equals ( want1 ) ) { f . format ( "  ** %s: %s 0x%x (%s) not equal to %s 0x%x (%s) %n" , what , want1 , want1 . hashCode ( ) , name1 , want2 , want2 . hashCode ( ) , name2 ) ; ok = false ; } else { if ( showEach ) f . format ( "  OK <%s> equals <%s>%n" , want1 , want2 ) ; if ( result != null ) { result . add ( want1 ) ; result . add ( want2 ) ; } } } } } catch ( Throwable t ) { t . printStackTrace ( ) ; f . format ( " *** Throwable= %s %n" , t . getMessage ( ) ) ; } return ok ; }


Input: / * The COARDS standard offers limited support for climatological time . For compatibility with COARDS time coordinates should also be recognised as climatological if they have a units attribute of time - units relative to midnight on 1 January in year 0 i . e . since 0 - 1 - 1 in udunits syntax and provided they refer to the real - world calendar . We do not recommend this convention because ( a ) it does not provide any information about the intervals used to compute the climatology and ( b ) there is no standard for how dates since year 1 will be encoded with units having a reference time in year 0 since this year does not exist ; consequently there may be inconsistencies among software packages in the interpretation of the time coordinates . Year 0 may be a valid year in non - real - world calendars and therefore cannot be used to signal climatological time in such cases . [CODESPLIT] public static boolean isMine ( String hasName ) { if ( hasName . equalsIgnoreCase ( "COARDS" ) ) return true ; List < String > names = breakupConventionNames ( hasName ) ; for ( String name : names ) { if ( name . equalsIgnoreCase ( "COARDS" ) ) return true ; } return false ; }


Input:
we assume that coordinate axes get identified by being coordinate variables [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ncDataset , VariableEnhanced v ) { String unit = v . getUnitsString ( ) ; if ( unit == null ) return null ; unit = unit . trim ( ) ; if ( unit . equalsIgnoreCase ( "degrees_east" ) || unit . equalsIgnoreCase ( "degrees_E" ) || unit . equalsIgnoreCase ( "degreesE" ) || unit . equalsIgnoreCase ( "degree_east" ) || unit . equalsIgnoreCase ( "degree_E" ) || unit . equalsIgnoreCase ( "degreeE" ) ) return AxisType . Lon ; if ( unit . equalsIgnoreCase ( "degrees_north" ) || unit . equalsIgnoreCase ( "degrees_N" ) || unit . equalsIgnoreCase ( "degreesN" ) || unit . equalsIgnoreCase ( "degree_north" ) || unit . equalsIgnoreCase ( "degree_N" ) || unit . equalsIgnoreCase ( "degreeN" ) ) return AxisType . Lat ; if ( SimpleUnit . isDateUnit ( unit ) ) { return AxisType . Time ; } // look for other z coordinate
 if ( SimpleUnit . isCompatible ( "mbar" , unit ) ) return AxisType . Pressure ; if ( unit . equalsIgnoreCase ( "level" ) || unit . equalsIgnoreCase ( "layer" ) || unit . equalsIgnoreCase ( "sigma_level" ) ) return AxisType . GeoZ ; String positive = ncDataset . findAttValueIgnoreCase ( ( Variable ) v , CF . POSITIVE , null ) ; if ( positive != null ) { if ( SimpleUnit . isCompatible ( "m" , unit ) ) return AxisType . Height ; else return AxisType . GeoZ ; } // a bad idea, but CDC SST relies on it :
 // :Source = "NOAA/National Climatic Data Center";
 // :Contact = "Dick Reynolds, email: Richard.W.Reynolds@noaa.gov & Chunying Liu, email: Chunying.liu@noaa.gov";
 //:netcdf_Convention = "COARDS";
 // if (checkForMeter && SimpleUnit.isCompatible("m", unit))
 //   return AxisType.Height;
 return null ; }