Input: Get the Netcdf data type corresponding to the DODS BaseType class . This is the inverse of convertToDODSType () . [CODESPLIT] static public DataType convertToNCType ( opendap . dap . BaseType dtype , boolean isUnsigned ) { if ( dtype instanceof DString ) return DataType . STRING ; else if ( ( dtype instanceof DStructure ) || ( dtype instanceof DSequence ) || ( dtype instanceof DGrid ) ) return DataType . STRUCTURE ; else if ( dtype instanceof DFloat32 ) return DataType . FLOAT ; else if ( dtype instanceof DFloat64 ) return DataType . DOUBLE ; else if ( dtype instanceof DUInt32 ) return DataType . UINT ; else if ( dtype instanceof DUInt16 ) return DataType . USHORT ; else if ( dtype instanceof DInt32 ) return DataType . INT ; else if ( dtype instanceof DInt16 ) return DataType . SHORT ; else if ( dtype instanceof DByte ) return isUnsigned ? DataType . UBYTE : DataType . BYTE ; else throw new IllegalArgumentException ( "DODSVariable illegal type = " + dtype . getTypeName ( ) ) ; }


Input: Get whether this is an unsigned type . [CODESPLIT] static public boolean isUnsigned ( opendap . dap . BaseType dtype ) { return ( dtype instanceof DByte ) || ( dtype instanceof DUInt16 ) || ( dtype instanceof DUInt32 ) ; }


Input: This does the actual connection to the opendap server and reading of the data . All data calls go through here so we can add debugging . [CODESPLIT] DataDDS readDataDDSfromServer ( String CE ) throws IOException , opendap . dap . DAP2Exception { if ( debugServerCall ) System . out . println ( "DODSNetcdfFile.readDataDDSfromServer = <" + CE + ">" ) ; long start = 0 ; if ( debugTime ) start = System . currentTimeMillis ( ) ; if ( ! CE . startsWith ( "?" ) ) CE = "?" + CE ; DataDDS data ; synchronized ( this ) { data = dodsConnection . getData ( CE , null ) ; } if ( debugTime ) System . out . println ( "DODSNetcdfFile.readDataDDSfromServer took = " + ( System . currentTimeMillis ( ) - start ) / 1000.0 ) ; if ( debugDataResult ) { System . out . println ( " dataDDS return:" ) ; data . print ( System . out ) ; } return data ; }


Input: Make a single call to the DODS Server to read all the named variable s data in one client / server roundtrip . [CODESPLIT] @ Override public List < Array > readArrays ( List < Variable > preloadVariables ) throws IOException { //For performance tests: //if (true) return super.readArrays (variables); if ( preloadVariables . size ( ) == 0 ) return new ArrayList < Array > ( ) ; // construct the list of variables, skipping ones with cached data List < DodsV > reqDodsVlist = new ArrayList < DodsV > ( ) ; DodsV root ; for ( Variable var : preloadVariables ) { if ( var . hasCachedData ( ) ) continue ; reqDodsVlist . add ( ( DodsV ) var . getSPobject ( ) ) ; } Collections . sort ( reqDodsVlist ) ; // "depth first" order // read the data DataDDS dataDDS ; Map < DodsV , DodsV > map = new HashMap < DodsV , DodsV > ( 2 * reqDodsVlist . size ( ) + 1 ) ; if ( reqDodsVlist . size ( ) > 0 ) { // Create the request StringBuilder requestString = new StringBuilder ( ) ; for ( int i = 0 ; i < reqDodsVlist . size ( ) ; i ++ ) { DodsV dodsV = reqDodsVlist . get ( i ) ; requestString . append ( i == 0 ? "?" : "," ) ; // requestString.append(makeDODSname(dodsV)); requestString . append ( dodsV . getEncodedName ( ) ) ; } String s = requestString . toString ( ) ; try { dataDDS = readDataDDSfromServer ( requestString . toString ( ) ) ; root = DodsV . parseDataDDS ( dataDDS ) ; } catch ( Exception exc ) { logger . error ( "ERROR readDataDDSfromServer on " + requestString , exc ) ; throw new IOException ( exc . getMessage ( ) ) ; } // gotta find the corresponding data in "depth first" order for ( DodsV ddsV : reqDodsVlist ) { DodsV dataV = root . findDataV ( ddsV ) ; if ( dataV != null ) { if ( debugConvertData ) System . out . println ( "readArray found dataV= " + makeDODSname ( ddsV ) ) ; dataV . isDone = true ; map . put ( ddsV , dataV ) ; // thread safe! } else { logger . error ( "ERROR findDataV cant find " + makeDODSname ( ddsV ) + " on " + location ) ; } } } // For each variable either extract the data or use cached data. List < Array > result = new ArrayList < Array > ( ) ; for ( Variable var : preloadVariables ) { if ( var . hasCachedData ( ) ) { result . add ( var . read ( ) ) ; } else { Array data = null ; DodsV ddsV = ( DodsV ) var . getSPobject ( ) ; DodsV dataV = map . get ( ddsV ) ; if ( dataV == null ) { logger . error ( "DODSNetcdfFile.readArrays cant find " + makeDODSname ( ddsV ) + " in dataDDS; " + location ) ; //dataDDS.print( System.out); } else { if ( debugConvertData ) System . out . println ( "readArray converting " + makeDODSname ( ddsV ) ) ; dataV . isDone = true ; try { if ( var . isMemberOfStructure ( ) ) { // we want the top structure this variable is contained in. while ( ( dataV . parent != null ) && ( dataV . parent . bt != null ) ) { dataV = dataV . parent ; } data = convertD2N . convertNestedVariable ( var , null , dataV , true ) ; } else data = convertD2N . convertTopVariable ( var , null , dataV ) ; } catch ( DAP2Exception de ) { logger . error ( "ERROR convertVariable on " + var . getFullName ( ) , de ) ; throw new IOException ( de . getMessage ( ) ) ; } if ( var . isCaching ( ) ) { var . setCachedData ( data ) ; if ( debugCached ) System . out . println ( " cache for <" + var . getFullName ( ) + "> length =" + data . getSize ( ) ) ; } } result . add ( data ) ; } } return result ; }


Input: / * this is for reading variables that are members of structures protected Array readMemberData ( ucar . nc2 . Variable v Section section boolean flatten ) throws IOException InvalidRangeException { StringBuffer buff = new StringBuffer ( 100 ) ; buff . setLength ( 0 ) ; [CODESPLIT] public Array readWithCE ( ucar . nc2 . Variable v , String CE ) throws IOException { Array dataArray ; try { DataDDS dataDDS = readDataDDSfromServer ( CE ) ; DodsV root = DodsV . parseDataDDS ( dataDDS ) ; DodsV want = root . children . get ( 0 ) ; // can only be one if ( v . isMemberOfStructure ( ) ) dataArray = convertD2N . convertNestedVariable ( v , null , want , true ) ; else dataArray = convertD2N . convertTopVariable ( v , null , want ) ; } catch ( DAP2Exception ex ) { ex . printStackTrace ( ) ; throw new IOException ( ex . getMessage ( ) ) ; } catch ( ParseException ex ) { ex . printStackTrace ( ) ; throw new IOException ( ex . getMessage ( ) ) ; } return dataArray ; }


Input: debugging [CODESPLIT] public void getDetailInfo ( Formatter f ) { super . getDetailInfo ( f ) ; f . format ( "DDS = %n" ) ; ByteArrayOutputStream buffOS = new ByteArrayOutputStream ( 8000 ) ; dds . print ( buffOS ) ; f . format ( "%s%n" , new String ( buffOS . toByteArray ( ) , Util . UTF8 ) ) ; f . format ( "%nDAS = %n" ) ; buffOS = new ByteArrayOutputStream ( 8000 ) ; das . print ( buffOS ) ; f . format ( "%s%n" , new String ( buffOS . toByteArray ( ) , Util . UTF8 ) ) ; }


Input: Get a gif file make it into an ImageIcon . [CODESPLIT] public static ImageIcon getIcon ( String fullIconName , boolean errMsg ) { ImageIcon icon = null ; java . net . URL iconR = cl . getResource ( fullIconName ) ; if ( debugIcon ) { System . out . println ( "classLoader " + cl . getClassLoader ( ) ) ; System . out . println ( "  Resource.getIcon on " + fullIconName + " = " + iconR ) ; } if ( iconR != null ) icon = new ImageIcon ( iconR ) ; if ( ( icon == null ) && errMsg ) System . out . println ( "  ERROR: Resource.getIcon failed on " + fullIconName ) ; else if ( debugIcon ) System . out . println ( "  Resource.getIcon ok on " + fullIconName ) ; return icon ; }


Input: Get a gif file make it into an Image . [CODESPLIT] public static Image getImage ( String fullImageName ) { Image image = null ; java . net . URL url = cl . getResource ( fullImageName ) ; if ( url != null ) image = Toolkit . getDefaultToolkit ( ) . createImage ( url ) ; if ( image == null ) System . out . println ( "  ERROR: Resource.getImageResource failed on " + fullImageName ) ; return image ; }


Input: Get a gif file make it into a Cursor . [CODESPLIT] public static Cursor makeCursor ( String name ) { Image image = getImage ( name ) ; if ( null == image ) return null ; Cursor cursor ; try { Toolkit tk = Toolkit . getDefaultToolkit ( ) ; if ( debug ) { ImageObserver obs = new ImageObserver ( ) { public boolean imageUpdate ( Image image , int flags , int x , int y , int width , int height ) { return true ; } } ; System . out . println ( " bestCursorSize = " + tk . getBestCursorSize ( image . getWidth ( obs ) , image . getHeight ( obs ) ) ) ; System . out . println ( " getMaximumCursorColors = " + tk . getMaximumCursorColors ( ) ) ; } cursor = tk . createCustomCursor ( image , new Point ( 17 , 17 ) , name ) ; } catch ( IndexOutOfBoundsException e ) { System . out . println ( "NavigatedPanel createCustomCursor failed " + e ) ; return null ; } return cursor ; }


Input: Open a resource as a Stream . First try ClassLoader . getResourceAsStream () . If that fails try a plain old FileInputStream () . [CODESPLIT] public static InputStream getFileResource ( String resourcePath ) { InputStream is = cl . getResourceAsStream ( resourcePath ) ; if ( is != null ) { if ( debug ) System . out . println ( "Resource.getResourceAsStream ok on " + resourcePath ) ; return is ; } else if ( debug ) System . out . println ( "Resource.getResourceAsStream failed on (" + resourcePath + ")" ) ; try { is = new FileInputStream ( resourcePath ) ; if ( debug ) System . out . println ( "Resource.FileInputStream ok on " + resourcePath ) ; } catch ( FileNotFoundException e ) { if ( debug ) System . out . println ( "  FileNotFoundException: Resource.getFile failed on " + resourcePath ) ; } catch ( java . security . AccessControlException e ) { if ( debug ) System . out . println ( "  AccessControlException: Resource.getFile failed on " + resourcePath ) ; } return is ; }


Input: test [CODESPLIT] public static void main ( String [ ] args ) throws IOException { System . out . println ( "java.class.path = " + System . getProperty ( "java.class.path" ) ) ; System . out . println ( "Class = " + cl ) ; System . out . println ( "Class Loader = " + cl . getClassLoader ( ) ) ; try ( InputStream is = getFileResource ( "/ucar.unidata.util/Resource.java" ) ) { } try ( InputStream is = getFileResource ( "Resource.java" ) ) { } try ( InputStream is = getFileResource ( "test/test/Resource.java" ) ) { } }


Input: Read data subset from RandomAccessFile create primitive array of size Layout . getTotalNelems . Reading is controlled by the Layout object . [CODESPLIT] static public Object readDataFill ( RandomAccessFile raf , Layout index , DataType dataType , Object fillValue , int byteOrder ) throws java . io . IOException { Object arr = ( fillValue == null ) ? makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType ) : makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType , fillValue ) ; return readData ( raf , index , dataType , arr , byteOrder , true ) ; }


Input:
Read data subset from RandomAccessFile place in given primitive array . Reading is controlled by the Layout object . [CODESPLIT] static public Object readData ( RandomAccessFile raf , Layout layout , DataType dataType , Object arr , int byteOrder , boolean convertChar ) throws java . io . IOException { if ( showLayoutTypes ) System . out . println ( "***RAF LayoutType=" + layout . getClass ( ) . getName ( ) ) ; if ( dataType . getPrimitiveClassType ( ) == byte . class || dataType == DataType . CHAR ) { byte [ ] pa = ( byte [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFully ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } if ( convertChar && dataType == DataType . CHAR ) return convertByteToChar ( pa ) ; else return pa ; // javac ternary compile error
 } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = ( short [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readShort ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = ( int [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readInt ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = ( float [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFloat ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = ( double [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readDouble ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = ( long [ ] ) arr ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readLong ( pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . STRUCTURE ) { byte [ ] pa = ( byte [ ] ) arr ; int recsize = layout . getElemSize ( ) ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; raf . order ( byteOrder ) ; raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFully ( pa , ( int ) chunk . getDestElem ( ) * recsize , chunk . getNelems ( ) * recsize ) ; } return pa ; } throw new IllegalStateException ( "unknown type= " + dataType ) ; }


Input: Read data subset from PositioningDataInputStream create primitive array of size Layout . getTotalNelems . Reading is controlled by the Layout object . [CODESPLIT] static public Object readDataFill ( PositioningDataInputStream is , Layout index , DataType dataType , Object fillValue ) throws java . io . IOException { Object arr = ( fillValue == null ) ? makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType ) : makePrimitiveArray ( ( int ) index . getTotalNelems ( ) , dataType , fillValue ) ; return readData ( is , index , dataType , arr ) ; }


Input:
Read data subset from PositioningDataInputStream place in given primitive array . Reading is controlled by the Layout object . [CODESPLIT] static public Object readData ( PositioningDataInputStream raf , Layout index , DataType dataType , Object arr ) throws java . io . IOException { if ( showLayoutTypes ) System . out . println ( "***PositioningDataInputStream LayoutType=" + index . getClass ( ) . getName ( ) ) ; if ( dataType . getPrimitiveClassType ( ) == byte . class || dataType == DataType . CHAR ) { byte [ ] pa = ( byte [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . read ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } //return (dataType == DataType.CHAR) ? convertByteToChar(pa) : pa;
 if ( dataType == DataType . CHAR ) return convertByteToChar ( pa ) ; else return pa ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = ( short [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readShort ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = ( int [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readInt ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = ( float [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readFloat ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = ( double [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readDouble ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = ( long [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . readLong ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) , chunk . getNelems ( ) ) ; } return pa ; } else if ( dataType == DataType . STRUCTURE ) { int recsize = index . getElemSize ( ) ; byte [ ] pa = ( byte [ ] ) arr ; while ( index . hasNext ( ) ) { Layout . Chunk chunk = index . next ( ) ; raf . read ( chunk . getSrcPos ( ) , pa , ( int ) chunk . getDestElem ( ) * recsize , chunk . getNelems ( ) * recsize ) ; } return pa ; } throw new IllegalStateException ( ) ; }


Input: Read data subset from ByteBuffer create primitive array of size Layout . getTotalNelems . Reading is controlled by the Layout object . [CODESPLIT] static public Object readDataFill ( LayoutBB layout , DataType dataType , Object fillValue ) throws java . io . IOException { long size = layout . getTotalNelems ( ) ; if ( dataType == DataType . STRUCTURE ) size *= layout . getElemSize ( ) ; Object arr = ( fillValue == null ) ? makePrimitiveArray ( ( int ) size , dataType ) : makePrimitiveArray ( ( int ) size , dataType , fillValue ) ; return readData ( layout , dataType , arr ) ; }


Input:
Read data subset from ByteBuffer place in given primitive array . Reading is controlled by the LayoutBB object . [CODESPLIT] static public Object readData ( LayoutBB layout , DataType dataType , Object arr ) throws java . io . IOException { if ( showLayoutTypes ) System . out . println ( "***BB LayoutType=" + layout . getClass ( ) . getName ( ) ) ; if ( dataType . getPrimitiveClassType ( ) == byte . class || ( dataType == DataType . CHAR ) ) { byte [ ] pa = ( byte [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; ByteBuffer bb = chunk . getByteBuffer ( ) ; bb . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = . get ( ) ; } //return (dataType == DataType.CHAR) ? convertByteToChar(pa) : pa;
 if ( dataType == DataType . CHAR ) return convertByteToChar ( pa ) ; else return pa ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = ( short [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; ShortBuffer buff = chunk . getShortBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = ( int [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; IntBuffer buff = chunk . getIntBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = ( float [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; FloatBuffer buff = chunk . getFloatBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = ( double [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; DoubleBuffer buff = chunk . getDoubleBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = ( long [ ] ) arr ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; LongBuffer buff = chunk . getLongBuffer ( ) ; buff . position ( chunk . getSrcElem ( ) ) ; int pos = ( int ) chunk . getDestElem ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) pa [ pos ++ ] = buff . get ( ) ; } return pa ; } else if ( dataType == DataType . STRUCTURE ) { byte [ ] pa = ( byte [ ] ) arr ; int recsize = layout . getElemSize ( ) ; while ( layout . hasNext ( ) ) { LayoutBB . Chunk chunk = layout . next ( ) ; ByteBuffer bb = chunk . getByteBuffer ( ) ; bb . position ( chunk . getSrcElem ( ) * recsize ) ; int pos = ( int ) chunk . getDestElem ( ) * recsize ; for ( int i = 0 ; i < chunk . getNelems ( ) * recsize ; i ++ ) pa [ pos ++ ] = . get ( ) ; } return pa ; } throw new IllegalStateException ( ) ; }


Input:
Copy data to a channel . Used by ncstream . Not doing Structures correctly yet . [CODESPLIT] public static long copyToByteChannel ( Array data , WritableByteChannel channel ) throws java . io . IOException { Class classType = data . getElementType ( ) ; /* if (data instanceof ArrayStructure) { // use NcStream encoding
      DataOutputStream os = new DataOutputStream(Channels.newOutputStream(channel));
      return NcStream.encodeArrayStructure((ArrayStructure) data, null, os);
    } */ DataOutputStream outStream = new DataOutputStream ( Channels . newOutputStream ( channel ) ) ; IndexIterator iterA = data . getIndexIterator ( ) ; if ( classType == double . class ) { while ( iterA . hasNext ( ) ) outStream . writeDouble ( iterA . getDoubleNext ( ) ) ; } else if ( classType == float . class ) { while ( iterA . hasNext ( ) ) outStream . writeFloat ( iterA . getFloatNext ( ) ) ; } else if ( classType == long . class ) { while ( iterA . hasNext ( ) ) outStream . writeLong ( iterA . getLongNext ( ) ) ; } else if ( classType == int . class ) { while ( iterA . hasNext ( ) ) outStream . writeInt ( iterA . getIntNext ( ) ) ; } else if ( classType == short . class ) { while ( iterA . hasNext ( ) ) outStream . writeShort ( iterA . getShortNext ( ) ) ; } else if ( classType == char . class ) { // LOOK why are we using chars anyway ?
 byte [ ] pa = convertCharToByte ( ( char [ ] ) data . get1DJavaArray ( DataType . CHAR ) ) ; outStream . write ( pa , 0 , pa . length ) ; } else if ( classType == byte . class ) { while ( iterA . hasNext ( ) ) outStream . writeByte ( iterA . getByteNext ( ) ) ; } else if ( classType == boolean . class ) { while ( iterA . hasNext ( ) ) outStream . writeBoolean ( iterA . getBooleanNext ( ) ) ; } else if ( classType == String . class ) { long size = 0 ; while ( iterA . hasNext ( ) ) { String s = ( String ) iterA . getObjectNext ( ) ; size += NcStream . writeVInt ( outStream , s . length ( ) ) ; byte [ ] b = s . getBytes ( CDM . utf8Charset ) ; outStream . write ( b ) ; size += b . length ; } return size ; } else if ( classType == ByteBuffer . class ) { // OPAQUE
 long size = 0 ; while ( iterA . hasNext ( ) ) { ByteBuffer bb = ( ByteBuffer ) iterA . getObjectNext ( ) ; size += NcStream . writeVInt ( outStream , bb . limit ( ) ) ; bb . rewind ( ) ; channel . write ( bb ) ; size += bb . limit ( ) ; } return size ; } else if ( data instanceof ArrayObject ) { // vlen
 long size = 0 ; //size += NcStream.writeVInt(outStream, (int) data.getSize()); // nelems already written
 while ( iterA . hasNext ( ) ) { Array row = ( Array ) iterA . getObjectNext ( ) ; ByteBuffer bb = row . getDataAsByteBuffer ( ) ; byte [ ] result = bb . array ( ) ; size += NcStream . writeVInt ( outStream , result . length ) ; // size in bytes
 outStream . write ( result ) ; // array
 size += result . length ; } return size ; } else throw new UnsupportedOperationException ( "Class type = " + classType . getName ( ) ) ; return data . getSizeBytes ( ) ; }


Input: Create 1D primitive array of the given size and type [CODESPLIT] static public Object makePrimitiveArray ( int size , DataType dataType ) { Object arr = null ; if ( ( dataType . getPrimitiveClassType ( ) == byte . class ) || ( dataType == DataType . CHAR ) || ( dataType == DataType . OPAQUE ) || ( dataType == DataType . STRUCTURE ) ) { arr = new byte [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { arr = new short [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { arr = new int [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { arr = new long [ size ] ; } else if ( dataType == DataType . FLOAT ) { arr = new float [ size ] ; } else if ( dataType == DataType . DOUBLE ) { arr = new double [ size ] ; } else if ( dataType == DataType . STRING ) { arr = new String [ size ] ; } return arr ; }


Input:
Create 1D primitive array of the given size and type fill it with the given value [CODESPLIT] static public Object makePrimitiveArray ( int size , DataType dataType , Object fillValue ) { if ( dataType . getPrimitiveClassType ( ) == byte . class || ( dataType == DataType . CHAR ) ) { byte [ ] pa = new byte [ size ] ; byte val = ( ( Number ) fillValue ) . byteValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; // if (dataType == DataType.CHAR) return convertByteToChar(pa);
 return pa ; } else if ( dataType == DataType . OPAQUE ) { return new byte [ size ] ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { short [ ] pa = new short [ size ] ; short val = ( ( Number ) fillValue ) . shortValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { int [ ] pa = new int [ size ] ; int val = ( ( Number ) fillValue ) . intValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { long [ ] pa = new long [ size ] ; long val = ( ( Number ) fillValue ) . longValue ( ) ; if ( val != 0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType == DataType . FLOAT ) { float [ ] pa = new float [ size ] ; float val = ( ( Number ) fillValue ) . floatValue ( ) ; if ( val != 0.0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType == DataType . DOUBLE ) { double [ ] pa = new double [ size ] ; double val = ( ( Number ) fillValue ) . doubleValue ( ) ; if ( val != 0.0 ) for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = val ; return pa ; } else if ( dataType == DataType . STRING ) { String [ ] pa = new String [ size ] ; for ( int i = 0 ; i < size ; i ++ ) pa [ i ] = ( String ) fillValue ; return pa ; } else if ( dataType == DataType . STRUCTURE ) { byte [ ] pa = new byte [ size ] ; if ( fillValue != null ) { byte [ ] val = ( byte [ ] ) fillValue ; int count = 0 ; while ( count < size ) for ( byte aVal : val ) pa [ count ++ ] = aVal ; } return pa ; } throw new IllegalStateException ( ) ; }


Input: convert byte array to char array assuming UTF - 8 encoding [CODESPLIT] static public char [ ] convertByteToCharUTF ( byte [ ] byteArray ) { Charset c = CDM . utf8Charset ; CharBuffer output = c . decode ( ByteBuffer . wrap ( byteArray ) ) ; return output . array ( ) ; }


Input: convert char array to byte array assuming UTF - 8 encoding [CODESPLIT] static public byte [ ] convertCharToByteUTF ( char [ ] from ) { Charset c = CDM . utf8Charset ; ByteBuffer output = c . encode ( CharBuffer . wrap ( from ) ) ; return output . array ( ) ; }


Input:
convert byte array to char array [CODESPLIT] static public char [ ] convertByteToChar ( byte [ ] byteArray ) { int size = byteArray . length ; char [ ] cbuff = new char [ size ] ; for ( int i = 0 ; i < size ; i ++ ) cbuff [ i ] = ( char ) DataType . unsignedByteToShort ( byteArray [ i ] ) ; // NOTE: not Unicode !
 return cbuff ; } // convert char array to byte array
 static public byte [ ] convertCharToByte ( char [ ] from ) { byte [ ] to = null ; if ( from != null ) { int size = from . length ; to = new byte [ size ] ; for ( int i = 0 ; i < size ; i ++ ) to [ i ] = ( byte ) from [ i ] ; // LOOK wrong, convert back to unsigned byte ???
 } return to ; }


Input:
section reading for member data [CODESPLIT] static public ucar . ma2 . Array readSection ( ParsedSectionSpec cer ) throws IOException , InvalidRangeException { Variable inner = null ; List < Range > totalRanges = new ArrayList <> ( ) ; ParsedSectionSpec current = cer ; while ( current != null ) { totalRanges . addAll ( current . section . getRanges ( ) ) ; inner = current . v ; current = current . child ; } assert inner != null ; Section total = new Section ( totalRanges ) ; Array result = Array . factory ( inner . getDataType ( ) , total . getShape ( ) ) ; // must be a Structure
 Structure outer = ( Structure ) cer . v ; Structure outerSubset = outer . select ( cer . child . v . getShortName ( ) ) ; // allows IOSPs to optimize for  this case
 ArrayStructure outerData = ( ArrayStructure ) outerSubset . read ( cer . section ) ; extractSection ( cer . child , outerData , result . getIndexIterator ( ) ) ; return result ; }


Input:
LOOK could be used in createView ?? [CODESPLIT] static private ArrayStructure sectionArrayStructure ( ParsedSectionSpec child , ArrayStructure innerData , StructureMembers . Member m ) throws IOException , InvalidRangeException { StructureMembers membersw = new StructureMembers ( m . getStructureMembers ( ) ) ; // no data arrays get propagated
 ArrayStructureW result = new ArrayStructureW ( membersw , child . section . getShape ( ) ) ; int count = 0 ; Section . Iterator iter = child . section . getIterator ( child . v . getShape ( ) ) ; while ( iter . hasNext ( ) ) { int recno = iter . next ( null ) ; StructureData sd = innerData . getStructureData ( recno ) ; result . setStructureData ( sd , count ++ ) ; } return result ; }


Input: / * package [CODESPLIT] void add ( long recno , int fieldno , Array field ) { FieldArrays fs = records [ ( int ) recno ] ; if ( fs == null ) records [ ( int ) recno ] = ( fs = new FieldArrays ( this . nmembers ) ) ; fs . fields [ fieldno ] = field ; }


Input: Get the index th StructureData ( StructureDataA ) object We need instances of StructureData to give to the user . We use StructureDataA so we can centralize everything in this class . The total number of StructureData objects is dimsize . [CODESPLIT] @ Override public StructureData getStructureData ( int index ) { assert ( super . sdata != null ) ; if ( index < 0 || index >= this . dimsize ) throw new IllegalArgumentException ( index + " >= " + super . sdata . length ) ; assert ( super . sdata [ index ] != null ) ; return super . sdata [ index ] ; }


Input: Get member databuffer of type String or char . [CODESPLIT] public String getScalarString ( int recnum , StructureMembers . Member m ) { Array data = m . getDataArray ( ) ; return ( String ) data . getObject ( recnum ) . toString ( ) ; }


Input: Non - atomic cases [CODESPLIT] public StructureData getScalarStructure ( int index , StructureMembers . Member m ) { if ( m . getDataType ( ) != DataType . STRUCTURE ) throw new ForbiddenConversionException ( "Atomic field cannot be converted to Structure" ) ; Array ca = memberArray ( index , memberIndex ( m ) ) ; if ( ca . getDataType ( ) != DataType . STRUCTURE && ca . getDataType ( ) != DataType . SEQUENCE ) throw new ForbiddenConversionException ( "Attempt to access non-structure member" ) ; CDMArrayStructure as = ( CDMArrayStructure ) ca ; return as . getStructureData ( 0 ) ; }


Input: Key interface method coming in from StructureDataA . [CODESPLIT] @ Override public ucar . ma2 . Array getArray ( int recno , StructureMembers . Member m ) { return ( ucar . ma2 . Array ) memberArray ( recno , memberIndex ( m ) ) ; }


Input: Utilities [CODESPLIT] @ Override protected StructureData makeStructureData ( ArrayStructure as , int index ) { if ( super . sdata [ index ] == null ) super . sdata [ index ] = new StructureDataA ( as , index ) ; return super . sdata [ index ] ; }


Input: Compute the StructureMembers object from a DapStructure . May need to recurse if a field is itself a Structure [CODESPLIT] static StructureMembers computemembers ( DapVariable var ) { DapStructure ds = ( DapStructure ) var . getBaseType ( ) ; StructureMembers sm = new StructureMembers ( ds . getShortName ( ) ) ; List < DapVariable > fields = ds . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; DapType dt = field . getBaseType ( ) ; DataType cdmtype = CDMTypeFcns . daptype2cdmtype ( dt ) ; StructureMembers . Member m = sm . addMember ( field . getShortName ( ) , "" , null , cdmtype , CDMUtil . computeEffectiveShape ( field . getDimensions ( ) ) ) ; m . setDataParam ( i ) ; // So we can index into various lists // recurse if this field is itself a structure if ( dt . getTypeSort ( ) . isStructType ( ) ) { StructureMembers subsm = computemembers ( field ) ; m . setStructureMembers ( subsm ) ; } } return sm ; }


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 . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { // to print properly, cast to long and convert unsigned to signed
 long tempVal = ( ( long ) getValue ( ) ) & 0xFFFFFFFF L ; if ( print_decl_p ) { printDecl ( os , space , false ) ; os . println ( " = " + tempVal + ";" ) ; } else os . print ( tempVal ) ; }


Input: Add this as a dimension to a netCDF file [CODESPLIT] public void addDimensionsToNetcdfFile ( NetcdfFile ncfile , Group g ) { ncfile . addDimension ( g , new Dimension ( getName ( ) , getNEnsembles ( ) , true ) ) ; }


Input: test [CODESPLIT] public static void main ( String args [ ] ) { JFrame frame = new JFrame ( "Test prefs Field" ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; PrefPanel . Dialog d = new PrefPanel . Dialog ( frame , false , "title" , null , null ) ; PrefPanel pp = d . getPrefPanel ( ) ; final Field . Text tf = pp . addTextField ( "text" , "text" , "defValue" ) ; pp . setCursor ( 1 , 0 ) ; pp . addTextField ( "text2" , "text2" , "text2" ) ; //final Field.Int intf = pp.addIntField("int", "int", 66); tf . setText ( "better value" ) ; d . finish ( ) ; d . show ( ) ; JPanel main = new JPanel ( new FlowLayout ( ) ) ; frame . getContentPane ( ) . add ( main ) ; main . setPreferredSize ( new Dimension ( 200 , 200 ) ) ; frame . pack ( ) ; frame . setLocation ( 300 , 300 ) ; frame . setVisible ( true ) ; pp . addActionListener ( e -> { String text = tf . getText ( ) ; tf . setText ( text + "1" ) ; } ) ; }


Input: Construct a CrawlableDataset for the given path using the CrawlableDataset implementation indicated by the given class name . [CODESPLIT] public static CrawlableDataset createCrawlableDataset ( String path , String className , Object configObj ) throws IOException , ClassNotFoundException , NoSuchMethodException , IllegalAccessException , InvocationTargetException , InstantiationException , IllegalArgumentException , NullPointerException // throws CrDsException, IllegalArgumentException { if ( path == null ) throw new NullPointerException ( "Given path must not be null." ) ; String tmpClassName = ( className == null ? defaultClassName : className ) ; // @todo Remove alias until sure how to handle things like ".scour*" being a regular file. //    if ( CrawlableDatasetAlias.isAlias( tmpPath) ) //        return new CrawlableDatasetAlias( tmpPath, tmpClassName, configObj ); // Get the Class instance for desired CrawlableDataset implementation. Class crDsClass = Class . forName ( tmpClassName ) ; // Check that the Class is a CrawlableDataset. if ( ! CrawlableDataset . class . isAssignableFrom ( crDsClass ) ) { throw new IllegalArgumentException ( "Requested class <" + className + "> not an implementation of thredds.crawlabledataset.CrawlableDataset." ) ; } // Instantiate the desired CrawlableDataset. Class [ ] argTypes = { String . class , Object . class } ; Object [ ] args = { path , configObj } ; Constructor constructor = crDsClass . getDeclaredConstructor ( argTypes ) ; try { return ( CrawlableDataset ) constructor . newInstance ( args ) ; } catch ( InvocationTargetException e ) { if ( IOException . class . isAssignableFrom ( e . getCause ( ) . getClass ( ) ) ) throw ( IOException ) e . getCause ( ) ; else throw e ; } }


Input: Normalize the given path so that it can be used in the creation of a CrawlableDataset . This method can be used on absolute or relative paths . [CODESPLIT] public static String normalizePath ( String path ) { // Replace any occurance of a backslash ("\") with a slash ("/"). // NOTE: Both String and Pattern escape backslash, so need four backslashes to find one. // NOTE: No longer replace multiple backslashes with one slash, which allows for UNC pathnames (Windows LAN addresses). //       Was path.replaceAll( "\\\\+", "/"); String newPath = path . replaceAll ( "\\\\" , "/" ) ; // Remove trailing slashes. while ( newPath . endsWith ( "/" ) && ! newPath . equals ( "/" ) ) newPath = newPath . substring ( 0 , newPath . length ( ) - 1 ) ; return newPath ; }


Input: implement GisFeature methods : [CODESPLIT] public java . awt . geom . Rectangle2D getBounds2D ( ) { // Get the bounding box for this feature. from java.awt.geom.Rectangle2D double x0 = ( ( ( ContourLine ) ( lines . get ( 0 ) ) ) . getX ( ) ) [ 0 ] ; double y0 = ( ( ( ContourLine ) ( lines . get ( 0 ) ) ) . getY ( ) ) [ 0 ] ; double xMaxInd = x0 , xmin = x0 , yMaxInd = y0 , ymin = y0 ; for ( int i = 0 ; i < lines . size ( ) ; i ++ ) { GisPart cline = ( ContourLine ) ( lines . get ( i ) ) ; double [ ] xpts = cline . getX ( ) ; double [ ] ypts = cline . getY ( ) ; for ( int j = 0 ; j < cline . getNumPoints ( ) ; j ++ ) { if ( xpts [ j ] < xmin ) xmin = xpts [ j ] ; else if ( xpts [ j ] > xMaxInd ) xMaxInd = xpts [ j ] ; if ( ypts [ j ] < ymin ) ymin = ypts [ j ] ; else if ( ypts [ j ] > yMaxInd ) yMaxInd = ypts [ j ] ; } } // Rectangle2D.Double(double x, double y, double width, double height) Rectangle2D . Double rect = new Rectangle2D . Double ( xmin , ymin , xMaxInd - xmin , yMaxInd - ymin ) ; return rect ; }


Input:
this is where persist () reads / writes files [CODESPLIT] static public void setPersistenceCache ( DiskCache2 dc ) { diskCache2 = dc ; if ( diskCache2 != null ) diskCache2 . setAlwaysUseCache ( true ) ; // the persistence cache file has same name as the ncml - must put it into the cache else clobber ncml  7/31/2014
 }


Input: Add a nested dataset specified by an explicit netcdf element . enhance is handled by the reader so its always false here . [CODESPLIT] public void addExplicitDataset ( String cacheName , String location , String id , String ncoordS , String coordValueS , String sectionSpec , ucar . nc2 . util . cache . FileFactory reader ) { Dataset nested = makeDataset ( cacheName , location , id , ncoordS , coordValueS , sectionSpec , null , reader ) ; explicitDatasets . add ( nested ) ; }


Input:
Add a dataset scan [CODESPLIT] public void addDatasetScan ( Element crawlableDatasetElement , String dirName , String suffix , String regexpPatternString , String dateFormatMark , Set < NetcdfDataset . Enhance > enhanceMode , String subdirs , String olderThan ) { datasetManager . addDirectoryScan ( dirName , suffix , regexpPatternString , subdirs , olderThan , enhanceMode ) ; this . dateFormatMark = dateFormatMark ; if ( dateFormatMark != null ) { isDate = true ; if ( type == Type . joinExisting ) type = Type . joinExistingOne ; // tricky
 DateExtractor dateExtractor = new DateExtractorFromName ( dateFormatMark , true ) ; datasetManager . setDateExtractor ( dateExtractor ) ; } }


Input: experimental [CODESPLIT] public void addCollection ( String spec , String olderThan ) throws IOException { datasetManager = MFileCollectionManager . open ( spec , spec , olderThan , new Formatter ( ) ) ; }


Input:
all elements are processed finish construction [CODESPLIT] public void finish ( CancelTask cancelTask ) throws IOException { datasetManager . scan ( true ) ; // Make the list of Datasets, by scanning if needed.
 cacheDirty = true ; makeDatasets ( cancelTask ) ; //ucar.unidata.io.RandomAccessFile.setDebugAccess( true);
 buildNetcdfDataset ( cancelTask ) ; //ucar.unidata.io.RandomAccessFile.setDebugAccess( false);
 }


Input:
Make the list of Datasets from explicit and scans . [CODESPLIT] protected void makeDatasets ( CancelTask cancelTask ) throws IOException { // heres where the results will go
 datasets = new ArrayList <> ( ) ; for ( MFile cd : datasetManager . getFilesSorted ( ) ) { datasets . add ( makeDataset ( cd ) ) ; } // sort using Aggregation.Dataset as Comparator.
 // Sort by date if it exists, else filename.
 Collections . sort ( datasets ) ; /* optionally extract the date
      String dateCoordS = null;
      if (null != dateFormatMark) {
        String filename = myf.getName(); // LOOK operates on name, not path
        Date dateCoord = DateFromString.getDateUsingDemarkatedCount(filename, dateFormatMark, '#');
        dateCoordS = formatter.toDateTimeStringISO(dateCoord);
        if (debugDateParse) System.out.println("  adding " + myf.getPath() + " date= " + dateCoordS);
      } else {
        if (debugDateParse) System.out.println("  adding " + myf.getPath());
      }

      String location = myf.getPath();
      Aggregation.Dataset ds = makeDataset(location, location, null, null, dateCoordS, null, enhance, null);
      datasets.add(ds);
    }

    // Sort by date if it exists, else filename.
    Collections.sort(datasets, new Comparator<Aggregation.Dataset>() {
      public int compare(Aggregation.Dataset ds1, Aggregation.Dataset ds2) {
        if(ds1.cd == null)
           return ds1.getLocation().compareTo(ds2.getLocation()) ;
        if (ds1.cd.dateCoord != null) // LOOK can we generalize
          return ds1.cd.dateCoord.compareTo(ds2.cd.dateCoord);
        else
          return ds1.cd.file.getName().compareTo(ds2.cd.file.getName());
      }
    });  */ // add the explicit datasets - these need to be kept in order
 // LOOK - should they be before or after scanned? Does it make sense to mix scan and explicit?
 // AggFmrcSingle sets explicit datasets - the scan is empty
 for ( Aggregation . Dataset dataset : explicitDatasets ) { datasets . add ( dataset ) ; } // Remove unreadable files (i.e. due to permissions) from the aggregation.
 // LOOK: Is this logic we should install "upstream", perhaps in MFileCollectionManager?
 // It would affect other collections than just NcML aggregation in that case.
 for ( Iterator < Dataset > datasetsIter = datasets . iterator ( ) ; datasetsIter . hasNext ( ) ; ) { Dataset dataset = datasetsIter . next ( ) ; Path datasetPath ; if ( dataset . getMFile ( ) instanceof MFileOS ) { datasetPath = ( ( MFileOS ) dataset . getMFile ( ) ) . getFile ( ) . toPath ( ) ; } else if ( dataset . getMFile ( ) instanceof MFileOS7 ) { datasetPath = ( ( MFileOS7 ) dataset . getMFile ( ) ) . getNioPath ( ) ; } else { continue ; } if ( ! Files . isReadable ( datasetPath ) ) { // File.canRead() is broken on Windows, but the JDK7 methods work.
 logger . warn ( "Aggregation member isn't readable (permissions issue?). Skipping: " + datasetPath ) ; datasetsIter . remove ( ) ; } } // check for duplicate location
 Set < String > dset = new HashSet <> ( 2 * datasets . size ( ) ) ; for ( Aggregation . Dataset dataset : datasets ) { if ( dset . contains ( dataset . cacheLocation ) ) logger . warn ( "Duplicate dataset in aggregation = " + dataset . cacheLocation ) ; dset . add ( dataset . cacheLocation ) ; } if ( datasets . size ( ) == 0 ) { throw new IllegalStateException ( "There are no datasets in the aggregation " + datasetManager ) ; } }


Input:
Open one of the nested datasets as a template for the aggregation dataset . [CODESPLIT] protected Dataset getTypicalDataset ( ) throws IOException { List < Dataset > nestedDatasets = getDatasets ( ) ; int n = nestedDatasets . size ( ) ; if ( n == 0 ) throw new FileNotFoundException ( "No datasets in this aggregation" ) ; int select ; if ( typicalDatasetMode == TypicalDataset . LATEST ) select = n - 1 ; else if ( typicalDatasetMode == TypicalDataset . PENULTIMATE ) select = ( n < 2 ) ? 0 : n - 2 ; else if ( typicalDatasetMode == TypicalDataset . FIRST ) select = 0 ; else { // random is default
 if ( r == null ) r = new Random ( ) ; select = ( n < 2 ) ? 0 : r . nextInt ( n ) ; } return nestedDatasets . get ( select ) ; }


Input:
Dataset factory so subclasses can override [CODESPLIT] protected Dataset makeDataset ( String cacheName , String location , String id , String ncoordS , String coordValueS , String sectionSpec , EnumSet < NetcdfDataset . Enhance > enhance , ucar . nc2 . util . cache . FileFactory reader ) { return new Dataset ( cacheName , location , id , enhance , reader ) ; // overridden in OuterDim, tiled
 }


Input: All non - agg variables use a proxy to acquire the file before reading . If the variable is caching read data into cache now . If not caching VariableEnhanced . setProxyReader () is called . [CODESPLIT] protected void setDatasetAcquireProxy ( Dataset typicalDataset , NetcdfDataset newds ) throws IOException { DatasetProxyReader proxy = new DatasetProxyReader ( typicalDataset ) ; setDatasetAcquireProxy ( proxy , newds . getRootGroup ( ) ) ; }


Input:
This tracks Dataset elements that have resource control attributes [CODESPLIT] void putResourceControl ( Dataset ds ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( "putResourceControl " + ds . getRestrictAccess ( ) + " for " + ds . getName ( ) ) ; resourceControlHash . put ( ds . getUrlPath ( ) , ds . getRestrictAccess ( ) ) ; // resourceControl is inherited, but no guarentee that children paths are related, unless its a //   DatasetScan or InvDatasetFmrc. So we keep track of all datasets that have a ResourceControl, including children // DatasetScan and InvDatasetFmrc must use a PathMatcher, others can use exact match (hash) /* if (ds instanceof DatasetScan) {
      DatasetScan scan = (DatasetScan) ds;
      if (debugResourceControl)
        System.out.println("putResourceControl " + ds.getRestrictAccess() + " for datasetScan " + scan.getPath());
      resourceControlMatcher.put(scan.getPath(), ds.getRestrictAccess());

    } else { // dataset
      if (debugResourceControl)
        System.out.println("putResourceControl " + ds.getRestrictAccess() + " for dataset " + ds.getUrlPath());

      // LOOK: seems like you only need to add if InvAccess.InvService.isReletive
      // LOOK: seems like we should use resourceControlMatcher to make sure we match .dods, etc
      for (Access access : ds.getAccess()) {
        if (access.getService().isRelativeBase())
          resourceControlHash.put(access.getUrlPath(), ds.getRestrictAccess());
      }
    }  */ hasResourceControl = true ; }


Input: Add a point to the end of the line . [CODESPLIT] public void addPoint ( double x , double y ) { Point ptPrev = null ; if ( points . size ( ) > 0 ) { ptPrev = points . get ( points . size ( ) - 1 ) ; } this . points . add ( new CFPoint ( x , y , ptPrev , null , null ) ) ; }


Input: Sets the previous line which makes up the multiline which this line is a part of . If prev is a CFLine automatically connect the other line to this line as well . [CODESPLIT] public void setNext ( Line next ) { if ( next instanceof CFLine ) { setNext ( ( CFLine ) next ) ; } else this . next = next ; }


Input: Sets the previous line which makes up the multiline which this line is a part of . If prev is a CFLine automatically connect the other line to this line as well . [CODESPLIT] public void setPrev ( Line prev ) { if ( prev instanceof CFLine ) { setPrev ( ( CFLine ) prev ) ; } else this . prev = prev ; }


Input:
Given a dataset variable and index automatically populates this Line and returns it . If not found returns null . [CODESPLIT] public Line setupLine ( NetcdfDataset dataset , Variable var , int index ) { this . points . clear ( ) ; Array xPts = null ; Array yPts = null ; Variable nodeCounts = null ; Variable partNodeCounts = null ; List < CoordinateAxis > axes = dataset . getCoordinateAxes ( ) ; CoordinateAxis x = null ; CoordinateAxis y = null ; String [ ] nodeCoords = var . findAttributeIgnoreCase ( CF . NODE_COORDINATES ) . getStringValue ( ) . split ( " " ) ; // Look for x and y
 for ( CoordinateAxis ax : axes ) { if ( ax . getFullName ( ) . equals ( nodeCoords [ 0 ] ) ) x = ax ; if ( ax . getFullName ( ) . equals ( nodeCoords [ 1 ] ) ) y = ax ; } // Affirm node counts
 String node_c_str = var . findAttValueIgnoreCase ( CF . NODE_COUNT , "" ) ; if ( ! node_c_str . equals ( "" ) ) { nodeCounts = dataset . findVariable ( node_c_str ) ; } else return null ; // Affirm part node counts
 String pNodeCoStr = var . findAttValueIgnoreCase ( CF . PART_NODE_COUNT , "" ) ; if ( ! pNodeCoStr . equals ( "" ) ) { partNodeCounts = dataset . findVariable ( pNodeCoStr ) ; } SimpleGeometryIndexFinder indexFinder = new SimpleGeometryIndexFinder ( nodeCounts ) ; //Get beginning and ending indicies for this polygon
 int lower = indexFinder . getBeginning ( index ) ; int upper = indexFinder . getEnd ( index ) ; try { xPts = x . read ( lower + ":" + upper ) . reduce ( ) ; yPts = y . read ( lower + ":" + upper ) . reduce ( ) ; IndexIterator itrX = xPts . getIndexIterator ( ) ; IndexIterator itrY = yPts . getIndexIterator ( ) ; // No multipolygons just read in the whole thing
 if ( partNodeCounts == null ) { this . next = null ; this . prev = null ; // x and y should have the same shape, will add some handling on this
 while ( itrX . hasNext ( ) ) { this . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; } switch ( var . getRank ( ) ) { case 2 : this . setData ( var . read ( CFSimpleGeometryHelper . getSubsetString ( var , index ) ) . reduce ( ) ) ; break ; case 1 : this . setData ( var . read ( "" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations
 } } // If there are multipolygons then take the upper and lower of it and divy it up
 else { Line tail = this ; Array pnc = partNodeCounts . read ( ) ; IndexIterator pncItr = pnc . getIndexIterator ( ) ; // In part node count search for the right index to begin looking for "part node counts"
 int pncInd = 0 ; int pncEnd = 0 ; while ( pncEnd < lower ) { pncEnd += pncItr . getIntNext ( ) ; pncInd ++ ; } // Now the index is found, use part node count and the index to find each part node count of each individual part
 while ( lower < upper ) { int smaller = pnc . getInt ( pncInd ) ; while ( smaller > 0 ) { tail . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; smaller -- ; } // Set data of each
 switch ( var . getRank ( ) ) { case 2 : tail . setData ( var . read ( CFSimpleGeometryHelper . getSubsetString ( var , index ) ) . reduce ( ) ) ; break ; case 1 : tail . setData ( var . read ( "" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations
 } lower += tail . getPoints ( ) . size ( ) ; pncInd ++ ; tail . setNext ( new CFLine ( ) ) ; tail = tail . getNext ( ) ; } //Clean up
 tail = tail . getPrev ( ) ; if ( tail != null ) tail . setNext ( null ) ; } } catch ( IOException | InvalidRangeException | InvalidDataseriesException e ) { cfl . error ( e . getMessage ( ) ) ; ; return null ; } return this ; }


Input:
Gets the upper bounding box coordinate on the line . [CODESPLIT] public double [ ] getBBUpper ( ) { double [ ] bbUpper = new double [ 2 ] ; List < Point > ptList = this . getPoints ( ) ; if ( ptList . isEmpty ( ) ) return null ; bbUpper [ 0 ] = ptList . get ( 0 ) . getY ( ) ; bbUpper [ 1 ] = ptList . get ( 0 ) . getY ( ) ; for ( Point pt : this . getPoints ( ) ) { if ( bbUpper [ 0 ] < pt . getX ( ) ) { bbUpper [ 0 ] = pt . getX ( ) ; } if ( bbUpper [ 1 ] < pt . getY ( ) ) { bbUpper [ 1 ] = pt . getY ( ) ; } } // Got maximum points, add some padding.
 bbUpper [ 0 ] += 10 ; bbUpper [ 1 ] += 10 ; return bbUpper ; }


Input:
Gets the lower bounding box coordinate on the line . [CODESPLIT] public double [ ] getBBLower ( ) { double [ ] bbLower = new double [ 2 ] ; List < Point > ptList = this . getPoints ( ) ; if ( ptList . isEmpty ( ) ) return null ; bbLower [ 0 ] = ptList . get ( 0 ) . getY ( ) ; bbLower [ 1 ] = ptList . get ( 0 ) . getY ( ) ; for ( Point pt : this . getPoints ( ) ) { if ( bbLower [ 0 ] > pt . getX ( ) ) { bbLower [ 0 ] = pt . getX ( ) ; } if ( bbLower [ 1 ] > pt . getY ( ) ) { bbLower [ 1 ] = pt . getY ( ) ; } } // Got minimum points, add some padding.
 bbLower [ 0 ] -= 10 ; bbLower [ 1 ] -= 10 ; return bbLower ; }


Input: Validate this DatasetFilter object . Return true if valid false if invalid . [CODESPLIT] boolean validate ( StringBuilder out ) { this . isValid = true ; // If log from construction has content, append to validation output msg. if ( this . log . length ( ) > 0 ) { out . append ( this . log ) ; } // Validity check: 'name' cannot be null. (Though, 'name' // can be an empty string.) if ( this . getName ( ) == null ) { isValid = false ; out . append ( " ** DatasetFilter (4): null value for name is not valid." ) ; } // Check that type is not null. if ( this . getType ( ) == null ) { isValid = false ; out . append ( " ** DatasetFilter (5): null value for type is not valid (set with bad string?)." ) ; } // Validity check: 'matchPattern' must be null if 'type' value // is not 'RegExp'. if ( this . type == DatasetFilter . Type . REGULAR_EXPRESSION && this . matchPattern == null ) { isValid = false ; out . append ( " ** DatasetFilter (6): null value for matchPattern not valid when type is 'RegExp'." ) ; } if ( this . type != DatasetFilter . Type . REGULAR_EXPRESSION && this . type != null && this . matchPattern != null ) { isValid = false ; out . append ( " ** DatasetFilter (7): matchPattern value (" + this . matchPattern + ") must be null if type is not 'RegExp'." ) ; } return ( this . isValid ) ; }


Input: Test whether the given dataset matches the filter criteria . [CODESPLIT] private boolean match ( InvDataset dataset ) { // Check whether this filter applies to the given dataset. if ( this . getParentDatasetSource ( ) . isCollection ( dataset ) && ! this . applyToCollectionDatasets ) return ( false ) ; if ( ( ! this . getParentDatasetSource ( ) . isCollection ( dataset ) ) && ! this . applyToAtomicDatasets ) return ( false ) ; // Set the default matchPatternTarget so old versions still work. if ( this . matchPatternTarget == null ) { if ( this . getParentDatasetSource ( ) . isCollection ( dataset ) ) { this . setMatchPatternTarget ( "name" ) ; } else { this . setMatchPatternTarget ( "urlPath" ) ; } } if ( this . type == DatasetFilter . Type . REGULAR_EXPRESSION ) { boolean isMatch ; if ( this . getMatchPatternTarget ( ) . equals ( "name" ) ) { java . util . regex . Matcher matcher = this . regExpPattern . matcher ( dataset . getName ( ) ) ; isMatch = matcher . find ( ) ; } else if ( this . getMatchPatternTarget ( ) . equals ( "urlPath" ) ) { java . util . regex . Matcher matcher = this . regExpPattern . matcher ( ( ( InvDatasetImpl ) dataset ) . getUrlPath ( ) ) ; isMatch = matcher . find ( ) ; } else { // ToDo deal with any matchPatternTarget (XPath-ish) isMatch = false ; } //      // Invert the meaning of a match (accept things that don't match). //      if ( this.isRejectMatchingDatasets()) //      { //        // If match, return false. //        return( regExpMatch == null ? true : false ); //      } //      // Don't invert (a match is a match). //      else //      { // If match, return true. return ( isMatch ) ; //      } } else { System . err . println ( "WARNING -- DatasetFilter.accept(): unsupported type" + " <" + this . type . toString ( ) + ">." ) ; return ( false ) ; // @todo think about exceptions. //throw new java.lang.Exception( "DatasetFilter.accept():" + //  " unsupported type <" + this.type.toString() + ">."); } }


Input: Given a dataset and a group of filters return true if the group of filters indicates that the dataset should be accepted false if it should be rejected . <p / > To make filtering out a set of datasets as easy as allowing a set of datasets DatasetFilter provides a dataset reject mode as well as a dataset accept mode . Rejection of a dataset by any filter overrides acceptance by any number of filters . Therefore to be accepted by the group a dataset needs to be accepted by at least one filter however rejection by a single filter will cause rejection by the group . <p / > If the filter group is empty the dataset will be accepted . [CODESPLIT] public static boolean acceptDatasetByFilterGroup ( List filters , InvDataset dataset , boolean isCollectionDataset ) { if ( filters == null ) throw new NullPointerException ( "Given null list of filters." ) ; if ( dataset == null ) throw new NullPointerException ( "Given null dataset." ) ; // If not filters, accept all datasets. if ( filters . isEmpty ( ) ) return ( true ) ; // Loop through DatasetFilter list to check if current dataset should be accepted. // @todo If none of the filters apply to directories, accept all directories. boolean accept = false ; boolean anyApplyToAtomic = false ; boolean anyApplyToCollection = false ; for ( Iterator it = filters . iterator ( ) ; it . hasNext ( ) ; ) { DatasetFilter curFilter = ( DatasetFilter ) it . next ( ) ; anyApplyToAtomic |= curFilter . isApplyToAtomicDatasets ( ) ; anyApplyToCollection |= curFilter . isApplyToCollectionDatasets ( ) ; if ( curFilter . isAcceptMatchingDatasets ( ) ) { if ( curFilter . accept ( dataset ) ) { accept = true ; // Dataset accepted by current DatasetFilter. } } else // if ( ! curFilter.isAcceptMatchingDatasets()) { if ( curFilter . reject ( dataset ) ) { return ( false ) ; // Rejection takes precedence over accpetance } } } // At least one filter accepted (and none rejected), so accept. if ( accept ) return ( true ) ; // Check if any filters apply to dataset. If none apply, accept the dataset. if ( isCollectionDataset ) { if ( ! anyApplyToCollection ) return ( true ) ; // Collection ds, no collection filters. } else { if ( ! anyApplyToAtomic ) return ( true ) ; // Atomic ds, no atomic filters. } // Dataset not accepted or rejected by any DatasetFilter (so reject). return ( false ) ; }


Input: fdPoint remains open . [CODESPLIT] public void addAll ( FeatureDatasetPoint fdPoint ) throws IOException { try ( PointFeatureIterator pointFeatIter = new FlattenedDatasetPointCollection ( fdPoint ) . getPointFeatureIterator ( ) ) { while ( pointFeatIter . hasNext ( ) ) { StationPointFeature pointFeat = ( StationPointFeature ) pointFeatIter . next ( ) ; add ( pointFeat ) ; } } }


Input: Double - check idiom for lazy initialization of instance fields . See Effective Java 2nd Ed p . 283 . [CODESPLIT] private StationFeatureCopyFactory getStationFeatureCopyFactory ( StationPointFeature proto ) throws IOException { if ( stationFeatCopyFactory == null ) { synchronized ( this ) { if ( stationFeatCopyFactory == null ) { stationFeatCopyFactory = createStationFeatureCopyFactory ( proto ) ; } } } assert stationFeatCopyFactory != null : "We screwed this up." ; return stationFeatCopyFactory ; }


Input: Parse a constraint expression . Variables in the projection are marked as such in the CEEvaluator s ServerDDS instance . The selection subexpression is then parsed and a list of Clause objects is built . <p / > The parser is located in opendap . servers . parsers . CeParser . [CODESPLIT] public void parseConstraint ( String constraint , String urlencoded ) throws ParseException , opendap . dap . DAP2Exception , NoSuchVariableException , NoSuchFunctionException , InvalidOperatorException , InvalidParameterException , SBHException , WrongTypeException { if ( clauseFactory == null ) { clauseFactory = new ClauseFactory ( ) ; } // Parses constraint expression (duh...) and sets the // projection flag for each member of the CE's ServerDDS // instance. This also builds the list of clauses. try { CeParser . constraint_expression ( this , _dds . getFactory ( ) , clauseFactory , constraint , urlencoded ) ; } catch ( ConstraintException ce ) { // convert to a DAP2Exception ce . printStackTrace ( ) ; throw new DAP2Exception ( ce ) ; } if ( _Debug ) { int it = 0 ; Enumeration ec = getClauses ( ) ; System . out . println ( "Results of clause parsing:" ) ; if ( ! ec . hasMoreElements ( ) ) System . out . println ( "    No Clauses Found." ) ; while ( ec . hasMoreElements ( ) ) { it ++ ; System . out . println ( "    Clause " + it + ": " + ec . nextElement ( ) ) ; } } }


Input: Convenience wrapper for parseConstraint . [CODESPLIT] public void parseConstraint ( ReqState rs ) throws ParseException , opendap . dap . DAP2Exception , NoSuchVariableException , NoSuchFunctionException , InvalidOperatorException , InvalidParameterException , SBHException , WrongTypeException { parseConstraint ( rs . getConstraintExpression ( ) , rs . getRequestURL ( ) . toString ( ) ) ; }


Input: This function sends the variables described in the constrained DDS to the output described by <code > sink< / code > . This function calls <code > parse_constraint () < / code > <code > BaseType :: read () < / code > and <code > ServerIO :: serialize () < / code > . [CODESPLIT] public void send ( String dataset , OutputStream sink , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { Enumeration e = _dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { ServerMethods s = ( ServerMethods ) e . nextElement ( ) ; if ( _Debug ) System . out . println ( "Sending variable: " + ( ( BaseType ) s ) . getEncodedName ( ) ) ; if ( s . isProject ( ) ) { if ( _Debug ) System . out . println ( "Calling " + ( ( BaseType ) s ) . getTypeName ( ) + ".serialize() (Name: " + ( ( BaseType ) s ) . getEncodedName ( ) + ")" ) ; //System.out.printf("serialize %s (%s) start=%d%n ", ((BaseType) s).getName(), ((BaseType) s).getTypeName(), //    ((DataOutputStream) sink).size()); s . serialize ( dataset , ( DataOutputStream ) sink , this , specialO ) ; } } //System.out.printf("serialize total size=%d%n ", ((DataOutputStream) sink).size()); }


Input: Evaluate all of the Clauses in the Clause vector . [CODESPLIT] public boolean evalClauses ( Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { boolean result = true ; Enumeration ec = getClauses ( ) ; while ( ec . hasMoreElements ( ) && result == true ) { Object o = ec . nextElement ( ) ; if ( _Debug ) { System . out . println ( "Evaluating clause: " + ec . nextElement ( ) ) ; } result = ( ( TopLevelClause ) o ) . evaluate ( ) ; } // Hack: pop the projections of all DArrayDimensions that // have been pushed. return ( result ) ; }


Input: Mark all the variables in the DDS either as part of the current projection ( when <code > state< / code > is true ) or not ( <code > state< / code > is false ) . This is a convenience function that provides a way to clear or set an entire dataset described by a DDS with respect to its projection . [CODESPLIT] public void markAll ( boolean state ) throws DAP2Exception , NoSuchVariableException , SBHException { // For all the Variables in the DDS Enumeration e = _dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { // Get the thing Object o = e . nextElement ( ) ; //- Clip this to stop marking all dimensions of Grids and Arrays // If we are marking all for true, then we need to make sure // we get all the parts of each array and grid // This code should probably be moved into SDArray and SDGrid. // There we should add a resetProjections() method that changes // the current projection to be the entire array. 11/18/99 jhrg if ( state ) { if ( o instanceof SDArray ) { // Is this thing a SDArray? SDArray SDA = ( SDArray ) o ; // Get it's DArrayDimensions Enumeration eSDA = SDA . getDimensions ( ) ; while ( eSDA . hasMoreElements ( ) ) { DArrayDimension dad = ( DArrayDimension ) eSDA . nextElement ( ) ; // Tweak it's projection state dad . setProjection ( 0 , 1 , dad . getSize ( ) - 1 ) ; } } else if ( o instanceof SDGrid ) { // Is this thing a SDGrid? SDGrid SDG = ( SDGrid ) o ; SDArray sdgA = ( SDArray ) SDG . getVar ( 0 ) ; // Get it's internal SDArray. // Get it's DArrayDimensions Enumeration eSDA = sdgA . getDimensions ( ) ; while ( eSDA . hasMoreElements ( ) ) { DArrayDimension dad = ( DArrayDimension ) eSDA . nextElement ( ) ; // Tweak it's projection state dad . setProjection ( 0 , 1 , dad . getSize ( ) - 1 ) ; } } } //-------------------------- End Clip --------------------------- ServerMethods s = ( ServerMethods ) o ; s . setProject ( state ) ; } }


Input: Print all of the Clauses in the Clause vector . [CODESPLIT] public void printConstraint ( PrintWriter pw ) { Enumeration ec = getClauses ( ) ; boolean first = true ; while ( ec . hasMoreElements ( ) ) { Clause cl = ( Clause ) ec . nextElement ( ) ; if ( ! first ) pw . print ( " & " ) ; cl . printConstraint ( pw ) ; first = false ; } pw . flush ( ) ; }


Input: Amend the given NetcdfFile with metadata from HDF - EOS structMetadata . All Variables named StructMetadata . n where n = 1 2 3 ... are read in and their contents concatenated to make the structMetadata String . [CODESPLIT] static public boolean amendFromODL ( NetcdfFile ncfile , Group eosGroup ) throws IOException { String smeta = getStructMetadata ( eosGroup ) ; if ( smeta == null ) { return false ; } HdfEos fixer = new HdfEos ( ) ; fixer . fixAttributes ( ncfile . getRootGroup ( ) ) ; fixer . amendFromODL ( ncfile , smeta ) ; return true ; }


Input:
Amend the given NetcdfFile with metadata from HDF - EOS structMetadata [CODESPLIT] private void amendFromODL ( NetcdfFile ncfile , String structMetadata ) throws IOException { Group rootg = ncfile . getRootGroup ( ) ; ODLparser parser = new ODLparser ( ) ; Element root = parser . parseFromString ( structMetadata ) ; // now we have the ODL in JDOM elements
 FeatureType featureType = null ; // SWATH
 Element swathStructure = root . getChild ( "SwathStructure" ) ; if ( swathStructure != null ) { List < Element > swaths = swathStructure . getChildren ( ) ; for ( Element elemSwath : swaths ) { Element swathNameElem = elemSwath . getChild ( "SwathName" ) ; if ( swathNameElem == null ) { log . warn ( "No SwathName element in {} {} " , elemSwath . getName ( ) , ncfile . getLocation ( ) ) ; continue ; } String swathName = NetcdfFile . makeValidCdmObjectName ( swathNameElem . getText ( ) . trim ( ) ) ; Group swathGroup = findGroupNested ( rootg , swathName ) ; //if (swathGroup == null)
 //  swathGroup = findGroupNested(rootg, H4header.createValidObjectName(swathName));
 if ( swathGroup != null ) { featureType = amendSwath ( ncfile , elemSwath , swathGroup ) ; } else { log . warn ( "Cant find swath group {} {}" , swathName , ncfile . getLocation ( ) ) ; } } } // GRID
 Element gridStructure = root . getChild ( "GridStructure" ) ; if ( gridStructure != null ) { List < Element > grids = gridStructure . getChildren ( ) ; for ( Element elemGrid : grids ) { Element gridNameElem = elemGrid . getChild ( "GridName" ) ; if ( gridNameElem == null ) { log . warn ( "No GridName element in {} {} " , elemGrid . getName ( ) , ncfile . getLocation ( ) ) ; continue ; } String gridName = NetcdfFile . makeValidCdmObjectName ( gridNameElem . getText ( ) . trim ( ) ) ; Group gridGroup = findGroupNested ( rootg , gridName ) ; //if (gridGroup == null)
 //  gridGroup = findGroupNested(rootg, H4header.createValidObjectName(gridName));
 if ( gridGroup != null ) { featureType = amendGrid ( elemGrid , ncfile , gridGroup , ncfile . getLocation ( ) ) ; } else { log . warn ( "Cant find Grid group {} {}" , gridName , ncfile . getLocation ( ) ) ; } } } // POINT - NOT DONE YET
 Element pointStructure = root . getChild ( "PointStructure" ) ; if ( pointStructure != null ) { List < Element > pts = pointStructure . getChildren ( ) ; for ( Element elem : pts ) { Element nameElem = elem . getChild ( "PointName" ) ; if ( nameElem == null ) { log . warn ( "No PointName element in {} {}" , elem . getName ( ) , ncfile . getLocation ( ) ) ; continue ; } String name = nameElem . getText ( ) . trim ( ) ; Group ptGroup = findGroupNested ( rootg , name ) ; //if (ptGroup == null)
 //  ptGroup = findGroupNested(rootg, H4header.createValidObjectName(name));
 if ( ptGroup != null ) { featureType = FeatureType . POINT ; } else { log . warn ( "Cant find Point group {} {}" , name , ncfile . getLocation ( ) ) ; } } } if ( featureType != null ) { if ( showWork ) { log . debug ( "***EOS featureType= {}" , featureType . toString ( ) ) ; } rootg . addAttribute ( new Attribute ( CF . FEATURE_TYPE , featureType . toString ( ) ) ) ; // rootg.addAttribute(new Attribute(CDM.CONVENTIONS, "HDFEOS"));
 } }


Input:
convert to shared dimensions [CODESPLIT] private void setSharedDimensions ( Variable v , List < Element > values , List < Dimension > unknownDims , String location ) { if ( values . size ( ) == 0 ) { return ; } // remove the "scalar" dumbension
 Iterator < Element > iter = values . iterator ( ) ; while ( iter . hasNext ( ) ) { Element value = iter . next ( ) ; String dimName = value . getText ( ) . trim ( ) ; if ( dimName . equalsIgnoreCase ( "scalar" ) ) { iter . remove ( ) ; } } // gotta have same number of dimensions
 List < Dimension > oldDims = v . getDimensions ( ) ; if ( oldDims . size ( ) != values . size ( ) ) { log . error ( "Different number of dimensions for {} {}" , v , location ) ; return ; } List < Dimension > newDims = new ArrayList <> ( ) ; Group group = v . getParentGroup ( ) ; for ( int i = 0 ; i < values . size ( ) ; i ++ ) { Element value = values . get ( i ) ; String dimName = value . getText ( ) . trim ( ) ; dimName = NetcdfFile . makeValidCdmObjectName ( dimName ) ; Dimension dim = group . findDimension ( dimName ) ; Dimension oldDim = oldDims . get ( i ) ; if ( dim == null ) { dim = checkUnknownDims ( dimName , unknownDims , oldDim , location ) ; } if ( dim == null ) { log . error ( "Unknown Dimension= {} for variable = {} {} " , dimName , v . getFullName ( ) , location ) ; return ; } if ( dim . getLength ( ) != oldDim . getLength ( ) ) { log . error ( "Shared dimension ({}) has different length than data dimension ({}) shared={} org={} for {} {}" , dim . getShortName ( ) , oldDim . getShortName ( ) , dim . getLength ( ) , oldDim . getLength ( ) , v , location ) ; return ; } newDims . add ( dim ) ; } v . setDimensions ( newDims ) ; if ( showWork ) { log . debug ( " set shared dimensions for {}" , v . getNameAndDimensions ( ) ) ; } }


Input:
look if the wanted dimension is in the unknownDims list . [CODESPLIT] private Dimension checkUnknownDims ( String wantDim , List < Dimension > unknownDims , Dimension oldDim , String location ) { for ( Dimension dim : unknownDims ) { if ( dim . getShortName ( ) . equals ( wantDim ) ) { int len = oldDim . getLength ( ) ; if ( len == 0 ) { dim . setUnlimited ( true ) ; // allow zero length dimension !!
 } dim . setLength ( len ) ; // use existing (anon) dimension
 Group parent = dim . getGroup ( ) ; parent . addDimensionIfNotExists ( dim ) ; // add to the parent
 unknownDims . remove ( dim ) ; // remove from list LOOK is this ok?
 log . warn ( "unknownDim {} length set to {}{}" , wantDim , oldDim . getLength ( ) , location ) ; return dim ; } } return null ; }


Input: look for a group with the given name . recurse into subgroups if needed . breadth first [CODESPLIT] private Group findGroupNested ( Group parent , String name ) { for ( Group g : parent . getGroups ( ) ) { if ( g . getShortName ( ) . equals ( name ) ) { return g ; } } for ( Group g : parent . getGroups ( ) ) { Group result = findGroupNested ( g , name ) ; if ( result != null ) { return result ; } } return null ; }


Input: Get inline content as a string else null if there is none [CODESPLIT] public String readXlinkContent ( ) throws java . io . IOException { if ( uri == null ) return "" ; URL url = uri . toURL ( ) ; InputStream is = url . openStream ( ) ; ByteArrayOutputStream os = new ByteArrayOutputStream ( is . available ( ) ) ; // copy to string byte [ ] buffer = new byte [ 1024 ] ; while ( true ) { int bytesRead = is . read ( buffer ) ; if ( bytesRead == - 1 ) break ; os . write ( buffer , 0 , bytesRead ) ; } is . close ( ) ; return new String ( os . toByteArray ( ) , CDM . utf8Charset ) ; }


Input: Get the standard URL with resolution if the URL is reletive . catalog . resolveURI ( getUnresolvedUrlName () ) [CODESPLIT] public String getStandardUrlName ( ) { URI uri = getStandardUri ( ) ; if ( uri == null ) return null ; return uri . toString ( ) ; }


Input: Construct the standard THREDDS access URI for this dataset access method resolve if the URI is relative . [CODESPLIT] public URI getStandardUri ( ) { try { InvCatalog cat = dataset . getParentCatalog ( ) ; if ( cat == null ) return new URI ( getUnresolvedUrlName ( ) ) ; return cat . resolveUri ( getUnresolvedUrlName ( ) ) ; } catch ( java . net . URISyntaxException e ) { logger . warn ( "Error parsing URL= " + getUnresolvedUrlName ( ) ) ; return null ; } }


Input: ********************************************************************** Parse the . ini file indicated by the <code > private String iniFile< / code > . [CODESPLIT] private void parseFile ( ) { try { try ( BufferedReader fp = new BufferedReader ( new InputStreamReader ( new FileInputStream ( iniFile ) , Charset . forName ( "UTF-8" ) ) ) ; ) { boolean done = false ; while ( ! done ) { String thisLine = fp . readLine ( ) ; if ( thisLine != null && thisLine . trim ( ) . length ( ) == 0 ) thisLine = null ; if ( thisLine != null ) { if ( Debug ) System . out . println ( "Read: \"" + thisLine + "\"" ) ; if ( thisLine . startsWith ( ";" ) || thisLine . equalsIgnoreCase ( "" ) ) { // Do nothing, it's a comment if ( Debug ) System . out . println ( "Ignoring comment or blank line..." ) ; } else { int cindx = thisLine . indexOf ( ";" ) ; if ( cindx > 0 ) thisLine = thisLine . substring ( 0 , cindx ) . trim ( ) ; if ( Debug ) System . out . println ( "Comments removed: \"" + thisLine + "\"" ) ; if ( thisLine . startsWith ( "[" ) && thisLine . endsWith ( "]" ) ) { String sname = thisLine . substring ( 1 , thisLine . length ( ) - 1 ) . trim ( ) ; if ( Debug ) System . out . println ( "Found Section Name: " + sname ) ; if ( sectionNames == null ) sectionNames = new Vector ( ) ; sectionNames . add ( sname ) ; if ( sectionProperties == null ) sectionProperties = new Vector ( ) ; sectionProperties . add ( new Vector ( ) ) ; } else if ( sectionNames != null && sectionProperties != null ) { int eqidx = thisLine . indexOf ( "=" ) ; if ( eqidx != - 1 ) { String pair [ ] = new String [ 2 ] ; pair [ 0 ] = thisLine . substring ( 0 , eqidx ) . trim ( ) ; pair [ 1 ] = thisLine . substring ( eqidx + 1 , thisLine . length ( ) ) . trim ( ) ; if ( Debug ) System . out . println ( "pair[0]: \"" + pair [ 0 ] + "\"   pair[1]: \"" + pair [ 1 ] + "\"" ) ; // Add the pair to the current property list, which is the // last element in the sectionProperties vector. ( ( Vector ) sectionProperties . lastElement ( ) ) . add ( pair ) ; } } } } else { done = true ; } } } } catch ( FileNotFoundException e ) { System . err . println ( "Could Not Find ini File: \"" + iniFile + "\"" ) ; } catch ( IOException e ) { System . err . println ( "Could Not Read ini File: \"" + iniFile + "\"" ) ; } }


Input: ********************************************************************** Get the list of properties for the section <code > sectionName< / code > . [CODESPLIT] public Enumeration getPropList ( String sectionName ) { if ( sectionNames == null ) { System . err . println ( errMsg ) ; return ( null ) ; } int sectionIndex = 0 ; Enumeration e = sectionNames . elements ( ) ; boolean done = false ; while ( ! done && e . hasMoreElements ( ) ) { String thisName = ( String ) e . nextElement ( ) ; if ( sectionName . equalsIgnoreCase ( thisName ) ) done = true ; else sectionIndex ++ ; } if ( ! done ) return ( null ) ; return ( ( ( Vector ) sectionProperties . elementAt ( sectionIndex ) ) . elements ( ) ) ; }


Input: ********************************************************************** Get the named property from the current section . [CODESPLIT] public String getProperty ( String propertyName ) { if ( currentSection < 0 ) { String msg = "You must use the setSection() method before you can use getProperty()." ; System . err . println ( msg ) ; return ( msg ) ; } String pair [ ] = null ; Enumeration e = ( ( Vector ) sectionProperties . elementAt ( currentSection ) ) . elements ( ) ; boolean done = false ; while ( ! done && e . hasMoreElements ( ) ) { pair = ( String [ ] ) e . nextElement ( ) ; if ( pair [ 0 ] . equalsIgnoreCase ( propertyName ) ) done = true ; } if ( done ) return ( pair [ 1 ] ) ; return ( null ) ; }


Input: ********************************************************************** Prints the iniFile . [CODESPLIT] public void printProps ( PrintStream ps ) { Enumeration se = getSectionList ( ) ; if ( se == null ) { ps . println ( errMsg ) ; } else { while ( se . hasMoreElements ( ) ) { String sname = ( String ) se . nextElement ( ) ; setSection ( sname ) ; ps . println ( "[" + sname + "]" ) ; Enumeration pe = getPropList ( sname ) ; while ( pe != null && pe . hasMoreElements ( ) ) { String pair [ ] = ( String [ ] ) pe . nextElement ( ) ; String prop = pair [ 0 ] ; String valu = getProperty ( prop ) ; ps . println ( "    \"" + prop + "\" = \"" + valu + "\"" ) ; } } } }


Input: ********************************************************************** Set the section of the iniFile that you wish to work with . This is persistent for the life of the object or until it s set again . [CODESPLIT] public boolean setSection ( String sectionName ) { if ( sectionNames == null ) { System . err . println ( errMsg ) ; return ( false ) ; } int sectionIndex = 0 ; Enumeration e = sectionNames . elements ( ) ; boolean done = false ; while ( ! done && e . hasMoreElements ( ) ) { String thisName = ( String ) e . nextElement ( ) ; if ( sectionName . equalsIgnoreCase ( thisName ) ) done = true ; else sectionIndex ++ ; } if ( ! done ) return ( false ) ; currentSection = sectionIndex ; return ( true ) ; }


Input:
construct input fields based on Projection Class [CODESPLIT] public void setProjection ( ProjectionManager . ProjectionClass pc ) { // clear out any fields
 removeAll ( ) ; for ( ProjectionManager . ProjectionParam pp : pc . paramList ) { // construct the label
 JPanel thisPanel = new JPanel ( ) ; thisPanel . add ( new JLabel ( pp . name + ": " ) ) ; // text input field
 JTextField tf = new JTextField ( ) ; pp . setTextField ( tf ) ; tf . setColumns ( 12 ) ; thisPanel . add ( tf ) ; add ( thisPanel ) ; } revalidate ( ) ; }


Input: Changed 4 / 28 / 10 dmh : legal dods names are not same as legal javascript names so translate . [CODESPLIT] public static String nameForJsCode ( String dodsName ) { StringBuilder buf = new StringBuilder ( dodsName ) ; for ( int i = 0 ; i < buf . length ( ) ; i ++ ) { char c = buf . charAt ( i ) ; if ( c == ' ' ) buf . replace ( i , i + 1 , "_" ) ; else if ( legal_javascript_id_chars . indexOf ( c ) < 0 ) { String s = "_" + String . valueOf ( ( int ) c ) + "_" ; buf . replace ( i , i + 1 , s ) ; } } return "dods_" + buf . toString ( ) ; }


Input:
/ * void WWWOutput :: write_variable_entries ( DAS &das DDS &dds ) { This writes the text Variables : and then sets up the table so that the first variable s section is written into column two . _os << \

  Variables :
  ; [CODESPLIT] public void writeVariableEntries ( DAS das , DDS dds ) { // This writes the text `Variables:' and then sets up the table
 // so that the first variable's section is written into column two.
 pWrt . print ( "
\n" + "\n" + "
Variables:
\n" + "
\n" ) ; Enumeration e = dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; ( ( BrowserForm ) bt ) . printBrowserForm ( pWrt , das ) ; writeVariableAttributes ( bt , das ) ; pWrt . print ( "\n

\n\n" ) ; // End the current var's section
 pWrt . print ( "
\n\n" ) ; // Start the next var in column two
 } }


Input: / * void WWWOutput :: write_variable_attributes ( BaseType * btp DAS &das ) { AttrTable * attr = das . get_table ( btp - > name () ) ; Don t write anything if there are no attributes . if ( !attr ) return ; [CODESPLIT] public void writeVariableAttributes ( BaseType bt , DAS das ) { try { AttributeTable attr = das . getAttributeTable ( bt . getEncodedName ( ) ) ; if ( attr != null ) { pWrt . print ( "<textarea name=\"" + bt . getLongName ( ) . replace ( ' ' , ' ' ) + "_attr" + "\" rows=" + _attrRows + " cols=" + _attrCols + ">\n" ) ; writeAttributes ( attr ) ; pWrt . print ( "</textarea>\n\n" ) ; } } catch ( NoSuchAttributeException nsae ) { } }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest / wml2 : MonitoringPoint / sams : shape [CODESPLIT] public static ShapeType initShape ( ShapeType shape , StationTimeSeriesFeature stationFeat ) { // gml:Point PointDocument pointDoc = PointDocument . Factory . newInstance ( ) ; NcPointType . initPoint ( pointDoc . addNewPoint ( ) , stationFeat ) ; shape . set ( pointDoc ) ; return shape ; }


Input: Adds the specified component to the layout using the specified constraint object . [CODESPLIT] public void addLayoutComponent ( Component comp , Object constraint ) { if ( debug ) System . out . println ( name + " addLayoutComponent= " + comp . getClass ( ) . getName ( ) + " " + comp . hashCode ( ) + " " + constraint ) ; if ( ! ( constraint instanceof Constraint ) ) throw new IllegalArgumentException ( "MySpringLayout must be Constraint" ) ; constraintMap . put ( comp , constraint ) ; globalBounds = null ; }


Input: Invalidates the layout indicating that if the layout manager has cached information it should be discarded . [CODESPLIT] public void invalidateLayout ( Container target ) { if ( debug ) System . out . println ( name + " invalidateLayout " ) ; globalBounds = null ; // this probably need to be scheduled later ?? // layoutContainer( target); }


Input: Removes the specified component from the layout . [CODESPLIT] public void removeLayoutComponent ( Component comp ) { if ( debug ) System . out . println ( "removeLayoutComponent" ) ; constraintMap . remove ( comp ) ; globalBounds = null ; }


Input: Calculates the preferred size dimensions for the specified container given the components it contains . @param parent the container to be laid out [CODESPLIT] public Dimension preferredLayoutSize ( Container parent ) { if ( globalBounds == null ) layoutContainer ( parent ) ; if ( debug ) System . out . println ( name + " preferredLayoutSize " + globalBounds . getSize ( ) + " " + parent . getInsets ( ) ) ; return globalBounds . getSize ( ) ; }


Input: Calculates the minimum size dimensions for the specified container given the components it contains . [CODESPLIT] public Dimension minimumLayoutSize ( Container parent ) { if ( debug ) System . out . println ( "minimumLayoutSize" ) ; if ( globalBounds == null ) layoutContainer ( parent ) ; return globalBounds . getSize ( ) ; }


Input: Lays out the specified container . [CODESPLIT] public void layoutContainer ( Container target ) { synchronized ( target . getTreeLock ( ) ) { if ( debug ) System . out . println ( name + " layoutContainer " ) ; // first layout any nested LayoutM components // it seems that generally Swing laysout from outer to inner ??? int n = target . getComponentCount ( ) ; for ( int i = 0 ; i < n ; i ++ ) { Component comp = target . getComponent ( i ) ; if ( comp instanceof Container ) { Container c = ( Container ) comp ; LayoutManager m = c . getLayout ( ) ; if ( m instanceof LayoutM ) m . layoutContainer ( c ) ; } } // now layout this container reset ( target ) ; globalBounds = new Rectangle ( 0 , 0 , 0 , 0 ) ; while ( ! layoutPass ( target ) ) target . setPreferredSize ( globalBounds . getSize ( ) ) ; // ?? } }


Input: Determine if this CoordinateSystem can be made into a RadialCoordSys . [CODESPLIT] public static boolean isRadialCoordSys ( Formatter parseInfo , CoordinateSystem cs ) { return ( cs . getAzimuthAxis ( ) != null ) && ( cs . getRadialAxis ( ) != null ) && ( cs . getElevationAxis ( ) != null ) ; }


Input: Determine if the CoordinateSystem cs can be made into a GridCoordSys for the Variable v . [CODESPLIT] public static RadialCoordSys makeRadialCoordSys ( Formatter parseInfo , CoordinateSystem cs , VariableEnhanced v ) { if ( parseInfo != null ) { parseInfo . format ( " " ) ; v . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( " check CS " + cs . getName ( ) ) ; } if ( isRadialCoordSys ( parseInfo , cs ) ) { RadialCoordSys rcs = new RadialCoordSys ( cs ) ; if ( cs . isComplete ( v ) ) { if ( parseInfo != null ) parseInfo . format ( " OK%n" ) ; return rcs ; } else { if ( parseInfo != null ) parseInfo . format ( " NOT complete%n" ) ; } } return null ; }


Input: Get the maximum radial distance in km . [CODESPLIT] public double getMaximumRadial ( ) { if ( maxRadial == 0.0 ) { try { Array radialData = getRadialAxisDataCached ( ) ; maxRadial = MAMath . getMaximum ( radialData ) ; String units = getRadialAxis ( ) . getUnitsString ( ) ; SimpleUnit radialUnit = SimpleUnit . factory ( units ) ; maxRadial = radialUnit . convertTo ( maxRadial , SimpleUnit . kmUnit ) ; // convert to km } catch ( IOException e ) { e . printStackTrace ( ) ; } catch ( IllegalArgumentException e ) { e . printStackTrace ( ) ; } } return maxRadial ; }


Input: Get the units of Calendar time . To get a Date from a time value call DateUnit . getStandardDate ( double value ) . To get units as a String call DateUnit . getUnitsString () . [CODESPLIT] public ucar . nc2 . units . DateUnit getTimeUnits ( ) throws Exception { if ( null == dateUnit ) { dateUnit = new DateUnit ( timeAxis . getUnitsString ( ) ) ; } return dateUnit ; }


Input: debug [CODESPLIT] static public void main ( String [ ] args ) { System . out . println ( "1 Deg=" + Math . toDegrees ( 1000 * 111.0 / Earth . getRadius ( ) ) ) ; }


Input:
Reads data for the given point ( earthlocation ) and if bounded is true returns data for the closest point within the grid for points outside of the grid [CODESPLIT] public Point readData ( GridDatatype grid , CalendarDate date , EarthLocation location , boolean bounded ) throws java . io . IOException { if ( ! bounded ) { if ( Double . isNaN ( location . getAltitude ( ) ) ) { return readData ( grid , date , location . getLatitude ( ) , location . getLongitude ( ) ) ; } else { return readData ( grid , date , location . getAltitude ( ) , location . getLatitude ( ) , location . getLongitude ( ) ) ; } } //Bounded --> Read closest data
 GridCoordSystem gcs = grid . getCoordinateSystem ( ) ; int tidx = findTimeIndexForCalendarDate ( gcs , date ) ; int [ ] xy = gcs . findXYindexFromLatLonBounded ( location . getLatitude ( ) , location . getLongitude ( ) , null ) ; LatLonPoint latlon = gcs . getLatLon ( xy [ 0 ] , xy [ 1 ] ) ; Point p = new Point ( ) ; p . lat = latlon . getLatitude ( ) ; p . lon = latlon . getLongitude ( ) ; int zidx = - 1 ; if ( ! Double . isNaN ( location . getAltitude ( ) ) ) { CoordinateAxis1D zAxis = gcs . getVerticalAxis ( ) ; zidx = zAxis . findCoordElement ( location . getAltitude ( ) ) ; p . z = zAxis . getCoordValue ( zidx ) ; } Array data = grid . readDataSlice ( tidx , zidx , xy [ 1 ] , xy [ 0 ] ) ; p . dataValue = data . getDouble ( data . getIndex ( ) ) ; return p ; }


Input:
/ * ///////////////////////////////////////////////////// Uses apache HttpComponents [CODESPLIT] private HTTPMethod processMethod ( HTTPSession httpclient , String url , Command cmd ) throws HTTPException , UnsupportedEncodingException { HTTPMethod m = null ; if ( cmd == Command . GET ) m = HTTPFactory . Get ( httpclient , url ) ; else if ( cmd == Command . HEAD ) m = HTTPFactory . Head ( httpclient , url ) ; else if ( cmd == Command . OPTIONS ) m = HTTPFactory . Options ( httpclient , url ) ; else if ( cmd == Command . PUT ) { m = HTTPFactory . Put ( httpclient , url ) ; m . setRequestContent ( new StringEntity ( ta . getText ( ) ) ) ; // was  setRequestContentAsString(ta.getText());
 } return m ; }


Input:
Uses apache commons HttpClient [CODESPLIT] @ Urlencoded private void openURL2 ( String urlString , Command cmd ) { HTTPMethod m ; try ( HTTPSession httpclient = HTTPFactory . newSession ( urlString ) ) { /* you might think this works, but it doesnt:
      URI raw = new URI(urlString.trim());
      appendLine("raw scheme= " + raw.getScheme() + "\n auth= " + raw.getRawAuthority() + "\n path= " + raw.getRawPath() +
           "\n query= " + raw.getRawQuery() + "\n fragment= " + raw.getRawFragment()+"\n");

      URI url = new URI(raw.getScheme(), raw.getRawAuthority(),
              URIUtil.encodePath(raw.getRawPath()),
              URIUtil.encodeQuery(raw.getRawQuery()),
              raw.getRawFragment());
      appendLine("encoded scheme= " + url.getScheme() + "\n auth= " + url.getAuthority() + "\n path= " + url.getPath() +
           "\n query= " + url.getQuery() + "\n fragment= " + url.getFragment()+"\n");
      urlString = url.toString();
              */ //urlString = URLnaming.escapeQuery(urlString);
 if ( cmd == Command . GET ) m = HTTPFactory . Get ( httpclient , urlString ) ; else if ( cmd == Command . HEAD ) m = HTTPFactory . Head ( httpclient , urlString ) ; else if ( cmd == Command . OPTIONS ) m = HTTPFactory . Options ( httpclient , urlString ) ; else if ( cmd == Command . PUT ) { m = HTTPFactory . Put ( httpclient , urlString ) ; m . setRequestContent ( new StringEntity ( ta . getText ( ) ) ) ; // was  setRequestContentAsString(ta.getText());
 } else { throw new IOException ( "Unsupported command: " + cmd ) ; } m . setCompression ( "gzip,deflate" ) ; /* FIX
      appendLine("HttpClient " + m.getName() + " " + urlString);

      appendLine("   do Authentication= " + m.getDoAuthentication());
      appendLine("   follow Redirects= " + m.getFollowRedirects());

      appendLine("   cookie policy= " + p.getCookiePolicy());
      appendLine("   http version= " + p.getVersion().toString());
      appendLine("   timeout (msecs)= " + p.getSoTimeout());
      appendLine("   virtual host= " + p.getVirtualHost());
      */ printHeaders ( "Request Headers = " , m . getRequestHeaders ( ) ) ; appendLine ( " " ) ; m . execute ( ) ; printHeaders ( "Request Headers2 = " , m . getRequestHeaders ( ) ) ; appendLine ( " " ) ; appendLine ( "Status = " + m . getStatusCode ( ) + " " + m . getStatusText ( ) ) ; appendLine ( "Status Line = " + m . getStatusLine ( ) ) ; printHeaders ( "Response Headers = " , m . getResponseHeaders ( ) ) ; if ( cmd == Command . GET ) { appendLine ( "\nResponseBody---------------" ) ; String charset = m . getResponseCharSet ( ) ; if ( charset == null ) charset = CDM . UTF8 ; String contents = null ; // check for deflate and gzip compression
 Header h = m . getResponseHeader ( "content-encoding" ) ; String encoding = ( h == null ) ? null : h . getValue ( ) ; if ( encoding != null && encoding . equals ( "deflate" ) ) { byte [ ] body = m . getResponseAsBytes ( ) ; if ( body != null ) { InputStream is = new BufferedInputStream ( new InflaterInputStream ( new ByteArrayInputStream ( body ) ) , 10000 ) ; contents = IO . readContents ( is , charset ) ; double ratio = ( double ) contents . length ( ) / body . length ; appendLine ( "  deflate encoded=" + body . length + " decoded=" + contents . length ( ) + " ratio= " + ratio ) ; } } else if ( encoding != null && encoding . equals ( "gzip" ) ) { byte [ ] body = m . getResponseAsBytes ( ) ; if ( body != null ) { InputStream is = new BufferedInputStream ( new GZIPInputStream ( new ByteArrayInputStream ( body ) ) , 10000 ) ; contents = IO . readContents ( is , charset ) ; double ratio = ( double ) contents . length ( ) / body . length ; appendLine ( "  gzip encoded=" + body . length + " decoded=" + contents . length ( ) + " ratio= " + ratio ) ; } } else { byte [ ] body = m . getResponseAsBytes ( 50 * 1000 ) ; // max 50 Kbytes
 contents = ( body == null ) ? "" : new String ( body , charset ) ; } if ( contents != null ) { if ( contents . length ( ) > 50 * 1000 ) // limit contents
 contents = contents . substring ( 0 , 50 * 1000 ) ; appendLine ( contents ) ; } } else if ( cmd == Command . OPTIONS ) printSet ( "AllowedMethods = " , HTTPFactory . getAllowedMethods ( ) ) ; } catch ( IOException e ) { StringWriter sw = new StringWriter ( 5000 ) ; e . printStackTrace ( new PrintWriter ( sw ) ) ; appendLine ( sw . toString ( ) ) ; } }


Input:
Uses java . net [CODESPLIT] private void openURL ( String urlString , Command command ) { try { //Open the URLConnection for reading
 URL u = new URL ( urlString ) ; currentConnection = ( HttpURLConnection ) u . openConnection ( ) ; currentConnection . setRequestMethod ( command . toString ( ) ) ; // GET or HEAD
 currentConnection . setAllowUserInteraction ( true ) ; clear ( ) ; appendLine ( command + " request for " + urlString ) ; // request headers
 Map < String , List < String > > reqs = currentConnection . getRequestProperties ( ) ; for ( Map . Entry < String , List < String > > ent : reqs . entrySet ( ) ) { append ( " " + ent . getKey ( ) + ": " ) ; for ( String v : ent . getValue ( ) ) append ( v + " " ) ; appendLine ( "" ) ; } appendLine ( "" ) ; appendLine ( "getFollowRedirects=" + HttpURLConnection . getFollowRedirects ( ) ) ; appendLine ( "getInstanceFollowRedirects=" + currentConnection . getInstanceFollowRedirects ( ) ) ; appendLine ( "AllowUserInteraction=" + currentConnection . getAllowUserInteraction ( ) ) ; appendLine ( "" ) ; int code = currentConnection . getResponseCode ( ) ; String response = currentConnection . getResponseMessage ( ) ; // response headers
 appendLine ( " HTTP/1.x " + code + " " + response ) ; appendLine ( " content-length: " + currentConnection . getContentLength ( ) ) ; appendLine ( " content-encoding: " + currentConnection . getContentEncoding ( ) ) ; appendLine ( " content-type: " + currentConnection . getContentType ( ) ) ; appendLine ( "\nHeaders: " ) ; for ( int j = 1 ; true ; j ++ ) { String header = currentConnection . getHeaderField ( j ) ; String key = currentConnection . getHeaderFieldKey ( j ) ; if ( header == null || key == null ) break ; appendLine ( " " + key + ": " + header ) ; } appendLine ( "" ) ; appendLine ( "contents:" ) ; // read it
 java . io . InputStream is = currentConnection . getInputStream ( ) ; ByteArrayOutputStream bout = new ByteArrayOutputStream ( 200000 ) ; IO . copy ( is , bout ) ; is . close ( ) ; append ( new String ( bout . toByteArray ( ) , CDM . utf8Charset ) ) ; appendLine ( "end contents" ) ; } catch ( MalformedURLException e ) { append ( urlString + " is not a parseable URL" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }


Input: Transform geographic Earth coordinates to satellite view angle coordinate system also known as the intermediate coordinate system in CGMS Normalized Geostationary Projection . [CODESPLIT] public double [ ] earthToSat ( double geographic_lon , double geographic_lat ) { geographic_lat = geographic_lat * DEG_TO_RAD ; geographic_lon = geographic_lon * DEG_TO_RAD ; double geocentric_lat = Math . atan ( ( ( r_pol * r_pol ) / ( r_eq * r_eq ) ) * Math . tan ( geographic_lat ) ) ; double r_earth = r_pol / Math . sqrt ( 1.0 - ( ( r_eq * r_eq - r_pol * r_pol ) / ( r_eq * r_eq ) ) * Math . cos ( geocentric_lat ) * Math . cos ( geocentric_lat ) ) ; double r_1 = h - r_earth * Math . cos ( geocentric_lat ) * Math . cos ( geographic_lon - sub_lon ) ; double r_2 = - r_earth * Math . cos ( geocentric_lat ) * Math . sin ( geographic_lon - sub_lon ) ; double r_3 = r_earth * Math . sin ( geocentric_lat ) ; if ( r_1 > h ) { // often two geoid intersect points, use the closer one. return new double [ ] { Double . NaN , Double . NaN } ; } double lamda_sat = Double . NaN ; double theta_sat = Double . NaN ; if ( scan_geom . equals ( GEOS ) ) { // GEOS (eg. SEVIRI, MSG)  CGMS 03, 4.4.3.2, Normalized Geostationary Projection lamda_sat = Math . atan ( - r_2 / r_1 ) ; theta_sat = Math . asin ( r_3 / Math . sqrt ( r_1 * r_1 + r_2 * r_2 + r_3 * r_3 ) ) ; } else if ( scan_geom . equals ( GOES ) ) { // GOES (eg. GOES-R ABI) lamda_sat = Math . asin ( - r_2 / Math . sqrt ( r_1 * r_1 + r_2 * r_2 + r_3 * r_3 ) ) ; theta_sat = Math . atan ( r_3 / r_1 ) ; } return new double [ ] { lamda_sat , theta_sat } ; }


Input: Transform satellite view angle coordinates known as the intermeidate coordinates in the CGMS Normalized Geostationary Projection to geographic Earth coordinates . [CODESPLIT] public double [ ] satToEarth ( double x , double y ) { if ( scan_geom . equals ( GOES ) ) { // convert from GOES to GEOS for transfrom below double [ ] lambda_theta_geos = GOES_to_GEOS ( x , y ) ; x = lambda_theta_geos [ 0 ] ; y = lambda_theta_geos [ 1 ] ; } double c1 = ( h * Math . cos ( x ) * Math . cos ( y ) ) * ( h * Math . cos ( x ) * Math . cos ( y ) ) ; double c2 = ( Math . cos ( y ) * Math . cos ( y ) + fp * Math . sin ( y ) * Math . sin ( y ) ) * d ; if ( c1 < c2 ) { return new double [ ] { Double . NaN , Double . NaN } ; } double s_d = Math . sqrt ( c1 - c2 ) ; double s_n = ( h * Math . cos ( x ) * Math . cos ( y ) - s_d ) / ( Math . cos ( y ) * Math . cos ( y ) + fp * Math . sin ( y ) * Math . sin ( y ) ) ; double s_1 = h - s_n * Math . cos ( x ) * Math . cos ( y ) ; double s_2 = s_n * Math . sin ( x ) * Math . cos ( y ) ; double s_3 = - s_n * Math . sin ( y ) ; double s_xy = Math . sqrt ( s_1 * s_1 + s_2 * s_2 ) ; double geographic_lon = Math . atan ( s_2 / s_1 ) + sub_lon ; double geographic_lat = Math . atan ( - fp * ( s_3 / s_xy ) ) ; double lonDegrees = RAD_TO_DEG * geographic_lon ; double latDegrees = RAD_TO_DEG * geographic_lat ; // force output longitude to -180 to 180 range if ( lonDegrees < - 180.0 ) lonDegrees += 360.0 ; if ( lonDegrees > 180.0 ) lonDegrees -= 360.0 ; return new double [ ] { lonDegrees , latDegrees } ; }


Input: Transform view angle coordinates in the GOES scan geometry frame to view angle coordinates in the GEOS scan geometry frame . [CODESPLIT] public double [ ] GOES_to_GEOS ( double lamda_goes , double theta_goes ) { double theta_geos = Math . asin ( Math . sin ( theta_goes ) * Math . cos ( lamda_goes ) ) ; double lamda_geos = Math . atan ( Math . tan ( lamda_goes ) / Math . cos ( theta_goes ) ) ; return new double [ ] { lamda_geos , theta_geos } ; }


Input: Transform fractional FGF coordinates to ( longitude latitude ) . [CODESPLIT] public double [ ] FGFtoEarth ( double fgf_x , double fgf_y , double scale_x , double offset_x , double scale_y , double offset_y ) { double [ ] xy = FGFtoSat ( fgf_x , fgf_y , scale_x , offset_x , scale_y , offset_y ) ; return satToEarth ( xy [ 0 ] , xy [ 1 ] ) ; }