Input: Transform fractional FGF coordinates to ( lamda theta ) radians . [CODESPLIT] public double [ ] FGFtoSat ( double fgf_x , double fgf_y , double scale_x , double offset_x , double scale_y , double offset_y ) { double x = fgf_x * scale_x + offset_x ; double y = fgf_y * scale_y + offset_y ; return new double [ ] { x , y } ; }


Input: Transform integer FGF coordinates to ( longitude latitude ) of pixel center The ( i j ) pixel zero - based refers to the pixel center . [CODESPLIT] public double [ ] elemLineToEarth ( int elem , int line , double scale_x , double offset_x , double scale_y , double offset_y ) { return FGFtoEarth ( ( double ) elem , ( double ) line , scale_x , offset_x , scale_y , offset_y ) ; }


Input: Transform Earth coordinates ( lon lat ) to fractional FGF coordinates . [CODESPLIT] public double [ ] earthToFGF ( double geographic_lon , double geographic_lat , double scale_x , double offset_x , double scale_y , double offset_y ) { double [ ] xy = earthToSat ( geographic_lon , geographic_lat ) ; return SatToFGF ( xy [ 0 ] , xy [ 1 ] , scale_x , offset_x , scale_y , offset_y ) ; }


Input: Transform pixel center Earth coordinates ( lon lat ) to integer FGF coordinates . [CODESPLIT] public int [ ] earthToElemLine ( double geographic_lon , double geographic_lat , double scale_x , double offset_x , double scale_y , double offset_y ) { double [ ] fgf = earthToFGF ( geographic_lon , geographic_lat , scale_x , offset_x , scale_y , offset_y ) ; int elem = ( int ) Math . floor ( fgf [ 0 ] + 0.5 ) ; int line = ( int ) Math . floor ( fgf [ 1 ] + 0.5 ) ; return new int [ ] { elem , line } ; }


Input: Transform ( lamda theta ) in radians to fractional FGF coordinates . [CODESPLIT] public double [ ] SatToFGF ( double lamda , double theta , double scale_x , double offset_x , double scale_y , double offset_y ) { double fgf_x = ( lamda - offset_x ) / scale_x ; double fgf_y = ( theta - offset_y ) / scale_y ; return new double [ ] { fgf_x , fgf_y } ; }


Input: Find sweep_angle_axis associated with a scan geometry [CODESPLIT] public static String scanGeomToSweepAngleAxis ( String scanGeometry ) { String sweepAngleAxis = "y" ; if ( scanGeometry . equals ( GOES ) ) { sweepAngleAxis = "x" ; } return sweepAngleAxis ; }


Input: Find scan geometry associated with sweep_angle_axis [CODESPLIT] public static String sweepAngleAxisToScanGeom ( String sweepAngleAxis ) { String scanGeom = GOES ; if ( sweepAngleAxis . equals ( "y" ) ) { scanGeom = GEOS ; } return scanGeom ; }


Input: set the list of runtime coordinates ; add any that are not already present and make an empty CoordinateTimeAbstract for it [CODESPLIT] void setRuntimeCoords ( CoordinateRuntime runtimes ) { for ( int idx = 0 ; idx < runtimes . getSize ( ) ; idx ++ ) { CalendarDate cd = runtimes . getRuntimeDate ( idx ) ; long runtime = runtimes . getRuntime ( idx ) ; CoordinateTimeAbstract time = timeMap . get ( runtime ) ; if ( time == null ) { time = isTimeInterval ? new CoordinateTimeIntv ( this . code , this . timeUnit , cd , new ArrayList <> ( 0 ) , null ) : new CoordinateTime ( this . code , this . timeUnit , cd , new ArrayList <> ( 0 ) , null ) ; timeMap . put ( runtime , time ) ; } } }


Input: Open a ucar . nc2 . dt . PointObsDataset write out in CF point format . [CODESPLIT] public static boolean rewritePointObsDataset ( String fileIn , String fileOut , boolean inMemory ) throws IOException { System . out . println ( "Rewrite2 .nc files from " + fileIn + " to " + fileOut + " inMemory= " + inMemory ) ; long start = System . currentTimeMillis ( ) ; // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile . openInMemory ( fileIn ) : NetcdfFile . open ( fileIn ) ; NetcdfDataset ncd = new NetcdfDataset ( ncfile ) ; StringBuilder errlog = new StringBuilder ( ) ; PointObsDataset pobsDataset = ( PointObsDataset ) TypedDatasetFactory . open ( FeatureType . POINT , ncd , null , errlog ) ; if ( pobsDataset == null ) return false ; writePointObsDataset ( pobsDataset , fileOut ) ; pobsDataset . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . println ( " that took " + ( took - start ) + " msecs" ) ; return true ; }


Input: write data from a ucar . nc2 . dt . PointObsDataset into CF point format . [CODESPLIT] public static void writePointObsDataset ( PointObsDataset pobsDataset , String fileOut ) throws IOException { // see if we have an altitude String altUnits = null ; DataIterator iterOne = pobsDataset . getDataIterator ( - 1 ) ; while ( iterOne . hasNext ( ) ) { PointObsDatatype pobsData = ( PointObsDatatype ) iterOne . nextData ( ) ; ucar . unidata . geoloc . EarthLocation loc = pobsData . getLocation ( ) ; altUnits = Double . isNaN ( loc . getAltitude ( ) ) ? null : "meters" ; break ; } List < VariableSimpleIF > vars = pobsDataset . getDataVariables ( ) ; List < PointObVar > nvars = new ArrayList < PointObVar > ( vars . size ( ) ) ; // put vars in order for ( VariableSimpleIF v : vars ) { if ( v . getDataType ( ) . isNumeric ( ) ) nvars . add ( new PointObVar ( v ) ) ; } int ndoubles = vars . size ( ) ; double [ ] dvals = new double [ ndoubles ] ; for ( VariableSimpleIF v : vars ) { if ( v . getDataType ( ) . isString ( ) ) nvars . add ( new PointObVar ( v ) ) ; } String [ ] svals = new String [ vars . size ( ) - ndoubles ] ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( fos ) ; CFPointObWriter writer = new CFPointObWriter ( out , pobsDataset . getGlobalAttributes ( ) , altUnits , nvars , - 1 ) ; DataIterator iter = pobsDataset . getDataIterator ( 1000 * 1000 ) ; while ( iter . hasNext ( ) ) { PointObsDatatype pobsData = ( PointObsDatatype ) iter . nextData ( ) ; StructureData sdata = pobsData . getData ( ) ; int dcount = 0 ; int scount = 0 ; for ( PointObVar v : nvars ) { if ( v . getDataType ( ) . isNumeric ( ) ) { Array data = sdata . getArray ( v . getName ( ) ) ; data . resetLocalIterator ( ) ; if ( data . hasNext ( ) ) dvals [ dcount ++ ] = data . nextDouble ( ) ; } else if ( v . getDataType ( ) . isString ( ) ) { ArrayChar data = ( ArrayChar ) sdata . getArray ( v . getName ( ) ) ; svals [ scount ++ ] = data . getString ( ) ; } } ucar . unidata . geoloc . EarthLocation loc = pobsData . getLocation ( ) ; writer . addPoint ( loc . getLatitude ( ) , loc . getLongitude ( ) , loc . getAltitude ( ) , pobsData . getObservationTimeAsDate ( ) , dvals , svals ) ; } writer . finish ( ) ; }


Input: Open a ucar . nc2 . ft . PointFeatureCollection write out in CF point format . [CODESPLIT] public static boolean rewritePointFeatureDataset ( String fileIn , String fileOut , boolean inMemory ) throws IOException { System . out . println ( "Rewrite2 .nc files from " + fileIn + " to " + fileOut + " inMemory= " + inMemory ) ; long start = System . currentTimeMillis ( ) ; // do it in memory for speed NetcdfFile ncfile = inMemory ? NetcdfFile . openInMemory ( fileIn ) : NetcdfFile . open ( fileIn ) ; NetcdfDataset ncd = new NetcdfDataset ( ncfile ) ; Formatter errlog = new Formatter ( ) ; FeatureDataset fd = FeatureDatasetFactoryManager . wrap ( FeatureType . ANY_POINT , ncd , null , errlog ) ; if ( fd == null ) return false ; if ( fd instanceof FeatureDatasetPoint ) { writePointFeatureCollection ( ( FeatureDatasetPoint ) fd , fileOut ) ; fd . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . println ( " that took " + ( took - start ) + " msecs" ) ; return true ; } return false ; }


Input:
Write a ucar . nc2 . ft . PointFeatureCollection in CF point format . [CODESPLIT] public static int writePointFeatureCollection ( FeatureDatasetPoint pfDataset , String fileOut ) throws IOException { // extract the PointFeatureCollection PointFeatureCollection pointFeatureCollection = null ; List < DsgFeatureCollection > featureCollectionList = pfDataset . getPointFeatureCollectionList ( ) ; for ( DsgFeatureCollection featureCollection : featureCollectionList ) { if ( featureCollection instanceof PointFeatureCollection ) pointFeatureCollection = ( PointFeatureCollection ) featureCollection ; } if ( null == pointFeatureCollection ) throw new IOException ( "There is no PointFeatureCollection in  " + pfDataset . getLocation ( ) ) ; long start = System . currentTimeMillis ( ) ; FileOutputStream fos = new FileOutputStream ( fileOut ) ; DataOutputStream out = new DataOutputStream ( new BufferedOutputStream ( fos , 10000 ) ) ; WriterCFPointDataset writer = null ; /* LOOK BAD
    List<VariableSimpleIF> dataVars = new ArrayList<VariableSimpleIF>();
    ucar.nc2.NetcdfFile ncfile = pfDataset.getNetcdfFile();
    if ((ncfile == null) || !(ncfile instanceof NetcdfDataset))  {
      dataVars.addAll(pfDataset.getDataVariables());
    } else {
      NetcdfDataset ncd = (NetcdfDataset) ncfile;
      for (VariableSimpleIF vs : pfDataset.getDataVariables()) {
        if (ncd.findCoordinateAxis(vs.getName()) == null)
          dataVars.add(vs);
      }
    } */ int count = 0 ; for ( PointFeature pointFeature : pointFeatureCollection ) { StructureData data = pointFeature . getDataAll ( ) ; if ( count == 0 ) { EarthLocation loc = pointFeature . getLocation ( ) ; // LOOK we dont know this until we see the obs String altUnits = Double . isNaN ( loc . getAltitude ( ) ) ? null : "meters" ; // LOOK units may be wrong writer = new WriterCFPointDataset ( out , pfDataset . getGlobalAttributes ( ) , altUnits ) ; writer . writeHeader ( pfDataset . getDataVariables ( ) , - 1 ) ; } writer . writeRecord ( pointFeature , data ) ; count ++ ; } writer . finish ( ) ; out . flush ( ) ; out . close ( ) ; long took = System . currentTimeMillis ( ) - start ; System . out . printf ( "Write %d records from %s to %s took %d msecs %n" , count , pfDataset . getLocation ( ) , fileOut , took ) ; return count ; }


Input: Get member data array of any type as an Array . For more efficiency use getScalarXXX ( Member ) or getJavaArrayXXX ( Member ) is possible . [CODESPLIT] public Array getArray ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( "illegal member name =" + memberName ) ; return getArray ( m ) ; }


Input: Get member data array of any type as an Object eg Float Double String etc . [CODESPLIT] public Object getScalarObject ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( "illegal member name =" + memberName ) ; return getScalarObject ( m ) ; }


Input: Get member data array of any type as an Object eg Float Double String etc . [CODESPLIT] public Object getScalarObject ( StructureMembers . Member m ) { DataType dataType = m . getDataType ( ) ; //boolean isScalar = m.isScalar(); if ( dataType == DataType . DOUBLE ) { return getScalarDouble ( m ) ; } else if ( dataType == DataType . FLOAT ) { return getScalarFloat ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == byte . class ) { return getScalarByte ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { return getScalarShort ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { return getScalarInt ( m ) ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { return getScalarLong ( m ) ; } else if ( dataType == DataType . CHAR ) { return getScalarString ( m ) ; } else if ( dataType == DataType . STRING ) { return getScalarString ( m ) ; } else if ( dataType == DataType . STRUCTURE ) { return getScalarStructure ( m ) ; } else if ( dataType == DataType . SEQUENCE ) { return getArraySequence ( m ) ; } throw new RuntimeException ( "Dont have implemenation for " + dataType ) ; }


Input: Get scalar value as a float with conversion as needed . Underlying type must be convertible to float . [CODESPLIT] public float convertScalarFloat ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( "illegal member name =" + memberName ) ; return convertScalarFloat ( m ) ; }


Input: Get String value from rank 0 String or rank 1 char member array . [CODESPLIT] public String getScalarString ( String memberName ) { StructureMembers . Member m = findMember ( memberName ) ; if ( null == m ) throw new IllegalArgumentException ( "Member not found= " + memberName ) ; return getScalarString ( m ) ; }


Input: Get member data of type Structure . [CODESPLIT] public StructureData getScalarStructure ( String memberName ) { StructureMembers . Member m = findMember ( memberName ) ; if ( null == m ) throw new IllegalArgumentException ( "Member not found= " + memberName ) ; return getScalarStructure ( m ) ; }


Input: Get member data of type Structure . [CODESPLIT] public ArrayStructure getArrayStructure ( String memberName ) { StructureMembers . Member m = findMember ( memberName ) ; if ( null == m ) throw new IllegalArgumentException ( "Member not found= " + memberName ) ; return getArrayStructure ( m ) ; }


Input: Get ArraySequence for a member of type Sequence . [CODESPLIT] public ArraySequence getArraySequence ( String memberName ) { StructureMembers . Member m = members . findMember ( memberName ) ; if ( m == null ) throw new IllegalArgumentException ( "illegal member name =" + memberName ) ; return getArraySequence ( m ) ; }


Input: debugging [CODESPLIT] public void showInternal ( Formatter f , Indent indent ) { f . format ( "%sStructureData %s class=%s hash=0x%x%n" , indent , members . getName ( ) , this . getClass ( ) . getName ( ) , hashCode ( ) ) ; }


Input: Get the full heirarchical name of the dataset which has all parent collection names . [CODESPLIT] public String getFullName ( ) { return ( parent == null ) ? name : ( parent . getFullName ( ) == null || parent . getFullName ( ) . length ( ) == 0 ) ? name : parent . getFullName ( ) + "/" + name ; }


Input: If this dataset has an authority and an ID then the concatenation of them is the globally unique ID . [CODESPLIT] public String getUniqueID ( ) { String authority = getAuthority ( ) ; if ( ( authority != null ) && ( getID ( ) != null ) ) return authority + ":" + getID ( ) ; else if ( getID ( ) != null ) return getID ( ) ; else return null ; }


Input: Get access element of the specified service type for this dataset . If more than one get the first one . [CODESPLIT] public InvAccess getAccess ( thredds . catalog . ServiceType type ) { for ( InvAccess a : getAccess ( ) ) { InvService s = a . getService ( ) ; if ( s . getServiceType ( ) == type ) return a ; } return null ; }


Input: Get access element that matches the given access standard URL . Match on a . getStandardUrlName () . [CODESPLIT] public InvAccess findAccess ( String accessURL ) { for ( InvAccess a : getAccess ( ) ) { if ( accessURL . equals ( a . getStandardUrlName ( ) ) ) return a ; } return null ; }


Input: Find an immediate child dataset by its name . [CODESPLIT] public InvDatasetImpl findDatasetByName ( String name ) { for ( InvDataset ds : getDatasets ( ) ) { if ( ds . getName ( ) . equals ( name ) ) return ( InvDatasetImpl ) ds ; } return null ; }


Input: Get containing catalog . [CODESPLIT] public InvCatalog getParentCatalog ( ) { if ( catalog != null ) return catalog ; return ( parent != null ) ? parent . getParentCatalog ( ) : null ; }


Input: Get the metadata elements of the specified type . [CODESPLIT] public java . util . List < InvMetadata > getMetadata ( thredds . catalog . MetadataType want ) { List < InvMetadata > result = new ArrayList < InvMetadata > ( ) ; for ( InvMetadata m : getMetadata ( ) ) { MetadataType mtype = MetadataType . getType ( m . getMetadataType ( ) ) ; if ( mtype == want ) result . add ( m ) ; } return result ; }


Input: Find the named service declared in this dataset or one of its parents . [CODESPLIT] public InvService findService ( String name ) { if ( name == null ) return null ; // search local (but expanded) services for ( InvService p : services ) { if ( p . getName ( ) . equals ( name ) ) return p ; } // not found, look in parent if ( parent != null ) return parent . findService ( name ) ; return ( catalog == null ) ? null : catalog . findService ( name ) ; }


Input: Return the resource control value which indicates that only users with proper permission can access this resource . <p / > ??? Not sure if the value indicates anything or just set or not set . [CODESPLIT] public String getRestrictAccess ( ) { if ( restrictAccess != null ) return restrictAccess ; // not found, look in parent if ( parent != null ) return parent . getRestrictAccess ( ) ; return null ; }


Input: get Variables from the specified vocabulary [CODESPLIT] public ThreddsMetadata . Variables getVariables ( String vocab ) { ThreddsMetadata . Variables result = new ThreddsMetadata . Variables ( vocab , null , null , null , null ) ; if ( variables == null ) return result ; for ( ThreddsMetadata . Variables vs : variables ) { if ( vs . getVocabulary ( ) . equals ( vocab ) ) result . getVariableList ( ) . addAll ( vs . getVariableList ( ) ) ; } return result ; }


Input: private LatLonPointImpl origin ; // why are we keeping this? [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new FlatEarth ( getOriginLat ( ) , getOriginLon ( ) , getRotationAngle ( ) ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }


Input: Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double dx , dy ; fromLat = Math . toRadians ( fromLat ) ; dy = radius * ( fromLat - lat0 ) ; dx = radius * Math . cos ( fromLat ) * ( Math . toRadians ( fromLon ) - lon0 ) ; toX = cosRot * dx - sinRot * dy ; toY = sinRot * dx + cosRot * dy ; result . setLocation ( toX , toY ) ; return result ; }


Input: Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double x = world . getX ( ) ; double y = world . getY ( ) ; double cosl ; int TOLERENCE = 1 ; double xp , yp ; xp = cosRot * x + sinRot * y ; yp = - sinRot * x + cosRot * y ; toLat = Math . toDegrees ( lat0 ) + Math . toDegrees ( yp / radius ) ; //double lat2; //lat2 = lat0 + Math.toDegrees(yp/radius); cosl = Math . cos ( Math . toRadians ( toLat ) ) ; if ( Math . abs ( cosl ) < TOLERANCE ) { toLon = Math . toDegrees ( lon0 ) ; } else { toLon = Math . toDegrees ( lon0 ) + Math . toDegrees ( xp / cosl / radius ) ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double dy = radius * ( fromLat - lat0 ) ; double dx = radius * Math . cos ( fromLat ) * ( Math . toRadians ( fromLon ) - lon0 ) ; toX = cosRot * dx - sinRot * dy ; toY = sinRot * dx + cosRot * dy ; resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] projToLatLon ( double [ ] [ ] from , double [ ] [ ] to ) { int cnt = from [ 0 ] . length ; double [ ] fromXA = from [ INDEX_X ] ; double [ ] fromYA = from [ INDEX_Y ] ; double [ ] toLatA = to [ INDEX_LAT ] ; double [ ] toLonA = to [ INDEX_LON ] ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] ; double fromY = fromYA [ i ] ; double xp = cosRot * fromX + sinRot * fromY ; double yp = - sinRot * fromX + cosRot * fromY ; //toLat =  lat0 + Math.toDegrees(yp); toLat = Math . toDegrees ( lat0 ) + Math . toDegrees ( yp / radius ) ; double cosl = Math . cos ( Math . toRadians ( toLat ) ) ; if ( Math . abs ( cosl ) < TOLERANCE ) { toLon = Math . toDegrees ( lon0 ) ; } else { toLon = Math . toDegrees ( lon0 ) + Math . toDegrees ( xp / cosl / radius ) ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; toLatA [ i ] = toLat ; toLonA [ i ] = toLon ; } return to ; }


Input: Test [CODESPLIT] public static void main ( String [ ] args ) { FlatEarth a = new FlatEarth ( 90 , - 100 , 0.0 ) ; ProjectionPoint p = a . latLonToProj ( 89 , - 101 ) ; System . out . println ( "proj point = " + p ) ; LatLonPoint ll = a . projToLatLon ( p ) ; System . out . println ( "ll = " + ll ) ; }


Input: Find all catalogRef elements in the dataset tree formed by the given dataset list . [CODESPLIT] public static List < InvCatalogRef > findAllCatRefsInDatasetTree ( List < InvDataset > datasets , StringBuilder log , boolean onlyRelativeUrls ) { List < InvCatalogRef > catRefList = new ArrayList < InvCatalogRef > ( ) ; for ( InvDataset invds : datasets ) { InvDatasetImpl curDs = ( InvDatasetImpl ) invds ; if ( curDs instanceof InvDatasetScan ) continue ; if ( curDs instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) curDs ; String name = catRef . getName ( ) ; String href = catRef . getXlinkHref ( ) ; URI uri ; try { uri = new URI ( href ) ; } catch ( URISyntaxException e ) { log . append ( log . length ( ) > 0 ? "\n" : "" ) . append ( "***WARN - CatalogRef [" ) . append ( name ) . append ( "] with bad HREF [" ) . append ( href ) . append ( "] " ) ; continue ; } if ( onlyRelativeUrls && uri . isAbsolute ( ) ) continue ; catRefList . add ( catRef ) ; continue ; } if ( curDs . hasNestedDatasets ( ) ) catRefList . addAll ( findAllCatRefsInDatasetTree ( curDs . getDatasets ( ) , log , onlyRelativeUrls ) ) ; } return catRefList ; }


Input: Escape the characters necessary for a path to be valid for a URL [CODESPLIT] static public String escapePathForURL ( String path ) { try { return new URI ( null , null , path , null ) . toString ( ) ; } catch ( URISyntaxException e ) { return path ; } }


Input:
Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException { ArrayDouble . D3 array ; Array pertArray = getTimeSlice ( pertVar , timeIndex ) ; Array baseArray = getTimeSlice ( baseVar , timeIndex ) ; //ADD: use MAMath?
 //ADD: use IndexIterator from getIndexIteratorFast?
 int [ ] shape = pertArray . getShape ( ) ; //ADD: assert that rank = 3
 //ADD: assert that both arrays are same shape
 int ni = shape [ 0 ] ; int nj = shape [ 1 ] ; int nk = shape [ 2 ] ; array = new ArrayDouble . D3 ( ni , nj , nk ) ; Index index = array . getIndex ( ) ; for ( int i = 0 ; i < ni ; i ++ ) { for ( int j = 0 ; j < nj ; j ++ ) { for ( int k = 0 ; k < nk ; k ++ ) { index . set ( i , j , k ) ; double d = pertArray . getDouble ( index ) + baseArray . getDouble ( index ) ; if ( isZStag ) { d = d / 9.81 ; //convert geopotential to height
 } array . setDouble ( index , d ) ; } } } if ( isXStag ) { array = addStagger ( array , 2 ) ; //assuming x dim index is 2
 } if ( isYStag ) { array = addStagger ( array , 1 ) ; //assuming y dim index is 1
 } return array ; }


Input: Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { ArrayDouble . D3 data = getCoordinateArray ( timeIndex ) ; int [ ] origin = new int [ 3 ] ; int [ ] shape = new int [ 3 ] ; origin [ 0 ] = 0 ; origin [ 1 ] = yIndex ; origin [ 2 ] = xIndex ; shape [ 0 ] = data . getShape ( ) [ 0 ] ; shape [ 1 ] = 1 ; shape [ 2 ] = 1 ; Array tmp = data . section ( origin , shape ) ; return ( ArrayDouble . D1 ) tmp . reduce ( ) ; }


Input:
Add 1 to the size of the array for the given dimension . Use linear average and interpolation to fill in the values . [CODESPLIT] private ArrayDouble . D3 addStagger ( ArrayDouble . D3 array , int dimIndex ) { //ADD: assert 0<=dimIndex<=2
 int [ ] shape = array . getShape ( ) ; int [ ] newShape = new int [ 3 ] ; System . arraycopy ( shape , 0 , newShape , 0 , 3 ) ; newShape [ dimIndex ] ++ ; int ni = newShape [ 0 ] ; int nj = newShape [ 1 ] ; int nk = newShape [ 2 ] ; ArrayDouble . D3 newArray = new ArrayDouble . D3 ( ni , nj , nk ) ; //Index newIndex = newArray.getIndex();
 //extract 1d array to be extended
 int n = shape [ dimIndex ] ; //length of extracted array
 double [ ] d = new double [ n ] ; //tmp array to hold extracted values
 int [ ] eshape = new int [ 3 ] ; //shape of extracted array
 int [ ] neweshape = new int [ 3 ] ; //shape of new array slice to write into
 for ( int i = 0 ; i < 3 ; i ++ ) { eshape [ i ] = ( i == dimIndex ) ? n : 1 ; neweshape [ i ] = ( i == dimIndex ) ? n + 1 : 1 ; } int [ ] origin = new int [ 3 ] ; try { //loop through the other 2 dimensions and "extrapinterpolate" the other
 for ( int i = 0 ; i < ( ( dimIndex == 0 ) ? 1 : ni ) ; i ++ ) { for ( int j = 0 ; j < ( ( dimIndex == 1 ) ? 1 : nj ) ; j ++ ) { for ( int k = 0 ; k < ( ( dimIndex == 2 ) ? 1 : nk ) ; k ++ ) { origin [ 0 ] = i ; origin [ 1 ] = j ; origin [ 2 ] = k ; IndexIterator it = array . section ( origin , eshape ) . getIndexIterator ( ) ; for ( int l = 0 ; l < n ; l ++ ) { d [ l ] = it . getDoubleNext ( ) ; //get the original values
 } double [ ] d2 = extrapinterpolate ( d ) ; //compute new values
 //define slice of new array to write into
 IndexIterator newit = newArray . section ( origin , neweshape ) . getIndexIterator ( ) ; for ( int l = 0 ; l < n + 1 ; l ++ ) { newit . setDoubleNext ( d2 [ l ] ) ; } } } } } catch ( InvalidRangeException e ) { //ADD: report error?
 return null ; } return newArray ; }


Input:
Add one element to the array by linear interpolation and extrapolation at the ends . [CODESPLIT] private double [ ] extrapinterpolate ( double [ ] array ) { int n = array . length ; double [ ] d = new double [ n + 1 ] ; //end points from linear extrapolation
 //equations confirmed by Christopher Lindholm
 d [ 0 ] = 1.5 * array [ 0 ] - 0.5 * array [ 1 ] ; d [ n ] = 1.5 * array [ n - 1 ] - 0.5 * array [ n - 2 ] ; //inner points from simple average
 for ( int i = 1 ; i < n ; i ++ ) { d [ i ] = 0.5 * ( array [ i - 1 ] + array [ i ] ) ; } return d ; }


Input: copy constructor - avoid clone !! [CODESPLIT] public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new AlbersEqualArea ( getOriginLat ( ) , getOriginLon ( ) , getParallelOne ( ) , getParallelTwo ( ) , getFalseEasting ( ) , getFalseNorthing ( ) , getEarthRadius ( ) ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }


Input:
Precalculate some stuff [CODESPLIT] private void precalculate ( ) { double par1r = Math . toRadians ( this . par1 ) ; double par2r = Math . toRadians ( this . par2 ) ; if ( Math . abs ( par2 - par1 ) < TOLERANCE ) { // single parallel
 n = Math . sin ( par1r ) ; } else { n = ( Math . sin ( par1r ) + Math . sin ( par2r ) ) / 2.0 ; } double c2 = Math . pow ( Math . cos ( par1r ) , 2 ) ; C = c2 + 2 * n * Math . sin ( par1r ) ; rho0 = computeRho ( lat0 ) ; }


Input: Compute the RHO parameter [CODESPLIT] private double computeRho ( double lat ) { return earth_radius * Math . sqrt ( C - 2 * n * Math . sin ( lat ) ) / n ; }


Input: Compute theta [CODESPLIT] private double computeTheta ( double lon ) { double dlon = LatLonPointImpl . lonNormal ( Math . toDegrees ( lon ) - lon0Degrees ) ; return n * Math . toRadians ( dlon ) ; }


Input: Get the scale at the given lat . [CODESPLIT] public double getScale ( double lat ) { lat = Math . toRadians ( lat ) ; double n = Math . cos ( lat ) ; double d = Math . sqrt ( C - 2 * n * Math . sin ( lat ) ) ; return n / d ; }


Input: Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; fromLon = Math . toRadians ( fromLon ) ; double rho = computeRho ( fromLat ) ; double theta = computeTheta ( fromLon ) ; toX = rho * Math . sin ( theta ) + falseEasting ; toY = rho0 - rho * Math . cos ( theta ) + falseNorthing ; result . setLocation ( toX , toY ) ; return result ; }


Input: Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double rrho0 = rho0 ; if ( n < 0 ) { rrho0 *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = rrho0 - fromY ; double rho = Math . sqrt ( fromX * fromX + yd * yd ) ; double theta = Math . atan2 ( fromX , yd ) ; if ( n < 0 ) { rho *= - 1.0 ; } toLat = Math . toDegrees ( Math . asin ( ( C - Math . pow ( ( rho * n / earth_radius ) , 2 ) ) / ( 2 * n ) ) ) ; toLon = Math . toDegrees ( theta / n + lon0 ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] projToLatLon ( float [ ] [ ] from , float [ ] [ ] to ) { int cnt = from [ 0 ] . length ; float [ ] fromXA = from [ INDEX_X ] ; float [ ] fromYA = from [ INDEX_Y ] ; float [ ] toLatA = to [ INDEX_LAT ] ; float [ ] toLonA = to [ INDEX_LON ] ; double rrho0 = rho0 ; double toLat , toLon ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromX = fromXA [ i ] - falseEasting ; double fromY = fromYA [ i ] - falseNorthing ; if ( n < 0 ) { rrho0 *= - 1.0 ; fromX *= - 1.0 ; fromY *= - 1.0 ; } double yd = rrho0 - fromY ; double rho = Math . sqrt ( fromX * fromX + yd * yd ) ; double theta = Math . atan2 ( fromX , yd ) ; if ( n < 0 ) { rho *= - 1.0 ; } toLat = Math . toDegrees ( Math . asin ( ( C - Math . pow ( ( rho * n / earth_radius ) , 2 ) ) / ( 2 * n ) ) ) ; toLon = Math . toDegrees ( theta / n + lon0 ) ; toLatA [ i ] = ( float ) toLat ; toLonA [ i ] = ( float ) toLon ; } return to ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public double [ ] [ ] latLonToProj ( double [ ] [ ] from , double [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; double [ ] fromLatA = from [ latIndex ] ; double [ ] fromLonA = from [ lonIndex ] ; double [ ] resultXA = to [ INDEX_X ] ; double [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; fromLon = Math . toRadians ( fromLon ) ; double rho = computeRho ( fromLat ) ; double theta = computeTheta ( fromLon ) ; toX = rho * Math . sin ( theta ) ; toY = rho0 - rho * Math . cos ( theta ) ; resultXA [ i ] = toX + falseEasting ; resultYA [ i ] = toY + falseNorthing ; } return to ; }


Input: Test [CODESPLIT] public static void main ( String [ ] args ) { AlbersEqualArea a = new AlbersEqualArea ( 23 , - 96 , 29.5 , 45.5 ) ; System . out . printf ( "name=%s%n" , a . getName ( ) ) ; System . out . println ( "ll = 35N 75W" ) ; ProjectionPoint p = a . latLonToProj ( 35 , - 75 ) ; System . out . println ( "proj point = " + p ) ; LatLonPoint ll = a . projToLatLon ( p ) ; System . out . println ( "ll = " + ll ) ; }


Input:
Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( addName ) pw . print ( ", " ) ; String s = getValue ( ) ; // Get rid of null terminations on strings
 if ( ( s . length ( ) > 0 ) && s . charAt ( s . length ( ) - 1 ) == ( ( char ) 0 ) ) { // jc mod
 if ( _Debug ) System . out . println ( "Removing null termination from string \"" + getEncodedName ( ) + "\"." ) ; char cArray [ ] = s . toCharArray ( ) ; s = new String ( cArray , 0 , cArray . length - 1 ) ; } pw . print ( "\"" + s + "\"" ) ; if ( newLine ) pw . print ( "\n" ) ; }


Input: / * <xs : element ref = dc : title / > <xs : element ref = dc : creator / > <xs : element ref = dc : subject / > <xs : element ref = dc : description / > <xs : element ref = dc : publisher / > <xs : element ref = dc : contributor / > <xs : element ref = dc : date / > <xs : element ref = dc : type / > <xs : element ref = dc : format / > <xs : element ref = dc : identifier / > <xs : element ref = dc : source / > <xs : element ref = dc : language / > <xs : element ref = dc : relation / > <xs : element ref = dc : coverage / > <xs : element ref = dc : rights / > <! -- controlled vocabulary from dcmitype -- > <xs : element ref = dcmitype : dcmitype / > [CODESPLIT] public void writeDataset ( InvDataset ds , Element rootElem ) { rootElem . addContent ( new Element ( "title" , defNS ) . addContent ( ds . getName ( ) ) ) ; rootElem . addContent ( new Element ( "Entry_ID" , defNS ) . addContent ( ds . getUniqueID ( ) ) ) ; // keywords List < ThreddsMetadata . Vocab > list = ds . getKeywords ( ) ; if ( list . size ( ) > 0 ) { for ( ThreddsMetadata . Vocab k : list ) { rootElem . addContent ( new Element ( "Keyword" , defNS ) . addContent ( k . getText ( ) ) ) ; } } //temporal CalendarDateRange tm = ds . getCalendarDateCoverage ( ) ; Element tmElem = new Element ( "Temporal_Coverage" , defNS ) ; rootElem . addContent ( tmElem ) ; tmElem . addContent ( new Element ( "Start_Date" , defNS ) . addContent ( tm . getStart ( ) . toString ( ) ) ) ; tmElem . addContent ( new Element ( "End_Date" , defNS ) . addContent ( tm . getEnd ( ) . toString ( ) ) ) ; //geospatial ThreddsMetadata . GeospatialCoverage geo = ds . getGeospatialCoverage ( ) ; Element geoElem = new Element ( "Spatial_Coverage" , defNS ) ; rootElem . addContent ( geoElem ) ; geoElem . addContent ( new Element ( "Southernmost_Latitude" , defNS ) . addContent ( Double . toString ( geo . getLatSouth ( ) ) ) ) ; geoElem . addContent ( new Element ( "Northernmost_Latitude" , defNS ) . addContent ( Double . toString ( geo . getLatNorth ( ) ) ) ) ; geoElem . addContent ( new Element ( "Westernmost_Latitude" , defNS ) . addContent ( Double . toString ( geo . getLonWest ( ) ) ) ) ; geoElem . addContent ( new Element ( "Easternmost_Latitude" , defNS ) . addContent ( Double . toString ( geo . getLonEast ( ) ) ) ) ; rootElem . addContent ( new Element ( "Use_Constraints" , defNS ) . addContent ( ds . getDocumentation ( "rights" ) ) ) ; // data center List < ThreddsMetadata . Source > slist = ds . getPublishers ( ) ; if ( list . size ( ) > 0 ) { for ( ThreddsMetadata . Source p : slist ) { Element dataCenter = new Element ( "Data_Center" , defNS ) ; rootElem . addContent ( dataCenter ) ; writePublisher ( p , dataCenter ) ; } } rootElem . addContent ( new Element ( "Summary" , defNS ) . addContent ( ds . getDocumentation ( "summary" ) ) ) ; Element primaryURLelem = new Element ( "Related_URL" , defNS ) ; rootElem . addContent ( primaryURLelem ) ; String primaryURL = threddsServerURL + "?catalog=" + ( ( InvCatalogImpl ) ds . getParentCatalog ( ) ) . getBaseURI ( ) . toString ( ) + "&dataset=" + ds . getID ( ) ; primaryURLelem . addContent ( new Element ( "URL_Content_Type" , defNS ) . addContent ( "THREDDS access page" ) ) ; primaryURLelem . addContent ( new Element ( "URL" , defNS ) . addContent ( primaryURL ) ) ; DateType today = new DateType ( false , new Date ( ) ) ; rootElem . addContent ( new Element ( "DIF_Creation_Date" , defNS ) . addContent ( today . toDateTimeStringISO ( ) ) ) ; }


Input: testing [CODESPLIT] public static void main ( String [ ] args ) throws Exception { InvCatalogFactory catFactory = InvCatalogFactory . getDefaultFactory ( true ) ; doOne ( catFactory , "file:///C:/dev/thredds/catalog/test/data/TestHarvest.xml" ) ; }


Input: Is this a valid file? [CODESPLIT] @ Override public boolean isValidFile ( RandomAccessFile raf ) throws IOException { try { gemreader = makeStationReader ( ) ; return gemreader . init ( raf , false ) ; } catch ( Exception ioe ) { return false ; } }


Input:
Open the service provider for reading . [CODESPLIT] @ Override public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { //System.out.printf("GempakSurfaceIOSP open %s (%s) %n", raf.getLocation(), Calendar.getInstance().getTime());
 super . open ( raf , ncfile , cancelTask ) ; if ( gemreader == null ) { gemreader = makeStationReader ( ) ; } initTables ( ) ; gemreader . init ( raf , true ) ; buildNCFile ( ) ; }


Input: Get the detail information [CODESPLIT] public String getDetailInfo ( ) { Formatter ff = new Formatter ( ) ; ff . format ( "%s" , super . getDetailInfo ( ) ) ; ff . format ( "%s" , parseInfo ) ; return ff . toString ( ) ; }


Input: Make a structure for the part [CODESPLIT] protected Structure makeStructure ( String partName , List < Dimension > dimensions , boolean includeMissing ) { List < GempakParameter > params = gemreader . getParameters ( partName ) ; if ( params == null ) { return null ; } Structure sVar = new Structure ( ncfile , null , null , partName ) ; sVar . setDimensions ( dimensions ) ; for ( GempakParameter param : params ) { sVar . addMemberVariable ( makeParamVariable ( param , null ) ) ; } if ( includeMissing ) { sVar . addMemberVariable ( makeMissingVariable ( ) ) ; } return sVar ; }


Input: Make the missing variable [CODESPLIT] protected Variable makeMissingVariable ( ) { Variable var = new Variable ( ncfile , null , null , MISSING_VAR ) ; var . setDataType ( DataType . BYTE ) ; var . setDimensions ( ( List < Dimension > ) null ) ; var . addAttribute ( new Attribute ( "description" , "missing flag - 1 means all params are missing" ) ) ; var . addAttribute ( new Attribute ( CDM . MISSING_VALUE , ( byte ) 1 ) ) ; return var ; }


Input: Make a variable from a GempakParmaeter [CODESPLIT] protected Variable makeParamVariable ( GempakParameter param , List < Dimension > dims ) { Variable var = new Variable ( ncfile , null , null , param . getName ( ) ) ; var . setDataType ( DataType . FLOAT ) ; var . setDimensions ( dims ) ; var . addAttribute ( new Attribute ( CDM . LONG_NAME , param . getDescription ( ) ) ) ; String units = param . getUnit ( ) ; if ( ( units != null ) && ! units . equals ( "" ) ) { var . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; } var . addAttribute ( new Attribute ( CDM . MISSING_VALUE , RMISS ) ) ; return var ; }


Input:
Add on global attributes for all types [CODESPLIT] protected void addGlobalAttributes ( ) { // global stuff
 ncfile . addAttribute ( null , new Attribute ( CDM . CONVENTIONS , getConventions ( ) ) ) ; String fileType = "GEMPAK " + gemreader . getFileType ( ) ; ncfile . addAttribute ( null , new Attribute ( "file_format" , fileType ) ) ; ncfile . addAttribute ( null , new Attribute ( "history" , "Direct read of " + fileType + " into NetCDF-Java API" ) ) ; ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , getCFFeatureType ( ) ) ) ; }


Input: Get the size of a particular station variable [CODESPLIT] protected int getStnVarSize ( String name ) { int size = - 1 ; for ( int i = 0 ; i < stnVarNames . length ; i ++ ) { if ( name . equals ( stnVarNames [ i ] ) ) { size = stnVarSizes [ i ] ; break ; } } return size ; }


Input:
Make the station variables from a representative station [CODESPLIT] protected List < Variable > makeStationVars ( List < GempakStation > stations , Dimension dim ) { int numStations = stations . size ( ) ; List < Variable > vars = new ArrayList <> ( ) ; List < String > stnKeyNames = gemreader . getStationKeyNames ( ) ; for ( String varName : stnKeyNames ) { Variable v = makeStationVariable ( varName , dim ) ; Attribute stIDAttr = new Attribute ( CF . STANDARD_NAME , "station_id" ) ; if ( varName . equals ( GempakStation . STID ) ) { // Use STID as the station_id for the dataset.
 v . addAttribute ( stIDAttr ) ; } vars . add ( v ) ; } // see if we fill these in completely now
 if ( ( dim != null ) && ( numStations > 0 ) ) { for ( Variable v : vars ) { Array varArray ; if ( v . getDataType ( ) . equals ( DataType . CHAR ) ) { int [ ] shape = v . getShape ( ) ; varArray = new ArrayChar . D2 ( shape [ 0 ] , shape [ 1 ] ) ; } else { varArray = get1DArray ( v . getDataType ( ) , numStations ) ; } assert varArray != null ; int index = 0 ; String varname = v . getFullName ( ) ; for ( GempakStation stn : stations ) { String test = "" ; switch ( varname ) { case GempakStation . STID : test = stn . getName ( ) ; break ; case GempakStation . STNM : ( ( ArrayInt . D1 ) varArray ) . set ( index , stn . getSTNM ( ) ) ; break ; case GempakStation . SLAT : ( ( ArrayFloat . D1 ) varArray ) . set ( index , ( float ) stn . getLatitude ( ) ) ; break ; case GempakStation . SLON : ( ( ArrayFloat . D1 ) varArray ) . set ( index , ( float ) stn . getLongitude ( ) ) ; break ; case GempakStation . SELV : ( ( ArrayFloat . D1 ) varArray ) . set ( index , ( float ) stn . getAltitude ( ) ) ; break ; case GempakStation . STAT : test = stn . getSTAT ( ) ; break ; case GempakStation . COUN : test = stn . getCOUN ( ) ; break ; case GempakStation . STD2 : test = stn . getSTD2 ( ) ; break ; case GempakStation . SPRI : ( ( ArrayInt . D1 ) varArray ) . set ( index , stn . getSPRI ( ) ) ; break ; case GempakStation . SWFO : test = stn . getSWFO ( ) ; break ; case GempakStation . WFO2 : test = stn . getWFO2 ( ) ; break ; } if ( ! test . equals ( "" ) ) { ( ( ArrayChar . D2 ) varArray ) . setString ( index , test ) ; } index ++ ; } v . setCachedData ( varArray , false ) ; } } return vars ; }


Input: Get a 1DArray for the type and length [CODESPLIT] private Array get1DArray ( DataType type , int len ) { Array varArray = null ; if ( type . equals ( DataType . FLOAT ) ) { varArray = new ArrayFloat . D1 ( len ) ; } else if ( type . equals ( DataType . DOUBLE ) ) { varArray = new ArrayDouble . D1 ( len ) ; } else if ( type . equals ( DataType . INT ) ) { varArray = new ArrayInt . D1 ( len , false ) ; } return varArray ; }


Input: Make a station variable [CODESPLIT] protected Variable makeStationVariable ( String varname , Dimension firstDim ) { String longName = varname ; String unit = null ; DataType type = DataType . CHAR ; List < Dimension > dims = new ArrayList <> ( ) ; List < Attribute > attrs = new ArrayList <> ( ) ; if ( firstDim != null ) { dims . add ( firstDim ) ; } switch ( varname ) { case GempakStation . STID : longName = "Station identifier" ; dims . add ( DIM_LEN8 ) ; break ; case GempakStation . STNM : longName = "WMO station id" ; type = DataType . INT ; break ; case GempakStation . SLAT : longName = "latitude" ; unit = CDM . LAT_UNITS ; type = DataType . FLOAT ; attrs . add ( new Attribute ( CF . STANDARD_NAME , "latitude" ) ) ; break ; case GempakStation . SLON : longName = "longitude" ; unit = CDM . LON_UNITS ; type = DataType . FLOAT ; attrs . add ( new Attribute ( CF . STANDARD_NAME , "longitude" ) ) ; break ; case GempakStation . SELV : longName = "altitude" ; unit = "meter" ; type = DataType . FLOAT ; attrs . add ( new Attribute ( CF . POSITIVE , CF . POSITIVE_UP ) ) ; attrs . add ( new Attribute ( CF . STANDARD_NAME , CF . STATION_ALTITUDE ) ) ; break ; case GempakStation . STAT : longName = "state or province" ; dims . add ( DIM_LEN2 ) ; break ; case GempakStation . COUN : longName = "country code" ; dims . add ( DIM_LEN2 ) ; break ; case GempakStation . STD2 : longName = "Extended station id" ; dims . add ( DIM_LEN4 ) ; break ; case GempakStation . SPRI : longName = "Station priority" ; type = DataType . INT ; break ; case GempakStation . SWFO : longName = "WFO code" ; dims . add ( DIM_LEN4 ) ; break ; case GempakStation . WFO2 : longName = "Second WFO code" ; dims . add ( DIM_LEN4 ) ; break ; } Variable v = new Variable ( ncfile , null , null , varname ) ; v . setDataType ( type ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; if ( unit != null ) { v . addAttribute ( new Attribute ( CDM . UNITS , unit ) ) ; } if ( type . equals ( DataType . FLOAT ) ) { v . addAttribute ( new Attribute ( CDM . MISSING_VALUE , RMISS ) ) ; } else if ( type . equals ( DataType . INT ) ) { v . addAttribute ( new Attribute ( CDM . MISSING_VALUE , IMISS ) ) ; } if ( ! attrs . isEmpty ( ) ) { for ( Attribute attr : attrs ) { v . addAttribute ( attr ) ; } } if ( ! dims . isEmpty ( ) ) { v . setDimensions ( dims ) ; } else { v . setDimensions ( ( String ) null ) ; } return v ; }


Input: Compute post - reduction state . [CODESPLIT] private int yy_lr_goto_state_ ( int yystate , int yysym ) { int yyr = yypgoto_ [ yysym - yyntokens_ ] + yystate ; if ( 0 <= yyr && yyr <= yylast_ && yycheck_ [ yyr ] == yystate ) return yytable_ [ yyr ] ; else return yydefgoto_ [ yysym - yyntokens_ ] ; }


Input: / * Return YYSTR after stripping away unnecessary quotes and backslashes so that it s suitable for yyerror . The heuristic is that double - quoting is unnecessary unless the string contains an apostrophe a comma or backslash ( other than backslash - backslash ) . YYSTR is taken from yytname . [CODESPLIT] private final String yytnamerr_ ( String yystr ) { if ( yystr . charAt ( 0 ) == ' ' ) { StringBuffer yyr = new StringBuffer ( ) ; strip_quotes : for ( int i = 1 ; i < yystr . length ( ) ; i ++ ) switch ( yystr . charAt ( i ) ) { case ' ' : case ' ' : break strip_quotes ; case ' ' : if ( yystr . charAt ( ++ i ) != ' ' ) break strip_quotes ; /* Fall through.  */ default : yyr . append ( yystr . charAt ( i ) ) ; break ; case ' ' : return yyr . toString ( ) ; } } else if ( yystr . equals ( "$end" ) ) return "end of input" ; return yystr ; }


Input: / * -------------------------------- . | Print this symbol on YYOUTPUT . | -------------------------------- [CODESPLIT] private void yy_symbol_print ( String s , int yytype , Object yyvaluep ) { if ( yydebug > 0 ) yycdebug ( s + ( yytype < yyntokens_ ? " token " : " nterm " ) + yytname_ [ yytype ] + " (" + ( yyvaluep == null ? "(null)" : yyvaluep . toString ( ) ) + ")" ) ; }


Input:
Parse input from the scanner that was specified at object construction time . Return whether the end of the input was reached successfully . [CODESPLIT] public boolean parse ( ) throws ParseException , ParseException { /* Lookahead and lookahead in internal form.  */ int yychar = yyempty_ ; int yytoken = 0 ; /* State.  */ int yyn = 0 ; int yylen = 0 ; int yystate = 0 ; YYStack yystack = new YYStack ( ) ; int label = YYNEWSTATE ; /* Error handling.  */ int yynerrs_ = 0 ; /* Semantic value of the lookahead.  */ Object yylval = null ; yycdebug ( "Starting parse\n" ) ; yyerrstatus_ = 0 ; /* Initialize the stack.  */ yystack . push ( yystate , yylval ) ; for ( ; ; ) switch ( label ) { /* New state.  Unlike in the C/C++ skeletons, the state is already
           pushed when we come here.  */ case YYNEWSTATE : yycdebug ( "Entering state " + yystate + "\n" ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; /* Accept?  */ if ( yystate == yyfinal_ ) return true ; /* Take a decision.  First try without lookahead.  */ yyn = yypact_ [ yystate ] ; if ( yy_pact_value_is_default_ ( yyn ) ) { label = YYDEFAULT ; break ; } /* Read a lookahead token.  */ if ( yychar == yyempty_ ) { yycdebug ( "Reading a token: " ) ; yychar = yylexer . yylex ( ) ; yylval = yylexer . getLVal ( ) ; } /* Convert token to internal form.  */ if ( yychar <= Lexer . EOF ) { yychar = yytoken = Lexer . EOF ; yycdebug ( "Now at end of input.\n" ) ; } else { yytoken = yytranslate_ ( yychar ) ; yy_symbol_print ( "Next token is" , yytoken , yylval ) ; } /* If the proper action on seeing token YYTOKEN is to reduce or to
           detect an error, take that action.  */ yyn += yytoken ; if ( yyn < 0 || yylast_ < yyn || yycheck_ [ yyn ] != yytoken ) label = YYDEFAULT ; /* <= 0 means reduce or error.  */ else if ( ( yyn = yytable_ [ yyn ] ) <= 0 ) { if ( yy_table_value_is_error_ ( yyn ) ) label = YYERRLAB ; else { yyn = - yyn ; label = YYREDUCE ; } } else { /* Shift the lookahead token.  */ yy_symbol_print ( "Shifting" , yytoken , yylval ) ; /* Discard the token being shifted.  */ yychar = yyempty_ ; /* Count tokens shifted since error; after three, turn off error
               status.  */ if ( yyerrstatus_ > 0 ) -- yyerrstatus_ ; yystate = yyn ; yystack . push ( yystate , yylval ) ; label = YYNEWSTATE ; } break ; /*-----------------------------------------------------------.
      | yydefault -- do the default action for the current state.  |
      `-----------------------------------------------------------*/ case YYDEFAULT : yyn = yydefact_ [ yystate ] ; if ( yyn == 0 ) label = YYERRLAB ; else label = YYREDUCE ; break ; /*-----------------------------.
      | yyreduce -- Do a reduction.  |
      `-----------------------------*/ case YYREDUCE : yylen = yyr2_ [ yyn ] ; label = yyaction ( yyn , yystack , yylen ) ; yystate = yystack . stateAt ( 0 ) ; break ; /*------------------------------------.
      | yyerrlab -- here on detecting error |
      `------------------------------------*/ case YYERRLAB : /* If not already recovering from an error, report this error.  */ if ( yyerrstatus_ == 0 ) { ++ yynerrs_ ; if ( yychar == yyempty_ ) yytoken = yyempty_ ; yyerror ( yysyntax_error ( yystate , yytoken ) ) ; } if ( yyerrstatus_ == 3 ) { /* If just tried and failed to reuse lookahead token after an
         error, discard it.  */ if ( yychar <= Lexer . EOF ) { /* Return failure if at end of input.  */ if ( yychar == Lexer . EOF ) return false ; } else yychar = yyempty_ ; } /* Else will try to reuse lookahead token after shifting the error
           token.  */ label = YYERRLAB1 ; break ; /*-------------------------------------------------.
      | errorlab -- error raised explicitly by YYERROR.  |
      `-------------------------------------------------*/ case YYERROR : /* Do not reclaim the symbols of the rule which action triggered
           this YYERROR.  */ yystack . pop ( yylen ) ; yylen = 0 ; yystate = yystack . stateAt ( 0 ) ; label = YYERRLAB1 ; break ; /*-------------------------------------------------------------.
      | yyerrlab1 -- common code for both syntax error and YYERROR.  |
      `-------------------------------------------------------------*/ case YYERRLAB1 : yyerrstatus_ = 3 ; /* Each real token shifted decrements this.  */ for ( ; ; ) { yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { yyn += yyterror_ ; if ( 0 <= yyn && yyn <= yylast_ && yycheck_ [ yyn ] == yyterror_ ) { yyn = yytable_ [ yyn ] ; if ( 0 < yyn ) break ; } } /* Pop the current state because it cannot handle the
             * error token.  */ if ( yystack . height == 0 ) return false ; yystack . pop ( ) ; yystate = yystack . stateAt ( 0 ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; } if ( label == YYABORT ) /* Leave the switch.  */ break ; /* Shift the error token.  */ yy_symbol_print ( "Shifting" , yystos_ [ yyn ] , yylval ) ; yystate = yyn ; yystack . push ( yyn , yylval ) ; label = YYNEWSTATE ; break ; /* Accept.  */ case YYACCEPT : return true ; /* Abort.  */ case YYABORT : return false ; } }


Input:
Generate an error message . [CODESPLIT] private String yysyntax_error ( int yystate , int tok ) { if ( yyErrorVerbose ) { /* There are many possibilities here to consider:
           - If this state is a consistent state with a default action,
             then the only way this function was invoked is if the
             default action is an error action.  In that case, don't
             check for expected tokens because there are none.
           - The only way there can be no lookahead present (in tok) is
             if this state is a consistent state with a default action.
             Thus, detecting the absence of a lookahead is sufficient to
             determine that there is no unexpected or expected token to
             report.  In that case, just report a simple "syntax error".
           - Don't assume there isn't a lookahead just because this
             state is a consistent state with a default action.  There
             might have been a previous inconsistent state, consistent
             state with a non-default action, or user semantic action
             that manipulated yychar.  (However, yychar is currently out
             of scope during semantic actions.)
           - Of course, the expected token list depends on states to
             have correct lookahead information, and it depends on the
             parser not to perform extra reductions after fetching a
             lookahead from the scanner and before detecting a syntax
             error.  Thus, state merging (from LALR or IELR) and default
             reductions corrupt the expected token list.  However, the
             list is correct for canonical LR with one exception: it
             will still contain any token that will not be accepted due
             to an error action in a later state.
        */ if ( tok != yyempty_ ) { /* FIXME: This method of building the message is not compatible
               with internationalization.  */ StringBuffer res = new StringBuffer ( "syntax error, unexpected " ) ; res . append ( yytnamerr_ ( yytname_ [ tok ] ) ) ; int yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { /* Start YYX at -YYN if negative to avoid negative
                   indexes in YYCHECK.  In other words, skip the first
                   -YYN actions for this state because they are default
                   actions.  */ int yyxbegin = yyn < 0 ? - yyn : 0 ; /* Stay within bounds of both yycheck and yytname.  */ int yychecklim = yylast_ - yyn + 1 ; int yyxend = yychecklim < yyntokens_ ? yychecklim : yyntokens_ ; int count = 0 ; for ( int x = yyxbegin ; x < yyxend ; ++ x ) if ( yycheck_ [ x + yyn ] == x && x != yyterror_ && ! yy_table_value_is_error_ ( yytable_ [ x + yyn ] ) ) ++ count ; if ( count < 5 ) { count = 0 ; for ( int x = yyxbegin ; x < yyxend ; ++ x ) if ( yycheck_ [ x + yyn ] == x && x != yyterror_ && ! yy_table_value_is_error_ ( yytable_ [ x + yyn ] ) ) { res . append ( count ++ == 0 ? ", expecting " : " or " ) ; res . append ( yytnamerr_ ( yytname_ [ x ] ) ) ; } } } return res . toString ( ) ; } } return "syntax error" ; }


Input: Report on the debug stream that the rule yyrule is going to be reduced . [CODESPLIT] private void yy_reduce_print ( int yyrule , YYStack yystack ) { if ( yydebug == 0 ) return ; int yylno = yyrline_ [ yyrule ] ; int yynrhs = yyr2_ [ yyrule ] ; /* Print the symbols being reduced, and their result.  */ yycdebug ( "Reducing stack by rule " + ( yyrule - 1 ) + " (line " + yylno + "), " ) ; /* The symbols being reduced.  */ for ( int yyi = 0 ; yyi < yynrhs ; yyi ++ ) yy_symbol_print ( "   $" + ( yyi + 1 ) + " ="  , yystos_ [ yystack . stateAt ( yynrhs - ( yyi + 1 ) ) ] , ( ( yystack . valueAt ( yynrhs - ( yyi + 1 ) ) ) ) ) ; }


Input: / * the parse function allows the specification of a new stream in case one is reusing the parser [CODESPLIT] boolean parse ( String constraint ) throws ParseException { ( ( Celex ) yylexer ) . reset ( parsestate , constraint ) ; return parse ( ) ; }


Input: This parses then fills in the evaluator from the AST [CODESPLIT] static public boolean constraint_expression ( CEEvaluator ceEval , BaseTypeFactory factory , ClauseFactory clauseFactory , String constraint , String url // for error reporting ) throws DAP2Exception , ParseException { CeParser parser = new CeParser ( factory ) ; parser . setURL ( url ) ; parser . setConstraint ( constraint ) ; ServerDDS sdds = ceEval . getDDS ( ) ; if ( ! parser . parse ( constraint ) ) return false ; ASTconstraint root = ( ASTconstraint ) parser . getAST ( ) ; root . init ( ceEval , factory , clauseFactory , sdds , parser . getASTnodeset ( ) ) ; root . walkConstraint ( ) ; return true ; }


Input: Compares this prefix against another PrefixSymbol . The sort keys are decreasing length ( major ) and increasing lexicality ( minor ) . [CODESPLIT] public final int compareTo ( Object obj ) { String thatID = ( ( PrefixSymbol ) obj ) . getID ( ) ; int comp = thatID . length ( ) - getID ( ) . length ( ) ; if ( comp == 0 ) comp = getID ( ) . compareTo ( thatID ) ; return comp ; }


Input: Compares this prefix against a String . The sort keys are decreasing length ( major ) and increasing lexicality ( minor ) . [CODESPLIT] public final int compareTo ( String string ) { int comp = string . length ( ) - getID ( ) . length ( ) ; return comp < 0 ? comp : comp == 0 ? ( getID ( ) . compareTo ( string ) == 0 ? 0 : - 1 ) : ( getID ( ) . compareTo ( string . substring ( 0 , getID ( ) . length ( ) ) ) == 0 ? 0 : - 1 ) ; }


Input: Read the DMR trimmed . [CODESPLIT] public String readDMR ( ) throws DapException { try { if ( state != State . INITIAL ) throw new DapException ( "Attempt to read DMR twice" ) ; byte [ ] dmr8 = null ; if ( requestmode == RequestMode . DMR ) { // The whole buffer is the dmr; // but we do not know the length ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; int c ; while ( ( c = input . read ( ) ) >= 0 ) { baos . write ( c ) ; } baos . close ( ) ; dmr8 = baos . toByteArray ( ) ; } else if ( requestmode == RequestMode . DAP ) { // Pull in the DMR chunk header if ( ! readHeader ( input ) ) throw new DapException ( "Malformed chunk count" ) ; // Read the DMR databuffer dmr8 = new byte [ this . chunksize ] ; int red = read ( dmr8 , 0 , this . chunksize ) ; if ( red < this . chunksize ) throw new DapException ( "Short chunk" ) ; } else assert false : "Internal error" ; // Convert DMR to a string String dmr = new String ( dmr8 , DapUtil . UTF8 ) ; // Clean it up dmr = dmr . trim ( ) ; // Make sure it has trailing \r\n" if ( dmr . endsWith ( "\r\n" ) ) { // do nothing } else if ( dmr . endsWith ( "\n" ) ) dmr = dmr . substring ( 0 , dmr . length ( ) - 2 ) + "\r\n" ; else dmr = dmr + "\r\n" ; // Figure out the endian-ness of the response this . remoteorder = ( flags & DapUtil . CHUNK_LITTLE_ENDIAN ) == 0 ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; this . nochecksum = ( flags & DapUtil . CHUNK_NOCHECKSUM ) != 0 ; // Set the state if ( ( flags & DapUtil . CHUNK_ERROR ) != 0 ) state = State . ERROR ; else if ( ( flags & DapUtil . CHUNK_END ) != 0 ) state = State . END ; else state = State . DATA ; return dmr ; //return the DMR } catch ( IOException ioe ) { throw new DapException ( ioe . getMessage ( ) ) ; } }


Input: Read an error chunk [CODESPLIT] public String readError ( ) throws IOException { state = State . ERROR ; // Read the error body databuffer byte [ ] bytes = new byte [ this . chunksize ] ; try { if ( read ( bytes , 0 , this . chunksize ) < this . chunksize ) throw new ErrorException ( "Short chunk" ) ; } catch ( IOException ioe ) { throw new ErrorException ( ioe ) ; } String document = new String ( bytes , DapUtil . UTF8 ) ; return document ; }


Input: Reads the next byte of databuffer from the input stream . The value byte is returned as an <code > int< / code > in the range <code > 0< / code > to <code > 255< / code > . If no byte is available because the end of the stream has been reached the value <code > - 1< / code > is returned . This method blocks until input databuffer is available the end of the stream is detected or an exception is thrown . <p > Operates by loading chunk by chunk . If an error chunk is detected then return ErrorException ( which is a subclass of IOException ) . [CODESPLIT] public int read ( ) throws IOException { if ( requestmode == RequestMode . DMR ) throw new UnsupportedOperationException ( "Attempt to read databuffer when DMR only" ) ; // Runtime if ( avail <= 0 ) { if ( ( flags & DapUtil . CHUNK_END ) != 0 ) return - 1 ; // Treat as EOF if ( ! readHeader ( input ) ) return - 1 ; // EOF // See if we have an error chunk, // and if so, turn it into an exception if ( ( flags & DapUtil . CHUNK_ERROR ) != 0 ) { String document = readError ( ) ; throwError ( document ) ; } } avail -- ; return input . read ( ) ; }


Input: Reads up to len databuffer of databuffer from the input stream into an array of databuffer . An attempt is made to read as many as len databuffer but a smaller number may be read . The number of databuffer actually read is returned as an integer . [CODESPLIT] public int read ( byte [ ] buf , int off , int len ) throws IOException { // Sanity check if ( off < 0 || len < 0 ) throw new IndexOutOfBoundsException ( ) ; // Runtime if ( off >= buf . length || buf . length < ( off + len ) ) throw new IndexOutOfBoundsException ( ) ; //Runtime if ( requestmode == RequestMode . DMR ) throw new UnsupportedOperationException ( "Attempt to read databuffer when DMR only" ) ; // Runtime // Attempt to read len bytes out of a sequence of chunks int count = len ; int pos = off ; while ( count > 0 ) { if ( avail <= 0 ) { if ( ( flags & DapUtil . CHUNK_END ) != 0 || ! readHeader ( input ) ) return ( len - count ) ; // return # databuffer read // See if we have an error chunk, // and if so, turn it into an exception if ( ( flags & DapUtil . CHUNK_ERROR ) != 0 ) { String document = readError ( ) ; throwError ( document ) ; } } else { int actual = ( this . avail < count ? this . avail : count ) ; int red = input . read ( buf , pos , actual ) ; if ( red < 0 ) throw new IOException ( "Unexpected EOF" ) ; pos += red ; count -= red ; this . avail -= red ; } } return len ; }


Input: Read the size + flags header from the input stream and use it to initialize the chunk state [CODESPLIT] boolean readHeader ( InputStream input ) throws IOException { byte [ ] bytehdr = new byte [ 4 ] ; int red = input . read ( bytehdr ) ; if ( red == - 1 ) return false ; if ( red < 4 ) throw new IOException ( "Short binary chunk count" ) ; this . flags = ( ( int ) bytehdr [ 0 ] ) & 0xFF ; // Keep unsigned bytehdr [ 0 ] = 0 ; ByteBuffer buf = ByteBuffer . wrap ( bytehdr ) . order ( ByteOrder . BIG_ENDIAN ) ; this . chunksize = buf . getInt ( ) ; this . avail = this . chunksize ; return true ; }


Input:
/ * <Exp_CodeFlagTables_E > <No > 837< / No > <FXY > 002119< / FXY > <ElementName_E > Instrument operations< / ElementName_E > <CodeFigure > 0< / CodeFigure > <EntryName_E > Intermediate frequency calibration mode ( IF CAL ) < / EntryName_E > <Status > Operational< / Status > < / Exp_CodeFlagTables_E > [CODESPLIT] static private void init ( Map < Short , CodeFlagTables > table ) { String filename = BufrTables . RESOURCE_PATH + CodeFlagFilename ; try ( InputStream is = CodeFlagTables . class . getResourceAsStream ( filename ) ) { SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document tdoc = builder . build ( is ) ; org . jdom2 . Element root = tdoc . getRootElement ( ) ; List < Element > elems = root . getChildren ( ) ; for ( Element elem : elems ) { String fxyS = elem . getChildText ( "FXY" ) ; String desc = elem . getChildText ( "ElementName_en" ) ; short fxy = Descriptor . getFxy2 ( fxyS ) ; CodeFlagTables ct = table . get ( fxy ) ; if ( ct == null ) { ct = new CodeFlagTables ( fxy , desc ) ; table . put ( fxy , ct ) ; // System.out.printf(" added %s == %s %n", ct.id, desc);
 } String line = elem . getChildText ( "No" ) ; String codeS = elem . getChildText ( "CodeFigure" ) ; String value = elem . getChildText ( "EntryName_en" ) ; if ( ( codeS == null ) || ( value == null ) ) continue ; if ( value . toLowerCase ( ) . startsWith ( "reserved" ) ) continue ; if ( value . toLowerCase ( ) . startsWith ( "not used" ) ) continue ; int code ; if ( codeS . toLowerCase ( ) . contains ( "all" ) ) { code = - 1 ; } else try { code = Integer . parseInt ( codeS ) ; } catch ( NumberFormatException e ) { log . debug ( "NumberFormatException on line " + line + " in " + codeS ) ; continue ; } ct . addValue ( ( short ) code , value ) ; } } catch ( IOException | JDOMException e ) { log . error ( "Can't read BUFR code table " + filename , e ) ; } }


Input: udunits [CODESPLIT] static public String toDateTimeStringISO ( CalendarDate cd ) { if ( cd . getDateTime ( ) . getMillisOfSecond ( ) == 0 ) return isof . print ( cd . getDateTime ( ) ) ; else return isof_with_millis_of_second . print ( cd . getDateTime ( ) ) ; }


Input: Old version using DateFormatter @param iso ISO 8601 date String @return equivilent Date [CODESPLIT] @ Deprecated static public Date parseISODate ( String iso ) { DateFormatter df = new DateFormatter ( ) ; return df . getISODate ( iso ) ; }


Input: Convert an ISO formatted String to a CalendarDate . @param calt calendar may be null for default calendar ( Calendar . getDefault () ) @param iso ISO 8601 date String <pre > possible forms for W3C profile of ISO 8601 Year : YYYY ( eg 1997 ) Year and month : YYYY - MM ( eg 1997 - 07 ) Complete date : YYYY - MM - DD ( eg 1997 - 07 - 16 ) Complete date plus hours and minutes : YYYY - MM - DDThh : mmTZD ( eg 1997 - 07 - 16T19 : 20 + 01 : 00 ) Complete date plus hours minutes and seconds : YYYY - MM - DDThh : mm : ssTZD ( eg 1997 - 07 - 16T19 : 20 : 30 + 01 : 00 ) Complete date plus hours minutes seconds and a decimal fraction of a second YYYY - MM - DDThh : mm : ss . sTZD ( eg 1997 - 07 - 16T19 : 20 : 30 . 45 + 01 : 00 ) [CODESPLIT] static public CalendarDate isoStringToCalendarDate ( Calendar calt , String iso ) throws IllegalArgumentException { DateTime dt = parseIsoTimeString ( calt , iso ) ; Calendar useCal = Calendar . of ( dt . getChronology ( ) ) ; return new CalendarDate ( useCal , dt ) ; }


Input: Does not handle non - standard Calendars [CODESPLIT] static public Date isoStringToDate ( String iso ) throws IllegalArgumentException { CalendarDate dt = isoStringToCalendarDate ( null , iso ) ; return dt . toDate ( ) ; }


Input: wml2 : MeasurementTVP [CODESPLIT] public static MeasureTVPType initMeasurementTVP ( MeasureTVPType measurementTVP , PointFeature pointFeat , VariableSimpleIF dataVar ) throws IOException { // wml2:time NcTimePositionType . initTime ( measurementTVP . addNewTime ( ) , pointFeat ) ; // wml2:value NcMeasureType . initValue ( measurementTVP . addNewValue ( ) , pointFeat , dataVar ) ; return measurementTVP ; }


Input: Reads a URL or file in as a table . [CODESPLIT] static public List < Record > readTable ( String urlString , String format , int maxLines ) throws IOException , NumberFormatException { InputStream ios ; if ( urlString . startsWith ( "http:" ) ) { URL url = new URL ( urlString ) ; ios = url . openStream ( ) ; } else { ios = new FileInputStream ( urlString ) ; } return readTable ( ios , format , maxLines ) ; }


Input: Reads an input stream containing lines of ascii in fixed width format . Breaks each line into a set of Fields ( space or comma delimited ) which may be String integer or double . [CODESPLIT] static public List < Record > readTable ( InputStream ios , String format , int maxLines ) throws IOException , NumberFormatException { List < Record > result ; try { TableParser parser = new TableParser ( format ) ; result = parser . readAllRecords ( ios , maxLines ) ; } finally { ios . close ( ) ; } return result ; }


Input: Copy contents of src to target . skip ones that already exist ( by name ) . Dimensions and Variables are replaced with equivalent elements but unlimited dimensions are turned into regular dimensions . Attribute doesnt have to be replaced because its immutable so its copied by reference . [CODESPLIT] static public void transferDataset ( NetcdfFile src , NetcdfDataset target , ReplaceVariableCheck replaceCheck ) { transferGroup ( src , target , src . getRootGroup ( ) , target . getRootGroup ( ) , replaceCheck ) ; }


Input: transfer the objects in src group to the target group [CODESPLIT] static private void transferGroup ( NetcdfFile ds , NetcdfDataset targetDs , Group src , Group targetGroup , ReplaceVariableCheck replaceCheck ) { boolean unlimitedOK = true ; // LOOK why not allowed? // group attributes transferGroupAttributes ( src , targetGroup ) ; // dimensions for ( Dimension d : src . getDimensions ( ) ) { if ( null == targetGroup . findDimensionLocal ( d . getShortName ( ) ) ) { Dimension newd = new Dimension ( d . getShortName ( ) , d . getLength ( ) , d . isShared ( ) , unlimitedOK && d . isUnlimited ( ) , d . isVariableLength ( ) ) ; targetGroup . addDimension ( newd ) ; } } // variables for ( Variable v : src . getVariables ( ) ) { Variable targetV = targetGroup . findVariable ( v . getShortName ( ) ) ; VariableEnhanced targetVe = ( VariableEnhanced ) targetV ; boolean replace = ( replaceCheck != null ) && replaceCheck . replace ( v ) ; // replaceCheck not currently used if ( replace || ( null == targetV ) ) { // replace it if ( ( v instanceof Structure ) && ! ( v instanceof StructureDS ) ) { v = new StructureDS ( targetGroup , ( Structure ) v ) ; // else if (!(v instanceof VariableDS) && !(v instanceof StructureDS)) Doug Lindolm } else if ( ! ( v instanceof VariableDS ) ) { v = new VariableDS ( targetGroup , v , false ) ; // enhancement done by original variable, this is just to reparent to target dataset. } if ( null != targetV ) targetGroup . remove ( targetV ) ; targetGroup . addVariable ( v ) ; // reparent group v . resetDimensions ( ) ; // dimensions will be different } else if ( ! targetV . hasCachedData ( ) && ( targetVe . getOriginalVariable ( ) == null ) ) { // this is the case where we defined the variable, but didnt set its data. we now set it with the first nested // dataset that has a variable with the same name targetVe . setOriginalVariable ( v ) ; } } // nested groups - check if target already has it for ( Group srcNested : src . getGroups ( ) ) { Group nested = targetGroup . findGroup ( srcNested . getShortName ( ) ) ; if ( null == nested ) { nested = new Group ( ds , targetGroup , srcNested . getShortName ( ) ) ; targetGroup . addGroup ( nested ) ; } transferGroup ( ds , targetDs , srcNested , nested , replaceCheck ) ; } }


Input: Copy attributes from src to target skip ones that already exist ( by name ) [CODESPLIT] static public void transferVariableAttributes ( Variable src , Variable target ) { for ( Attribute a : src . getAttributes ( ) ) { if ( null == target . findAttribute ( a . getShortName ( ) ) ) target . addAttribute ( a ) ; } }


Input: Copy attributes from src to target skip ones that already exist ( by name ) [CODESPLIT] static public void transferGroupAttributes ( Group src , Group target ) { for ( Attribute a : src . getAttributes ( ) ) { if ( null == target . findAttribute ( a . getShortName ( ) ) ) target . addAttribute ( a ) ; } }


Input: Find the Group in newFile that corresponds ( by name ) with oldGroup [CODESPLIT] static public Group findGroup ( NetcdfFile newFile , Group oldGroup ) { List < Group > chain = new ArrayList <> ( 5 ) ; Group g = oldGroup ; while ( g . getParentGroup ( ) != null ) { // skip the root chain . add ( 0 , g ) ; // put in front g = g . getParentGroup ( ) ; } Group newg = newFile . getRootGroup ( ) ; for ( Group oldg : chain ) { newg = newg . findGroup ( oldg . getShortName ( ) ) ; if ( newg == null ) return null ; } return newg ; }


Input: stn file must be in the same directory or one up [CODESPLIT] private File getStnFile ( String location ) { File file = new File ( location ) ; File stnFile = new File ( file . getParentFile ( ) , STN_FILE ) ; if ( ! stnFile . exists ( ) ) { if ( file . getParentFile ( ) == null ) return null ; stnFile = new File ( file . getParentFile ( ) . getParentFile ( ) , STN_FILE ) ; if ( ! stnFile . exists ( ) ) return null ; } return stnFile ; }


Input:
if a DAT file [CODESPLIT] @ Override public void open ( RandomAccessFile raff , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raff , ncfile , cancelTask ) ; int pos = location . lastIndexOf ( "." ) ; String ext = location . substring ( pos ) ; File file = new File ( location ) ; File stnFile = getStnFile ( location ) ; if ( stnFile == null ) throw new FileNotFoundException ( "Station File does not exist=" + location ) ; if ( ext . equals ( IDX_EXT ) ) { stnRaf = RandomAccessFile . acquire ( stnFile . getPath ( ) ) ; } else if ( ext . equals ( DAT_EXT ) ) { stnRaf = RandomAccessFile . acquire ( stnFile . getPath ( ) ) ; dataRaf = raff ; //extract the station id
 String name = file . getName ( ) ; stationId = name . substring ( 0 , name . length ( ) - DAT_EXT . length ( ) ) ; } else { // pointed to the station file
 stnRaf = raff ; dataDir = new File ( file . getParentFile ( ) , DAT_DIR ) ; } NcmlConstructor ncmlc = new NcmlConstructor ( ) ; if ( ! ncmlc . populateFromResource ( "resources/nj22/iosp/igra-por.ncml" , ncfile ) ) { throw new IllegalStateException ( ncmlc . getErrlog ( ) . toString ( ) ) ; } ncfile . finish ( ) ; //dataVinfo = setVinfo(dataRaf, ncfile, dataPattern, "all_data");
 stnVinfo = setVinfo ( stnRaf , ncfile , stnPattern , "station" ) ; seriesVinfo = setVinfo ( stnRaf , ncfile , dataHeaderPattern , "station.time_series" ) ; profileVinfo = setVinfo ( stnRaf , ncfile , dataPattern , "station.time_series.levels" ) ; StructureMembers . Member m = stnVinfo . sm . findMember ( STNID ) ; StructureDataRegexp . VinfoField f = ( StructureDataRegexp . VinfoField ) m . getDataObject ( ) ; stn_fldno = f . fldno ; /* make index file if needed
    File idxFile = new File(base + IDX_EXT);
    if (!idxFile.exists())
      makeIndex(stnVinfo, dataVinfo, idxFile);
    else
      readIndex(idxFile.getPath());  */ }


Input: ////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { StructureDataRegexp . Vinfo vinfo = ( StructureDataRegexp . Vinfo ) v2 . getSPobject ( ) ; if ( stationId != null ) return new ArraySequence ( vinfo . sm , new SingleStationSeqIter ( vinfo ) , vinfo . nelems ) ; else return new ArraySequence ( vinfo . sm , new StationSeqIter ( vinfo ) , vinfo . nelems ) ; }


Input: ///////////////////////////// [CODESPLIT] public SubsetParams makeSubset ( CoverageCollection gcd ) { Calendar cal = gcd . getCalendar ( ) ; boolean isFmrc = gcd . getCoverageType ( ) == FeatureType . FMRC ; SubsetParams subset = new SubsetParams ( ) ; // vars subset . set ( SubsetParams . variables , var ) ; // other coords if ( vertCoord != null ) subset . set ( SubsetParams . vertCoord , vertCoord ) ; if ( ensCoord != null ) subset . set ( SubsetParams . ensCoord , ensCoord ) ; // horiz subset if ( hasProjectionBB ( ) ) subset . set ( SubsetParams . projBB , getProjectionBB ( ) ) ; else if ( hasLatLonBB ( ) ) subset . set ( SubsetParams . latlonBB , getLatLonBoundingBox ( ) ) ; if ( horizStride != null && horizStride != 1 ) subset . set ( SubsetParams . horizStride , horizStride ) ; if ( hasLatLonPoint ( ) ) subset . set ( SubsetParams . latlonPoint , new LatLonPointImpl ( getLatitude ( ) , getLongitude ( ) ) ) ; if ( isFmrc ) { // 2D Time subsetting // runtime CalendarDate rundate = getRuntimeDate ( cal ) ; if ( rundate != null ) subset . set ( SubsetParams . runtime , rundate ) ; else if ( allRuntime ) subset . set ( SubsetParams . runtimeAll , true ) ; else subset . set ( SubsetParams . runtimeLatest , true ) ; // default // timeOffset if ( timeOffsetVal != null ) subset . set ( SubsetParams . timeOffset , timeOffsetVal ) ; else if ( firstTimeOffset ) subset . set ( SubsetParams . timeOffsetFirst , true ) ; else { // if no timeOffset, will allow some time values CalendarDate date = getRequestedDate ( cal ) ; CalendarDateRange dateRange = getCalendarDateRange ( cal ) ; if ( isPresentTime ( ) ) subset . setTimePresent ( ) ; else if ( isAllTimes ( ) && ! allRuntime ) { subset . set ( SubsetParams . timeAll , true ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } else if ( date != null ) { // for allRuntimes, only a date is allowed subset . set ( SubsetParams . time , date ) ; } else if ( dateRange != null && ! allRuntime ) { subset . set ( SubsetParams . timeRange , dateRange ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } } } else { // not an FMRC // time CalendarDate date = getRequestedDate ( cal ) ; CalendarDateRange dateRange = getCalendarDateRange ( cal ) ; if ( isPresentTime ( ) ) subset . setTimePresent ( ) ; else if ( isAllTimes ( ) ) { subset . set ( SubsetParams . timeAll , true ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } else if ( date != null ) { subset . set ( SubsetParams . time , date ) ; } else if ( dateRange != null ) { subset . set ( SubsetParams . timeRange , dateRange ) ; if ( timeStride != null && timeStride != 1 ) subset . set ( SubsetParams . timeStride , timeStride ) ; } else { subset . set ( SubsetParams . timePresent , true ) ; } } return subset ; }


Input: Finds the first instance of c at or after fromIndex ( 0 .. ) in cArray . [CODESPLIT] public static int indexOf ( char [ ] cArray , char c , int fromIndex ) { int cArrayLength = cArray . length ; for ( int index = Math . max ( fromIndex , 0 ) ; index < cArrayLength ; index ++ ) { if ( cArray [ index ] == c ) return index ; } return - 1 ; }


Input: This includes hiASCII / ISO Latin 1 / ISO 8859 - 1 but not extensive unicode characters . Letters are A .. Z a .. z and #192 .. #255 ( except #215 and #247 ) . For unicode characters see Java Lang Spec pg 14 . [CODESPLIT] public static boolean isLetter ( int c ) { //return (((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')) //|| ((c >= '\u00c0') && (c <= '\u00FF') && (c != '\u00d7') //&& (c != '\u00f7'))); if ( c < ' ' ) return false ; if ( c <= ' ' ) return true ; if ( c < ' ' ) return false ; if ( c <= ' ' ) return true ; if ( c < ' ' ) return false ; if ( c == ' ' ) return false ; if ( c <= ' ' ) return true ; return false ; }


Input: Returns a string where all occurences of <TT > oldCh< / TT > have been replaced with <TT > newCh< / TT > . This doesn t throw exceptions if bad values . [CODESPLIT] public static String replaceAll ( String s , char oldCh , char newCh ) { int po = s . indexOf ( oldCh ) ; if ( po < 0 ) return s ; StringBuilder buffer = new StringBuilder ( s ) ; while ( po >= 0 ) { buffer . setCharAt ( po , newCh ) ; po = s . indexOf ( oldCh , po + 1 ) ; } return buffer . toString ( ) ; }


Input: Convert a string to an int . Leading or trailing spaces are automatically removed . This accepts hexadecimal integers starting with 0x . Leading 0 s ( e . g . 0012 ) are ignored ; number is treated as decimal ( not octal as Java would ) . Floating point numbers are rounded . This won t throw an exception if the number isn t formatted right . To make a string from an int use + i Integer . toHexString or Integer . toString ( i radix ) . [CODESPLIT] public static int parseInt ( String s ) { //*** XML.decodeEntities relies on leading 0's being ignored  //    and number treated as decimal (not octal) //quickly reject most non-numbers //This is a huge speed improvement when parsing ASCII data files //  because Java is very slow at filling in the stack trace when an exception is thrown. if ( s == null ) return Integer . MAX_VALUE ; s = s . trim ( ) ; if ( s . length ( ) == 0 ) return Integer . MAX_VALUE ; char ch = s . charAt ( 0 ) ; if ( ( ch < ' ' || ch > ' ' ) && ch != ' ' && ch != ' ' && ch != ' ' ) return Integer . MAX_VALUE ; //try to parse hex or regular int         try { if ( s . startsWith ( "0x" ) ) return Integer . parseInt ( s . substring ( 2 ) , 16 ) ; return Integer . parseInt ( s ) ; } catch ( Exception e ) { //falls through } //round from double? try { //2011-02-09 Bob Simons added to avoid Java hang bug. //But now, latest version of Java is fixed. //if (isDoubleTrouble(s)) return 0;   return ErddapMath2 . roundToInt ( Double . parseDouble ( s ) ) ; } catch ( Exception e ) { return Integer . MAX_VALUE ; } }


Input: Convert a string to a double . Leading or trailing spaces are automatically removed . This accepts hexadecimal integers starting with 0x . Whole number starting with 0 ( e . g . 012 ) is treated as decimal ( not octal as Java would ) . This won t throw an exception if the number isn t formatted right . [CODESPLIT] public static double parseDouble ( String s ) { //quickly reject most non-numbers //This is a huge speed improvement when parsing ASCII data files //  because Java is very slow at filling in the stack trace when an exception is thrown. if ( s == null ) return Double . NaN ; s = s . trim ( ) ; if ( s . length ( ) == 0 ) return Double . NaN ; char ch = s . charAt ( 0 ) ; if ( ( ch < ' ' || ch > ' ' ) && ch != ' ' && ch != ' ' && ch != ' ' ) return Double . NaN ; try { if ( s . startsWith ( "0x" ) ) return Integer . parseInt ( s . substring ( 2 ) , 16 ) ; //2011-02-09 Bob Simons added to avoid Java hang bug. //But now, latest version of Java is fixed. //if (isDoubleTrouble(s)) return 0;   return Double . parseDouble ( s ) ; } catch ( Exception e ) { return Double . NaN ; } }


Input: This converts String representation of a long . Leading or trailing spaces are automatically removed . This * doesn t * round . So floating point values lead to Long . MAX_VALUE . [CODESPLIT] public static long parseLong ( String s ) { //quickly reject most non-numbers //This is a huge speed improvement when parsing ASCII data files //  because Java is very slow at filling in the stack trace when an exception is thrown. if ( s == null ) return Long . MAX_VALUE ; s = s . trim ( ) ; if ( s . length ( ) == 0 ) return Long . MAX_VALUE ; char ch = s . charAt ( 0 ) ; if ( ( ch < ' ' || ch > ' ' ) && ch != ' ' && ch != ' ' ) return Long . MAX_VALUE ; try { if ( s . startsWith ( "0x" ) ) return Long . parseLong ( s . substring ( 2 ) , 16 ) ; return Long . parseLong ( s ) ; } catch ( Exception e ) { return Long . MAX_VALUE ; } }


Input: This converts a double to a rational number ( m * 10^t ) . This is similar to Math2 . mantissa and Math2 . intExponent but works via string manipulation to avoid roundoff problems ( e . g . with 6 . 6260755e - 24 ) . [CODESPLIT] public static int [ ] toRational ( double d ) { if ( d == 0 ) return new int [ ] { 0 , 0 } ; if ( ! ErddapMath2 . isFinite ( d ) ) return new int [ ] { 1 , Integer . MAX_VALUE } ; String s = "" + d ; //-12.0 or 6.6260755E-24 //String2.log("\nd=" + d + "\ns=" + s); int ten = 0 ; //remove the e int epo = s . indexOf ( ' ' ) ; if ( epo > 0 ) { ten = parseInt ( s . substring ( epo + 1 ) ) ; s = s . substring ( 0 , epo ) ; //String2.log("remove E s=" + s + " ten=" + ten); } //remove .0; remove decimal point if ( s . endsWith ( ".0" ) ) s = s . substring ( 0 , s . length ( ) - 2 ) ; int dpo = s . indexOf ( ' ' ) ; if ( dpo > 0 ) { ten -= s . length ( ) - dpo - 1 ; s = s . substring ( 0 , dpo ) + s . substring ( dpo + 1 ) ; //String2.log("remove . s=" + s + " ten=" + ten); } //convert s to long //need to lose some precision? long tl = parseLong ( s ) ; //String2.log("tl=" + tl + " s=" + s); while ( Math . abs ( tl ) > 1000000000 ) { tl = Math . round ( tl / 10.0 ) ; ten ++ ; //String2.log("tl=" + tl + " ten=" + ten); } //remove trailing 0's while ( tl != 0 && tl / 10 == tl / 10.0 ) { tl /= 10 ; ten ++ ; //String2.log("remove 0 tl=" + tl + " ten=" + ten); } //add up to 3 0's? if ( tl < 100000 && ten >= 1 && ten <= 3 ) { while ( ten > 0 ) { tl *= 10 ; ten -- ; } } return new int [ ] { ( int ) tl , ten } ; //safe since large values handled above }


Input:
Gets the beginning index of a geometry s points given the index of the geometry within the array . [CODESPLIT] public int getBeginning ( int index ) { //Test if the last end is the new beginning
 if ( index == ( pastIndex + 1 ) ) { return previousEnd + 1 ; } // Otherwise, find it!
 int newBeginning = 0 ; for ( int i = 0 ; i < index ; i ++ ) { newBeginning += getNodeCount ( i ) ; } pastIndex = index ; previousBegin = newBeginning ; return newBeginning ; }


Input:
Gets the ending index of a geometry s points given the index of the geometry within the array . [CODESPLIT] public int getEnd ( int index ) { // Test if the last beginning is the new end
 if ( index == ( pastIndex - 1 ) ) { return previousBegin - 1 ; } // Otherwise find it!
 int new_end = 0 ; for ( int i = 0 ; i < index + 1 ; i ++ ) { new_end += getNodeCount ( i ) ; } pastIndex = index ; previousEnd = new_end ; return new_end - 1 ; }


Input:
************************************************************************ Default handler for OPeNDAP ascii requests . Returns OPeNDAP DAP2 data in comma delimited ascii columns for ingestion into some not so OPeNDAP enabled application such as MS - Excel . Accepts constraint expressions in exactly the same way as the regular OPeNDAP dataserver . [CODESPLIT] public void sendASCII ( ReqState rs , String dataSet ) throws DAP2Exception , ParseException { if ( Debug . isSet ( "showResponse" ) ) System . out . println ( "Sending OPeNDAP ASCII Data For: " + dataSet + "    CE: '" + rs . getConstraintExpression ( ) + "'" ) ; String requestURL , ce ; DataDDS dds ; if ( rs . getConstraintExpression ( ) == null ) { ce = "" ; } else { ce = "?" + rs . getConstraintExpression ( ) ; } int suffixIndex = rs . getRequestURL ( ) . toString ( ) . lastIndexOf ( "." ) ; requestURL = rs . getRequestURL ( ) . substring ( 0 , suffixIndex ) ; if ( Debug . isSet ( "showResponse" ) ) { System . out . println ( "New Request URL Resource: '" + requestURL + "'" ) ; System . out . println ( "New Request Constraint Expression: '" + ce + "'" ) ; } if ( _Debug ) System . out . println ( "Making connection to .dods service..." ) ; try ( DConnect2 url = new DConnect2 ( requestURL , true ) ) { if ( _Debug ) System . out . println ( "Requesting data..." ) ; dds = url . getData ( ce , null , new asciiFactory ( ) ) ; if ( _Debug ) System . out . println ( " ASC DDS: " ) ; if ( _Debug ) dds . print ( System . out ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; PrintWriter pwDebug = new PrintWriter ( new OutputStreamWriter ( System . out , Util . UTF8 ) ) ; if ( dds != null ) { dds . print ( pw ) ; pw . println ( "---------------------------------------------" ) ; String s = "" ; Enumeration e = dds . getVariables ( ) ; while ( e . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; if ( _Debug ) ( ( toASCII ) bt ) . toASCII ( pwDebug , true , null , true ) ; //bt.toASCII(pw,addName,getNAme(),true);
 ( ( toASCII ) bt ) . toASCII ( pw , true , null , true ) ; } } else { String betterURL = rs . getRequestURL ( ) . substring ( 0 , rs . getRequestURL ( ) . lastIndexOf ( "." ) ) + ".dods?" + rs . getConstraintExpression ( ) ; pw . println ( "-- ASCII RESPONSE HANDLER PROBLEM --" ) ; pw . println ( "" ) ; pw . println ( "The ASCII response handler was unable to obtain requested data set." ) ; pw . println ( "" ) ; pw . println ( "Because this handler calls it's own OPeNDAP server to get the requested" ) ; pw . println ( "data the source error is obscured." ) ; pw . println ( "" ) ; pw . println ( "To get a better idea of what is going wrong, try requesting the URL:" ) ; pw . println ( "" ) ; pw . println ( "    " + betterURL ) ; pw . println ( "" ) ; pw . println ( "And then look carefully at the returned document. Note that if you" ) ; pw . println ( "are using a browser to access the URL the returned document will" ) ; pw . println ( "more than likely be treated as a download and written to your" ) ; pw . println ( "local disk. It should be a file with the extension \".dods\"" ) ; pw . println ( "" ) ; pw . println ( "Locate it, open it with a text editor, and find your" ) ; pw . println ( "way to happiness and inner peace." ) ; pw . println ( "" ) ; } //pw.println("</pre>");
 pw . flush ( ) ; if ( _Debug ) pwDebug . flush ( ) ; } catch ( FileNotFoundException fnfe ) { System . out . println ( "OUCH! FileNotFoundException: " + fnfe . getMessage ( ) ) ; fnfe . printStackTrace ( System . out ) ; } catch ( MalformedURLException mue ) { System . out . println ( "OUCH! MalformedURLException: " + mue . getMessage ( ) ) ; mue . printStackTrace ( System . out ) ; } catch ( IOException ioe ) { System . out . println ( "OUCH! IOException: " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( System . out ) ; } catch ( Throwable t ) { System . out . println ( "OUCH! Throwable: " + t . getMessage ( ) ) ; t . printStackTrace ( System . out ) ; } if ( _Debug ) System . out . println ( " GetAsciiHandler done" ) ; }


Input: Throw exception if failure [CODESPLIT] boolean createIndex ( FeatureCollectionConfig . PartitionType ptype , Formatter errlog ) throws IOException { if ( ptype == FeatureCollectionConfig . PartitionType . all ) return createAllRuntimeCollections ( errlog ) ; else return createMultipleRuntimeCollections ( errlog ) ; }


Input:
Throw exception if failure [CODESPLIT] private boolean createMultipleRuntimeCollections ( Formatter errlog ) throws IOException { long start = System . currentTimeMillis ( ) ; List < MFile > files = new ArrayList <> ( ) ; List < ? extends Group > groups = makeGroups ( files , false , errlog ) ; List < MFile > allFiles = Collections . unmodifiableList ( files ) ; if ( allFiles . size ( ) == 0 ) { throw new IllegalStateException ( "No files in this collection =" + name + " topdir=" + dcm . getRoot ( ) ) ; } if ( groups . size ( ) == 0 ) { throw new IllegalStateException ( "No records in this collection =" + name + " topdir=" + dcm . getRoot ( ) ) ; } // Create the master runtimes, classify the result CalendarDateRange calendarDateRangeAll = null ; //boolean allTimesAreOne = true; boolean allTimesAreUnique = true ; Set < Long > allRuntimes = new HashSet <> ( ) ; for ( Group g : groups ) { allRuntimes . addAll ( g . getCoordinateRuntimes ( ) ) ; for ( Coordinate coord : g . getCoordinates ( ) ) { if ( coord instanceof CoordinateTime2D ) { CoordinateTime2D coord2D = ( CoordinateTime2D ) coord ; if ( allTimesAreUnique ) { allTimesAreUnique = coord2D . hasUniqueTimes ( ) ; } } if ( coord instanceof CoordinateTimeAbstract ) { CalendarDateRange calendarDateRange = ( ( CoordinateTimeAbstract ) coord ) . makeCalendarDateRange ( null ) ; if ( calendarDateRangeAll == null ) calendarDateRangeAll = calendarDateRange ; else calendarDateRangeAll = calendarDateRangeAll . extend ( calendarDateRange ) ; } } } List < Long > sortedList = new ArrayList <> ( allRuntimes ) ; Collections . sort ( sortedList ) ; if ( sortedList . size ( ) == 0 ) throw new IllegalArgumentException ( "No runtimes in this collection =" + name ) ; else if ( sortedList . size ( ) == 1 ) this . type = GribCollectionImmutable . Type . SRC ; else if ( allTimesAreUnique ) this . type = GribCollectionImmutable . Type . MRUTC ; else this . type = GribCollectionImmutable . Type . MRC ; CoordinateRuntime masterRuntimes = new CoordinateRuntime ( sortedList , null ) ; MFile indexFileForRuntime = GribCollectionMutable . makeIndexMFile ( this . name , directory ) ; boolean ok = writeIndex ( this . name , indexFileForRuntime . getPath ( ) , masterRuntimes , groups , allFiles , calendarDateRangeAll ) ; /* if (this.type ==  GribCollectionImmutable.Type.MRC) {
      GribBestDatasetBuilder.makeDatasetBest();
    } */ long took = System . currentTimeMillis ( ) - start ; logger . debug ( "That took {} msecs" , took ) ; return ok ; }


Input: creates seperate collection and index for each runtime . [CODESPLIT] private boolean createAllRuntimeCollections ( Formatter errlog ) throws IOException { long start = System . currentTimeMillis ( ) ; this . type = GribCollectionImmutable . Type . SRC ; boolean ok = true ; List < MFile > files = new ArrayList <> ( ) ; List < ? extends Group > groups = makeGroups ( files , true , errlog ) ; List < MFile > allFiles = Collections . unmodifiableList ( files ) ; // gather into collections with a single runtime Map < Long , List < Group > > runGroups = new HashMap <> ( ) ; for ( Group g : groups ) { List < Group > runGroup = runGroups . computeIfAbsent ( g . getRuntime ( ) . getMillis ( ) , k -> new ArrayList <> ( ) ) ; runGroup . add ( g ) ; } // write each rungroup separately boolean multipleRuntimes = runGroups . values ( ) . size ( ) > 1 ; List < MFile > partitions = new ArrayList <> ( ) ; for ( List < Group > runGroupList : runGroups . values ( ) ) { Group g = runGroupList . get ( 0 ) ; // if multiple Runtimes, we will write a partition. otherwise, we need to use the standard name (without runtime) so we know the filename from the collection String gcname = multipleRuntimes ? GribCollectionMutable . makeName ( this . name , g . getRuntime ( ) ) : this . name ; MFile indexFileForRuntime = GribCollectionMutable . makeIndexMFile ( gcname , directory ) ; // not using disk cache LOOK why ? partitions . add ( indexFileForRuntime ) ; // create the master runtimes, consisting of the single runtime List < Long > runtimes = new ArrayList <> ( 1 ) ; runtimes . add ( g . getRuntime ( ) . getMillis ( ) ) ; CoordinateRuntime masterRuntimes = new CoordinateRuntime ( runtimes , null ) ; CalendarDateRange calendarDateRangeAll = null ; for ( Coordinate coord : g . getCoordinates ( ) ) { if ( coord instanceof CoordinateTimeAbstract ) { CalendarDateRange calendarDateRange = ( ( CoordinateTimeAbstract ) coord ) . makeCalendarDateRange ( null ) ; if ( calendarDateRangeAll == null ) calendarDateRangeAll = calendarDateRange ; else calendarDateRangeAll = calendarDateRangeAll . extend ( calendarDateRange ) ; } } assert calendarDateRangeAll != null ; // for each Group write an index file ok &= writeIndex ( gcname , indexFileForRuntime . getPath ( ) , masterRuntimes , runGroupList , allFiles , calendarDateRangeAll ) ; logger . info ( "GribCollectionBuilder write {} ok={}" , indexFileForRuntime . getPath ( ) , ok ) ; } // if theres more than one runtime, create a partition collection to collect all the runtimes together if ( multipleRuntimes ) { Collections . sort ( partitions ) ; // ?? PartitionManager part = new PartitionManagerFromIndexList ( dcm , partitions , logger ) ; part . putAuxInfo ( FeatureCollectionConfig . AUX_CONFIG , dcm . getAuxInfo ( FeatureCollectionConfig . AUX_CONFIG ) ) ; ok &= GribCdmIndex . updateGribCollectionFromPCollection ( isGrib1 , part , CollectionUpdateType . always , errlog , logger ) ; } long took = System . currentTimeMillis ( ) - start ; logger . debug ( "That took {} msecs" , took ) ; return ok ; }


Input: See if edit value is valid put error message in buff . [CODESPLIT] protected boolean _validate ( StringBuffer buff ) { String editValue = tf . getText ( ) . trim ( ) ; if ( editValue . length ( ) == 0 ) return true ; // empty ok try { new TimeDuration ( tf . getText ( ) ) ; return true ; } catch ( java . text . ParseException e ) { buff . append ( label ) . append ( ": " ) . append ( e . getMessage ( ) ) ; return false ; } }


Input: get current value from editComponent [CODESPLIT] protected Object getEditValue ( ) { String editValue = tf . getText ( ) . trim ( ) ; if ( editValue . length ( ) == 0 ) return null ; // empty ok try { return new TimeDuration ( editValue ) ; } catch ( java . text . ParseException e ) { return null ; } }


Input: set current value of editComponent [CODESPLIT] protected void setEditValue ( Object value ) { if ( value == null ) tf . setText ( "" ) ; else tf . setText ( value . toString ( ) ) ; // tf.repaint(); }


Input:
Return the string of entity ID for the Dorade image file [CODESPLIT] DataType getDataType ( int format ) { DataType p ; switch ( format ) { case 1 : // 8-bit signed integer format.
 p = DataType . SHORT ; break ; case 2 : // 16-bit signed integer format.
 p = DataType . FLOAT ; break ; case 3 : // 32-bit signed integer format.
 p = DataType . LONG ; break ; case 4 : // 32-bit IEEE float format.
 p = DataType . FLOAT ; break ; case 5 : //  16-bit IEEE float format.
 p = DataType . DOUBLE ; break ; default : p = null ; break ; } //end of switch
 return p ; }