Input:
/ * ( non - Javadoc ) [CODESPLIT] @ Override public boolean isValid ( NcssPointParamsBean params , ConstraintValidatorContext constraintValidatorContext ) { constraintValidatorContext . disableDefaultConstraintViolation ( ) ; boolean isValid = true ; boolean isStnRequest = params . hasLatLonPoint ( ) && params . hasStations ( ) ; boolean isPointRequest = params . hasLatLonPoint ( ) && ! params . hasStations ( ) ; // if no stn param is provided ignore all the others, it must be a point request // if stn == all --> all stations		 if ( ! isStnRequest && ! isPointRequest ) { isValid = false ; constraintValidatorContext . buildConstraintViolationWithTemplate ( "{thredds.server.ncSubset.validation.lat_or_lon_missing}" ) . addConstraintViolation ( ) ; } /* if( params.getSubset() != null && !params.getSubset().equals("stns") && !params.getSubset().equals("all") && !params.getSubset().equals("bb")  ){
			isValid = false;
			constraintValidatorContext
			.buildConstraintViolationWithTemplate("{thredds.server.ncSubset.validation.subsettypeerror}")
			.addConstraintViolation();
		}

		if( params.getSubset() != null && params.getSubset().equals("stns") && params.getStns() == null ){
			isValid = false;
			constraintValidatorContext
			.buildConstraintViolationWithTemplate("{thredds.server.ncSubset.validation.subsettypeerror.no_stns_param}")
			.addConstraintViolation();
		}

		if( params.getSubset() != null && params.getSubset().equals("bb") && (params.getNorth()  == null || params.getSouth() == null || params.getEast() == null || params.getWest() == null  )){
			isValid = false;
			constraintValidatorContext
			.buildConstraintViolationWithTemplate("{thredds.server.ncSubset.validation.subsettypeerror.no_bounding_box}")
			.addConstraintViolation();
		}		*/ return isValid ; }


Input: Determine if a valid date range was specified [CODESPLIT] private boolean hasValidDateRange ( String time_start , String time_end , String time_duration ) { // no range if ( ( null == time_start ) && ( null == time_end ) && ( null == time_duration ) ) return false ; if ( ( null != time_start ) && ( null != time_end ) ) return true ; if ( ( null != time_start ) && ( null != time_duration ) ) return true ; if ( ( null != time_end ) && ( null != time_duration ) ) return true ; // misformed range // errs.append("Must have 2 of 3 parameters: time_start, time_end, time_duration\n"); return false ; }


Input: Iterator interface extended [CODESPLIT] @ Override public boolean hasNext ( ) { switch ( state ) { case INITIAL : return ( slice . getFirst ( ) < slice . getStop ( ) ) ; case STARTED : return ( this . index < slice . getLast ( ) ) ; case DONE : } return false ; }


Input:
Returns the <code > Attribute< / code > which matches name . [CODESPLIT] public final Attribute getAttribute ( String clearname ) { //throws NoSuchAttributeException {
 Attribute a = ( Attribute ) _attr . get ( clearname ) ; return ( a ) ; }


Input: Returns the <code > Attribute< / code > which matches name . [CODESPLIT] public final boolean hasAttribute ( String clearname ) { Attribute a = ( Attribute ) _attr . get ( clearname ) ; if ( a == null ) { return ( false ) ; } return ( true ) ; }


Input:
Adds an attribute to the table . If the given name already refers to an attribute and the attribute has a vector value the given value is appended to the attribute vector . Calling this function repeatedly is the way to create an attribute vector . <p / > The function throws an exception if the attribute is a container or if the type of the input value does not match the existing attribute s type and the <code > check< / code > parameter is true . Use the <code > appendContainer< / code > method to add container attributes . [CODESPLIT] public final void appendAttribute ( String clearname , int type , String value , boolean check ) throws DASException { Attribute a = ( Attribute ) _attr . get ( clearname ) ; if ( a != null && ( type != a . getType ( ) ) ) { // type mismatch error
 throw new AttributeExistsException ( "The Attribute `" + clearname + "' was previously defined with a different type." ) ; } else if ( a != null ) { a . appendValue ( value , check ) ; } else { a = new Attribute ( type , clearname , value , check ) ; _attr . put ( clearname , a ) ; } }


Input: Adds an attribute to the table . If the given name already refers to an attribute and the attribute has a vector value the given value is appended to the attribute vector . Calling this function repeatedly is the way to create an attribute vector . <p / > The function throws an exception if the attribute is a container or if the type of the input value does not match the existing attribute s type . Use the <code > appendContainer< / code > method to add container attributes . [CODESPLIT] public final void appendAttribute ( String clearname , int type , String value ) throws DASException { appendAttribute ( clearname , type , value , true ) ; }


Input:
Create and append an attribute container to the table . A container is another <code > AttributeTable< / code > object . [CODESPLIT] public final AttributeTable appendContainer ( String clearname ) { // return null if clearname already exists
 // FIXME! THIS SHOULD RETURN AN EXCEPTION!
 if ( _attr . get ( clearname ) != null ) return null ; AttributeTable at = new AttributeTable ( clearname ) ; Attribute a = new Attribute ( clearname , at ) ; _attr . put ( clearname , a ) ; return at ; }


Input:
Create and append an attribute container to the table . A container is another <code > AttributeTable< / code > object . [CODESPLIT] public final void addContainer ( String clearname , AttributeTable at ) throws AttributeExistsException { // return null if name already exists
 if ( _attr . get ( clearname ) != null ) { throw new AttributeExistsException ( "The Attribute '" + clearname + "' already exists in the container '" + getEncodedName ( ) + "'" ) ; } Attribute a = new Attribute ( clearname , at ) ; _attr . put ( clearname , a ) ; }


Input:
Add an alias to the current table . This method is used by the DAS parser to build Aliases for the DAS . And the DDSXMLParser to add them to the DDX <p / > The new ( 9 / 26 / 02 ) DDS requires the use of <code > addAlias ( String String String ) < / code > and is the preffered way of representing the DAS information . [CODESPLIT] public final void addAlias ( String alias , String attributeName ) throws NoSuchAttributeException , AttributeExistsException { // complain if alias name already exists in this AttributeTable.
 if ( _attr . get ( alias ) != null ) { throw new AttributeExistsException ( "Could not alias `" + alias + "' to `" + attributeName + "'. " + "It is a duplicat name in this AttributeTable" ) ; } if ( Debug . isSet ( "AttributTable" ) ) { log . debug ( "Adding alias '" + alias + "' to AttributeTable '" + getClearName ( ) + "'" ) ; } Alias newAlias = new Alias ( alias , attributeName ) ; _attr . put ( alias , newAlias ) ; }


Input:
Delete the attribute named <code > name< / code > . If the attribute has a vector value delete the <code > i< / code > th element of the vector . [CODESPLIT] public final void delAttribute ( String clearname , int i ) throws DASException { if ( i == - 1 ) { // delete the whole attribute
 _attr . remove ( clearname ) ; } else { Attribute a = ( Attribute ) _attr . get ( clearname ) ; if ( a != null ) { if ( a . isContainer ( ) ) { _attr . remove ( clearname ) ; // delete the entire container
 } else { a . deleteValueAt ( i ) ; } } } }


Input: Print the attribute table on the given <code > PrintWriter< / code > . [CODESPLIT] public void print ( PrintWriter os , String pad ) { if ( Debug . isSet ( "AttributTable" ) ) os . println ( "Entered AttributeTable.print()" ) ; os . println ( pad + getEncodedName ( ) + " {" ) ; for ( Enumeration e = getNames ( ) ; e . hasMoreElements ( ) ; ) { String name = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( name ) ; if ( a != null ) a . print ( os , pad + "    " ) ; } os . println ( pad + "}" ) ; if ( Debug . isSet ( "AttributTable" ) ) os . println ( "Leaving AttributeTable.print()" ) ; os . flush ( ) ; }


Input: Print the attribute table on the given <code > OutputStream< / code > . [CODESPLIT] public final void print ( OutputStream os , String pad ) { print ( new PrintWriter ( new BufferedWriter ( new OutputStreamWriter ( os , Util . UTF8 ) ) ) , pad ) ; }


Input:
Returns a clone of this <code > AttributeTable< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { AttributeTable at = ( AttributeTable ) super . cloneDAG ( map ) ; at . _attr = new SortedTable ( ) ; for ( int i = 0 ; i < _attr . size ( ) ; i ++ ) { String key = ( String ) _attr . getKey ( i ) ; Attribute element = ( Attribute ) _attr . elementAt ( i ) ; // clone element (don't clone key because it's a read-only String)
 at . _attr . put ( key , ( Attribute ) cloneDAG ( map , element ) ) ; } return at ; }


Input: subcenters [CODESPLIT] @ Override public String getSubCenterName ( int subcenter ) { if ( subcenterMap == null ) subcenterMap = makeSubcenterMap ( ) ; return subcenterMap . get ( subcenter ) ; }


Input: gen process [CODESPLIT] @ Override @ Nullable public String getGeneratingProcessName ( int genProcess ) { if ( genProcessMap == null ) makeGenProcessMap ( ) ; return genProcessMap . get ( genProcess ) ; }


Input: / levels [CODESPLIT] @ Override public Grib1ParamLevel getParamLevel ( Grib1SectionProductDefinition pds ) { int levelType = pds . getLevelType ( ) ; int pds11 = pds . getLevelValue1 ( ) ; int pds12 = pds . getLevelValue2 ( ) ; int pds1112 = pds11 << 8 | pds12 ; switch ( levelType ) { case 210 : return new Grib1ParamLevel ( this , levelType , ( float ) pds1112 , GribNumbers . MISSING ) ; case 218 : return new Grib1ParamLevel ( this , levelType , ( float ) pds11 + 200 , ( float ) pds12 + 200 ) ; case 246 : return new Grib1ParamLevel ( this , levelType , ( float ) pds1112 , GribNumbers . MISSING ) ; default : return new Grib1ParamLevel ( this , pds ) ; } }


Input: Returns { @code true } if this point is nearly equal to { @code that } . The near equality of points is determined using { @link Misc#nearlyEquals ( double double double ) } with the specified maxRelDiff . [CODESPLIT] public boolean nearlyEquals ( LatLonPointNoNormalize that , double maxRelDiff ) { return Misc . nearlyEquals ( this . getLatitude ( ) , that . getLatitude ( ) , maxRelDiff ) && Misc . nearlyEquals ( this . getLongitude ( ) , that . getLongitude ( ) , maxRelDiff ) ; }


Input: Given a relative path as an array of path segments ( see { @link #getPathSegments ( String ) } return the path relative to the first path segment . [CODESPLIT] public static String stepDownRelativePath ( String [ ] pathSegments ) { if ( ! CrawlableDatasetUtils . isValidRelativePath ( pathSegments ) ) throw new IllegalArgumentException ( "Path segments not a valid relative path." ) ; if ( pathSegments . length < 2 ) throw new IllegalArgumentException ( "Number of path segments must be > 1." ) ; StringBuilder sb = new StringBuilder ( ) ; for ( int i = 1 ; i < pathSegments . length - 1 ; i ++ ) { sb . append ( pathSegments [ i ] ) . append ( "/" ) ; } sb . append ( pathSegments [ pathSegments . length - 1 ] ) ; return sb . toString ( ) ; }


Input: Register a DSP using its class string name . [CODESPLIT] synchronized public void register ( String className , boolean last ) throws DapException { try { Class < ? extends DSP > klass = ( Class < ? extends DSP > ) loader . loadClass ( className ) ; register ( klass , last ) ; } catch ( ClassNotFoundException e ) { throw new DapException ( e ) ; } }


Input: Register a DSP class . [CODESPLIT] synchronized public void register ( Class < ? extends DSP > klass , boolean last ) { // is this already defined? if ( registered ( klass ) ) return ; if ( last ) registry . add ( new Registration ( klass ) ) ; else registry . add ( 0 , new Registration ( klass ) ) ; }


Input: See if a specific DSP is registered [CODESPLIT] synchronized public boolean registered ( Class < ? extends DSP > klass ) { for ( Registration r : registry ) { if ( r . dspclass == klass ) return true ; } return false ; }


Input: Unregister dsp . [CODESPLIT] synchronized public void unregister ( Class < ? extends DSP > klass ) { for ( int i = 0 ; i < registry . size ( ) ; i ++ ) { if ( registry . get ( i ) . dspclass == klass ) { registry . remove ( i ) ; break ; } } }


Input:
Lazy instantiation . [CODESPLIT] public static Grib2Tables factory ( int center , int subCenter , int masterVersion , int localVersion , int genProcessId ) { Grib2TablesId id = new Grib2TablesId ( center , subCenter , masterVersion , localVersion , genProcessId ) ; Grib2Tables cust = tables . get ( id ) ; if ( cust != null ) return cust ; // note that we match on id, so same Grib2Customizer may be mapped to multiple id's (eg match on -1)
 Grib2TableConfig config = Grib2TableConfig . matchTable ( id ) ; cust = build ( config ) ; tables . put ( id , cust ) ; return cust ; }


Input:
Get the time interval in units of gr . getPDS () . getTimeUnit () [CODESPLIT] @ Nullable public TimeCoordIntvDateValue getForecastTimeInterval ( Grib2Record gr ) { // note  from Arthur Taylor (degrib):
 /* If there was a range I used:

    End of interval (EI) = (bytes 36-42 show an "end of overall time interval")
    C1) End of Interval = EI;
    Begin of Interval = EI - range

    and if there was no interval then I used:
    C2) End of Interval = Begin of Interval = Ref + ForeT.
    */ if ( ! gr . getPDS ( ) . isTimeInterval ( ) ) return null ; Grib2Pds . PdsInterval pdsIntv = ( Grib2Pds . PdsInterval ) gr . getPDS ( ) ; int timeUnitOrg = gr . getPDS ( ) . getTimeUnit ( ) ; // calculate total "range"
 int range = 0 ; for ( Grib2Pds . TimeInterval ti : pdsIntv . getTimeIntervals ( ) ) { if ( ti . timeRangeUnit == 255 ) continue ; if ( ( ti . timeRangeUnit != timeUnitOrg ) || ( ti . timeIncrementUnit != timeUnitOrg && ti . timeIncrementUnit != 255 && ti . timeIncrement != 0 ) ) { if ( ! timeUnitWarnWasSent ) { logger . warn ( "TimeInterval has different units timeUnit org=" + timeUnitOrg + " TimeInterval=" + ti . timeIncrementUnit ) ; timeUnitWarnWasSent = true ; // throw new RuntimeException("TimeInterval(2) has different units");
 } } range += ti . timeRangeLength ; if ( ti . timeIncrementUnit != 255 ) range += ti . timeIncrement ; } CalendarPeriod unitPeriod = Grib2Utils . getCalendarPeriod ( convertTimeUnit ( timeUnitOrg ) ) ; if ( unitPeriod == null ) return null ; CalendarPeriod period = unitPeriod . multiply ( range ) ; // End of Interval as date
 CalendarDate EI = pdsIntv . getIntervalTimeEnd ( ) ; if ( EI == CalendarDate . UNKNOWN ) { // all values were set to zero   LOOK guessing!
 return new TimeCoordIntvDateValue ( gr . getReferenceDate ( ) , period ) ; } else { return new TimeCoordIntvDateValue ( period , EI ) ; } }


Input:
Get interval size in units of hours . Only use in GribVariable to decide on variable identity when intvMerge = false . [CODESPLIT] public double getForecastTimeIntervalSizeInHours ( Grib2Pds pds ) { Grib2Pds . PdsInterval pdsIntv = ( Grib2Pds . PdsInterval ) pds ; int timeUnitOrg = pds . getTimeUnit ( ) ; // calculate total "range" in units of timeUnit
 int range = 0 ; for ( Grib2Pds . TimeInterval ti : pdsIntv . getTimeIntervals ( ) ) { if ( ti . timeRangeUnit == 255 ) continue ; if ( ( ti . timeRangeUnit != timeUnitOrg ) || ( ti . timeIncrementUnit != timeUnitOrg && ti . timeIncrementUnit != 255 && ti . timeIncrement != 0 ) ) { logger . warn ( "TimeInterval(2) has different units timeUnit org=" + timeUnitOrg + " TimeInterval=" + ti . timeIncrementUnit ) ; throw new RuntimeException ( "TimeInterval(2) has different units" ) ; } range += ti . timeRangeLength ; if ( ti . timeIncrementUnit != 255 ) range += ti . timeIncrement ; } // now convert that range to units of the requested period.
 CalendarPeriod timeUnitPeriod = Grib2Utils . getCalendarPeriod ( convertTimeUnit ( timeUnitOrg ) ) ; if ( timeUnitPeriod == null ) return GribNumbers . UNDEFINEDD ; if ( timeUnitPeriod . equals ( CalendarPeriod . Hour ) ) return range ; double fac ; if ( timeUnitPeriod . getField ( ) == CalendarPeriod . Field . Month ) { fac = 30.0 * 24.0 ; // nominal hours in a month
 } else if ( timeUnitPeriod . getField ( ) == CalendarPeriod . Field . Year ) { fac = 365.0 * 24.0 ; // nominal hours in a year
 } else { fac = CalendarPeriod . Hour . getConvertFactor ( timeUnitPeriod ) ; } return fac * range ; }


Input: If this has a time interval coordinate get time interval [CODESPLIT] @ Nullable public int [ ] getForecastTimeIntervalOffset ( Grib2Record gr ) { TimeCoordIntvDateValue tinvd = getForecastTimeInterval ( gr ) ; if ( tinvd == null ) return null ; Grib2Pds pds = gr . getPDS ( ) ; int unit = convertTimeUnit ( pds . getTimeUnit ( ) ) ; TimeCoordIntvValue tinv = tinvd . convertReferenceDate ( gr . getReferenceDate ( ) , Grib2Utils . getCalendarPeriod ( unit ) ) ; if ( tinv == null ) return null ; int [ ] result = new int [ 2 ] ; result [ 0 ] = tinv . getBounds1 ( ) ; result [ 1 ] = tinv . getBounds2 ( ) ; return result ; }


Input:
Unit of vertical coordinate . from Grib2 code table 4 . 5 . Only levels with units get a dimension added [CODESPLIT] @ Override public VertCoordType getVertUnit ( int code ) { //     VertCoordType(int code, String desc, String abbrev, String units, String datum, boolean isPositiveUp, boolean isLayer)
 switch ( code ) { case 11 : case 12 : return new VertCoordType ( code , "m" , null , true ) ; case 20 : return new VertCoordType ( code , "K" , null , false ) ; case 100 : return new VertCoordType ( code , "Pa" , null , false ) ; case 102 : return new VertCoordType ( code , "m" , "mean sea level" , true ) ; case 103 : return new VertCoordType ( code , "m" , "ground" , true ) ; case 104 : case 105 : return new VertCoordType ( code , "sigma" , null , false ) ; // positive?
 case 106 : return new VertCoordType ( code , "m" , "land surface" , false ) ; case 107 : return new VertCoordType ( code , "K" , null , true ) ; // positive?
 case 108 : return new VertCoordType ( code , "Pa" , "ground" , true ) ; case 109 : return new VertCoordType ( code , "K m2 kg-1 s-1" , null , true ) ; // positive?
 case 114 : return new VertCoordType ( code , "numeric" , null , false ) ; case 117 : return new VertCoordType ( code , "m" , null , true ) ; case 119 : return new VertCoordType ( code , "Pa" , null , false ) ; // ??
 case 160 : return new VertCoordType ( code , "m" , "sea level" , false ) ; case 161 : return new VertCoordType ( code , "m" , "water surface" , false ) ; // LOOK NCEP specific
 case 235 : return new VertCoordType ( code , "0.1 C" , null , true ) ; case 237 : return new VertCoordType ( code , "m" , null , true ) ; case 238 : return new VertCoordType ( code , "m" , null , true ) ; default : return new VertCoordType ( code , null , null , true ) ; } }


Input: Compute inferred information [CODESPLIT] public void finish ( ) { if ( this . finished ) return ; if ( this . ce == null ) this . visiblenodes = nodelist ; else { this . visiblenodes = new ArrayList < DapNode > ( nodelist . size ( ) ) ; for ( int i = 0 ; i < nodelist . size ( ) ; i ++ ) { DapNode node = nodelist . get ( i ) ; if ( ce . references ( node ) ) visiblenodes . add ( node ) ; } } this . topvariables = new ArrayList < DapVariable > ( ) ; this . allvariables = new ArrayList < DapVariable > ( ) ; this . allgroups = new ArrayList < DapGroup > ( ) ; this . allenums = new ArrayList < DapEnumeration > ( ) ; this . allcompounds = new ArrayList < DapStructure > ( ) ; this . alldimensions = new ArrayList < DapDimension > ( ) ; finishR ( this ) ; }


Input: Recursive helper [CODESPLIT] protected void finishR ( DapNode node ) { if ( ce != null && ! ce . references ( node ) ) return ; switch ( node . getSort ( ) ) { case DIMENSION : this . alldimensions . add ( ( DapDimension ) node ) ; break ; case ENUMERATION : this . allenums . add ( ( DapEnumeration ) node ) ; break ; case SEQUENCE : case STRUCTURE : this . allcompounds . add ( ( DapStructure ) node ) ; break ; case VARIABLE : if ( node . isTopLevel ( ) ) this . topvariables . add ( ( DapVariable ) node ) ; this . allvariables . add ( ( DapVariable ) node ) ; break ; case GROUP : case DATASET : DapGroup g = ( DapGroup ) node ; this . allgroups . add ( g ) ; for ( DapNode subnode : g . getDecls ( ) ) { finishR ( subnode ) ; } break ; default : /*ignore*/ break ; } }


Input: Parse an FQN and use it to trace to a specific object in a dataset . Note that this is quite tricky in the face of backslash escapes . Because of backslash escapes we cannot use the String . split function because it does appear to be possible to write a regexp that handles preceding backslashes correctly . Instead we must parse character by character left to right . Traversal into structs : In theory a map variable could point to a field of a structure . However in practice this will not work because we would need a specific instance of that field which means including dimension indices must be included starting from some top - level variable . We choose for now to make that illegal until such time as there is a well - defined meaning for this . Note : this assumes the fqn is absolute ( i . e . starts with / ) . [CODESPLIT] public DapNode lookup ( String fqn , DapSort ... sortset ) throws DapException { fqn = fqn . trim ( ) ; if ( fqn == null ) return null ; if ( "" . equals ( fqn ) || "/" . equals ( fqn ) ) { return this ; } if ( fqn . charAt ( 0 ) == ' ' ) fqn = fqn . substring ( 1 ) ; // remove leading / //Check first for an atomic type TypeSort ts = TypeSort . getTypeSort ( fqn ) ; if ( ts != null && ts . isAtomic ( ) ) { // see if we are looking for an atomic type for ( DapSort ds : sortset ) { if ( ds == DapSort . ATOMICTYPE ) return DapType . lookup ( ts ) ; } } // Do not use split to be able to look for escaped '/' // Warning: elements of path are unescaped List < String > path = DapUtil . backslashSplit ( fqn , ' ' ) ; DapGroup current = dataset ; // Walk all but the last element to walk group path for ( int i = 0 ; i < path . size ( ) - 1 ; i ++ ) { String groupname = Escape . backslashUnescape ( path . get ( i ) ) ; DapGroup g = ( DapGroup ) current . findInGroup ( groupname , DapSort . GROUP ) ; if ( g == null ) return null ; assert ( g . getSort ( ) == DapSort . GROUP ) ; current = ( DapGroup ) g ; } if ( ! ALLOWFIELDMAPS ) { String targetname = Escape . backslashUnescape ( path . get ( path . size ( ) - 1 ) ) ; return current . findInGroup ( targetname , sortset ) ; } else { // ALLOWFIELDMAPS) // We need to handle the last segment of the group path // to deal with struct walking using '.'. We need to obtain the last segment // with escapes intact so we can spot '.' separators. // Locate the last element in the last group // Start by looking for any containing structure String varpart = path . get ( path . size ( ) - 1 ) ; // Note that this still has escapes // So that '.' parsing will be correct. List < String > structpath = DapUtil . backslashSplit ( varpart , ' ' ) ; String outer = Escape . backslashUnescape ( structpath . get ( 0 ) ) ; if ( structpath . size ( ) == 1 ) { return current . findInGroup ( outer , sortset ) ; } else { // It is apparently a structure field // locate the outermost structure to start with DapStructure currentstruct = ( DapStructure ) current . findInGroup ( outer , DapSort . STRUCTURE , DapSort . SEQUENCE ) ; if ( currentstruct == null ) return null ; // does not exist // search for the innermost structure String fieldname ; for ( int i = 1 ; i < structpath . size ( ) - 1 ; i ++ ) { fieldname = Escape . backslashUnescape ( structpath . get ( i ) ) ; DapVariable field = ( DapVariable ) currentstruct . findByName ( fieldname ) ; if ( field == null ) throw new DapException ( "No such field: " + fieldname ) ; if ( ! field . isCompound ( ) ) break ; currentstruct = ( DapStructure ) field . getBaseType ( ) ; } fieldname = Escape . backslashUnescape ( structpath . get ( structpath . size ( ) - 1 ) ) ; DapVariable field = currentstruct . findByName ( fieldname ) ; if ( field == null ) throw new DapException ( "No such field: " + fieldname ) ; if ( field . getSort ( ) . oneof ( sortset ) ) return ( field ) ; } } return null ; }


Input: Sort the nodelist into prefix left to right order [CODESPLIT] public void sort ( ) { List < DapNode > sorted = new ArrayList < DapNode > ( ) ; sortR ( this , sorted ) ; // Assign indices for ( int i = 0 ; i < sorted . size ( ) ; i ++ ) { sorted . get ( i ) . setIndex ( i ) ; } this . nodelist = sorted ; }


Input: Sort helper [CODESPLIT] public void sortR ( DapNode node , List < DapNode > sortlist ) { DapVariable var = null ; Map < String , DapAttribute > attrs = null ; sortlist . add ( node ) ; switch ( node . getSort ( ) ) { case DATASET : case GROUP : // Walk the decls in this group in order // attributes, dimensions, enums, variables, groups DapGroup group = ( DapGroup ) node ; attrs = group . getAttributes ( ) ; for ( Map . Entry < String , DapAttribute > entry : attrs . entrySet ( ) ) { sortR ( entry . getValue ( ) , sortlist ) ; } List < DapDimension > dims = group . getDimensions ( ) ; if ( dims != null ) for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { sortR ( dims . get ( i ) , sortlist ) ; } List < DapEnumeration > enums = group . getEnums ( ) ; if ( enums != null ) for ( int i = 0 ; i < enums . size ( ) ; i ++ ) { sortR ( enums . get ( i ) , sortlist ) ; } List < DapVariable > vars = group . getVariables ( ) ; if ( vars != null ) for ( int i = 0 ; i < vars . size ( ) ; i ++ ) { sortR ( vars . get ( i ) , sortlist ) ; } List < DapGroup > groups = group . getGroups ( ) ; if ( groups != null ) for ( int i = 0 ; i < groups . size ( ) ; i ++ ) { sortR ( groups . get ( i ) , sortlist ) ; } break ; case VARIABLE : var = ( DapVariable ) node ; attrs = var . getAttributes ( ) ; if ( attrs != null ) for ( Map . Entry < String , DapAttribute > entry : attrs . entrySet ( ) ) { sortR ( entry . getValue ( ) , sortlist ) ; } List < DapMap > maps = var . getMaps ( ) ; if ( maps != null ) for ( int i = 0 ; i < maps . size ( ) ; i ++ ) { sortR ( maps . get ( i ) , sortlist ) ; } dims = var . getDimensions ( ) ; if ( dims != null ) for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { sortR ( dims . get ( i ) , sortlist ) ; } break ; case ATTRIBUTE : attrs = node . getAttributes ( ) ; if ( attrs != null ) for ( String name : attrs . keySet ( ) ) { sortR ( attrs . get ( name ) , sortlist ) ; } break ; default : break ; } }


Input: Compare 2 tables print report . [CODESPLIT] public static void compareTables ( Grib2ParamTableInterface t1 , Grib2ParamTableInterface t2 , Formatter f ) { int extra = 0 ; int udunits = 0 ; int conflict = 0 ; f . format ( "%s%n" , t2 . getName ( ) ) ; for ( GribTables . Parameter p1 : t1 . getParameters ( ) ) { if ( t1 . getParameter ( p1 . getNumber ( ) ) == null ) { f . format ( " ERROR %s missing own parameter %d%n" , t1 . getShortName ( ) , p1 . getNumber ( ) ) ; } GribTables . Parameter p2 = t2 . getParameter ( p1 . getNumber ( ) ) ; if ( p2 == null ) { extra ++ ; if ( verbose ) { f . format ( "  %s missing %s%n" , t2 . getShortName ( ) , p1 ) ; } } else { if ( ! Util . equivilantName ( p1 . getName ( ) , p2 . getName ( ) ) ) { f . format ( "  p1=%10s %s%n" , p1 . getId ( ) , p1 . getName ( ) ) ; f . format ( "  p2=%10s %s%n" , p2 . getId ( ) , p2 . getName ( ) ) ; conflict ++ ; } if ( ! p1 . getUnit ( ) . equalsIgnoreCase ( p2 . getUnit ( ) ) ) { String cu1 = Util . cleanUnit ( p1 . getUnit ( ) ) ; String cu2 = Util . cleanUnit ( p2 . getUnit ( ) ) ; // eliminate common non-udunits boolean isUnitless1 = Util . isUnitless ( cu1 ) ; boolean isUnitless2 = Util . isUnitless ( cu2 ) ; if ( isUnitless1 != isUnitless2 ) { f . format ( "  unitless for %10s %s != %s%n" , p1 . getId ( ) , cu1 , cu2 ) ; udunits ++ ; } else if ( ! isUnitless1 ) { try { SimpleUnit su1 = SimpleUnit . factoryWithExceptions ( cu1 ) ; if ( ! su1 . isCompatible ( cu2 ) ) { f . format ( "  incompatible for %10s %s (%s) != %s (org %s)%n" , p1 . getId ( ) , cu1 , su1 , cu2 , p2 . getUnit ( ) ) ; udunits ++ ; } } catch ( Exception e ) { f . format ( "  udunits cant parse=%10s %15s %15s%n" , p1 . getId ( ) , cu1 , cu2 ) ; } } } } } int missing = 0 ; for ( GribTables . Parameter p2 : t2 . getParameters ( ) ) { if ( t2 . getParameter ( p2 . getNumber ( ) ) == null ) { f . format ( " ERROR %s missing own parameter %d%n" , t2 . getShortName ( ) , p2 . getNumber ( ) ) ; } GribTables . Parameter p1 = t1 . getParameter ( p2 . getNumber ( ) ) ; if ( p1 == null ) { missing ++ ; f . format ( "  %s missing %s%n" , t1 . getShortName ( ) , p2 ) ; } } if ( conflict > 0 || udunits > 0 || missing > 0 ) { f . format ( " ***Conflicts=%d extra=%d udunits=%d missing=%s%n" , conflict , extra , udunits , missing ) ; } }


Input: stuff for Iosp [CODESPLIT] RandomAccessFile getRaf ( int partno , int fileno ) throws IOException { Partition part = getPartition ( partno ) ; try ( GribCollectionImmutable gc = part . getGribCollection ( ) ) { return gc . getDataRaf ( fileno ) ; } }


Input: debugging [CODESPLIT] public String getFilename ( int partno , int fileno ) throws IOException { Partition part = getPartition ( partno ) ; try ( GribCollectionImmutable gc = part . getGribCollection ( ) ) { return gc . getFilename ( fileno ) ; } }


Input: Check if this is a valid file for this IOServiceProvider . [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { try { raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . seek ( 0 ) ; raf . skipBytes ( 4 ) ; String test = raf . readString ( 40 ) ; return test . equals ( EMISSIONS ) || test . equals ( AVERAGE ) || test . equals ( AIRQUALITY ) || test . equals ( INSTANT ) ; } catch ( IOException ioe ) { return false ; } }


Input:
Open existing file and populate ncfile with it . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { /*
     * <b>open</b> initializes the file meta data and creates all variables.
     * The meta-data and variable information is gathered from the UAM-IV
     * header.  The header format is detailed in the CAMx User's
     * guide and copied here.
     *
     * Header:
     * name,note,ione,nspec,ibdate,btime,iedate,etime
     * rdum,rdum,iutm,xorg,yorg,delx,dely,nx,ny,nz,idum,idum,rdum,rdum,rdum
     * ione,ione,nx,ny
     * (mspec(l),l=1,nspec)
     *
     * name - Text string (character*4(10) array)
     * note - Text string containing file description (character*4(60) array)
     * ione - Dummy variable = 1
     * nspec - Number of species on file
     * ibdate - Beginning date (YYJJJ)
     * btime - Beginning hour (HHMM)
     * iedate - Ending date (YYJJJ)
     * etime - Ending hour (HHMM)
     * rdum - Dummy real variable
     * iutm - UTM zone (ignored for other projections)
     * xorg - Grid x-origin at southwest corner of domain (m or degrees longitude)
     * yorg - Grid y-origin at southwest corner of domain (m or degrees latitude)
     * delx - Cell size in x-direction (m or degrees longitude)
     * dely - Cell size in y-direction (m or degrees longitude)
     * nx - Number of grid columns
     * ny - Number of grid rows
     * nz - Number of layers
     * idum - Dummy integer variable
     * mspec - Species names for nspec species (character*4(10,nspec) array)
     *
     *
     *   time step is HHMMSS
     *
     *  the projection is:
     *   LCC // >  :GDTYP = 2; // int
     *   First True Latitude (Alpha):  	30N // >  :P_ALP = 30.0; // double
     *   Second True Latitude (Beta): 	60N // >  :P_BET = 60.0; // double
     *   Central Longitude (Gamma): 	100W //>  :XCENT = -100.0; // double
     *   Projection Origin: 	(100W, 40N) //>  :YCENT = 40.0; // double
     *
     */ // Internalize raf and ncfile
 super . open ( raf , ncfile , cancelTask ) ; // set raf to big endian and start at the beginning
 raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . seek ( 0 ) ; // Read first line of UAM-IV header
 raf . skipBytes ( 4 ) ; // Skip record pad
 String name = raf . readString ( 40 ) ; // read 40 name
 String note = raf . readString ( 240 ) ; int itzone = raf . readInt ( ) ; // Read the time zone
 int nspec = raf . readInt ( ) ; // Read number of species
 int bdate = raf . readInt ( ) ; // get file start date
 float btime = raf . readFloat ( ) ; // get file start time
 int edate = raf . readInt ( ) ; // get file end date
 float etime = raf . readFloat ( ) ; // get file end time
 int btimei = ( int ) btime ; // convert btime to an integer
 // CAMx times are sometimes provided as HH or HHMM.
 // IOAPI times are always provided as HHMMSS.
 // CAMx times less than 100 are HH and should be
 // multipled by 100 to get HHMM.  CAMx times less
 // 10000 are HHMM and should be multipled by 100
 // to get HHMMSS.
 if ( btimei < 100 ) btimei = btimei * 100 ; if ( btimei < 10000 ) btimei = btimei * 100 ; /*
    * Dates are YYJJJ and are heuristically converted
    * to YYYYJJJ based on the following assumption:
    * YY < 70 are 2000
    * YY >= 70 are 1900
    *
    */ if ( bdate < 70000 ) { edate = edate + 2000000 ; bdate = bdate + 2000000 ; } else { edate = edate + 1900000 ; bdate = bdate + 1900000 ; } raf . skipBytes ( 4 ) ; //Skip record pad
 // Read second line of UAM-IV header
 raf . skipBytes ( 4 ) ; //Skip record pad
 float plon = raf . readFloat ( ) ; // get polar longitude
 float plat = raf . readFloat ( ) ; // get polar latitude
 int iutm = raf . readInt ( ) ; // get utm
 float xorg = raf . readFloat ( ) ; // get x origin in meters
 float yorg = raf . readFloat ( ) ; // get y origin in meters
 float delx = raf . readFloat ( ) ; // get x cell size in meters
 float dely = raf . readFloat ( ) ; // get y cell size in meters
 int nx = raf . readInt ( ) ; // get number of columns
 int ny = raf . readInt ( ) ; // get number of rows
 int nz = raf . readInt ( ) ; // get number of layers
 // get projection number
 //    (0: lat-lon;
 //     1: Universal Transverse Mercator;
 //     2: Lambert Conic Conformal;
 //     3: Polar stereographic)
 // These translate to IOAPI GDTYP3D values 1, 5, 2, and 6 respectively
 int iproj = raf . readInt ( ) ; int istag = raf . readInt ( ) ; // Read stagger indicator
 float tlat1 = raf . readFloat ( ) ; // Read true latitude 1
 float tlat2 = raf . readFloat ( ) ; // Read true latitude 2
 raf . skipBytes ( 4 ) ; //Skip 1 dummies
 raf . skipBytes ( 4 ) ; //Skip record pad
 // Read third line of UAM-IV header
 raf . skipBytes ( 4 ) ; //Skip record pad
 raf . skipBytes ( 8 ) ; //Skip 2 dummies
 int nx2 = raf . readInt ( ) ; // duplicate number of columns
 int ny2 = raf . readInt ( ) ; // duplicate number of rows
 raf . skipBytes ( 8 ) ; //Skip 2 dummies
 nz = Math . max ( nz , 1 ) ; // number of layers; Emissions files occasionally report 0 layers
 /*
     * 1) Read each species name
     * 2) remove white space from the name
     * 3) store the names
     * 4) internalize them
     */ int count = 0 ; String [ ] spc_names = new String [ nspec ] ; while ( count < nspec ) { String spc = raf . readString ( 40 ) ; // 1) read species name
 spc_names [ count ++ ] = spc . replace ( " " , "" ) ; // 2&3) store name without whitespace
 } this . species_names = spc_names ; // 4) internalize names
 raf . skipBytes ( 4 ) ; // Skip record pad
 // Note this position; it is the start of the data block
 this . data_start = raf . getFilePointer ( ) ; // Note the number of float equivalents (4 byte chunks) in data block
 int data_length_float_equivalents = ( ( int ) raf . length ( ) - ( int ) data_start ) / 4 ; // Store 2D value size
 this . n2dvals = nx * ny ; // Store 3D value size
 this . n3dvals = nx * ny * nz ; // Store 2D binary data block size: include values (nx*ny),
 // species name (10), a dummy (1) and 2 record pads
 int spc_2D_block = nx * ny + 10 + 2 + 1 ; // Store 3D binary data block size
 this . spc_3D_block = spc_2D_block * nz ; // Store whole data block size; includes date (6)
 this . data_block = this . spc_3D_block * nspec + 6 ; // Store the number of times
 int ntimes = data_length_float_equivalents / this . data_block ; // Add dimensions based on header values
 ncfile . addDimension ( null , new Dimension ( "TSTEP" , ntimes , true ) ) ; ncfile . addDimension ( null , new Dimension ( "LAY" , nz , true ) ) ; ncfile . addDimension ( null , new Dimension ( "ROW" , ny , true ) ) ; ncfile . addDimension ( null , new Dimension ( "COL" , nx , true ) ) ; // Force sync of dimensions
 ncfile . finish ( ) ; count = 0 ; /*
    * For each species, create a variable with long_name,
    * and var_desc, and units.  long_name and var_desc are
    * simply the species name.  units is heuristically
    * determined from the name
    */ HashSet < String > AeroSpcs = new HashSet <> ( Arrays . asList ( "PSO4" , "PNO3" , "PNH4" , "PH2O" , "SOPA" , "SOPB" , "NA" , "PCL" , "POA" , "PEC" , "FPRM" , "FCRS" , "CPRM" , "CCRS" ) ) ; HashSet < String > LULC = new HashSet <> ( Arrays . asList ( "WATER" , "ICE" , "LAKE" , "ENEEDL" , "EBROAD" , "DNEEDL" , "DBROAD" , "TBROAD" , "DDECID" , "ESHRUB" , "DSHRUB" , "TSHRUB" , "SGRASS" , "LGRASS" , "CROPS" , "RICE" , "SUGAR" , "MAIZE" , "COTTON" , "ICROPS" , "URBAN" , "TUNDRA" , "SWAMP" , "DESERT" , "MWOOD" , "TFOREST" ) ) ; while ( count < nspec ) { String spc = spc_names [ count ++ ] ; Variable temp = ncfile . addVariable ( null , spc , DataType . FLOAT , "TSTEP LAY ROW COL" ) ; if ( spc . equals ( WINDX ) || spc . equals ( WINDY ) || spc . equals ( SPEED ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "m/s" ) ) ; } else if ( spc . equals ( VERTDIFF ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "m**2/s" ) ) ; } else if ( spc . equals ( TEMP ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "K" ) ) ; } else if ( spc . equals ( PRESS ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "hPa" ) ) ; } else if ( spc . equals ( HEIGHT ) || spc . equals ( PBL ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "m" ) ) ; } else if ( spc . equals ( CLDWATER ) || spc . equals ( PRECIP ) || spc . equals ( RAIN ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "g/m**3" ) ) ; } else if ( spc . equals ( CLDOD ) || spc . equals ( "CLOUDOD" ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "none" ) ) ; } else if ( spc . equals ( "SNOWCOVER" ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "yes/no" ) ) ; } else if ( spc . startsWith ( "SOA" ) || AeroSpcs . contains ( spc ) ) { if ( name . equals ( EMISSIONS ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "g/time" ) ) ; } else { temp . addAttribute ( new Attribute ( CDM . UNITS , "ug/m**3" ) ) ; } } else if ( LULC . contains ( spc ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "fraction" ) ) ; } else if ( spc . lastIndexOf ( "_" ) > - 1 ) { String tmpunit = spc . substring ( spc . lastIndexOf ( "_" ) + 1 ) ; tmpunit = tmpunit . trim ( ) ; switch ( tmpunit ) { case "M2pS" : tmpunit = "m**2/s" ; break ; case "MpS" : tmpunit = "m/s" ; break ; case "PPM" : tmpunit = "ppm" ; break ; case "MB" : tmpunit = "millibar" ; break ; case "GpM3" : tmpunit = "g/m**3" ; break ; case "M" : tmpunit = "m" ; break ; } temp . addAttribute ( new Attribute ( CDM . UNITS , tmpunit ) ) ; } else { if ( name . equals ( EMISSIONS ) ) { temp . addAttribute ( new Attribute ( CDM . UNITS , "mol/time" ) ) ; } else { temp . addAttribute ( new Attribute ( CDM . UNITS , "ppm" ) ) ; } } temp . addAttribute ( new Attribute ( CDM . LONG_NAME , spc ) ) ; temp . addAttribute ( new Attribute ( "var_desc" , spc ) ) ; } /*
    * Create 1...n array of "sigma" values
    */ double [ ] sigma = new double [ nz + 1 ] ; count = 0 ; while ( count < nz + 1 ) { sigma [ count ++ ] = count ; } int [ ] size = new int [ 1 ] ; size [ 0 ] = nz + 1 ; Array sigma_arr = Array . factory ( DataType . DOUBLE , size , sigma ) ; /*
    * Add meta-data according to the IOAPI conventions
    * http://www.baronams.com/products/ioapi
    */ ncfile . addAttribute ( null , new Attribute ( "VGLVLS" , sigma_arr ) ) ; ncfile . addAttribute ( null , new Attribute ( "SDATE" , bdate ) ) ; ncfile . addAttribute ( null , new Attribute ( "STIME" , btimei ) ) ; ncfile . addAttribute ( null , new Attribute ( "TSTEP" , 10000 ) ) ; ncfile . addAttribute ( null , new Attribute ( "NSTEPS" , ntimes ) ) ; ncfile . addAttribute ( null , new Attribute ( "NLAYS" , nz ) ) ; ncfile . addAttribute ( null , new Attribute ( "NROWS" , ny ) ) ; ncfile . addAttribute ( null , new Attribute ( "NCOLS" , nx ) ) ; ncfile . addAttribute ( null , new Attribute ( "XORIG" , ( double ) xorg ) ) ; ncfile . addAttribute ( null , new Attribute ( "YORIG" , ( double ) yorg ) ) ; ncfile . addAttribute ( null , new Attribute ( "XCELL" , ( double ) delx ) ) ; ncfile . addAttribute ( null , new Attribute ( "YCELL" , ( double ) dely ) ) ; /*
     * IOAPI Projection parameters are provided by a colocated camxproj.txt file;
     *
     * to do:
     * 1) needs earth radius
     * 2) needs better error checking
    */ Integer gdtyp = 2 ; Double p_alp = 20. ; Double p_bet = 60. ; Double p_gam = 0. ; Double xcent = - 95. ; Double ycent = 25. ; if ( ! ( ( iproj == 0 ) && ( tlat1 == 0 ) && ( tlat2 == 0 ) && ( plon == 0 ) && ( plat == 0 ) ) ) { xcent = ( double ) plon ; ycent = ( double ) plat ; if ( iproj == 0 ) { // Lat-Lon (iproj=0) has no additional information
 gdtyp = 1 ; } else if ( iproj == 1 ) { // UTM uses only iutm
 gdtyp = 5 ; p_alp = ( double ) iutm ; } else if ( iproj == 2 ) { gdtyp = 2 ; p_alp = ( double ) tlat1 ; p_bet = ( double ) tlat2 ; p_gam = ( double ) plon ; } else if ( iproj == 3 ) { gdtyp = 6 ; if ( plat == 90 ) { p_alp = 1. ; } else if ( plat == - 90 ) { p_alp = - 1. ; } p_bet = ( double ) tlat1 ; p_gam = ( double ) plon ; } else { gdtyp = 2 ; p_alp = 20. ; p_bet = 60. ; p_gam = 0. ; xcent = - 95. ; ycent = 25. ; } } String thisLine ; String projpath = raf . getLocation ( ) ; Boolean lgdtyp = false ; Boolean lp_alp = false ; Boolean lp_bet = false ; Boolean lp_gam = false ; Boolean lxcent = false ; Boolean lycent = false ; int lastIndex = projpath . lastIndexOf ( File . separator ) ; if ( lastIndex <= 0 ) lastIndex = projpath . lastIndexOf ( ' ' ) ; if ( lastIndex > 0 ) projpath = projpath . substring ( 0 , lastIndex ) ; projpath = projpath + File . separator + "camxproj.txt" ; File paramFile = new File ( projpath ) ; if ( paramFile . exists ( ) ) { try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( new FileInputStream ( paramFile ) , CDM . UTF8 ) ) ) { while ( ( thisLine = br . readLine ( ) ) != null ) { if ( thisLine . length ( ) == 0 ) continue ; if ( thisLine . charAt ( 0 ) == ' ' ) continue ; String [ ] key_value = thisLine . split ( "=" ) ; switch ( key_value [ 0 ] ) { case "GDTYP" : gdtyp = Integer . parseInt ( key_value [ 1 ] ) ; lgdtyp = true ; break ; case "P_ALP" : p_alp = Double . parseDouble ( key_value [ 1 ] ) ; lp_alp = true ; break ; case "P_BET" : p_bet = Double . parseDouble ( key_value [ 1 ] ) ; lp_bet = true ; break ; case "P_GAM" : p_gam = Double . parseDouble ( key_value [ 1 ] ) ; lp_gam = true ; break ; case "YCENT" : ycent = Double . parseDouble ( key_value [ 1 ] ) ; lycent = true ; break ; case "XCENT" : xcent = Double . parseDouble ( key_value [ 1 ] ) ; lxcent = true ; break ; } } } if ( ! lgdtyp ) log . warn ( "GDTYP not found; using " + gdtyp . toString ( ) ) ; if ( ! lp_alp ) log . warn ( "P_ALP not found; using " + p_alp . toString ( ) ) ; if ( ! lp_bet ) log . warn ( "P_BET not found; using " + p_bet . toString ( ) ) ; if ( ! lp_gam ) log . warn ( "P_GAM not found; using " + p_gam . toString ( ) ) ; if ( ! lxcent ) log . warn ( "XCENT not found; using " + xcent . toString ( ) ) ; if ( ! lycent ) log . warn ( "YCENT not found; using " + ycent . toString ( ) ) ; } else { if ( log . isDebugEnabled ( ) ) log . debug ( "UAMIVServiceProvider: adding projection file" ) ; try ( FileOutputStream out = new FileOutputStream ( paramFile ) ) { OutputStreamWriter fout = new OutputStreamWriter ( out , CDM . utf8Charset ) ; BufferedWriter bw = new BufferedWriter ( fout ) ; bw . write ( "# Projection parameters are based on IOAPI.  For details, see www.baronams.com/products/ioapi/GRIDS.html" ) ; bw . newLine ( ) ; bw . write ( "GDTYP=" ) ; bw . write ( gdtyp . toString ( ) ) ; bw . newLine ( ) ; bw . write ( "P_ALP=" ) ; bw . write ( p_alp . toString ( ) ) ; bw . newLine ( ) ; bw . write ( "P_BET=" ) ; bw . write ( p_bet . toString ( ) ) ; bw . newLine ( ) ; bw . write ( "P_GAM=" ) ; bw . write ( p_gam . toString ( ) ) ; bw . newLine ( ) ; bw . write ( "XCENT=" ) ; bw . write ( xcent . toString ( ) ) ; bw . newLine ( ) ; bw . write ( "YCENT=" ) ; bw . write ( ycent . toString ( ) ) ; bw . newLine ( ) ; bw . flush ( ) ; bw . close ( ) ; } } ncfile . addAttribute ( null , new Attribute ( "GDTYP" , gdtyp ) ) ; ncfile . addAttribute ( null , new Attribute ( "P_ALP" , p_alp ) ) ; ncfile . addAttribute ( null , new Attribute ( "P_BET" , p_bet ) ) ; ncfile . addAttribute ( null , new Attribute ( "P_GAM" , p_gam ) ) ; ncfile . addAttribute ( null , new Attribute ( "XCENT" , xcent ) ) ; ncfile . addAttribute ( null , new Attribute ( "YCENT" , ycent ) ) ; }


Input:
Read data from a top level Variable and return a memory resident Array . This Array has the same element type as the Variable and the requested shape . [CODESPLIT] public ucar . ma2 . Array readData ( Variable v2 , Section wantSection ) throws IOException , InvalidRangeException { /*
     * <b>readData</b> seeks and reads the data for each variable.  The variable
     * data format is detailed in the CAMx User's guide and summarized here.
     *
     * For each time:
     *   ibdate,btime,iedate,etime
     *   Loop from 1 to nspec species:
     *     ione,mspec(l),((val(i,j,l),i=1,nx),j=1,ny)
     *
     *
     * ione - Dummy variable = 1
     * nspec - Number of species on file
     * ibdate - Beginning date (YYJJJ)
     * btime - Beginning hour (HHMM)
     * iedate - Ending date (YYJJJ)
     * etime - Ending hour (HHMM)
     * mspec - Species names for nspec species (character*4(10,nspec) array)
     * val - Species l, layer k initial concentrations (ppm for gases, ug/m3 for aerosols)
     *       for nx grid columns and ny grid rows
     *
     */ // CAMx UAM-IV Files are all big endian
 raf . order ( RandomAccessFile . BIG_ENDIAN ) ; // Prepare an array for binary data
 int size = ( int ) v2 . getSize ( ) ; float [ ] arr = new float [ size ] ; // Move to data block of file
 raf . seek ( this . data_start ) ; /*
     * First record is stime,sdate,etime,edate
     * We are skipping the data, but checking
     * the consistency of the Fortran "unformatted"
     * data record
    */ int pad1 = raf . readInt ( ) ; raf . skipBytes ( 16 ) ; int pad2 = raf . readInt ( ) ; if ( pad1 != pad2 ) { throw new IOException ( "Asymmetric fortran buffer values: 1" ) ; } // Find species name/id associated with this variable
 int spcid = - 1 ; String spc = "" ; while ( ! spc . equals ( v2 . getShortName ( ) ) ) { spc = this . species_names [ ++ spcid ] ; } /*
    * Skip data associated with species that are prior
    * in the data block
    */ raf . skipBytes ( this . spc_3D_block * spcid * 4 ) ; // Initialize count for indexing arr
 int count = 0 ; while ( count < size ) { /*
      * Read species name and store the initial record pad.
      * Note: it might be good to compare
      *       spc string to variable.getShortName
      */ if ( count == 0 ) { pad1 = raf . readInt ( ) ; int ione = raf . readInt ( ) ; spc = raf . readString ( 40 ) ; } /*
      * If we have read a 2D slice, read the final record pad
      * and compare to initial record pad.  If everything is okay, proceed.
      * (1) skip to next 2D slice
      * (2) store initial pad
      * (3) read spc name
      * Note: it might be good to compare
      *       spc string to variable.getShortName
      */ if ( ( count != 0 ) && ( ( count % this . n2dvals ) == 0 ) ) { pad2 = raf . readInt ( ) ; if ( pad1 != pad2 ) { //System.out.println(pad1);
 //System.out.println(pad2);
 throw new IOException ( "Asymmetric fortran buffer values: 2" ) ; } if ( ( count % this . n3dvals ) == 0 ) { raf . skipBytes ( ( this . data_block - this . spc_3D_block ) * 4 ) ; } pad1 = raf . readInt ( ) ; int ione = raf . readInt ( ) ; spc = raf . readString ( 40 ) ; } /*
      * Attempt to read a Float from the file
      */ try { arr [ count ++ ] = raf . readFloat ( ) ; } catch ( java . lang . ArrayIndexOutOfBoundsException io ) { throw new IOException ( io . getMessage ( ) ) ; } } // Convert java float[] to ma2.Array
 Array data = Array . factory ( DataType . FLOAT , v2 . getShape ( ) , arr ) ; // Subset the data based on the wantSection and return a 4D variable
 return data . sectionNoReduce ( wantSection . getRanges ( ) ) ; }


Input:
Find first variable with given attribute name [CODESPLIT] static public VarAtt findVariableWithAttribute ( NetcdfDataset ds , String attName ) { for ( Variable v : ds . getVariables ( ) ) { Attribute att = v . findAttributeIgnoreCase ( attName ) ; if ( att != null ) return new VarAtt ( v , att ) ; } // descend into structures
 for ( Variable v : ds . getVariables ( ) ) { if ( v instanceof Structure ) { Structure s = ( Structure ) v ; for ( Variable vs : s . getVariables ( ) ) { Attribute att = vs . findAttributeIgnoreCase ( attName ) ; if ( att != null ) return new VarAtt ( vs , att ) ; } } } return null ; }


Input:
Find first variable with given attribute name and value . If not found search one level into structures . [CODESPLIT] static public Variable findVariableWithAttributeValue ( NetcdfDataset ds , String attName , String attValue ) { for ( Variable v : ds . getVariables ( ) ) { String haveValue = ds . findAttValueIgnoreCase ( v , attName , null ) ; if ( ( haveValue != null ) && haveValue . equals ( attValue ) ) return v ; } // descend into structures
 for ( Variable v : ds . getVariables ( ) ) { if ( v instanceof Structure ) { Variable vn = findVariableWithAttributeValue ( ( Structure ) v , attName , attValue ) ; if ( null != vn ) return vn ; } } return null ; }


Input: Find first variable with given attribute name and value [CODESPLIT] static public String findNameOfVariableWithAttributeValue ( NetcdfDataset ds , String attName , String attValue ) { Variable v = findVariableWithAttributeValue ( ds , attName , attValue ) ; return ( v == null ) ? null : v . getShortName ( ) ; }


Input: Find first member variable in this struct with given attribute name and value [CODESPLIT] static public Variable findVariableWithAttributeValue ( Structure struct , String attName , String attValue ) { for ( Variable v : struct . getVariables ( ) ) { Attribute att = v . findAttributeIgnoreCase ( attName ) ; if ( ( att != null ) && att . getStringValue ( ) . equals ( attValue ) ) return v ; } return null ; }


Input: Find structure variable of rank 2 with the 2 given dimensions ( or ) Find structure variable of rank 1 with the 1 given dimension [CODESPLIT] static public Structure findStructureWithDimensions ( NetcdfDataset ds , Dimension dim0 , Dimension dim1 ) { for ( Variable v : ds . getVariables ( ) ) { if ( ! ( v instanceof Structure ) ) continue ; if ( dim1 != null && v . getRank ( ) == 2 && v . getDimension ( 0 ) . equals ( dim0 ) && v . getDimension ( 1 ) . equals ( dim1 ) ) return ( Structure ) v ; if ( dim1 == null && v . getRank ( ) == 1 && v . getDimension ( 0 ) . equals ( dim0 ) ) return ( Structure ) v ; } return null ; }


Input: Find first nested structure [CODESPLIT] static public Structure findNestedStructure ( Structure s ) { for ( Variable v : s . getVariables ( ) ) { if ( ( v instanceof Structure ) ) return ( Structure ) v ; } return null ; }


Input: Does this dataset have a record structure? netcdf - 3 specific [CODESPLIT] static public boolean hasNetcdf3RecordStructure ( NetcdfDataset ds ) { Variable v = ds . findVariable ( "record" ) ; return ( v != null ) && ( v . getDataType ( ) == DataType . STRUCTURE ) ; }


Input: Translate key to value [CODESPLIT] static public String getLiteral ( NetcdfDataset ds , String key , Formatter errlog ) { if ( key . startsWith ( ":" ) ) { String val = ds . findAttValueIgnoreCase ( null , key . substring ( 1 ) , null ) ; if ( ( val == null ) && ( errlog != null ) ) errlog . format ( " Cant find global attribute %s%n" , key ) ; return val ; } return key ; }


Input: Turn the key into a String and return the corresponding featureType if any . [CODESPLIT] static public FeatureType getFeatureType ( NetcdfDataset ds , String key , Formatter errlog ) { FeatureType ft = null ; String fts = getLiteral ( ds , key , errlog ) ; if ( fts != null ) { ft = FeatureType . valueOf ( fts . toUpperCase ( ) ) ; if ( ( ft == null ) && ( errlog != null ) ) errlog . format ( " Cant find Feature type %s from %s%n" , fts , key ) ; } return ft ; }


Input: Find the variable pointed to by key [CODESPLIT] static public String getVariableName ( NetcdfDataset ds , String key , Formatter errlog ) { Variable v = null ; String vs = getLiteral ( ds , key , errlog ) ; if ( vs != null ) { v = ds . findVariable ( vs ) ; if ( ( v == null ) && ( errlog != null ) ) errlog . format ( " Cant find Variable %s from %s%n" , vs , key ) ; } return v == null ? null : v . getShortName ( ) ; }


Input:
Find the dimension pointed to by key [CODESPLIT] static public Dimension getDimension ( NetcdfDataset ds , String key , Formatter errlog ) { Dimension d = null ; String s = getLiteral ( ds , key , errlog ) ; if ( s != null ) { d = ds . findDimension ( s ) ; // LOOK use group
 if ( ( d == null ) && ( errlog != null ) ) errlog . format ( " Cant find Variable %s from %s%n" , s , key ) ; } return d ; }


Input: Find the dimension pointed to by key [CODESPLIT] static public String getDimensionName ( NetcdfDataset ds , String key , Formatter errlog ) { Dimension d = getDimension ( ds , key , errlog ) ; return ( d == null ) ? null : d . getShortName ( ) ; }


Input: Get the coordinate value at the i j index . [CODESPLIT] public double getCoordValue ( int j , int i ) { if ( coords == null ) doRead ( ) ; return coords . get ( j , i ) ; }


Input:
larger than you would ever expect [CODESPLIT] static private double connectLon ( double connect , double val ) { if ( Double . isNaN ( connect ) ) return val ; if ( Double . isNaN ( val ) ) return val ; double diff = val - connect ; if ( Math . abs ( diff ) < MAX_JUMP ) return val ; // common case fast
 // we have to add or subtract 360
 double result = diff > 0 ? val - 360 : val + 360 ; double diff2 = connect - result ; if ( ( Math . abs ( diff2 ) ) < Math . abs ( diff ) ) val = result ; return val ; }


Input: Get the coordinate values as a 1D double array in canonical order . [CODESPLIT] public double [ ] getCoordValues ( ) { if ( coords == null ) doRead ( ) ; if ( ! isNumeric ( ) ) throw new UnsupportedOperationException ( "CoordinateAxis2D.getCoordValues() on non-numeric" ) ; return ( double [ ] ) coords . get1DJavaArray ( DataType . DOUBLE ) ; }


Input: Create a new CoordinateAxis2D as a section of this CoordinateAxis2D . [CODESPLIT] public CoordinateAxis2D section ( Range r1 , Range r2 ) throws InvalidRangeException { List < Range > section = new ArrayList <> ( ) ; section . add ( r1 ) ; section . add ( r2 ) ; return ( CoordinateAxis2D ) section ( section ) ; }


Input:
Normal case : do something reasonable in deciding on the edges when we have the midpoints of a 2D coordinate . [CODESPLIT] static public ArrayDouble . D2 makeEdges ( ArrayDouble . D2 midpoints ) { int [ ] shape = midpoints . getShape ( ) ; int ny = shape [ 0 ] ; int nx = shape [ 1 ] ; ArrayDouble . D2 edge = new ArrayDouble . D2 ( ny + 1 , nx + 1 ) ; for ( int y = 0 ; y < ny - 1 ; y ++ ) { for ( int x = 0 ; x < nx - 1 ; x ++ ) { // the interior edges are the average of the 4 surrounding midpoints
 double xval = ( midpoints . get ( y , x ) + midpoints . get ( y , x + 1 ) + midpoints . get ( y + 1 , x ) + midpoints . get ( y + 1 , x + 1 ) ) / 4 ; edge . set ( y + 1 , x + 1 , xval ) ; } // extrapolate to exterior points
 edge . set ( y + 1 , 0 , edge . get ( y + 1 , 1 ) - ( edge . get ( y + 1 , 2 ) - edge . get ( y + 1 , 1 ) ) ) ; edge . set ( y + 1 , nx , edge . get ( y + 1 , nx - 1 ) + ( edge . get ( y + 1 , nx - 1 ) - edge . get ( y + 1 , nx - 2 ) ) ) ; } // extrapolate to the first and last row
 for ( int x = 0 ; x < nx + 1 ; x ++ ) { edge . set ( 0 , x , edge . get ( 1 , x ) - ( edge . get ( 2 , x ) - edge . get ( 1 , x ) ) ) ; edge . set ( ny , x , edge . get ( ny - 1 , x ) + ( edge . get ( ny - 1 , x ) - edge . get ( ny - 2 , x ) ) ) ; } return edge ; }


Input:
Experimental : for WRF rotated ( NMM E ) Grids [CODESPLIT] static public ArrayDouble . D2 makeXEdgesRotated ( ArrayDouble . D2 midx ) { int [ ] shape = midx . getShape ( ) ; int ny = shape [ 0 ] ; int nx = shape [ 1 ] ; ArrayDouble . D2 edgex = new ArrayDouble . D2 ( ny + 2 , nx + 1 ) ; // compute the interior rows
 for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 1 ; x < nx ; x ++ ) { double xval = ( midx . get ( y , x - 1 ) + midx . get ( y , x ) ) / 2 ; edgex . set ( y + 1 , x , xval ) ; } edgex . set ( y + 1 , 0 , midx . get ( y , 0 ) - ( edgex . get ( y + 1 , 1 ) - midx . get ( y , 0 ) ) ) ; edgex . set ( y + 1 , nx , midx . get ( y , nx - 1 ) - ( edgex . get ( y + 1 , nx - 1 ) - midx . get ( y , nx - 1 ) ) ) ; } // compute the first row
 for ( int x = 0 ; x < nx ; x ++ ) { edgex . set ( 0 , x , midx . get ( 0 , x ) ) ; } // compute the last row
 for ( int x = 0 ; x < nx - 1 ; x ++ ) { edgex . set ( ny + 1 , x , midx . get ( ny - 1 , x ) ) ; } return edgex ; }


Input:
Experimental : for WRF rotated ( NMM E ) Grids [CODESPLIT] static public ArrayDouble . D2 makeYEdgesRotated ( ArrayDouble . D2 midy ) { int [ ] shape = midy . getShape ( ) ; int ny = shape [ 0 ] ; int nx = shape [ 1 ] ; ArrayDouble . D2 edgey = new ArrayDouble . D2 ( ny + 2 , nx + 1 ) ; // compute the interior rows
 for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 1 ; x < nx ; x ++ ) { double yval = ( midy . get ( y , x - 1 ) + midy . get ( y , x ) ) / 2 ; edgey . set ( y + 1 , x , yval ) ; } edgey . set ( y + 1 , 0 , midy . get ( y , 0 ) - ( edgey . get ( y + 1 , 1 ) - midy . get ( y , 0 ) ) ) ; edgey . set ( y + 1 , nx , midy . get ( y , nx - 1 ) - ( edgey . get ( y + 1 , nx - 1 ) - midy . get ( y , nx - 1 ) ) ) ; } // compute the first row
 for ( int x = 0 ; x < nx ; x ++ ) { double pt0 = midy . get ( 0 , x ) ; double pt = edgey . get ( 2 , x ) ; double diff = pt0 - pt ; edgey . set ( 0 , x , pt0 + diff ) ; } // compute the last row
 for ( int x = 0 ; x < nx - 1 ; x ++ ) { double pt0 = midy . get ( ny - 1 , x ) ; double pt = edgey . get ( ny - 1 , x ) ; double diff = pt0 - pt ; edgey . set ( ny + 1 , x , pt0 + diff ) ; } return edgey ; }


Input:
bounds calculations [CODESPLIT] private ArrayDouble . D3 makeBoundsFromAux ( ) { if ( ! computeIsInterval ( ) ) return null ; Attribute boundsAtt = findAttributeIgnoreCase ( CF . BOUNDS ) ; if ( boundsAtt == null ) return null ; String boundsVarName = boundsAtt . getStringValue ( ) ; VariableDS boundsVar = ( VariableDS ) ncd . findVariable ( getParentGroup ( ) , boundsVarName ) ; Array data ; try { //boundsVar.setUseNaNs(false); // missing values not allowed
 data = boundsVar . read ( ) ; } catch ( IOException e ) { log . warn ( "CoordinateAxis2D.makeBoundsFromAux read failed " , e ) ; return null ; } ArrayDouble . D3 bounds ; assert ( data . getRank ( ) == 3 ) && ( data . getShape ( ) [ 2 ] == 2 ) : "incorrect shape data for variable " + boundsVar ; if ( data instanceof ArrayDouble . D3 ) { bounds = ( ArrayDouble . D3 ) data ; } else { bounds = ( ArrayDouble . D3 ) Array . factory ( DataType . DOUBLE , data . getShape ( ) ) ; MAMath . copy ( data , bounds ) ; } return bounds ; }


Input: return index if only one match if no matches return - 1 if > 1 match return - nhits [CODESPLIT] private int findSingleHit ( ArrayDouble . D2 boundsForRun , double target ) { int hits = 0 ; int idxFound = - 1 ; int n = boundsForRun . getShape ( ) [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { if ( contains ( target , boundsForRun . get ( i , 0 ) , boundsForRun . get ( i , 1 ) ) ) { hits ++ ; idxFound = i ; } } if ( hits == 1 ) return idxFound ; if ( hits == 0 ) return - 1 ; return - hits ; }


Input: return index of closest value to target [CODESPLIT] private int findClosest ( ArrayDouble . D2 boundsForRun , double target ) { double minDiff = Double . MAX_VALUE ; int idxFound = - 1 ; int n = boundsForRun . getShape ( ) [ 0 ] ; for ( int i = 0 ; i < n ; i ++ ) { double midpoint = ( boundsForRun . get ( i , 0 ) + boundsForRun . get ( i , 1 ) ) / 2.0 ; double diff = Math . abs ( midpoint - target ) ; if ( diff < minDiff ) { minDiff = diff ; idxFound = i ; } } return idxFound ; }


Input: / * private static void doit2 ( String spec String timePart Formatter errlog ) { CollectionSpecParser specp = new CollectionSpecParser ( spec timePart errlog ) ; System . out . printf ( spec = %s timePart = %s%n%s%n spec timePart specp ) ; String err = errlog . toString () ; if ( err . length () > 0 ) System . out . printf ( %s%n err ) ; System . out . printf ( ----------------------------------- %n ) ; } [CODESPLIT] private static void doit ( String spec , Formatter errlog ) { CollectionSpecParser specp = new CollectionSpecParser ( spec , errlog ) ; System . out . printf ( "spec= %s%n%s%n" , spec , specp ) ; String err = errlog . toString ( ) ; if ( err . length ( ) > 0 ) System . out . printf ( "%s%n" , err ) ; System . out . printf ( "-----------------------------------%n" ) ; }


Input: Sets the system of units . This must be called before any call to <code > instance () < / code > . [CODESPLIT] public static synchronized void setInstance ( final UnitSystem instance ) throws UnitSystemException { if ( instance != null ) { throw new UnitSystemException ( "Unit system already used" ) ; } UnitSystemManager . instance = instance ; }


Input: getName is deprecated because as the code below shows it has no consistent meaning . Sometimes it returns the short name sometimes it returns the full name . [CODESPLIT] @ Deprecated public String getName ( ) { switch ( sort ) { case ATTRIBUTE : case DIMENSION : case ENUMERATION : // for these cases, getName is getShortName return getShortName ( ) ; case VARIABLE : // Atomic case SEQUENCE : case STRUCTURE : case GROUP : // for these cases, getName is getFullName return getFullName ( ) ; default : break ; } return getShortName ( ) ; // default }


Input: NetcdfDataset can end up wrapping a variable in multiple wrapping classes ( e . g . VariableDS ) . Goal of this procedure is to get down to the lowest level Variable instance [CODESPLIT] static public CDMNode unwrap ( CDMNode node ) { if ( ! ( node instanceof Variable ) ) return node ; Variable inner = ( Variable ) node ; for ( ; ; ) { if ( inner instanceof VariableDS ) { VariableDS vds = ( VariableDS ) inner ; inner = vds . getOriginalVariable ( ) ; if ( inner == null ) { inner = vds ; break ; } } else if ( inner instanceof StructureDS ) { StructureDS sds = ( StructureDS ) inner ; inner = sds . getOriginalVariable ( ) ; if ( inner == null ) { inner = sds ; break ; } } else break ; // base case we have straight Variable or Stucture } return inner ; }


Input: Add an action to the popup menu . Note that the menuName is made the NAME value of the action . [CODESPLIT] public void addAction ( String menuName , Action act ) { act . putValue ( Action . NAME , menuName ) ; super . add ( act ) ; }


Input: Add an action to the popup menu with an icon . Note that the menuName is made the NAME value of the action . [CODESPLIT] public void addAction ( String menuName , String iconName , Action act ) { addAction ( menuName , BAMutil . getIcon ( iconName , true ) , act ) ; }


Input: Add an action to the popup menu with an icon . Note that the menuName is made the NAME value of the action . [CODESPLIT] public void addAction ( String menuName , ImageIcon icon , Action act ) { act . putValue ( Action . NAME , menuName ) ; act . putValue ( Action . SMALL_ICON , icon ) ; JMenuItem mi = add ( act ) ; mi . setHorizontalTextPosition ( SwingConstants . LEFT ) ; }


Input: Add an action to the popup menu using a JCheckBoxMenuItem . Fetch the toggle state using : <pre > Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; < / pre > [CODESPLIT] public void addActionCheckBox ( String menuName , AbstractAction act , boolean state ) { JMenuItem mi = new JCheckBoxMenuItem ( menuName , state ) ; mi . addActionListener ( new BAMutil . ActionToggle ( act , mi ) ) ; act . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; add ( mi ) ; }


Input:
Find the longest match . [CODESPLIT] public Match match ( String path ) { SortedMap < String , Match > tail = treeMap . tailMap ( path ) ; if ( tail . isEmpty ( ) ) return null ; String after = tail . firstKey ( ) ; //System.out.println("  "+path+"; after="+afterPath);
 if ( path . startsWith ( after ) ) // common case
 return treeMap . get ( after ) ; // have to check more, until no common starting chars
 for ( String key : tail . keySet ( ) ) { if ( path . startsWith ( key ) ) return treeMap . get ( key ) ; // terminate when there's no match at all.
 if ( StringUtil2 . match ( path , key ) == 0 ) break ; } return null ; }


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


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


Input: reading [CODESPLIT] public void open ( RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; headerParser = new H5header ( this . raf , ncfile , this ) ; headerParser . read ( null ) ; // check if its an HDF5-EOS file Group eosInfo = ncfile . getRootGroup ( ) . findGroup ( HdfEos . HDF5_GROUP ) ; if ( eosInfo != null && useHdfEos ) { isEos = HdfEos . amendFromODL ( ncfile , eosInfo ) ; } ncfile . finish ( ) ; }


Input: all the work is here so can be called recursively [CODESPLIT] private Array readData ( ucar . nc2 . Variable v2 , long dataPos , Section wantSection ) throws IOException , InvalidRangeException { H5header . Vinfo vinfo = ( H5header . Vinfo ) v2 . getSPobject ( ) ; DataType dataType = v2 . getDataType ( ) ; Object data ; Layout layout ; if ( vinfo . useFillValue ) { // fill value only Object pa = IospHelper . makePrimitiveArray ( ( int ) wantSection . computeSize ( ) , dataType , vinfo . getFillValue ( ) ) ; if ( dataType == DataType . CHAR ) pa = IospHelper . convertByteToChar ( ( byte [ ] ) pa ) ; return Array . factory ( dataType , wantSection . getShape ( ) , pa ) ; } if ( vinfo . mfp != null ) { // filtered if ( debugFilter ) System . out . println ( "read variable filtered " + v2 . getFullName ( ) + " vinfo = " + vinfo ) ; assert vinfo . isChunked ; ByteOrder bo = ( vinfo . typeInfo . endian == 0 ) ? ByteOrder . BIG_ENDIAN : ByteOrder . LITTLE_ENDIAN ; layout = new H5tiledLayoutBB ( v2 , wantSection , raf , vinfo . mfp . getFilters ( ) , bo ) ; if ( vinfo . typeInfo . isVString ) { data = readFilteredStringData ( ( LayoutBB ) layout ) ; } else { data = IospHelper . readDataFill ( ( LayoutBB ) layout , v2 . getDataType ( ) , vinfo . getFillValue ( ) ) ; } } else { // normal case if ( debug ) System . out . println ( "read variable " + v2 . getFullName ( ) + " vinfo = " + vinfo ) ; DataType readDtype = v2 . getDataType ( ) ; int elemSize = v2 . getElementSize ( ) ; Object fillValue = vinfo . getFillValue ( ) ; int endian = vinfo . typeInfo . endian ; // fill in the wantSection wantSection = Section . fill ( wantSection , v2 . getShape ( ) ) ; if ( vinfo . typeInfo . hdfType == 2 ) { // time readDtype = vinfo . mdt . timeType ; elemSize = readDtype . getSize ( ) ; fillValue = N3iosp . getFillValueDefault ( readDtype ) ; } else if ( vinfo . typeInfo . hdfType == 8 ) { // enum H5header . TypeInfo baseInfo = vinfo . typeInfo . base ; readDtype = baseInfo . dataType ; elemSize = readDtype . getSize ( ) ; fillValue = N3iosp . getFillValueDefault ( readDtype ) ; endian = baseInfo . endian ; } else if ( vinfo . typeInfo . hdfType == 9 ) { // vlen elemSize = vinfo . typeInfo . byteSize ; endian = vinfo . typeInfo . endian ; //wantSection = wantSection.removeVlen(); // remove vlen dimension } if ( vinfo . isChunked ) { layout = new H5tiledLayout ( ( H5header . Vinfo ) v2 . getSPobject ( ) , readDtype , wantSection ) ; } else { layout = new LayoutRegular ( dataPos , elemSize , v2 . getShape ( ) , wantSection ) ; } data = readData ( vinfo , v2 , layout , readDtype , wantSection . getShape ( ) , fillValue , endian ) ; } if ( data instanceof Array ) return ( Array ) data ; else if ( dataType == DataType . STRUCTURE ) return convertStructure ( ( Structure ) v2 , layout , wantSection . getShape ( ) , ( byte [ ] ) data ) ; // LOOK else return Array . factory ( dataType , wantSection . getShape ( ) , data ) ; }


Input:
/ * Read data subset from file for a variable return Array or java primitive array . [CODESPLIT] private Object readData ( H5header . Vinfo vinfo , Variable v , Layout layout , DataType dataType , int [ ] shape , Object fillValue , int endian ) throws java . io . IOException , InvalidRangeException { H5header . TypeInfo typeInfo = vinfo . typeInfo ; // special processing if ( typeInfo . hdfType == 2 ) { // time Object data = IospHelper . readDataFill ( raf , layout , dataType , fillValue , endian , true ) ; Array timeArray = Array . factory ( dataType , shape , data ) ; // now transform into an ISO Date String String [ ] stringData = new String [ ( int ) timeArray . getSize ( ) ] ; int count = 0 ; while ( timeArray . hasNext ( ) ) { long time = timeArray . nextLong ( ) ; stringData [ count ++ ] = CalendarDate . of ( time ) . toString ( ) ; } return Array . factory ( DataType . STRING , shape , stringData ) ; } if ( typeInfo . hdfType == 8 ) { // enum Object data = IospHelper . readDataFill ( raf , layout , dataType , fillValue , endian ) ; return Array . factory ( dataType , shape , data ) ; } if ( typeInfo . isVlen ) { // vlen (not string) DataType readType = dataType ; if ( typeInfo . base . hdfType == 7 ) // reference readType = DataType . LONG ; // general case is to read an array of vlen objects // each vlen generates an Array - so return ArrayObject of Array // boolean scalar = false; // layout.getTotalNelems() == 1; // if scalar, return just the len Array // remove 12/25/10 jcaron Array [ ] data = new Array [ ( int ) layout . getTotalNelems ( ) ] ; int count = 0 ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) { long address = chunk . getSrcPos ( ) + layout . getElemSize ( ) * i ; Array vlenArray = headerParser . getHeapDataArray ( address , readType , endian ) ; data [ count ++ ] = ( typeInfo . base . hdfType == 7 ) ? convertReference ( vlenArray ) : vlenArray ; } } int prefixrank = 0 ; for ( int i = 0 ; i < shape . length ; i ++ ) { // find leftmost vlen if ( shape [ i ] < 0 ) { prefixrank = i ; break ; } } Array result ; if ( prefixrank == 0 ) // if scalar, return just the singleton vlen array result = data [ 0 ] ; else { int [ ] newshape = new int [ prefixrank ] ; System . arraycopy ( shape , 0 , newshape , 0 , prefixrank ) ; // result = Array.makeObjectArray(readType, data[0].getClass(), newshape, data); result = Array . makeVlenArray ( newshape , data ) ; } /*
      else if (prefixrank == 1) // LOOK cant these two cases be combines - just differ in shape ??
        result = Array.makeObjectArray(readType, data[0].getClass(), new int[]{count}, data);
     else {  // LOOK cant these two cases be combines - just differ in shape ??
          // Otherwise create and fill in an n-dimensional Array Of Arrays
          int[] newshape = new int[prefixrank];
          System.arraycopy(shape, 0, newshape, 0, prefixrank);
          Array ndimarray = Array.makeObjectArray(readType, Array.class, newshape, null);
          // Transfer the elements of data into the n-dim arrays
          IndexIterator iter = ndimarray.getIndexIterator();
          for(int i = 0;iter.hasNext();i++) {
              iter.setObjectNext(data[i]);
          }
          result = ndimarray;
      } */ //return (scalar) ? data[0] : new ArrayObject(data[0].getClass(), shape, data); //return new ArrayObject(data[0].getClass(), shape, data); return result ; } if ( dataType == DataType . STRUCTURE ) { // LOOK what about subset ? int recsize = layout . getElemSize ( ) ; long size = recsize * layout . getTotalNelems ( ) ; byte [ ] byteArray = new byte [ ( int ) size ] ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; if ( debugStructure ) System . out . println ( " readStructure " + v . getFullName ( ) + " chunk= " + chunk + " index.getElemSize= " + layout . getElemSize ( ) ) ; // copy bytes directly into the underlying byte[] LOOK : assumes contiguous layout ?? raf . seek ( chunk . getSrcPos ( ) ) ; raf . readFully ( byteArray , ( int ) chunk . getDestElem ( ) * recsize , chunk . getNelems ( ) * recsize ) ; } // place data into an ArrayStructureBB return convertStructure ( ( Structure ) v , layout , shape , byteArray ) ; // LOOK } // normal case return readDataPrimitive ( layout , dataType , shape , fillValue , endian , true ) ; }


Input: recursive [CODESPLIT] private boolean convertStructure ( Structure s , StructureMembers sm ) { boolean hasHeap = false ; for ( StructureMembers . Member m : sm . getMembers ( ) ) { Variable v2 = s . findVariable ( m . getName ( ) ) ; assert v2 != null ; H5header . Vinfo vm = ( H5header . Vinfo ) v2 . getSPobject ( ) ; // apparently each member may have seperate byte order (!!!??) if ( vm . typeInfo . endian >= 0 ) m . setDataObject ( vm . typeInfo . endian == RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; // vm.dataPos : offset since start of Structure m . setDataParam ( ( int ) vm . dataPos ) ; // track if there is a heap if ( v2 . getDataType ( ) == DataType . STRING || v2 . isVariableLength ( ) ) hasHeap = true ; // recurse if ( v2 instanceof Structure ) { Structure nested = ( Structure ) v2 ; StructureMembers nestSm = nested . makeStructureMembers ( ) ; m . setStructureMembers ( nestSm ) ; hasHeap |= convertStructure ( nested , nestSm ) ; } } return hasHeap ; }


Input:
/ * public static int setOffsets ( StructureMembers members ) { int offset = 0 ; for ( StructureMembers . Member m : members . getMembers () ) { m . setDataParam ( offset ) ; offset + = m . getSizeBytes () ; [CODESPLIT] void convertHeap ( ArrayStructureBB asbb , int pos , StructureMembers sm ) throws java . io . IOException , InvalidRangeException { ByteBuffer bb = asbb . getByteBuffer ( ) ; for ( StructureMembers . Member m : sm . getMembers ( ) ) { if ( m . getDataType ( ) == DataType . STRING ) { m . setDataObject ( ByteOrder . nativeOrder ( ) ) ; // the index is always written in "native order" int size = m . getSize ( ) ; int destPos = pos + m . getDataParam ( ) ; String [ ] result = new String [ size ] ; for ( int i = 0 ; i < size ; i ++ ) result [ i ] = headerParser . readHeapString ( , destPos + i * 16 ) ; // 16 byte "heap ids" are in the ByteBuffer int index = asbb . addObjectToHeap ( result ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; // the string index is always written in "native order" bb . putInt ( destPos , index ) ; // overwrite with the index into the StringHeap } else if ( m . isVariableLength ( ) ) { int startPos = pos + m . getDataParam ( ) ; bb . order ( ByteOrder . LITTLE_ENDIAN ) ; ByteOrder bo = ( ByteOrder ) m . getDataObject ( ) ; int endian = bo . equals ( ByteOrder . LITTLE_ENDIAN ) ? RandomAccessFile . LITTLE_ENDIAN : RandomAccessFile . BIG_ENDIAN ; // Compute rank and size upto the first (and ideally last) VLEN int [ ] fieldshape = m . getShape ( ) ; int prefixrank = 0 ; int size = 1 ; for ( ; prefixrank < fieldshape . length ; prefixrank ++ ) { if ( fieldshape [ prefixrank ] < 0 ) break ; size *= fieldshape [ prefixrank ] ; } assert size == m . getSize ( ) : "Internal error: field size mismatch" ; Array [ ] fieldarray = new Array [ size ] ; // hold all the vlen instance data // destPos will point to each vlen instance in turn // assuming we have 'size' such instances in a row. int destPos = startPos ; for ( int i = 0 ; i < size ; i ++ ) { // vlenarray extracts the i'th vlen contents (struct not supported). Array vlenArray = headerParser . readHeapVlen ( bb , destPos , m . getDataType ( ) , endian ) ; fieldarray [ i ] = vlenArray ; destPos += VLEN_T_SIZE ; // Apparentlly no way to compute VLEN_T_SIZE on the fly } Array result ; if ( prefixrank == 0 ) // if scalar, return just the singleton vlen array result = fieldarray [ 0 ] ; else { int [ ] newshape = new int [ prefixrank ] ; System . arraycopy ( fieldshape , 0 , newshape , 0 , prefixrank ) ; // result = Array.makeObjectArray(m.getDataType(), fieldarray[0].getClass(), newshape, fieldarray); result = Array . makeVlenArray ( newshape , fieldarray ) ; } /* if (prefixrank == 1)
          result = Array.makeObjectArray(m.getDataType(), fieldarray[0].getClass(), new int[]{size}, fieldarray);
        else {
          // Otherwise create and fill in an n-dimensional Array Of Arrays
          int[] newshape = new int[prefixrank];
          System.arraycopy(fieldshape, 0, newshape, 0, prefixrank);
          Array ndimarray = Array.makeObjectArray(m.getDataType(), Array.class, newshape, null);
          // Transfer the elements of data into the n-dim arrays
          IndexIterator iter = ndimarray.getIndexIterator();
          for(int i = 0;iter.hasNext();i++) {
              iter.setObjectNext(fieldarray[i]);
          }
          result = ndimarray;
        } */ //Array vlenArray = headerParser.readHeapVlen(bb, destPos, m.getDataType(), endian); int index = asbb . addObjectToHeap ( result ) ; bb . order ( ByteOrder . nativeOrder ( ) ) ; bb . putInt ( startPos , index ) ; // overwrite with the index into the Heap } } }


Input: / * Read data subset from file for a variable create primitive array . [CODESPLIT] Object readDataPrimitive ( Layout layout , DataType dataType , int [ ] shape , Object fillValue , int endian , boolean convertChar ) throws java . io . IOException , InvalidRangeException { if ( dataType == DataType . STRING ) { int size = ( int ) layout . getTotalNelems ( ) ; String [ ] sa = new String [ size ] ; int count = 0 ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) { // 16 byte "heap ids" sa [ count ++ ] = headerParser . readHeapString ( chunk . getSrcPos ( ) + layout . getElemSize ( ) * i ) ; } } return sa ; } if ( dataType == DataType . OPAQUE ) { Array opArray = Array . factory ( DataType . OPAQUE , shape ) ; assert ( new Section ( shape ) . computeSize ( ) == layout . getTotalNelems ( ) ) ; int count = 0 ; while ( layout . hasNext ( ) ) { Layout . Chunk chunk = layout . next ( ) ; if ( chunk == null ) continue ; int recsize = layout . getElemSize ( ) ; for ( int i = 0 ; i < chunk . getNelems ( ) ; i ++ ) { byte [ ] pa = new byte [ recsize ] ; raf . seek ( chunk . getSrcPos ( ) + i * recsize ) ; raf . readFully ( pa , 0 , recsize ) ; opArray . setObject ( count ++ , ByteBuffer . wrap ( pa ) ) ; } } return opArray ; } // normal case return IospHelper . readDataFill ( raf , layout , dataType , fillValue , endian , convertChar ) ; }


Input: old way [CODESPLIT] private StructureData readStructure ( Structure s , ArrayStructureW asw , long dataPos ) throws IOException , InvalidRangeException { StructureDataW sdata = new StructureDataW ( asw . getStructureMembers ( ) ) ; if ( debug ) System . out . println ( " readStructure " + s . getFullName ( ) + " dataPos = " + dataPos ) ; for ( Variable v2 : s . getVariables ( ) ) { H5header . Vinfo vinfo = ( H5header . Vinfo ) v2 . getSPobject ( ) ; if ( debug ) System . out . println ( " readStructureMember " + v2 . getFullName ( ) + " vinfo = " + vinfo ) ; Array dataArray = readData ( v2 , dataPos + vinfo . dataPos , v2 . getShapeAsSection ( ) ) ; sdata . setMemberData ( v2 . getShortName ( ) , dataArray ) ; } return sdata ; }


Input:
create a NetcdfDataset out of this NetcdfFile adding coordinates etc . [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { if ( null != ds . findVariable ( "x" ) ) return ; // check if its already been done - aggregating enhanced datasets.
 // old way
 Attribute att = ds . findGlobalAttribute ( "MAPPROJ" ) ; int projType = att . getNumericValue ( ) . intValue ( ) ; double lat1 = findAttributeDouble ( ds , "TRUELAT1" , Double . NaN ) ; double lat2 = findAttributeDouble ( ds , "TRUELAT2" , Double . NaN ) ; double lat_origin = lat1 ; double lon_origin = findAttributeDouble ( ds , "TRUELON" , Double . NaN ) ; double false_easting = 0.0 ; double false_northing = 0.0 ; // new way
 String projName = ds . findAttValueIgnoreCase ( null , CF . GRID_MAPPING_NAME , null ) ; if ( projName != null ) { projName = projName . trim ( ) ; lat_origin = findAttributeDouble ( ds , "latitude_of_projection_origin" , Double . NaN ) ; lon_origin = findAttributeDouble ( ds , "longitude_of_central_meridian" , Double . NaN ) ; false_easting = findAttributeDouble ( ds , "false_easting" , 0.0 ) ; false_northing = findAttributeDouble ( ds , "false_northing" , 0.0 ) ; Attribute att2 = ds . findGlobalAttributeIgnoreCase ( "standard_parallel" ) ; if ( att2 != null ) { lat1 = att2 . getNumericValue ( ) . doubleValue ( ) ; lat2 = ( att2 . getLength ( ) > 1 ) ? att2 . getNumericValue ( 1 ) . doubleValue ( ) : lat1 ; } } else { if ( projType == 2 ) projName = "lambert_conformal_conic" ; } Variable coord_var = ds . findVariable ( "x_stag" ) ; if ( ! Double . isNaN ( false_easting ) || ! Double . isNaN ( false_northing ) ) { String units = ds . findAttValueIgnoreCase ( coord_var , CDM . UNITS , null ) ; double scalef = 1.0 ; try { scalef = SimpleUnit . getConversionFactor ( units , "km" ) ; } catch ( IllegalArgumentException e ) { log . error ( units + " not convertible to km" ) ; } false_easting *= scalef ; false_northing *= scalef ; } ProjectionImpl proj ; if ( ( projName != null ) && projName . equalsIgnoreCase ( "lambert_conformal_conic" ) ) { proj = new LambertConformal ( lat_origin , lon_origin , lat1 , lat2 , false_easting , false_northing ) ; projCT = new ProjectionCT ( "Projection" , "FGDC" , proj ) ; if ( false_easting == 0.0 ) calcCenterPoints ( ds , proj ) ; // old way
 } else { parseInfo . format ( "ERROR: unknown projection type = %s%n" , projName ) ; } if ( debugProj && ( proj != null ) ) { System . out . println ( " using LC " + proj . paramsToString ( ) ) ; double lat_check = findAttributeDouble ( ds , "CTRLAT" , Double . NaN ) ; double lon_check = findAttributeDouble ( ds , "CTRLON" , Double . NaN ) ; LatLonPointImpl lpt0 = new LatLonPointImpl ( lat_check , lon_check ) ; ProjectionPoint ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( "CTR lpt0= " + lpt0 + " ppt0=" + ppt0 ) ; Variable xstag = ds . findVariable ( "x_stag" ) ; ArrayFloat . D1 xstagData = ( ArrayFloat . D1 ) xstag . read ( ) ; float center_x = xstagData . get ( ( int ) xstag . getSize ( ) - 1 ) ; Variable ystag = ds . findVariable ( "y_stag" ) ; ArrayFloat . D1 ystagData = ( ArrayFloat . D1 ) ystag . read ( ) ; float center_y = ystagData . get ( ( int ) ystag . getSize ( ) - 1 ) ; System . out . println ( "CTR should be x,y= " + center_x / 2000 + ", " + center_y / 2000 ) ; lpt0 = new LatLonPointImpl ( lat_origin , lon_origin ) ; ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( "ORIGIN lpt0= " + lpt0 + " ppt0=" + ppt0 ) ; lpt0 = new LatLonPointImpl ( lat_origin , lon_origin ) ; ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( "TRUE ORIGIN lpt0= " + lpt0 + " ppt0=" + ppt0 ) ; } if ( projCT != null ) { VariableDS v = makeCoordinateTransformVariable ( ds , projCT ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisTypes , "GeoX GeoY" ) ) ; ds . addVariable ( null , v ) ; } if ( ds . findVariable ( "x_stag" ) != null ) ds . addCoordinateAxis ( makeCoordAxis ( ds , "x" ) ) ; if ( ds . findVariable ( "y_stag" ) != null ) ds . addCoordinateAxis ( makeCoordAxis ( ds , "y" ) ) ; if ( ds . findVariable ( "z_stag" ) != null ) ds . addCoordinateAxis ( makeCoordAxis ( ds , "z" ) ) ; Variable zsoil = ds . findVariable ( "ZPSOIL" ) ; if ( zsoil != null ) zsoil . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . GeoZ . toString ( ) ) ) ; ds . finish ( ) ; }


Input: old [CODESPLIT] private void calcCenterPoints ( NetcdfDataset ds , Projection proj ) throws IOException { double lat_check = findAttributeDouble ( ds , "CTRLAT" , Double . NaN ) ; double lon_check = findAttributeDouble ( ds , "CTRLON" , Double . NaN ) ; LatLonPointImpl lpt0 = new LatLonPointImpl ( lat_check , lon_check ) ; ProjectionPoint ppt0 = proj . latLonToProj ( lpt0 , new ProjectionPointImpl ( ) ) ; System . out . println ( "CTR lpt0= " + lpt0 + " ppt0=" + ppt0 ) ; Variable xstag = ds . findVariable ( "x_stag" ) ; int nxpts = ( int ) xstag . getSize ( ) ; ArrayFloat . D1 xstagData = ( ArrayFloat . D1 ) xstag . read ( ) ; float center_x = xstagData . get ( nxpts - 1 ) ; double false_easting = center_x / 2000 - ppt0 . getX ( ) * 1000.0 ; System . out . println ( "false_easting= " + false_easting ) ; Variable ystag = ds . findVariable ( "y_stag" ) ; int nypts = ( int ) ystag . getSize ( ) ; ArrayFloat . D1 ystagData = ( ArrayFloat . D1 ) ystag . read ( ) ; float center_y = ystagData . get ( nypts - 1 ) ; double false_northing = center_y / 2000 - ppt0 . getY ( ) * 1000.0 ; System . out . println ( "false_northing= " + false_northing ) ; double dx = findAttributeDouble ( ds , "DX" , Double . NaN ) ; double dy = findAttributeDouble ( ds , "DY" , Double . NaN ) ; double w = dx * ( nxpts - 1 ) ; double h = dy * ( nypts - 1 ) ; double startx = ppt0 . getX ( ) * 1000.0 - w / 2 ; double starty = ppt0 . getY ( ) * 1000.0 - h / 2 ; xstag . setValues ( nxpts , startx , dx ) ; ystag . setValues ( nypts , starty , dy ) ; }


Input: //////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private CoordinateAxis makeCoordAxis ( NetcdfDataset ds , String axisName ) throws IOException { Variable stagV = ds . findVariable ( axisName + "_stag" ) ; Array data_stag = stagV . read ( ) ; int n = ( int ) data_stag . getSize ( ) - 1 ; DataType dt = DataType . getType ( data_stag ) ; Array data = Array . factory ( dt , new int [ ] { n } ) ; Index stagIndex = data_stag . getIndex ( ) ; Index dataIndex = data . getIndex ( ) ; for ( int i = 0 ; i < n ; i ++ ) { double val = data_stag . getDouble ( stagIndex . set ( i ) ) + data_stag . getDouble ( stagIndex . set ( i + 1 ) ) ; data . setDouble ( dataIndex . set ( i ) , 0.5 * val ) ; } DataType dtype = DataType . getType ( data ) ; String units = ds . findAttValueIgnoreCase ( stagV , CDM . UNITS , "m" ) ; CoordinateAxis v = new CoordinateAxis1D ( ds , null , axisName , dtype , axisName , units , "synthesized non-staggered " + axisName + " coordinate" ) ; v . setCachedData ( data , true ) ; return v ; }


Input: Sort specific [CODESPLIT] public void addSegment ( CEAST segment ) { assert sort == Sort . SEGMENT ; if ( subnodes == null ) subnodes = new NodeList ( ) ; subnodes . add ( segment ) ; }


Input: testing 1 - 2 - 3 [CODESPLIT] public static void main ( String [ ] args ) { ProjectionManager d = new ProjectionManager ( null , null ) ; d . setVisible ( ) ; }


Input: Finds the first occurrence of match in data . [CODESPLIT] public int indexOf ( byte [ ] data , int start , int max ) { int j = 0 ; if ( data . length == 0 ) return - 1 ; if ( start + max > data . length ) System . out . println ( "HEY KMPMatch" ) ; for ( int i = start ; i < start + max ; i ++ ) { while ( j > 0 && match [ j ] != data [ i ] ) j = failure [ j - 1 ] ; if ( match [ j ] == data [ i ] ) j ++ ; if ( j == match . length ) return i - match . length + 1 ; } return - 1 ; }


Input: / * Finds the first occurrence of match in data . @param data search in this byte block @param start start at data [ start ] @param max end at data [ start + max ] @return index into block of first match else - 1 if not found . [CODESPLIT] private int [ ] computeFailure ( byte [ ] match ) { int [ ] result = new int [ match . length ] ; int j = 0 ; for ( int i = 1 ; i < match . length ; i ++ ) { while ( j > 0 && match [ j ] != match [ i ] ) j = result [ j - 1 ] ; if ( match [ j ] == match [ i ] ) j ++ ; result [ i ] = j ; } return result ; }


Input: /////////////////////////////////////////////// [CODESPLIT] public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { String convention = ncd . findAttValueIgnoreCase ( null , "Conventions" , null ) ; if ( ( null != convention ) && convention . equals ( _Coordinate . Convention ) ) { String format = ncd . findAttValueIgnoreCase ( null , "Format" , null ) ; if ( format != null && format . equals ( "Level3/NIDS" ) ) return this ; } return null ; }


Input: this method removes the least popular picture ( s ) in the cache . It first removes those pictures which have been suggested for removal . And then it picks any it can find As many pictures are removed as nescessary untill there are less pictures in the cache than the Settings . maxCache specifies . ( If maxCache is 0 then the Enumeration finds no elements and we don t get an endless loop . [CODESPLIT] public static synchronized void removeLeastPopular ( ) { Tools . log ( "PictureCache.removeLeastPopular:" ) ; //reportCache(); Enumeration e = removalQueue . elements ( ) ; while ( ( e . hasMoreElements ( ) ) && ( pictureCache . size ( ) >= maxCache ) ) { String removeElement = ( String ) e . nextElement ( ) ; Tools . log ( "PictureCache.remove: " + removeElement ) ; pictureCache . remove ( removeElement ) ; removalQueue . remove ( removeElement ) ; } e = pictureCache . keys ( ) ; while ( ( pictureCache . size ( ) >= maxCache ) && ( e . hasMoreElements ( ) ) ) { String removeElement = ( String ) e . nextElement ( ) ; Tools . log ( "PictureCache.remove: " + removeElement ) ; pictureCache . remove ( removeElement ) ; } }


Input: store an image in the cache [CODESPLIT] public static synchronized void add ( URL url , SourcePicture sp ) { Tools . log ( "PictureCache.add: " + url . toString ( ) ) ; if ( sp . getSourceBufferedImage ( ) == null ) { Tools . log ( "PictureCache.add: invoked with a null picture! Not cached!" ) ; return ; } if ( ( maxCache < 1 ) ) { Tools . log ( "PictureCache.add: cache is diabled. Not adding picture." ) ; return ; } if ( isInCache ( url ) ) { Tools . log ( "Picture " + url . toString ( ) + " is already in the cache. Not adding again." ) ; return ; } if ( pictureCache . size ( ) >= maxCache ) removeLeastPopular ( ) ; if ( pictureCache . size ( ) < maxCache ) pictureCache . put ( url . toString ( ) , sp ) ; //reportCache();	 }


Input: method to inspect the cache [CODESPLIT] public static synchronized void reportCache ( ) { Tools . log ( "   PictureCache.reportCache: cache contains: " + Integer . toString ( pictureCache . size ( ) ) + " max: " + Integer . toString ( maxCache ) ) ; //Tools.freeMem(); Enumeration e = pictureCache . keys ( ) ; while ( e . hasMoreElements ( ) ) { Tools . log ( "   Cache contains: " + ( ( String ) e . nextElement ( ) ) ) ; } Tools . log ( "  End of cache contents" ) ; }


Input: method to stop all background loading [CODESPLIT] public static void stopBackgroundLoading ( ) { Enumeration e = cacheLoadsInProgress . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( SourcePicture ) e . nextElement ( ) ) . stopLoading ( ) ; } }


Input: method to stop all background loading except the indicated file . Returns whether the image is already being loaded . True = loading in progress False = not in progress . [CODESPLIT] public static boolean stopBackgroundLoadingExcept ( URL exemptionURL ) { SourcePicture sp ; String exemptionURLString = exemptionURL . toString ( ) ; Enumeration e = cacheLoadsInProgress . elements ( ) ; boolean inProgress = false ; while ( e . hasMoreElements ( ) ) { sp = ( ( SourcePicture ) e . nextElement ( ) ) ; if ( ! sp . getUrlString ( ) . equals ( exemptionURLString ) ) sp . stopLoading ( ) ; else { Tools . log ( "PictureCache.stopBackgroundLoading: picture was already loading" ) ; inProgress = true ; } } return inProgress ; }


Input: listeners will receive columnAdded () / columnRemoved () event [CODESPLIT] public void setColumnVisible ( TableColumn column , boolean visible ) { if ( isColumnVisible ( column ) == visible ) { return ; // Visibility status did not change. } if ( ! visible ) { super . removeColumn ( column ) ; } else { // find the visible index of the column: // iterate through both collections of visible and all columns, counting // visible columns up to the one that's about to be shown again int noVisibleColumns = tableColumns . size ( ) ; int noInvisibleColumns = allTableColumns . size ( ) ; int visibleIndex = 0 ; for ( int invisibleIndex = 0 ; invisibleIndex < noInvisibleColumns ; ++ invisibleIndex ) { TableColumn visibleColumn = ( visibleIndex < noVisibleColumns ? tableColumns . get ( visibleIndex ) : null ) ; TableColumn testColumn = allTableColumns . get ( invisibleIndex ) ; if ( testColumn == column ) { if ( visibleColumn != column ) { super . addColumn ( column ) ; super . moveColumn ( tableColumns . size ( ) - 1 , visibleIndex ) ; } return ; // #################### } if ( testColumn == visibleColumn ) { ++ visibleIndex ; } } } }


Input: Removes <code > column< / code > from this column model . Posts <code > columnRemoved< / code > event . Will do nothing if the column is not in this model . [CODESPLIT] @ Override public void removeColumn ( TableColumn column ) { int allColumnsIndex = allTableColumns . indexOf ( column ) ; if ( allColumnsIndex != - 1 ) { allTableColumns . removeElementAt ( allColumnsIndex ) ; } super . removeColumn ( column ) ; }


Input: Moves the column from <code > oldIndex< / code > to <code > newIndex< / code > . Posts <code > columnMoved< / code > event . Will not move any columns if <code > oldIndex< / code > equals <code > newIndex< / code > . [CODESPLIT] @ Override public void moveColumn ( int oldIndex , int newIndex ) { if ( ( oldIndex < 0 ) || ( oldIndex >= getColumnCount ( ) ) || ( newIndex < 0 ) || ( newIndex >= getColumnCount ( ) ) ) throw new IllegalArgumentException ( "moveColumn() - Index out of range" ) ; TableColumn fromColumn = tableColumns . get ( oldIndex ) ; TableColumn toColumn = tableColumns . get ( newIndex ) ; int allColumnsOldIndex = allTableColumns . indexOf ( fromColumn ) ; int allColumnsNewIndex = allTableColumns . indexOf ( toColumn ) ; if ( oldIndex != newIndex ) { allTableColumns . removeElementAt ( allColumnsOldIndex ) ; allTableColumns . insertElementAt ( fromColumn , allColumnsNewIndex ) ; } super . moveColumn ( oldIndex , newIndex ) ; }


Input: Returns an <code > Enumeration< / code > of all the columns in the model . [CODESPLIT] public Enumeration < TableColumn > getColumns ( boolean onlyVisible ) { Vector columns = ( onlyVisible ? tableColumns : allTableColumns ) ; return columns . elements ( ) ; }


Input: Returns the <code > TableColumn< / code > object for the column at <code > columnIndex< / code > . [CODESPLIT] public TableColumn getColumn ( int columnIndex , boolean onlyVisible ) { if ( onlyVisible ) { return tableColumns . elementAt ( columnIndex ) ; } else { return allTableColumns . elementAt ( columnIndex ) ; } }


Input: Adapted from JTable . createDefaultColumnsFromModel () . [CODESPLIT] public void createColumnsFromModel ( TableModel newModel ) { if ( newModel != model ) { if ( model != null ) { model . removeTableModelListener ( this ) ; // Stop listening to old model. } newModel . addTableModelListener ( this ) ; // Start listening to new one. model = newModel ; } // Removes all current columns including the hidden ones. // For visible columns that are removed, TableColumnModelEvents get fired. while ( ! allTableColumns . isEmpty ( ) ) { removeColumn ( allTableColumns . elementAt ( 0 ) ) ; } // Create new columns from the data model info for ( int modelColumnIndex = 0 ; modelColumnIndex < newModel . getColumnCount ( ) ; modelColumnIndex ++ ) { TableColumn newColumn = new TableColumn ( modelColumnIndex ) ; String columnName = newModel . getColumnName ( modelColumnIndex ) ; newColumn . setHeaderValue ( columnName ) ; addColumn ( newColumn ) ; } }


Input: Static factory methods for creating HTTPMethod instances [CODESPLIT] static public HTTPMethod Get ( HTTPSession session , String legalurl ) throws HTTPException { return makemethod ( HTTPSession . Methods . Get , session , legalurl ) ; }


Input: Common method creation code so we can isolate mocking [CODESPLIT] static protected HTTPMethod makemethod ( HTTPSession . Methods m , HTTPSession session , String url ) throws HTTPException { HTTPMethod meth = null ; if ( MOCKMETHODCLASS == null ) { // do the normal case meth = new HTTPMethod ( m , session , url ) ; } else { //(MOCKMETHODCLASS != null) java . lang . Class methodcl = MOCKMETHODCLASS ; Constructor < HTTPMethod > cons = null ; try { cons = methodcl . getConstructor ( HTTPSession . Methods . class , HTTPSession . class , String . class ) ; } catch ( Exception e ) { throw new HTTPException ( "HTTPFactory: no proper HTTPMethod constructor available" , e ) ; } try { meth = cons . newInstance ( m , session , url ) ; } catch ( Exception e ) { throw new HTTPException ( "HTTPFactory: HTTPMethod constructor failed" , e ) ; } } return meth ; }


Input: //////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] public void deflate ( Formatter f , Variable v ) throws IOException { H5header . Vinfo vinfo = ( H5header . Vinfo ) v . getSPobject ( ) ; DataBTree btree = vinfo . btree ; if ( btree == null || vinfo . useFillValue ) { f . format ( "%s not chunked%n" , v . getShortName ( ) ) ; return ; } }


Input: / * extend Variable { repeated PartitionVariable partition = 100 ; repeated Parameter vparams = 101 ; // not used yet } [CODESPLIT] @ Override protected GribCollectionMutable . VariableIndex readVariableExtensions ( GribCollectionMutable . GroupGC group , GribCollectionProto . Variable proto , GribCollectionMutable . VariableIndex vi ) { List < GribCollectionProto . PartitionVariable > pvList = proto . getPartVariableList ( ) ; PartitionCollectionMutable . VariableIndexPartitioned vip = pc . makeVariableIndexPartitioned ( group , vi , pvList . size ( ) ) ; vip . setPartitions ( pvList ) ; // cant put this in the constructor vip . ndups = vi . ndups ; vip . nrecords = vi . nrecords ; vip . nmissing = vi . nmissing ; return vip ; }