Input: ////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] static private NetcdfFile acquireNcml ( FileCache cache , FileFactory factory , Object hashKey , String location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object spiObject ) throws IOException { if ( cache == null ) return NcMLReader . readNcML ( location , cancelTask ) ; if ( factory == null ) factory = new NcMLFactory ( ) ; // LOOK maybe always should use NcMLFactory ? return ( NetcdfFile ) cache . acquire ( factory , hashKey , DatasetUrl . findDatasetUrl ( location ) , buffer_size , cancelTask , spiObject ) ; }


Input: Clear Coordinate System metadata to allow them to be redone [CODESPLIT] public void clearCoordinateSystems ( ) { coordSys = new ArrayList <> ( ) ; coordAxes = new ArrayList <> ( ) ; coordTransforms = new ArrayList <> ( ) ; for ( Variable v : getVariables ( ) ) { VariableEnhanced ve = ( VariableEnhanced ) v ; ve . clearCoordinateSystems ( ) ; // ?? } enhanceMode . remove ( Enhance . CoordSystems ) ; }


Input: Retrieve the CoordinateAxis with the specified Axis Type . [CODESPLIT] public CoordinateAxis findCoordinateAxis ( AxisType type ) { if ( type == null ) return null ; for ( CoordinateAxis v : coordAxes ) { if ( type == v . getAxisType ( ) ) return v ; } return null ; }


Input: Retrieve the CoordinateAxis with the specified type . [CODESPLIT] public CoordinateAxis findCoordinateAxis ( String fullName ) { if ( fullName == null ) return null ; for ( CoordinateAxis v : coordAxes ) { if ( fullName . equals ( v . getFullName ( ) ) ) return v ; } return null ; }


Input: Retrieve the CoordinateSystem with the specified name . [CODESPLIT] public CoordinateSystem findCoordinateSystem ( String name ) { if ( name == null ) return null ; for ( CoordinateSystem v : coordSys ) { if ( name . equals ( v . getName ( ) ) ) return v ; } return null ; }


Input: Retrieve the CoordinateTransform with the specified name . [CODESPLIT] public CoordinateTransform findCoordinateTransform ( String name ) { if ( name == null ) return null ; for ( CoordinateTransform v : coordTransforms ) { if ( name . equals ( v . getName ( ) ) ) return v ; } return null ; }


Input: Close all resources ( files sockets etc ) associated with this dataset . If the underlying file was acquired it will be released otherwise closed . [CODESPLIT] @ Override public synchronized void close ( ) throws java . io . IOException { if ( agg != null ) { agg . persistWrite ( ) ; // LOOK  maybe only on real close ?? agg . close ( ) ; } if ( cache != null ) { //unlocked = true; if ( cache . release ( this ) ) return ; } if ( orgFile != null ) orgFile . close ( ) ; orgFile = null ; }


Input:
//////////////////////////////////// [CODESPLIT] @ Override protected Boolean makeRecordStructure ( ) { if ( this . orgFile == null ) return false ; Boolean hasRecord = ( Boolean ) this . orgFile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ( hasRecord == null ) || ! hasRecord ) return false ; Variable orgV = this . orgFile . getRootGroup ( ) . findVariable ( "record" ) ; if ( ( orgV == null ) || ! ( orgV instanceof Structure ) ) return false ; Structure orgStructure = ( Structure ) orgV ; Dimension udim = getUnlimitedDimension ( ) ; if ( udim == null ) return false ; Group root = getRootGroup ( ) ; StructureDS newStructure = new StructureDS ( this , root , null , "record" , udim . getShortName ( ) , null , null ) ; newStructure . setOriginalVariable ( orgStructure ) ; for ( Variable v : getVariables ( ) ) { if ( ! v . isUnlimited ( ) ) continue ; VariableDS memberV ; try { memberV = ( VariableDS ) v . slice ( 0 , 0 ) ; // set unlimited dimension to 0 } catch ( InvalidRangeException e ) { log . error ( "Cant slice variable " + v ) ; return false ; } memberV . setParentStructure ( newStructure ) ; // reparent /* memberV.createNewCache(); // decouple caching
      //orgV = orgStructure.findVariable(v.getShortName());
      //if (orgV != null)
      //  memberV.setOriginalVariable(orgV);

      // remove record dimension
      List<Dimension> dims = new ArrayList<Dimension>(v.getDimensions());
      dims.remove(0);
      memberV.setDimensions(dims); */ newStructure . addMemberVariable ( memberV ) ; } root . addVariable ( newStructure ) ; finish ( ) ; //if (isEnhancedScaleOffset()) //  newStructure.enhance(); return true ; }


Input: Add a CoordinateAxis to the dataset by turning the VariableDS into a CoordinateAxis ( if needed ) . Also adds it to the list of variables . Replaces any existing Variable and CoordinateAxis with the same name . [CODESPLIT] public CoordinateAxis addCoordinateAxis ( VariableDS v ) { if ( v == null ) return null ; CoordinateAxis oldVar = findCoordinateAxis ( v . getFullName ( ) ) ; if ( oldVar != null ) coordAxes . remove ( oldVar ) ; CoordinateAxis ca = ( v instanceof CoordinateAxis ) ? ( CoordinateAxis ) v : CoordinateAxis . factory ( this , v ) ; coordAxes . add ( ca ) ; if ( v . isMemberOfStructure ( ) ) { Structure parentOrg = v . getParentStructure ( ) ; // gotta be careful to get the wrapping parent Structure parent = ( Structure ) findVariable ( parentOrg . getFullNameEscaped ( ) ) ; parent . replaceMemberVariable ( ca ) ; } else { removeVariable ( v . getParentGroup ( ) , v . getShortName ( ) ) ; // remove by short name if it exists addVariable ( ca . getParentGroup ( ) , ca ) ; } return ca ; }


Input: is this enhancement already done ? [CODESPLIT] public boolean enhanceNeeded ( Set < Enhance > want ) throws IOException { if ( want == null ) return false ; for ( Enhance mode : want ) { if ( ! this . enhanceMode . contains ( mode ) ) return true ; } return false ; }


Input: Generate the list of values from a starting value and an increment . Will reshape to variable if needed . [CODESPLIT] public void setValues ( Variable v , int npts , double start , double incr ) { if ( npts != v . getSize ( ) ) throw new IllegalArgumentException ( "bad npts = " + npts + " should be " + v . getSize ( ) ) ; Array data = Array . makeArray ( v . getDataType ( ) , npts , start , incr ) ; if ( v . getRank ( ) != 1 ) data = data . reshape ( v . getShape ( ) ) ; v . setCachedData ( data , true ) ; }


Input: Set the data values from a list of Strings . [CODESPLIT] public void setValues ( Variable v , List < String > values ) throws IllegalArgumentException { Array data = Array . makeArray ( v . getDataType ( ) , values ) ; if ( data . getSize ( ) != v . getSize ( ) ) throw new IllegalArgumentException ( "Incorrect number of values specified for the Variable " + v . getFullName ( ) + " needed= " + v . getSize ( ) + " given=" + data . getSize ( ) ) ; if ( v . getRank ( ) != 1 ) // dont have to reshape for rank 1 data = data . reshape ( v . getShape ( ) ) ; v . setCachedData ( data , true ) ; }


Input: Make a 1D array from a list of strings . [CODESPLIT] static public Array makeArray ( DataType dtype , List < String > stringValues ) throws NumberFormatException { return Array . makeArray ( dtype , stringValues ) ; }


Input: Show debug / underlying implementation details [CODESPLIT] @ Override public void getDetailInfo ( Formatter f ) { f . format ( "NetcdfDataset location= %s%n" , getLocation ( ) ) ; f . format ( "  title= %s%n" , getTitle ( ) ) ; f . format ( "  id= %s%n" , getId ( ) ) ; f . format ( "  fileType= %s%n" , getFileTypeId ( ) ) ; f . format ( "  fileDesc= %s%n" , getFileTypeDescription ( ) ) ; f . format ( "  class= %s%n" , getClass ( ) . getName ( ) ) ; if ( agg == null ) { f . format ( "  has no Aggregation element%n" ) ; } else { f . format ( "%nAggregation:%n" ) ; agg . getDetailInfo ( f ) ; } if ( orgFile == null ) { f . format ( "  has no referenced NetcdfFile%n" ) ; showCached ( f ) ; showProxies ( f ) ; } else { f . format ( "%nReferenced File:%n" ) ; f . format ( "%s" , orgFile . getDetailInfo ( ) ) ; } }


Input: / * Debugging : get the information from parsing [CODESPLIT] void dumpClasses ( Group g , PrintWriter out ) { out . println ( "Dimensions:" ) ; for ( Dimension ds : g . getDimensions ( ) ) { out . println ( "  " + ds . getShortName ( ) + " " + ds . getClass ( ) . getName ( ) ) ; } out . println ( "Atributes:" ) ; for ( Attribute a : g . getAttributes ( ) ) { out . println ( "  " + a . getShortName ( ) + " " + a . getClass ( ) . getName ( ) ) ; } out . println ( "Variables:" ) ; dumpVariables ( g . getVariables ( ) , out ) ; out . println ( "Groups:" ) ; for ( Group nested : g . getGroups ( ) ) { out . println ( "  " + nested . getFullName ( ) + " " + nested . getClass ( ) . getName ( ) ) ; dumpClasses ( nested , out ) ; } }


Input: Debugging [CODESPLIT] public static void debugDump ( PrintWriter out , NetcdfDataset ncd ) { String referencedLocation = ncd . orgFile == null ? "(null)" : ncd . orgFile . getLocation ( ) ; out . println ( "\nNetcdfDataset dump = " + ncd . getLocation ( ) + " url= " + referencedLocation + "\n" ) ; ncd . dumpClasses ( ncd . getRootGroup ( ) , out ) ; }


Input: LOOK : Can we use CFPointWriter . CommandLine for CLI parsing instead? Would that break existing scripts? [CODESPLIT] public static void main ( String arg [ ] ) throws IOException { String usage = "usage: ucar.nc2.dataset.NetcdfDataset -in <fileIn> -out <fileOut> [-isLargeFile] [-netcdf4]" ; if ( arg . length < 4 ) { System . out . println ( usage ) ; System . exit ( 0 ) ; } boolean isLargeFile = false ; boolean netcdf4 = false ; String datasetIn = null , datasetOut = null ; for ( int i = 0 ; i < arg . length ; i ++ ) { String s = arg [ i ] ; if ( s . equalsIgnoreCase ( "-in" ) ) datasetIn = arg [ i + 1 ] ; if ( s . equalsIgnoreCase ( "-out" ) ) datasetOut = arg [ i + 1 ] ; if ( s . equalsIgnoreCase ( "-isLargeFile" ) ) isLargeFile = true ; if ( s . equalsIgnoreCase ( "-netcdf4" ) ) netcdf4 = true ; } if ( ( datasetIn == null ) || ( datasetOut == null ) ) { System . out . println ( usage ) ; System . exit ( 0 ) ; } CancelTaskImpl cancel = new CancelTaskImpl ( ) ; NetcdfFile ncfileIn = ucar . nc2 . dataset . NetcdfDataset . openFile ( datasetIn , cancel ) ; System . out . printf ( "NetcdfDatataset read from %s write to %s " , datasetIn , datasetOut ) ; NetcdfFileWriter . Version version = netcdf4 ? NetcdfFileWriter . Version . netcdf4 : NetcdfFileWriter . Version . netcdf3 ; FileWriter2 writer = new ucar . nc2 . FileWriter2 ( ncfileIn , datasetOut , version , null ) ; writer . getNetcdfFileWriter ( ) . setLargeFile ( isLargeFile ) ; NetcdfFile ncfileOut = writer . write ( cancel ) ; if ( ncfileOut != null ) ncfileOut . close ( ) ; ncfileIn . close ( ) ; cancel . setDone ( true ) ; System . out . printf ( "%s%n" , cancel ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static FeatureDatasetPoint getPointDataset ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsPointDataset ( request , response ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static GridDataset getGridDataset ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsGridDataset ( request , response ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static CoverageCollection getCoverageCollection ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsCoverageDataset ( request , response ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public static NetcdfFile getNetcdfFile ( HttpServletRequest request , HttpServletResponse response , String path ) throws IOException { TdsRequestedDataset trd = new TdsRequestedDataset ( request , null ) ; if ( path != null ) trd . path = path ; return trd . openAsNetcdfFile ( request , response ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public FeatureDatasetPoint openAsPointDataset ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return datasetManager . openPointDataset ( request , response , path ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public CoverageCollection openAsCoverageDataset ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return datasetManager . openCoverageDataset ( request , response , path ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public GridDataset openAsGridDataset ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return isRemote ? ucar . nc2 . dt . grid . GridDataset . open ( path ) : datasetManager . openGridDataset ( request , response , path ) ; }


Input: return null means request has been handled and calling routine should exit without further processing [CODESPLIT] public NetcdfFile openAsNetcdfFile ( HttpServletRequest request , HttpServletResponse response ) throws IOException { return isRemote ? NetcdfDataset . openDataset ( path ) : datasetManager . openNetcdfFile ( request , response , path ) ; }


Input:
when we dont know how many in the iteration [CODESPLIT] private Array extractMemberArrayFromIteration ( StructureMembers . Member proxym , int [ ] rshape ) throws IOException { DataType dataType = proxym . getDataType ( ) ; Object dataArray = null ; int count = 0 ; int initial = 1000 ; try ( StructureDataIterator sdataIter = getStructureDataIterator ( ) ) { switch ( dataType ) { case DOUBLE : { ArrayList < Double > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; double [ ] data = sdata . getJavaArrayDouble ( realm ) ; for ( double aData : data ) result . ( aData ) ; count ++ ; } double [ ] da = new double [ result . size ( ) ] ; int i = 0 ; for ( Double d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case FLOAT : { ArrayList < Float > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; float [ ] data = sdata . getJavaArrayFloat ( realm ) ; for ( float aData : data ) result . ( aData ) ; count ++ ; } float [ ] da = new float [ result . size ( ) ] ; int i = 0 ; for ( Float d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case UBYTE : case BYTE : case ENUM1 : { ArrayList < Byte > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; byte [ ] data = sdata . getJavaArrayByte ( realm ) ; for ( byte aData : data ) result . ( aData ) ; count ++ ; } byte [ ] da = new byte [ result . size ( ) ] ; int i = 0 ; for ( Byte d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case USHORT : case SHORT : case ENUM2 : { ArrayList < Short > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; short [ ] data = sdata . getJavaArrayShort ( realm ) ; for ( short aData : data ) result . ( aData ) ; count ++ ; } short [ ] da = new short [ result . size ( ) ] ; int i = 0 ; for ( Short d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case UINT : case INT : case ENUM4 : { ArrayList < Integer > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; int [ ] data = sdata . getJavaArrayInt ( realm ) ; for ( int aData : data ) result . ( aData ) ; count ++ ; } int [ ] da = new int [ result . size ( ) ] ; int i = 0 ; for ( Integer d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case ULONG : case LONG : { ArrayList < Long > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; long [ ] data = sdata . getJavaArrayLong ( realm ) ; for ( long aData : data ) result . ( aData ) ; count ++ ; } long [ ] da = new long [ result . size ( ) ] ; int i = 0 ; for ( Long d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case CHAR : { ArrayList < Character > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; char [ ] data = sdata . getJavaArrayChar ( realm ) ; for ( char aData : data ) result . ( aData ) ; count ++ ; } char [ ] da = new char [ result . size ( ) ] ; int i = 0 ; for ( Character d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case STRING : { ArrayList < String > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; String [ ] data = sdata . getJavaArrayString ( realm ) ; result . addAll ( Arrays . asList ( data ) ) ; count ++ ; } String [ ] da = new String [ result . size ( ) ] ; int i = 0 ; for ( String d : result ) da [ i ++ ] = ; dataArray = da ; break ; } case STRUCTURE : { ArrayList < StructureData > result = new ArrayList <> ( initial ) ; while ( sdataIter . hasNext ( ) ) { StructureData sdata = sdataIter . next ( ) ; StructureMembers . Member realm = sdata . getStructureMembers ( ) . findMember ( proxym . getName ( ) ) ; ArrayStructure as = sdata . getArrayStructure ( realm ) ; StructureDataIterator innerIter = as . getStructureDataIterator ( ) ; while ( innerIter . hasNext ( ) ) result . add ( innerIter . next ( ) ) ; count ++ ; } rshape [ 0 ] = count ; StructureMembers membersw = new StructureMembers ( proxym . getStructureMembers ( ) ) ; // no data arrays get propagated
 return new ArrayStructureW ( membersw , rshape , result . toArray ( new StructureData [ 0 ] ) ) ; } } } // create an array to hold the result
 rshape [ 0 ] = count ; return Array . factory ( dataType , rshape , dataArray ) ; }


Input: Compute the linear index from the current odometer indices . [CODESPLIT] public long index ( ) { long offset = 0 ; for ( int i = 0 ; i < this . indices . length ; i ++ ) { offset *= this . dimsizes [ i ] ; offset += this . indices [ i ] ; } return offset ; }


Input: Make MFileOS7 if file exists otherwise return null [CODESPLIT] static public MFileOS7 getExistingFile ( String filename ) throws IOException { if ( filename == null ) return null ; Path path = Paths . get ( filename ) ; if ( Files . exists ( path ) ) return new MFileOS7 ( path ) ; return null ; }


Input: Return the known ServiceType that matches the given name ( ignoring case ) or null if the name is unknown . [CODESPLIT] public static ServiceType findType ( String name ) { if ( name == null ) return null ; for ( ServiceType serviceType : members ) { if ( serviceType . name . equalsIgnoreCase ( name ) ) return serviceType ; } return null ; }


Input: Return a ServiceType that matches the given name by either matching a known type ( ignoring case ) or creating an unknown type . [CODESPLIT] public static ServiceType getType ( String name ) { if ( name == null ) return null ; ServiceType type = findType ( name ) ; return type != null ? type : new ServiceType ( name , false ) ; }


Input: / * public void setCollection ( String filename ) throws IOException { if ( filename . endsWith ( GribCollection . IDX_EXT )) { openIndex ( filename ) ; } else { openCollection ( filename ) ; } } [CODESPLIT] public void setCollection ( String spec ) throws IOException { this . spec = spec ; this . cust = null ; Formatter f = new Formatter ( ) ; this . dcm = scanCollection ( spec , f ) ; if ( dcm == null ) { javax . swing . JOptionPane . showMessageDialog ( this , "Collection is null\n" + f . toString ( ) ) ; return ; } Map < Grib2Variable , Grib2ParameterBean > pdsSet = new HashMap <> ( ) ; Map < Integer , Grib2SectionGridDefinition > gdsSet = new HashMap <> ( ) ; java . util . List < Grib2ParameterBean > params = new ArrayList <> ( ) ; int fileno = 0 ; for ( MFile mfile : fileList ) { f . format ( "%n %s%n" , mfile . getPath ( ) ) ; try ( ucar . unidata . io . RandomAccessFile raf = new ucar . unidata . io . RandomAccessFile ( mfile . getPath ( ) , "r" ) ) { raf . order ( ByteOrder . BIG_ENDIAN ) ; processGribFile ( mfile , fileno ++ , raf , pdsSet , gdsSet , params , f ) ; } } param2BeanTable . setBeans ( params ) ; }


Input: / * public boolean writeIndex ( Formatter f ) throws IOException { MCollection dcm = scanCollection ( spec f ) ; [CODESPLIT] public void showInfo ( Formatter f ) { if ( dcm == null ) { if ( spec == null ) return ; dcm = scanCollection ( spec , f ) ; if ( dcm == null ) return ; } // just a list of the files f . format ( "dcm = %s%n" , dcm ) ; try { for ( MFile mfile : dcm . getFilesSorted ( ) ) { f . format ( "  %s%n" , mfile . getPath ( ) ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; //To change body of catch statement use File | Settings | File Templates. } // show nrecords, data size int nrecords = 0 ; long dataSize = 0 ; long msgSize = 0 ; for ( Object o : param2BeanTable . getBeans ( ) ) { Grib2ParameterBean p = ( Grib2ParameterBean ) o ; for ( Grib2RecordBean r : p . getRecordBeans ( ) ) { nrecords ++ ; dataSize += r . getDataLength ( ) ; msgSize += r . getMsgLength ( ) ; } } f . format ( "nrecords = %d, total grib data size = %d, total grib msg sizes = %d" , nrecords , dataSize , msgSize ) ; }


Input: / * private void checkRuntimes ( Formatter f ) { Map<Date DateCount > runs = new HashMap<Date DateCount > () ; List<Grib2ParameterBean > params = param2BeanTable . getBeans () ; for ( Grib2ParameterBean pb : params ) { List<Grib2RecordBean > records = pb . getRecordBeans () ; for ( Grib2RecordBean record : records ) { Date d = record . getBaseTime () ; DateCount dc = runs . get ( d ) ; if ( dc == null ) { dc = new DateCount ( d ) ; runs . put ( d dc ) ; } dc . count ++ ; } } [CODESPLIT] private void checkDuplicates ( Formatter f ) { // how unique are the pds ? Set < Long > pdsMap = new HashSet <> ( ) ; int dups = 0 ; int count = 0 ; // do all records have the same runtime ? Map < CalendarDate , DateCount > dateMap = new HashMap <> ( ) ; List < Grib2ParameterBean > params = param2BeanTable . getBeans ( ) ; for ( Grib2ParameterBean param : params ) { for ( Grib2RecordBean record : param . getRecordBeans ( ) ) { CalendarDate d = record . gr . getReferenceDate ( ) ; DateCount dc = dateMap . get ( d ) ; if ( dc == null ) { dc = new DateCount ( d ) ; dateMap . put ( d , dc ) ; } dc . count ++ ; Grib2SectionProductDefinition pdss = record . gr . getPDSsection ( ) ; long crc = pdss . calcCRC ( ) ; if ( pdsMap . contains ( crc ) ) dups ++ ; else pdsMap . add ( crc ) ; count ++ ; } } f . format ( "PDS duplicates = %d / %d%n%n" , dups , count ) ; List < DateCount > dcList = new ArrayList <> ( dateMap . values ( ) ) ; Collections . sort ( dcList ) ; f . format ( "Run Dates%n" ) ; int total = 0 ; for ( DateCount dc : dcList ) { f . format ( " %s == %d%n" , dc . d , dc . count ) ; total += dc . count ; } f . format ( "total records = %d%n" , total ) ; }


Input: //////////////////////////// [CODESPLIT] private void writeToFile ( List beans ) { if ( fileChooser == null ) fileChooser = new FileManager ( null , null , null , ( PreferencesExt ) prefs . node ( "FileManager" ) ) ; FileOutputStream fos = null ; RandomAccessFile raf = null ; try { String filename = null ; boolean append = false ; int n = 0 ; MFile curr = null ; for ( Object o : beans ) { Grib2RecordBean bean = ( Grib2RecordBean ) o ; MFile mfile = fileList . get ( bean . gr . getFile ( ) ) ; if ( curr == null || curr != mfile ) { if ( raf != null ) raf . close ( ) ; raf = new RandomAccessFile ( mfile . getPath ( ) , "r" ) ; curr = mfile ; } if ( fos == null ) { String defloc = mfile . getPath ( ) ; filename = fileChooser . chooseFilenameToSave ( defloc + ".grib2" ) ; if ( filename == null ) return ; File f = new File ( filename ) ; append = f . exists ( ) ; fos = new FileOutputStream ( filename , append ) ; } Grib2SectionIndicator is = bean . gr . getIs ( ) ; int size = ( int ) ( is . getMessageLength ( ) ) ; long startPos = is . getStartPos ( ) ; if ( startPos < 0 ) { JOptionPane . showMessageDialog ( Grib2DataPanel . this , "Old index does not have message start - record not written" ) ; } byte [ ] rb = new byte [ size ] ; raf . seek ( startPos ) ; raf . readFully ( rb ) ; fos . write ( rb ) ; n ++ ; } JOptionPane . showMessageDialog ( Grib2DataPanel . this , filename + ": " + n + " records successfully written, append=" + append ) ; } catch ( Exception ex ) { JOptionPane . showMessageDialog ( Grib2DataPanel . this , "ERROR: " + ex . getMessage ( ) ) ; ex . printStackTrace ( ) ; } finally { try { if ( fos != null ) fos . close ( ) ; if ( raf != null ) raf . close ( ) ; } catch ( IOException ioe ) { } } }


Input: Get a List of all the features in the shapefile that intersect the specified bounding box . This requires testing every feature in the List created at construction so it s faster to just give a bounding box o the constructor if you will only do this once . [CODESPLIT] public List < EsriFeature > getFeatures ( Rectangle2D bBox ) { if ( bBox == null ) return features ; List < EsriFeature > list = new ArrayList <> ( ) ; for ( EsriFeature gf : features ) { if ( gf . getBounds2D ( ) . intersects ( bBox ) ) list . add ( gf ) ; } return list ; }


Input: Discretize elements of array to a lower resolution . For example if resolution = 100 . the value 3 . 14159265358979 will be changed to 3 . 14 . [CODESPLIT] private void discretize ( double [ ] d , int n ) { if ( coarseness == 0.0 ) return ; for ( int i = 0 ; i < n ; i ++ ) { d [ i ] = ( Math . rint ( resolution * d [ i ] ) / resolution ) ; } }


Input:
_more_ [CODESPLIT] protected AxisType getAxisType ( NetcdfDataset ncDataset , VariableEnhanced v ) { String name = v . getShortName ( ) ; if ( name . equals ( "time" ) ) { return AxisType . Time ; } if ( name . equals ( "lat" ) ) { return AxisType . Lat ; } if ( name . equals ( "lon" ) ) { return AxisType . Lon ; } // if (name.equals("xLeo") ) return AxisType.GeoX;
 // if (name.equals("yLeo") ) return AxisType.GeoY;
 if ( name . equals ( "alt" ) ) { return AxisType . Height ; } return null ; }


Input:
create a NetcdfDataset out of this NetcdfFile adding coordinates etc . [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { // latitude
 if ( ! hasAxisType ( ds , AxisType . Lat ) ) { // already has _CoordinateAxisType
 if ( ! addAxisType ( ds , "latitude" , AxisType . Lat ) ) { // directly named
 String vname = ds . findAttValueIgnoreCase ( null , "latitude_coordinate" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Lat ) ) { // attribute named
 Variable v = hasUnits ( ds , "degrees_north,degrees_N,degreesN,degree_north,degree_N,degreeN" ) ; if ( v != null ) addAxisType ( v , AxisType . Lat ) ; // CF-1
 } } } // longitude
 if ( ! hasAxisType ( ds , AxisType . Lon ) ) { // already has _CoordinateAxisType
 if ( ! addAxisType ( ds , "longitude" , AxisType . Lon ) ) { // directly named
 String vname = ds . findAttValueIgnoreCase ( null , "longitude_coordinate" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Lon ) ) { // attribute named
 Variable v = hasUnits ( ds , "degrees_east,degrees_E,degreesE,degree_east,degree_E,degreeE" ) ; if ( v != null ) addAxisType ( v , AxisType . Lon ) ; // CF-1
 } } } // altitude
 if ( ! hasAxisType ( ds , AxisType . Height ) ) { // already has _CoordinateAxisType
 if ( ! addAxisType ( ds , "altitude" , AxisType . Height ) ) { // directly named
 if ( ! addAxisType ( ds , "depth" , AxisType . Height ) ) { // directly named
 String vname = ds . findAttValueIgnoreCase ( null , "altitude_coordinate" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Height ) ) { // attribute named
 for ( int i = 0 ; i < ds . getVariables ( ) . size ( ) ; i ++ ) { VariableEnhanced ve = ( VariableEnhanced ) ds . getVariables ( ) . get ( i ) ; String positive = ds . findAttValueIgnoreCase ( ( Variable ) ve , CF . POSITIVE , null ) ; if ( positive != null ) { addAxisType ( ( Variable ) ve , AxisType . Height ) ; // CF-1
 break ; } } } } } } // time
 if ( ! hasAxisType ( ds , AxisType . Time ) ) { // already has _CoordinateAxisType
 if ( ! addAxisType ( ds , "time" , AxisType . Time ) ) { // directly named
 String vname = ds . findAttValueIgnoreCase ( null , "time_coordinate" , null ) ; if ( ! addAxisType ( ds , vname , AxisType . Time ) ) { // attribute named
 for ( int i = 0 ; i < ds . getVariables ( ) . size ( ) ; i ++ ) { VariableEnhanced ve = ( VariableEnhanced ) ds . getVariables ( ) . get ( i ) ; String unit = ve . getUnitsString ( ) ; if ( unit == null ) continue ; if ( SimpleUnit . isDateUnit ( unit ) ) { addAxisType ( ( Variable ) ve , AxisType . Time ) ; // CF-1
 break ; } } } } } }


Input: Add all the content from another ThreddsMetadata [CODESPLIT] public void add ( ThreddsMetadata tmd , boolean includeInherited ) { creators . addAll ( tmd . getCreators ( ) ) ; contributors . addAll ( tmd . getContributors ( ) ) ; dates . addAll ( tmd . getDates ( ) ) ; docs . addAll ( tmd . getDocumentation ( ) ) ; keywords . addAll ( tmd . getKeywords ( ) ) ; projects . addAll ( tmd . getProjects ( ) ) ; properties . addAll ( tmd . getProperties ( ) ) ; publishers . addAll ( tmd . getPublishers ( ) ) ; variables . addAll ( tmd . getVariables ( ) ) ; if ( includeInherited ) metadata . addAll ( tmd . getMetadata ( ) ) ; else { for ( InvMetadata mdata : tmd . getMetadata ( ) ) { if ( ! mdata . isInherited ( ) ) metadata . add ( mdata ) ; } } // LOOK! should be copies ??!! if ( gc == null ) gc = tmd . getGeospatialCoverage ( ) ; if ( timeCoverage == null ) timeCoverage = tmd . getTimeCoverage ( ) ; if ( serviceName == null ) serviceName = tmd . getServiceName ( ) ; if ( dataType == null ) dataType = tmd . getDataType ( ) ; if ( dataSize == 0.0 ) dataSize = tmd . getDataSize ( ) ; if ( dataFormat == null ) dataFormat = tmd . getDataFormatType ( ) ; if ( authorityName == null ) authorityName = tmd . getAuthority ( ) ; if ( variableMapLink == null ) variableMapLink = tmd . getVariableMap ( ) ; }


Input: set specified type of documentation [CODESPLIT] public void addDocumentation ( String type , String content ) { if ( content == null ) { removeDocumentation ( type ) ; return ; } content = content . trim ( ) ; for ( InvDocumentation doc : getDocumentation ( ) ) { String dtype = doc . getType ( ) ; if ( ( dtype != null ) && dtype . equalsIgnoreCase ( type ) ) { doc . setInlineContent ( content ) ; return ; } } if ( content . length ( ) > 0 ) addDocumentation ( new InvDocumentation ( null , null , null , type , content ) ) ; }


Input: remove all instances of specified type of documentation [CODESPLIT] public void removeDocumentation ( String type ) { Iterator iter = docs . iterator ( ) ; while ( iter . hasNext ( ) ) { InvDocumentation doc = ( InvDocumentation ) iter . next ( ) ; String dtype = doc . getType ( ) ; if ( ( dtype != null ) && dtype . equalsIgnoreCase ( type ) ) iter . remove ( ) ; } }


Input: ///////////////// [CODESPLIT] private long getFilePos ( long elem ) { int segno = 0 ; while ( elem >= segMax [ segno ] ) segno ++ ; return segPos [ segno ] + elem - segMin [ segno ] ; }


Input: how many more bytes are in this segment ? [CODESPLIT] private int getMaxBytes ( long start ) { int segno = 0 ; while ( start >= segMax [ segno ] ) segno ++ ; return ( int ) ( segMax [ segno ] - start ) ; }


Input:
Convert a time unit to a CalendarPeriod GRIB1 and GRIB2 are the same ( ! ) [CODESPLIT] public static CalendarPeriod getCalendarPeriod ( int timeUnit ) { // LOOK - some way to intern these ? put in hash table  ?
 switch ( timeUnit ) { // code table 4.4
 case 0 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Minute ) ; case 1 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Hour ) ; case 2 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Day ) ; case 3 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Month ) ; case 4 : return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Year ) ; case 5 : return CalendarPeriod . of ( 10 , CalendarPeriod . Field . Year ) ; case 6 : return CalendarPeriod . of ( 30 , CalendarPeriod . Field . Year ) ; case 7 : return CalendarPeriod . of ( 100 , CalendarPeriod . Field . Year ) ; case 10 : return CalendarPeriod . of ( 3 , CalendarPeriod . Field . Hour ) ; case 11 : return CalendarPeriod . of ( 6 , CalendarPeriod . Field . Hour ) ; case 12 : return CalendarPeriod . of ( 12 , CalendarPeriod . Field . Hour ) ; case 13 : return CalendarPeriod . of ( 15 , CalendarPeriod . Field . Minute ) ; case 14 : return CalendarPeriod . of ( 30 , CalendarPeriod . Field . Minute ) ; default : throw new UnsupportedOperationException ( "Unknown time unit = " + timeUnit ) ; } }


Input:
Prints the value of all variables in this vector . This method is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space ) { int len = getLength ( ) ; for ( int i = 0 ; i < len - 1 ; i ++ ) { // to print properly, cast to long and convert to unsigned
 os . print ( ( ( long ) getValue ( i ) ) & 0xFFFF L ) ; os . print ( ", " ) ; } // print last value, if any, without trailing comma
 if ( len > 0 ) os . print ( ( ( long ) getValue ( len - 1 ) ) & 0xFFFF L ) ; }


Input:
Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { int modFour = vals . length % 4 ; // number of bytes to pad
 int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; for ( int i = 0 ; i < vals . length ; i ++ ) { vals [ i ] = source . readByte ( ) ; if ( statusUI != null ) { statusUI . incrementByteCount ( 1 ) ; if ( statusUI . userCancelled ( ) ) throw new DataReadException ( "User cancelled" ) ; } } // pad out to a multiple of four bytes
 byte unused ; for ( int i = 0 ; i < pad ; i ++ ) unused = source . readByte ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( pad ) ; }


Input:
Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { int modFour = vals . length % 4 ; // number of bytes to pad
 int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeByte ( vals [ i ] ) ; } // pad out to a multiple of four bytes
 for ( int i = 0 ; i < pad ; i ++ ) sink . writeByte ( 0 ) ; }


Input:
Write a subset of the data to a <code > DataOutputStream< / code > . [CODESPLIT] public void externalize ( DataOutputStream sink , int start , int stop , int stride ) throws IOException { int count = 0 ; for ( int i = start ; i <= stop ; i += stride ) { sink . writeByte ( vals [ i ] ) ; count ++ ; } // pad out to a multiple of four bytes
 int modFour = count % 4 ; int pad = ( modFour != 0 ) ? ( 4 - modFour ) : 0 ; for ( int i = 0 ; i < pad ; i ++ ) sink . writeByte ( 0 ) ; }


Input:
Get the input stream to the given resource [CODESPLIT] public static InputStream getInputStream ( String resourceName ) throws FileNotFoundException { // Try class loader to get resource
 ClassLoader cl = GribResourceReader . class . getClassLoader ( ) ; InputStream s = cl . getResourceAsStream ( resourceName ) ; if ( s != null ) { return s ; } // Try the file system
 File f = new File ( resourceName ) ; if ( f . exists ( ) ) return new FileInputStream ( f ) ; // give up
 throw new FileNotFoundException ( "Cant find resource " + resourceName ) ; }


Input: Is this my file? [CODESPLIT] public static boolean isMine ( NetcdfFile ncfile ) { String cs = ncfile . findAttValueIgnoreCase ( null , CDM . CONVENTIONS , null ) ; if ( cs != null ) return false ; String s = ncfile . findAttValueIgnoreCase ( null , "DataType" , null ) ; if ( ( s == null ) || ! ( s . equalsIgnoreCase ( "LatLonGrid" ) || s . equalsIgnoreCase ( "LatLonHeightGrid" ) ) ) return false ; if ( ( null == ncfile . findGlobalAttribute ( "Latitude" ) ) || ( null == ncfile . findGlobalAttribute ( "Longitude" ) ) || ( null == ncfile . findGlobalAttribute ( "LatGridSpacing" ) ) || ( null == ncfile . findGlobalAttribute ( "LonGridSpacing" ) ) || ( null == ncfile . findGlobalAttribute ( "Time" ) ) ) return false ; return ! ( null == ncfile . findDimension ( "Lat" ) || null == ncfile . findDimension ( "Lon" ) ) ; }


Input: / * static public StructureData make ( String name String value ) { StructureMembers members = new StructureMembers ( ) ; StructureMembers . Member m = members . addMember ( name null null DataType . STRING new int [] { 1 } ) ; StructureDataW sw = new StructureDataW ( members ) ; Array dataArray = Array . factory ( DataType . STRING new int [] { 1 } ) ; dataArray . setObject ( dataArray . getIndex () value ) ; sw . setMemberData ( m dataArray ) ; return sw ; } [CODESPLIT] static public StructureData make ( String name , Object value ) { StructureMembers members = new StructureMembers ( "" ) ; DataType dtype = DataType . getType ( value . getClass ( ) , false ) ; // LOOK unsigned StructureMembers . Member m = members . addMember ( name , null , null , dtype , new int [ ] { 1 } ) ; StructureDataW sw = new StructureDataW ( members ) ; Array dataArray = Array . factory ( dtype , new int [ ] { 1 } ) ; dataArray . setObject ( dataArray . getIndex ( ) , value ) ; sw . setMemberData ( m , dataArray ) ; return sw ; }


Input: CatalogCrawler . Listener [CODESPLIT] @ Override public void getDataset ( Dataset ds , Object context ) { if ( ds . hasAccess ( ) ) { DataFactory tdataFactory = new DataFactory ( ) ; Access access = tdataFactory . chooseDatasetAccess ( ds . getAccess ( ) ) ; if ( access == null ) throw new IllegalStateException ( ) ; MFileRemote mfile = new MFileRemote ( access ) ; if ( mfile . getPath ( ) . endsWith ( ".xml" ) ) return ; // eliminate latest.xml  LOOK kludge-o-rama mfiles . add ( mfile ) ; if ( debug ) System . out . format ( "add %s %n" , mfile . getPath ( ) ) ; } }


Input:
Register a class that implements a Convention . [CODESPLIT] static public void registerConvention ( String conventionName , Class c , ConventionNameOk match ) { if ( ! ( CoordSysBuilderIF . class . isAssignableFrom ( c ) ) ) throw new IllegalArgumentException ( "CoordSysBuilderIF Class " + c . getName ( ) + " must implement CoordSysBuilderIF" ) ; // fail fast - check newInstance works
 try { c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( "CoordSysBuilderIF Class " + c . getName ( ) + " cannot instantiate, probably need default Constructor" ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( "CoordSysBuilderIF Class " + c . getName ( ) + " is not accessible" ) ; } // user stuff gets put at top
 if ( userMode ) conventionList . add ( 0 , new Convention ( conventionName , c , match ) ) ; else conventionList . add ( new Convention ( conventionName , c , match ) ) ; }


Input: Register a class that implements a Convention . [CODESPLIT] static public void registerConvention ( String conventionName , String className ) throws ClassNotFoundException { Class c = Class . forName ( className ) ; registerConvention ( conventionName , c , null ) ; }


Input: Breakup list of Convention names in the Convention attribute in CF compliant way . [CODESPLIT] static public List < String > breakupConventionNames ( String convAttValue ) { List < String > names = new ArrayList <> ( ) ; if ( ( convAttValue . indexOf ( ' ' ) > 0 ) || ( convAttValue . indexOf ( ' ' ) > 0 ) ) { StringTokenizer stoke = new StringTokenizer ( convAttValue , ",;" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } else if ( ( convAttValue . indexOf ( ' ' ) > 0 ) ) { StringTokenizer stoke = new StringTokenizer ( convAttValue , "/" ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } else { StringTokenizer stoke = new StringTokenizer ( convAttValue , " " ) ; while ( stoke . hasMoreTokens ( ) ) { String name = stoke . nextToken ( ) ; names . add ( name . trim ( ) ) ; } } return names ; }


Input:
Build a list of Conventions [CODESPLIT] static public String buildConventionAttribute ( String mainConv , String ... convAtts ) { List < String > result = new ArrayList <> ( ) ; result . add ( mainConv ) ; for ( String convs : convAtts ) { if ( convs == null ) continue ; List < String > ss = breakupConventionNames ( convs ) ; // may be a list
 for ( String s : ss ) { if ( matchConvention ( s ) == null ) // only add extra ones, not ones that compete with mainConv
 result . add ( s ) ; } } // now form comma separated result
 boolean start = true ; Formatter f = new Formatter ( ) ; for ( String s : result ) { if ( start ) f . format ( "%s" , s ) ; else f . format ( ", %s" , s ) ; start = false ; } return f . toString ( ) ; }


Input:
Get a CoordSysBuilder whose job it is to add Coordinate information to a NetcdfDataset . [CODESPLIT] static public @ Nonnull CoordSysBuilderIF factory ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { // look for the Conventions attribute
 String convName = ds . findAttValueIgnoreCase ( null , CDM . CONVENTIONS , null ) ; if ( convName == null ) convName = ds . findAttValueIgnoreCase ( null , "Convention" , null ) ; // common mistake Convention instead of Conventions
 if ( convName != null ) convName = convName . trim ( ) ; // look for ncml first
 if ( convName != null ) { String convNcML = ncmlHash . get ( convName ) ; if ( convNcML != null ) { CoordSysBuilder csb = new CoordSysBuilder ( ) ; NcMLReader . wrapNcML ( ds , convNcML , cancelTask ) ; return csb ; } } // look for registered conventions using convention name
 Class convClass = null ; if ( convName != null ) { convClass = matchConvention ( convName ) ; // now look for comma or semicolon or / delimited list
 if ( convClass == null ) { List < String > names = breakupConventionNames ( convName ) ; if ( names . size ( ) > 0 ) { // search the registered conventions, in order
 for ( Convention conv : conventionList ) { for ( String name : names ) { if ( name . equalsIgnoreCase ( conv . convName ) ) { convClass = conv . convClass ; convName = name ; } } if ( convClass != null ) break ; } } } } // look for ones that dont use Convention attribute, in order added.
 // call static isMine() using reflection.
 if ( convClass == null ) { for ( Convention conv : conventionList ) { Class c = conv . convClass ; Method m ; try { m = c . getMethod ( "isMine" , NetcdfFile . class ) ; // LOOK cant we test if method exists ?
 } catch ( NoSuchMethodException ex ) { continue ; } try { Boolean result = ( Boolean ) m . invoke ( null , ds ) ; if ( result ) { convClass = c ; break ; } } catch ( Exception ex ) { log . error ( "ERROR: Class " + c . getName ( ) + " Exception invoking isMine method\n" + ex ) ; } } } // use service loader mechanism
 // call static isMine() using reflection.
 CoordSysBuilderIF builder = null ; if ( convClass == null ) { for ( CoordSysBuilderIF csb : ServiceLoader . load ( CoordSysBuilderIF . class ) ) { Class c = csb . getClass ( ) ; Method m ; try { m = c . getMethod ( "isMine" , NetcdfFile . class ) ; } catch ( NoSuchMethodException ex ) { continue ; } try { Boolean result = ( Boolean ) m . invoke ( null , ds ) ; if ( result ) { builder = csb ; convClass = c ; break ; } } catch ( Exception ex ) { log . error ( "ERROR: Class " + c . getName ( ) + " Exception invoking isMine method%n" + ex ) ; } } } // if no convention class found, use the default
 if ( convClass == null ) convClass = DefaultConvention . class ; if ( builder == null ) { // get an instance of the class
 try { builder = ( CoordSysBuilderIF ) convClass . newInstance ( ) ; } catch ( Exception e ) { log . error ( "failed on CoordSysBuilderIF for " + convClass . getName ( ) , e ) ; throw new RuntimeException ( e ) ; } } if ( convName == null ) builder . addUserAdvice ( "No 'Conventions' global attribute." ) ; else if ( convClass == DefaultConvention . class ) builder . addUserAdvice ( "No CoordSysBuilder is defined for Conventions= '" + convName + "'\n" ) ; else builder . setConventionUsed ( convClass . getName ( ) ) ; ds . addAttribute ( null , new Attribute ( _Coordinate . _CoordSysBuilder , convClass . getName ( ) ) ) ; return builder ; }


Input:
Heres where the work is to identify coordinate axes and coordinate systems . [CODESPLIT] @ Override public void buildCoordinateSystems ( NetcdfDataset ncDataset ) { // put status info into parseInfo that can be shown to someone trying to debug this process
 parseInfo . format ( "Parsing with Convention = %s%n" , conventionName ) ; // Bookkeeping info for each variable is kept in the VarProcess inner class
 addVariables ( ncDataset , ncDataset . getVariables ( ) , varList ) ; // identify which variables are coordinate axes
 findCoordinateAxes ( ncDataset ) ; // identify which variables are used to describe coordinate system
 findCoordinateSystems ( ncDataset ) ; // identify which variables are used to describe coordinate transforms
 findCoordinateTransforms ( ncDataset ) ; // turn Variables into CoordinateAxis objects
 makeCoordinateAxes ( ncDataset ) ; // make Coordinate Systems for all Coordinate Systems Variables
 makeCoordinateSystems ( ncDataset ) ; // assign explicit CoordinateSystem objects to variables
 assignCoordinateSystemsExplicit ( ncDataset ) ; // assign implicit CoordinateSystem objects to variables
 makeCoordinateSystemsImplicit ( ncDataset ) ; // optionally assign implicit CoordinateSystem objects to variables that dont have one yet
 if ( useMaximalCoordSys ) makeCoordinateSystemsMaximal ( ncDataset ) ; // make Coordinate Transforms
 makeCoordinateTransforms ( ncDataset ) ; // assign Coordinate Transforms
 assignCoordinateTransforms ( ncDataset ) ; if ( debug ) System . out . println ( "parseInfo = \n" + parseInfo . toString ( ) ) ; }


Input: Identify coordinate axes set VarProcess . isCoordinateAxis = true . Default is to look for those referenced by _CoordinateAxes attribute . Note coordinate variables are already identified . [CODESPLIT] protected void findCoordinateAxes ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . coordAxes != null ) findCoordinateAxes ( vp , vp . coordAxes ) ; if ( vp . coordinates != null ) findCoordinateAxes ( vp , vp . coordinates ) ; } }


Input: Identify coordinate systems set VarProcess . isCoordinateSystem = true . Default is to look for those referenced by _CoordinateSystems attribute . [CODESPLIT] protected void findCoordinateSystems ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . coordSys != null ) { StringTokenizer stoker = new StringTokenizer ( vp . coordSys ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap != null ) { if ( ! ap . isCoordinateSystem ) parseInfo . format ( " CoordinateSystem = %s added; referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; ap . isCoordinateSystem = true ; } else { parseInfo . format ( "***Cant find coordSystem %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find coordSystem %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; } } } } }


Input: Identify coordinate transforms set VarProcess . isCoordinateTransform = true . Default is to look for those referenced by _CoordinateTransforms attribute ( or has a _CoordinateTransformType attribute done in VarProcess constructor ) [CODESPLIT] protected void findCoordinateTransforms ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . coordTransforms != null ) { StringTokenizer stoker = new StringTokenizer ( vp . coordTransforms ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap != null ) { if ( ! ap . isCoordinateTransform ) parseInfo . format ( " CoordinateTransform = %s added; referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; ap . isCoordinateTransform = true ; } else { parseInfo . format ( "***Cant find CoordinateTransform %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find CoordinateTransform %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; } } } } }


Input: Take previously identified Coordinate Axis and Coordinate Variables and make them into a CoordinateAxis . Uses the getAxisType () method to figure out the type if not already set . [CODESPLIT] protected void makeCoordinateAxes ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateAxis || vp . isCoordinateVariable ) { if ( vp . axisType == null ) vp . axisType = getAxisType ( ncDataset , ( VariableEnhanced ) vp . v ) ; if ( vp . axisType == null ) { userAdvice . format ( "Coordinate Axis %s does not have an assigned AxisType%n" , vp . v . getFullName ( ) ) ; } vp . makeIntoCoordinateAxis ( ) ; } } }


Input: Take all previously identified Coordinate Systems and create a CoordinateSystem object . [CODESPLIT] protected void makeCoordinateSystems ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateSystem ) { vp . makeCoordinateSystem ( ) ; } } }


Input:
Assign explicit CoordinateSystem objects to variables . [CODESPLIT] protected void assignCoordinateSystemsExplicit ( NetcdfDataset ncDataset ) { // look for explicit references to coord sys variables
 for ( VarProcess vp : varList ) { if ( vp . coordSys != null && ! vp . isCoordinateTransform ) { StringTokenizer stoker = new StringTokenizer ( vp . coordSys ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap == null ) { parseInfo . format ( "***Cant find Coordinate System variable %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find Coordinate System variable %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; continue ; } if ( ap . cs == null ) { parseInfo . format ( "***Not a Coordinate System variable %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Not a Coordinate System variable %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; continue ; } VariableEnhanced ve = ( VariableEnhanced ) vp . v ; ve . addCoordinateSystem ( ap . cs ) ; } } } // look for explicit references from coord sys variables to data variables
 for ( VarProcess csVar : varList ) { if ( ! csVar . isCoordinateSystem || ( csVar . coordSysFor == null ) ) continue ; // get list of dimensions from '_CoordinateSystemFor' attribute
 List < Dimension > dimList = new ArrayList <> ( 6 ) ; StringTokenizer stoker = new StringTokenizer ( csVar . coordSysFor ) ; while ( stoker . hasMoreTokens ( ) ) { String dname = stoker . nextToken ( ) ; Dimension dim = ncDataset . getRootGroup ( ) . findDimension ( dname ) ; if ( dim == null ) { parseInfo . format ( "***Cant find Dimension %s referenced from CoordSys var= %s%n" , dname , csVar . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find Dimension %s referenced from CoordSys var= %s%n" , dname , csVar . v . getFullName ( ) ) ; } else dimList . add ( dim ) ; } // look for vars with those dimensions
 for ( VarProcess vp : varList ) { if ( ! vp . hasCoordinateSystem ( ) && vp . isData ( ) && ( csVar . cs != null ) ) { VariableEnhanced ve = ( VariableEnhanced ) vp . v ; if ( CoordinateSystem . isSubset ( dimList , vp . v . getDimensionsAll ( ) ) && CoordinateSystem . isSubset ( vp . v . getDimensionsAll ( ) , dimList ) ) ve . addCoordinateSystem ( csVar . cs ) ; } } } // look for explicit listings of coordinate axes
 for ( VarProcess vp : varList ) { VariableEnhanced ve = ( VariableEnhanced ) vp . v ; if ( ! vp . hasCoordinateSystem ( ) && ( vp . coordAxes != null ) && vp . isData ( ) ) { List < CoordinateAxis > dataAxesList = getAxes ( vp , vp . coordAxes , vp . v . getFullName ( ) ) ; if ( dataAxesList . size ( ) > 1 ) { String coordSysName = CoordinateSystem . makeName ( dataAxesList ) ; CoordinateSystem cs = ncDataset . findCoordinateSystem ( coordSysName ) ; if ( cs != null ) { ve . addCoordinateSystem ( cs ) ; parseInfo . format ( " assigned explicit CoordSystem '%s' for var= %s%n" , cs . getName ( ) , vp . v . getFullName ( ) ) ; } else { CoordinateSystem csnew = new CoordinateSystem ( ncDataset , dataAxesList , null ) ; ve . addCoordinateSystem ( csnew ) ; ncDataset . addCoordinateSystem ( csnew ) ; parseInfo . format ( " created explicit CoordSystem '%s' for var= %s%n" , csnew . getName ( ) , vp . v . getFullName ( ) ) ; } } } } }


Input:
Make implicit CoordinateSystem objects for variables that dont already have one by using the variables list of coordinate axes and any coordinateVariables for it . Must be at least 2 axes . All of a variable s _Coordinate Variables_ plus any variables listed in a * __CoordinateAxes_ * or * _coordinates_ * attribute will be made into an * _implicit_ * Coordinate System . If there are at least two axes and the coordinate system uses all of the variable s dimensions it will be asssigned to the data variable . [CODESPLIT] protected void makeCoordinateSystemsImplicit ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( ! vp . hasCoordinateSystem ( ) && vp . maybeData ( ) ) { List < CoordinateAxis > dataAxesList = vp . findCoordinateAxes ( true ) ; if ( dataAxesList . size ( ) < 2 ) continue ; VariableEnhanced ve = ( VariableEnhanced ) vp . v ; String csName = CoordinateSystem . makeName ( dataAxesList ) ; CoordinateSystem cs = ncDataset . findCoordinateSystem ( csName ) ; if ( ( cs != null ) && cs . isComplete ( vp . v ) ) { // must be complete
 ve . addCoordinateSystem ( cs ) ; parseInfo . format ( " assigned implicit CoordSystem '%s' for var= %s%n" , cs . getName ( ) , vp . v . getFullName ( ) ) ; } else { CoordinateSystem csnew = new CoordinateSystem ( ncDataset , dataAxesList , null ) ; csnew . setImplicit ( true ) ; if ( csnew . isComplete ( vp . v ) ) { ve . addCoordinateSystem ( csnew ) ; ncDataset . addCoordinateSystem ( csnew ) ; parseInfo . format ( " created implicit CoordSystem '%s' for var= %s%n" , csnew . getName ( ) , vp . v . getFullName ( ) ) ; } } } } }


Input:
If a variable still doesnt have a coordinate system use hueristics to try to find one that was probably forgotten . Examine existing CS . create a subset of axes that fits the variable . Choose the one with highest rank . It must have X Y or lat lon . If so add it . [CODESPLIT] protected void makeCoordinateSystemsMaximal ( NetcdfDataset ncDataset ) { boolean requireCompleteCoordSys = ! ncDataset . getEnhanceMode ( ) . contains ( NetcdfDataset . Enhance . IncompleteCoordSystems ) ; for ( VarProcess vp : varList ) { VariableEnhanced ve = ( VariableEnhanced ) vp . v ; if ( vp . hasCoordinateSystem ( ) || ! vp . isData ( ) ) continue ; // look through all axes that fit
 List < CoordinateAxis > axisList = new ArrayList <> ( ) ; List < CoordinateAxis > axes = ncDataset . getCoordinateAxes ( ) ; for ( CoordinateAxis axis : axes ) { if ( isCoordinateAxisForVariable ( axis , ve ) ) axisList . add ( axis ) ; } if ( axisList . size ( ) < 2 ) continue ; String csName = CoordinateSystem . makeName ( axisList ) ; CoordinateSystem cs = ncDataset . findCoordinateSystem ( csName ) ; boolean okToBuild = false ; // do coordinate systems need to be complete?
 // default enhance mode is yes, they must be complete
 if ( requireCompleteCoordSys ) { if ( cs != null ) { // only build if coordinate system is complete
 okToBuild = cs . isComplete ( ve ) ; } } else { // coordinate system can be incomplete, so we're ok to build if we find something
 okToBuild = true ; } if ( cs != null && okToBuild ) { ve . addCoordinateSystem ( cs ) ; parseInfo . format ( " assigned maximal CoordSystem '%s' for var= %s%n" , cs . getName ( ) , ve . getFullName ( ) ) ; } else { CoordinateSystem csnew = new CoordinateSystem ( ncDataset , axisList , null ) ; // again, do coordinate systems need to be complete?
 // default enhance mode is yes, they must be complete
 if ( requireCompleteCoordSys ) { // only build if new coordinate system is complete
 okToBuild = csnew . isComplete ( ve ) ; } if ( okToBuild ) { csnew . setImplicit ( true ) ; ve . addCoordinateSystem ( csnew ) ; ncDataset . addCoordinateSystem ( csnew ) ; parseInfo . format ( " created maximal CoordSystem '%s' for var= %s%n" , csnew . getName ( ) , ve . getFullName ( ) ) ; } } } }


Input:
Does this axis fit this variable . True if all of the dimensions in the axis also appear in the variable . If char variable last dimension is left out . [CODESPLIT] protected boolean isCoordinateAxisForVariable ( Variable axis , VariableEnhanced v ) { List < Dimension > varDims = v . getDimensionsAll ( ) ; List < Dimension > axisDims = axis . getDimensionsAll ( ) ; // a CHAR variable must really be a STRING, so leave out the last (string length) dimension
 int checkDims = axisDims . size ( ) ; if ( axis . getDataType ( ) == DataType . CHAR ) checkDims -- ; for ( int i = 0 ; i < checkDims ; i ++ ) { Dimension axisDim = axisDims . get ( i ) ; if ( ! varDims . contains ( axisDim ) ) { return false ; } } return true ; }


Input: Take all previously identified Coordinate Transforms and create a CoordinateTransform object by calling CoordTransBuilder . makeCoordinateTransform () . [CODESPLIT] protected void makeCoordinateTransforms ( NetcdfDataset ncDataset ) { for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && vp . ct == null ) { vp . ct = CoordTransBuilder . makeCoordinateTransform ( vp . ds , vp . v , parseInfo , userAdvice ) ; } } }


Input:
Assign CoordinateTransform objects to Coordinate Systems . [CODESPLIT] protected void assignCoordinateTransforms ( NetcdfDataset ncDataset ) { // look for explicit transform assignments on the coordinate systems
 for ( VarProcess vp : varList ) { if ( vp . isCoordinateSystem && vp . coordTransforms != null ) { StringTokenizer stoker = new StringTokenizer ( vp . coordTransforms ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess ap = findVarProcess ( vname , vp ) ; if ( ap != null ) { if ( ap . ct != null ) { vp . addCoordinateTransform ( ap . ct ) ; parseInfo . format ( " assign explicit coordTransform %s to CoordSys= %s%n" , ap . ct , vp . cs ) ; } else { parseInfo . format ( "***Cant find coordTransform in %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find coordTransform in %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; } } else { parseInfo . format ( "***Cant find coordTransform variable= %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find coordTransform variable= %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; } } } } // look for explicit coordSys assignments on the coordinate transforms
 for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && ( vp . ct != null ) && ( vp . coordSys != null ) ) { StringTokenizer stoker = new StringTokenizer ( vp . coordSys ) ; while ( stoker . hasMoreTokens ( ) ) { String vname = stoker . nextToken ( ) ; VarProcess vcs = findVarProcess ( vname , vp ) ; if ( vcs == null ) { parseInfo . format ( "***Cant find coordSystem variable= %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; userAdvice . format ( "***Cant find coordSystem variable= %s referenced from var= %s%n" , vname , vp . v . getFullName ( ) ) ; } else { vcs . addCoordinateTransform ( vp . ct ) ; parseInfo . format ( "***assign explicit coordTransform %s to CoordSys=  %s%n" , vp . ct , vp . cs ) ; } } } } // look for coordAxes assignments on the coordinate transforms
 for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && ( vp . ct != null ) && ( vp . coordAxes != null ) ) { List < CoordinateAxis > dataAxesList = vp . findCoordinateAxes ( false ) ; if ( dataAxesList . size ( ) > 0 ) { for ( CoordinateSystem cs : ncDataset . getCoordinateSystems ( ) ) { if ( cs . containsAxes ( dataAxesList ) ) { cs . addCoordinateTransform ( vp . ct ) ; parseInfo . format ( "***assign (implicit coordAxes) coordTransform %s to CoordSys=  %s%n" , vp . ct , cs ) ; } } } } } // look for coordAxisType assignments on the coordinate transforms
 for ( VarProcess vp : varList ) { if ( vp . isCoordinateTransform && ( vp . ct != null ) && ( vp . coordAxisTypes != null ) ) { List < AxisType > axisTypesList = new ArrayList <> ( ) ; StringTokenizer stoker = new StringTokenizer ( vp . coordAxisTypes ) ; while ( stoker . hasMoreTokens ( ) ) { String name = stoker . nextToken ( ) ; AxisType atype ; if ( null != ( atype = AxisType . getType ( name ) ) ) axisTypesList . add ( atype ) ; } if ( axisTypesList . size ( ) > 0 ) { for ( CoordinateSystem cs : ncDataset . getCoordinateSystems ( ) ) { if ( cs . containsAxisTypes ( axisTypesList ) ) { cs . addCoordinateTransform ( vp . ct ) ; parseInfo . format ( "***assign (implicit coordAxisType) coordTransform %s to CoordSys=  %s%n" , vp . ct , cs ) ; } } } } } }


Input: track coordinate variables [CODESPLIT] protected void addCoordinateVariable ( Dimension dim , VarProcess vp ) { List < VarProcess > list = coordVarMap . get ( dim ) ; if ( list == null ) { list = new ArrayList <> ( ) ; coordVarMap . put ( dim , list ) ; } if ( ! list . contains ( vp ) ) list . add ( vp ) ; }


Input: Munge this catalog so the given dataset is the top catalog . [CODESPLIT] public void subset ( InvDataset ds ) { InvDatasetImpl dataset = ( InvDatasetImpl ) ds ; // Make all inherited metadata local. dataset . transferMetadata ( dataset , true ) ; topDataset = dataset ; datasets . clear ( ) ; // throw away the rest datasets . add ( topDataset ) ; // parent lookups need to be local //InvService service = dataset.getServiceDefault(); //if (service != null) LOOK //  dataset.serviceName = service.getName(); dataset . dataType = dataset . getDataType ( ) ; // all properties need to be local // LOOK dataset.setPropertiesLocal( new ArrayList(dataset.getProperties())); // next part requires this before it dataset . setCatalog ( this ) ; dataset . parent = null ; // any referenced services need to be local List < InvService > services = new ArrayList < InvService > ( dataset . getServicesLocal ( ) ) ; findServices ( services , dataset ) ; dataset . setServicesLocal ( services ) ; finish ( ) ; }


Input: } [CODESPLIT] void findServices ( List < InvService > result , InvDataset ds ) { if ( ds instanceof InvCatalogRef ) return ; // look for access elements with unresolved services for ( InvAccess a : ds . getAccess ( ) ) { InvService s = a . getService ( ) ; InvDataset d = a . getDataset ( ) ; if ( null == d . findService ( s . getName ( ) ) && ! ( result . contains ( s ) ) ) result . add ( s ) ; } // recurse into nested datasets for ( InvDataset nested : ds . getDatasets ( ) ) { findServices ( result , nested ) ; } }


Input: Munge this catalog to remove any dataset that doesnt pass through the filter . [CODESPLIT] public void filter ( DatasetFilter filter ) { mark ( filter , topDataset ) ; delete ( topDataset ) ; this . filter = filter ; }


Input: unread CatalogRefs are always kept . [CODESPLIT] private boolean mark ( DatasetFilter filter , InvDatasetImpl ds ) { if ( ds instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) ds ; if ( ! catRef . isRead ( ) ) return false ; } // recurse into nested datasets first boolean allMarked = true ; for ( InvDataset nested : ds . getDatasets ( ) ) { allMarked &= mark ( filter , ( InvDatasetImpl ) nested ) ; } if ( ! allMarked ) return false ; if ( filter . accept ( ds ) >= 0 ) return false ; // mark for deletion ds . setMark ( true ) ; if ( debugFilter ) System . out . println ( " mark " + ds . getName ( ) ) ; return true ; }


Input: remove marked datasets [CODESPLIT] private void delete ( InvDatasetImpl ds ) { if ( ds instanceof InvCatalogRef ) { InvCatalogRef catRef = ( InvCatalogRef ) ds ; if ( ! catRef . isRead ( ) ) return ; } Iterator iter = ds . getDatasets ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { InvDatasetImpl nested = ( InvDatasetImpl ) iter . next ( ) ; if ( nested . getMark ( ) ) { iter . remove ( ) ; if ( debugFilter ) System . out . println ( " remove " + nested . getName ( ) ) ; } else delete ( nested ) ; } }


Input:
Finish constructing after all elements have been added or modified . This routine will do any needed internal consistency work . Its ok to call multiple times . [CODESPLIT] public boolean finish ( ) { // make topDataset if needed //if (topDataset == null) { if ( datasets . size ( ) == 1 ) { // already only one; make it top topDataset = ( InvDatasetImpl ) datasets . get ( 0 ) ; } else { // create one topDataset = new InvDatasetImpl ( null , name == null ? "Top Dataset" : name ) ; for ( InvDataset dataset : datasets ) topDataset . addDataset ( ( InvDatasetImpl ) dataset ) ; topDataset . setServicesLocal ( services ) ; } //} topDataset . setCatalog ( this ) ; // build dataset hash table dsHash = new HashMap < String , InvDataset > ( ) ; addDatasetIds ( topDataset ) ; // recurse through the datasets and finish them return topDataset . finish ( ) ; } private void addDatasetIds ( InvDatasetImpl ds ) { addDatasetByID ( ds ) ; if ( ds instanceof InvCatalogRef ) return ; //if (ds instanceof InvDatasetFmrc) return; // recurse into nested for ( InvDataset invDataset : ds . getDatasets ( ) ) { InvDatasetImpl nested = ( InvDatasetImpl ) invDataset ; addDatasetIds ( nested ) ; } } /**
   * Add Dataset to internal hash.
   *
   * @param ds : add this dataset if ds.getID() != null
   * @see InvCatalog#findDatasetByID
   */ public void addDatasetByID  ( InvDatasetImpl ds ) { //if (ds.getID() != null && ds.getID().startsWith("null")) //  System.out.printf("HEY addDatasetByID %s%n", ds.getID()); if ( ds . getID ( ) != null ) dsHash . put ( ds . getID ( ) , ds ) ; } /**
   * Find the dataset in this catalog by its ID. If found, remove it.
   *
   * @param ds Remove this dataset from the hash
   */ public void removeDatasetByID  ( InvDatasetImpl ds ) { if ( ds . getID ( ) != null ) dsHash . remove ( ds . getID ( ) ) ; } /**
   * Add Dataset (1.0)
   *
   * @param ds add this dataset
   */ public void addDataset  ( InvDatasetImpl ds ) { if ( ds != null ) datasets . add ( ds ) ; } /**
   * Remove the given dataset from this catalog if it is a direct child of this catalog.
   *
   * @param ds remove this dataset
   * @return true if found and removed
   */ public boolean removeDataset  ( InvDatasetImpl ds ) { if ( this . datasets . remove ( ds ) ) { ds . setParent ( null ) ; removeDatasetByID ( ds ) ; return true ; } return false ; } /**
   * Replace the given dataset if it is a nested dataset.
   *
   * @param remove - the dataset element to be removed
   * @param add    - the dataset element to be added
   * @return true on success
   */ public boolean replaceDataset  ( InvDatasetImpl remove , InvDatasetImpl add ) { if ( topDataset . equals ( remove ) ) { topDataset = add ; topDataset . setCatalog ( this ) ; } for ( int i = 0 ; i < datasets . size ( ) ; i ++ ) { InvDataset dataset = datasets . get ( i ) ; if ( dataset . equals ( remove ) ) { datasets . set ( i , add ) ; removeDatasetByID ( remove ) ; addDatasetByID ( add ) ; return true ; } } return false ; } /**
   * Add Property (1.0)
   *
   * @param p add this property
   */ public void addProperty  ( InvProperty p ) { properties . add ( p ) ; } /**
   * Add Service (1.0)
   *
   * @param s add this service
   */ public void addService  ( InvService s ) { if ( s == null ) throw new IllegalArgumentException ( "Service to add was null." ) ; // While adding a service, there are three possible results: if ( s . getName ( ) != null ) { Object obj = serviceHash . get ( s . getName ( ) ) ; if ( obj == null ) { // 1) No service with matching name entry was found, add given service; serviceHash . put ( s . getName ( ) , s ) ; services . add ( s ) ; return ; } else { // A service with matching name was found. if ( s . equals ( obj ) ) { // 2) matching name entry, objects are equal so OK; return ; } else { // 3) matching name entry, objects are not equal so ??? // @todo throw an exception??? // Currently just dropping given service log . append ( "Multiple Services with the same name\n" ) ; return ; } } } } /**
   * Add top-level InvDataset to this catalog.
   *
   * @deprecated Use addDataset() instead; datamodel now allows multiple top level datasets.
   */ public void setDataset  ( InvDatasetImpl ds ) { topDataset = ds ; addDataset ( ds ) ; } /**
   * String describing how the catalog was created, for debugging.
   *
   * @return how the catalog was created, for debugging
   */ public String getCreateFrom  ( ) { return createFrom ; } /**
   * Set how the catalog was created, for debugging.
   * @param createFrom how the catalog was created, for debugging
   */ public void setCreateFrom  ( String createFrom ) { this . createFrom = createFrom ; } /**
   * Set the catalog base URI.
   * Its used to resolve reletive URLS.
   * @param baseURI set to this
   */ public void setBaseURI  ( URI baseURI ) { this . baseURI = baseURI ; } /**
   * @return the catalog base URI.
   */ public URI getBaseURI  ( ) { return baseURI ; } /*
   * @return DTD string
   *
  public String getDTDid() {
    return dtdID;
  }

  /*
   * set DTD
   *
  public void setDTDid(String dtdID) {
    this.dtdID = dtdID;
  } */ /**
   * Set the expires date after which the catalog is no longer valid.
   *
   * @param expiresDate a {@link DateType} representing the date after which the catlog is no longer valid.
   */ public void setExpires  ( DateType expiresDate ) { this . expires = expiresDate ; } /**
   * Check if there is a fatal error and catalog should not be used.
   *
   * @return true if catalog not useable.
   */ public boolean hasFatalError  ( ) { return hasError ; } /**
   * Append an error message to the message log. Call check() to get the log when
   * everything is done.
   *
   * @param message   append this message to log
   * @param isInvalid true if this is a fatal error.
   */ public void appendErrorMessage  ( String message , boolean isInvalid ) { log . append ( message ) ; hasError = hasError | isInvalid ; } /**
   * Check internal data structures.
   *
   * @param out  : print errors here
   * @param show : print messages for each object (debug)
   * @return true if no fatal consistency errors.
   */ public boolean check  ( StringBuilder out , boolean show ) { boolean isValid = ! hasError ; out . append ( "----Catalog Validation\n" ) ; if ( log . length ( ) > 0 ) out . append ( log ) ; if ( show ) System . out . println ( " catalog valid = " + isValid ) ; //if (topDataset != null) //  isValid &= topDataset.check( out, show); for ( InvDataset ds : datasets ) { InvDatasetImpl dsi = ( InvDatasetImpl ) ds ; dsi . check ( out , show ) ; // cant make it invalid !! } return isValid ; } public String getLog  ( ) { return log . toString ( ) ; } /**
   * Debugging: dump entire data structure.
   *
   * @return String representation.
   */ public String dump  ( ) { StringBuilder buff = new StringBuilder ( 1000 ) ; buff . setLength ( 0 ) ; buff . append ( "Catalog <" ) . append ( getName ( ) ) . append ( "> <" ) . append ( getVersion ( ) ) . append ( "> <" ) . append ( getCreateFrom ( ) ) . append ( ">\n" ) ; buff . append ( topDataset . dump ( 2 ) ) ; return buff . toString ( ) ; } /*
   * Add a PropertyChangeEvent Listener. THIS IS EXPERIMENTAL DO NOT RELY ON.
   * Throws a PropertyChangeEvent:
   *

propertyName = "InvCatalogRefInit", getNewValue() = InvCatalogRef that was just initialized
   *

   * @param l the listener
   *
  public void addPropertyChangeListener(PropertyChangeListener l) {
    if (listenerList == null) listenerList = new EventListenerList();
    listenerList.add(PropertyChangeListener.class, l);
  }

  /**
   * Remove a PropertyChangeEvent Listener.
   * @param l the listener
   *
  public void removePropertyChangeListener(PropertyChangeListener l) {
    listenerList.remove(PropertyChangeListener.class, l);
  }

  private EventListenerList listenerList = null;

  // PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue)
  void firePropertyChangeEvent(PropertyChangeEvent event) {
    // System.out.println("firePropertyChangeEvent "+event);
    if (listenerList == null) return;

    // Process the listeners last to first
    Object[] listeners = listenerList.getListenerList();
    for (int i = listeners.length - 2; i >= 0; i -= 2) {
      if (listeners[i] == PropertyChangeListener.class) {
        ((PropertyChangeListener) listeners[i + 1]).propertyChange(event);
      }
    }
  } */ /**
   * This finds the topmost catalog, even when its a InvCatalogRef.
   * Used to throw a PropertyChange event on the top catalog.
   *
   * @return top catalog
   */ InvCatalogImpl getTopCatalog  ( ) { return ( top == null ) ? this : top ; } void setTopCatalog  ( InvCatalogImpl top ) { this . top = top ; } private InvCatalogImpl top = null ; //////////////////////////////////////////// /* private InvCatalogFactory factory = null;
  // private InvCatalogConvertIF converter = null;

  // this is how catalogRefs read their catalogs
  InvCatalogFactory getCatalogFactory() {
    return factory;
  }

  void setCatalogFactory(InvCatalogFactory factory) {
    this.factory = factory;
  }

  // track converter
  InvCatalogConvertIF getCatalogConverter() {
    return converter;
  }

  void setCatalogConverter(InvCatalogConvertIF converter) {
    this.converter = converter;
  } */ /*
   * Set the connverter to 1.0, typically to write a 0.6 out to a 1.0
   *
  public void setCatalogConverterToVersion1() {
    setCatalogConverter(factory.getCatalogConverter(XMLEntityResolver.CATALOG_NAMESPACE_10));
  } */ /**
   * Write the catalog as an XML document to the specified stream.
   *
   * @param os write to this OutputStream
   * @throws java.io.IOException on an error.
   */ public void writeXML  ( java . io . OutputStream os ) throws java . io . IOException { InvCatalogConvertIF converter = InvCatalogFactory . getDefaultConverter ( ) ; converter . writeXML ( this , os ) ; } /**
   * Write the catalog as an XML document to the specified stream.
   *
   * @param os  write to this OutputStream
   * @param raw if true, write original (server) version, else write client version
   * @throws java.io.IOException on an error.
   */ public void writeXML  ( java . io . OutputStream os , boolean raw ) throws java . io . IOException { InvCatalogConvertIF converter = InvCatalogFactory . getDefaultConverter ( ) ; converter . writeXML ( this , os , raw ) ; } ////////////////////////////////////////////////////////////////////////// /**
   * Get dataset roots.
   *
   * @return List of InvProperty. May be empty, may not be null.
   */ public java . util . List < DataRootConfig > getDatasetRoots  ( ) { return roots ; } /**
   * Add Dataset Root, key = path,  value = location.
   * @param root add a dataset root
   */ public void addDatasetRoot  ( DataRootConfig root ) { roots . add ( root ) ; } /**
   * InvCatalogImpl elements with same values are equal.
   */ public boolean equals  ( Object o ) { if ( this == o ) return true ; if ( ! ( o instanceof InvCatalogImpl ) ) return false ; return o . hashCode ( ) == this . hashCode ( ) ; } /**
   * Override Object.hashCode() to implement equals.
   */ public int hashCode  ( ) { if ( hashCode == 0 ) { int result = 17 ; if ( null != getName ( ) ) result = 37 * result + getName ( ) . hashCode ( ) ; result = 37 * result + getServices ( ) . hashCode ( ) ; result = 37 * result + getDatasets ( ) . hashCode ( ) ; hashCode = result ; } return hashCode ; } private volatile int hashCode = 0 ; // Bloch, item 8 public boolean isStatic  ( ) { return isStatic ; } public void setStatic  ( boolean aStatic ) { isStatic = aStatic ; } }


Input:
This converts a string [ units ] since [ isoDate ] ( e . g . minutes since 1985 - 01 - 01 ) into a baseSeconds ( seconds since 1970 - 01 - 01 ) and a factor ( minutes returns 60 ) .
 So simplistically epochSeconds = storedTime * factor + baseSeconds .
 Or simplistically storedTime = ( epochSeconds - baseSeconds ) / factor . [CODESPLIT] public static double [ ] getTimeBaseAndFactor ( String tsUnits ) throws Exception { String errorInMethod = ErddapString2 . ERROR + " in Calendar2.getTimeBaseAndFactor(" + tsUnits + "):\n" ; if ( tsUnits == null ) { throw new NullPointerException ( errorInMethod + "tsUnits must be non-null." ) ; } int sincePo = tsUnits . toLowerCase ( ) . indexOf ( " since " ) ; if ( sincePo <= 0 ) throw new IllegalArgumentException ( errorInMethod + "units string doesn't contain \" since \"." ) ; double factorToGetSeconds = factorToGetSeconds ( tsUnits . substring ( 0 , sincePo ) ) ; GregorianCalendar baseGC = parseISODateTimeZulu ( tsUnits . substring ( sincePo + 7 ) ) ; double baseSeconds = baseGC . getTimeInMillis ( ) / 1000.0 ; return new double [ ] { baseSeconds , factorToGetSeconds } ; }


Input: This returns the factor to multiply by units data to get seconds data ( e . g . minutes returns 60 ) . This is used for part of dealing with udunits - style minutes since 1970 - 01 - 01 - style strings . [CODESPLIT] public static double factorToGetSeconds ( String units ) throws Exception { units = units . trim ( ) . toLowerCase ( ) ; if ( units . equals ( "ms" ) || units . equals ( "msec" ) || units . equals ( "msecs" ) || units . equals ( "millis" ) || units . equals ( "millisec" ) || units . equals ( "millisecs" ) || units . equals ( "millisecond" ) || units . equals ( "milliseconds" ) ) return 0.001 ; if ( units . equals ( "s" ) || units . equals ( "sec" ) || units . equals ( "secs" ) || units . equals ( "second" ) || units . equals ( "seconds" ) ) return 1 ; if ( units . equals ( "m" ) || units . equals ( "min" ) || units . equals ( "mins" ) || units . equals ( "minute" ) || units . equals ( "minutes" ) ) return SECONDS_PER_MINUTE ; if ( units . equals ( "h" ) || units . equals ( "hr" ) || units . equals ( "hrs" ) || units . equals ( "hour" ) || units . equals ( "hours" ) ) return SECONDS_PER_HOUR ; if ( units . equals ( "d" ) || units . equals ( "day" ) || units . equals ( "days" ) ) return SECONDS_PER_DAY ; if ( units . equals ( "week" ) || units . equals ( "weeks" ) ) return 7 * SECONDS_PER_DAY ; if ( units . equals ( "mon" ) || units . equals ( "mons" ) || units . equals ( "month" ) || units . equals ( "months" ) ) return 30 * SECONDS_PER_DAY ; if ( units . equals ( "yr" ) || units . equals ( "yrs" ) || units . equals ( "year" ) || units . equals ( "years" ) ) return 360 * SECONDS_PER_DAY ; throw new RuntimeException ( ErddapString2 . ERROR + " in Calendar2.factorToGetSeconds: units=\"" + units + "\" is invalid." ) ; }


Input: This parses n int values from s and stores results in resultsN ( or leaves items in resultsN untouched if no value available ) . [CODESPLIT] private static void parseN ( String s , char separatorN [ ] , int resultsN [ ] ) { //ensure s starts with a digit if ( s == null ) s = "" ; s = s . trim ( ) ; int sLength = s . length ( ) ; if ( sLength < 1 || ! ( s . charAt ( 0 ) == ' ' || ErddapString2 . isDigit ( s . charAt ( 0 ) ) ) ) { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } int po1 , po2 = - 1 ; //String2.log("parseN " + s); //search for digits, non-digit.   "1970-01-01T00:00:00.000-01:00" boolean mMode = s . charAt ( 0 ) == ' ' ; //initial '-' is required and included when evaluating number int nParts = separatorN . length ; for ( int part = 0 ; part < nParts ; part ++ ) { if ( po2 + 1 < sLength ) { //accumulate digits po1 = po2 + 1 ; po2 = po1 ; if ( mMode ) { if ( po2 < sLength && s . charAt ( po2 ) == ' ' ) po2 ++ ; else { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } } while ( po2 < sLength && ErddapString2 . isDigit ( s . charAt ( po2 ) ) ) po2 ++ ; //digit //if no number, return; we're done if ( po2 == po1 ) return ; if ( part > 0 && separatorN [ part - 1 ] == ' ' ) { resultsN [ part ] = ErddapMath2 . roundToInt ( 1000 * ErddapString2 . parseDouble ( "0." + s . substring ( po1 , po2 ) ) ) ; //String2.log("  millis=" + resultsN[part]); } else { resultsN [ part ] = ErddapString2 . parseInt ( s . substring ( po1 , po2 ) ) ; } //if invalid number, return trouble if ( resultsN [ part ] == Integer . MAX_VALUE ) { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } //if no more source characters, we're done if ( po2 >= sLength ) { //String2.log("  " + String2.toCSSVString(resultsN)); return ; } //if invalid separator, stop trying to read more; return trouble mMode = false ; char ch = s . charAt ( po2 ) ; if ( ch == ' ' ) ch = ' ' ; if ( separatorN [ part ] == ' ' ) { } else if ( separatorN [ part ] == ' )    if ( ch == ' ' ) { //do nothing } else if ( ch == ' ' ) { po2 -- ; //number starts with - mMode = true ; } else { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } } else if ( ch != separatorN [ part ] ) { //if not exact match ... //if current part is ':' or '.' and not matched, try to skip forward to '±' if ( ( separatorN [ part ] == ' ' || separatorN [ part ] == ' ' ) && part < nParts - 1 ) { int pmPart = ErddapString2 . indexOf ( separatorN , ' ,   art    ) ;  if ( pmPart >= 0 ) { //String2.log("  jump to +/-"); part = pmPart ; if ( ch == ' ' ) { //do nothing } else if ( ch == ' ' ) { po2 -- ; //number starts with - mMode = true ; } else { resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } continue ; } //if < 0, fall through to failure } resultsN [ 0 ] = Integer . MAX_VALUE ; return ; } } } }


Input:
This converts an ISO date time string ( [ - ] YYYY - MM - DDTHH : MM : SS . SSS±ZZ : ZZ ) into a GregorianCalendar object .
 It is lenient ; so Jan 32 is converted to Feb 1 ;
 The T may be any non - digit .
 The time zone can be omitted .
 The parts at the end of the time can be omitted .
 If there is no time the end parts of the date can be omitted . Year is required .
 This tries hard to be tolerant of non - valid formats ( e . g . 1971 - 1 - 2 1971 - 01 )
 As of 11 / 9 / 2006 NO LONGER TRUE : If year is 0 .. 49 it is assumed to be 2000 .. 2049 .
 As of 11 / 9 / 2006 NO LONGER TRUE : If year is 50 .. 99 it is assumed to be 1950 .. 1999 .
 If the string is too short the end of 1970 - 01 - 01T00 : 00 : 00 . 000Z will be added ( effectively ) .
 If the string is too long the excess will be ignored .
 If a required separator is incorrect it is an error .
 If the date is improperly formatted it returns null .
 Timezone Z or is treated as - 00 : 00 ( UTC / Zulu time )
 Timezones : e . g . 2007 - 01 - 02T03 : 04 : 05 - 01 : 00 is same as 2007 - 01 - 02T04 : 04 : 05 [CODESPLIT] public static GregorianCalendar parseISODateTime ( GregorianCalendar gc , String s ) { if ( s == null ) s = "" ; boolean negative = s . startsWith ( "-" ) ; if ( negative ) s = s . substring ( 1 ) ; if ( s . length ( ) < 1 || ! ErddapString2 . isDigit ( s . charAt ( 0 ) ) ) throw new RuntimeException ( ErddapString2 . ERROR + " in parseISODateTime: for first character of dateTime='" + s + "' isn't a digit!" ) ; if ( gc == null ) throw new RuntimeException ( ErddapString2 . ERROR + " in parseISODateTime: gc is null!" ) ; //default ymdhmsmom     year is the only required value int ymdhmsmom [ ] = { Integer . MAX_VALUE , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 } ; //remove trailing Z or "UTC" s = s . trim ( ) ; if ( Character . toLowerCase ( s . charAt ( s . length ( ) - 1 ) ) == ' ' ) s = s . substring ( 0 , s . length ( ) - 1 ) . trim ( ) ; if ( s . length ( ) >= 3 ) { String last3 = s . substring ( s . length ( ) - 3 ) . toLowerCase ( ) ; if ( last3 . equals ( "utc" ) || last3 . equals ( "gmt" ) ) s = s . substring ( 0 , s . length ( ) - 3 ) . trim ( ) ; } //if e.g., 1970-01-01 00:00:00 0:00, change ' ' to '+' (first ' '->'+' is irrelevant) s = ErddapString2 . replaceAll ( s , ' ' , ' ' ) ; //separators (\u0000=any non-digit) char separator [ ] = { ' ' , ' ' , ' ' , ' ' , ' ' , ' ' , ' ,   : ,   \ } ;  parseN ( s , separator , ymdhmsmom ) ; if ( ymdhmsmom [ 0 ] == Integer . MAX_VALUE ) throw new RuntimeException ( ErddapString2 . ERROR + " in parseISODateTime: dateTime='" + s + "' has an invalid format!" ) ; //do time zone adjustment //String2.log("#7=" + ymdhmsmom[7] + " #8=" + ymdhmsmom[8]); if ( ymdhmsmom [ 7 ] != 0 ) ymdhmsmom [ 3 ] -= ymdhmsmom [ 7 ] ; if ( ymdhmsmom [ 8 ] != 0 ) ymdhmsmom [ 4 ] -= ymdhmsmom [ 7 ] < 0 ? - ymdhmsmom [ 8 ] : ymdhmsmom [ 8 ] ; //set gc      month -1 since gc month is 0.. gc . set ( ( negative ? - 1 : 1 ) * ymdhmsmom [ 0 ] , ymdhmsmom [ 1 ] - 1 , ymdhmsmom [ 2 ] , ymdhmsmom [ 3 ] , ymdhmsmom [ 4 ] , ymdhmsmom [ 5 ] ) ; gc . set ( MILLISECOND , ymdhmsmom [ 6 ] ) ; gc . get ( YEAR ) ; //force recalculations return gc ; }


Input:
main . [CODESPLIT] public static void main ( String args [ ] ) throws Exception { //String fileIn = "C:/data/dt2/point/bufr/IUA_CWAO_20060202_12.bufr";
 //String fileIn = "C:/data/bufr/edition3/idd/profiler/PROFILER_3.bufr";
 //String fileIn = "C:/data/bufr/edition3/ecmwf/synop.bufr";
 //String fileIn = "R:/testdata2/bufr/edition3/idd/profiler/PROFILER_1.bufr";
 String fileIn = "D:/mlode/bufr/cat.out" ; NetcdfDataset ncf = NetcdfDataset . openDataset ( fileIn ) ; System . out . println ( ncf . toString ( ) ) ; /* Structure s = (Structure) ncf.findVariable(obsRecord);
    StructureData sdata = s.readStructure(2);
    PrintWriter pw = new PrintWriter(System.out);
    NCdumpW.printStructureData(pw, sdata);  */ new WriteT41_ncFlat ( ncf , "D:/mlode/bufr/cat2.nc" , true ) ; //Variable v = ncf.findVariable("recordIndex");
 //NCdumpW.printArray(v.read(), "recordIndex", pw, null);
 /* ucar.nc2.Variable v;

    v = ncf.findVariable("trajectory_id");
    if (v != null) {
      Array data = v.read();
      NCdump.printArray(data, v.getName(), System.out, null);
    }
    v = ncf.findVariable("station_id");
    if (v != null) {
      Array data = v.read();
      NCdump.printArray(data, v.getName(), System.out, null);
    }
    v = ncf.findVariable("firstChild");
    if (v != null) {
      Array data = v.read();
      NCdump.printArray(data, v.getName(), System.out, null);
    }
    v = ncf.findVariable("numChildren");
    if (v != null) {
      Array data = v.read();
      NCdump.printArray(data, v.getName(), System.out, null);
    }
    System.out.println();

    v = ncf.findVariable("record");
    //ucar.nc2.Variable v = ncf.findVariable("Latitude");
    //ucar.nc2.Variable v = ncf.findVariable("time");
    //System.out.println();
    //System.out.println( v.toString());

    if (v instanceof Structure) {
      Structure s = (Structure) v;
      StructureDataIterator iter = s.getStructureIterator();
      int count = 0;
      PrintWriter pw = new PrintWriter( System.out);
      while (iter.hasNext()) {
        System.out.println("record "+count);
        NCdumpW.printStructureData(pw, iter.next());
        count++;
      }
      Array data = v.read();
      NCdump.printArray(data, "record", System.out, null);
    } else {
      Array data = v.read();
      int[] length = data.getShape();
      System.out.println();
      System.out.println("v2 length =" + length[0]);

      IndexIterator ii = data.getIndexIterator();
      for (; ii.hasNext();) {
        System.out.println(ii.getFloatNext());
      }
    }
    ncf.close();  */ }


Input: Static Methods [CODESPLIT] static File findSystemTempDir ( String [ ] candidates ) { for ( String candidate : candidates ) { File f = new File ( candidate ) ; if ( f . exists ( ) && f . canRead ( ) && f . canWrite ( ) ) return f ; if ( f . mkdirs ( ) ) // Try to create the path return f ; } // As a last resort use the java temp file mechanism try { File tempfile = File . createTempFile ( "tmp" , "tmp" ) ; File tempdir = tempfile . getParentFile ( ) ; if ( ! tempdir . canWrite ( ) || ! tempdir . canRead ( ) ) return null ; return tempdir ; } catch ( IOException e ) { return null ; } }


Input: Servlet API ( Selected ) [CODESPLIT] public void init ( ) throws ServletException { try { if ( initialized ) return ; initialized = true ; logServerStartup . info ( getClass ( ) . getName ( ) + " initialization" ) ; System . setProperty ( "file.encoding" , "UTF-8" ) ; Field charset = Charset . class . getDeclaredField ( "defaultCharset" ) ; charset . setAccessible ( true ) ; charset . set ( null , null ) ; } catch ( Exception e ) { throw new ServletException ( e ) ; } }


Input: Invoked on first get so that everything is available especially Spring stuff . [CODESPLIT] public void initOnce ( HttpServletRequest req ) throws SendError { if ( once ) return ; once = true ; log . info ( getClass ( ) . getName ( ) + " GET initialization" ) ; if ( this . tdsContext == null ) throw new SendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR , "Cannot find TDS Context" ) ; // Get server host + port name StringBuilder buf = new StringBuilder ( ) ; buf . append ( req . getServerName ( ) ) ; int port = req . getServerPort ( ) ; if ( port > 0 ) { buf . append ( ":" ) ; buf . append ( port ) ; } this . server = buf . toString ( ) ; // Obtain servlet path info String tmp = HTTPUtil . canonicalpath ( req . getContextPath ( ) ) ; this . threddsname = HTTPUtil . nullify ( HTTPUtil . relpath ( tmp ) ) ; tmp = HTTPUtil . canonicalpath ( req . getServletPath ( ) ) ; this . requestname = HTTPUtil . nullify ( HTTPUtil . relpath ( tmp ) ) ; if ( this . threddsname == null ) this . threddsname = DEFAULTSERVLETNAME ; // Get the upload dir File updir = tdsContext . getUploadDir ( ) ; if ( updir == null ) { log . warn ( "No tds.upload.dir specified" ) ; this . uploaddir = null ; } else this . uploaddir = HTTPUtil . canonicalpath ( updir . getAbsolutePath ( ) ) ; // Get the download dir File downdir = tdsContext . getDownloadDir ( ) ; if ( downdir == null ) { log . warn ( "No tds.download.dir specified" ) ; this . downloaddir = null ; } else this . downloaddir = HTTPUtil . canonicalpath ( downdir . getAbsolutePath ( ) ) ; }


Input: //////////////////////////////////////////////// [CODESPLIT] protected String inquire ( ) { Map < String , String > result = new HashMap <> ( ) ; // Return all known server key values if ( this . downloaddir != null ) result . put ( "downloaddir" , this . downloaddir ) ; if ( this . uploaddir != null ) result . put ( "uploaddir" , this . uploaddir ) ; String sresult = mapToString ( result , true , "download" ) ; return sresult ; }


Input: for BufrMessageViewer [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , Message single ) throws IOException { this . raf = raf ; protoMessage = single ; protoMessage . getRootDataDescriptor ( ) ; // construct the data descriptors, check for complete tables if ( ! protoMessage . isTablesComplete ( ) ) throw new IllegalStateException ( "BUFR file has incomplete tables" ) ; BufrConfig config = BufrConfig . openFromMessage ( raf , protoMessage , null ) ; // this fills the netcdf object Construct2 construct = new Construct2 ( protoMessage , config , ncfile ) ; obsStructure = construct . getObsStructure ( ) ; isSingle = true ; ncfile . finish ( ) ; }


Input: /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public String getDetailInfo ( ) { Formatter ff = new Formatter ( ) ; ff . format ( "%s" , super . getDetailInfo ( ) ) ; protoMessage . dump ( ff ) ; ff . format ( "%n" ) ; config . show ( ff ) ; return ff . toString ( ) ; }


Input: Add value to the named counter . Add counter if it doesnt already exist . [CODESPLIT] public boolean count ( String name , Comparable value ) { Counter counter = map . get ( name ) ; if ( counter == null ) { counter = add ( name ) ; } return counter . count ( value ) ; }


Input: Gets an instance of this database . [CODESPLIT] public static synchronized StandardPrefixDB instance ( ) throws PrefixDBException { if ( instance == null ) { try { instance = new StandardPrefixDB ( ) ; } catch ( final Exception e ) { throw new PrefixDBException ( "Couldn't create standard prefix-database" , e ) ; } } return instance ; }


Input: Adds a prefix to the database . [CODESPLIT] private void add ( final String name , final String symbol , final double definition ) throws PrefixExistsException { addName ( name , definition ) ; addSymbol ( symbol , definition ) ; }


Input: Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final PrefixDB db = StandardPrefixDB . instance ( ) ; System . out . println ( "db.getPrefixBySymbol(\"cm\") = \"" + db . getPrefixBySymbol ( "cm" ) + ' ' ) ; System . out . println ( "db.getPrefixBySymbol(\"dm\") = \"" + db . getPrefixBySymbol ( "dm" ) + ' ' ) ; }


Input: for other behavior override this ; use compareXXX routines . [CODESPLIT] public int compare ( TableRow other , int col ) { String s1 = getValueAt ( col ) . toString ( ) ; String s2 = other . getValueAt ( col ) . toString ( ) ; int ret = s1 . compareToIgnoreCase ( s2 ) ; // break ties if ( ret == 0 ) return compareTie ( other , col ) ; return ret ; }


Input: for use by the subclass [CODESPLIT] protected int compareBoolean ( TableRow other , int col , boolean b1 , boolean b2 ) { // break ties if ( b1 == b2 ) return compareTie ( other , col ) ; return b1 ? 1 : - 1 ; }


Input: Parser specific methods [CODESPLIT] DapGroup getGroupScope ( ) throws DapException { DapGroup gscope = ( DapGroup ) searchScope ( DapSort . GROUP , DapSort . DATASET ) ; if ( gscope == null ) throw new DapException ( "Undefined Group Scope" ) ; return gscope ; }


Input: Attribute map utilities [CODESPLIT] SaxEvent pull ( XMLAttributeMap map , String name ) { SaxEvent event = map . remove ( name . toLowerCase ( ) ) ; return event ; }


Input: add any reserved xml attributes to a node unchanged [CODESPLIT] void passReserved ( XMLAttributeMap map , DapNode node ) throws ParseException { try { DapAttribute attr = null ; for ( Map . Entry < String , SaxEvent > entry : map . entrySet ( ) ) { SaxEvent event = entry . getValue ( ) ; String key = entry . getKey ( ) ; String value = event . value ; if ( isReserved ( key ) ) node . addXMLAttribute ( key , value ) ; } } catch ( DapException de ) { throw new ParseException ( de ) ; } }


Input: Attribute map utilities [CODESPLIT] SaxEvent peek ( XMLAttributeMap map , String name ) { SaxEvent event = map . get ( name . toLowerCase ( ) ) ; return event ; }


Input: Attribute construction [CODESPLIT] DapAttribute makeAttribute ( DapSort sort , String name , DapType basetype , List < String > nslist , DapNode parent ) throws DapException { DapAttribute attr = new DapAttribute ( name , basetype ) ; if ( sort == DapSort . ATTRIBUTE ) { attr . setBaseType ( basetype ) ; } parent . addAttribute ( attr ) ; attr . setNamespaceList ( nslist ) ; return attr ; }


Input: Abstract action definitions [CODESPLIT] @ Override void enterdataset ( XMLAttributeMap attrs ) throws ParseException { this . debug = getDebugLevel ( ) > 0 ; // make sure we have the latest value if ( debug ) report ( "enterdataset" ) ; SaxEvent name = pull ( attrs , "name" ) ; SaxEvent dapversion = pull ( attrs , "dapversion" ) ; SaxEvent dmrversion = pull ( attrs , "dmrversion" ) ; if ( isempty ( name ) ) throw new ParseException ( "Empty dataset name attribute" ) ; // convert and test version numbers float ndapversion = DAPVERSION ; if ( dapversion != null ) try { ndapversion = Float . parseFloat ( dapversion . value ) ; } catch ( NumberFormatException nfe ) { ndapversion = DAPVERSION ; } if ( ndapversion != DAPVERSION ) throw new ParseException ( "Dataset dapVersion mismatch: " + dapversion . value ) ; float ndmrversion = DMRVERSION ; if ( dmrversion != null ) try { ndmrversion = Float . parseFloat ( dmrversion . value ) ; } catch ( NumberFormatException nfe ) { ndmrversion = DMRVERSION ; } if ( ndmrversion != DMRVERSION ) throw new ParseException ( "Dataset dmrVersion mismatch: " + dmrversion . value ) ; this . root = new DapDataset ( name . value ) ; this . root . setDapVersion ( Float . toString ( ndapversion ) ) ; this . root . setDMRVersion ( Float . toString ( ndmrversion ) ) ; this . root . setDataset ( this . root ) ; passReserved ( attrs , this . root ) ; scopestack . push ( this . root ) ; }


Input: This is called for <Value > ... < / Value > [CODESPLIT] @ Override void value ( String value ) throws ParseException { if ( debug ) report ( "value" ) ; try { DapAttribute parent = ( DapAttribute ) getScope ( DapSort . ATTRIBUTE ) ; createvalue ( value , parent ) ; } catch ( DapException de ) { throw new ParseException ( de ) ; } }