Input:
assume that its done in the event thread [CODESPLIT] boolean showDataset ( ) { // temp kludge for initialization
 java . util . List grids = gridDataset . getGrids ( ) ; if ( ( grids == null ) || grids . size ( ) == 0 ) { javax . swing . JOptionPane . showMessageDialog ( null , "No gridded fields in file " + gridDataset . getTitle ( ) ) ; return false ; } currentField = ( GridDatatype ) grids . get ( 0 ) ; currentSlice = 0 ; currentLevel = 0 ; currentTime = 0 ; currentEnsemble = 0 ; currentRunTime = 0 ; eventsOK = false ; // dont let this trigger redraw
 renderGrid . setGeoGrid ( currentField ) ; ui . setFields ( gridDataset . getGrids ( ) ) ; setField ( currentField ) ; // if possible, change the projection and the map area to one that fits this
 // dataset
 ProjectionImpl dataProjection = currentField . getProjection ( ) ; if ( dataProjection != null ) setProjection ( dataProjection ) ; // ready to draw
 //draw(true);
 // events now ok
 eventsOK = true ; return true ; }


Input:
public GridDatatype getField () { return currentField ; } [CODESPLIT] private boolean setField ( Object fld ) { GridDatatype gg = null ; if ( fld instanceof GridDatatype ) gg = ( GridDatatype ) fld ; else if ( fld instanceof String ) gg = gridDataset . findGridDatatype ( ( String ) fld ) ; if ( null == gg ) return false ; renderGrid . setGeoGrid ( gg ) ; currentField = gg ; GridCoordSystem gcs = gg . getCoordinateSystem ( ) ; gcs . setProjectionBoundingBox ( ) ; // set levels
 CoordinateAxis1D vaxis = gcs . getVerticalAxis ( ) ; levelNames = ( vaxis == null ) ? new ArrayList ( ) : vaxis . getNames ( ) ; if ( ( levelNames == null ) || ( currentLevel >= levelNames . size ( ) ) ) currentLevel = 0 ; vertPanel . setCoordSys ( currentField . getCoordinateSystem ( ) , currentLevel ) ; // set times
 if ( gcs . hasTimeAxis ( ) ) { CoordinateAxis1DTime taxis = gcs . hasTimeAxis1D ( ) ? gcs . getTimeAxis1D ( ) : gcs . getTimeAxisForRun ( 0 ) ; timeNames = ( taxis == null ) ? new ArrayList ( ) : taxis . getNames ( ) ; if ( ( timeNames == null ) || ( currentTime >= timeNames . size ( ) ) ) currentTime = 0 ; hasDependentTimeAxis = ! gcs . hasTimeAxis1D ( ) ; } else hasDependentTimeAxis = false ; // set ensembles
 CoordinateAxis1D eaxis = gcs . getEnsembleAxis ( ) ; ensembleNames = ( eaxis == null ) ? new ArrayList ( ) : eaxis . getNames ( ) ; currentEnsemble = ensembleNames . size ( ) > 0 ? 0 : - 1 ; // set runtimes
 CoordinateAxis1DTime rtaxis = gcs . getRunTimeAxis ( ) ; runtimeNames = ( rtaxis == null ) ? new ArrayList ( ) : rtaxis . getNames ( ) ; currentRunTime = runtimeNames . size ( ) > 0 ? 0 : - 1 ; ui . setField ( gg ) ; return true ; }


Input: / * TABLE C - SUB - CENTERS FOR CENTER 9 US NWS FIELD STATIONS from bdgparm . f John Halquist <John . Halquist [CODESPLIT] @ Override @ Nullable public String getSubCenterName ( int subcenter ) { if ( nwsoSubCenter == null ) nwsoSubCenter = readNwsoSubCenter ( "resources/grib1/noaa_rfc/tableC.txt" ) ; if ( nwsoSubCenter == null ) return null ; return nwsoSubCenter . get ( subcenter ) ; }


Input:
order : num name desc unit [CODESPLIT] @ Nullable private static Map < Integer , String > readNwsoSubCenter ( String path ) { Map < Integer , String > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , CDM . utf8Charset ) ) ) { while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } if ( ( line . length ( ) == 0 ) || line . startsWith ( "#" ) ) { continue ; } StringBuilder lineb = new StringBuilder ( line ) ; StringUtil2 . remove ( lineb , "'+,/" ) ; String [ ] flds = lineb . toString ( ) . split ( "[:]" ) ; int val = Integer . parseInt ( flds [ 0 ] . trim ( ) ) ; // must have a number
 String name = flds [ 1 ] . trim ( ) + ": " + flds [ 2 ] . trim ( ) ; result . put ( val , name ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe
 } catch ( IOException ioError ) { logger . warn ( "An error occurred in Grib1Tables while trying to open the table " + path + " : " + ioError ) ; return null ; } }


Input: Does not handle non - standard calendars [CODESPLIT] static public CalendarDateRange of ( DateRange dr ) { if ( dr == null ) return null ; return CalendarDateRange . of ( dr . getStart ( ) . getDate ( ) , dr . getEnd ( ) . getDate ( ) ) ; }


Input:
reletive error in position - GRIB numbers sometimes miscoded [CODESPLIT] public static Grib2Gds factory ( int template , byte [ ] data ) { Grib2Gds result ; switch ( template ) { case 0 : result = new LatLon ( data ) ; break ; case 1 : result = new RotatedLatLon ( data ) ; break ; case 10 : result = new Mercator ( data ) ; break ; case 20 : result = new PolarStereographic ( data ) ; break ; case 30 : result = new LambertConformal ( data , 30 ) ; break ; case 31 : result = new AlbersEqualArea ( data ) ; break ; case 40 : result = new GaussLatLon ( data ) ; break ; case 50 : // Spherical Harmonic Coefficients BOGUS
 result = new GdsSpherical ( data , template ) ; break ; case 90 : result = new SpaceViewPerspective ( data ) ; break ; // LOOK NCEP specific
 case 204 : result = new CurvilinearOrthogonal ( data ) ; break ; case 32769 : result = new RotatedLatLon32769 ( data ) ; break ; default : throw new UnsupportedOperationException ( "Unsupported GDS type = " + template ) ; } result . finish ( ) ; // stuff that cant be done in the constructor
 return result ; }


Input:
/ * Code Table Code table 3 . 2 - Shape of the Earth ( 3 . 2 ) 0 : Earth assumed spherical with radius = 6 367 470 . 0 m 1 : Earth assumed spherical with radius specified ( in m ) by data producer 2 : Earth assumed oblate spheroid with size as determined by IAU in 1965 ( major axis = 6 378 160 . 0 m minor axis = 6 356 775 . 0 m f = 1 / 297 . 0 ) 3 : Earth assumed oblate spheroid with major and minor axes specified ( in km ) by data producer 4 : Earth assumed oblate spheroid as defined in IAG - GRS80 model ( major axis = 6 378 137 . 0 m minor axis = 6 356 752 . 314 m f = 1 / 298 . 257 222 101 ) 5 : Earth assumed represented by WGS84 ( as used by ICAO since 1998 ) 6 : Earth assumed spherical with radius of 6 371 229 . 0 m 7 : Earth assumed oblate spheroid with major or minor axes specified ( in m ) by data producer 8 : Earth model assumed spherical with radius of 6 371 200 m but the horizontal datum of the resulting latitude / longitude field is the WGS84 reference frame [CODESPLIT] protected Earth getEarth ( ) { switch ( earthShape ) { case 0 : return new Earth ( 6367470.0 ) ; case 1 : if ( earthRadius < 6000000 ) earthRadius *= 1000.0 ; // bad units
 return new Earth ( earthRadius ) ; case 2 : return EarthEllipsoid . IAU ; case 3 : // oblate in km, so bad values will be large and not scaled
 if ( majorAxis < 6000000 ) majorAxis *= 1000.0 ; if ( minorAxis < 6000000 ) minorAxis *= 1000.0 ; return new EarthEllipsoid ( "Grib2 Type 3" , - 1 , majorAxis , minorAxis , 0 ) ; case 4 : return EarthEllipsoid . IAG_GRS80 ; case 5 : return EarthEllipsoid . WGS84 ; case 6 : return new Earth ( 6371229.0 ) ; case 7 : // Oblate in meters
 if ( majorAxis < 6000000 ) majorAxis *= 1000.0 ; // bad units
 if ( minorAxis < 6000000 ) minorAxis *= 1000.0 ; // bad units
 return new EarthEllipsoid ( "Grib2 Type 7" , - 1 , majorAxis , minorAxis , 0 ) ; case 8 : return new Earth ( 6371200.0 ) ; case 9 : return EarthEllipsoid . Airy1830 ; default : return new Earth ( ) ; } }


Input: also see Snyder p 101 [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double fromLat = Math . toRadians ( latLon . getLatitude ( ) ) ; double theta = computeTheta ( latLon . getLongitude ( ) ) ; double term = earth . isSpherical ( ) ? n2 * Math . sin ( fromLat ) : n * MapMath . qsfn ( Math . sin ( fromLat ) , e , one_es ) ; double rho = c - term ; if ( rho < 0.0 ) throw new RuntimeException ( "F" ) ; rho = dd * Math . sqrt ( rho ) ; double toX = rho * Math . sin ( theta ) ; double toY = rho0 - rho * Math . cos ( theta ) ; result . setLocation ( totalScale * toX + falseEasting , totalScale * toY + falseNorthing ) ; return result ; }


Input:
Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = ( world . getX ( ) - falseEasting ) / totalScale ; // assumes cartesion coords in km
 double fromY = ( world . getY ( ) - falseNorthing ) / totalScale ; fromY = rho0 - fromY ; double rho = MapMath . distance ( fromX , fromY ) ; if ( rho == 0.0 ) { toLon = 0.0 ; toLat = n > 0.0 ? MapMath . HALFPI : - MapMath . HALFPI ; } else { if ( n < 0.0 ) { rho = - rho ; fromX = - fromX ; fromY = - fromY ; } double lpphi = rho / dd ; if ( ! earth . isSpherical ( ) ) { lpphi = ( c - lpphi * lpphi ) / n ; if ( Math . abs ( ec - Math . abs ( lpphi ) ) > TOL7 ) { if ( Math . abs ( lpphi ) > 2.0 ) throw new IllegalArgumentException ( "AlbersEqualAreaEllipse x,y=" + world ) ; lpphi = phi1_ ( lpphi , e , one_es ) ; if ( lpphi == Double . MAX_VALUE ) throw new RuntimeException ( "I" ) ; } else { lpphi = ( lpphi < 0. ) ? - MapMath . HALFPI : MapMath . HALFPI ; } } else { // spherical case
 lpphi = ( c - lpphi * lpphi ) / n2 ; if ( Math . abs ( lpphi ) <= 1.0 ) { lpphi = Math . asin ( lpphi ) ; } else { lpphi = ( lpphi < 0. ) ? - MapMath . HALFPI : MapMath . HALFPI ; } } toLon = Math . atan2 ( fromX , fromY ) / n ; //coverity[swapped_arguments]
 toLat = lpphi ; } result . setLatitude ( Math . toDegrees ( toLat ) ) ; result . setLongitude ( Math . toDegrees ( toLon ) + lon0deg ) ; return result ; }


Input: / * Parse invocation interface [CODESPLIT] public int dapparse ( String text , DDS dds , DAS das , DAP2Exception err ) throws ParseException { //setDebugLevel(1); ddsobject = dds ; dasobject = das ; errobject = ( err == null ? new DAP2Exception ( ) : err ) ; dapdebug = getDebugLevel ( ) ; Boolean accept = parse ( text ) ; if ( ! accept ) throw new ParseException ( "Dap2 Parser returned false" ) ; return parseClass ; }


Input: Call this to parse a DDS [CODESPLIT] public int ddsparse ( String text , DDS dds ) throws ParseException { return dapparse ( text , dds , null , null ) ; }


Input: Call this to parse a DAS [CODESPLIT] public int dasparse ( String text , DAS das ) throws ParseException { return dapparse ( text , null , das , null ) ; }


Input: Call this to parse an error {} body [CODESPLIT] public int errparse ( String text , DAP2Exception err ) throws ParseException { return dapparse ( text , null , null , err ) ; }


Input: / * Use the initial keyword to indicate what we are parsing [CODESPLIT] void tagparse ( Dap2Parse parsestate , int kind ) throws ParseException { /* Create the storage object corresponding to what we are parsing */ String expected = parseactual ( ) ; switch ( kind ) { case SCAN_DATASET : parseClass = DapDDS ; if ( ddsobject == null ) throw new ParseException ( "DapParse: found DDS, expected " + expected ) ; break ; case SCAN_ATTR : parseClass = DapDAS ; if ( dasobject == null ) throw new ParseException ( "DapParse: found DAS, expected " + parseactual ( ) ) ; lexstate . dassetup ( ) ; break ; case SCAN_ERROR : parseClass = DapERR ; if ( errobject == null ) throw new ParseException ( "DapParse: found error{}, expected " + parseactual ( ) ) ; break ; default : throw new ParseException ( "Unknown tag argument: " + kind ) ; } }


Input: / * Since there is no common parent class for BaseType Attribute and AttributeTable provide a type specific name getter . [CODESPLIT] String extractname ( Object o ) throws ParseException { if ( o instanceof BaseType ) return ( ( BaseType ) o ) . getClearName ( ) ; if ( o instanceof Attribute ) return ( ( Attribute ) o ) . getClearName ( ) ; if ( o instanceof AttributeTable ) return ( ( AttributeTable ) o ) . getClearName ( ) ; throw new ParseException ( "extractname: illegal object class: " + o ) ; }


Input: Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public final boolean init ( RandomAccessFile raf , boolean fullCheck ) throws IOException { rf = raf ; raf . order ( RandomAccessFile . BIG_ENDIAN ) ; return init ( fullCheck ) ; }


Input: Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( rf == null ) { logError ( "File is null" ) ; return false ; } gridIndex = new GridIndex ( rf . getLocation ( ) ) ; rf . order ( RandomAccessFile . BIG_ENDIAN ) ; if ( rf . length ( ) < 44 ) return false ; int numEntries = Math . abs ( readInt ( 10 ) ) ; if ( numEntries > 1000000 ) { needToSwap = true ; numEntries = Math . abs ( McIDASUtil . swbyt4 ( numEntries ) ) ; } if ( numEntries > MAX_GRIDS ) { return false ; } //System.out.println("need to Swap = " + needToSwap); //System.out.println("number entries="+numEntries); // go back to the beginning rf . seek ( 0 ) ; // read the fileheader String label = rf . readString ( 32 ) ; // GEMPAK too closely like McIDAS if ( label . contains ( "GEMPAK DATA MANAGEMENT FILE" ) ) { logError ( "label indicates this is a GEMPAK grid" ) ; return false ; } else { // check that they are all printable ASCII chars for ( int i = 0 ; i < label . length ( ) ; i ++ ) { String s0 = label . substring ( i , i + 1 ) ; if ( ! ( 0 <= s0 . compareTo ( " " ) && s0 . compareTo ( "~" ) <= 0 ) ) { logError ( "bad label, not a McIDAS grid" ) ; return false ; } } } //System.out.println("label = " + label); // int project = readInt(8); //System.out.println("Project = " + project); int date = readInt ( 9 ) ; // dates are supposed to be yyyddd, but account for ccyyddd up to year 4000 if ( ( date < 10000 ) || ( date > 400000 ) ) { logError ( "date wrong, not a McIDAS grid" ) ; return false ; } //System.out.println("date = " + date); if ( rf . length ( ) < 4 * ( numEntries + 12 ) ) return false ; int [ ] entries = new int [ numEntries ] ; for ( int i = 0 ; i < numEntries ; i ++ ) { entries [ i ] = readInt ( i + 11 ) ; // sanity check that this is indeed a McIDAS Grid file if ( entries [ i ] < - 1 ) { logError ( "bad grid offset " + i + ": " + entries [ i ] ) ; return false ; } } if ( ! fullCheck ) { return true ; } // Don't swap: rf . order ( RandomAccessFile . BIG_ENDIAN ) ; for ( int i = 0 ; i < numEntries ; i ++ ) { if ( entries [ i ] == - 1 ) { continue ; } int [ ] header = new int [ 64 ] ; rf . seek ( entries [ i ] * 4 ) ; rf . readInt ( header , 0 , 64 ) ; if ( needToSwap ) { swapGridHeader ( header ) ; } try { McIDASGridRecord gr = new McIDASGridRecord ( entries [ i ] , header ) ; //if (gr.getGridDefRecordId().equals("CONF X:93 Y:65")) { //if (gr.getGridDefRecordId().equals("CONF X:54 Y:47")) { // figure out how to handle Mercator projections // if ( !(gr.getGridDefRecordId().startsWith("MERC"))) { gridIndex . addGridRecord ( gr ) ; if ( gdsMap . get ( gr . getGridDefRecordId ( ) ) == null ) { McGridDefRecord mcdef = gr . getGridDefRecord ( ) ; //System.out.println("new nav " + mcdef.toString()); gdsMap . put ( mcdef . toString ( ) , mcdef ) ; gridIndex . addHorizCoordSys ( mcdef ) ; } //} } catch ( McIDASException me ) { logError ( "problem creating grid dir" ) ; return false ; } } // check to see if there are any grids that we can handle if ( gridIndex . getGridRecords ( ) . isEmpty ( ) ) { logError ( "no grids found" ) ; return false ; } return true ; }


Input: Swap the grid header avoiding strings [CODESPLIT] private void swapGridHeader ( int [ ] gh ) { McIDASUtil . flip ( gh , 0 , 5 ) ; McIDASUtil . flip ( gh , 7 , 7 ) ; McIDASUtil . flip ( gh , 9 , 10 ) ; McIDASUtil . flip ( gh , 12 , 14 ) ; McIDASUtil . flip ( gh , 32 , 51 ) ; }


Input: Read the grid [CODESPLIT] public float [ ] readGrid ( McIDASGridRecord gr ) throws IOException { float [ ] data ; //try { int te = ( gr . getOffsetToHeader ( ) + 64 ) * 4 ; int rows = gr . getRows ( ) ; int cols = gr . getColumns ( ) ; rf . seek ( te ) ; float scale = ( float ) gr . getParamScale ( ) ; data = new float [ rows * cols ] ; rf . order ( needToSwap ? RandomAccessFile . LITTLE_ENDIAN : RandomAccessFile . BIG_ENDIAN ) ; // int n = 0; // store such that 0,0 is in lower left corner... for ( int nc = 0 ; nc < cols ; nc ++ ) { for ( int nr = 0 ; nr < rows ; nr ++ ) { int temp = rf . readInt ( ) ; // check for missing value data [ ( rows - nr - 1 ) * cols + nc ] = ( temp == McIDASUtil . MCMISSING ) ? Float . NaN : ( ( float ) temp ) / scale ; } } rf . order ( RandomAccessFile . BIG_ENDIAN ) ; //} catch (Exception esc) { //  System.out.println(esc); //} return data ; }


Input: Read an integer [CODESPLIT] public int readInt ( int word ) throws IOException { if ( rf == null ) { throw new IOException ( "no file to read from" ) ; } rf . seek ( word * 4 ) ; // set the order if ( needToSwap ) { rf . order ( RandomAccessFile . LITTLE_ENDIAN ) ; // swap } else { rf . order ( RandomAccessFile . BIG_ENDIAN ) ; } int idata = rf . readInt ( ) ; rf . order ( RandomAccessFile . BIG_ENDIAN ) ; return idata ; }


Input: for testing purposes [CODESPLIT] public static void main ( String [ ] args ) throws IOException { String file = "GRID2001" ; if ( args . length > 0 ) { file = args [ 0 ] ; } McIDASGridReader mg = new McIDASGridReader ( file ) ; GridIndex gridIndex = mg . getGridIndex ( ) ; List grids = gridIndex . getGridRecords ( ) ; System . out . println ( "found " + grids . size ( ) + " grids" ) ; int num = Math . min ( grids . size ( ) , 10 ) ; for ( int i = 0 ; i < num ; i ++ ) { System . out . println ( grids . get ( i ) ) ; } }


Input: Writes a constraint OWS element out . [CODESPLIT] private void writeAConstraint ( String name , boolean isImplemented ) { String defValue ; if ( isImplemented ) defValue = "TRUE" ; else defValue = "FALSE" ; fileOutput += "<ows:Constraint name=\"" + name + "\"> " + "<ows:NoValues/> " + "<ows:DefaultValue>" + defValue + "</ows:DefaultValue> " + "</ows:Constraint>" ; }


Input: Writes headers and service sections [CODESPLIT] private void writeHeadersAndSS ( ) { fileOutput += "<wfs:WFS_Capabilities xsi:schemaLocation=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd " ) + " xmlns:xsi=" + WFSXMLHelper . encQuotes ( "http://www.w3.org/2001/XMLSchema-instance" ) + " xmlns:xlink=" + WFSXMLHelper . encQuotes ( "http://www.w3.org/1999/xlink" ) + " xmlns:gml=" + WFSXMLHelper . encQuotes ( "http://opengis.net/gml" ) + " xmlns:fes=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/fes/2.0" ) + " xmlns:ogc=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/ogc" ) + " xmlns:ows=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/ows/1.1\" xmlns:wfs=\"http://opengis.net/wfs/2.0" ) + " xmlns=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/wfs/2.0" ) + " version=\"2.0.0\">" ; writeServiceInfo ( ) ; }


Input:
Takes all added operations and writes an operations metadata section . [CODESPLIT] public void writeOperations ( ) { fileOutput += "<ows:OperationsMetadata> " ; for ( WFSRequestType rt : operationList ) { writeAOperation ( rt ) ; } // Write parameters
 fileOutput += "<ows:Parameter name=\"AcceptVersions\"> " + "<ows:AllowedValues> " + "<ows:Value>2.0.0</ows:Value>" + "</ows:AllowedValues>" + "</ows:Parameter>" ; fileOutput += "<ows:Parameter name=\"AcceptFormats\">" + "<ows:AllowedValues> " + "<ows:Value>text/xml</ows:Value>" + "</ows:AllowedValues>" + "</ows:Parameter>" ; fileOutput += "<ows:Parameter name=\"Sections\"> " + "<ows:AllowedValues> " + "<ows:Value>ServiceIdentification</ows:Value> " + "<ows:Value>ServiceProvider</ows:Value> " + "<ows:Value>OperationsMetadata</ows:Value> " + "<ows:Value>FeatureTypeList</ows:Value> " + "</ows:AllowedValues>" + "</ows:Parameter>" ; fileOutput += "<ows:Parameter name=\"version\"> " + "<ows:AllowedValues> " + "<ows:Value>2.0.0</ows:Value>" + "</ows:AllowedValues>" + "</ows:Parameter>" ; // Write constraints
 writeAConstraint ( "ImplementsBasicWFS" , true ) ; writeAConstraint ( "ImplementsTransactionalWFS" , false ) ; writeAConstraint ( "ImplementsLockingWFS" , false ) ; writeAConstraint ( "KVPEncoding" , false ) ; writeAConstraint ( "XMLEncoding" , true ) ; writeAConstraint ( "SOAPEncoding" , false ) ; writeAConstraint ( "ImplementsInheritance" , false ) ; writeAConstraint ( "ImplementsRemoteResolve" , false ) ; writeAConstraint ( "ImplementsResultPaging" , false ) ; writeAConstraint ( "ImplementsStandardJoins" , false ) ; writeAConstraint ( "ImplementsSpatialJoins" , false ) ; writeAConstraint ( "ImplementsTemporalJoins" , false ) ; writeAConstraint ( "ImplementsFeatureVersioning" , false ) ; writeAConstraint ( "ManageStoredQueries" , false ) ; writeAConstraint ( "PagingIsTransactionSafe" , false ) ; writeAConstraint ( "QueryExpressions" , false ) ; fileOutput += "</ows:OperationsMetadata>" ; }


Input: LOOK - needs to be a directory or maybe an MFILE collection [CODESPLIT] public void execute ( String filename ) throws IOException { try ( RandomAccessFile mraf = new RandomAccessFile ( filename , "r" ) ) { MessageScanner scanner = new MessageScanner ( mraf ) ; while ( scanner . hasNext ( ) ) { Message m = scanner . next ( ) ; if ( m == null ) continue ; total_msgs ++ ; if ( m . getNumberDatasets ( ) == 0 ) continue ; // LOOK check on tables complete etc ?? m . setRawBytes ( scanner . getMessageBytes ( m ) ) ; // decide what to do with the message dispatcher . dispatch ( m ) ; } dispatcher . resetBufrTableMessages ( ) ; } }


Input: Read all the files in a directory and process them . Files are sorted by filename . [CODESPLIT] public void readAll ( File dir , FileFilter ff , Closure closure , LogFilter logf , Stats stat ) throws IOException { File [ ] files = dir . listFiles ( ) ; if ( files == null ) { System . out . printf ( "Dir has no files= %s%n" , dir ) ; return ; } List < File > list = Arrays . asList ( files ) ; Collections . sort ( list ) ; for ( File f : list ) { if ( ( ff != null ) && ! ff . accept ( f ) ) continue ; if ( f . isDirectory ( ) ) readAll ( f , ff , closure , logf , stat ) ; else scanLogFile ( f , closure , logf , stat ) ; } }


Input: Read a log file . [CODESPLIT] public void scanLogFile ( File file , Closure closure , LogFilter logf , Stats stat ) throws IOException { try ( InputStream ios = new FileInputStream ( file ) ) { System . out . printf ( "-----Reading %s %n" , file . getPath ( ) ) ; BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( ios , CDM . utf8Charset ) , 40 * 1000 ) ; int total = 0 ; int count = 0 ; while ( ( maxLines < 0 ) || ( count < maxLines ) ) { Log log = parser . nextLog ( dataIS ) ; if ( log == null ) break ; total ++ ; if ( ( logf != null ) && ! logf . pass ( log ) ) continue ; closure . process ( log ) ; count ++ ; } if ( stat != null ) { stat . total += total ; stat . passed += count ; } System . out . printf ( "----- %s total requests=%d passed=%d %n" , file . getPath ( ) , total , count ) ; } }


Input: Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public static GempakGridReader getInstance ( RandomAccessFile raf , boolean fullCheck ) throws IOException { GempakGridReader ggr = new GempakGridReader ( raf . getLocation ( ) ) ; ggr . init ( raf , fullCheck ) ; return ggr ; }


Input: Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { boolean ok = super . init ( fullCheck ) ; if ( ! ok ) return false ; // Modeled after GD_OFIL if ( dmLabel . kftype != MFGD ) { logError ( "not a grid file" ) ; return false ; } // find the part for GRID DMPart part = getPart ( "GRID" ) ; if ( part == null ) { logError ( "No part named GRID found" ) ; return false ; } int lenhdr = part . klnhdr ; if ( lenhdr > LLGDHD ) { logError ( "Grid part header too long" ) ; return false ; } // int khdrln = lenhdr - 2; // check that the column names are correct for ( int i = 0 ; i < keys . kkcol . size ( ) ; i ++ ) { Key colkey = keys . kkcol . get ( i ) ; if ( ! colkey . name . equals ( kcolnm [ i ] ) ) { logError ( "Column name " + colkey + " doesn't match " + kcolnm [ i ] ) ; return false ; } } if ( ! fullCheck ) { return true ; } gridIndex = new GridIndex ( filename ) ; // Make the NAV and ANAL blocks float [ ] headerArray = getFileHeader ( NAVB ) ; if ( headerArray == null ) { return false ; } navBlock = new NavigationBlock ( headerArray ) ; //System.out.println("nav = " + navBlock); gridIndex . addHorizCoordSys ( navBlock ) ; headerArray = getFileHeader ( ANLB ) ; if ( headerArray == null ) { return false ; } analBlock = new AnalysisBlock ( headerArray ) ; // Make the grid headers // TODO: move this up into GempakFileReader using DM_RHDA // and account for the flipping there. List < GempakGridRecord > tmpList = new ArrayList <> ( ) ; int [ ] header = new int [ dmLabel . kckeys ] ; if ( ( headers == null ) || ( headers . colHeaders == null ) ) { return false ; } int gridNum = 0 ; for ( int [ ] fullHeader : headers . colHeaders ) { gridNum ++ ; // grid numbers are 1 based if ( ( fullHeader == null ) || ( fullHeader [ 0 ] == IMISSD ) ) { continue ; } // TODO: have GempakGridRecord skip the first word System . arraycopy ( fullHeader , 1 , header , 0 , header . length ) ; GempakGridRecord gh = new GempakGridRecord ( gridNum , header ) ; gh . navBlock = navBlock ; String name = gh . getParameterName ( ) ; //if (name.equals("TMPK") || //    name.equals("UREL") || //    name.equals("VREL") || //    name.equals("PMSL")) { tmpList . add ( gh ) ; //} } // reset the file size since we've gone through all the grids. fileSize = rf . length ( ) ; // find the packing types for these grids // TODO: go back to using gridList //List gridList = gridIndex.getGridRecords(); //if ( !gridList.isEmpty()) { if ( ! tmpList . isEmpty ( ) ) { for ( GempakGridRecord gh : tmpList ) { gh . packingType = getGridPackingType ( gh . gridNumber ) ; if ( ( gh . packingType == MDGGRB ) || ( gh . packingType == MDGRB2 ) || ( gh . packingType == MDGNON ) ) { gridIndex . addGridRecord ( gh ) ; } } } else { return false ; } // check to see if there are any grids that we can handle if ( gridIndex . getGridRecords ( ) . isEmpty ( ) ) { return false ; } return true ; }


Input: Run the program [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( "need to supply a GEMPAK grid file name" ) ; System . exit ( 1 ) ; } try { GempakGridParameterTable . addParameters ( "resources/nj22/tables/gempak/wmogrib3.tbl" ) ; GempakGridParameterTable . addParameters ( "resources/nj22/tables/gempak/ncepgrib2.tbl" ) ; } catch ( Exception e ) { System . out . println ( "unable to init param tables" ) ; } GempakGridReader ggr = getInstance ( getFile ( args [ 0 ] ) , true ) ; String var = "PMSL" ; if ( ( args . length > 1 ) && ! args [ 1 ] . equalsIgnoreCase ( "X" ) ) { var = args [ 1 ] ; } ggr . showGridInfo ( args . length != 3 ) ; GempakGridRecord gh = ggr . findGrid ( var ) ; if ( gh != null ) { System . out . println ( "\n" + var + ":" ) ; System . out . println ( gh ) ; for ( int j = 0 ; j < 2 ; j ++ ) { System . out . println ( "Using DP: " + ggr . useDP ) ; float [ ] data = ggr . readGrid ( gh ) ; if ( data != null ) { System . out . println ( "# of points = " + data . length ) ; int cnt = 0 ; int it = 10 ; float min = Float . POSITIVE_INFINITY ; float max = Float . NEGATIVE_INFINITY ; for ( int i = 0 ; i < data . length ; i ++ ) { if ( cnt == it ) { cnt = 0 ; } cnt ++ ; if ( ( data [ i ] != RMISSD ) && ( data [ i ] < min ) ) { min = data [ i ] ; } if ( ( data [ i ] != RMISSD ) && ( data [ i ] > max ) ) { max = data [ i ] ; } } System . out . println ( "max/min = " + max + "/" + min ) ; } else { System . out . println ( "unable to decode grid data" ) ; } ggr . useDP = ! ggr . useDP ; } } }


Input: Get the grid packing type [CODESPLIT] public int getGridPackingType ( int gridNumber ) throws IOException { // See DM_RDTR int irow = 1 ; // Always 1 for grids if ( ( gridNumber < 1 ) || ( gridNumber > dmLabel . kcol ) ) { logWarning ( "bad grid number " + gridNumber ) ; return - 9 ; } int iprt = getPartNumber ( "GRID" ) ; if ( iprt == 0 ) { logWarning ( "couldn't find part: GRID" ) ; return - 10 ; } // gotta subtract 1 because parts are 1 but List is 0 based DMPart part = parts . get ( iprt - 1 ) ; // check for valid data type if ( part . ktyprt != MDGRID ) { logWarning ( "Not a valid type: " + GempakUtil . getDataType ( part . ktyprt ) ) ; return - 21 ; } int ilenhd = part . klnhdr ; int ipoint = dmLabel . kpdata + ( irow - 1 ) * dmLabel . kcol * dmLabel . kprt + ( gridNumber - 1 ) * dmLabel . kprt + ( iprt - 1 ) ; // From DM_RPKG int istart = DM_RINT ( ipoint ) ; if ( istart == 0 ) { return - 15 ; } int length = DM_RINT ( istart ) ; int isword = istart + 1 ; if ( length <= ilenhd ) { logWarning ( "length (" + length + ") is less than header length (" + ilenhd + ")" ) ; return - 15 ; } else if ( Math . abs ( length ) > 10000000 ) { logWarning ( "length is huge: " + length ) ; return - 34 ; } int [ ] header = new int [ ilenhd ] ; DM_RINT ( isword , header ) ; // int nword = length - ilenhd; isword += ilenhd ; // read the data packing type return DM_RINT ( isword ) ; }


Input: Find the first grid with this name [CODESPLIT] public GempakGridRecord findGrid ( String parm ) { List < GridRecord > gridList = gridIndex . getGridRecords ( ) ; if ( gridList == null ) { return null ; } for ( GridRecord grid : gridList ) { GempakGridRecord gh = ( GempakGridRecord ) grid ; if ( gh . param . trim ( ) . equals ( parm ) ) { return gh ; } } return null ; }


Input: Read the data [CODESPLIT] public float [ ] readGrid ( GridRecord gr ) throws IOException { int gridNumber = ( ( GempakGridRecord ) gr ) . getGridNumber ( ) ; //int irow = 1;  // Always 1 for grids //int icol = gridNumber; RData data = DM_RDTR ( 1 , gridNumber , "GRID" , gr . getDecimalScale ( ) ) ; float [ ] vals = null ; if ( data != null ) { vals = data . data ; } return vals ; }


Input: Unpack a packed grid [CODESPLIT] public float [ ] DM_RPKG ( int isword , int nword , int decimalScale ) throws IOException { // from DM_RPKG // read the data packing type float [ ] data ; int ipktyp = DM_RINT ( isword ) ; int iiword = isword + 1 ; int lendat = nword - 1 ; if ( ipktyp == MDGNON ) { // no packing data = new float [ lendat ] ; DM_RFLT ( iiword , data ) ; return data ; } int iiw ; int irw ; if ( ipktyp == MDGDIF ) { iiw = 4 ; irw = 3 ; } else if ( ipktyp == MDGRB2 ) { iiw = 4 ; irw = 1 ; } else { iiw = 3 ; irw = 2 ; } int [ ] iarray = new int [ iiw ] ; float [ ] rarray = new float [ irw ] ; DM_RINT ( iiword , iarray ) ; iiword = iiword + iiw ; lendat = lendat - iiw ; DM_RFLT ( iiword , rarray ) ; iiword = iiword + irw ; lendat = lendat - irw ; if ( ipktyp == MDGRB2 ) { data = unpackGrib2Data ( iiword , lendat , iarray , rarray ) ; return data ; } int nbits = iarray [ 0 ] ; int misflg = iarray [ 1 ] ; boolean miss = misflg != 0 ; int kxky = iarray [ 2 ] ; // int mword = kxky; int kx = 0 ; if ( iiw == 4 ) { kx = iarray [ 3 ] ; } float ref = rarray [ 0 ] ; float scale = rarray [ 1 ] ; float difmin = 0 ; if ( irw == 3 ) { difmin = rarray [ 2 ] ; } data = unpackData ( iiword , lendat , ipktyp , kxky , nbits , ref , scale , miss , difmin , kx , decimalScale ) ; return data ; }


Input: Read packed data [CODESPLIT] private synchronized float [ ] unpackData ( int iiword , int nword , int ipktyp , int kxky , int nbits , float ref , float scale , boolean miss , float difmin , int kx , int decimalScale ) throws IOException { if ( ipktyp == MDGGRB ) { if ( ! useDP ) { return unpackGrib1Data ( iiword , nword , kxky , nbits , ref , scale , miss , decimalScale ) ; } else { if ( nword * 32 < kxky * nbits ) { // to account for badly written files nword ++ ; } int [ ] ksgrid = new int [ nword ] ; DM_RINT ( iiword , ksgrid ) ; return DP_UGRB ( ksgrid , kxky , nbits , ref , scale , miss , decimalScale ) ; } } else if ( ipktyp == MDGNMC ) { return null ; } else if ( ipktyp == MDGDIF ) { return null ; } return null ; }


Input:
Unpack grib data packed into ints [CODESPLIT] private synchronized float [ ] DP_UGRB ( int [ ] idata , int kxky , int nbits , float qmin , float scale , boolean misflg , int decimalScale ) throws IOException { float scaleFactor = ( decimalScale == 0 ) ? 1.f : ( float ) Math . pow ( 10.0 , - decimalScale ) ; // //Check for valid input. // float [ ] grid = new float [ kxky ] ; if ( ( nbits <= 1 ) || ( nbits > 31 ) ) { return grid ; } if ( scale == 0. ) { return grid ; } // //Compute missing data value. // int imax = ( int ) ( Math . pow ( 2 , nbits ) - 1 ) ; // //Retrieve data points from buffer. // int iword = 0 ; int ibit = 1 ; // 1 based bit position for ( int i = 0 ; i < kxky ; i ++ ) { // //    Get the integer from the buffer. // int jshft = nbits + ibit - 33 ; int idat = 0 ; idat = ( jshft < 0 ) ? idata [ iword ] >>> Math . abs ( jshft ) : idata [ iword ] << jshft ; idat = idat & imax ; // //    Check to see if packed integer overflows into next word. LOOK fishy bit operations // if ( jshft > 0 ) { jshft -= 32 ; int idat2 = 0 ; idat2 = idata [ iword + 1 ] >>> Math . abs ( jshft ) ; idat = idat | idat2 ; } // //    Compute value of word. // if ( ( idat == imax ) && misflg ) { grid [ i ] = RMISSD ; } else { grid [ i ] = ( qmin + idat * scale ) * scaleFactor ; } // //    Set location for next word. // ibit += nbits ; if ( ibit > 32 ) { ibit -= 32 ; iword ++ ; } /*
            if (i < 25) {
                System.out.println("grid["+i+"]: " + grid[i]);
            }
            */ } return grid ; }


Input:
Read packed Grib1 data using ucar . grib code [CODESPLIT] private float [ ] unpackGrib1Data ( int iiword , int nword , int kxky , int nbits , float ref , float scale , boolean miss , int decimalScale ) throws IOException { //System.out.println("decimal scale = " + decimalScale); float [ ] values = new float [ kxky ] ; bitPos = 0 ; bitBuf = 0 ; next = 0 ; ch1 = 0 ; ch2 = 0 ; ch3 = 0 ; ch4 = 0 ; rf . seek ( getOffset ( iiword ) ) ; int idat ; // save a pow call if we can float scaleFactor = ( decimalScale == 0 ) ? 1.f : ( float ) Math . pow ( 10.0 , - decimalScale ) ; //float scaleFactor = (float) Math.pow(10.0, -decimalScale); for ( int i = 0 ; i < values . length ; i ++ ) { idat = bits2UInt ( nbits ) ; if ( miss && ( idat == IMISSD ) ) { values [ i ] = IMISSD ; } else { values [ i ] = ( ref + scale * idat ) * scaleFactor ; } /*
            if (i < 25) {
                System.out.println("values[" + i + "] = " + values[i]);
            }
            */ } return values ; }


Input: Read packed Grib2 data [CODESPLIT] private float [ ] unpackGrib2Data ( int iiword , int lendat , int [ ] iarray , float [ ] rarray ) throws IOException { long start = getOffset ( iiword ) ; rf . seek ( start ) ; Grib2Record gr = makeGribRecord ( rf , start ) ; float [ ] data = gr . readData ( rf ) ; if ( ( ( iarray [ 3 ] >> 6 ) & 1 ) == 0 ) { // -y scanning - flip data = gb2_ornt ( iarray [ 1 ] , iarray [ 2 ] , iarray [ 3 ] , data ) ; } return data ; }


Input: for GempakGridReader [CODESPLIT] private Grib2Record makeGribRecord ( RandomAccessFile raf , long start ) throws IOException { Grib2SectionIndicator is = new Grib2SectionIndicator ( start , 0 , 0 ) ; // apparently not in GEMPAK file (!) Grib2SectionIdentification ids = null ; Grib2SectionLocalUse lus = null ; Grib2SectionGridDefinition gds = null ; Grib2SectionProductDefinition pds = null ; Grib2SectionDataRepresentation drs = null ; Grib2SectionBitMap bms = null ; Grib2SectionData dataSection = null ; raf . seek ( start ) ; raf . order ( RandomAccessFile . BIG_ENDIAN ) ; int secLength = raf . readInt ( ) ; if ( secLength > 0 ) { ids = new Grib2SectionIdentification ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { lus = new Grib2SectionLocalUse ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { gds = new Grib2SectionGridDefinition ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { pds = new Grib2SectionProductDefinition ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { drs = new Grib2SectionDataRepresentation ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { bms = new Grib2SectionBitMap ( raf ) ; } secLength = raf . readInt ( ) ; if ( secLength > 0 ) { dataSection = new Grib2SectionData ( raf ) ; if ( dataSection . getMsgLength ( ) > secLength ) // presumably corrupt throw new IllegalStateException ( "Illegal Grib2SectionData Message Length" ) ; } // LOOK - not dealing with repeated records return new Grib2Record ( null , is , ids , lus , gds , pds , drs , bms , dataSection , false , Grib2Index . ScanModeMissing ) ; }


Input: Print out the navigation block so it looks something like this : <pre > GRID NAVIGATION : PROJECTION : LCC ANGLES : 25 . 0 - 95 . 0 25 . 0 GRID SIZE : 93 65 LL CORNER : 12 . 19 - 133 . 46 UR CORNER : 57 . 29 - 49 . 38 < / pre > [CODESPLIT] public void printNavBlock ( ) { StringBuilder buf = new StringBuilder ( "GRID NAVIGATION:" ) ; if ( navBlock != null ) { buf . append ( navBlock . toString ( ) ) ; } else { buf . append ( "\n\tUNKNOWN GRID NAVIGATION" ) ; } System . out . println ( buf . toString ( ) ) ; }


Input: Print out the analysis block so it looks something like this : [CODESPLIT] public void printAnalBlock ( ) { StringBuilder buf = new StringBuilder ( "GRID ANALYSIS BLOCK:" ) ; if ( analBlock != null ) { buf . append ( analBlock . toString ( ) ) ; } else { buf . append ( "\n\tUNKNOWN ANALYSIS TYPE" ) ; } System . out . println ( buf . toString ( ) ) ; }


Input: Print out the grids . [CODESPLIT] public void printGrids ( ) { List < GridRecord > gridList = gridIndex . getGridRecords ( ) ; if ( gridList == null ) return ; System . out . println ( "  NUM       TIME1              TIME2           LEVL1 LEVL2  VCORD PARM" ) ; for ( GridRecord aGridList : gridList ) { System . out . println ( aGridList ) ; } }


Input: List out the grid information ( aka GDINFO ) [CODESPLIT] public void showGridInfo ( boolean printGrids ) { List gridList = gridIndex . getGridRecords ( ) ; System . out . println ( "\nGRID FILE: " + getFilename ( ) + "\n" ) ; printNavBlock ( ) ; System . out . println ( "" ) ; printAnalBlock ( ) ; System . out . println ( "\nNumber of grids in file:  " + gridList . size ( ) ) ; System . out . println ( "\nMaximum number of grids in file:  " + dmLabel . kcol ) ; System . out . println ( "" ) ; if ( printGrids ) { printGrids ( ) ; } }


Input: gb2_ornt <p / > This function checks the fields scanning mode flags and re - orders the grid point values so that they traverse left to right for each row starting at the bottom row . <p / > gb2_ornt ( kx ky scan_mode ingrid fgrid iret ) <p / > Input parameters : kx int Number of columns ky int Number of rows scan_mode int GRIB2 scanning mode flag * ingrid float unpacked GRIB2 grid data <p / > Output parameters : * fgrid float Unpacked grid data * iret int Return code - 40 = scan mode not implemented <p / > Log : S . Gilbert 1 / 04 [CODESPLIT] private float [ ] gb2_ornt ( int kx , int ky , int scan_mode , float [ ] ingrid ) { float [ ] fgrid = new float [ ingrid . length ] ; int ibeg , jbeg , iinc , jinc , itmp ; int icnt , jcnt , kcnt , idxarr ; int idrct , jdrct , consec , boustr ; idrct = ( scan_mode >> 7 ) & 1 ; jdrct = ( scan_mode >> 6 ) & 1 ; consec = ( scan_mode >> 5 ) & 1 ; boustr = ( scan_mode >> 4 ) & 1 ; if ( idrct == 0 ) { ibeg = 0 ; iinc = 1 ; } else { ibeg = kx - 1 ; iinc = - 1 ; } if ( jdrct == 1 ) { jbeg = 0 ; jinc = 1 ; } else { jbeg = ky - 1 ; jinc = - 1 ; } kcnt = 0 ; if ( ( consec == 1 ) && ( boustr == 0 ) ) { /*  adjacent points in same column;  each column same direction  */ for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = ky * icnt + jcnt ; fgrid [ kcnt ] = ingrid [ idxarr ] ; kcnt ++ ; } } } else if ( ( consec == 0 ) && ( boustr == 0 ) ) { /*  adjacent points in same row;  each row same direction  */ for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = kx * jcnt + icnt ; fgrid [ kcnt ] = ingrid [ idxarr ] ; kcnt ++ ; } } } else if ( ( consec == 1 ) && ( boustr == 1 ) ) { /*  adjacent points in same column; each column alternates direction */ for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { itmp = jcnt ; if ( ( idrct == 1 ) && ( kx % 2 == 0 ) ) { itmp = ky - jcnt - 1 ; } for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = ky * icnt + itmp ; fgrid [ kcnt ] = ingrid [ idxarr ] ; itmp = ( itmp != jcnt ) ? jcnt : ky - jcnt - 1 ; /* toggle */ kcnt ++ ; } } } else if ( ( consec == 0 ) && ( boustr == 1 ) ) { /*  adjacent points in same row;  each row alternates direction  */ if ( jdrct == 0 ) { if ( ( idrct == 0 ) && ( ky % 2 == 0 ) ) { ibeg = kx - 1 ; iinc = - 1 ; } if ( ( idrct == 1 ) && ( ky % 2 == 0 ) ) { ibeg = 0 ; iinc = 1 ; } } for ( jcnt = jbeg ; ( ( 0 <= jcnt ) && ( jcnt < ky ) ) ; jcnt += jinc ) { for ( icnt = ibeg ; ( ( 0 <= icnt ) && ( icnt < kx ) ) ; icnt += iinc ) { idxarr = kx * jcnt + icnt ; fgrid [ kcnt ] = ingrid [ idxarr ] ; kcnt ++ ; } ibeg = ( ibeg != 0 ) ? 0 : kx - 1 ; /* toggle */ iinc = ( iinc != 1 ) ? 1 : - 1 ; /* toggle */ } } //else {          logically dead code //fgrid = ingrid; //} return fgrid ; }


Input: Convert bits ( nb ) to Unsigned Int . [CODESPLIT] private int bits2UInt ( int nb ) throws IOException { int bitsLeft = nb ; int result = 0 ; if ( bitPos == 0 ) { //bitBuf = raf.read(); getNextByte ( ) ; bitPos = 8 ; } while ( true ) { int shift = bitsLeft - bitPos ; if ( shift > 0 ) { // Consume the entire buffer result |= bitBuf << shift ; bitsLeft -= bitPos ; // Get the next byte from the RandomAccessFile //bitBuf = raf.read(); getNextByte ( ) ; bitPos = 8 ; } else { // Consume a portion of the buffer result |= bitBuf >> - shift ; bitPos -= bitsLeft ; bitBuf &= 0xff >> ( 8 - bitPos ) ; // mask off consumed bits return result ; } } // end while }


Input: Get the next byte [CODESPLIT] private void getNextByte ( ) throws IOException { if ( ! needToSwap ) { // Get the next byte from the RandomAccessFile bitBuf = rf . read ( ) ; } else { if ( next == 3 ) { bitBuf = ch3 ; } else if ( next == 2 ) { bitBuf = ch2 ; } else if ( next == 1 ) { bitBuf = ch1 ; } else { ch1 = rf . read ( ) ; ch2 = rf . read ( ) ; ch3 = rf . read ( ) ; ch4 = rf . read ( ) ; bitBuf = ch4 ; next = 4 ; } next -- ; } }


Input:
Adds a variable to the container . [CODESPLIT] public void addVariable ( BaseType v ) { vals = v . newPrimitiveVector ( ) ; setClearName ( v . getClearName ( ) ) ; v . setParent ( this ) ; setContainerVar ( v ) ; // save v for cloning
 }


Input:
Coverity [ CALL_SUPER ] [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType
 // and all of the different signatures of printDecl() in BaseType
 // lead to one signature, we must be careful to override that
 // SAME signature here. That way all calls to printDecl() for
 // this object lead to this implementation.
 //os.println("DVector.printDecl()");
 os . print ( space + getTypeName ( ) ) ; vals . printDecl ( os , " " , print_semi , constrained ) ; }


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 . print ( " = " ) ; } os . print ( "{ " ) ; vals . printVal ( os , "" ) ; if ( print_decl_p ) os . println ( "};" ) ; else os . print ( "}" ) ; }


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 { // Because arrays of primitive types (ie int32, float32, byte, etc) are
 // handled in the C++ core using the XDR package we must read the
 // length twice for those types. For BaseType vectors, we should read
 // it only once. This is in effect a work around for a bug in the C++
 // core as the C++ core does not consume 2 length values for the
 // BaseType vectors. Bummer...
 int length ; length = source . readInt ( ) ; if ( ! ( vals instanceof BaseTypePrimitiveVector ) ) { // because both XDR and OPeNDAP write the length, we must read it twice
 int length2 = source . readInt ( ) ; //LogStream.out.println("array1 length read: "+getName()+" "+length+ " -- "+length2);
 //LogStream.out.println("  array type = : "+vals.getClass().getName());
 // QC the second length
 if ( length != length2 ) { throw new DataReadException ( "Inconsistent array length read: " + length + " != " + length2 ) ; } } /* else {
          LogStream.dbg.println("array2 length read: "+getName()+" "+length);
          LogStream.dbg.println("  array type = : "+vals.getClass().getName());
        } */ if ( length < 0 ) throw new DataReadException ( "Negative array length read." ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 8 ) ; vals . setLength ( length ) ; vals . deserialize ( source , sv , statusUI ) ; }


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 { // Because arrays of primitive types (ie int32, float32, byte, etc) are
 // handled in the C++ core using the XDR package we must write the
 // length twice for those types. For BaseType vectors, we should write
 // it only once. This is in effect a work around for a bug in the C++
 // core as the C++ core does not consume 2 length values for thge
 // BaseType vectors. Bummer...
 int length = vals . getLength ( ) ; sink . writeInt ( length ) ; if ( ! ( vals instanceof BaseTypePrimitiveVector ) ) { // because both XDR and OPeNDAP write the length, we must write it twice
 sink . writeInt ( length ) ; } vals . externalize ( sink ) ; }


Input:
Returns a clone of this <code > Vector< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DVector v = ( DVector ) super . cloneDAG ( map ) ; v . vals = ( PrimitiveVector ) cloneDAG ( map , vals ) ; // clone the container variable
 v . containedvar = ( BaseType ) cloneDAG ( map , containedvar ) ; return v ; }


Input:
Get Calendar date from fields . Uses UTZ time zone [CODESPLIT] public static CalendarDate of ( Calendar cal , int year , int monthOfYear , int dayOfMonth , int hourOfDay , int minuteOfHour , int secondOfMinute ) { Chronology base = Calendar . getChronology ( cal ) ; /* if (base == null)
      base = ISOChronology.getInstanceUTC(); // already in UTC
    else
      base = ZonedChronology.getInstance( base, DateTimeZone.UTC); // otherwise wrap it to be in UTC  */ DateTime dt = new DateTime ( year , monthOfYear , dayOfMonth , hourOfDay , minuteOfHour , secondOfMinute , base ) ; if ( ! Calendar . isDefaultChronology ( cal ) ) dt = dt . withChronology ( Calendar . getChronology ( cal ) ) ; dt = dt . withZone ( DateTimeZone . UTC ) ; return new CalendarDate ( cal , dt ) ; }


Input: Create CalendarDate from a java . util . Date . Uses standard Calendar . [CODESPLIT] public static CalendarDate of ( java . util . Date date ) { DateTime dt = new DateTime ( date , DateTimeZone . UTC ) ; return new CalendarDate ( null , dt ) ; }


Input:
Create CalendarDate from msecs since epoch Uses standard Calendar . [CODESPLIT] public static CalendarDate of ( long msecs ) { // Constructs an instance set to the milliseconds from 1970-01-01T00:00:00Z using ISOChronology in the specified time zone.
 DateTime dt = new DateTime ( msecs , DateTimeZone . UTC ) ; return new CalendarDate ( null , dt ) ; }


Input: Create CalendarDate from msecs since epoch Uses the given Calendar . [CODESPLIT] public static CalendarDate of ( Calendar cal , long msecs ) { Chronology base = Calendar . getChronology ( cal ) ; DateTime dt = new DateTime ( msecs , base ) ; return new CalendarDate ( cal , dt ) ; }


Input: Get CalendarDate from ISO date string [CODESPLIT] @ Nullable public static CalendarDate parseUdunitsOrIso ( String calendarName , String isoOrUdunits ) { CalendarDate result ; try { result = parseISOformat ( calendarName , isoOrUdunits ) ; } catch ( Exception e ) { try { result = parseUdunits ( calendarName , isoOrUdunits ) ; } catch ( Exception e2 ) { return null ; } } return result ; }


Input: Get CalendarDate from ISO date string [CODESPLIT] public static CalendarDate parseISOformat ( String calendarName , String isoDateString ) { Calendar cal = Calendar . get ( calendarName ) ; if ( cal == null ) cal = Calendar . getDefault ( ) ; return CalendarDateFormatter . isoStringToCalendarDate ( cal , isoDateString ) ; }


Input: Get CalendarDate from udunit date string [CODESPLIT] public static CalendarDate parseUdunits ( String calendarName , String udunits ) { int pos = udunits . indexOf ( ' ' ) ; if ( pos < 0 ) return null ; String valString = udunits . substring ( 0 , pos ) . trim ( ) ; String unitString = udunits . substring ( pos + 1 ) . trim ( ) ; CalendarDateUnit cdu = CalendarDateUnit . of ( calendarName , unitString ) ; double val = Double . parseDouble ( valString ) ; return cdu . makeCalendarDate ( val ) ; }


Input: / * Millisec ( PeriodType . millis () ) Second ( PeriodType . seconds () ) Minute ( PeriodType . minutes () ) Hour ( PeriodType . hours () ) Day ( PeriodType . days () ) Month ( PeriodType . months () ) Year ( PeriodType . years () ) [CODESPLIT] public int getFieldValue ( CalendarPeriod . Field fld ) { switch ( fld ) { case Day : return dateTime . get ( DateTimeFieldType . dayOfMonth ( ) ) ; case Hour : return dateTime . get ( DateTimeFieldType . hourOfDay ( ) ) ; case Millisec : return dateTime . get ( DateTimeFieldType . millisOfSecond ( ) ) ; case Minute : return dateTime . get ( DateTimeFieldType . minuteOfHour ( ) ) ; case Month : return dateTime . get ( DateTimeFieldType . monthOfYear ( ) ) ; case Second : return dateTime . get ( DateTimeFieldType . secondOfMinute ( ) ) ; case Year : return dateTime . get ( DateTimeFieldType . year ( ) ) ; } throw new IllegalArgumentException ( "unimplemented " + fld ) ; }


Input: calendar date field [CODESPLIT] public CalendarDate add ( CalendarPeriod period ) { switch ( period . getField ( ) ) { case Millisec : return new CalendarDate ( cal , dateTime . plusMillis ( period . getValue ( ) ) ) ; case Second : return new CalendarDate ( cal , dateTime . plusSeconds ( period . getValue ( ) ) ) ; case Minute : return new CalendarDate ( cal , dateTime . plusMinutes ( period . getValue ( ) ) ) ; case Hour : return new CalendarDate ( cal , dateTime . plusHours ( period . getValue ( ) ) ) ; case Day : return new CalendarDate ( cal , dateTime . plusDays ( period . getValue ( ) ) ) ; case Month : return new CalendarDate ( cal , dateTime . plusMonths ( period . getValue ( ) ) ) ; case Year : return new CalendarDate ( cal , dateTime . plusYears ( period . getValue ( ) ) ) ; } throw new UnsupportedOperationException ( "period units = " + period ) ; }


Input: calendar date field [CODESPLIT] public CalendarDate subtract ( CalendarPeriod period ) { switch ( period . getField ( ) ) { case Millisec : return new CalendarDate ( cal , dateTime . minusMillis ( period . getValue ( ) ) ) ; case Second : return new CalendarDate ( cal , dateTime . minusSeconds ( period . getValue ( ) ) ) ; case Minute : return new CalendarDate ( cal , dateTime . minusMinutes ( period . getValue ( ) ) ) ; case Hour : return new CalendarDate ( cal , dateTime . minusHours ( period . getValue ( ) ) ) ; case Day : return new CalendarDate ( cal , dateTime . minusDays ( period . getValue ( ) ) ) ; case Month : return new CalendarDate ( cal , dateTime . minusMonths ( period . getValue ( ) ) ) ; case Year : return new CalendarDate ( cal , dateTime . minusYears ( period . getValue ( ) ) ) ; } throw new UnsupportedOperationException ( "period units = " + period ) ; }


Input: truncate the CalendarDate by zeroing all the fields that are less than the field . So 2013 - 03 - 01T19 : 30 becomes 2013 - 03 - 01T00 : 00 if the field is day [CODESPLIT] public CalendarDate truncate ( CalendarPeriod . Field fld ) { switch ( fld ) { case Minute : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , dateTime . getDayOfMonth ( ) , dateTime . getHourOfDay ( ) , dateTime . getMinuteOfHour ( ) , 0 ) ; case Hour : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , dateTime . getDayOfMonth ( ) , dateTime . getHourOfDay ( ) , 0 , 0 ) ; case Day : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , dateTime . getDayOfMonth ( ) , 0 , 0 , 0 ) ; case Month : return CalendarDate . of ( cal , dateTime . getYear ( ) , dateTime . getMonthOfYear ( ) , 1 , 0 , 0 , 0 ) ; case Year : return CalendarDate . of ( cal , dateTime . getYear ( ) , 1 , 1 , 0 , 0 , 0 ) ; } return this ; }


Input: Get difference between two calendar dates in given Field units [CODESPLIT] public long getDifference ( CalendarDate o , CalendarPeriod . Field fld ) { switch ( fld ) { case Millisec : return getDifferenceInMsecs ( o ) ; case Second : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_SECOND ) ; case Minute : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_MINUTE ) ; case Hour : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_HOUR ) ; case Day : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_DAY ) ; case Month : int tmonth = getFieldValue ( CalendarPeriod . Field . Month ) ; int omonth = o . getFieldValue ( CalendarPeriod . Field . Month ) ; int years = ( int ) this . getDifference ( o , CalendarPeriod . Field . Year ) ; return tmonth - omonth + 12 * years ; case Year : int tyear = getFieldValue ( CalendarPeriod . Field . Year ) ; int oyear = o . getFieldValue ( CalendarPeriod . Field . Year ) ; return tyear - oyear ; } return dateTime . getMillis ( ) - o . dateTime . getMillis ( ) ; }


Input: / * package access [CODESPLIT] Map < Variable , Array > create ( ) throws DapException { // iterate over the variables represented in the DSP List < DapVariable > topvars = this . dmr . getTopVariables ( ) ; Map < Variable , Array > map = null ; for ( DapVariable var : topvars ) { DataCursor cursor = this . dsp . getVariableData ( var ) ; Array array = createVar ( cursor ) ; Variable cdmvar = ( Variable ) nodemap . get ( var ) ; arraymap . put ( cdmvar , array ) ; } return this . arraymap ; }


Input: Create an Atomic Valued variable . [CODESPLIT] protected CDMArrayAtomic createAtomicVar ( DataCursor data ) throws DapException { CDMArrayAtomic array = new CDMArrayAtomic ( data ) ; return array ; }


Input: Create an array of structures . WARNING : the underlying CDM code ( esp . NetcdfDataset ) apparently does not support nested structure arrays ; so this code may throw an exception . [CODESPLIT] protected CDMArrayStructure createStructure ( DataCursor data ) throws DapException { CDMArrayStructure arraystruct = new CDMArrayStructure ( this . cdmroot , data ) ; DapVariable var = ( DapVariable ) data . getTemplate ( ) ; DapStructure struct = ( DapStructure ) var . getBaseType ( ) ; int nmembers = struct . getFields ( ) . size ( ) ; List < DapDimension > dimset = var . getDimensions ( ) ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; long offset = index . index ( ) ; DataCursor [ ] cursors = ( DataCursor [ ] ) data . read ( index ) ; DataCursor ithelement = cursors [ 0 ] ; for ( int f = 0 ; f < nmembers ; f ++ ) { DataCursor dc = ( DataCursor ) ithelement . readField ( f ) ; Array afield = createVar ( dc ) ; arraystruct . add ( offset , f , afield ) ; } } return arraystruct ; }


Input: Create a sequence . WARNING : the underlying CDM code ( esp . NetcdfDataset ) apparently does not support nested sequence arrays . [CODESPLIT] protected CDMArraySequence createSequence ( DataCursor data ) throws DapException { CDMArraySequence arrayseq = new CDMArraySequence ( this . cdmroot , data ) ; DapVariable var = ( DapVariable ) data . getTemplate ( ) ; DapSequence template = ( DapSequence ) var . getBaseType ( ) ; List < DapDimension > dimset = var . getDimensions ( ) ; long dimsize = DapUtil . dimProduct ( dimset ) ; int nfields = template . getFields ( ) . size ( ) ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) ) ; while ( odom . hasNext ( ) ) { odom . next ( ) ; DataCursor seq = ( ( DataCursor [ ] ) data . read ( odom . indices ( ) ) ) [ 0 ] ; long nrecords = seq . getRecordCount ( ) ; for ( int r = 0 ; r < nrecords ; r ++ ) { DataCursor rec = seq . readRecord ( r ) ; for ( int f = 0 ; f < nfields ; f ++ ) { DataCursor dc = rec . readField ( f ) ; Array afield = createVar ( dc ) ; arrayseq . add ( r , f , afield ) ; } } } return arrayseq ; }


Input: Invoked once on first request so that everything is available especially Spring stuff . [CODESPLIT] public void doonce ( HttpServletRequest req ) throws SendError { if ( once ) return ; super . initOnce ( req ) ; if ( this . downloaddir == null ) throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , "Download disabled" ) ; this . downloaddirname = new File ( this . downloaddir ) . getName ( ) ; // Get the download form File downform = null ; downform = tdsContext . getDownloadForm ( ) ; if ( downform == null ) { // Look in WEB-INF directory File root = tdsContext . getServletRootDirectory ( ) ; downform = new File ( root , DEFAULTDOWNLOADFORM ) ; } try { this . downloadform = loadForm ( downform ) ; } catch ( IOException ioe ) { throw new SendError ( HttpStatus . SC_PRECONDITION_FAILED , ioe ) ; } }


Input: Setup for each request [CODESPLIT] public void setup ( HttpServletRequest req , HttpServletResponse resp ) throws SendError { this . req = req ; this . res = resp ; if ( ! once ) doonce ( req ) ; // Parse any query parameters try { this . params = new DownloadParameters ( req ) ; } catch ( IOException ioe ) { throw new SendError ( res . SC_BAD_REQUEST , ioe ) ; } }


Input: Controller entry point ( s ) [CODESPLIT] @ RequestMapping ( value = "**" , method = RequestMethod . GET ) public void doGet ( HttpServletRequest req , HttpServletResponse res ) throws ServletException { try { setup ( req , res ) ; String sresult = null ; switch ( this . params . command ) { case DOWNLOAD : try { String fulltargetpath = download ( ) ; if ( this . params . fromform ) { sendForm ( "Download succeeded: result file: " + fulltargetpath ) ; } else { Map < String , String > result = new HashMap <> ( ) ; result . put ( "download" , fulltargetpath ) ; sresult = mapToString ( result , true , "download" ) ; sendOK ( sresult ) ; } } catch ( SendError se ) { if ( this . params . fromform ) { // Send back the download form with error msg sendForm ( "Download failed: " + se . getMessage ( ) ) ; } else throw se ; } break ; case INQUIRE : sresult = inquire ( ) ; // Send back the inquiry answers sendOK ( sresult ) ; break ; case NONE : // Use form-based download // Send back the download form sendForm ( "No files downloaded" ) ; break ; } } catch ( SendError se ) { sendError ( se ) ; } catch ( Exception e ) { String msg = getStackTrace ( e ) ; sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , msg , e ) ; } }


Input: Reifiers [CODESPLIT] protected void makeNetcdf4 ( NetcdfFile ncfile , String target ) throws IOException { try { CancelTaskImpl cancel = new CancelTaskImpl ( ) ; FileWriter2 writer = new FileWriter2 ( ncfile , target , NetcdfFileWriter . Version . netcdf4 , chunking ) ; writer . getNetcdfFileWriter ( ) . setLargeFile ( true ) ; NetcdfFile ncfileOut = writer . write ( cancel ) ; if ( ncfileOut != null ) ncfileOut . close ( ) ; cancel . setDone ( true ) ; } catch ( IOException ioe ) { throw ioe ; // temporary } }


Input: Given a typical string insert backslashes before and \\ characters and control characters . [CODESPLIT] static protected String escapeString ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; switch ( c ) { case ' ' : buf . append ( "\\\"" ) ; break ; case ' ' : buf . append ( "\\\\" ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; default : if ( c < ' ' ) buf . append ( String . format ( "\\x%02x" , ( c & 0xff ) ) ) ; else buf . append ( ( char ) c ) ; break ; } } return buf . toString ( ) ; }


Input: //////////////////////////////////////////////// [CODESPLIT] @ Override protected String buildForm ( String msg ) { StringBuilder svc = new StringBuilder ( ) ; svc . append ( this . server ) ; svc . append ( "/" ) ; svc . append ( this . threddsname ) ; String form = String . format ( this . downloadform , svc . toString ( ) , msg ) ; return form ; }


Input: Convert a list of ucar . ma2 . Range to a list of Slice More or less the inverst of create CDMRanges [CODESPLIT] static public List < Slice > createSlices ( List < Range > rangelist ) throws dap4 . core . util . DapException { List < Slice > slices = new ArrayList < Slice > ( rangelist . size ( ) ) ; for ( int i = 0 ; i < rangelist . size ( ) ; i ++ ) { Range r = rangelist . get ( i ) ; // r does not store last int stride = r . stride ( ) ; int first = r . first ( ) ; int n = r . length ( ) ; int stop = first + ( n * stride ) ; Slice cer = new Slice ( first , stop - 1 , stride ) ; slices . add ( cer ) ; } return slices ; }


Input: Test a List<Range > against a List<DapDimension > to see if the range list represents the whole set of dimensions within the specified indices . [CODESPLIT] static public boolean isWhole ( List < Range > rangelist , List < DapDimension > dimset , int start , int stop ) throws dap4 . core . util . DapException { int rsize = ( rangelist == null ? 0 : rangelist . size ( ) ) ; if ( rsize != dimset . size ( ) ) throw new dap4 . core . util . DapException ( "range/dimset rank mismatch" ) ; if ( rsize == 0 ) return true ; if ( start < 0 || stop < start || stop > rsize ) throw new dap4 . core . util . DapException ( "Invalid start/stop indices" ) ; for ( int i = start ; i < stop ; i ++ ) { Range r = rangelist . get ( i ) ; DapDimension d = dimset . get ( i ) ; if ( r . stride ( ) != 1 || r . first ( ) != 0 || r . length ( ) != d . getSize ( ) ) return false ; } return true ; }


Input: Test a List<Range > against a List<Slice > to see if the range list is whole wrt the slices [CODESPLIT] static public boolean isWhole ( List < Range > rangelist , List < Slice > slices ) throws dap4 . core . util . DapException { if ( rangelist . size ( ) != slices . size ( ) ) return false ; for ( int i = 0 ; i < rangelist . size ( ) ; i ++ ) { Range r = rangelist . get ( i ) ; Slice slice = slices . get ( i ) ; if ( r . stride ( ) != 1 || r . first ( ) != 0 || r . length ( ) != slice . getCount ( ) ) return false ; } return true ; }


Input: Test a List<Range > against the CDM variable s dimensions to see if the range list is whole wrt the dimensions [CODESPLIT] static public boolean isWhole ( List < Range > rangelist , Variable var ) throws dap4 . core . util . DapException { List < Dimension > dimset = var . getDimensions ( ) ; if ( rangelist . size ( ) != dimset . size ( ) ) return false ; for ( int i = 0 ; i < rangelist . size ( ) ; i ++ ) { Range r = rangelist . get ( i ) ; Dimension dim = dimset . get ( i ) ; if ( r . stride ( ) != 1 || r . first ( ) != 0 || r . length ( ) != dim . getLength ( ) ) return false ; } return true ; }


Input: NetcdfDataset can wrap a NetcdfFile . Goal of this procedure is to get down to the lowest level NetcdfFile instance . [CODESPLIT] static public NetcdfFile unwrapfile ( NetcdfFile file ) { for ( ; ; ) { if ( file instanceof NetcdfDataset ) { NetcdfDataset ds = ( NetcdfDataset ) file ; file = ds . getReferencedFile ( ) ; if ( file == null ) break ; } else break ; } return file ; }


Input: Test if any dimension is variable length [CODESPLIT] static public boolean containsVLEN ( List < Dimension > dimset ) { if ( dimset == null ) return false ; for ( Dimension dim : dimset ) { if ( dim . isVariableLength ( ) ) return true ; } return false ; }


Input: Compute the shape inferred from a set of slices . Effective means that any trailing vlen will be ignored . [CODESPLIT] static public int [ ] computeEffectiveShape ( List < DapDimension > dimset ) { if ( dimset == null || dimset . size ( ) == 0 ) return new int [ 0 ] ; int effectiverank = dimset . size ( ) ; int [ ] shape = new int [ effectiverank ] ; for ( int i = 0 ; i < effectiverank ; i ++ ) { shape [ i ] = ( int ) dimset . get ( i ) . getSize ( ) ; } return shape ; }


Input: Extract as a long value from a ( presumably ) atomic typed array of values ; dataset position is presumed correct . [CODESPLIT] static public long extractLongValue ( TypeSort atomtype , DataCursor dataset , Index index ) throws DapException { Object result ; result = dataset . read ( index ) ; long lvalue = CDMTypeFcns . extract ( atomtype , result ) ; return lvalue ; }


Input: Extract as a double value from a ( presumably ) atomic typed array of values ; dataset position is presumed correct . [CODESPLIT] static public double extractDoubleValue ( TypeSort atomtype , DataCursor dataset , Index index ) throws DapException { Object result ; result = dataset . read ( index ) ; double dvalue = 0.0 ; if ( atomtype . isIntegerType ( ) || atomtype . isEnumType ( ) ) { long lvalue = extractLongValue ( atomtype , dataset , index ) ; dvalue = ( double ) lvalue ; } else if ( atomtype == TypeSort . Float32 ) { dvalue = ( double ) ( ( Float ) result ) . floatValue ( ) ; } else if ( atomtype == TypeSort . Float64 ) { dvalue = ( ( Double ) result ) . doubleValue ( ) ; } else throw new ForbiddenConversionException ( ) ; return dvalue ; }


Input: Convert an array of one type of values to another type [CODESPLIT] static public Object convertVector ( DapType dsttype , DapType srctype , Object src ) { int i ; TypeSort srcatomtype = srctype . getAtomicType ( ) ; TypeSort dstatomtype = dsttype . getAtomicType ( ) ; if ( srcatomtype == dstatomtype ) { return src ; } if ( srcatomtype . isIntegerType ( ) && TypeSort . getSignedVersion ( srcatomtype ) == TypeSort . getSignedVersion ( dstatomtype ) ) return src ; Object result = CDMTypeFcns . convert ( dstatomtype , srcatomtype , src ) ; if ( result == null ) throw new ForbiddenConversionException ( ) ; return result ; }


Input: / * static public ucar . ma2 . Array arraySlice ( ucar . ma2 . Array array Section section ) throws DapException { Case it out . if ( !dapvar . getBaseType () . isStructType () ) { // = > Atomic type if ( dapvar . isTopLevel () ) { Simplest case : use createview but watch out for final VLEN List<Range > ranges = section . getRanges () ; try { if ( CDMUtil . hasVLEN ( ranges )) return array . section ( ranges . subList ( 0 ranges . size () - 2 )) ; else return array . section ( ranges ) ; } catch ( InvalidRangeException ire ) { throw new DapException ( ire ) ; } } else throw new UnsupportedOperationException () ; // same as other cdm } else { // struct type assert ( array instanceof CDMArrayStructure ) ; CDMArrayStructure struct = ( CDMArrayStructure ) array ; if ( dapvar . isTopLevel () ) { Build a new ArrayStructure containing the relevant instances . int [] shape = section . getShape () ; StructureMembers sm = new StructureMembers ( struct . getStructureMembers () ) ; ArrayStructureMA slice = new ArrayStructureMA ( sm shape ) ; CDMOdometer odom = new CDMOdometer ( dapvar . getDimensions () section . getRanges () ) ; Compute the number of structuredata instances we need long totalsize = section . computeSize () ; List<StructureMembers . Member > mlist = sm . getMembers () ; StructureData [] newdata = new StructureData [ ( int ) totalsize ] ; for ( int i = 0 ; odom . hasNext () ; odom . next () i ++ ) { long recno = odom . index () ; StructureDataW clone = new StructureDataW ( sm ) ; newdata [ i ] = clone ; StructureData record = struct . getStructureData (( int ) recno ) ; for ( int j = 0 ; j < mlist . size () ; j ++ ) { StructureMembers . Member m = mlist . get ( j ) ; clone . setMemberData ( m record . getArray ( m )) ; } } return slice ; } else throw new UnsupportedOperationException () ; // same as other cdm } } [CODESPLIT] static public String getChecksumString ( byte [ ] checksum ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < checksum . length ; i ++ ) { byte b = checksum [ i ] ; buf . append ( hexchars . charAt ( b >> 4 ) ) ; buf . append ( hexchars . charAt ( b & 0xF ) ) ; } return buf . toString ( ) ; }


Input: Convert a Section + variable to a constraint <p > <p > static public View sectionToView ( CDMDSP dsp Variable v Section section ) throws DapException { if ( section == null || section . getRank () == 0 ) return null ; // Get the corresponding DapNode DapVariable dv = ( DapVariable ) dsp . getNode () . get ( v ) ; if ( dv == null ) throw new DapException ( Variable has no corresponding dap node : + v . getFullName () ) ; // Get the structure path wrt DapDataset for dv // and use path plus the Section to construct a constraint List<DapVariable > structpath = DapUtil . getStructurePath ( dv ) ; List<Range > ranges = section . getRanges () ; View view = new View ( dmr ) ; int next = 0 ; for ( int i = 0 ; i < structpath . size () ; i ++ ) { dv = structpath . get ( i ) ; int rank = dv . getRank () ; ViewVariable vv = new ViewVariable ( dv ) ; List<Slice > slices = new ArrayList<Slice > ( rank ) ; for ( int j = 0 ; j < rank ; j ++ next ++ ) { if ( next > = ranges . size () ) throw new DapException ( Range :: Rank mismatch ) ; Range range = ranges . get ( next ) ; Slice slice = new Slice ( range . first () range . last () range . stride () ) . validate () ; slices . add ( slice ) ; } vv . setSlices ( slices ) ; view . put ( dv vv ) ; } view . validate ( View . EXPAND ) ; return view ; } [CODESPLIT] static public List < Range > dimsetToRanges ( List < DapDimension > dimset ) throws dap4 . core . util . DapException { if ( dimset == null ) return null ; List < Range > ranges = new ArrayList <> ( ) ; for ( int i = 0 ; i < dimset . size ( ) ; i ++ ) { DapDimension dim = dimset . get ( i ) ; try { Range r = new Range ( dim . getShortName ( ) , 0 , ( int ) dim . getSize ( ) - 1 , 1 ) ; ranges . add ( r ) ; } catch ( InvalidRangeException ire ) { throw new dap4 . core . util . DapException ( ire ) ; } } return ranges ; }


Input: Convert given value of this unit to the new unit . <em > NOTE : the current value of this unit ignored the given value is used instead . This is different than ucar . units or SimpleUnit . < / em > [CODESPLIT] public double convertTo ( double value , TimeUnit outputUnit ) throws ConversionException { return uu . convertTo ( value , outputUnit . uu ) ; }


Input: Add the time amount to the given Date return a new Date . [CODESPLIT] public Date add ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . SECOND , ( int ) getValueInSeconds ( ) ) ; return cal . getTime ( ) ; }


Input: Multiplies this unit by another unit . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { return that instanceof ScaledUnit ? new ScaledUnit ( getScale ( ) * ( ( ScaledUnit ) that ) . getScale ( ) , getUnit ( ) . multiplyBy ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( getScale ( ) , getUnit ( ) . multiplyBy ( that ) ) ; }


Input: Divides this unit by another unit . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit ( getScale ( ) / ( ( ScaledUnit ) that ) . getScale ( ) , getUnit ( ) . divideBy ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( getScale ( ) , getUnit ( ) . divideBy ( that ) ) ; }


Input: Divides this unit into another unit . [CODESPLIT] @ Override protected Unit myDivideInto ( final Unit that ) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit ( ( ( ScaledUnit ) that ) . getScale ( ) / getScale ( ) , getUnit ( ) . divideInto ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( 1 / getScale ( ) , getUnit ( ) . divideInto ( that ) ) ; }


Input: Raises this unit to a power . [CODESPLIT] @ Override protected Unit myRaiseTo ( final int power ) throws RaiseException { return new ScaledUnit ( Math . pow ( getScale ( ) , power ) , getUnit ( ) . raiseTo ( power ) ) ; }


Input: Converts a numeric value from this unit to the underlying derived unit . [CODESPLIT] public double toDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) _unit ) . toDerivedUnit ( amount * getScale ( ) ) ; }


Input: Converts numeric values from this unit to the underlying derived unit . [CODESPLIT] public float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { final float scale = ( float ) getScale ( ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = input [ i ] * scale ; } if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . toDerivedUnit ( output , output ) ; }


Input: Converts a numeric value from the underlying derived unit to this unit . [CODESPLIT] public double fromDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( amount ) / getScale ( ) ; }


Input: Returns the canonical string representation of the unit . [CODESPLIT] public String getCanonicalString ( ) { return DerivedUnitImpl . DIMENSIONLESS . equals ( _unit ) ? Double . toString ( getScale ( ) ) : Double . toString ( getScale ( ) ) + " " + _unit . toString ( ) ; }


Input: Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final BaseUnit meter = BaseUnit . getOrCreate ( UnitName . newUnitName ( "meter" , null , "m" ) , BaseQuantity . LENGTH ) ; final ScaledUnit nauticalMile = new ScaledUnit ( 1852f , meter ) ; System . out . println ( "nauticalMile.getUnit().equals(meter)=" + nauticalMile . getUnit ( ) . equals ( meter ) ) ; final ScaledUnit nauticalMileMeter = ( ScaledUnit ) nauticalMile . multiplyBy ( meter ) ; System . out . println ( "nauticalMileMeter.divideBy(nauticalMile)=" + nauticalMileMeter . divideBy ( nauticalMile ) ) ; System . out . println ( "meter.divideBy(nauticalMile)=" + meter . divideBy ( nauticalMile ) ) ; System . out . println ( "nauticalMile.raiseTo(2)=" + nauticalMile . raiseTo ( 2 ) ) ; System . out . println ( "nauticalMile.toDerivedUnit(1.)=" + nauticalMile . toDerivedUnit ( 1. ) ) ; System . out . println ( "nauticalMile.toDerivedUnit(new float[]{1,2,3}, new float[3])[1]=" + nauticalMile . toDerivedUnit ( new float [ ] { 1 , 2 , 3 } , new float [ 3 ] ) [ 1 ] ) ; System . out . println ( "nauticalMile.fromDerivedUnit(1852.)=" + nauticalMile . fromDerivedUnit ( 1852. ) ) ; System . out . println ( "nauticalMile.fromDerivedUnit(new float[]{1852},new float[1])[0]=" + nauticalMile . fromDerivedUnit ( new float [ ] { 1852 } , new float [ 1 ] ) [ 0 ] ) ; System . out . println ( "nauticalMile.equals(nauticalMile)=" + nauticalMile . equals ( nauticalMile ) ) ; final ScaledUnit nautical2Mile = new ScaledUnit ( 2 , nauticalMile ) ; System . out . println ( "nauticalMile.equals(nautical2Mile)=" + nauticalMile . equals ( nautical2Mile ) ) ; System . out . println ( "nauticalMile.isDimensionless()=" + nauticalMile . isDimensionless ( ) ) ; final BaseUnit radian = BaseUnit . getOrCreate ( UnitName . newUnitName ( "radian" , null , "rad" ) , BaseQuantity . PLANE_ANGLE ) ; final ScaledUnit degree = new ScaledUnit ( 3.14159 / 180 , radian ) ; System . out . println ( "degree.isDimensionless()=" + degree . isDimensionless ( ) ) ; }


Input: Read the section of data described by want [CODESPLIT] public Array readData ( SectionIterable want ) throws IOException , InvalidRangeException { if ( vindex instanceof PartitionCollectionImmutable . VariableIndexPartitioned ) return readDataFromPartition ( ( PartitionCollectionImmutable . VariableIndexPartitioned ) vindex , want ) ; else return readDataFromCollection ( vindex , want ) ; }


Input: / * SectionIterable iterates over the source indexes corresponding to vindex s SparseArray . IOSP : works because variable coordinate corresponds 1 - 1 to Grib Coordinate . GribCoverage : must translate coordinates to Grib Coordinate index . want . getShape () indicates the result Array shape . SectionIterable . next ( int [] index ) is not used here . [CODESPLIT] private Array readDataFromCollection ( GribCollectionImmutable . VariableIndex vindex , SectionIterable want ) throws IOException { // first time, read records and keep in memory vindex . readRecords ( ) ; int rank = want . getRank ( ) ; int sectionLen = rank - 2 ; // all but x, y SectionIterable sectionWanted = want . subSection ( 0 , sectionLen ) ; // assert sectionLen == vindex.getRank(); LOOK true or false ?? // collect all the records that need to be read int resultIndex = 0 ; for ( int sourceIndex : sectionWanted ) { // addRecord(sourceIndex, count++); GribCollectionImmutable . Record record = vindex . getRecordAt ( sourceIndex ) ; if ( Grib . debugRead ) logger . debug ( "GribIosp debugRead sourceIndex=%d resultIndex=%d record is null=%s%n" , sourceIndex , resultIndex , record == null ) ; if ( record != null ) records . add ( new DataRecord ( resultIndex , record , vindex . group . getGdsHorizCoordSys ( ) ) ) ; resultIndex ++ ; } // sort by file and position, then read DataReceiverIF dataReceiver = new DataReceiver ( want . getShape ( ) , want . getRange ( rank - 2 ) , want . getRange ( rank - 1 ) ) ; read ( dataReceiver ) ; return dataReceiver . getArray ( ) ; }


Input: / * Iterates using SectionIterable . next ( int [] index ) . The work of translating that down into partition heirarchy and finally to a GC is all in VariableIndexPartitioned . getDataRecord ( int [] index ) want . getShape () indicates the result Array shape . [CODESPLIT] private Array readDataFromPartition ( PartitionCollectionImmutable . VariableIndexPartitioned vindexP , SectionIterable section ) throws IOException { int rank = section . getRank ( ) ; SectionIterable sectionWanted = section . subSection ( 0 , rank - 2 ) ; // all but x, y SectionIterable . SectionIterator iterWanted = sectionWanted . getIterator ( ) ; // iterator over wanted indices in vindexP int [ ] indexWanted = new int [ rank - 2 ] ; // place to put the iterator result int [ ] useIndex = indexWanted ; // collect all the records that need to be read int resultPos = 0 ; while ( iterWanted . hasNext ( ) ) { iterWanted . next ( indexWanted ) ; // returns the vindexP index in indexWanted array // for MRUTP, must munge the index here (not in vindexP.getDataRecord, because its recursive if ( vindexP . getType ( ) == GribCollectionImmutable . Type . MRUTP ) { // find the partition from getRuntimeIdxFromMrutpTimeIndex CoordinateTime2D time2D = ( CoordinateTime2D ) vindexP . getCoordinateTime ( ) ; assert time2D != null ; int [ ] timeIndices = time2D . getTimeIndicesFromMrutp ( indexWanted [ 0 ] ) ; int [ ] indexReallyWanted = new int [ indexWanted . length + 1 ] ; indexReallyWanted [ 0 ] = timeIndices [ 0 ] ; indexReallyWanted [ 1 ] = timeIndices [ 1 ] ; System . arraycopy ( indexWanted , 1 , indexReallyWanted , 2 , indexWanted . length - 1 ) ; useIndex = indexReallyWanted ; } PartitionCollectionImmutable . DataRecord record = vindexP . getDataRecord ( useIndex ) ; if ( record == null ) { if ( Grib . debugRead ) logger . debug ( "readDataFromPartition missing data%n" ) ; resultPos ++ ; // can just skip, since result is prefilled with NaNs continue ; } record . resultIndex = resultPos ; records . add ( record ) ; resultPos ++ ; } // sort by file and position, then read DataReceiverIF dataReceiver = new DataReceiver ( section . getShape ( ) , section . getRange ( rank - 2 ) , section . getRange ( rank - 1 ) ) ; readPartitioned ( dataReceiver ) ; return dataReceiver . getArray ( ) ; }


Input: Coordinate based subsetting for Coverage [CODESPLIT] public Array readData2 ( CoordsSet want , RangeIterator yRange , RangeIterator xRange ) throws IOException { if ( vindex instanceof PartitionCollectionImmutable . VariableIndexPartitioned ) return readDataFromPartition2 ( ( PartitionCollectionImmutable . VariableIndexPartitioned ) vindex , want , yRange , xRange ) ; else return readDataFromCollection2 ( vindex , want , yRange , xRange ) ; }


Input: Read all of the data records that have been added . The full ( x y ) record is read the reciever will subset the ( x y ) as needed . [CODESPLIT] private void read ( DataReceiverIF dataReceiver ) throws IOException { Collections . sort ( records ) ; int currFile = - 1 ; RandomAccessFile rafData = null ; try { for ( DataRecord dr : records ) { if ( Grib . debugIndexOnly || Grib . debugGbxIndexOnly ) { GribIosp . debugIndexOnlyCount ++ ; currentDataRecord = dr . record ; currentDataRafFilename = gribCollection . getDataRafFilename ( dr . record . fileno ) ; if ( Grib . debugIndexOnlyShow ) dr . show ( gribCollection ) ; dataReceiver . setDataToZero ( ) ; continue ; } if ( dr . record . fileno != currFile ) { if ( rafData != null ) rafData . close ( ) ; rafData = gribCollection . getDataRaf ( dr . record . fileno ) ; currFile = dr . record . fileno ; } if ( dr . record . pos == GribCollectionMutable . MISSING_RECORD ) continue ; if ( GribDataReader . validator != null && dr . validation != null && rafData != null ) { GribDataReader . validator . validate ( gribCollection . cust , rafData , dr . record . pos + dr . record . drsOffset , dr . validation ) ; } else if ( show && rafData != null ) { // for validation show ( dr . validation ) ; show ( rafData , dr . record . pos + dr . record . drsOffset ) ; } float [ ] data = readData ( rafData , dr ) ; GdsHorizCoordSys hcs = vindex . group . getGdsHorizCoordSys ( ) ; dataReceiver . addData ( data , dr . resultIndex , hcs . nx ) ; } } finally { if ( rafData != null ) rafData . close ( ) ; // make sure its closed even on exception } }


Input: Double - check idiom for lazy initialization of instance fields . See Effective Java 2nd Ed p . 283 . [CODESPLIT] protected StationHelper getStationHelper ( ) { if ( stationHelper == null ) { synchronized ( this ) { if ( stationHelper == null ) { try { stationHelper = createStationHelper ( ) ; } catch ( IOException e ) { // The methods that will call getStationHelper() aren't declared to throw IOException, so we must // wrap it in an unchecked exception. throw new RuntimeException ( e ) ; } } } } assert stationHelper != null : "stationHelper is null for StationTimeSeriesCollectionImpl" + getName ( ) ; return stationHelper ; }


Input: subset [CODESPLIT] @ Override public StationTimeSeriesFeatureCollection subset ( ucar . unidata . geoloc . LatLonRect boundingBox ) throws IOException { return subset ( getStationFeatures ( boundingBox ) ) ; }


Input: might need to override for efficiency [CODESPLIT] @ Override public PointFeatureCollection flatten ( List < String > stationNames , CalendarDateRange dateRange , List < VariableSimpleIF > varList ) throws IOException { if ( ( stationNames == null ) || ( stationNames . size ( ) == 0 ) ) return new StationTimeSeriesCollectionFlattened ( this , dateRange ) ; List < StationFeature > subsetStations = getStationHelper ( ) . getStationFeaturesFromNames ( stationNames ) ; return new StationTimeSeriesCollectionFlattened ( new StationSubset ( this , subsetStations ) , dateRange ) ; }


Input: Find the named service declared in the top level of this catalog . [CODESPLIT] public InvService findService ( String name ) { if ( name == null ) return null ; for ( InvService s : services ) { if ( name . equals ( s . getName ( ) ) ) return s ; // look for nested servers if ( s . getServiceType ( ) == ServiceType . COMPOUND ) { InvService result = s . findNestedService ( name ) ; if ( result != null ) return result ; } } return null ; }


Input: Resolve reletive URIs using the catalog s base URI . If the uriString is not reletive then no resolution is done . This also allows baseURI to be a file : scheme . [CODESPLIT] public URI resolveUri ( String uriString ) throws URISyntaxException { URI want = new URI ( uriString ) ; if ( ( baseURI == null ) || want . isAbsolute ( ) ) return want ; // gotta deal with file ourself String scheme = baseURI . getScheme ( ) ; if ( ( scheme != null ) && scheme . equals ( "file" ) ) { // LOOK at ucar.nc2.util.NetworkUtils.resolve String baseString = baseURI . toString ( ) ; if ( ( uriString . length ( ) > 0 ) && ( uriString . charAt ( 0 ) == ' ' ) ) return new URI ( baseString + uriString ) ; int pos = baseString . lastIndexOf ( ' ' ) ; if ( pos > 0 ) { String r = baseString . substring ( 0 , pos + 1 ) + uriString ; return new URI ( r ) ; } } //otherwise let the URI class resolve it return baseURI . resolve ( want ) ; }


Input: Retrieve String value ; only call if isString () is true . [CODESPLIT] public String getStringValue ( ) { if ( valueS == null ) { StringBuilder sbuff = new StringBuilder ( ) ; for ( double v : valueD ) { sbuff . append ( v ) . append ( " " ) ; } valueS = sbuff . toString ( ) ; } return valueS ; }


Input: This method returns the gate size in meters [CODESPLIT] public int getGateSize ( int datatype ) { switch ( datatype ) { case REFLECTIVITY : return ( ( int ) reflect_gate_size ) ; case VELOCITY_HI : case VELOCITY_LOW : case SPECTRUM_WIDTH : return ( ( int ) doppler_gate_size ) ; //high resolution case REFLECTIVITY_HIGH : return ( ( int ) reflectHR_gate_size ) ; case VELOCITY_HIGH : return ( ( int ) velocityHR_gate_size ) ; case SPECTRUM_WIDTH_HIGH : return ( ( int ) spectrumHR_gate_size ) ; case DIFF_REFLECTIVITY_HIGH : return ( ( int ) zdrHR_gate_size ) ; case DIFF_PHASE : return ( ( int ) phiHR_gate_size ) ; case CORRELATION_COEFFICIENT : return ( ( int ) rhoHR_gate_size ) ; } return - 1 ; }


Input: This method returns the starting gate in meters [CODESPLIT] public int getGateStart ( int datatype ) { switch ( datatype ) { case REFLECTIVITY : return ( ( int ) reflect_first_gate ) ; case VELOCITY_HI : case VELOCITY_LOW : case SPECTRUM_WIDTH : return ( ( int ) doppler_first_gate ) ; //high resolution case REFLECTIVITY_HIGH : return ( ( int ) reflectHR_first_gate ) ; case VELOCITY_HIGH : return ( ( int ) velocityHR_first_gate ) ; case SPECTRUM_WIDTH_HIGH : return ( ( int ) spectrumHR_first_gate ) ; case DIFF_REFLECTIVITY_HIGH : return ( ( int ) zdrHR_first_gate ) ; case DIFF_PHASE : return ( ( int ) phiHR_first_gate ) ; case CORRELATION_COEFFICIENT : return ( ( int ) rhoHR_first_gate ) ; } return - 1 ; }


Input: This method returns the number of gates [CODESPLIT] public int getGateCount ( int datatype ) { switch ( datatype ) { case REFLECTIVITY : return ( ( int ) reflect_gate_count ) ; case VELOCITY_HI : case VELOCITY_LOW : case SPECTRUM_WIDTH : return ( ( int ) doppler_gate_count ) ; // hight resolution case REFLECTIVITY_HIGH : return ( ( int ) reflectHR_gate_count ) ; case VELOCITY_HIGH : return ( ( int ) velocityHR_gate_count ) ; case SPECTRUM_WIDTH_HIGH : return ( ( int ) spectrumHR_gate_count ) ; case DIFF_REFLECTIVITY_HIGH : return ( ( int ) zdrHR_gate_count ) ; case DIFF_PHASE : return ( ( int ) phiHR_gate_count ) ; case CORRELATION_COEFFICIENT : return ( ( int ) rhoHR_gate_count ) ; } return 0 ; }


Input: Read data from this record . [CODESPLIT] public void readData ( RandomAccessFile raf , int datatype , Range gateRange , IndexIterator ii ) throws IOException { long offset = message_offset ; offset += MESSAGE_HEADER_SIZE ; // offset is from "start of digital radar data message header" offset += getDataOffset ( datatype ) ; raf . seek ( offset ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "  read recno " + recno + " at offset " + offset + " count= " + getGateCount ( datatype ) ) ; logger . debug ( "   offset: reflect= " + reflect_offset + " velocity= " + velocity_offset + " spWidth= " + spectWidth_offset ) ; } int dataCount = getGateCount ( datatype ) ; if ( datatype == DIFF_PHASE ) { short [ ] data = new short [ dataCount ] ; raf . readShort ( data , 0 , dataCount ) ; for ( int gateIdx : gateRange ) { if ( gateIdx >= dataCount ) ii . setShortNext ( MISSING_DATA ) ; else ii . setShortNext ( data [ gateIdx ] ) ; } } else { byte [ ] data = new byte [ dataCount ] ; raf . readFully ( data ) ; //short [] ds = convertunsignedByte2Short(data); for ( int gateIdx : gateRange ) { if ( gateIdx >= dataCount ) ii . setByteNext ( MISSING_DATA ) ; else ii . setByteNext ( data [ gateIdx ] ) ; } } }


Input: Instances which have same content are equal . <p / > public boolean equals ( Object oo ) { if ( this == oo ) return true ; if ( ! ( oo instanceof Level2Record )) return false ; return hashCode () == oo . hashCode () ; } <p / > / ** Override Object . hashCode () to implement equals . * public int hashCode () { if ( hashCode == 0 ) { int result = 17 ; result = 37 * result + elevation_num ; // result = 37 * result + cut ; // result = 37 * result + datatype ; hashCode = result ; } return hashCode ; } private volatile int hashCode = 0 ; [CODESPLIT] public short [ ] convertunsignedByte2Short ( byte [ ] inb ) { int len = inb . length ; short [ ] outs = new short [ len ] ; int i = 0 ; for ( byte b : inb ) { outs [ i ++ ] = convertunsignedByte2Short ( b ) ; } return outs ; }


Input:
Write a NetcdfDataset as an NcML - G document to the specified stream . [CODESPLIT] public void writeXML ( NetcdfDataset ncd , OutputStream os , boolean showCoords , String uri ) throws IOException { // Output the document, use standard formatter
 //XMLOutputter fmt = new XMLOutputter("  ", true);
 //fmt.setLineSeparator("\n");
 XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; fmt . output ( makeDocument ( ncd , showCoords , uri ) , os ) ; }


Input:
/ * private Element makeReferenceSys ( ReferenceSystem referenceSystem ) { Element elem = new Element ( referenceCoordinateSystem thredds . client . catalog . Catalog . ncmlNS ) ; elem . setAttribute ( name referenceSystem . getName () ) ; elem . setAttribute ( authority referenceSystem . getAuthority () ) ; if ( referenceSystem . getReferenceType () ! = null ) elem . setAttribute ( type referenceSystem . getReferenceType () . toString () ) ; [CODESPLIT] private Element makeVariable ( VariableDS var ) { Element varElem = new Element ( "variable" , thredds . client . catalog . Catalog . ncmlNS ) ; varElem . setAttribute ( "name" , var . getFullName ( ) ) ; StringBuffer buff = new StringBuffer ( ) ; List dims = var . getDimensions ( ) ; for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { Dimension dim = ( Dimension ) dims . get ( i ) ; if ( i > 0 ) buff . append ( " " ) ; buff . append ( dim . getShortName ( ) ) ; } if ( buff . length ( ) > 0 ) varElem . setAttribute ( "shape" , buff . toString ( ) ) ; DataType dt = var . getDataType ( ) ; if ( dt != null ) varElem . setAttribute ( "type" , dt . toString ( ) ) ; // attributes
 for ( Attribute att : var . getAttributes ( ) ) { varElem . addContent ( makeAttribute ( att , "attribute" ) ) ; } if ( var . isMetadata ( ) ) varElem . addContent ( makeValues ( var ) ) ; // coordinate systems
 List csys = var . getCoordinateSystems ( ) ; if ( csys . size ( ) > 0 ) { buff . setLength ( 0 ) ; for ( int i = 0 ; i < csys . size ( ) ; i ++ ) { CoordinateSystem cs = ( CoordinateSystem ) csys . get ( i ) ; if ( i > 0 ) buff . append ( " " ) ; buff . append ( cs . getName ( ) ) ; } varElem . setAttribute ( "coordinateSystems" , buff . toString ( ) ) ; } return varElem ; }


Input: ///////////////////////////// [CODESPLIT] public SubsetParams makeSubset ( ) { SubsetParams subset = new SubsetParams ( ) ; // vars subset . set ( SubsetParams . variables , var ) ; // horiz if ( stns != null ) subset . set ( SubsetParams . stations , stns ) ; else if ( hasLatLonBB ( ) ) subset . set ( SubsetParams . latlonBB , getLatLonBoundingBox ( ) ) ; else if ( hasLatLonPoint ( ) ) subset . set ( SubsetParams . latlonPoint , new LatLonPointImpl ( getLatitude ( ) , getLongitude ( ) ) ) ; // time CalendarDate date = getRequestedDate ( Calendar . getDefault ( ) ) ; CalendarDateRange dateRange = getCalendarDateRange ( Calendar . getDefault ( ) ) ; if ( isAllTimes ( ) ) { subset . set ( SubsetParams . timeAll , true ) ; } else if ( date != null ) { subset . set ( SubsetParams . time , date ) ; } else if ( dateRange != null ) { subset . set ( SubsetParams . timeRange , dateRange ) ; } else { subset . set ( SubsetParams . timePresent , true ) ; } if ( timeWindow != null ) { CalendarPeriod period = CalendarPeriod . of ( timeWindow ) ; subset . set ( SubsetParams . timeWindow , period ) ; } return subset ; }


Input: deal with having components on more than one line [CODESPLIT] public Dimension preferredLayoutSize ( Container target ) { synchronized ( target . getTreeLock ( ) ) { Dimension dim = new Dimension ( 0 , 0 ) ; for ( int i = 0 ; i < target . getComponentCount ( ) ; i ++ ) { Component m = target . getComponent ( i ) ; if ( m . isVisible ( ) ) { Dimension d = m . getPreferredSize ( ) ; // original // dim.height = Math.max(dim.height, d.height); //if (i > 0) { dim.width += hgap; } // dim.width += d.width; // new  way Point p = m . getLocation ( ) ; dim . width = Math . max ( dim . width , p . x + d . width ) ; dim . height = Math . max ( dim . height , p . y + d . height ) ; } } Insets insets = target . getInsets ( ) ; dim . width += insets . left + insets . right + getHgap ( ) * 2 ; dim . height += insets . top + insets . bottom + getVgap ( ) * 2 ; return dim ; } }


Input: Return the requested dataset if it is the ancestor dataset or an allowed descendant of the ancestor dataset otherwise return null . The given filter determines whether a dataset is allowed or not . [CODESPLIT] static CrawlableDataset verifyDescendantDataset ( CrawlableDataset ancestorCrDs , String path , CrawlableDatasetFilter filter ) { // Make sure requested path is descendant of ancestor dataset. if ( ! ancestorCrDs . isCollection ( ) ) throw new IllegalArgumentException ( "Ancestor dataset <" + ancestorCrDs . getPath ( ) + "> not a collection." ) ; if ( ! path . startsWith ( ancestorCrDs . getPath ( ) ) ) throw new IllegalArgumentException ( "Dataset path <" + path + "> not descendant of given dataset <" + ancestorCrDs . getPath ( ) + ">." ) ; // If path and ancestor are the same, return ancestor. if ( path . length ( ) == ancestorCrDs . getPath ( ) . length ( ) ) return ancestorCrDs ; // Crawl into the dataset collection through each level of the given path // checking that each level is accepted by the given CrawlableDatasetFilter. String remainingPath = path . substring ( ancestorCrDs . getPath ( ) . length ( ) ) ; if ( remainingPath . startsWith ( "/" ) ) remainingPath = remainingPath . substring ( 1 ) ; String [ ] pathSegments = remainingPath . split ( "/" ) ; CrawlableDataset curCrDs = ancestorCrDs ; for ( int i = 0 ; i < pathSegments . length ; i ++ ) { curCrDs = curCrDs . getDescendant ( pathSegments [ i ] ) ; if ( filter != null ) if ( ! filter . accept ( curCrDs ) ) return null ; } // Only check complete path for existence since speed of check depends on implementation. if ( ! curCrDs . exists ( ) ) return null ; return curCrDs ; }


Input:
Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array psArray = readArray ( psVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; //p0 = (p0Var == null) ? 1.0 : p0Var.readScalarDouble();
 p0 = computeP0 ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; // it's possible to have rank 3 because pressure can have a level, usually 1
 // Check if rank 3 and try to reduce
 if ( psArray . getRank ( ) == 3 ) psArray = psArray . reduce ( 0 ) ; int [ ] shape2D = psArray . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index psIndex = psArray . getIndex ( ) ; ArrayDouble . D3 press = new ArrayDouble . D3 ( nz , ny , nx ) ; double ps ; for ( int z = 0 ; z < nz ; z ++ ) { double term1 = aArray . getDouble ( aIndex . set ( z ) ) * p0 ; //AP might need unit conversion
 if ( ! apUnits . equals ( units ) ) { term1 = convertPressureToPSUnits ( apUnits , term1 ) ; } double bz = bArray . getDouble ( bIndex . set ( z ) ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { ps = psArray . getDouble ( psIndex . set ( y , x ) ) ; press . set ( z , y , x , term1 + bz * ps ) ; } } } return press ; }


Input:
Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array psArray = readArray ( psVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; //p0 = (p0Var == null) ? 1.0 : p0Var.readScalarDouble();
 p0 = computeP0 ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; // it's possible to have rank 3 because pressure can have a level, usually 1
 // Check if rank 3 and try to reduce
 if ( psArray . getRank ( ) == 3 ) psArray = psArray . reduce ( 0 ) ; Index psIndex = psArray . getIndex ( ) ; ArrayDouble . D1 press = new ArrayDouble . D1 ( nz ) ; double ps ; for ( int z = 0 ; z < nz ; z ++ ) { double term1 = aArray . getDouble ( aIndex . set ( z ) ) * p0 ; //AP might need unit conversion
 if ( ! apUnits . equals ( units ) ) { term1 = convertPressureToPSUnits ( apUnits , term1 ) ; } double bz = bArray . getDouble ( bIndex . set ( z ) ) ; ps = psArray . getDouble ( psIndex . set ( yIndex , xIndex ) ) ; press . set ( z , term1 + bz * ps ) ; } return press ; }


Input: Create a ProjectionRect from the given LatLonRect . Handles lat / lon points that do not intersect the projection panel . [CODESPLIT] @ Override public ProjectionRect latLonToProjBB ( LatLonRect rect ) { BoundingBoxHelper bbhelper = new BoundingBoxHelper ( this , maxR ) ; return bbhelper . latLonToProjBB ( rect ) ; }


Input: //////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static void tryit ( double want , double x ) { System . out . printf ( "x = %f %f %f %n" , x , x / want , want / x ) ; }