Input: Create a subset of this VerticalTransform . [CODESPLIT] public VerticalTransform subset ( Range t_range , Range z_range , Range y_range , Range x_range ) throws ucar . ma2 . InvalidRangeException { return new VerticalTransformSubset ( this , t_range , z_range , y_range , x_range ) ; }


Input:
current version [CODESPLIT] public static GridDatasetInv open ( MCollection cm , MFile mfile , Element ncml ) throws IOException { // do we already have it ?
 byte [ ] xmlBytes = ( ( CollectionManagerAbstract ) cm ) . getMetadata ( mfile , "fmrInv.xml" ) ; // LOOK should we keep this functionality ??
 if ( xmlBytes != null ) { if ( logger . isDebugEnabled ( ) ) logger . debug ( " got xmlFile in cache =" + mfile . getPath ( ) + " size = " + xmlBytes . length ) ; if ( xmlBytes . length < 300 ) { logger . warn ( " xmlFile in cache only has nbytes =" + xmlBytes . length + "; will reread" ) ; // drop through and regenerate
 } else { GridDatasetInv inv = readXML ( xmlBytes ) ; // check if version required regen
 if ( inv . version >= REQ_VERSION ) { // check if file has changed
 long fileModifiedSecs = mfile . getLastModified ( ) / 1000 ; // ignore msecs
 long xmlModifiedSecs = inv . getLastModified ( ) / 1000 ; // ignore msecs
 if ( xmlModifiedSecs >= fileModifiedSecs ) { // LOOK if fileDate is -1, will always succeed
 if ( logger . isDebugEnabled ( ) ) logger . debug ( " cache ok " + new Date ( inv . getLastModified ( ) ) + " >= " + new Date ( mfile . getLastModified ( ) ) + " for " + mfile . getName ( ) ) ; return inv ; // ok, use it
 } else { if ( logger . isInfoEnabled ( ) ) logger . info ( " cache out of date " + new Date ( inv . getLastModified ( ) ) + " < " + new Date ( mfile . getLastModified ( ) ) + " for " + mfile . getName ( ) ) ; } } else { if ( logger . isInfoEnabled ( ) ) logger . info ( " version needs upgrade " + inv . version + " < " + REQ_VERSION + " for " + mfile . getName ( ) ) ; } } } // generate it and save it
 GridDataset gds = null ; try { if ( ncml == null ) { gds = GridDataset . open ( mfile . getPath ( ) ) ; } else { NetcdfFile nc = NetcdfDataset . acquireFile ( new DatasetUrl ( null , mfile . getPath ( ) ) , null ) ; NetcdfDataset ncd = NcMLReader . mergeNcML ( nc , ncml ) ; // create new dataset
 ncd . enhance ( ) ; // now that the ncml is added, enhance "in place", ie modify the NetcdfDataset
 gds = new GridDataset ( ncd ) ; } // System.out.println("gds dataset= "+ gds.getNetcdfDataset());
 GridDatasetInv inv = new GridDatasetInv ( gds , cm . extractDate ( mfile ) ) ; String xmlString = inv . writeXML ( new Date ( mfile . getLastModified ( ) ) ) ; ( ( CollectionManagerAbstract ) cm ) . putMetadata ( mfile , "fmrInv.xml" , xmlString . getBytes ( CDM . utf8Charset ) ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( " added xmlFile " + mfile . getPath ( ) + ".fmrInv.xml to cache" ) ; if ( debug ) System . out . printf ( " added xmlFile %s.fmrInv.xml to cache%n" , mfile . getPath ( ) ) ; // System.out.println("new xmlBytes= "+ xmlString);
 return inv ; } finally { if ( gds != null ) gds . close ( ) ; } }


Input:
/////////////////////////////////////////////////////////////////////// [CODESPLIT] private TimeCoord getTimeCoordinate ( CoordinateAxis1DTime axis ) { // check for same axis
 for ( TimeCoord tc : times ) { if ( tc . getAxisName ( ) . equals ( axis . getFullName ( ) ) ) return tc ; } // check for same offsets
 TimeCoord want = new TimeCoord ( runDate , axis ) ; for ( TimeCoord tc : times ) { if ( ( tc . equalsData ( want ) ) ) return tc ; } // its a new one
 times . add ( want ) ; return want ; }


Input: //////////////////////////////////////////////////// [CODESPLIT] private VertCoord getVertCoordinate ( int wantId ) { if ( wantId < 0 ) return null ; for ( VertCoord vc : vaxes ) { if ( vc . getId ( ) == wantId ) return vc ; } return null ; }


Input: //////////////////////////////////////////////////// [CODESPLIT] private EnsCoord getEnsCoordinate ( int ens_id ) { if ( ens_id < 0 ) return null ; for ( EnsCoord ec : eaxes ) { if ( ( ec . getId ( ) == ens_id ) ) return ec ; } return null ; }


Input: Write the XML representation to a String . [CODESPLIT] public String writeXML ( Date lastModified ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( writeDocument ( lastModified ) ) ; }


Input:
Create the XML representation of the GridDatasetInv [CODESPLIT] Document writeDocument ( Date lastModified ) { Element rootElem = new Element ( "gridInventory" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( "location" , location ) ; rootElem . setAttribute ( "runTime" , runTimeString ) ; if ( lastModified != null ) { rootElem . setAttribute ( "lastModified" , CalendarDateFormatter . toDateTimeString ( lastModified ) ) ; } rootElem . setAttribute ( "version" , Integer . toString ( CURR_VERSION ) ) ; // list all the vertical coords
 Collections . sort ( vaxes ) ; int count = 0 ; for ( VertCoord vc : vaxes ) { vc . setId ( count ++ ) ; Element vcElem = new Element ( "vertCoord" ) ; rootElem . addContent ( vcElem ) ; vcElem . setAttribute ( "id" , Integer . toString ( vc . getId ( ) ) ) ; vcElem . setAttribute ( "name" , vc . getName ( ) ) ; if ( vc . getUnits ( ) != null ) vcElem . setAttribute ( CDM . UNITS , vc . getUnits ( ) ) ; StringBuilder sbuff = new StringBuilder ( ) ; double [ ] values1 = vc . getValues1 ( ) ; double [ ] values2 = vc . getValues2 ( ) ; for ( int j = 0 ; j < values1 . length ; j ++ ) { if ( j > 0 ) sbuff . append ( " " ) ; sbuff . append ( Double . toString ( values1 [ j ] ) ) ; if ( values2 != null ) { sbuff . append ( "," ) ; sbuff . append ( Double . toString ( values2 [ j ] ) ) ; } } vcElem . addContent ( sbuff . toString ( ) ) ; } // list all the time coords
 count = 0 ; for ( TimeCoord tc : times ) { tc . setId ( count ++ ) ; Element timeElement = new Element ( "timeCoord" ) ; rootElem . addContent ( timeElement ) ; timeElement . setAttribute ( "id" , Integer . toString ( tc . getId ( ) ) ) ; timeElement . setAttribute ( "name" , tc . getName ( ) ) ; timeElement . setAttribute ( "isInterval" , tc . isInterval ( ) ? "true" : "false" ) ; Formatter sbuff = new Formatter ( ) ; if ( tc . isInterval ( ) ) { double [ ] bound1 = tc . getBound1 ( ) ; double [ ] bound2 = tc . getBound2 ( ) ; for ( int j = 0 ; j < bound1 . length ; j ++ ) sbuff . format ( ( Locale ) null , "%f %f," , bound1 [ j ] , bound2 [ j ] ) ; } else { for ( double offset : tc . getOffsetTimes ( ) ) sbuff . format ( ( Locale ) null , " % , " , offset ) ; } timeElement . addContent ( sbuff . toString ( ) ) ; List < GridDatasetInv . Grid > vars = tc . getGridInventory ( ) ; Collections . sort ( vars ) ; for ( Grid grid : vars ) { Element varElem = new Element ( "grid" ) ; timeElement . addContent ( varElem ) ; varElem . setAttribute ( "name" , grid . name ) ; if ( grid . ec != null ) varElem . setAttribute ( "ens_id" , Integer . toString ( grid . ec . getId ( ) ) ) ; if ( grid . vc != null ) varElem . setAttribute ( "vert_id" , Integer . toString ( grid . vc . getId ( ) ) ) ; } } return doc ; }


Input:
Construct a GridDatasetInv from its XML representation [CODESPLIT] private static GridDatasetInv readXML ( byte [ ] xmlString ) throws IOException { InputStream is = new BufferedInputStream ( new ByteArrayInputStream ( xmlString ) ) ; org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( is ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) + " reading from XML " ) ; } Element rootElem = doc . getRootElement ( ) ; GridDatasetInv fmr = new GridDatasetInv ( ) ; fmr . runTimeString = rootElem . getAttributeValue ( "runTime" ) ; fmr . location = rootElem . getAttributeValue ( "location" ) ; if ( fmr . location == null ) fmr . location = rootElem . getAttributeValue ( "name" ) ; // old way
 String lastModifiedS = rootElem . getAttributeValue ( "lastModified" ) ; if ( lastModifiedS != null ) fmr . lastModified = CalendarDateFormatter . isoStringToDate ( lastModifiedS ) ; String version = rootElem . getAttributeValue ( "version" ) ; fmr . version = ( version == null ) ? 0 : Integer . parseInt ( version ) ; if ( fmr . version < REQ_VERSION ) return fmr ; fmr . runDate = DateUnit . parseCalendarDate ( fmr . runTimeString ) ; java . util . List < Element > vList = rootElem . getChildren ( "vertCoord" ) ; for ( Element vertElem : vList ) { VertCoord vc = new VertCoord ( ) ; fmr . vaxes . add ( vc ) ; vc . setId ( Integer . parseInt ( vertElem . getAttributeValue ( "id" ) ) ) ; vc . setName ( vertElem . getAttributeValue ( "name" ) ) ; vc . setUnits ( vertElem . getAttributeValue ( CDM . UNITS ) ) ; // parse the values
 String values = vertElem . getTextNormalize ( ) ; StringTokenizer stoke = new StringTokenizer ( values ) ; int n = stoke . countTokens ( ) ; double [ ] values1 = new double [ n ] ; double [ ] values2 = null ; int count = 0 ; while ( stoke . hasMoreTokens ( ) ) { String toke = stoke . nextToken ( ) ; int pos = toke . indexOf ( ' ' ) ; if ( pos < 0 ) values1 [ count ] = Double . parseDouble ( toke ) ; else { if ( values2 == null ) values2 = new double [ n ] ; String val1 = toke . substring ( 0 , pos ) ; String val2 = toke . substring ( pos + 1 ) ; values1 [ count ] = Double . parseDouble ( val1 ) ; values2 [ count ] = Double . parseDouble ( val2 ) ; } count ++ ; } vc . setValues1 ( values1 ) ; vc . setValues2 ( values2 ) ; } java . util . List < Element > tList = rootElem . getChildren ( "timeCoord" ) ; for ( Element timeElem : tList ) { TimeCoord tc = new TimeCoord ( fmr . runDate ) ; fmr . times . add ( tc ) ; tc . setId ( Integer . parseInt ( timeElem . getAttributeValue ( "id" ) ) ) ; String s = timeElem . getAttributeValue ( "isInterval" ) ; boolean isInterval = ( s != null ) && ( s . equals ( "true" ) ) ; if ( isInterval ) { String boundsAll = timeElem . getTextNormalize ( ) ; String [ ] bounds = boundsAll . split ( "," ) ; int n = bounds . length ; double [ ] bound1 = new double [ n ] ; double [ ] bound2 = new double [ n ] ; int count = 0 ; for ( String b : bounds ) { String [ ] value = b . split ( " " ) ; bound1 [ count ] = Double . parseDouble ( value [ 0 ] ) ; bound2 [ count ] = Double . parseDouble ( value [ 1 ] ) ; count ++ ; } tc . setBounds ( bound1 , bound2 ) ; } else { String values = timeElem . getTextNormalize ( ) ; String [ ] value = values . split ( "," ) ; int n = value . length ; double [ ] offsets = new double [ n ] ; int count = 0 ; for ( String v : value ) offsets [ count ++ ] = Double . parseDouble ( v ) ; tc . setOffsetTimes ( offsets ) ; } //get the variable names
 List < Element > varList = timeElem . getChildren ( "grid" ) ; for ( Element vElem : varList ) { Grid grid = fmr . makeGrid ( vElem . getAttributeValue ( "name" ) ) ; if ( vElem . getAttributeValue ( "ens_id" ) != null ) grid . ec = fmr . getEnsCoordinate ( Integer . parseInt ( vElem . getAttributeValue ( "ens_id" ) ) ) ; if ( vElem . getAttributeValue ( "vert_id" ) != null ) grid . vc = fmr . getVertCoordinate ( Integer . parseInt ( vElem . getAttributeValue ( "vert_id" ) ) ) ; tc . addGridInventory ( grid ) ; grid . tc = tc ; } } return fmr ; }


Input: / * Reset the lexer [CODESPLIT] public void reset ( Dap2Parse state ) { this . parsestate = state ; this . text = new TextStream ( ) ; yytext = new StringBuilder ( ) ; lval = null ; }


Input: Entry point for the scanner . Returns the token identifier corresponding to the next token and prepares to return the semantic value of the token . [CODESPLIT] public int yylex ( ) throws ParseException { int token ; int c ; token = 0 ; yytext . setLength ( 0 ) ; text . mark ( ) ; try { token = - 1 ; while ( token < 0 && ( c = text . read ( ) ) > 0 ) { if ( c == ' ' ) { lineno ++ ; } else if ( c <= ' ' || c == ' ' ) { /* whitespace: ignore */ } else if ( c == ' ' ) { /* single line comment */ for ( ; ; ) { c = text . read ( ) ; if ( c == ' ' || c == ' ' ) break ; } } else if ( worddelims . indexOf ( c ) >= 0 ) { token = c ; } else if ( c == ' ' ) { boolean more = true ; /* We have a string token; will be reported as SCAN_WORD */ while ( more && ( c = text . read ( ) ) > 0 ) { if ( DAP2STRING ) { /* Implement DAP2 standard */ switch ( c ) { case ' ' : more = false ; break ; case ' ' : c = text . read ( ) ; if ( c < 0 ) more = false ; break ; case ' ' : default : break ; } } else { // not used : Implement a more java/c like alternative for string encoding switch ( c ) { case ' ' : more = false ; break ; case ' ' : c = text . read ( ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : { int d1 , d2 ; c = text . read ( ) ; d1 = tohex ( c ) ; if ( d1 < 0 ) { throw new ParseException ( "Illegal \\xDD in TOKEN_STRING" ) ; } else { c = text . read ( ) ; d2 = tohex ( c ) ; if ( d2 < 0 ) { throw new ParseException ( "Illegal \\xDD in TOKEN_STRING" ) ; } else { c = ( ( d1 ) << 4 ) | d2 ; } } } break ; default : break ; } break ; default : break ; } } if ( more ) yytext . append ( ( char ) c ) ; } token = WORD_STRING ; } else if ( wordchars1 . indexOf ( c ) >= 0 ) { yytext . append ( ( char ) c ) ; /* we have a SCAN_WORD (== identifier | number) */ while ( ( c = text . read ( ) ) > 0 ) { if ( wordcharsn . indexOf ( c ) < 0 ) { text . backup ( ) ; break ; } yytext . append ( ( char ) c ) ; } token = WORD_WORD ; /* assume */ /* check for keyword */ String tmp = yytext . toString ( ) ; for ( int i = 0 ; ; i ++ ) { if ( keywords [ i ] == null ) break ; if ( keywords [ i ] . equalsIgnoreCase ( tmp ) ) { token = keytokens [ i ] ; break ; } } } else { /* illegal */ String msg = String . format ( "Illegal Character: '%c'" , c ) ; yytext . append ( ( char ) c ) ; lexerror ( msg ) ; throw new ParseException ( msg ) ; } } // do eof check if ( token <= 0 ) { token = 0 ; lval = null ; } else { lval = ( yytext . length ( ) == 0 ? ( String ) null : yytext . toString ( ) ) ; } if ( parsestate . getDebugLevel ( ) > 0 ) dumptoken ( token , ( String ) lval ) ; return token ; /* Return the type of the token.  */ } catch ( IOException ioe ) { throw new ParseException ( ioe ) ; } }


Input: Entry point for error reporting . Emits an error in a user - defined way . [CODESPLIT] public void yyerror ( String s ) { String kind = "?" ; switch ( parsestate . parseClass ) { case Dap2Parse . DapDAS : kind = "DAS" ; break ; case Dap2Parse . DapDDS : kind = "DDS" ; break ; case Dap2Parse . DapERR : kind = "Error" ; break ; default : kind = "?" ; break ; } System . err . println ( "yyerror: " + s + "; " + kind + " parse failed at line: " + lineno + " char: " + charno + "; near: " ) ; String context = parsestate . flatten ( getInput ( ) ) ; int show = ( context . length ( ) < CONTEXTLEN ? context . length ( ) : CONTEXTLEN ) ; System . err . println ( context . substring ( context . length ( ) - show ) + "^" ) ; if ( parsestate . getURL ( ) != null ) System . err . println ( "\turl=" + parsestate . getURL ( ) ) ; new Exception ( ) . printStackTrace ( System . err ) ; }


Input: Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; if ( null == c ) { double a = aVar . readScalarDouble ( ) ; double b = bVar . readScalarDouble ( ) ; depth_c = depthCVar . readScalarDouble ( ) ; c = makeC ( sArray , a , b ) ; } return makeHeight ( etaArray , sArray , depthArray , c , depth_c ) ; }


Input: Get the 1D vertical coordinate array for this time step and the specified X Y index for Lat - Lon point . [CODESPLIT] public ArrayDouble . D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; if ( null == c ) { double a = aVar . readScalarDouble ( ) ; double b = bVar . readScalarDouble ( ) ; depth_c = depthCVar . readScalarDouble ( ) ; c = makeC ( sArray , a , b ) ; } return makeHeight1D ( etaArray , sArray , depthArray , c , depth_c , xIndex , yIndex ) ; }


Input:
Make the C array [CODESPLIT] private Array makeC ( Array s , double a , double b ) { int nz = ( int ) s . getSize ( ) ; Index sIndex = s . getIndex ( ) ; if ( a == 0 ) return s ; // per R. Signell, USGS
 ArrayDouble . D1 c = new ArrayDouble . D1 ( nz ) ; double fac1 = 1.0 - b ; double denom1 = 1.0 / Math . sinh ( a ) ; double denom2 = 1.0 / ( 2.0 * Math . tanh ( 0.5 * a ) ) ; for ( int i = 0 ; i < nz ; i ++ ) { double sz = s . getDouble ( sIndex . set ( i ) ) ; double term1 = fac1 * Math . sinh ( a * sz ) * denom1 ; double term2 = b * ( Math . tanh ( a * ( sz + 0.5 ) ) * denom2 - 0.5 ) ; c . set ( i , term1 + term2 ) ; } return c ; }


Input:
Make height from the given data . <br > old equationn : height ( x y z ) = eta ( x y ) * ( 1 + s ( z )) + depth_c * s ( z ) + ( depth ( x y ) - depth_c ) * C ( z ) <p / > <p / > / * - sachin 03 / 23 / 09 The new corrected equation according to Hernan Arango ( Rutgers ) height ( x y z ) = S ( x y z ) + eta ( x y ) * ( 1 + S ( x y z ) / depth ( x y ) ) <p / > where S ( x y z ) = depth_c * s ( z ) + ( depth ( x y ) - depth_c ) * C ( z ) / [CODESPLIT] private ArrayDouble . D3 makeHeight ( Array eta , Array s , Array depth , Array c , double depth_c ) { int nz = ( int ) s . getSize ( ) ; Index sIndex = s . getIndex ( ) ; Index cIndex = c . getIndex ( ) ; int [ ] shape2D = eta . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index etaIndex = eta . getIndex ( ) ; Index depthIndex = depth . getIndex ( ) ; ArrayDouble . D3 height = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int z = 0 ; z < nz ; z ++ ) { double sz = s . getDouble ( sIndex . set ( z ) ) ; double cz = c . getDouble ( cIndex . set ( z ) ) ; double term1 = depth_c * sz ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { //-sachin 03/23/09  modifications according to corrected equation.
 double fac1 = depth . getDouble ( depthIndex . set ( y , x ) ) ; double term2 = ( fac1 - depth_c ) * cz ; double Sterm = term1 + term2 ; double term3 = eta . getDouble ( etaIndex . set ( y , x ) ) ; double term4 = 1 + Sterm / fac1 ; double hterm = Sterm + term3 * term4 ; height . set ( z , y , x , hterm ) ; } } } return height ; }


Input: Initiate the response with an XML file with an XML header [CODESPLIT] public void startXML ( ) { fileOutput += "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" ; fileOutput += "<schema " + "xmlns:" + WFSController . TDSNAMESPACE + "=" + WFSXMLHelper . encQuotes ( namespace ) + " " + "xmlns:ogc=\"http://www.opengis.net/ogc\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" " + "xmlns=\"http://www.w3.org/2001/XMLSchema\" xmlns:gml=\"http://www.opengis.net/gml\" " + "targetNamespace=\"" + server + "\" elementFormDefault=\"qualified\" " + "version=\"0.1\">" ; fileOutput += "<xsd:import namespace=\"http://www.opengis.net/gml\" " + "schemaLocation=\"http://schemas.opengis.net/gml/2.1.2/feature.xsd\"/>" ; }


Input: Write the features from the featureList . For each feature write its attributes [CODESPLIT] public void writeFeatures ( ) { for ( WFSFeature feat : featureList ) { fileOutput += "<xsd:complexType name=\"" + feat . getTitle ( ) + "\">" ; fileOutput += "<xsd:complexContent>" ; fileOutput += "<xsd:extension base=\"gml:" + feat . getType ( ) + "\">" ; fileOutput += "<xsd:sequence>" ; for ( WFSFeatureAttribute attribute : feat . getAttributes ( ) ) { fileOutput += "<xsd:element name =\"" + attribute . getName ( ) + "\" type=\"" + attribute . getType ( ) + "\"/>" ; } fileOutput += "</xsd:sequence>" ; fileOutput += "</xsd:extension>" ; fileOutput += "</xsd:complexContent>" ; fileOutput += "</xsd:complexType>" ; fileOutput += "<xsd:element name =\"" + feat . getName ( ) + "\" type=\"tds:" + feat . getTitle ( ) + "\"/>" ; } }


Input:
Add levels from the GridRecords [CODESPLIT] void addLevels ( List < GridRecord > records ) { for ( GridRecord record : records ) { Double d = new Double ( record . getLevel1 ( ) ) ; if ( ! levels . contains ( d ) ) { levels . add ( d ) ; } if ( dontUseVertical && ( levels . size ( ) > 1 ) ) { if ( GridServiceProvider . debugVert ) { System . out . println ( "GribCoordSys: unused level coordinate has > 1 levels = " + verticalName + " " + record . getLevelType1 ( ) + " " + levels . size ( ) ) ; } } } Collections . sort ( levels ) ; if ( positive . equals ( "down" ) ) { Collections . reverse ( levels ) ; // TODO: delete /* for( int i = 0; i < (levels.size()/2); i++ ){
        Double tmp = (Double) levels.get( i );
        levels.set( i, levels.get(levels.size() -i -1));
        levels.set(levels.size() -i -1, tmp );
     } */ } }


Input: Match levels [CODESPLIT] boolean matchLevels ( List < GridRecord > records ) { // first create a new list List < Double > levelList = new ArrayList < Double > ( records . size ( ) ) ; for ( GridRecord record : records ) { Double d = new Double ( record . getLevel1 ( ) ) ; if ( ! levelList . contains ( d ) ) { levelList . add ( d ) ; } } Collections . sort ( levelList ) ; if ( positive . equals ( "down" ) ) { Collections . reverse ( levelList ) ; } // gotta equal existing list return levelList . equals ( levels ) ; }


Input: Add dimensions to the netcdf file [CODESPLIT] void addDimensionsToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( dontUseVertical ) { return ; } int nlevs = levels . size ( ) ; ncfile . addDimension ( g , new Dimension ( verticalName , nlevs , true ) ) ; }


Input: Add this coordinate system to the netCDF file [CODESPLIT] void addToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( dontUseVertical ) { return ; } if ( g == null ) { g = ncfile . getRootGroup ( ) ; } String dims = "time" ; if ( ! dontUseVertical ) { dims = dims + " " + verticalName ; } if ( hcs . isLatLon ( ) ) { dims = dims + " lat lon" ; } else { dims = dims + " y x" ; } //Collections.sort( levels); int nlevs = levels . size ( ) ; // ncfile.addDimension(g, new Dimension(verticalName, nlevs, true)); // coordinate axis and coordinate system Variable Variable v = new Variable ( ncfile , g , null , verticalName ) ; v . setDataType ( DataType . DOUBLE ) ; v . addAttribute ( new Attribute ( "long_name" , lookup . getLevelDescription ( record ) ) ) ; v . addAttribute ( new Attribute ( "units" , lookup . getLevelUnit ( record ) ) ) ; // positive attribute needed for CF-1 Height and Pressure if ( positive != null ) { v . addAttribute ( new Attribute ( "positive" , positive ) ) ; } if ( units != null ) { AxisType axisType ; if ( SimpleUnit . isCompatible ( "millibar" , units ) ) { axisType = AxisType . Pressure ; } else if ( SimpleUnit . isCompatible ( "m" , units ) ) { axisType = AxisType . Height ; } else { axisType = AxisType . GeoZ ; } v . addAttribute ( new Attribute ( "grid_level_type" , Integer . toString ( record . getLevelType1 ( ) ) ) ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axisType . toString ( ) ) ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , dims ) ) ; if ( ! hcs . isLatLon ( ) ) { v . addAttribute ( new Attribute ( _Coordinate . Transforms , hcs . getGridName ( ) ) ) ; } } double [ ] data = new double [ nlevs ] ; for ( int i = 0 ; i < levels . size ( ) ; i ++ ) { Double d = ( Double ) levels . get ( i ) ; data [ i ] = d . doubleValue ( ) ; } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { nlevs } , data ) ; v . setDimensions ( verticalName ) ; v . setCachedData ( dataArray , false ) ; ncfile . addVariable ( g , v ) ; // look for vertical transforms if ( record . getLevelType1 ( ) == 109 ) { findCoordinateTransform ( g , "Pressure" , record . getLevelType1 ( ) ) ; } }


Input: Find the coordinate transform [CODESPLIT] void findCoordinateTransform ( Group g , String nameStartsWith , int levelType ) { // look for variable that uses this coordinate List < Variable > vars = g . getVariables ( ) ; for ( Variable v : vars ) { if ( v . getShortName ( ) . equals ( nameStartsWith ) ) { Attribute att = v . findAttribute ( "grid_level_type" ) ; if ( ( att == null ) || ( att . getNumericValue ( ) . intValue ( ) != levelType ) ) { continue ; } v . addAttribute ( new Attribute ( _Coordinate . TransformType , "Vertical" ) ) ; v . addAttribute ( new Attribute ( "transform_name" , "Existing3DField" ) ) ; } } }


Input: Get the index of a particular GridRecord [CODESPLIT] int getIndex ( GridRecord record ) { Double d = new Double ( record . getLevel1 ( ) ) ; return levels . indexOf ( d ) ; }


Input: Be sure to call this when your application exits otherwise your process may not exit without being killed . [CODESPLIT] static public void exit ( ) { if ( timer != null ) { timer . cancel ( ) ; System . out . printf ( "DiskCache2.exit()%n" ) ; } timer = null ; }


Input: Default DiskCache2 strategy : use $user_home / . unidata / cache / no scouring alwaysUseCache = false Mimics default DiskCache static class [CODESPLIT] static public DiskCache2 getDefault ( ) { String root = System . getProperty ( "nj22.cache" ) ; if ( root == null ) { String home = System . getProperty ( "user.home" ) ; if ( home == null ) home = System . getProperty ( "user.dir" ) ; if ( home == null ) home = "." ; root = home + "/.unidata/cache/" ; } DiskCache2 result = new DiskCache2 ( ) ; result . setRootDirectory ( root ) ; result . alwaysUseCache = false ; return result ; }


Input: / * Set the cache root directory . Create it if it doesnt exist . Normally this is set in the Constructor . [CODESPLIT] public void setRootDirectory ( String cacheDir ) { if ( ! cacheDir . endsWith ( "/" ) ) cacheDir = cacheDir + "/" ; root = StringUtil2 . replace ( cacheDir , ' ' , "/" ) ; // no nasty backslash File dir = new File ( root ) ; if ( ! dir . mkdirs ( ) ) { // ok } if ( ! dir . exists ( ) ) { fail = true ; cacheLog . error ( "DiskCache2 failed to create directory " + root ) ; } else { cacheLog . debug ( "DiskCache2 create directory " + root ) ; } }


Input: Get a File in the cache corresponding to the fileLocation . File may or may not exist . If fileLocation has / in it and cachePathPolicy == NestedDirectory the nested directories will be created . [CODESPLIT] public File getCacheFile ( String fileLocation ) { if ( neverUseCache ) return null ; if ( ! alwaysUseCache ) { File f = new File ( fileLocation ) ; if ( canWrite ( f ) ) return f ; } File f = new File ( makeCachePath ( fileLocation ) ) ; //if (f.exists()) // f.setLastModified( System.currentTimeMillis()); if ( cachePathPolicy == CachePathPolicy . NestedDirectory ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) ) { boolean ret = dir . mkdirs ( ) ; if ( ! ret ) cacheLog . warn ( "Error creating dir: " + dir ) ; } } return f ; }


Input: Get the named File . If exists or isWritable return it . Otherwise get corresponding file in the cache directory . [CODESPLIT] public File getFile ( String fileLocation ) { if ( ! alwaysUseCache ) { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; if ( canWrite ( f ) ) return f ; } if ( neverUseCache ) { throw new IllegalStateException ( "neverUseCache=true, but file does not exist and directory is not writeable =" + fileLocation ) ; } File f = new File ( makeCachePath ( fileLocation ) ) ; if ( cachePathPolicy == CachePathPolicy . NestedDirectory ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) cacheLog . warn ( "Cant create directories for file " + dir . getPath ( ) ) ; } return f ; }


Input: Returns { @code true } if we can write to the file . [CODESPLIT] public static boolean canWrite ( File f ) { Path path = f . toPath ( ) . toAbsolutePath ( ) ; try { if ( Files . isDirectory ( path ) ) { // Try to create a file within the directory to determine if it's writable. Files . delete ( Files . createTempFile ( path , "check" , null ) ) ; } else if ( Files . isRegularFile ( path ) ) { // Try to open the file for writing in append mode. Files . newOutputStream ( path , StandardOpenOption . APPEND ) . close ( ) ; } else { // File does not exist. See if it's parent directory exists and is writeable. Files . delete ( Files . createTempFile ( path . getParent ( ) , "check" , null ) ) ; } } catch ( IOException | SecurityException e ) { return false ; } return true ; }


Input: Looking for an existing file in cache or no [CODESPLIT] public File getExistingFileOrCache ( String fileLocation ) { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; if ( neverUseCache ) return null ; File fc = new File ( makeCachePath ( fileLocation ) ) ; if ( fc . exists ( ) ) return fc ; return null ; }


Input: Create a new uniquely named file in the root directory . Mimics File . createTempFile () [CODESPLIT] public synchronized File createUniqueFile ( String prefix , String suffix ) { if ( suffix == null ) suffix = ".tmp" ; Random random = new Random ( System . currentTimeMillis ( ) ) ; File result = new File ( getRootDirectory ( ) , prefix + Integer . toString ( random . nextInt ( ) ) + suffix ) ; while ( result . exists ( ) ) result = new File ( getRootDirectory ( ) , prefix + Integer . toString ( random . nextInt ( ) ) + suffix ) ; return result ; }


Input: Make the cache filename [CODESPLIT] private String makeCachePath ( String fileLocation ) { // remove ':', '?', '=', replace '\' with '/', leading or trailing '/' String cachePath = fileLocation ; cachePath = StringUtil2 . remove ( cachePath , ' ' ) ; cachePath = StringUtil2 . remove ( cachePath , ' ' ) ; cachePath = StringUtil2 . replace ( cachePath , ' ' , "/" ) ; if ( cachePath . startsWith ( "/" ) ) cachePath = cachePath . substring ( 1 ) ; if ( cachePath . endsWith ( "/" ) ) cachePath = cachePath . substring ( 0 , cachePath . length ( ) - 1 ) ; cachePath = StringUtil2 . remove ( cachePath , ' ' ) ; // remove directories if ( cachePathPolicy == CachePathPolicy . OneDirectory ) { cachePath = StringUtil2 . replace ( cachePath , ' ' , "-" ) ; } // eliminate leading directories else if ( cachePathPolicy == CachePathPolicy . NestedTruncate ) { int pos = cachePath . indexOf ( cachePathPolicyParam ) ; if ( pos >= 0 ) cachePath = cachePath . substring ( pos + cachePathPolicyParam . length ( ) ) ; if ( cachePath . startsWith ( "/" ) ) cachePath = cachePath . substring ( 1 ) ; } // make sure the parent directory exists if ( cachePathPolicy != CachePathPolicy . OneDirectory ) { File file = new File ( root + cachePath ) ; File parent = file . getParentFile ( ) ; if ( ! parent . exists ( ) ) { if ( root == null ) { // LOOK shouldnt happen, remove soon System . out . printf ( "mkdir4 %s%n" , parent . getPath ( ) ) ; new Throwable ( ) . printStackTrace ( ) ; } boolean ret = parent . mkdirs ( ) ; if ( ! ret ) cacheLog . warn ( "Error creating parent: " + parent ) ; } } return root + cachePath ; }


Input: Show cache contents for debugging . [CODESPLIT] public void showCache ( PrintStream pw ) { pw . println ( "Cache files" ) ; pw . println ( "Size   LastModified       Filename" ) ; File dir = new File ( root ) ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) for ( File file : files ) { String org = null ; try { org = URLDecoder . decode ( file . getName ( ) , "UTF8" ) ; } catch ( UnsupportedEncodingException e ) { e . printStackTrace ( ) ; } pw . println ( " " + file . length ( ) + " " + new Date ( file . lastModified ( ) ) + " " + org ) ; } }


Input: Remove any files or directories whose last modified time greater than persistMinutes [CODESPLIT] public void cleanCache ( File dir , Formatter sbuff , boolean isRoot ) { long now = System . currentTimeMillis ( ) ; File [ ] files = dir . listFiles ( ) ; if ( files == null ) { throw new IllegalStateException ( "DiskCache2: not a directory or I/O error on dir=" + dir . getAbsolutePath ( ) ) ; } // check for empty directory if ( ! isRoot && ( files . length == 0 ) ) { long duration = now - dir . lastModified ( ) ; duration /= 1000 * 60 ; // minutes if ( duration > persistMinutes ) { boolean ok = dir . delete ( ) ; if ( ! ok ) cacheLog . error ( "Unable to delete file " + dir . getAbsolutePath ( ) ) ; if ( sbuff != null ) sbuff . format ( " deleted %s %s lastModified= %s%n" , ok , dir . getPath ( ) , CalendarDate . of ( dir . lastModified ( ) ) ) ; } return ; } // check for expired files for ( File file : files ) { if ( file . isDirectory ( ) ) { cleanCache ( file , sbuff , false ) ; } else { long duration = now - file . lastModified ( ) ; duration /= 1000 * 60 ; // minutes if ( duration > persistMinutes ) { boolean ok = file . delete ( ) ; if ( ! ok ) cacheLog . error ( "Unable to delete file " + file . getAbsolutePath ( ) ) ; if ( sbuff != null ) sbuff . format ( " deleted %s %s lastModified= %s%n" , ok , file . getPath ( ) , CalendarDate . of ( file . lastModified ( ) ) ) ; } } } }


Input: This method has the standard behavior when this object has been created using the standard constructors . Otherwise it uses currentToken and expectedTokenSequences to generate a parse error message and returns it . If this object has been created due to a parse error and you do not catch it ( it gets thrown from the parser ) then this method is called during the printing of the final stack trace and hence the correct error message gets displayed . [CODESPLIT] public String getMessage ( ) { if ( ! specialConstructor ) { return super . getMessage ( ) ; } StringBuilder expected = new StringBuilder ( ) ; int maxSize = 0 ; for ( int [ ] expectedTokenSequence : expectedTokenSequences ) { if ( maxSize < expectedTokenSequence . length ) { maxSize = expectedTokenSequence . length ; } for ( int anExpectedTokenSequence : expectedTokenSequence ) { expected . append ( tokenImage [ anExpectedTokenSequence ] ) . append ( ' ' ) ; } if ( expectedTokenSequence [ expectedTokenSequence . length - 1 ] != 0 ) { expected . append ( "..." ) ; } expected . append ( eol ) . append ( "    " ) ; } StringBuilder b = new StringBuilder ( "Encountered \"" ) ; Token tok = currentToken . next ; for ( int i = 0 ; i < maxSize ; i ++ ) { if ( i != 0 ) b . append ( " " ) ; if ( tok . kind == 0 ) { b . append ( tokenImage [ 0 ] ) ; break ; } b . append ( " " ) . append ( tokenImage [ tok . kind ] ) . append ( " \"" ) ; b . append ( add_escapes ( tok . image ) ) ; b . append ( " \"" ) ; tok = tok . next ; } b . append ( "\" at line " ) . append ( currentToken . next . beginLine ) . append ( ", column " ) . append ( currentToken . next . beginColumn ) ; b . append ( "." ) . append ( eol ) ; if ( expectedTokenSequences . length == 1 ) { b . append ( "Was expecting:" ) . append ( eol ) . append ( "    " ) ; } else { b . append ( "Was expecting one of:" ) . append ( eol ) . append ( "    " ) ; } expected . append ( expected . toString ( ) ) ; return b . toString ( ) ; }


Input: ////////////////////////////////////////////// TableModelListener //////////////////////////////////////////////// [CODESPLIT] @ Override public void tableChanged ( final TableModelEvent e ) { if ( e . getFirstRow ( ) == TableModelEvent . HEADER_ROW ) { return ; // Do not respond to changes in the number of columns here, only row and data changes. } // ColumnWidthsResizer requires that the internal Swing TableModelListeners that update the JTable view // run their updates BEFORE it does its thing. Unfortunately, the order in which listeners are notified is // undefined (see https://weblogs.java.net/blog/alexfromsun/archive/2011/06/15/swing-better-world-listeners). // As a work-around, we're going to place the resize operation at the end of the event queue. That way, it'll // be executed after all TableModelListeners have been notified. EventQueue . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { // Do not cache the value of doFullScan; we need to reevaluate each time because the number of rows in // the table could have changed. boolean doFullScan = table . getRowCount ( ) <= fullScanCutoff ; if ( e . getColumn ( ) == TableModelEvent . ALL_COLUMNS ) { resize ( table , doFullScan ) ; // Resize all columns. } else { resize ( table , e . getColumn ( ) , doFullScan ) ; // Resize only the affected column. } } } ) ; }


Input: /////////////////////////////////////////// TableColumnModelListener ///////////////////////////////////////////// [CODESPLIT] @ Override public void columnAdded ( TableColumnModelEvent e ) { boolean doFullScan = table . getRowCount ( ) <= fullScanCutoff ; resize ( table , e . getToIndex ( ) , doFullScan ) ; // Only resize added column. }


Input: Calculate the bearing between the 2 points . See calculateBearing below . [CODESPLIT] public static Bearing calculateBearing ( Earth e , LatLonPoint pt1 , LatLonPoint pt2 , Bearing result ) { return calculateBearing ( e , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , pt2 . getLatitude ( ) , pt2 . getLongitude ( ) , result ) ; }


Input: Calculate the bearing between the 2 points . See calculateBearing below . Uses default Earth object . [CODESPLIT] public static Bearing calculateBearing ( LatLonPoint pt1 , LatLonPoint pt2 , Bearing result ) { return calculateBearing ( defaultEarth , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , pt2 . getLatitude ( ) , pt2 . getLongitude ( ) , result ) ; }


Input: Computes distance ( in km ) azimuth ( degrees clockwise positive from North 0 to 360 ) and back azimuth ( degrees clockwise positive from North 0 to 360 ) from latitude - longituide point pt1 to latitude - longituide pt2 . Uses default Earth object . [CODESPLIT] public static Bearing calculateBearing ( double lat1 , double lon1 , double lat2 , double lon2 , Bearing result ) { return calculateBearing ( defaultEarth , lat1 , lon1 , lat2 , lon2 , result ) ; }


Input:
Computes distance ( in km ) azimuth ( degrees clockwise positive from North 0 to 360 ) and back azimuth ( degrees clockwise positive from North 0 to 360 ) from latitude - longituide point pt1 to latitude - longituide pt2 .
 Algorithm from U . S . National Geodetic Survey FORTRAN program inverse subroutine INVER1 by L . PFEIFER and JOHN G . GERGEN . See http : // www . ngs . noaa . gov / TOOLS / Inv_Fwd / Inv_Fwd . html
 Original documentation :
 SOLUTION OF THE GEODETIC INVERSE PROBLEM AFTER T . VINCENTY
 MODIFIED RAINSFORD S METHOD WITH HELMERT S ELLIPTICAL TERMS
 EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
 STANDPOINT / FOREPOINT MUST NOT BE THE GEOGRAPHIC POLE
 Reference ellipsoid is the WGS - 84 ellipsoid .
 See http : // www . colorado . edu / geography / gcraft / notes / datum / elist . html
 Requires close to 1 . 4 E - 5 seconds wall clock time per call on a 550 MHz Pentium with Linux 7 . 2 . [CODESPLIT] public static Bearing calculateBearing ( Earth e , double lat1 , double lon1 , double lat2 , double lon2 , Bearing result ) { if ( result == null ) { result = new Bearing ( ) ; } if ( ( lat1 == lat2 ) && ( lon1 == lon2 ) ) { result . distance = 0 ; result . azimuth = 0 ; result . backazimuth = 0 ; return result ; } A = e . getMajor ( ) ; F = e . getFlattening ( ) ; R = 1.0 - F ; // Algorithm from National Geodetic Survey, FORTRAN program "inverse,"
 // subroutine "INVER1," by L. PFEIFER and JOHN G. GERGEN.
 // http://www.ngs.noaa.gov/TOOLS/Inv_Fwd/Inv_Fwd.html
 // Conversion to JAVA from FORTRAN was made with as few changes as possible
 // to avoid errors made while recasting form, and to facilitate any future
 // comparisons between the original code and the altered version in Java.
 // Original documentation:
 // SOLUTION OF THE GEODETIC INVERSE PROBLEM AFTER T.VINCENTY
 // MODIFIED RAINSFORD'S METHOD WITH HELMERT'S ELLIPTICAL TERMS
 // EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
 // STANDPOINT/FOREPOINT MUST NOT BE THE GEOGRAPHIC POLE
 // A IS THE SEMI-MAJOR AXIS OF THE REFERENCE ELLIPSOID
 // F IS THE FLATTENING (NOT RECIPROCAL) OF THE REFERNECE ELLIPSOID
 // LATITUDES GLAT1 AND GLAT2
 // AND LONGITUDES GLON1 AND GLON2 ARE IN RADIANS POSITIVE NORTH AND EAST
 // FORWARD AZIMUTHS AT BOTH POINTS RETURNED IN RADIANS FROM NORTH
 //
 // Reference ellipsoid is the WGS-84 ellipsoid.
 // See http://www.colorado.edu/geography/gcraft/notes/datum/elist.html
 // FAZ is forward azimuth in radians from pt1 to pt2;
 // BAZ is backward azimuth from point 2 to 1;
 // S is distance in meters.
 //
 // Conversion to JAVA from FORTRAN was made with as few changes as possible
 // to avoid errors made while recasting form, and to facilitate any future
 // comparisons between the original code and the altered version in Java.
 //
 //IMPLICIT REAL*8 (A-H,O-Z)
 //  COMMON/CONST/PI,RAD
 //  COMMON/ELIPSOID/A,F
 double GLAT1 = rad * lat1 ; double GLAT2 = rad * lat2 ; double TU1 = R * Math . sin ( GLAT1 ) / Math . cos ( GLAT1 ) ; double TU2 = R * Math . sin ( GLAT2 ) / Math . cos ( GLAT2 ) ; double CU1 = 1. / Math . sqrt ( TU1 * TU1 + 1. ) ; double SU1 = CU1 * TU1 ; double CU2 = 1. / Math . sqrt ( TU2 * TU2 + 1. ) ; double S = CU1 * CU2 ; double BAZ = S * TU2 ; double FAZ = BAZ * TU1 ; double GLON1 = rad * lon1 ; double GLON2 = rad * lon2 ; double X = GLON2 - GLON1 ; double D , SX , CX , SY , CY , Y , SA , C2A , CZ , E , C ; int loopCnt = 0 ; do { loopCnt ++ ; //Check for an infinite loop
 if ( loopCnt > 1000 ) { throw new IllegalArgumentException ( "Too many iterations calculating bearing:" + lat1 + " " + lon1 + " " + lat2 + " " + lon2 ) ; } SX = Math . sin ( X ) ; CX = Math . cos ( X ) ; TU1 = CU2 * SX ; TU2 = BAZ - SU1 * CU2 * CX ; SY = Math . sqrt ( TU1 * TU1 + TU2 * TU2 ) ; CY = S * CX + FAZ ; Y = Math . atan2 ( SY , CY ) ; SA = S * SX / SY ; C2A = - SA * SA + 1. ; CZ = FAZ + FAZ ; if ( C2A > 0. ) { CZ = - CZ / C2A + CY ; } E = CZ * CZ * 2. - 1. ; C = ( ( - 3. * C2A + 4. ) * F + 4. ) * C2A * F / 16. ; D = X ; X = ( ( E * CY * C + CZ ) * SY * C + Y ) * SA ; X = ( 1. - C ) * X * F + GLON2 - GLON1 ; //IF(DABS(D-X).GT.EPS) GO TO 100
 } while ( Math . abs ( D - X ) > EPS ) ; if ( loopCnt > maxLoopCnt ) { maxLoopCnt = loopCnt ; //        System.err.println("loopCnt:" + loopCnt);
 } FAZ = Math . atan2 ( TU1 , TU2 ) ; BAZ = Math . atan2 ( CU1 * SX , BAZ * CX - SU1 * CU2 ) + Math . PI ; X = Math . sqrt ( ( 1. / R / R - 1. ) * C2A + 1. ) + 1. ; X = ( X - 2. ) / X ; C = 1. - X ; C = ( X * X / 4. + 1. ) / C ; D = ( 0.375 * X * X - 1. ) * X ; X = E * CY ; S = 1. - E - E ; S = ( ( ( ( SY * SY * 4. - 3. ) * S * CZ * D / 6. - X ) * D / 4. + CZ ) * SY * D + Y ) * C * A * R ; result . distance = S / 1000.0 ; // meters to km
 result . azimuth = FAZ * deg ; // radians to degrees
 if ( result . azimuth < 0.0 ) { result . azimuth += 360.0 ; // reset azs from -180 to 180 to 0 to 360
 } result . backazimuth = BAZ * deg ; // radians to degrees; already in 0 to 360 range
 return result ; }


Input:
Test the calculations - forward and back [CODESPLIT] public static void main ( String [ ] args ) { //Bearing         workBearing = new Bearing();
 LatLonPointImpl pt1 = new LatLonPointImpl ( 40 , - 105 ) ; LatLonPointImpl pt2 = new LatLonPointImpl ( 37.4 , - 118.4 ) ; Bearing b = calculateBearing ( pt1 , pt2 , null ) ; System . out . println ( "Bearing from " + pt1 + " to " + pt2 + " = \n\t" + b ) ; LatLonPointImpl pt3 = new LatLonPointImpl ( ) ; pt3 = findPoint ( pt1 , b . getAngle ( ) , b . getDistance ( ) , pt3 ) ; System . out . println ( "using first point, angle and distance, found second point at " + pt3 ) ; pt3 = findPoint ( pt2 , b . getBackAzimuth ( ) , b . getDistance ( ) , pt3 ) ; System . out . println ( "using second point, backazimuth and distance, found first point at " + pt3 ) ; /*  uncomment for timing tests
        for(int j=0;j<10;j++) {
            long t1 = System.currentTimeMillis();
            for(int i=0;i<30000;i++) {
                workBearing = Bearing.calculateBearing(42.5,-93.0,
                                                       48.9,-117.09,workBearing);
            }
            long t2 = System.currentTimeMillis();
            System.err.println ("time:" + (t2-t1));
        }
        */ }


Input: Calculate a position given an azimuth and distance from another point . [CODESPLIT] public static LatLonPointImpl findPoint ( Earth e , LatLonPoint pt1 , double az , double dist , LatLonPointImpl result ) { return findPoint ( e , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , az , dist , result ) ; }


Input: Calculate a position given an azimuth and distance from another point . Uses default Earth . [CODESPLIT] public static LatLonPointImpl findPoint ( LatLonPoint pt1 , double az , double dist , LatLonPointImpl result ) { return findPoint ( defaultEarth , pt1 . getLatitude ( ) , pt1 . getLongitude ( ) , az , dist , result ) ; }


Input: Calculate a position given an azimuth and distance from another point . See details below . Uses default Earth . [CODESPLIT] public static LatLonPointImpl findPoint ( double lat1 , double lon1 , double az , double dist , LatLonPointImpl result ) { return findPoint ( defaultEarth , lat1 , lon1 , az , dist , result ) ; }


Input:
Calculate a position given an azimuth and distance from another point . <p / > <p / > Algorithm from National Geodetic Survey FORTRAN program forward subroutine DIRCT1 by stephen j . frakes . http : // www . ngs . noaa . gov / TOOLS / Inv_Fwd / Inv_Fwd . html <p > Original documentation : <pre > SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T . VINCENTY MODIFIED RAINSFORD S METHOD WITH HELMERT S ELLIPTICAL TERMS EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL < / pre > [CODESPLIT] public static LatLonPointImpl findPoint ( Earth e , double lat1 , double lon1 , double az , double dist , LatLonPointImpl result ) { if ( result == null ) { result = new LatLonPointImpl ( ) ; } if ( ( dist == 0 ) ) { result . setLatitude ( lat1 ) ; result . setLongitude ( lon1 ) ; return result ; } A = e . getMajor ( ) ; F = e . getFlattening ( ) ; R = 1.0 - F ; // Algorithm from National Geodetic Survey, FORTRAN program "forward,"
 // subroutine "DIRCT1," by stephen j. frakes.
 // http://www.ngs.noaa.gov/TOOLS/Inv_Fwd/Inv_Fwd.html
 // Conversion to JAVA from FORTRAN was made with as few changes as
 // possible to avoid errors made while recasting form, and
 // to facilitate any future comparisons between the original
 // code and the altered version in Java.
 // Original documentation:
 //   SUBROUTINE DIRCT1(GLAT1,GLON1,GLAT2,GLON2,FAZ,BAZ,S)
 //
 //   SOLUTION OF THE GEODETIC DIRECT PROBLEM AFTER T.VINCENTY
 //   MODIFIED RAINSFORD'S METHOD WITH HELMERT'S ELLIPTICAL TERMS
 //   EFFECTIVE IN ANY AZIMUTH AND AT ANY DISTANCE SHORT OF ANTIPODAL
 //
 //   A IS THE SEMI-MAJOR AXIS OF THE REFERENCE ELLIPSOID
 //   F IS THE FLATTENING OF THE REFERENCE ELLIPSOID
 //   LATITUDES AND LONGITUDES IN RADIANS POSITIVE NORTH AND EAST
 //   AZIMUTHS IN RADIANS CLOCKWISE FROM NORTH
 //   GEODESIC DISTANCE S ASSUMED IN UNITS OF SEMI-MAJOR AXIS A
 //
 //   PROGRAMMED FOR CDC-6600 BY LCDR L.PFEIFER NGS ROCKVILLE MD 20FEB75
 //   MODIFIED FOR SYSTEM 360 BY JOHN G GERGEN NGS ROCKVILLE MD 750608
 //
 if ( az < 0.0 ) { az += 360.0 ; // reset azs from -180 to 180 to 0 to 360
 } double FAZ = az * rad ; double GLAT1 = lat1 * rad ; double GLON1 = lon1 * rad ; double S = dist * 1000. ; // convert to meters
 double TU = R * Math . sin ( GLAT1 ) / Math . cos ( GLAT1 ) ; double SF = Math . sin ( FAZ ) ; double CF = Math . cos ( FAZ ) ; double BAZ = 0. ; if ( CF != 0 ) { BAZ = Math . atan2 ( TU , CF ) * 2 ; } double CU = 1. / Math . sqrt ( TU * TU + 1. ) ; double SU = TU * CU ; double SA = CU * SF ; double C2A = - SA * SA + 1. ; double X = Math . sqrt ( ( 1. / R / R - 1. ) * C2A + 1. ) + 1. ; X = ( X - 2. ) / X ; double C = 1. - X ; C = ( X * X / 4. + 1 ) / C ; double D = ( 0.375 * X * X - 1. ) * X ; TU = S / R / A / C ; double Y = TU ; double SY , CY , CZ , E , GLAT2 , GLON2 ; do { SY = Math . sin ( Y ) ; CY = Math . cos ( Y ) ; CZ = Math . cos ( BAZ + Y ) ; E = CZ * CZ * 2. - 1. ; C = Y ; X = E * CY ; Y = E + E - 1. ; Y = ( ( ( SY * SY * 4. - 3. ) * Y * CZ * D / 6. + X ) * D / 4. - CZ ) * SY * D + TU ; } while ( Math . abs ( Y - C ) > EPS ) ; BAZ = CU * CY * CF - SU * SY ; C = R * Math . sqrt ( SA * SA + BAZ * BAZ ) ; D = SU * CY + CU * SY * CF ; GLAT2 = Math . atan2 ( D , C ) ; C = CU * CY - SU * SY * CF ; X = Math . atan2 ( SY * SF , C ) ; C = ( ( - 3. * C2A + 4. ) * F + 4. ) * C2A * F / 16. ; D = ( ( E * CY * C + CZ ) * SY * C + Y ) * SA ; GLON2 = GLON1 + X - ( 1. - C ) * D * F ; BAZ = ( Math . atan2 ( SA , BAZ ) + Math . PI ) * deg ; result . setLatitude ( GLAT2 * deg ) ; result . setLongitude ( GLON2 * deg ) ; return result ; }


Input: method to invoke with a filename or URL of a picture that is to be loaded a new thread . This is handy to update the screen while the loading chuggs along in the background . [CODESPLIT] public void loadPictureInThread ( URL imageUrl , int priority , double rotation ) { if ( pictureStatusCode == LOADING ) { stopLoadingExcept ( imageUrl ) ; } this . imageUrl = imageUrl ; this . rotation = rotation ; LoadThread t = new LoadThread ( this ) ; t . setPriority ( priority ) ; t . start ( ) ; }


Input: method to invoke with a filename or URL of a picture that is to be loaded in the main thread . [CODESPLIT] public void loadPicture ( URL imageUrl , double rotation ) { if ( pictureStatusCode == LOADING ) { stopLoadingExcept ( imageUrl ) ; } this . imageUrl = imageUrl ; this . rotation = rotation ; loadPicture ( ) ; }


Input:
loads a picture from the URL in the imageUrl object into the sourcePictureBufferedImage object and updates the status when done or failed . [CODESPLIT] public void loadPicture ( ) { Tools . log ( "SourcePicture.loadPicture: " + imageUrl . toString ( ) + " loaded into SourcePicture object: " + Integer . toString ( this . hashCode ( ) ) ) ; //Tools.freeMem(); setStatus ( LOADING , "Loading: " + imageUrl . toString ( ) ) ; abortFlag = false ; try { // Java 1.4 way with a Listener ImageInputStream iis = ImageIO . createImageInputStream ( imageUrl . openStream ( ) ) ; Iterator i = ImageIO . getImageReaders ( iis ) ; if ( ! i . hasNext ( ) ) { throw new IOException ( "No Readers Available!" ) ; } reader = ( ImageReader ) i . next ( ) ; // grab the first one reader . addIIOReadProgressListener ( imageProgressListener ) ; reader . setInput ( iis ) ; sourcePictureBufferedImage = null ; // try { sourcePictureBufferedImage = reader . read ( 0 ) ; // just get the first image /* } catch ( OutOfMemoryError e ) {
				Tools.log("SourcePicture caught an OutOfMemoryError while loading an image." );

				iis.close();
				reader.removeIIOReadProgressListener( imageProgressListener );
				reader.dispose();

				setStatus(ERROR, "Out of Memory Error while reading " + imageUrl.toString());
				sourcePictureBufferedImage = null;
				// PictureCache.clear();

				JOptionPane.showMessageDialog( null,  //deliberately null or it swaps the window
					"outOfMemoryError",
					"genericError",
					JOptionPane.ERROR_MESSAGE);

				System.gc();
				System.runFinalization();

				Tools.log("JPO has now run a garbage collection and finalization.");
				return;
			} */ iis . close ( ) ; reader . removeIIOReadProgressListener ( imageProgressListener ) ; //Tools.log("!!dispose being called!!"); reader . dispose ( ) ; if ( ! abortFlag ) { if ( rotation != 0 ) { setStatus ( ROTATING , "Rotating: " + imageUrl . toString ( ) ) ; int xRot = sourcePictureBufferedImage . getWidth ( ) / 2 ; int yRot = sourcePictureBufferedImage . getHeight ( ) / 2 ; AffineTransform rotateAf = AffineTransform . getRotateInstance ( Math . toRadians ( rotation ) , xRot , yRot ) ; AffineTransformOp op = new AffineTransformOp ( rotateAf , AffineTransformOp . TYPE_BILINEAR ) ; Rectangle2D newBounds = op . getBounds2D ( sourcePictureBufferedImage ) ; // a simple AffineTransform would give negative top left coordinates --> // do another transform to get 0,0 as top coordinates again. double minX = newBounds . getMinX ( ) ; double minY = newBounds . getMinY ( ) ; AffineTransform translateAf = AffineTransform . getTranslateInstance ( minX * ( - 1 ) , minY * ( - 1 ) ) ; rotateAf . preConcatenate ( translateAf ) ; op = new AffineTransformOp ( rotateAf , AffineTransformOp . TYPE_BILINEAR ) ; newBounds = op . getBounds2D ( sourcePictureBufferedImage ) ; // this piece of code is so essential!!! Otherwise the internal image format // is totally altered and either the AffineTransformOp decides it doesn't // want to rotate the image or web browsers can't read the resulting image. BufferedImage targetImage = new BufferedImage ( ( int ) newBounds . getWidth ( ) , ( int ) newBounds . getHeight ( ) , BufferedImage . TYPE_3BYTE_BGR ) ; sourcePictureBufferedImage = op . filter ( sourcePictureBufferedImage , targetImage ) ; } setStatus ( READY , "Loaded: " + imageUrl . toString ( ) ) ; PictureCache . add ( imageUrl , ( SourcePicture ) this . clone ( ) ) ; } else { setStatus ( ERROR , "Aborted: " + imageUrl . toString ( ) ) ; sourcePictureBufferedImage = null ; } } catch ( IOException e ) { setStatus ( ERROR , "Error while reading " + imageUrl . toString ( ) ) ; sourcePictureBufferedImage = null ; } }


Input: this method can be invoked to stop the current reader [CODESPLIT] public void stopLoading ( ) { if ( imageUrl == null ) return ; // SourcePicture has never been used yet Tools . log ( "SourcePicture.stopLoading: called on " + imageUrl ) ; if ( pictureStatusCode == LOADING ) { reader . abort ( ) ; abortFlag = true ; //reader.dispose(); //setStatus( ERROR, "Cache Loading was stopped " + imageUrl.toString() ); //sourcePictureBufferedImage = null;  // actually the thread reading the image continues } }


Input: this method can be invoked to stop the current reader except if it is reading the desired file . It returns true is the desired file is being loaded . Otherwise it returns false . [CODESPLIT] public boolean stopLoadingExcept ( URL exemptionURL ) { if ( imageUrl == null ) return false ; // has never been used yet if ( pictureStatusCode != LOADING ) { Tools . log ( "SourcePicture.stopLoadingExcept: called but pointless since image is not LOADING: " + imageUrl . toString ( ) ) ; return false ; } if ( ! exemptionURL . toString ( ) . equals ( imageUrl . toString ( ) ) ) { Tools . log ( "SourcePicture.stopLoadingExcept: called with Url " + exemptionURL . toString ( ) + " --> stopping loading of " + imageUrl . toString ( ) ) ; stopLoading ( ) ; return true ; } else return false ; }


Input: return the size of the image or Zero if there is none [CODESPLIT] public Dimension getSize ( ) { if ( sourcePictureBufferedImage != null ) return new Dimension ( sourcePictureBufferedImage . getWidth ( ) , sourcePictureBufferedImage . getHeight ( ) ) ; else return new Dimension ( 0 , 0 ) ; }


Input: method to register the listening object of the status events [CODESPLIT] public void addListener ( SourcePictureListener listener ) { Tools . log ( "SourcePicture.addListener: listener added on SourcePicture " + Integer . toString ( this . hashCode ( ) ) + " of class: " + listener . getClass ( ) . toString ( ) ) ; sourcePictureListeners . add ( listener ) ; //showListeners(); }


Input: method to register the listening object of the status events [CODESPLIT] public void removeListener ( SourcePictureListener listener ) { Tools . log ( "SourcePicture.removeListener: listener removed from SourcePicture " + Integer . toString ( this . hashCode ( ) ) + " of class: " + listener . getClass ( ) . toString ( ) ) ; sourcePictureListeners . remove ( listener ) ; //showListeners(); }


Input: Method that sets the status of the ScalablePicture object and notifies intereasted objects of a change in status ( not built yet ) . [CODESPLIT] private void setStatus ( int statusCode , String statusMessage ) { Tools . log ( "\nSourcePicture.setStatus: sending status: " + statusMessage ) ; pictureStatusCode = statusCode ; pictureStatusMessage = statusMessage ; Vector nonmodifiedVector = ( Vector ) sourcePictureListeners . clone ( ) ; Enumeration e = nonmodifiedVector . elements ( ) ; while ( e . hasMoreElements ( ) ) { //((SourcePictureListener) e.nextElement()) //	.sourceStatusChange(pictureStatusCode, pictureStatusMessage, this ); SourcePictureListener spl = ( ( SourcePictureListener ) e . nextElement ( ) ) ; spl . sourceStatusChange ( pictureStatusCode , pictureStatusMessage , this ) ; Tools . log ( "\nSourcePicture.setStatus: sending status: " + statusMessage + " to " + spl . getClass ( ) . toString ( ) ) ; } }


Input: sets the buffered image . Unusual method use with care . [CODESPLIT] public void setSourceBufferedImage ( BufferedImage img , String statusMessage ) { sourcePictureBufferedImage = img ; setStatus ( READY , statusMessage ) ; }


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


Input: for associated fields [CODESPLIT] DataDescriptor makeAssociatedField ( int bitWidth ) { DataDescriptor assDD = new DataDescriptor ( ) ; assDD . name = name + "_associated_field" ; assDD . units = "" ; assDD . refVal = 0 ; assDD . scale = 0 ; assDD . bitWidth = bitWidth ; assDD . type = 0 ; assDD . f = 0 ; assDD . x = 31 ; assDD . y = 22 ; assDD . fxy = ( short ) ( ( f << 14 ) + ( x << 8 ) + ( y ) ) ; return assDD ; }


Input:
Transfer info from the proto message to another message with the exact same structure . [CODESPLIT] static public void transferInfo ( List < DataDescriptor > fromList , List < DataDescriptor > toList ) { // get info from proto message
 if ( fromList . size ( ) != toList . size ( ) ) throw new IllegalArgumentException ( "list sizes dont match " + fromList . size ( ) + " != " + toList . size ( ) ) ; for ( int i = 0 ; i < fromList . size ( ) ; i ++ ) { DataDescriptor from = fromList . get ( i ) ; DataDescriptor to = toList . get ( i ) ; to . refersTo = from . refersTo ; to . name = from . name ; if ( from . getSubKeys ( ) != null ) transferInfo ( from . getSubKeys ( ) , to . getSubKeys ( ) ) ; } }


Input:
count the bits used by the data in this dd and its children only accurate for not compressed and not variable length [CODESPLIT] int countBits ( ) { int total_nbits = 0 ; total_nbytesCDM = 0 ; for ( DataDescriptor dd : subKeys ) { if ( dd . subKeys != null ) { total_nbits += dd . countBits ( ) ; total_nbytesCDM += dd . total_nbytesCDM ; } else if ( dd . f == 0 ) { total_nbits += dd . bitWidth ; total_nbytesCDM += dd . getByteWidthCDM ( ) ; } } // replication
 if ( replication > 1 ) { total_nbits *= replication ; total_nbytesCDM *= replication ; } return total_nbits ; }


Input: LOOK need different hashCode reader assumes using object id [CODESPLIT] public boolean equals2 ( Object o ) { if ( this == o ) return true ; if ( o == null || getClass ( ) != o . getClass ( ) ) return false ; DataDescriptor that = ( DataDescriptor ) o ; if ( fxy != that . fxy ) return false ; if ( replication != that . replication ) return false ; if ( type != that . type ) return false ; if ( subKeys != null ? ! subKeys . equals ( that . subKeys ) : that . subKeys != null ) return false ; return true ; }


Input: has to use hashCode2 so cant use list . hashCode () [CODESPLIT] private int getListHash ( ) { if ( subKeys == null ) return 0 ; int result = 1 ; for ( DataDescriptor e : subKeys ) result = 31 * result + ( e == null ? 0 : e . hashCode2 ( ) ) ; return result ; }


Input:
Load the dbase file header . [CODESPLIT] private int loadHeader ( ) { if ( headerLoaded ) return 0 ; InputStream s = stream ; if ( s == null ) return - 1 ; try { BufferedInputStream bs = new BufferedInputStream ( s ) ; ds = new DataInputStream ( bs ) ; /* read the header as one block of bytes*/ Header = new byte [ 32 ] ; ds . readFully ( Header ) ; //System.out.println("dbase header is " + Header);
 if ( Header [ 0 ] == ' ' ) { //looks like html coming back to us!
 close ( ds ) ; return - 1 ; } filetype = Header [ 0 ] ; /* 4 bytes for number of records is in little endian */ nrecords = Swap . swapInt ( Header , 4 ) ; nbytesheader = Swap . swapShort ( Header , 8 ) ; /* read in the Field Descriptors */ /* have to figure how many there are from
      * the header size.  Should be nbytesheader/32 -1
      */ nfields = ( nbytesheader / 32 ) - 1 ; if ( nfields < 1 ) { System . out . println ( "nfields = " + nfields ) ; System . out . println ( "nbytesheader = " + nbytesheader ) ; return - 1 ; } FieldDesc = new DbaseFieldDesc [ nfields ] ; data = new DbaseData [ nfields ] ; for ( int i = 0 ; i < nfields ; i ++ ) { FieldDesc [ i ] = new DbaseFieldDesc ( ds , filetype ) ; data [ i ] = new DbaseData ( FieldDesc [ i ] , nrecords ) ; } /* read the last byte of the header (0x0d) */ ds . readByte ( ) ; headerLoaded = true ; } catch ( java . io . IOException e ) { close ( s ) ; return - 1 ; } return 0 ; }


Input: Load the dbase file data . [CODESPLIT] private int loadData ( ) { if ( ! headerLoaded ) return - 1 ; if ( dataLoaded ) return 0 ; InputStream s = stream ; if ( s == null ) return - 1 ; try { /* read in the data */ for ( int i = 0 ; i < nrecords ; i ++ ) { /* read the data record indicator */ byte recbyte = ds . readByte ( ) ; if ( recbyte == 0x20 ) { for ( int j = 0 ; j < nfields ; j ++ ) { data [ j ] . readRowN ( ds , i ) ; } } else { /* a deleted record */ nrecords -- ; i -- ; } } dataLoaded = true ; } catch ( java . io . IOException e ) { close ( s ) ; return - 1 ; } finally { close ( s ) ; } return 0 ; }


Input: Extract the data for a given field by name . [CODESPLIT] public DbaseData getField ( String Name ) { for ( int i = 0 ; i < nfields ; i ++ ) { if ( FieldDesc [ i ] . Name . equals ( Name ) ) return data [ i ] ; } return null ; }


Input: Extract the double array of data for a field by Name . [CODESPLIT] public double [ ] getDoublesByName ( String Name ) { DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) == DbaseData . TYPE_CHAR ) { String [ ] s = d . getStrings ( ) ; double [ ] dd = new double [ s . length ] ; for ( int i = 0 ; i < s . length ; i ++ ) { dd [ i ] = Double . valueOf ( s [ i ] ) ; } return dd ; } if ( d . getType ( ) == DbaseData . TYPE_BOOLEAN ) { boolean [ ] b = d . getBooleans ( ) ; double [ ] dd = new double [ b . length ] ; for ( int i = 0 ; i < b . length ; i ++ ) { if ( b [ i ] ) { dd [ i ] = 1 ; } else { dd [ i ] = 0 ; } } return dd ; } return d . getDoubles ( ) ; }


Input: Extract the string array of data for a field by Name . [CODESPLIT] public String [ ] getStringsByName ( String Name ) { DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) != DbaseData . TYPE_CHAR ) return null ; return d . getStrings ( ) ; }


Input: Extract the boolean array of data for a field by Name . [CODESPLIT] public boolean [ ] getBooleansByName ( String Name ) { DbaseData d ; if ( ( d = getField ( Name ) ) == null ) return null ; if ( d . getType ( ) != DbaseData . TYPE_BOOLEAN ) return null ; return d . getBooleans ( ) ; }


Input: Get the name of a field by column number . [CODESPLIT] public String getFieldName ( int i ) { if ( i >= nfields || i < 0 ) { return null ; } return ( FieldDesc [ i ] . Name ) ; }


Input: Get a list of all the field names in the dbase file [CODESPLIT] public String [ ] getFieldNames ( ) { String [ ] s = new String [ nfields ] ; for ( int i = 0 ; i < nfields ; i ++ ) { s [ i ] = getFieldName ( i ) ; } return s ; }


Input:
Test program dumps a Dbase file to stdout . [CODESPLIT] public static void main ( String [ ] args ) { if ( args . length < 1 ) { System . out . println ( "filename or URL required" ) ; System . exit ( - 1 ) ; } for ( String s : args ) { System . out . println ( "*** Dump of Dbase " + s + ":" ) ; try { DbaseFile dbf = new DbaseFile ( s ) ; // load() method reads all data at once
 if ( dbf . loadHeader ( ) != 0 ) { System . out . println ( "Error loading header" + s ) ; System . exit ( - 1 ) ; } // output schema as [type0 field0, type1 field1, ...]
 String [ ] fieldNames = dbf . getFieldNames ( ) ; System . out . print ( "[" ) ; int nf = dbf . getNumFields ( ) ; DbaseData [ ] dbd = new DbaseData [ nf ] ; for ( int field = 0 ; field < nf ; field ++ ) { dbd [ field ] = dbf . getField ( field ) ; switch ( dbd [ field ] . getType ( ) ) { case DbaseData . TYPE_BOOLEAN : System . out . print ( "boolean " ) ; break ; case DbaseData . TYPE_CHAR : System . out . print ( "String " ) ; break ; case DbaseData . TYPE_NUMERIC : System . out . print ( "double " ) ; break ; } System . out . print ( fieldNames [ field ] ) ; if ( field < nf - 1 ) System . out . print ( ", " ) ; } System . out . println ( "]" ) ; if ( dbf . loadData ( ) != 0 ) { System . out . println ( "Error loading data" + s ) ; System . exit ( - 1 ) ; } // output data
 for ( int rec = 0 ; rec < dbf . getNumRecords ( ) ; rec ++ ) { for ( int field = 0 ; field < nf ; field ++ ) { System . out . print ( dbd [ field ] . getData ( rec ) ) ; if ( field < nf - 1 ) System . out . print ( ", " ) ; else System . out . println ( ) ; } } } catch ( IOException e ) { e . printStackTrace ( ) ; break ; } } }


Input: attributes are not allowed on some node types [CODESPLIT] public Map < String , DapAttribute > getAttributes ( ) { if ( attributes == null ) attributes = new HashMap < String , DapAttribute > ( ) ; return attributes ; }


Input: This may occur after initial construction [CODESPLIT] synchronized public DapAttribute setAttribute ( DapAttribute attr ) throws DapException { if ( attributes == null ) attributes = new HashMap < String , DapAttribute > ( ) ; DapAttribute old = attributes . get ( attr . getShortName ( ) ) ; attributes . put ( attr . getShortName ( ) , attr ) ; attr . setParent ( this ) ; return old ; }


Input: Used by AbstractDSP to suppress certain attributes . [CODESPLIT] public synchronized void removeAttribute ( DapAttribute attr ) throws DapException { if ( this . attributes == null ) return ; String name = attr . getShortName ( ) ; if ( this . attributes . containsKey ( name ) ) this . attributes . remove ( name ) ; }


Input: Closest containing group [CODESPLIT] public DapGroup getGroup ( ) { if ( this . sort == DapSort . DATASET ) return null ; // Walk the parent node until we find a group DapNode group = parent ; while ( group != null ) { switch ( group . getSort ( ) ) { case DATASET : case GROUP : return ( DapGroup ) group ; default : group = group . getParent ( ) ; break ; } } return ( DapGroup ) group ; }


Input: Closest containing group structure sequence [CODESPLIT] public DapNode getContainer ( ) { DapNode parent = this . parent ; switch ( getSort ( ) ) { default : break ; case ENUMCONST : parent = ( ( DapEnumConst ) this ) . getParent ( ) . getContainer ( ) ; break ; case ATTRIBUTE : case ATTRIBUTESET : case OTHERXML : parent = ( ( DapAttribute ) this ) . getParent ( ) ; if ( parent instanceof DapVariable ) parent = parent . getContainer ( ) ; break ; case MAP : parent = ( ( DapMap ) this ) . getVariable ( ) . getContainer ( ) ; break ; } return parent ; }


Input: Set the parent DapNode ; may sometimes be same as container but not always ( think attributes or maps ) . Invariant : parent must be either a group or a variable . We can infer the container so set that also . [CODESPLIT] public void setParent ( DapNode parent ) { assert this . parent == null ; assert ( ( this . getSort ( ) == DapSort . ENUMCONST && parent . getSort ( ) == DapSort . ENUMERATION ) || parent . getSort ( ) . isa ( DapSort . GROUP ) || parent . getSort ( ) == DapSort . VARIABLE || parent . getSort ( ) == DapSort . STRUCTURE || parent . getSort ( ) == DapSort . SEQUENCE || this . getSort ( ) == DapSort . ATTRIBUTE || this . getSort ( ) == DapSort . ATTRIBUTESET ) ; this . parent = parent ; }


Input: Here escaped means backslash escaped short name [CODESPLIT] public String getEscapedShortName ( ) { if ( this . escapedname == null ) this . escapedname = Escape . backslashEscape ( getShortName ( ) , null ) ; return this . escapedname ; }


Input: Compute the path upto and including some specified containing node ( null = > root ) The containing node is included as is this node . [CODESPLIT] public List < DapNode > getPath ( ) { List < DapNode > path = new ArrayList < DapNode > ( ) ; DapNode current = this ; for ( ; ; ) { path . add ( 0 , current ) ; current = current . getParent ( ) ; if ( current == null ) break ; } return path ; }


Input: Get the transitive list of containers Not including this node [CODESPLIT] public List < DapNode > getContainerPath ( ) { List < DapNode > path = new ArrayList < DapNode > ( ) ; DapNode current = this . getContainer ( ) ; for ( ; ; ) { path . add ( 0 , current ) ; if ( current . getContainer ( ) == null ) break ; current = current . getContainer ( ) ; } return path ; }


Input: Get the transitive list of containing groups Possibly including this node [CODESPLIT] public List < DapGroup > getGroupPath ( ) { List < DapGroup > path = new ArrayList < DapGroup > ( ) ; DapNode current = this ; for ( ; ; ) { if ( current . getSort ( ) == DapSort . GROUP || current . getSort ( ) == DapSort . DATASET ) path . add ( 0 , ( DapGroup ) current ) ; if ( current . getContainer ( ) == null ) break ; current = current . getContainer ( ) ; } return path ; }


Input: Compute the FQN of this node [CODESPLIT] public String computefqn ( ) { List < DapNode > path = getPath ( ) ; // excludes root/wrt StringBuilder fqn = new StringBuilder ( ) ; DapNode parent = path . get ( 0 ) ; for ( int i = 1 ; i < path . size ( ) ; i ++ ) { // start at 1 to skip root DapNode current = path . get ( i ) ; // Depending on what parent is, use different delimiters switch ( parent . getSort ( ) ) { case DATASET : case GROUP : case ENUMERATION : fqn . append ( ' ' ) ; fqn . append ( Escape . backslashEscape ( current . getShortName ( ) , "/." ) ) ; break ; // These use '.' case STRUCTURE : case SEQUENCE : case ENUMCONST : case VARIABLE : fqn . append ( ' ' ) ; fqn . append ( current . getEscapedShortName ( ) ) ; break ; default : // Others should never happen throw new IllegalArgumentException ( "Illegal FQN parent" ) ; } parent = current ; } return fqn . toString ( ) ; }


Input: Misc . Methods [CODESPLIT] public boolean isTopLevel ( ) { return parent == null || parent . getSort ( ) == DapSort . DATASET || parent . getSort ( ) == DapSort . GROUP ; }


Input: TypedDatasetFactoryIF [CODESPLIT] public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { String convStr = ncd . findAttValueIgnoreCase ( null , "Conventions" , null ) ; if ( ( null != convStr ) && convStr . startsWith ( "CF/Radial" ) ) return this ; return null ; }


Input: _more_ [CODESPLIT] protected void addRadialVariable ( NetcdfDataset nds , Variable var ) { RadialVariable rsvar = null ; String vName = var . getShortName ( ) ; int tIdx = var . findDimensionIndex ( "time" ) ; int rIdx = var . findDimensionIndex ( "range" ) ; int ptsIdx = var . findDimensionIndex ( "n_points" ) ; if ( ( ( tIdx == 0 ) && ( rIdx == 1 ) ) || ( ptsIdx == 0 ) ) { VariableSimpleIF v = new MyRadialVariableAdapter ( vName , var . getAttributes ( ) ) ; rsvar = makeRadialVariable ( nds , v , var ) ; } if ( rsvar != null ) { dataVariables . add ( rsvar ) ; } }


Input: _more_ [CODESPLIT] public String getInfo ( ) { StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( "CFRadial2Dataset\n" ) ; sbuff . append ( super . getDetailInfo ( ) ) ; sbuff . append ( "\n\n" ) ; sbuff . append ( parseInfo . toString ( ) ) ; return sbuff . toString ( ) ; }


Input: Compilation [CODESPLIT] protected void build ( String document , byte [ ] serialdata , ByteOrder order ) throws DapException { DapDataset dmr = parseDMR ( document ) ; if ( DEBUG || DUMPDMR ) { System . err . println ( "\n+++++++++++++++++++++" ) ; System . err . println ( dmr ) ; System . err . println ( "+++++++++++++++++++++\n" ) ; } if ( DEBUG || DUMPDAP ) { ByteBuffer data = ByteBuffer . wrap ( serialdata ) ; System . err . println ( "+++++++++++++++++++++" ) ; System . err . println ( "\n---------------------" ) ; DapDump . dumpbytes ( data , false ) ; System . err . println ( "\n---------------------\n" ) ; } build ( dmr , serialdata , order ) ; }


Input: Build the data from the incoming serial data Note that some DSP s will not use [CODESPLIT] protected void build ( DapDataset dmr , byte [ ] serialdata , ByteOrder order ) throws DapException { setDMR ( dmr ) ; // "Compile" the databuffer section of the server response this . databuffer = ByteBuffer . wrap ( serialdata ) . order ( order ) ; D4DataCompiler compiler = new D4DataCompiler ( this , getChecksumMode ( ) , getOrder ( ) , this . databuffer ) ; compiler . compile ( ) ; }


Input: not tested [CODESPLIT] private void write ( StationObsDataset sobsDataset ) throws IOException { createGlobalAttributes ( ) ; createStations ( sobsDataset . getStations ( ) ) ; ncfile . addGlobalAttribute ( "time_coverage_start" , dateFormatter . toDateTimeStringISO ( sobsDataset . getStartDate ( ) ) ) ; ncfile . addGlobalAttribute ( "time_coverage_end" , dateFormatter . toDateTimeStringISO ( sobsDataset . getEndDate ( ) ) ) ; createDataVariables ( sobsDataset . getDataVariables ( ) ) ; // global attributes List gatts = sobsDataset . getGlobalAttributes ( ) ; for ( int i = 0 ; i < gatts . size ( ) ; i ++ ) { Attribute att = ( Attribute ) gatts . get ( i ) ; ncfile . addGlobalAttribute ( att ) ; } // done with define mode ncfile . create ( ) ; // write out the station info writeStationData ( sobsDataset . getStations ( ) ) ; // now write the observations if ( ! ( Boolean ) ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ) throw new IllegalStateException ( "can't add record variable" ) ; int [ ] origin = new int [ 1 ] ; int [ ] originTime = new int [ 2 ] ; int recno = 0 ; ArrayStructureW sArray = null ; ArrayObject . D1 timeArray = new ArrayObject . D1 ( DataType . STRING , String . class , false , 1 ) ; DataIterator diter = sobsDataset . getDataIterator ( 1000 * 1000 ) ; while ( diter . hasNext ( ) ) { StationObsDatatype sobs = ( StationObsDatatype ) diter . nextData ( ) ; StructureData recordData = sobs . getData ( ) ; // needs to be wrapped as an ArrayStructure, even though we are only writing one at a time. if ( sArray == null ) sArray = new ArrayStructureW ( recordData . getStructureMembers ( ) , new int [ ] { 1 } ) ; sArray . setStructureData ( recordData , 0 ) ; // date is handled specially timeArray . set ( 0 , dateFormatter . toDateTimeStringISO ( sobs . getObservationTimeAsDate ( ) ) ) ; // write the recno record origin [ 0 ] = recno ; originTime [ 0 ] = recno ; try { ncfile . write ( "record" , origin , sArray ) ; ncfile . writeStringData ( timeName , originTime , timeArray ) ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; throw new IllegalStateException ( e ) ; } recno ++ ; } ncfile . close ( ) ; }


Input: Get the object that has the specified key . This returns the object itself not a copy so if you change the bean and call store . save () any changes to the object will be saved even without calling putBean () . If you want to change the object without saving the changes you must make a copy of the object yourself . [CODESPLIT] public Object getBean ( String key , Object def ) { if ( key == null ) throw new NullPointerException ( "Null key" ) ; if ( isRemoved ( ) ) throw new IllegalStateException ( "Node has been removed." ) ; synchronized ( lock ) { Object result = null ; try { result = _getObject ( key ) ; if ( result != null ) { if ( result instanceof Bean . Collection ) result = ( ( Bean . Collection ) result ) . getCollection ( ) ; else if ( result instanceof Bean ) result = ( ( Bean ) result ) . getObject ( ) ; } } catch ( Exception e ) { // Ignoring exception causes default to be returned } return ( result == null ? def : result ) ; } }


Input: Stores an object using simple bean properties . If the exact key and value are already in the storedDefaults ( using equals () to test for equality ) then it is not stored . [CODESPLIT] public void putBean ( String key , Object newValue ) { // if matches a stored Default, dont store Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , new Bean ( newValue ) ) ; }


Input: Stores a Collection of beans . The beans are stored using simple bean properties . The collection of beans must all be of the same class . [CODESPLIT] public void putBeanCollection ( String key , Collection newValue ) { // if matches a stored Default, dont store Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , new Bean . Collection ( newValue ) ) ; }


Input: Stores an object using XMLEncoder / XMLDecoder . Use this for arbitrary objects . If the exact key and value are already in the storedDefaults ( using equals () to test for equality ) then it is not stored . [CODESPLIT] public void putBeanObject ( String key , Object newValue ) { // if matches a stored Default, dont store Object oldValue = getBean ( key , null ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , newValue ) ; }


Input: Get an arrayList . This returns a copy of the stored list . [CODESPLIT] public List getList ( String key , List def ) { try { Object bean = getBean ( key , def ) ; return ( List ) bean ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } }


Input: Implements <tt > AbstractPreferences< / tt > <tt > childrenNamesSpi () < / tt > method . Find all children nodes of this node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected String [ ] childrenNamesSpi ( ) { HashSet allKids = new HashSet ( children . keySet ( ) ) ; PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKids . addAll ( sd . childrenNamesSpi ( absolutePath ( ) ) ) ; ArrayList list = new ArrayList ( allKids ) ; Collections . sort ( list ) ; String result [ ] = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) result [ i ] = list . get ( i ) . toString ( ) ; return result ; }


Input: / * Find all children nodes of named node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected Collection childrenNamesSpi ( String nodePath ) { HashSet allKids = new HashSet ( ) ; try { if ( nodeExists ( nodePath ) ) { PreferencesExt node = ( PreferencesExt ) node ( nodePath ) ; allKids . addAll ( node . children . keySet ( ) ) ; } } catch ( java . util . prefs . BackingStoreException e ) { } PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKids . addAll ( sd . childrenNamesSpi ( nodePath ) ) ; return allKids ; }


Input: / * Find all key names of this node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected String [ ] keysSpi ( ) throws BackingStoreException { HashSet allKeys = new HashSet ( keyValues . keySet ( ) ) ; //show( "allKeys1 ", allKeys); PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) allKeys . addAll ( sd . keysSpi ( absolutePath ( ) ) ) ; //show( "allKeys2 ", allKeys); ArrayList list = new ArrayList ( allKeys ) ; Collections . sort ( list ) ; //show( "allKeys3 ", list); String result [ ] = new String [ list . size ( ) ] ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) result [ i ] = list . get ( i ) . toString ( ) ; return result ; }


Input: / * Find all keys of named node ( or of identically named nodes in storedDefaults ) [CODESPLIT] protected Collection keysSpi ( String nodePath ) { HashSet allKeys = new HashSet ( ) ; try { if ( nodeExists ( nodePath ) ) { PreferencesExt node = ( PreferencesExt ) node ( nodePath ) ; //show( "subKeys1 "+nodePath, node.keyValues.keySet()); allKeys . addAll ( node . keyValues . keySet ( ) ) ; } } catch ( java . util . prefs . BackingStoreException e ) { } PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) { allKeys . addAll ( sd . keysSpi ( nodePath ) ) ; //show( "subKeys2 ", allKeys); } return allKeys ; }


Input: / * Returns the named child of this preference node creating it if it does not already exist . It is guaranteed that name is non - null non - empty does not contain the slash character ( / ) and is no longer than Preferences . MAX_NAME_LENGTH characters . Also it is guaranteed that this node has not been removed . ( The implementor needn t check for any of these things . ) [CODESPLIT] protected AbstractPreferences childSpi ( String name ) { PreferencesExt child ; if ( null != ( child = ( PreferencesExt ) children . get ( name ) ) ) return child ; child = new PreferencesExt ( this , name ) ; children . put ( name , child ) ; child . newNode = true ; return child ; }


Input: / * Gets the value with this keyName if not found look in storedDefaults . [CODESPLIT] protected String getSpi ( String keyName ) { Object o = _getObject ( keyName ) ; return ( o == null ) ? null : o . toString ( ) ; }


Input: / * Stores the value with this key if not already in storedDefaults . [CODESPLIT] protected void putSpi ( String key , String newValue ) { // if matches a stored Default, dont store String oldValue = getSpi ( key ) ; if ( ( oldValue == null ) || ! oldValue . equals ( newValue ) ) keyValues . put ( key , newValue ) ; }


Input: / * removes node no effect on storedDefaults [CODESPLIT] protected void removeNodeSpi ( ) throws BackingStoreException { //System.out.println(" removeNodeSpi :"+name()); if ( parent != null ) { if ( null == parent . children . remove ( name ( ) ) ) System . out . println ( "ERROR PreferencesExt.removeNodeSpi :" + name ( ) ) ; } }


Input: assume key non - null locked node [CODESPLIT] private Object _getObject ( String keyName ) { Object result = null ; try { result = keyValues . get ( keyName ) ; if ( result == null ) { // if failed, check the stored Defaults PreferencesExt sd = getStoredDefaults ( ) ; if ( sd != null ) result = sd . getObjectFromNode ( absolutePath ( ) , keyName ) ; } } catch ( Exception e ) { // Ignoring exception causes default to be returned } return result ; }


Input: isolate dependencies here - in case we have a minimal I / O mode where not all fields are available [CODESPLIT] public float [ ] readData ( RandomAccessFile raf ) throws IOException { Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drss . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drss . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drss . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( gds . isThin ( ) ) data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , GribData . getInterpolationMethod ( ) ) ; lastRecordRead = this ; return data ; }


Input: debugging - do not use [CODESPLIT] @ Nullable public int [ ] readRawData ( RandomAccessFile raf ) throws IOException { Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drss . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drss . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drss . getDrs ( raf ) ; return reader . getRawData ( raf , bms , gdrs ) ; }


Input: Read data array [CODESPLIT] public float [ ] readData ( RandomAccessFile raf , long drsPos ) throws IOException { raf . seek ( drsPos ) ; Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation ( raf ) ; Grib2SectionBitMap bms = new Grib2SectionBitMap ( raf ) ; Grib2SectionData dataSection = new Grib2SectionData ( raf ) ; Grib2Gds gds = getGDS ( ) ; Grib2DataReader reader = new Grib2DataReader ( drs . getDataTemplate ( ) , gdss . getNumberPoints ( ) , drs . getDataPoints ( ) , getScanMode ( ) , gds . getNxRaw ( ) , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drs . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( gds . isThin ( ) ) data = QuasiRegular . convertQuasiGrid ( data , gds . getNptsInLine ( ) , gds . getNxRaw ( ) , gds . getNyRaw ( ) , GribData . getInterpolationMethod ( ) ) ; lastRecordRead = this ; return data ; }


Input: Read data array : use when you want to be independent of the GribRecord [CODESPLIT] public static float [ ] readData ( RandomAccessFile raf , long drsPos , long bmsPos , int gdsNumberPoints , int scanMode , int nx , int ny , int [ ] nptsInLine ) throws IOException { raf . seek ( drsPos ) ; Grib2SectionDataRepresentation drs = new Grib2SectionDataRepresentation ( raf ) ; Grib2SectionBitMap bms = new Grib2SectionBitMap ( raf ) ; Grib2SectionData dataSection = new Grib2SectionData ( raf ) ; if ( bmsPos > 0 ) bms = Grib2SectionBitMap . factory ( raf , bmsPos ) ; Grib2DataReader reader = new Grib2DataReader ( drs . getDataTemplate ( ) , gdsNumberPoints , drs . getDataPoints ( ) , scanMode , nx , dataSection . getStartingPosition ( ) , dataSection . getMsgLength ( ) ) ; Grib2Drs gdrs = drs . getDrs ( raf ) ; float [ ] data = reader . getData ( raf , bms , gdrs ) ; if ( nptsInLine != null ) data = QuasiRegular . convertQuasiGrid ( data , nptsInLine , nx , ny , GribData . getInterpolationMethod ( ) ) ; if ( getlastRecordRead ) lastRecordRead = Grib2RecordScanner . findRecordByDrspos ( raf , drsPos ) ; return data ; }


Input: Print data from a DSP - optionally constrained [CODESPLIT] public DSPPrinter print ( ) throws DapException { DapDataset dmr = this . dsp . getDMR ( ) ; if ( this . ce == null ) this . ce = CEConstraint . getUniversal ( dmr ) ; this . printer . setIndent ( 0 ) ; List < DapVariable > topvars = dmr . getTopVariables ( ) ; for ( int i = 0 ; i < topvars . size ( ) ; i ++ ) { DapVariable top = topvars . get ( i ) ; List < Slice > slices = this . ce . getConstrainedSlices ( top ) ; if ( this . ce . references ( top ) ) { DataCursor data = dsp . getVariableData ( top ) ; printVariable ( data , slices ) ; } } printer . eol ( ) ; return this ; }


Input: Print an arbitrary DataVariable using a constraint . <p > Handling newlines is a bit tricky so the rule is that the last newline is elided and left for the caller to print . Exceptions : ? [CODESPLIT] protected void printVariable ( DataCursor data , List < Slice > slices ) throws DapException { DapVariable dapv = ( DapVariable ) data . getTemplate ( ) ; if ( data . isScalar ( ) ) { assert slices == Slice . SCALARSLICES ; printScalar ( data ) ; } else { // not scalar printArray ( data , slices ) ; } }


Input: Print a single structure or sequence or record instance [CODESPLIT] protected void printCompoundInstance ( DataCursor datav ) throws DapException { //Index index = datav.getIndex(); DapStructure dstruct = ( DapStructure ) ( ( DapVariable ) datav . getTemplate ( ) ) . getBaseType ( ) ; switch ( datav . getScheme ( ) ) { case STRUCTURE : case RECORD : List < DapVariable > dfields = dstruct . getFields ( ) ; for ( int f = 0 ; f < dfields . size ( ) ; f ++ ) { DapVariable field = dfields . get ( f ) ; List < Slice > fieldslices = this . ce . getConstrainedSlices ( field ) ; DataCursor fdata = datav . readField ( f ) ; printVariable ( fdata , fieldslices ) ; } break ; case SEQUENCE : DapSequence dseq = ( DapSequence ) dstruct ; long count = datav . getRecordCount ( ) ; for ( long r = 0 ; r < count ; r ++ ) { DataCursor dr = datav . readRecord ( r ) ; printer . marginPrint ( "[" ) ; printer . eol ( ) ; printer . indent ( ) ; printCompoundInstance ( dr ) ; printer . outdent ( ) ; printer . marginPrint ( "]" ) ; } break ; default : throw new DapException ( "Unexpected data cursor scheme:" + datav . getScheme ( ) ) ; } }


Input: copy constructor - avoid clone !! [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { // constructor takes sweep_angle_axis, so need to translate between // scan geometry and sweep_angle_axis first // GOES: x // GEOS: y String sweepAxisAngle = GEOSTransform . scanGeomToSweepAngleAxis ( navigation . scan_geom ) ; return new Geostationary ( navigation . sub_lon_degrees , sweepAxisAngle , geoCoordinateScaleFactor ) ; }


Input: Writes an NcML element to a string . [CODESPLIT] public String writeToString ( Element elem ) { try ( StringWriter writer = new StringWriter ( ) ) { writeToWriter ( elem , writer ) ; return writer . toString ( ) ; } catch ( IOException e ) { throw new AssertionError ( "CAN'T HAPPEN: StringWriter.close() is a no-op." , e ) ; } }


Input: Writes an NcML element to an output file . [CODESPLIT] public void writeToFile ( Element elem , File outFile ) throws IOException { try ( OutputStream outStream = new BufferedOutputStream ( new FileOutputStream ( outFile , false ) ) ) { writeToStream ( elem , outStream ) ; } }


Input: Writes an NcML element to an output stream . [CODESPLIT] public void writeToStream ( Element elem , OutputStream outStream ) throws IOException { try ( Writer writer = new BufferedWriter ( new OutputStreamWriter ( new BufferedOutputStream ( outStream ) , xmlFormat . getEncoding ( ) ) ) ) { writeToWriter ( elem , writer ) ; } }


Input:
Writes an NcML element to a Writer . [CODESPLIT] public void writeToWriter ( Element elem , Writer writer ) throws IOException { xmlOutputter . setFormat ( xmlFormat ) ; elem . detach ( ) ; // In case this element had previously been added to a Document.
 xmlOutputter . output ( new Document ( elem ) , writer ) ; }


Input: ////////////////////////////////////// Element creation //////////////////////////////////////// [CODESPLIT] public Element makeExplicitNetcdfElement ( NetcdfFile ncFile , String location ) { Element netcdfElem = makeNetcdfElement ( ncFile , location ) ; netcdfElem . addContent ( 0 , new Element ( "explicit" , namespace ) ) ; return netcdfElem ; }


Input:
enum Typedef [CODESPLIT] public Element makeEnumTypedefElement ( EnumTypedef etd ) { Element typeElem = new Element ( "enumTypedef" , namespace ) ; typeElem . setAttribute ( "name" , etd . getShortName ( ) ) ; typeElem . setAttribute ( "type" , etd . getBaseType ( ) . toString ( ) ) ; // Use a TreeMap so that the key-value pairs are emitted in a consistent order.
 TreeMap < Integer , String > map = new TreeMap <> ( etd . getMap ( ) ) ; for ( Map . Entry < Integer , String > entry : map . entrySet ( ) ) { typeElem . addContent ( new Element ( "enum" , namespace ) . setAttribute ( "key" , Integer . toString ( entry . getKey ( ) ) ) . addContent ( entry . getValue ( ) ) ) ; } return typeElem ; }


Input: Only for shared dimensions . [CODESPLIT] public Element makeDimensionElement ( Dimension dim ) throws IllegalArgumentException { if ( ! dim . isShared ( ) ) { throw new IllegalArgumentException ( "Cannot create private dimension: " + "in NcML, <dimension> elements are always shared." ) ; } Element dimElem = new Element ( "dimension" , namespace ) ; dimElem . setAttribute ( "name" , dim . getShortName ( ) ) ; dimElem . setAttribute ( "length" , Integer . toString ( dim . getLength ( ) ) ) ; if ( dim . isUnlimited ( ) ) dimElem . setAttribute ( "isUnlimited" , "true" ) ; return dimElem ; }


Input:
Creates a { @code <values > } element from the variable s data . [CODESPLIT] public Element makeValuesElement ( Variable variable , boolean allowRegular ) throws IOException { Element elem = new Element ( "values" , namespace ) ; StringBuilder buff = new StringBuilder ( ) ; Array a = variable . read ( ) ; if ( variable . getDataType ( ) == DataType . CHAR ) { char [ ] data = ( char [ ] ) a . getStorage ( ) ; elem . setText ( new String ( data ) ) ; } else if ( variable . getDataType ( ) == DataType . STRING ) { elem . setAttribute ( "separator" , "|" ) ; int count = 0 ; for ( IndexIterator iter = a . getIndexIterator ( ) ; iter . hasNext ( ) ; ) { if ( count ++ > 0 ) { buff . append ( "|" ) ; } buff . append ( iter . getObjectNext ( ) ) ; } elem . setText ( buff . toString ( ) ) ; } else { //check to see if regular
 if ( allowRegular && ( a . getRank ( ) == 1 ) && ( a . getSize ( ) > 2 ) ) { Index ima = a . getIndex ( ) ; double start = a . getDouble ( ima . set ( 0 ) ) ; double incr = a . getDouble ( ima . set ( 1 ) ) - start ; boolean isRegular = true ; for ( int i = 2 ; i < a . getSize ( ) ; i ++ ) { double v1 = a . getDouble ( ima . set ( i ) ) ; double v0 = a . getDouble ( ima . set ( i - 1 ) ) ; if ( ! ucar . nc2 . util . Misc . nearlyEquals ( v1 - v0 , incr ) ) isRegular = false ; } if ( isRegular ) { elem . setAttribute ( "start" , Double . toString ( start ) ) ; elem . setAttribute ( "increment" , Double . toString ( incr ) ) ; elem . setAttribute ( "npts" , Long . toString ( variable . getSize ( ) ) ) ; return elem ; } } // not regular
 boolean isRealType = ( variable . getDataType ( ) == DataType . DOUBLE ) || ( variable . getDataType ( ) == DataType . FLOAT ) ; IndexIterator iter = a . getIndexIterator ( ) ; buff . append ( isRealType ? iter . getDoubleNext ( ) : iter . getIntNext ( ) ) ; while ( iter . hasNext ( ) ) { buff . append ( " " ) ; buff . append ( isRealType ? iter . getDoubleNext ( ) : iter . getIntNext ( ) ) ; } elem . setText ( buff . toString ( ) ) ; } // not string
 return elem ; }


Input: wml2 : MeasurementTVP / wml2 : value [CODESPLIT] public static MeasureType initValue ( MeasureType value , PointFeature pointFeat , VariableSimpleIF dataVar ) throws IOException { // TEXT StructureMembers . Member firstDataMember = pointFeat . getDataAll ( ) . findMember ( dataVar . getShortName ( ) ) ; assert firstDataMember != null : String . format ( "%s appeared in the list of data variables but not in the StructureData." , dataVar . getShortName ( ) ) ; Array dataArray = pointFeat . getDataAll ( ) . getArray ( firstDataMember ) ; assert dataArray . getSize ( ) == 1 : String . format ( "Expected array to be scalar, but its shape was %s." , Arrays . toString ( dataArray . getShape ( ) ) ) ; double dataVal = dataArray . getDouble ( 0 ) ; value . setDoubleValue ( dataVal ) ; return value ; }


Input:
Make the coordinate transform [CODESPLIT] public ProjectionCT makeCoordinateTransform ( AttributeContainer ctv , String units ) { int [ ] area = getIntArray ( ctv , McIDASAreaProjection . ATTR_AREADIR ) ; int [ ] nav = getIntArray ( ctv , McIDASAreaProjection . ATTR_NAVBLOCK ) ; int [ ] aux = null ; if ( ctv . findAttributeIgnoreCase ( McIDASAreaProjection . ATTR_AUXBLOCK ) != null ) { aux = getIntArray ( ctv , McIDASAreaProjection . ATTR_AUXBLOCK ) ; } // not clear if its ok if aux is null, coverity is complaining
 McIDASAreaProjection proj = new McIDASAreaProjection ( area , nav , aux ) ; return new ProjectionCT ( ctv . getName ( ) , "FGDC" , proj ) ; }


Input: get the int array from the variable attribute [CODESPLIT] private int [ ] getIntArray ( AttributeContainer ctv , String attName ) { Attribute att = ctv . findAttribute ( attName ) ; if ( att == null ) { throw new IllegalArgumentException ( "McIDASArea coordTransformVariable " + ctv . getName ( ) + " must have " + attName + " attribute" ) ; } Array arr = att . getValues ( ) ; return ( int [ ] ) arr . get1DJavaArray ( int . class ) ; }


Input:
Vert [CODESPLIT] @ Override public VertCoordType getVertUnit ( int code ) { switch ( code ) { case 235 : return new VertCoordType ( code , "0.1 C" , null , true ) ; case 237 : return new VertCoordType ( code , "m" , null , true ) ; case 238 : return new VertCoordType ( code , "m" , null , true ) ; case 241 : return new VertCoordType ( code , "count" , null , true ) ; // eg see NCEP World Watch datasets
 default : return super . getVertUnit ( code ) ; } }


Input: shared by all instances [CODESPLIT] @ Override @ Nullable public String getStatisticName ( int id ) { if ( id < 192 ) return super . getStatisticName ( id ) ; if ( statName == null ) statName = initTable410 ( ) ; if ( statName == null ) return null ; return statName . get ( id ) ; }


Input: shared by all instances [CODESPLIT] @ Override @ Nullable public String getGeneratingProcessName ( int genProcess ) { if ( genProcessMap == null ) genProcessMap = NcepTables . getNcepGenProcess ( ) ; if ( genProcessMap == null ) return null ; return genProcessMap . get ( genProcess ) ; }