Input: Dump the contents of a buffer from 0 to position [CODESPLIT] static public void dumpbytes ( ByteBuffer buf0 ) { int stop = buf0 . limit ( ) ; int size = stop + 8 ; int savepos = buf0 . position ( ) ; assert savepos == 0 ; byte [ ] bytes = new byte [ size ] ; Arrays . fill ( bytes , ( byte ) 0 ) ; buf0 . get ( bytes , 0 , stop ) ; buf0 . position ( savepos ) ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) . order ( buf0 . order ( ) ) ; buf . position ( 0 ) ; buf . limit ( size ) ; int i = 0 ; try { for ( i = 0 ; buf . position ( ) < stop ; i ++ ) { savepos = buf . position ( ) ; int iv = buf . getInt ( ) ; buf . position ( savepos ) ; long lv = buf . getLong ( ) ; buf . position ( savepos ) ; short sv = buf . getShort ( ) ; buf . position ( savepos ) ; byte b = buf . get ( ) ; int ub = ( ( int ) b ) & 0x000000FF ; long uiv = ( ( long ) iv ) & 0xFFFFFFFF  L ; int usv = ( ( int ) sv ) & 0xFFFF ; int ib = ( int ) b ; char c = ( char ) ub ; String s = Character . toString ( c ) ; if ( c == ' ' ) s = "\\r" ; else if ( c == ' ' ) s = "\\n" ; else if ( c < ' ' || c >= 0x7f ) s = "?" ; System . err . printf ( "[%03d] %02x %03d %4d '%s'" , i , ub , ub , ib , s ) ; System . err . printf ( "\t%12d 0x%08x" , iv , uiv ) ; System . err . printf ( "\t%5d\t0x%04x" , sv , usv ) ; System . err . println ( ) ; System . err . flush ( ) ; } } catch ( Exception e ) { System . err . println ( "failure:" + e ) ; } finally { System . err . flush ( ) ; //new Exception().printStackTrace(System.err); System . err . flush ( ) ; } }


Input: Find the EarthEllipsoid that matches this name . [CODESPLIT] public static EarthEllipsoid getType ( String name ) { if ( name == null ) return null ; return hash . get ( name ) ; }


Input: Find the EarthEllipsoid that matches this EPSG Id . [CODESPLIT] public static EarthEllipsoid getType ( int epsgId ) { Collection < EarthEllipsoid > all = getAll ( ) ; for ( EarthEllipsoid ellipsoid : all ) { if ( ellipsoid . epsgId == epsgId ) { return ellipsoid ; } } return null ; }


Input: / * message DataCol { string name = 1 ; // fullname for top shortname for member DataType dataType = 2 ; Section section = 3 ; bool bigend = 4 ; uint32 version = 5 ; bool isVlen = 7 ; uint32 nelems = 9 ; [CODESPLIT] public NcStreamProto . DataCol encodeData2 ( String name , boolean isVlen , Section section , Array data ) { NcStreamProto . DataCol . Builder builder = NcStreamProto . DataCol . newBuilder ( ) ; DataType dataType = data . getDataType ( ) ; builder . setName ( name ) ; builder . setDataType ( NcStream . convertDataType ( data . getDataType ( ) ) ) ; builder . setBigend ( ByteOrder . nativeOrder ( ) == ByteOrder . BIG_ENDIAN ) ; builder . setVersion ( NcStream . ncstream_data_version ) ; if ( ! isVlen ) { builder . setNelems ( ( int ) data . getSize ( ) ) ; builder . setSection ( NcStream . encodeSection ( section ) ) ; } if ( isVlen ) { builder . setIsVlen ( true ) ; encodeVlenData ( builder , section , data ) ; } else if ( dataType == DataType . STRING ) { if ( data instanceof ArrayChar ) { // is this possible ? ArrayChar cdata = ( ArrayChar ) data ; for ( String s : cdata ) builder . addStringdata ( s ) ; Section ssection = section . removeLast ( ) ; builder . setSection ( NcStream . encodeSection ( ssection ) ) ; } else if ( data instanceof ArrayObject ) { IndexIterator iter = data . getIndexIterator ( ) ; while ( iter . hasNext ( ) ) builder . addStringdata ( ( String ) iter . next ( ) ) ; } else { throw new IllegalStateException ( "Unknown class for STRING =" + data . getClass ( ) . getName ( ) ) ; } } else if ( dataType == DataType . OPAQUE ) { if ( data instanceof ArrayObject ) { IndexIterator iter = data . getIndexIterator ( ) ; while ( iter . hasNext ( ) ) { ByteBuffer bb = ( ByteBuffer ) iter . next ( ) ; // Need to use duplicate so that internal state of bb isn't affected builder . addOpaquedata ( ByteString . copyFrom ( bb . duplicate ( ) ) ) ; } } else { throw new IllegalStateException ( "Unknown class for OPAQUE =" + data . getClass ( ) . getName ( ) ) ; } } else if ( dataType == DataType . STRUCTURE ) { builder . setStructdata ( encodeStructureData ( data ) ) ; } else if ( dataType == DataType . SEQUENCE ) { throw new UnsupportedOperationException ( "Not implemented yet SEQUENCE =" + data . getClass ( ) . getName ( ) ) ; } else { // normal case builder . setPrimdata ( copyArrayToByteString ( data ) ) ; } return builder . build ( ) ; }


Input: /////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public Array decode ( NcStreamProto . DataCol dproto , Section parentSection ) throws IOException { ByteOrder bo = dproto . getBigend ( ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; DataType dataType = NcStream . convertDataType ( dproto . getDataType ( ) ) ; Section section = ( dataType == DataType . SEQUENCE ) ? new Section ( ) : NcStream . decodeSection ( dproto . getSection ( ) ) ; if ( ! dproto . getIsVlen ( ) ) { assert dproto . getNelems ( ) == section . computeSize ( ) ; } // special cases if ( dproto . getIsVlen ( ) ) { if ( parentSection == null ) return decodeVlenData ( dproto ) ; else return decodeVlenData ( dproto , parentSection ) ; } else if ( dataType == DataType . STRING ) { Array data = Array . factory ( dataType , section . getShape ( ) ) ; IndexIterator ii = data . getIndexIterator ( ) ; for ( String s : dproto . getStringdataList ( ) ) { ii . setObjectNext ( s ) ; } return data ; } else if ( dataType == DataType . STRUCTURE ) { return decodeStructureData ( dproto , parentSection ) ; } else if ( dataType == DataType . OPAQUE ) { Array data = Array . factory ( dataType , section . getShape ( ) ) ; IndexIterator ii = data . getIndexIterator ( ) ; for ( ByteString s : dproto . getOpaquedataList ( ) ) { ii . setObjectNext ( s . asReadOnlyByteBuffer ( ) ) ; } return data ; } else { // common case ByteBuffer bb = dproto . getPrimdata ( ) . asReadOnlyByteBuffer ( ) ; bb . order ( bo ) ; return Array . factory ( dataType , section . getShape ( ) , bb ) ; } }


Input: top level vlen [CODESPLIT] public Array decodeVlenData ( NcStreamProto . DataCol dproto ) throws IOException { DataType dataType = NcStream . convertDataType ( dproto . getDataType ( ) ) ; ByteBuffer bb = dproto . getPrimdata ( ) . asReadOnlyByteBuffer ( ) ; ByteOrder bo = dproto . getBigend ( ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; bb . order ( bo ) ; Array alldata = Array . factory ( dataType , new int [ ] { dproto . getNelems ( ) } , bb ) ; // flat array IndexIterator all = alldata . getIndexIterator ( ) ; Section section = NcStream . decodeSection ( dproto . getSection ( ) ) ; Array [ ] data = new Array [ ( int ) section . computeSize ( ) ] ; // divide the primitive data into variable length arrays int count = 0 ; for ( int len : dproto . getVlensList ( ) ) { Array primdata = Array . factory ( dataType , new int [ ] { len } ) ; IndexIterator prim = primdata . getIndexIterator ( ) ; for ( int i = 0 ; i < len ; i ++ ) { prim . setObjectNext ( all . getObjectNext ( ) ) ; // generic } data [ count ++ ] = primdata ; } // return Array.makeObjectArray(dataType, data[0].getClass(), section.getShape(), data); return Array . makeVlenArray ( section . getShape ( ) , data ) ; }


Input: vlen inside a Structure [CODESPLIT] private Array decodeVlenData ( NcStreamProto . DataCol dproto , Section parentSection ) throws IOException { DataType dataType = NcStream . convertDataType ( dproto . getDataType ( ) ) ; ByteBuffer bb = dproto . getPrimdata ( ) . asReadOnlyByteBuffer ( ) ; ByteOrder bo = dproto . getBigend ( ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; bb . order ( bo ) ; Array alldata = Array . factory ( dataType , new int [ ] { dproto . getNelems ( ) } , bb ) ; // 1D array IndexIterator all = alldata . getIndexIterator ( ) ; int psize = ( int ) parentSection . computeSize ( ) ; Section section = NcStream . decodeSection ( dproto . getSection ( ) ) ; Section vsection = section . removeFirst ( parentSection ) ; int vsectionSize = ( int ) vsection . computeSize ( ) ; // the # of varlen Arrays at the inner structure // LOOK check for scalar // divide the primitive data into variable length arrays int countInner = 0 ; Array [ ] pdata = new Array [ psize ] ; for ( int pCount = 0 ; pCount < psize ; pCount ++ ) { Array [ ] vdata = new Array [ vsectionSize ] ; for ( int vCount = 0 ; vCount < vsectionSize ; vCount ++ ) { int vlen = dproto . getVlens ( countInner ++ ) ; Array primdata = Array . factory ( dataType , new int [ ] { vlen } ) ; IndexIterator prim = primdata . getIndexIterator ( ) ; for ( int i = 0 ; i < vlen ; i ++ ) { prim . setObjectNext ( all . getObjectNext ( ) ) ; // generic } vdata [ vCount ] = primdata ; } pdata [ pCount ] = Array . makeVlenArray ( vsection . getShape ( ) , vdata ) ; } // ArrayObject(parentShape) return Array . makeVlenArray ( parentSection . getShape ( ) , pdata ) ; }


Input: Extract all A - HREF contained URLS from the given URL and return in List [CODESPLIT] public ArrayList extract ( String url ) throws IOException { if ( debug ) System . out . println ( " URLextract=" + url ) ; baseURL = new URL ( url ) ; InputStream in = baseURL . openStream ( ) ; InputStreamReader r = new InputStreamReader ( filterTag ( in ) , CDM . UTF8 ) ; HTMLEditorKit . ParserCallback callback = new CallerBacker ( ) ; urlList = new ArrayList ( ) ; wantURLS = true ; wantText = false ; parser . parse ( r , callback , false ) ; return urlList ; }


Input: Extract text content from the given URL and return in String [CODESPLIT] public String getTextContent ( String url ) throws IOException { if ( debug ) System . out . println ( " URL.getTextContent=" + url ) ; baseURL = new URL ( url ) ; InputStream in = baseURL . openStream ( ) ; InputStreamReader r = new InputStreamReader ( filterTag ( in ) , CDM . UTF8 ) ; HTMLEditorKit . ParserCallback callback = new CallerBacker ( ) ; textBuffer = new StringBuffer ( 3000 ) ; wantURLS = false ; wantText = true ; parser . parse ( r , callback , false ) ; return textBuffer . toString ( ) ; }


Input: workaround for HTMLEditorKit . Parser cant deal with content - encoding [CODESPLIT] private InputStream filterTag ( InputStream in ) throws IOException { BufferedReader buffIn = new BufferedReader ( new InputStreamReader ( in , CDM . UTF8 ) ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( 10000 ) ; String line = buffIn . readLine ( ) ; while ( line != null ) { String lline = line . toLowerCase ( ) ; if ( lline . contains ( "<meta " ) ) // skip meta tags continue ; //System.out.println("--"+line); bos . write ( line . getBytes ( CDM . utf8Charset ) ) ; line = buffIn . readLine ( ) ; } buffIn . close ( ) ; return new ByteArrayInputStream ( bos . toByteArray ( ) ) ; }


Input: LOOK DataOutputStream uses big - endian [CODESPLIT] @ Override public long readToByteChannel ( ucar . nc2 . Variable v2 , Section section , WritableByteChannel channel ) throws java . io . IOException , ucar . ma2 . InvalidRangeException { Array data = readData ( v2 , section ) ; return IospHelper . copyToByteChannel ( data , channel ) ; }


Input:
Create the Dataset Description XML document from this GridDataset [CODESPLIT] public Document makeDatasetDescription ( ) throws IOException { Element rootElem = new Element ( "gridDataset" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( "location" , gcd . getName ( ) ) ; if ( null != path ) rootElem . setAttribute ( "path" , path ) ; // coordinate axes for ( CoverageCoordAxis axis : gcd . getCoordAxes ( ) ) { rootElem . addContent ( writeAxis ( axis ) ) ; } // gridSets for ( CoordSysSet gridset : gcd . getCoverageSets ( ) ) { rootElem . addContent ( writeCoverageSet ( gridset . getCoordSys ( ) , gridset . getCoverages ( ) , gcd . getProjBoundingBox ( ) ) ) ; } // coordinate transforms for ( CoverageTransform ct : gcd . getCoordTransforms ( ) ) { rootElem . addContent ( writeCoordTransform ( ct ) ) ; } /* global attributes
     Iterator atts = gds.getGlobalAttributes().iterator();
     while (atts.hasNext()) {
       ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();
       rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, "attribute", null));
     } */ // add lat/lon bounding box LatLonRect bb = gcd . getLatlonBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range CalendarDateRange calDateRange = gcd . getCalendarDateRange ( ) ; if ( calDateRange != null ) { Element dateRange = new Element ( "TimeSpan" ) ; dateRange . addContent ( new Element ( "begin" ) . addContent ( calDateRange . getStart ( ) . toString ( ) ) ) ; dateRange . addContent ( new Element ( "end" ) . addContent ( calDateRange . getEnd ( ) . toString ( ) ) ) ; rootElem . addContent ( dateRange ) ; } return doc ; }


Input: / * private Element writeCoordSys ( GridCoordSystem cs ) { Element csElem = new Element ( coordSys ) ; csElem . setAttribute ( name cs . getName () ) ; List axes = cs . getCoordinateAxes () ; for ( int i = 0 ; i < axes . size () ; i ++ ) { CoordinateAxis axis = ( CoordinateAxis ) axes . get ( i ) ; Element axisElem = new Element ( axisRef ) ; axisElem . setAttribute ( name axis . getName () ) ; csElem . addContent ( axisElem ) ; } List cts = cs . getCoordinateTransforms () ; for ( int j = 0 ; j < cts . size () ; j ++ ) { CoordinateTransform ct = ( CoordinateTransform ) cts . get ( j ) ; Element elem = new Element ( coordTransRef ) ; elem . setAttribute ( name ct . getName () ) ; csElem . addContent ( elem ) ; } return csElem ; } [CODESPLIT] private Element writeCoordTransform ( CoverageTransform ct ) { Element ctElem = new Element ( "coordTransform" ) ; ctElem . setAttribute ( "name" , ct . getName ( ) ) ; ctElem . setAttribute ( "transformType" , ct . isHoriz ( ) ? "Projection" : "Vertical" ) ; for ( Attribute param : ct . getAttributes ( ) ) { Element pElem = ncmlWriter . makeAttributeElement ( param ) ; pElem . setName ( "parameter" ) ; ctElem . addContent ( pElem ) ; } return ctElem ; }


Input: Add all ; replace old if has same name [CODESPLIT] @ Override public void addAll ( Iterable < Attribute > atts ) { for ( Attribute att : atts ) addAttribute ( att ) ; }


Input: Remove an Attribute by name . [CODESPLIT] @ Override public boolean removeAttribute ( String attName ) { Attribute att = findAttribute ( attName ) ; return att != null && atts . remove ( att ) ; }


Input: Remove an Attribute by name ignoring case [CODESPLIT] @ Override public boolean removeAttributeIgnoreCase ( String attName ) { Attribute att = findAttributeIgnoreCase ( attName ) ; return att != null && atts . remove ( att ) ; }


Input: Get offsets from firstDate in units of timeUnit [CODESPLIT] public List < Double > getOffsetsInTimeUnits ( ) { double start = firstDate . getMillis ( ) ; List < Double > result = new ArrayList <> ( runtimes . length ) ; for ( int idx = 0 ; idx < runtimes . length ; idx ++ ) { double runtime = ( double ) getRuntime ( idx ) ; double msecs = ( runtime - start ) ; result . add ( msecs / timeUnit . getValueInMillisecs ( ) ) ; } return result ; }


Input: add an ActionSource listener [CODESPLIT] public void addActionSourceListener ( ActionSourceListener l ) { if ( ! eventType . equals ( l . getEventTypeName ( ) ) ) throw new IllegalArgumentException ( "ActionCoordinator: tried to add ActionSourceListener for wrong kind of Action " + eventType + " != " + l . getEventTypeName ( ) ) ; lm . addListener ( l ) ; l . addActionValueListener ( this ) ; }


Input:
add an ActionValue listener public void addActionValueListener ( ActionValueListener l ) { lm . addListener ( l ) ; } remove an ActionValue listener public void removeActionValueListener ( ActionValueListener l ) { lm . removeListener ( l ) ; } [CODESPLIT] static public void main ( String [ ] argv ) { ActionCoordinator ac = new ActionCoordinator ( "test" ) ; /*    System.out.println("failure test------------");
    try {
      ac.addActionSourceListener(new ActionSourceListener("that") {
        public void actionPerformed( java.awt.event.ActionEvent e) {
          System.out.println(" event ok ");
        }
      });
      System.out.println("good dog!");
    } catch (IllegalArgumentException e) {
      System.out.println("bad dog! = "+e);
    }

    System.out.println("next test------------");  */ ActionSourceListener as1 = new ActionSourceListener ( "test" ) { public void actionPerformed ( ActionValueEvent e ) { System . out . println ( " first listener got event " + e . getValue ( ) ) ; } } ; ac . addActionSourceListener ( as1 ) ; ActionSourceListener as2 = new ActionSourceListener ( "test" ) { public void actionPerformed ( ActionValueEvent e ) { System . out . println ( " second listener got event " + e . getValue ( ) ) ; } } ; ac . addActionSourceListener ( as2 ) ; ActionSourceListener as3 = new ActionSourceListener ( "test" ) { public void actionPerformed ( ActionValueEvent e ) { System . out . println ( " third listener got event " + e . getValue ( ) ) ; } } ; ac . addActionSourceListener ( as3 ) ; as1 . fireActionValueEvent ( "testing" , "newValue 1" ) ; as2 . fireActionValueEvent ( "testing" , "newValue 2" ) ; }


Input: HttpSessionAttributeListener [CODESPLIT] public void attributeRemoved ( HttpSessionBindingEvent e ) { if ( e . getValue ( ) instanceof GuardedDataset ) { GuardedDataset gdataset = ( GuardedDataset ) e . getValue ( ) ; gdataset . close ( ) ; //System.out.printf(" close gdataset %s in session %s %n", gdataset, e.getSession().getId()); //if (log.isDebugEnabled()) log.debug(" close gdataset " + gdataset + " in session " + e.getSession().getId()); } }


Input:
Use factory to obtain a EsriShapefileRenderer . This caches the EsriShapefile for reuse . <p / > Implementation note : should switch to weak references . [CODESPLIT] static public EsriShapefileRenderer factory ( String filename ) { if ( sfileHash == null ) sfileHash = new HashMap < String , EsriShapefileRenderer > ( ) ; if ( sfileHash . containsKey ( filename ) ) return sfileHash . get ( filename ) ; try { EsriShapefileRenderer sfile = new EsriShapefileRenderer ( filename ) ; sfileHash . put ( filename , sfile ) ; return sfile ; } catch ( Exception ex ) { //System.err.println("EsriShapefileRenderer failed on " + filename + "\n" + ex);
 //ex.printStackTrace();
 return null ; } }


Input: Read the value ( parameters are ignored ) . [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws IOException { setData ( ncVar . read ( ) ) ; return ( false ) ; }


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 ) { if ( print_decl_p ) { printDecl ( os , space , false ) ; os . println ( " = \"" + Util . escattr ( val ) + "\";" ) ; } else os . print ( "\"" + Util . escattr ( val ) + "\"" ) ; }


Input:
Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { int dap_len = source . readInt ( ) ; //LogStream.out.println("DString deserialize string dap_length: "+ dap_len);
 if ( dap_len < 0 ) throw new DataReadException ( "Negative string length (dap_length: " + dap_len + ") read." ) ; if ( dap_len > Short . MAX_VALUE ) throw new DataReadException ( "DString deserialize string length (dap_length: " + dap_len + ") too large." ) ; int modFour = dap_len % 4 ; // number of bytes to pad
 int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; byte byteArray [ ] = new byte [ dap_len ] ; // With blackdown JDK1.1.8v3 (comes with matlab 6) read() didn't always
 // finish reading a string.  readFully() insures that it gets all <dap_len>
 // characters it requested.  rph 08/20/01.
 //source.read(byteArray, 0, dap_len);
 source . readFully ( byteArray , 0 , dap_len ) ; // pad out to a multiple of four bytes
 byte unused ; for ( int i = 0 ; i < pad ; i ++ ) unused = source . readByte ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 + dap_len + pad ) ; // convert bytes to a new String using ISO8859_1 (Latin 1) encoding.
 // This was chosen because it converts each byte to its Unicode value
 // with no translation (the first 256 glyphs in Unicode are ISO8859_1)
 try { val = new String ( byteArray , 0 , dap_len , "ISO8859_1" ) ; hasValue = true ; } catch ( UnsupportedEncodingException e ) { // this should never happen
 throw new UnsupportedEncodingException ( "ISO8859_1 encoding not supported by this VM!" ) ; } }


Input:
Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { // convert String to a byte array using ISO8859_1 (Latin 1) encoding.
 // This was chosen because it converts each byte to its Unicode value
 // with no translation (the first 256 glyphs in Unicode are ISO8859_1)
 try { byte byteArray [ ] = val . getBytes ( "ISO8859_1" ) ; sink . writeInt ( byteArray . length ) ; int modFour = byteArray . length % 4 ; // number of bytes to pad
 int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; sink . write ( byteArray , 0 , byteArray . length ) ; for ( int i = 0 ; i < pad ; i ++ ) { sink . writeByte ( 0 ) ; } } catch ( UnsupportedEncodingException e ) { // this should never happen
 throw new UnsupportedEncodingException ( "ISO8859_1 encoding not supported by this VM!" ) ; } }


Input: See if either coordinate is + / - infinite . This happens sometimes in projective geometry . [CODESPLIT] public boolean isInfinite ( ) { return ( x == java . lang . Double . POSITIVE_INFINITY ) || ( x == java . lang . Double . NEGATIVE_INFINITY ) || ( y == java . lang . Double . POSITIVE_INFINITY ) || ( y == java . lang . Double . NEGATIVE_INFINITY ) ; }


Input: See if either coordinate in <code > pt< / code > is + / - infinite . This happens sometimes in projective geometry . [CODESPLIT] static public boolean isInfinite ( ProjectionPoint pt ) { return ( pt . getX ( ) == java . lang . Double . POSITIVE_INFINITY ) || ( pt . getX ( ) == java . lang . Double . NEGATIVE_INFINITY ) || ( pt . getY ( ) == java . lang . Double . POSITIVE_INFINITY ) || ( pt . getY ( ) == java . lang . Double . NEGATIVE_INFINITY ) ; }


Input: Computes the shape of the largest possible <b > contiguous< / b > chunk starting at { @link #getCurrentCounter () } and with { @code numElems < = maxChunkElems } . [CODESPLIT] public int [ ] computeChunkShape ( long maxChunkElems ) { int [ ] chunkShape = new int [ rank ] ; for ( int iDim = 0 ; iDim < rank ; ++ iDim ) { int size = ( int ) ( maxChunkElems / stride [ iDim ] ) ; size = ( size == 0 ) ? 1 : size ; size = Math . min ( size , shape [ iDim ] - current [ iDim ] ) ; chunkShape [ iDim ] = size ; } return chunkShape ; }


Input: / * public void setValue ( NativeLong value ) { getPointer () . setNativeLong ( 0 value ) ; } [CODESPLIT] public void setValue ( SizeT value ) { Pointer p = getPointer ( ) ; if ( Native . SIZE_T_SIZE == 8 ) { p . setLong ( 0 , value . longValue ( ) ) ; } else { p . setInt ( 0 , value . intValue ( ) ) ; } }


Input:
Create a java . util . Date from this udunits String . [CODESPLIT] static public Date getStandardDate ( String text ) { double value ; String udunitString ; text = text . trim ( ) ; StringTokenizer stoker = new StringTokenizer ( text ) ; String firstToke = stoker . nextToken ( ) ; try { value = Double . parseDouble ( firstToke ) ; udunitString = text . substring ( firstToke . length ( ) ) ; } catch ( NumberFormatException e ) { // stupid way to test if it starts with a number
 value = 0.0 ; udunitString = text ; } DateUnit du ; try { du = new DateUnit ( udunitString ) ; } catch ( Exception e ) { return null ; } return du . makeDate ( value ) ; }


Input: Create a java . util . Date from a udunit or ISO String . [CODESPLIT] static public Date getStandardOrISO ( String text ) { Date result = getStandardDate ( text ) ; if ( result == null ) { DateFormatter formatter = new DateFormatter ( ) ; result = formatter . getISODate ( text ) ; } return result ; }


Input: Get the origin Date . [CODESPLIT] public Date getDateOrigin ( ) { if ( ! ( uu instanceof TimeScaleUnit ) ) return null ; TimeScaleUnit tu = ( TimeScaleUnit ) uu ; return tu . getOrigin ( ) ; }


Input: Get the equivalent java . util . Date . [CODESPLIT] public Date getDate ( ) { double secs = timeUnit . getValueInSeconds ( value ) ; return new Date ( getDateOrigin ( ) . getTime ( ) + ( long ) ( 1000 * secs ) ) ; }


Input:
Create a Date from this base unit and the given value . [CODESPLIT] public Date makeDate ( double val ) { if ( Double . isNaN ( val ) ) return null ; double secs = timeUnit . getValueInSeconds ( val ) ; //
 return new Date ( getDateOrigin ( ) . getTime ( ) + ( long ) ( 1000 * secs ) ) ; }


Input: Create the equivalent value from this base unit and the given Date . Inverse of makeDate . [CODESPLIT] public double makeValue ( Date date ) { double secs = date . getTime ( ) / 1000.0 ; double origin_secs = getDateOrigin ( ) . getTime ( ) / 1000.0 ; double diff = secs - origin_secs ; try { timeUnit . setValueInSeconds ( diff ) ; } catch ( Exception e ) { throw new RuntimeException ( e . getMessage ( ) ) ; } return timeUnit . getValue ( ) ; }


Input: Make a standard GMT string representation from this unit and given value . [CODESPLIT] public String makeStandardDateString ( double value ) { Date date = makeDate ( value ) ; if ( date == null ) return null ; DateFormatter formatter = new DateFormatter ( ) ; return formatter . toDateTimeStringISO ( date ) ; }


Input: Get the grid spacing in kilometers [CODESPLIT] private double getGridSpacingInKm ( String type ) { double value = gds . getDouble ( type ) ; if ( Double . isNaN ( value ) ) return value ; String gridUnit = gds . getParam ( GridDefRecord . GRID_UNITS ) ; SimpleUnit unit ; if ( gridUnit == null || gridUnit . length ( ) == 0 ) { unit = SimpleUnit . meterUnit ; } else { unit = SimpleUnit . factory ( gridUnit ) ; } if ( unit != null && SimpleUnit . isCompatible ( unit . getUnitString ( ) , "km" ) ) { value = unit . convertTo ( value , SimpleUnit . kmUnit ) ; } return value ; }


Input: Add the dimensions associated with this coord sys to the netCDF file [CODESPLIT] void addDimensionsToNetcdfFile ( NetcdfFile ncfile ) { if ( isLatLon ) { ncfile . addDimension ( g , new Dimension ( "lat" , gds . getInt ( GridDefRecord . NY ) , true ) ) ; ncfile . addDimension ( g , new Dimension ( "lon" , gds . getInt ( GridDefRecord . NX ) , true ) ) ; } else { ncfile . addDimension ( g , new Dimension ( "y" , gds . getInt ( GridDefRecord . NY ) , true ) ) ; ncfile . addDimension ( g , new Dimension ( "x" , gds . getInt ( GridDefRecord . NX ) , true ) ) ; } }


Input: Add the variables to the netCDF file [CODESPLIT] void addToNetcdfFile ( NetcdfFile ncfile ) { if ( isLatLon ) { double dy ; if ( gds . getDouble ( GridDefRecord . DY ) == GridDefRecord . UNDEFINED ) { dy = setLatLonDxDy ( ) ; } else { dy = ( gds . getDouble ( GridDefRecord . LA2 ) < gds . getDouble ( GridDefRecord . LA1 ) ) ? - gds . getDouble ( GridDefRecord . DY ) : gds . getDouble ( GridDefRecord . DY ) ; } // lat if ( isGaussian ) { addGaussianLatAxis ( ncfile , "lat" , "degrees_north" , "latitude coordinate" , "latitude" , AxisType . Lat ) ; } else { addCoordAxis ( ncfile , "lat" , gds . getInt ( GridDefRecord . NY ) , gds . getDouble ( GridDefRecord . LA1 ) , dy , "degrees_north" , "latitude coordinate" , "latitude" , AxisType . Lat ) ; } // lon addCoordAxis ( ncfile , "lon" , gds . getInt ( GridDefRecord . NX ) , gds . getDouble ( GridDefRecord . LO1 ) , gds . getDouble ( GridDefRecord . DX ) , "degrees_east" , "longitude coordinate" , "longitude" , AxisType . Lon ) ; // add dummy variable for lat/lon coord system addCoordSystemVariable ( ncfile , "latLonCoordSys" , "time lat lon" ) ; } else { int projType = lookup . getProjectionType ( gds ) ; if ( makeProjection ( ncfile , projType ) ) { double [ ] yData , xData ; if ( projType == GridTableLookup . RotatedLatLon ) { double dy = ( gds . getDouble ( "La2" ) < gds . getDouble ( GridDefRecord . LA1 ) ? - gds . getDouble ( GridDefRecord . DY ) : gds . getDouble ( GridDefRecord . DY ) ) ; yData = addCoordAxis ( ncfile , "y" , gds . getInt ( GridDefRecord . NY ) , gds . getDouble ( GridDefRecord . LA1 ) , dy , "degrees" , "y coordinate of projection" , "projection_y_coordinate" , AxisType . GeoY ) ; xData = addCoordAxis ( ncfile , "x" , gds . getInt ( GridDefRecord . NX ) , gds . getDouble ( GridDefRecord . LO1 ) , gds . getDouble ( GridDefRecord . DX ) , "degrees" , "x coordinate of projection" , "projection_x_coordinate" , AxisType . GeoX ) ; } else if ( projType == GridTableLookup . Orthographic ) { yData = addCoordAxis ( ncfile , "y" , gds . getInt ( GridDefRecord . NY ) , starty , incry , "km" , // fake km - really pixel "y coordinate of projection" , "projection_y_coordinate" , AxisType . GeoY ) ; // dunno what the 3 is xData = addCoordAxis ( ncfile , "x" , gds . getInt ( GridDefRecord . NX ) , startx , incrx , "km" , "x coordinate of projection" , "projection_x_coordinate" , AxisType . GeoX ) ; } else if ( projType == GridTableLookup . Curvilinear ) { yData = null ; xData = null ; } else { yData = addCoordAxis ( ncfile , "y" , gds . getInt ( GridDefRecord . NY ) , starty , getDyInKm ( ) , "km" , "y coordinate of projection" , "projection_y_coordinate" , AxisType . GeoY ) ; xData = addCoordAxis ( ncfile , "x" , gds . getInt ( GridDefRecord . NX ) , startx , getDxInKm ( ) , "km" , "x coordinate of projection" , "projection_x_coordinate" , AxisType . GeoX ) ; } // optional 2D lat/lon if ( GridServiceProvider . addLatLon && ( projType != GridTableLookup . Curvilinear ) ) addLatLon2D ( ncfile , xData , yData ) ; } } }


Input: Add a coordinate axis [CODESPLIT] private double [ ] addCoordAxis ( NetcdfFile ncfile , String name , int n , double start , double incr , String units , String desc , String standard_name , AxisType axis ) { // ncfile.addDimension(g, new Dimension(name, n, true)); Variable v = new Variable ( ncfile , g , null , name ) ; v . setDataType ( DataType . DOUBLE ) ; v . setDimensions ( name ) ; // create the data double [ ] data = new double [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { data [ i ] = start + incr * i ; } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { n } , data ) ; v . setCachedData ( dataArray , false ) ; v . addAttribute ( new Attribute ( "units" , units ) ) ; v . addAttribute ( new Attribute ( "long_name" , desc ) ) ; v . addAttribute ( new Attribute ( "standard_name" , standard_name ) ) ; v . addAttribute ( new Attribute ( "grid_spacing" , incr + " " + units ) ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axis . toString ( ) ) ) ; ncfile . addVariable ( g , v ) ; return data ; }


Input: Add a gaussian lat axis [CODESPLIT] private double [ ] addGaussianLatAxis ( NetcdfFile ncfile , String name , String units , String desc , String standard_name , AxisType axis ) { double np = gds . getDouble ( GridDefRecord . NUMBERPARALLELS ) ; if ( Double . isNaN ( np ) ) np = gds . getDouble ( "Np" ) ; if ( Double . isNaN ( np ) ) throw new IllegalArgumentException ( "Gaussian Lat/Lon grid must have 'NumberParallels' or 'Np' (number of parallels) parameter" ) ; double startLat = gds . getDouble ( GridDefRecord . LA1 ) ; double endLat = gds . getDouble ( GridDefRecord . LA2 ) ; int nlats = ( int ) ( 2 * np ) ; GaussianLatitudes gaussLats = GaussianLatitudes . factory ( nlats ) ; int bestStartIndex = 0 , bestEndIndex = 0 ; double bestStartDiff = Double . MAX_VALUE ; double bestEndDiff = Double . MAX_VALUE ; for ( int i = 0 ; i < nlats ; i ++ ) { double diff = Math . abs ( gaussLats . latd [ i ] - startLat ) ; if ( diff < bestStartDiff ) { bestStartDiff = diff ; bestStartIndex = i ; } diff = Math . abs ( gaussLats . latd [ i ] - endLat ) ; if ( diff < bestEndDiff ) { bestEndDiff = diff ; bestEndIndex = i ; } } int ny = gds . getInt ( GridDefRecord . NY ) ; if ( Math . abs ( bestEndIndex - bestStartIndex + 1 ) != ny ) { log . warn ( "GRIB gaussian lats: NP != NY, use NY" ) ; // see email from Toussaint@dkrz.de datafil: nlats = ny ; gaussLats = GaussianLatitudes . factory ( nlats ) ; bestStartIndex = 0 ; bestEndIndex = ny - 1 ; } boolean goesUp = bestEndIndex > bestStartIndex ; Variable v = new Variable ( ncfile , g , null , name ) ; v . setDataType ( DataType . DOUBLE ) ; v . setDimensions ( name ) ; // create the data int useIndex = bestStartIndex ; double [ ] data = new double [ ny ] ; double [ ] gaussw = new double [ ny ] ; for ( int i = 0 ; i < ny ; i ++ ) { data [ i ] = gaussLats . latd [ useIndex ] ; gaussw [ i ] = gaussLats . gaussw [ useIndex ] ; if ( goesUp ) { useIndex ++ ; } else { useIndex -- ; } } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { ny } , data ) ; v . setCachedData ( dataArray , false ) ; v . addAttribute ( new Attribute ( "units" , units ) ) ; v . addAttribute ( new Attribute ( "long_name" , desc ) ) ; v . addAttribute ( new Attribute ( "standard_name" , standard_name ) ) ; v . addAttribute ( new Attribute ( "weights" , "gaussw" ) ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axis . toString ( ) ) ) ; ncfile . addVariable ( g , v ) ; v = new Variable ( ncfile , g , null , "gaussw" ) ; v . setDataType ( DataType . DOUBLE ) ; v . setDimensions ( name ) ; v . addAttribute ( new Attribute ( "long_name" , "gaussian weights (unnormalized)" ) ) ; dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { ny } , gaussw ) ; v . setCachedData ( dataArray , false ) ; ncfile . addVariable ( g , v ) ; return data ; }


Input: Make a projection and add it to the netCDF file [CODESPLIT] private boolean makeProjection ( NetcdfFile ncfile , int projType ) { switch ( projType ) { case GridTableLookup . RotatedLatLon : makeRotatedLatLon ( ncfile ) ; break ; case GridTableLookup . PolarStereographic : makePS ( ) ; break ; case GridTableLookup . LambertConformal : makeLC ( ) ; break ; case GridTableLookup . Mercator : makeMercator ( ) ; break ; case GridTableLookup . Orthographic : //makeSpaceViewOrOthographic(); makeMSGgeostationary ( ) ; break ; case GridTableLookup . Curvilinear : makeCurvilinearAxis ( ncfile ) ; break ; default : throw new UnsupportedOperationException ( "unknown projection = " + gds . getInt ( GridDefRecord . GRID_TYPE ) ) ; } // dummy coordsys variable Variable v = new Variable ( ncfile , g , null , grid_name ) ; v . setDataType ( DataType . CHAR ) ; v . setDimensions ( "" ) ; // scalar char [ ] data = new char [ ] { ' ' } ; Array dataArray = Array . factory ( DataType . CHAR , new int [ 0 ] , data ) ; v . setCachedData ( dataArray , false ) ; for ( Attribute att : attributes ) v . addAttribute ( att ) ; // add CF Conventions attributes v . addAttribute ( new Attribute ( GridCF . EARTH_SHAPE , shape_name ) ) ; // LOOK - spherical earth ?? double radius_spherical_earth = gds . getDouble ( GridDefRecord . RADIUS_SPHERICAL_EARTH ) ; // have to check both because Grib1 and Grib2 used different names if ( Double . isNaN ( radius_spherical_earth ) ) radius_spherical_earth = gds . getDouble ( "radius_spherical_earth" ) ; if ( ! Double . isNaN ( radius_spherical_earth ) ) { //inconsistent - sometimes in km, sometimes in m. if ( radius_spherical_earth < 10000.00 ) // then its in km radius_spherical_earth *= 1000.0 ; // convert to meters v . addAttribute ( new Attribute ( GridCF . EARTH_RADIUS , radius_spherical_earth ) ) ; //this attribute needs to be meters } else { // oblate earth double major_axis = gds . getDouble ( GridDefRecord . MAJOR_AXIS_EARTH ) ; if ( Double . isNaN ( major_axis ) ) major_axis = gds . getDouble ( "major_axis_earth" ) ; double minor_axis = gds . getDouble ( GridDefRecord . MINOR_AXIS_EARTH ) ; if ( Double . isNaN ( minor_axis ) ) minor_axis = gds . getDouble ( "minor_axis_earth" ) ; if ( ! Double . isNaN ( major_axis ) && ! Double . isNaN ( minor_axis ) ) { v . addAttribute ( new Attribute ( GridCF . SEMI_MAJOR_AXIS , major_axis ) ) ; v . addAttribute ( new Attribute ( GridCF . SEMI_MINOR_AXIS , minor_axis ) ) ; } } addGDSparams ( v ) ; ncfile . addVariable ( g , v ) ; return true ; }


Input: Add the GDS params to the variable as attributes [CODESPLIT] private void addGDSparams ( Variable v ) { // add all the gds parameters List < String > keyList = new ArrayList <> ( gds . getKeys ( ) ) ; Collections . sort ( keyList ) ; String pre = getGDSprefix ( ) ; for ( String key : keyList ) { String name = pre + "_param_" + key ; String vals = gds . getParam ( key ) ; try { int vali = Integer . parseInt ( vals ) ; if ( key . equals ( GridDefRecord . VECTOR_COMPONENT_FLAG ) ) { String cf = GridCF . VectorComponentFlag . of ( vali ) ; v . addAttribute ( new Attribute ( name , cf ) ) ; } else { v . addAttribute ( new Attribute ( name , vali ) ) ; } } catch ( Exception e ) { try { double vald = Double . parseDouble ( vals ) ; v . addAttribute ( new Attribute ( name , vald ) ) ; } catch ( Exception e2 ) { v . addAttribute ( new Attribute ( name , vals ) ) ; } } } }


Input: Add coordinate system variable [CODESPLIT] private void addCoordSystemVariable ( NetcdfFile ncfile , String name , String dims ) { Variable v = new Variable ( ncfile , g , null , name ) ; v . setDataType ( DataType . CHAR ) ; v . setDimensions ( "" ) ; // scalar Array dataArray = Array . factory ( DataType . CHAR , new int [ 0 ] , new char [ ] { ' ' } ) ; v . setCachedData ( dataArray , false ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , dims ) ) ; if ( isLatLon ( ) ) v . addAttribute ( new Attribute ( _Coordinate . Transforms , "" ) ) ; // to make sure its identified as a Coordinate System Variable else v . addAttribute ( new Attribute ( _Coordinate . Transforms , getGridName ( ) ) ) ; addGDSparams ( v ) ; ncfile . addVariable ( g , v ) ; }


Input: Make a LambertConformalConic projection [CODESPLIT] private void makeLC ( ) { // we have to project in order to find the origin proj = new LambertConformal ( gds . getDouble ( GridDefRecord . LATIN1 ) , gds . getDouble ( GridDefRecord . LOV ) , gds . getDouble ( GridDefRecord . LATIN1 ) , gds . getDouble ( GridDefRecord . LATIN2 ) ) ; LatLonPointImpl startLL = new LatLonPointImpl ( gds . getDouble ( GridDefRecord . LA1 ) , gds . getDouble ( GridDefRecord . LO1 ) ) ; ProjectionPointImpl start = ( ProjectionPointImpl ) proj . latLonToProj ( startLL ) ; startx = start . getX ( ) ; starty = start . getY ( ) ; if ( Double . isNaN ( getDxInKm ( ) ) ) { setDxDy ( startx , starty , proj ) ; } if ( GridServiceProvider . debugProj ) { System . out . println ( "GridHorizCoordSys.makeLC start at latlon " + startLL ) ; double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( "GridHorizCoordSys.makeLC end at latlon " + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( "   end at proj coord " + endPP ) ; double endx = startx + getNx ( ) * getDxInKm ( ) ; double endy = starty + getNy ( ) * getDyInKm ( ) ; System . out . println ( "   should be x=" + endx + " y=" + endy ) ; } attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "lambert_conformal_conic" ) ) ; if ( gds . getDouble ( GridDefRecord . LATIN1 ) == gds . getDouble ( GridDefRecord . LATIN2 ) ) { attributes . add ( new Attribute ( GridCF . STANDARD_PARALLEL , gds . getDouble ( GridDefRecord . LATIN1 ) ) ) ; } else { double [ ] data = new double [ ] { gds . getDouble ( GridDefRecord . LATIN1 ) , gds . getDouble ( GridDefRecord . LATIN2 ) } ; attributes . add ( new Attribute ( GridCF . STANDARD_PARALLEL , Array . factory ( DataType . DOUBLE , new int [ ] { 2 } , data ) ) ) ; } //attributes.add(new Attribute("longitude_of_central_meridian", attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_CENTRAL_MERIDIAN , gds . getDouble ( GridDefRecord . LOV ) ) ) ; //attributes.add(new Attribute("latitude_of_projection_origin", attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , gds . getDouble ( GridDefRecord . LATIN1 ) ) ) ; }


Input: Make a PolarStereographic projection [CODESPLIT] private void makePS ( ) { String nproj = gds . getParam ( GridDefRecord . NPPROJ ) ; double latOrigin = ( nproj == null || nproj . equalsIgnoreCase ( "true" ) ) ? 90.0 : - 90.0 ; // Why the scale factor?. according to GRIB docs: // "Grid lengths are in units of meters, at the 60 degree latitude circle nearest to the pole" // since the scale factor at 60 degrees = k = 2*k0/(1+sin(60))  [Snyder,Working Manual p157] // then to make scale = 1 at 60 degrees, k0 = (1+sin(60))/2 = .933 double scale ; double lad = gds . getDouble ( GridDefRecord . LAD ) ; if ( Double . isNaN ( lad ) ) { scale = .933 ; } else { scale = ( 1.0 + Math . sin ( Math . toRadians ( Math . abs ( lad ) ) ) ) / 2 ; } proj = new Stereographic ( latOrigin , gds . getDouble ( GridDefRecord . LOV ) , scale ) ; // we have to project in order to find the origin ProjectionPointImpl start = ( ProjectionPointImpl ) proj . latLonToProj ( new LatLonPointImpl ( gds . getDouble ( GridDefRecord . LA1 ) , gds . getDouble ( GridDefRecord . LO1 ) ) ) ; startx = start . getX ( ) ; starty = start . getY ( ) ; if ( Double . isNaN ( getDxInKm ( ) ) ) setDxDy ( startx , starty , proj ) ; if ( GridServiceProvider . debugProj ) { System . out . printf ( "starting proj coord %s lat/lon %s%n" , start , proj . projToLatLon ( start ) ) ; System . out . println ( "   should be LA1=" + gds . getDouble ( GridDefRecord . LA1 ) + " l)1=" + gds . getDouble ( GridDefRecord . LO1 ) ) ; } attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "polar_stereographic" ) ) ; //attributes.add(new Attribute("longitude_of_projection_origin", attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , gds . getDouble ( GridDefRecord . LOV ) ) ) ; //attributes.add(new Attribute("straight_vertical_longitude_from_pole", attributes . add ( new Attribute ( GridCF . STRAIGHT_VERTICAL_LONGITUDE_FROM_POLE , gds . getDouble ( GridDefRecord . LOV ) ) ) ; //attributes.add(new Attribute("scale_factor_at_projection_origin", attributes . add ( new Attribute ( GridCF . SCALE_FACTOR_AT_PROJECTION_ORIGIN , scale ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , latOrigin ) ) ; }


Input:
Make a Mercator projection [CODESPLIT] private void makeMercator ( ) { /**
     * Construct a Mercator Projection.
     * @param lon0 longitude of origin (degrees)
     * @param par standard parallel (degrees). cylinder cuts earth at this latitude.
     */ double Latin = gds . getDouble ( GridDefRecord . LAD ) ; // name depends on Grib version 1 or 2 if ( Double . isNaN ( Latin ) ) Latin = gds . getDouble ( GridDefRecord . LATIN ) ; double Lo1 = gds . getDouble ( GridDefRecord . LO1 ) ; //gds.Lo1; double La1 = gds . getDouble ( GridDefRecord . LA1 ) ; //gds.La1; // put longitude origin at first point - doesnt actually matter proj = new Mercator ( Lo1 , Latin ) ; // find out where ProjectionPoint startP = proj . latLonToProj ( new LatLonPointImpl ( La1 , Lo1 ) ) ; startx = startP . getX ( ) ; starty = startP . getY ( ) ; if ( Double . isNaN ( getDxInKm ( ) ) ) { setDxDy ( startx , starty , proj ) ; } attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "mercator" ) ) ; attributes . add ( new Attribute ( GridCF . STANDARD_PARALLEL , Latin ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lo1 ) ) ; if ( GridServiceProvider . debugProj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; if ( Lo2 < Lo1 ) Lo2 += 360 ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( "GridHorizCoordSys.makeMercator: end at latlon= " + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( "   start at proj coord " + new ProjectionPointImpl ( startx , starty ) ) ; System . out . println ( "   end at proj coord " + endPP ) ; double endx = startx + ( getNx ( ) - 1 ) * getDxInKm ( ) ; double endy = starty + ( getNy ( ) - 1 ) * getDyInKm ( ) ; System . out . println ( "   should be x=" + endx + " y=" + endy ) ; } }


Input: RotatedLatLon [CODESPLIT] private void makeRotatedLatLon ( NetcdfFile ncfile ) { double splat = gds . getDouble ( GridDefRecord . SPLAT ) ; double splon = gds . getDouble ( GridDefRecord . SPLON ) ; double spangle = gds . getDouble ( GridDefRecord . ROTATIONANGLE ) ; // Given projection coordinates, need LatLon coordinates proj = new RotatedLatLon ( splat , splon , spangle ) ; LatLonPoint startLL = proj . projToLatLon ( new ProjectionPointImpl ( gds . getDouble ( GridDefRecord . LO1 ) , gds . getDouble ( GridDefRecord . LA1 ) ) ) ; startx = startLL . getLongitude ( ) ; starty = startLL . getLatitude ( ) ; addCoordSystemVariable ( ncfile , "latLonCoordSys" , "time y x" ) ; // splat, splon, spangle attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "rotated_latlon_grib" ) ) ; attributes . add ( new Attribute ( "grid_south_pole_latitude" , splat ) ) ; attributes . add ( new Attribute ( "grid_south_pole_longitude" , splon ) ) ; attributes . add ( new Attribute ( "grid_south_pole_angle" , spangle ) ) ; if ( GridServiceProvider . debugProj ) { System . out . println ( "Location of pole of rotated grid:" ) ; System . out . println ( "Lon=" + splon + ", Lat=" + splat ) ; System . out . println ( "Axial rotation about pole of rotated grid:" + spangle ) ; System . out . println ( "Location of LL in rotated grid:" ) ; System . out . println ( "Lon=" + gds . getDouble ( GridDefRecord . LO1 ) + ", " + "Lat=" + gds . getDouble ( GridDefRecord . LA1 ) ) ; System . out . println ( "Location of LL in non-rotated grid:" ) ; System . out . println ( "Lon=" + startx + ", Lat=" + starty ) ; double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; System . out . println ( "Location of UR in rotated grid:" ) ; System . out . println ( "Lon=" + Lo2 + ", Lat=" + La2 ) ; System . out . println ( "Location of UR in non-rotated grid:" ) ; LatLonPoint endUR = proj . projToLatLon ( new ProjectionPointImpl ( Lo2 , La2 ) ) ; System . out . println ( "Lon=" + endUR . getLongitude ( ) + ", Lat=" + endUR . getLatitude ( ) ) ; double dy = ( La2 < gds . getDouble ( GridDefRecord . LA1 ) ) ? - gds . getDouble ( GridDefRecord . DY ) : gds . getDouble ( GridDefRecord . DY ) ; double endx = gds . getDouble ( GridDefRecord . LO1 ) + ( getNx ( ) - 1 ) * gds . getDouble ( GridDefRecord . DX ) ; double endy = gds . getDouble ( GridDefRecord . LA1 ) + ( getNy ( ) - 1 ) * dy ; System . out . println ( "End point rotated grid should be x=" + endx + " y=" + endy ) ; } }


Input: Make a Space View Orthographic projection [CODESPLIT] private void makeSpaceViewOrOthographic ( ) { double Lat0 = gds . getDouble ( GridDefRecord . LAP ) ; // sub-satellite point lat double Lon0 = gds . getDouble ( GridDefRecord . LOP ) ; // sub-satellite point lon double xp = gds . getDouble ( GridDefRecord . XP ) ; // sub-satellite point in grid lengths double yp = gds . getDouble ( GridDefRecord . YP ) ; double dx = gds . getDouble ( GridDefRecord . DX ) ; // apparent diameter in units of grid lengths double dy = gds . getDouble ( GridDefRecord . DY ) ; // have to check both names because Grib1 and Grib2 used different names double major_axis = gds . getDouble ( GridDefRecord . MAJOR_AXIS_EARTH ) ; // km if ( Double . isNaN ( major_axis ) ) major_axis = gds . getDouble ( "major_axis_earth" ) ; double minor_axis = gds . getDouble ( GridDefRecord . MINOR_AXIS_EARTH ) ; // km if ( Double . isNaN ( minor_axis ) ) minor_axis = gds . getDouble ( "minor_axis_earth" ) ; // Nr = altitude of camera from center, in units of radius double nr = gds . getDouble ( GridDefRecord . NR ) * 1e-6 ; double apparentDiameter = 2 * Math . sqrt ( ( nr - 1 ) / ( nr + 1 ) ) ; // apparent diameter, units of radius (see Snyder p 173) // app diameter kmeters / app diameter grid lengths = m per grid length double gridLengthX = major_axis * apparentDiameter / dx ; double gridLengthY = minor_axis * apparentDiameter / dy ; // have to add to both for consistency gds . addParam ( GridDefRecord . DX , String . valueOf ( 1000 * gridLengthX ) ) ; // meters gds . addParam ( GridDefRecord . DX , new Double ( 1000 * gridLengthX ) ) ; gds . addParam ( GridDefRecord . DY , String . valueOf ( 1000 * gridLengthY ) ) ; // meters gds . addParam ( GridDefRecord . DY , new Double ( 1000 * gridLengthY ) ) ; startx = - gridLengthX * xp ; // km starty = - gridLengthY * yp ; double radius = Earth . getRadius ( ) / 1000.0 ; // km if ( nr == 1111111111.0 ) { // LOOK: not sure how all ones will appear as a double, need example proj = new Orthographic ( Lat0 , Lon0 , radius ) ; attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "orthographic" ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lon0 ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , Lat0 ) ) ; } else { // "space view perspective" double height = ( nr - 1.0 ) * radius ; // height = the height of the observing camera in km proj = new VerticalPerspectiveView ( Lat0 , Lon0 , radius , height ) ; attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "vertical_perspective" ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lon0 ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , Lat0 ) ) ; attributes . add ( new Attribute ( "height_above_earth" , height ) ) ; } if ( GridServiceProvider . debugProj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) + 360.0 ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( "GridHorizCoordSys.makeOrthographic end at latlon " + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( "   end at proj coord " + endPP ) ; double endx = startx + getNx ( ) * getDxInKm ( ) ; double endy = starty + getNy ( ) * getDyInKm ( ) ; System . out . println ( "   should be x=" + endx + " y=" + endy ) ; } }


Input: Make a Eumetsat MSG Normalized Geostationary Projection projection . Fake coordinates for now then see if this can be generalized . [CODESPLIT] private void makeMSGgeostationary ( ) { double Lat0 = gds . getDouble ( GridDefRecord . LAP ) ; // sub-satellite point lat double Lon0 = gds . getDouble ( GridDefRecord . LOP ) ; // sub-satellite point lon //int nx = gds.getInt(GridDefRecord.NX); int ny = gds . getInt ( GridDefRecord . NY ) ; int x_off = gds . getInt ( GridDefRecord . XP ) ; // sub-satellite point in grid lengths int y_off = gds . getInt ( GridDefRecord . YP ) ; double dx ; // = gds.getDouble(GridDefRecord.DX);  // apparent diameter of earth in units of grid lengths double dy = gds . getDouble ( GridDefRecord . DY ) ; // per Simon Eliot 1/18/2010, there is a bug in Eumetsat grib files, // we need to "correct for ellipsoidal earth" // (Note we should check who the originating center is // "Originating_center" = "EUMETSAT Operation Centre" in the GRIB id (section 1)) // although AFAIK, eumetsat is only one using this projection. if ( dy < 2100 ) { dx = 1207 ; dy = 1203 ; } else { dx = 3622 ; dy = 3610 ; } // have to check both names because Grib1 and Grib2 used different names double major_axis = gds . getDouble ( GridDefRecord . MAJOR_AXIS_EARTH ) ; // m if ( Double . isNaN ( major_axis ) ) major_axis = gds . getDouble ( "major_axis_earth" ) ; double minor_axis = gds . getDouble ( GridDefRecord . MINOR_AXIS_EARTH ) ; // m if ( Double . isNaN ( minor_axis ) ) minor_axis = gds . getDouble ( "minor_axis_earth" ) ; // Nr = altitude of camera from center, in units of radius double nr = gds . getDouble ( GridDefRecord . NR ) * 1e-6 ; // altitude of the camera from the Earths centre, measured in units of the Earth (equatorial) radius // CFAC = 2^16 / {[2 * arcsine (10^6 / Nr)] / dx } double as = 2 * Math . asin ( 1.0 / nr ) ; double cfac = dx / as ; double lfac = dy / as ; // use km, so scale by the earth radius double scale_factor = ( nr - 1 ) * major_axis / 1000 ; // this sets the units of the projection x,y coords in km double scale_x = scale_factor ; // LOOK fake neg need scan value double scale_y = - scale_factor ; // LOOK fake neg need scan value startx = scale_factor * ( 1 - x_off ) / cfac ; starty = scale_factor * ( y_off - ny ) / lfac ; incrx = scale_factor / cfac ; incry = scale_factor / lfac ; attributes . add ( new Attribute ( GridCF . GRID_MAPPING_NAME , "MSGnavigation" ) ) ; attributes . add ( new Attribute ( GridCF . LONGITUDE_OF_PROJECTION_ORIGIN , Lon0 ) ) ; attributes . add ( new Attribute ( GridCF . LATITUDE_OF_PROJECTION_ORIGIN , Lat0 ) ) ; //attributes.add(new Attribute("semi_major_axis", new Double(major_axis))); //attributes.add(new Attribute("semi_minor_axis", new Double(minor_axis))); attributes . add ( new Attribute ( "height_from_earth_center" , nr * major_axis ) ) ; attributes . add ( new Attribute ( "scale_x" , scale_x ) ) ; attributes . add ( new Attribute ( "scale_y" , scale_y ) ) ; proj = new MSGnavigation ( Lat0 , Lon0 , major_axis , minor_axis , nr * major_axis , scale_x , scale_y ) ; if ( GridServiceProvider . debugProj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) + 360.0 ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; System . out . println ( "GridHorizCoordSys.makeMSGgeostationary end at latlon " + endLL ) ; ProjectionPointImpl endPP = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; System . out . println ( "   end at proj coord " + endPP ) ; double endx = 1 + getNx ( ) ; double endy = 1 + getNy ( ) ; System . out . println ( "   should be x=" + endx + " y=" + endy ) ; } }


Input:
CurvilinearAxis [CODESPLIT] private void makeCurvilinearAxis ( NetcdfFile ncfile ) { List < Variable > vars = ncfile . getRootGroup ( ) . getVariables ( ) ; String latpp = null , lonpp = null , latU = null , lonU = null , latV = null , lonV = null ; // has to be done twice because there's no guarantee that the // coordinate variables will be accessed first List < String > timeDimLL = new ArrayList <> ( ) ; List < String > timeDimV = new ArrayList <> ( ) ; for ( Variable var : vars ) { if ( var . getShortName ( ) . startsWith ( "Latitude" ) ) { // remove time dependency int [ ] shape = var . getShape ( ) ; if ( var . getRank ( ) == 3 && shape [ 0 ] == 1 ) { // remove time dependencies - MAJOR KLUDGE List < Dimension > dims = var . getDimensions ( ) ; if ( ! timeDimLL . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimLL . add ( dims . get ( 0 ) . getShortName ( ) ) ; dims . remove ( 0 ) ; var . setDimensions ( dims ) ; } // add lat attributes var . addAttribute ( new Attribute ( "units" , "degrees_north" ) ) ; var . addAttribute ( new Attribute ( "long_name" , "latitude coordinate" ) ) ; var . addAttribute ( new Attribute ( "standard_name" , "latitude" ) ) ; var . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; if ( var . getShortName ( ) . contains ( "U_Wind_Component" ) ) { latU = var . getFullName ( ) ; } else if ( var . getShortName ( ) . contains ( "V_Wind_Component" ) ) { latV = var . getFullName ( ) ; } else { latpp = var . getFullName ( ) ; } } else if ( var . getShortName ( ) . startsWith ( "Longitude" ) ) { // remove time dependency int [ ] shape = var . getShape ( ) ; if ( var . getRank ( ) == 3 && shape [ 0 ] == 1 ) { // remove time dependencies - MAJOR KLUDGE List < Dimension > dims = var . getDimensions ( ) ; if ( ! timeDimLL . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimLL . add ( dims . get ( 0 ) . getShortName ( ) ) ; dims . remove ( 0 ) ; var . setDimensions ( dims ) ; } // add lon attributes var . addAttribute ( new Attribute ( "units" , "degrees_east" ) ) ; var . addAttribute ( new Attribute ( "long_name" , "longitude coordinate" ) ) ; var . addAttribute ( new Attribute ( "standard_name" , "longitude" ) ) ; var . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; if ( var . getShortName ( ) . contains ( "U_Wind_Component" ) ) { lonU = var . getFullName ( ) ; } else if ( var . getShortName ( ) . contains ( "V_Wind_Component" ) ) { lonV = var . getFullName ( ) ; } else { lonpp = var . getFullName ( ) ; } } } // add coordinates attribute to variables for ( Variable var : vars ) { List < Dimension > dims = var . getDimensions ( ) ; if ( var . getShortName ( ) . startsWith ( "U-component" ) ) { var . addAttribute ( new Attribute ( "coordinates" , latU + " " + lonU ) ) ; if ( ! timeDimV . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimV . add ( dims . get ( 0 ) . getShortName ( ) ) ; } else if ( var . getShortName ( ) . startsWith ( "V-component" ) ) { var . addAttribute ( new Attribute ( "coordinates" , latV + " " + lonV ) ) ; if ( ! timeDimV . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimV . add ( dims . get ( 0 ) . getShortName ( ) ) ; // rest of variables default to Pressure_Point } else { var . addAttribute ( new Attribute ( "coordinates" , latpp + " " + lonpp ) ) ; if ( ! timeDimV . contains ( dims . get ( 0 ) . getShortName ( ) ) ) timeDimV . add ( dims . get ( 0 ) . getShortName ( ) ) ; } } /* remove Latitude/Longitude time dimension and variable if possible
    for( String tdLL : timeDimLL) {
      if( timeDimV.contains( tdLL ))
        continue;
      // else only used with Lat/Lon
      ncfile.getRootGroup().removeDimension( tdLL );
      ncfile.getRootGroup().removeVariable( tdLL );
    } */ }


Input: Calculate the dx and dy from startx starty and projection . [CODESPLIT] private void setDxDy ( double startx , double starty , ProjectionImpl proj ) { double Lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double La2 = gds . getDouble ( GridDefRecord . LA2 ) ; if ( Double . isNaN ( Lo2 ) || Double . isNaN ( La2 ) ) { return ; } LatLonPointImpl endLL = new LatLonPointImpl ( La2 , Lo2 ) ; ProjectionPointImpl end = ( ProjectionPointImpl ) proj . latLonToProj ( endLL ) ; double dx = Math . abs ( end . getX ( ) - startx ) / ( gds . getInt ( GridDefRecord . NX ) - 1 ) ; double dy = Math . abs ( end . getY ( ) - starty ) / ( gds . getInt ( GridDefRecord . NY ) - 1 ) ; gds . addParam ( GridDefRecord . DX , String . valueOf ( dx ) ) ; gds . addParam ( GridDefRecord . DY , String . valueOf ( dy ) ) ; gds . addParam ( GridDefRecord . GRID_UNITS , "km" ) ; }


Input: Calculate Dx Dy Lat Lon Grid Note : this assumes lo1 < lo2 and dx is positive going east [CODESPLIT] private double setLatLonDxDy ( ) { double lo1 = gds . getDouble ( GridDefRecord . LO1 ) ; double la1 = gds . getDouble ( GridDefRecord . LA1 ) ; double lo2 = gds . getDouble ( GridDefRecord . LO2 ) ; double la2 = gds . getDouble ( GridDefRecord . LA2 ) ; if ( Double . isNaN ( lo2 ) || Double . isNaN ( la2 ) ) { return Double . NaN ; } if ( lo2 < lo1 ) lo2 += 360 ; double dx = Math . abs ( lo2 - lo1 ) / ( gds . getInt ( GridDefRecord . NX ) - 1 ) ; double dy = Math . abs ( la2 - la1 ) / ( gds . getInt ( GridDefRecord . NY ) - 1 ) ; gds . addParam ( GridDefRecord . DX , String . valueOf ( dx ) ) ; gds . addParam ( GridDefRecord . DY , String . valueOf ( dy ) ) ; // in case someone checked on these before, we need to override gds . addParam ( GridDefRecord . DX , new Double ( dx ) ) ; gds . addParam ( GridDefRecord . DY , new Double ( dy ) ) ; gds . addParam ( GridDefRecord . GRID_UNITS , "degree" ) ; return dy ; }


Input: /////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected InvAccessImpl readAccess ( InvDatasetImpl dataset , Element accessElem ) { String urlPath = accessElem . getAttributeValue ( "urlPath" ) ; String serviceName = accessElem . getAttributeValue ( "serviceName" ) ; String dataFormat = accessElem . getAttributeValue ( "dataFormat" ) ; return new InvAccessImpl ( dataset , urlPath , serviceName , null , dataFormat , readDataSize ( accessElem ) ) ; }


Input: read a dataset element [CODESPLIT] protected InvDatasetImpl readDataset ( InvCatalogImpl catalog , InvDatasetImpl parent , Element dsElem , URI base ) { // deal with aliases String name = dsElem . getAttributeValue ( "name" ) ; String alias = dsElem . getAttributeValue ( "alias" ) ; if ( alias != null ) { InvDatasetImpl ds = ( InvDatasetImpl ) catalog . findDatasetByID ( alias ) ; if ( ds == null ) { factory . appendErr ( " ** Parse error: dataset named " + name + " has illegal alias = " + alias + "\n" ) ; return null ; } return new InvDatasetImplProxy ( name , ds ) ; } InvDatasetImpl dataset = new InvDatasetImpl ( parent , name ) ; readDatasetInfo ( catalog , dataset , dsElem , base ) ; if ( InvCatalogFactory . debugXML ) System . out . println ( " Dataset added: " + dataset . dump ( ) ) ; return dataset ; }


Input: read a dataset scan element [CODESPLIT] protected InvDatasetScan readDatasetScan ( InvCatalogImpl catalog , InvDatasetImpl parent , Element dsElem , URI base ) { InvDatasetScan datasetScan ; if ( dsElem . getAttributeValue ( "dirLocation" ) == null ) { if ( dsElem . getAttributeValue ( "location" ) == null ) { logger . error ( "readDatasetScan(): datasetScan has neither a \"location\" nor a \"dirLocation\" attribute." ) ; datasetScan = null ; } else { return readDatasetScanNew ( catalog , parent , dsElem , base ) ; } } else { String name = dsElem . getAttributeValue ( "name" ) ; factory . appendWarning ( "**Warning: Dataset " + name + " using old form of DatasetScan (dirLocation instead of location)\n" ) ; String path = dsElem . getAttributeValue ( "path" ) ; String scanDir = expandAliasForPath ( dsElem . getAttributeValue ( "dirLocation" ) ) ; String filter = dsElem . getAttributeValue ( "filter" ) ; String addDatasetSizeString = dsElem . getAttributeValue ( "addDatasetSize" ) ; String addLatest = dsElem . getAttributeValue ( "addLatest" ) ; String sortOrderIncreasingString = dsElem . getAttributeValue ( "sortOrderIncreasing" ) ; boolean sortOrderIncreasing = false ; if ( sortOrderIncreasingString != null ) if ( sortOrderIncreasingString . equalsIgnoreCase ( "true" ) ) sortOrderIncreasing = true ; boolean addDatasetSize = true ; if ( addDatasetSizeString != null ) if ( addDatasetSizeString . equalsIgnoreCase ( "false" ) ) addDatasetSize = false ; if ( path != null ) { if ( path . charAt ( 0 ) == ' ' ) path = path . substring ( 1 ) ; int last = path . length ( ) - 1 ; if ( path . charAt ( last ) == ' ' ) path = path . substring ( 0 , last ) ; } if ( scanDir != null ) { int last = scanDir . length ( ) - 1 ; if ( scanDir . charAt ( last ) != ' ' ) scanDir = scanDir + ' ' ; } Element atcElem = dsElem . getChild ( "addTimeCoverage" , defNS ) ; String dsNameMatchPattern = null ; String startTimeSubstitutionPattern = null ; String duration = null ; if ( atcElem != null ) { dsNameMatchPattern = atcElem . getAttributeValue ( "datasetNameMatchPattern" ) ; startTimeSubstitutionPattern = atcElem . getAttributeValue ( "startTimeSubstitutionPattern" ) ; duration = atcElem . getAttributeValue ( "duration" ) ; } try { datasetScan = new InvDatasetScan ( catalog , parent , name , path , scanDir , filter , addDatasetSize , addLatest , sortOrderIncreasing , dsNameMatchPattern , startTimeSubstitutionPattern , duration ) ; readDatasetInfo ( catalog , datasetScan , dsElem , base ) ; if ( InvCatalogFactory . debugXML ) System . out . println ( " Dataset added: " + datasetScan . dump ( ) ) ; } catch ( Exception e ) { logger . error ( "Reading DatasetScan" , e ) ; datasetScan = null ; } } return datasetScan ; }


Input: } [CODESPLIT] protected DatasetEnhancer readDatasetScanAddTimeCoverage ( Element addTimeCovElem ) { DatasetEnhancer timeCovEnhancer = null ; String matchName = addTimeCovElem . getAttributeValue ( "datasetNameMatchPattern" ) ; String matchPath = addTimeCovElem . getAttributeValue ( "datasetPathMatchPattern" ) ; String subst = addTimeCovElem . getAttributeValue ( "startTimeSubstitutionPattern" ) ; String duration = addTimeCovElem . getAttributeValue ( "duration" ) ; if ( matchName != null && subst != null && duration != null ) { timeCovEnhancer = RegExpAndDurationTimeCoverageEnhancer . getInstanceToMatchOnDatasetName ( matchName , subst , duration ) ; } else if ( matchPath != null && subst != null && duration != null ) { timeCovEnhancer = RegExpAndDurationTimeCoverageEnhancer . getInstanceToMatchOnDatasetPath ( matchPath , subst , duration ) ; } return timeCovEnhancer ; }


Input: / * MetadataConverterIF [CODESPLIT] public Object readMetadataContent ( InvDataset dataset , org . jdom2 . Element mdataElement ) { InvMetadata m = readMetadata ( dataset . getParentCatalog ( ) , ( InvDatasetImpl ) dataset , mdataElement ) ; return m . getThreddsMetadata ( ) ; }


Input: this is only called for ThredddsMetadata [CODESPLIT] public Object readMetadataContentFromURL ( InvDataset dataset , java . net . URI uri ) throws java . io . IOException { Element elem = readContentFromURL ( uri ) ; Object contentObject = readMetadataContent ( dataset , elem ) ; if ( debugMetadataRead ) System . out . println ( " convert to " + contentObject . getClass ( ) . getName ( ) ) ; return contentObject ; }


Input: Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( InvCatalogImpl catalog , OutputStream os , boolean raw ) throws IOException { this . raw = raw ; writeXML ( catalog , os ) ; this . raw = false ; }


Input: / * protected void writeCat6InheritedMetadata ( Element elem ThreddsMetadata tmi ) { if (( tmi . getDataType () == null ) && ( tmi . getServiceName () == null ) && ( tmi . getAuthority () == null ) && ( tmi . getProperties () . size () == 0 )) return ; [CODESPLIT] protected void writeInheritedMetadata ( Element elem , ThreddsMetadata tmi ) { Element mdataElem = new Element ( "metadata" , defNS ) ; mdataElem . setAttribute ( "inherited" , "true" ) ; writeThreddsMetadata ( mdataElem , tmi ) ; if ( mdataElem . getChildren ( ) . size ( ) > 0 ) elem . addContent ( mdataElem ) ; }


Input: Get the type for the first level of this GridRecord [CODESPLIT] public int getLevelType1 ( ) { // TODO:  flush this out int gribLevel = getDirBlock ( ) [ 51 ] ; int levelType = 0 ; if ( ! ( ( gribLevel == McIDASUtil . MCMISSING ) || ( gribLevel == 0 ) ) ) { levelType = gribLevel ; } else { levelType = 1 ; } return levelType ; }


Input: Check if this is a valid file for this IOServiceProvider . You must make this method thread safe ie dont keep any state . [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { raf . seek ( 0 ) ; String test = raf . readString ( MAGIC . length ( ) ) ; return test . equals ( MAGIC ) ; }


Input:
Open existing file and populate ncfile with it . This method is only called by the NetcdfFile constructor on itself . The provided NetcdfFile object will be empty except for the location String and the IOServiceProvider associated with this NetcdfFile object . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; Structure seq = new Sequence ( ncfile , null , null , RECORD ) ; ncfile . addVariable ( null , seq ) ; /*
    makeLightningVariable(NetcdfFile ncfile, Group group,
                          Structure seq, String name,
                          DataType dataType, String dims,
                          String longName, String cfName,
                          String units, AxisType type) {
    */ Variable v = makeLightningVariable ( ncfile , null , seq , TSEC , DataType . INT , "" , "time of stroke" , null , secondsSince1970 , AxisType . Time ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , "nsec" , DataType . INT , "" , "nanoseconds since tsec" , null , "1.0e-9 s" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , LAT , DataType . INT , "" , "latitude" , "latitude" , CDM . LAT_UNITS , AxisType . Lat ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , new Float ( 1.0e-3 ) ) ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , LON , DataType . INT , "" , "longitude" , "longitude" , CDM . LON_UNITS , AxisType . Lon ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , new Float ( 1.0e-3 ) ) ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , SIGNAL , DataType . SHORT , "" , "signal strength/polarity [150 NLDN measures ~= 30 kAmps]" , null , "" , null ) ; v . addAttribute ( new Attribute ( CDM . SCALE_FACTOR , new Float ( 1.0e-1 ) ) ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , MULTIPLICITY , DataType . BYTE , "" , "multiplicity [#strokes per flash]" , null , "" , null ) ; seq . addMemberVariable ( v ) ; v = new Variable ( ncfile , null , seq , FILL ) ; v . setDataType ( DataType . BYTE ) ; v . setDimensions ( "" ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , MAJOR_AXIS , DataType . BYTE , "" , "error ellipse semi-major axis" , null , "" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , ECCENTRICITY , DataType . BYTE , "" , "error ellipse eccentricity " , null , "" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , ELLIPSE_ANGLE , DataType . BYTE , "" , "error ellipse axis angle of orientation " , null , "degrees" , null ) ; seq . addMemberVariable ( v ) ; v = makeLightningVariable ( ncfile , null , seq , CHISQR , DataType . BYTE , "" , "chi-squared" , null , "" , null ) ; seq . addMemberVariable ( v ) ; addLightningGlobalAttributes ( ncfile ) ; ncfile . finish ( ) ; sm = seq . makeStructureMembers ( ) ; sm . findMember ( TSEC ) . setDataParam ( 0 ) ; sm . findMember ( NSEC ) . setDataParam ( 4 ) ; sm . findMember ( LAT ) . setDataParam ( 8 ) ; sm . findMember ( LON ) . setDataParam ( 12 ) ; sm . findMember ( SIGNAL ) . setDataParam ( 18 ) ; sm . findMember ( MULTIPLICITY ) . setDataParam ( 22 ) ; sm . findMember ( FILL ) . setDataParam ( 23 ) ; sm . findMember ( MAJOR_AXIS ) . setDataParam ( 24 ) ; sm . findMember ( ECCENTRICITY ) . setDataParam ( 25 ) ; sm . findMember ( ELLIPSE_ANGLE ) . setDataParam ( 26 ) ; sm . findMember ( CHISQR ) . setDataParam ( 27 ) ; sm . setStructureSize ( recSize ) ; }


Input: Add the global attributes . [CODESPLIT] protected void addLightningGlobalAttributes ( NetcdfFile ncfile ) { super . addLightningGlobalAttributes ( ncfile ) ; ncfile . addAttribute ( null , new Attribute ( "title" , "NLDN Lightning Data" ) ) ; ncfile . addAttribute ( null , new Attribute ( CDM . CONVENTIONS , "NLDN-CDM" ) ) ; }


Input: Read data from a top level Variable and return a memory resident Array . This Array has the same element type as the Variable and the requested shape . [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { return new ArraySequence ( sm , new SeqIter ( ) , nelems ) ; }


Input: Writes an array of bytes to the compressed output stream . This method will block until all the bytes are written . [CODESPLIT] public void write ( byte [ ] b , int off , int len ) throws IOException { count += len ; super . write ( b , off , len ) ; }


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

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

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

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

 [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; super . printVal ( os , space , print_decl_p ) ; }


Input: The RelOps interface defines how each type responds to relational operators . Most ( all? ) types will not have sensible responses to all of the relational operators ( e . g . DInt won t know how to match a regular expression but DString will ) . For those operators that are nonsensical a class should throw InvalidOperatorException . [CODESPLIT] public boolean equal ( BaseType bt ) throws InvalidOperatorException , RegExpException , SBHException { return ( Operator . op ( EQUAL , this , bt ) ) ; }


Input: Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . <p / > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { if ( ! isRead ( ) ) read ( dataset , specialO ) ; if ( ce . evalClauses ( specialO ) ) externalize ( sink ) ; }


Input: Sets the unencoded name of the class instance . [CODESPLIT] @ Override public void setClearName ( String clearname ) { super . setClearName ( clearname ) ; if ( _attr != null ) _attr . setClearName ( clearname ) ; if ( _attrTbl != null ) _attrTbl . setClearName ( clearname ) ; }


Input:
Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { //LogStream.out.println("BaseType.printDecl()...");
 os . print ( space + getTypeName ( ) + " " + getEncodedName ( ) ) ; if ( print_semi ) os . println ( ";" ) ; }


Input: Print the variable s declaration . Same as <code > printDecl ( os space true ) < / code > . [CODESPLIT] public final void printDecl ( PrintWriter os , String space ) { printDecl ( os , space , true , false ) ; }


Input: Print the variable s declaration using <code > OutputStream< / code > . [CODESPLIT] public final void printDecl ( OutputStream os , String space , boolean print_semi , boolean constrained ) { PrintWriter pw = new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( os , Util . UTF8 ) ) ) ; printDecl ( pw , space , print_semi , constrained ) ; pw . flush ( ) ; }


Input: Print the variable s declaration using <code > OutputStream< / code > . [CODESPLIT] public final void printDecl ( OutputStream os , String space , boolean print_semi ) { printDecl ( os , space , print_semi , false ) ; }


Input: Returns a clone of this <code > BaseType< / code > . See DAPNode . cloneDAG . [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { BaseType bt = ( BaseType ) super . cloneDAG ( map ) ; if ( this . _attrTbl != null ) bt . _attrTbl = ( AttributeTable ) cloneDAG ( map , this . _attrTbl ) ; if ( this . _attr != null ) bt . _attr = new Attribute ( getClearName ( ) , bt . _attrTbl ) ; return bt ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : resultTime / gml : TimeInstant [CODESPLIT] public static TimeInstantType initTimeInstant ( TimeInstantType timeInstant ) { // @gml:id String id = MarshallingUtil . createIdForType ( TimeInstantType . class ) ; timeInstant . setId ( id ) ; // gml:timePosition NcTimePositionType . initTimePosition ( timeInstant . addNewTimePosition ( ) ) ; return timeInstant ; }


Input:
Tries to find the coordinate variable of the specified type . [CODESPLIT] static public String getCoordinateName ( NetcdfDataset ds , AxisType a ) { List < Variable > varList = ds . getVariables ( ) ; for ( Variable v : varList ) { if ( v instanceof Structure ) { List < Variable > vars = ( ( Structure ) v ) . getVariables ( ) ; for ( Variable vs : vars ) { String axisType = ds . findAttValueIgnoreCase ( vs , _Coordinate . AxisType , null ) ; if ( ( axisType != null ) && axisType . equals ( a . toString ( ) ) ) return vs . getShortName ( ) ; } } else { String axisType = ds . findAttValueIgnoreCase ( v , _Coordinate . AxisType , null ) ; if ( ( axisType != null ) && axisType . equals ( a . toString ( ) ) ) return v . getShortName ( ) ; } } if ( a == AxisType . Lat ) return findVariableName ( ds , "latitude" ) ; if ( a == AxisType . Lon ) return findVariableName ( ds , "longitude" ) ; if ( a == AxisType . Time ) return findVariableName ( ds , "time" ) ; if ( a == AxisType . Height ) { Variable v = findVariable ( ds , "altitude" ) ; if ( null == v ) v = findVariable ( ds , "depth" ) ; if ( v != null ) return v . getShortName ( ) ; } // I think the CF part is done by the CoordSysBuilder adding the _CoordinateAxisType attrinutes.
 return null ; }


Input: Tries to find the coordinate variable of the specified type which has the specified dimension as its firsst dimension [CODESPLIT] static public String getCoordinateName ( NetcdfDataset ds , AxisType a , Dimension dim ) { String name = getCoordinateName ( ds , a ) ; if ( name == null ) return null ; Variable v = ds . findVariable ( name ) ; if ( v == null ) return null ; if ( v . isScalar ( ) ) return null ; if ( ! v . getDimension ( 0 ) . equals ( dim ) ) return null ; return name ; }


Input: Convert an ErrorResponse to the equivalent XML [CODESPLIT] public String buildXML ( ) { StringBuilder response = new StringBuilder ( ) ; response . append ( "<Error" ) ; if ( code > 0 ) response . append ( String . format ( " httpcode=\"%d\"" , code ) ) ; response . append ( ">\n" ) ; if ( message != null ) response . append ( "<Message>" + getMessage ( ) + "</Message>\n" ) ; if ( context != null ) response . append ( "<Context>" + getContext ( ) + "</Context>\n" ) ; if ( otherinfo != null ) response . append ( "<OtherInformation>" + getOtherInfo ( ) + "</OtherInformation>\n" ) ; return response . toString ( ) ; }


Input: Convert an ErrorResponse to the equivalent DapException . [CODESPLIT] public DapException buildException ( ) { String XML = buildXML ( ) ; DapException dapex = new DapException ( XML ) . setCode ( code ) ; return dapex ; }


Input:
return the list of Dimensions that were created [CODESPLIT] private List < Dimension > breakupLevels ( NetcdfDataset ds , Variable levelVar ) throws IOException { if ( debugBreakup ) parseInfo . format ( "breakupLevels = %s%n" , levelVar . getShortName ( ) ) ; List < Dimension > dimList = new ArrayList <> ( ) ; ArrayChar levelVarData ; try { levelVarData = ( ArrayChar ) levelVar . read ( ) ; } catch ( IOException ioe ) { return dimList ; } List < String > values = null ; String currentUnits = null ; ArrayChar . StringIterator iter = levelVarData . getStringIterator ( ) ; while ( iter . hasNext ( ) ) { String s = iter . next ( ) ; if ( debugBreakup ) parseInfo . format ( "   %s%n" , s ) ; StringTokenizer stoke = new StringTokenizer ( s ) ; /* problem with blank string:
   char pvvLevels(levels_35=35, charsPerLevel=10);
"MB 1000   ", "MB 975    ", "MB 950    ", "MB 925    ", "MB 900    ", "MB 875    ", "MB 850    ", "MB 825    ", "MB 800    ", "MB 775    ", "MB 750    ",
"MB 725    ", "MB 700    ", "MB 675    ", "MB 650    ", "MB 625    ", "MB 600    ", "MB 575    ", "MB 550    ", "MB 525    ", "MB 500    ", "MB 450    ",
"MB 400    ", "MB 350    ", "MB 300    ", "MB 250    ", "MB 200    ", "MB 150    ", "MB 100    ", "BL 0 30   ", "BL 60 90  ", "BL 90 120 ", "BL 120 150",
"BL 150 180", ""
*/ if ( ! stoke . hasMoreTokens ( ) ) continue ; // skip it
 // first token is the unit
 String units = stoke . nextToken ( ) . trim ( ) ; if ( ! units . equals ( currentUnits ) ) { if ( values != null ) dimList . add ( makeZCoordAxis ( ds , values , currentUnits ) ) ; values = new ArrayList <> ( ) ; currentUnits = units ; } // next token is the value
 if ( stoke . hasMoreTokens ( ) ) values . add ( stoke . nextToken ( ) ) ; else values . add ( "0" ) ; } if ( values != null ) dimList . add ( makeZCoordAxis ( ds , values , currentUnits ) ) ; if ( debugBreakup ) parseInfo . format ( "  done breakup%n" ) ; return dimList ; }


Input:
make a new variable out of the list in values [CODESPLIT] private Dimension makeZCoordAxis ( NetcdfDataset ds , List < String > values , String units ) throws IOException { int len = values . size ( ) ; String name = makeZCoordName ( units ) ; if ( len > 1 ) name = name + Integer . toString ( len ) ; else name = name + values . get ( 0 ) ; StringUtil2 . replace ( name , ' ' , "-" ) ; Dimension dim ; if ( null != ( dim = ds . getRootGroup ( ) . findDimension ( name ) ) ) { if ( dim . getLength ( ) == len ) { // check against actual values
 Variable coord = ds . getRootGroup ( ) . findVariable ( name ) ; Array coordData = coord . read ( ) ; Array newData = Array . makeArray ( coord . getDataType ( ) , values ) ; if ( MAMath . nearlyEquals ( coordData , newData ) ) { if ( debugBreakup ) parseInfo . format ( "  use existing coord %s%n" , dim ) ; return dim ; } } } String orgName = name ; int count = 1 ; while ( ds . getRootGroup ( ) . findDimension ( name ) != null ) { name = orgName + "-" + count ; count ++ ; } // create new one
 dim = new Dimension ( name , len ) ; ds . addDimension ( null , dim ) ; if ( debugBreakup ) parseInfo . format ( "  make Dimension = %s length = %d%n" , name , len ) ; // if (len < 2) return dim; // skip 1D
 if ( debugBreakup ) { parseInfo . format ( "  make ZCoordAxis = = %s length = %d%n" , name , len ) ; } CoordinateAxis v = new CoordinateAxis1D ( ds , null , name , DataType . DOUBLE , name , makeUnitsName ( units ) , makeLongName ( name ) ) ; String positive = getZisPositive ( ds , v ) ; if ( null != positive ) v . addAttribute ( new Attribute ( _Coordinate . ZisPositive , positive ) ) ; v . setValues ( values ) ; ds . addCoordinateAxis ( v ) ; parseInfo . format ( "Created Z Coordinate Axis = " ) ; v . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( "%n" ) ; return dim ; }


Input:
create new variables as sections of ncVar [CODESPLIT] private void createNewVariables ( NetcdfDataset ds , Variable ncVar , List < Dimension > newDims , Dimension levelDim ) throws InvalidRangeException { List < Dimension > dims = ncVar . getDimensions ( ) ; int newDimIndex = dims . indexOf ( levelDim ) ; //String shapeS = ncVar.getShapeS();
 int [ ] origin = new int [ ncVar . getRank ( ) ] ; int [ ] shape = ncVar . getShape ( ) ; int count = 0 ; for ( Dimension dim : newDims ) { String name = ncVar . getShortName ( ) + "-" + dim . getShortName ( ) ; origin [ newDimIndex ] = count ; shape [ newDimIndex ] = dim . getLength ( ) ; Variable varNew = ncVar . section ( new Section ( origin , shape ) ) ; varNew . setName ( name ) ; varNew . setDimension ( newDimIndex , dim ) ; // synthesize long name
 String long_name = ds . findAttValueIgnoreCase ( ncVar , CDM . LONG_NAME , ncVar . getShortName ( ) ) ; long_name = long_name + "-" + dim . getShortName ( ) ; ds . addVariableAttribute ( varNew , new Attribute ( CDM . LONG_NAME , long_name ) ) ; ds . addVariable ( null , varNew ) ; parseInfo . format ( "Created New Variable as section = " ) ; varNew . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( "%n" ) ; count += dim . getLength ( ) ; } }


Input:
construct time coordinate from reftime variable [CODESPLIT] private CoordinateAxis makeTimeCoordAxisFromReference ( NetcdfDataset ds , Variable timeVar , Array vals ) { Variable refVar = ds . findVariable ( "reftime" ) ; if ( refVar == null ) return null ; double refValue ; try { Array refArray = refVar . read ( ) ; refValue = refArray . getDouble ( refArray . getIndex ( ) ) ; // get the first value
 } catch ( IOException ioe ) { return null ; } if ( refValue == N3iosp . NC_FILL_DOUBLE ) return null ; // construct the values array - make it a double to be safe
 Array dvals = Array . factory ( DataType . DOUBLE , vals . getShape ( ) ) ; IndexIterator diter = dvals . getIndexIterator ( ) ; IndexIterator iiter = vals . getIndexIterator ( ) ; while ( iiter . hasNext ( ) ) diter . setDoubleNext ( iiter . getDoubleNext ( ) + refValue ) ; // add reftime to each of the values
 String units = ds . findAttValueIgnoreCase ( refVar , CDM . UNITS , "seconds since 1970-1-1 00:00:00" ) ; units = normalize ( units ) ; String desc = "synthesized time coordinate from reftime, valtimeMINUSreftime" ; CoordinateAxis1D timeCoord = new CoordinateAxis1D ( ds , null , "timeCoord" , DataType . DOUBLE , "record" , units , desc ) ; timeCoord . setCachedData ( dvals , true ) ; parseInfo . format ( "Created Time Coordinate Axis From Reference = " ) ; timeCoord . getNameAndDimensions ( parseInfo , true , false ) ; parseInfo . format ( "%n" ) ; return timeCoord ; }


Input: Shave n bits off the float [CODESPLIT] public static float bitShave ( float value , int bitMask ) { if ( Float . isNaN ( value ) ) return value ; // ?? int bits = Float . floatToRawIntBits ( value ) ; int shave = bits & bitMask ; return Float . intBitsToFloat ( shave ) ; }


Input: Write Grib file to a netcdf4 file . Experimental . [CODESPLIT] public static void main ( String [ ] args ) { String fileIn = ( args . length > 0 ) ? args [ 0 ] : "Q:/cdmUnitTest/formats/grib2/LMPEF_CLM_050518_1200.grb" ; String fileOut = ( args . length > 1 ) ? args [ 1 ] : "C:/tmp/ds.mint.bi" ; try ( GribToNetcdfWriter writer = new GribToNetcdfWriter ( fileIn , fileOut ) ) { writer . write ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }


Input: Retrieve the set of Enhancements that is associated with the given string . <p / > <table border = 1 > <tr > <th > String< / th > <th > Enhancements< / th > < / tr > <tr > <td > All< / td > <td > ConvertEnums ConvertUnsigned ApplyScaleOffset ConvertMissing CoordSystems< / td > < / tr > <tr > <td > None< / td > <td > &lt ; empty&gt ; < / td > < / tr > <tr > <td > ConvertEnums< / td > <td > ConvertEnums< / td > < / tr > <tr > <td > ConvertUnsigned< / td > <td > ConvertUnsigned< / td > < / tr > <tr > <td > ApplyScaleOffset< / td > <td > ApplyScaleOffset< / td > < / tr > <tr > <td > ConvertMissing< / td > <td > ConvertMissing< / td > < / tr > <tr > <td > CoordSystems< / td > <td > CoordSystems< / td > < / tr > <tr > <td > IncompleteCoordSystems< / td > <td > CoordSystems< / td > < / tr > <tr > <td > true< / td > <td > Alias for All < / td > < / tr > <tr > <td > ScaleMissingDefer< / td > <td > Alias for None < / td > < / tr > <tr > <td > AllDefer< / td > <td > ConvertEnums CoordSystems< / td > < / tr > <tr > <td > ScaleMissing< / td > <td > ConvertUnsigned ApplyScaleOffset ConvertMissing< / td > < / tr > < / table > [CODESPLIT] static public Set < Enhance > parseEnhanceMode ( String enhanceMode ) { if ( enhanceMode == null ) return null ; switch ( enhanceMode . toLowerCase ( ) ) { case "all" : return getEnhanceAll ( ) ; case "none" : return getEnhanceNone ( ) ; case "convertenums" : return EnumSet . of ( Enhance . ConvertEnums ) ; case "convertunsigned" : return EnumSet . of ( Enhance . ConvertUnsigned ) ; case "applyscaleoffset" : return EnumSet . of ( Enhance . ApplyScaleOffset ) ; case "convertmissing" : return EnumSet . of ( Enhance . ConvertMissing ) ; case "coordsystems" : return EnumSet . of ( Enhance . CoordSystems ) ; case "incompletecoordsystems" : return EnumSet . of ( Enhance . CoordSystems , Enhance . IncompleteCoordSystems ) ; // Legacy strings, retained for backwards compatibility: case "true" : return getEnhanceAll ( ) ; case "scalemissingdefer" : return getEnhanceNone ( ) ; case "alldefer" : return EnumSet . of ( Enhance . ConvertEnums , Enhance . CoordSystems ) ; case "scalemissing" : return EnumSet . of ( Enhance . ConvertUnsigned , Enhance . ApplyScaleOffset , Enhance . ConvertMissing ) ; // Return null by default, since some valid strings actually return an empty set. default : return null ; } }


Input: Enable file caching . call this before calling acquireFile () . When application terminates call NetcdfDataset . shutdown () . [CODESPLIT] static public synchronized void initNetcdfFileCache ( int minElementsInMemory , int maxElementsInMemory , int hardLimit , int period ) { netcdfFileCache = new ucar . nc2 . util . cache . FileCache ( "NetcdfFileCache " , minElementsInMemory , maxElementsInMemory , hardLimit , period ) ; }


Input: Make NetcdfFile into NetcdfDataset with given enhance mode [CODESPLIT] static public NetcdfDataset wrap ( NetcdfFile ncfile , Set < Enhance > mode ) throws IOException { if ( ncfile instanceof NetcdfDataset ) { NetcdfDataset ncd = ( NetcdfDataset ) ncfile ; if ( ! ncd . enhanceNeeded ( mode ) ) return ( NetcdfDataset ) ncfile ; } // enhancement requires wrappping, to not modify underlying dataset, eg if cached // perhaps need a method variant that allows the ncfile to be modified return new NetcdfDataset ( ncfile , mode ) ; }


Input: Factory method for opening a dataset through the netCDF API and identifying its coordinate variables . [CODESPLIT] static public NetcdfDataset openDataset ( String location , boolean enhance , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return openDataset ( location , enhance , - 1 , cancelTask , null ) ; }


Input: Factory method for opening a dataset through the netCDF API and identifying its coordinate variables . [CODESPLIT] static public NetcdfDataset openDataset ( String location , boolean enhance , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; return openDataset ( durl , enhance ? defaultEnhanceMode : null , buffer_size , cancelTask , spiObject ) ; }


Input: Factory method for opening a dataset through the netCDF API and identifying its coordinate variables . [CODESPLIT] static public NetcdfDataset openDataset ( DatasetUrl location , Set < Enhance > enhanceMode , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { // do not acquire NetcdfFile ncfile = openOrAcquireFile ( null , null , null , location , buffer_size , cancelTask , spiObject ) ; NetcdfDataset ds ; if ( ncfile instanceof NetcdfDataset ) { ds = ( NetcdfDataset ) ncfile ; enhance ( ds , enhanceMode , cancelTask ) ; // enhance "in place", ie modify the NetcdfDataset } else { ds = new NetcdfDataset ( ncfile , enhanceMode ) ; // enhance when wrapping } return ds ; }


Input:
/ * Enhancement use cases 1 . open NetcdfDataset ( enhance ) . 2 . NcML - must create the NetcdfDataset and enhance when its done . [CODESPLIT] static private CoordSysBuilderIF enhance ( NetcdfDataset ds , Set < Enhance > mode , CancelTask cancelTask ) throws IOException { if ( mode == null ) { mode = EnumSet . noneOf ( Enhance . class ) ; } // CoordSysBuilder may enhance dataset: add new variables, attributes, etc CoordSysBuilderIF builder = null ; if ( mode . contains ( Enhance . CoordSystems ) && ! ds . enhanceMode . contains ( Enhance . CoordSystems ) ) { builder = ucar . nc2 . dataset . CoordSysBuilder . factory ( ds , cancelTask ) ; builder . augmentDataset ( ds , cancelTask ) ; ds . convUsed = builder . getConventionUsed ( ) ; } // now enhance enum/scale/offset/unsigned, using augmented dataset if ( ( mode . contains ( Enhance . ConvertEnums ) && ! ds . enhanceMode . contains ( Enhance . ConvertEnums ) ) || ( mode . contains ( Enhance . ConvertUnsigned ) && ! ds . enhanceMode . contains ( Enhance . ConvertUnsigned ) ) || ( mode . contains ( Enhance . ApplyScaleOffset ) && ! ds . enhanceMode . contains ( Enhance . ApplyScaleOffset ) ) || ( mode . contains ( Enhance . ConvertMissing ) && ! ds . enhanceMode . contains ( Enhance . ConvertMissing ) ) ) { for ( Variable v : ds . getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) v ; ve . enhance ( mode ) ; if ( ( cancelTask != null ) && cancelTask . isCancel ( ) ) return null ; } } // now find coord systems which may change some Variables to axes, etc if ( builder != null ) { // temporarily set enhanceMode if incomplete coordinate systems are allowed if ( mode . contains ( Enhance . IncompleteCoordSystems ) ) { ds . enhanceMode . add ( Enhance . IncompleteCoordSystems ) ; builder . buildCoordinateSystems ( ds ) ; ds . enhanceMode . remove ( Enhance . IncompleteCoordSystems ) ; } else { builder . buildCoordinateSystems ( ds ) ; } } /* timeTaxis must be CoordinateAxis1DTime
    for (CoordinateSystem cs : ds.getCoordinateSystems()) {
      cs.makeTimeAxis();
    } */ ds . finish ( ) ; // recalc the global lists ds . enhanceMode . addAll ( mode ) ; return builder ; }


Input: Same as openDataset but file is acquired through the File Cache with defaultEnhanceMode without the need of setting the enhanceMode via the signature . You still close with NetcdfDataset . close () the release is handled automatically . You must first call initNetcdfFileCache () for caching to actually take place . [CODESPLIT] static public NetcdfDataset acquireDataset ( DatasetUrl location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return acquireDataset ( null , location , defaultEnhanceMode , - 1 , cancelTask , null ) ; }


Input: / * static public NetcdfDataset acquireDataset ( FileFactory fac String location Set<Enhance > enhanceMode int buffer_size ucar . nc2 . util . CancelTask cancelTask Object iospMessage ) throws IOException { [CODESPLIT] static public NetcdfDataset acquireDataset ( FileFactory fac , DatasetUrl durl , Set < Enhance > enhanceMode , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object iospMessage ) throws IOException { // caching not turned on if ( netcdfFileCache == null ) { if ( fac == null ) return openDataset ( durl , enhanceMode , buffer_size , cancelTask , iospMessage ) ; else // must use the factory if there is one return ( NetcdfDataset ) fac . open ( durl , buffer_size , cancelTask , iospMessage ) ; } if ( fac != null ) return ( NetcdfDataset ) openOrAcquireFile ( netcdfFileCache , fac , null , durl , buffer_size , cancelTask , iospMessage ) ; fac = new MyNetcdfDatasetFactory ( durl , enhanceMode ) ; return ( NetcdfDataset ) openOrAcquireFile ( netcdfFileCache , fac , fac . hashCode ( ) , durl , buffer_size , cancelTask , iospMessage ) ; }


Input: Factory method for opening a NetcdfFile through the netCDF API . [CODESPLIT] public static NetcdfFile openFile ( String location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; return openOrAcquireFile ( null , null , null , durl , - 1 , cancelTask , null ) ; }


Input: Factory method for opening a NetcdfFile through the netCDF API . May be any kind of file that can be read through the netCDF API including OpenDAP and NcML . <p > <p > This does not necessarily return a NetcdfDataset or enhance the dataset ; use NetcdfDataset . openDataset () method for that . [CODESPLIT] public static NetcdfFile openFile ( DatasetUrl location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { return openOrAcquireFile ( null , null , null , location , buffer_size , cancelTask , spiObject ) ; }


Input: Same as openFile but file is acquired through the File Cache . You still close with NetcdfFile . close () the release is handled automatically . You must first call initNetcdfFileCache () for caching to actually take place . [CODESPLIT] static public NetcdfFile acquireFile ( DatasetUrl location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return acquireFile ( null , null , location , - 1 , cancelTask , null ) ; }


Input: Same as openFile but file is acquired through the File Cache . You still close with NetcdfFile . close () the release is handled automatically . You must first call initNetcdfFileCache () for caching to actually take place . [CODESPLIT] static public NetcdfFile acquireFile ( ucar . nc2 . util . cache . FileFactory factory , Object hashKey , DatasetUrl location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { // must use the factory if there is one but no fileCache if ( ( netcdfFileCache == null ) && ( factory != null ) ) { return ( NetcdfFile ) factory . open ( location , buffer_size , cancelTask , spiObject ) ; } return openOrAcquireFile ( netcdfFileCache , factory , hashKey , location , buffer_size , cancelTask , spiObject ) ; }


Input: / * Open or acquire a NetcdfFile . [CODESPLIT] static private NetcdfFile openOrAcquireFile ( FileCache cache , FileFactory factory , Object hashKey , DatasetUrl durl , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { if ( durl . serviceType != null ) { switch ( durl . serviceType ) { case OPENDAP : return acquireDODS ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case CdmRemote : return acquireCdmRemote ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case DAP4 : return acquireDap4 ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case NCML : return acquireNcml ( cache , factory , hashKey , durl . trueurl , buffer_size , cancelTask , spiObject ) ; case THREDDS : Formatter log = new Formatter ( ) ; DataFactory tdf = new DataFactory ( ) ; NetcdfFile ncfile = tdf . openDataset ( durl . trueurl , false , cancelTask , log ) ; // LOOK acquire ?? if ( ncfile == null ) throw new IOException ( log . toString ( ) ) ; return ncfile ; case File : case HTTPServer : break ; // fall through default : throw new IOException ( "Unknown service type: " + durl . serviceType . toString ( ) ) ; } } // Next to last resort: find in the cache if ( cache != null ) { if ( factory == null ) factory = defaultNetcdfFileFactory ; return ( NetcdfFile ) cache . acquire ( factory , hashKey , durl , buffer_size , cancelTask , spiObject ) ; } // Last resort: try to open as a file or remote file return NetcdfFile . open ( durl . trueurl , buffer_size , cancelTask , spiObject ) ; }