public static UnitID newUnitID(final String name, final String plural,
			final String symbol) {
		UnitID id;
		try {
			id = name == null
					? new UnitSymbol(symbol)
					: UnitName.newUnitName(name, plural, symbol);
		}
		catch (final NameException e) {
			id = null; // can't happen
		}
		return id;
	}

public
static
UnitID
newUnitID
(
final
String
name
,
final
String
plural
,
final
String
symbol
)
{
UnitID
id
;
try
{
id
=
name
==
new
UnitSymbol
(
symbol
)
:
UnitName
.
newUnitName
(
name
,
plural
,
symbol
)
;
}
catch
(
final
NameException
e
)
{
id
=
;
// can't happen
}
return
id
;
}

Factory method for constructing an identifier from a name, plural, and
symbol.

@param name
The name for the unit. May be null
.
@param plural
The plural form of the name. If null
 and
name is non-
null, then regular
plural-forming rules are used on the name.
@param symbol
The symbol for the unit. May be null
.

Factory method for constructing an identifier from a name plural and symbol .


public static GradsAttribute parseAttribute(String attrSpec) {
        String[]     toks = attrSpec.split("\\s+");
        StringBuffer buf  = new StringBuffer();
        for (int i = 4; i < toks.length; i++) {
            buf.append(toks[i]);
            buf.append(" ");
        }

        // toks[0] is "@"
        return new GradsAttribute(toks[1], toks[2], toks[3],
                                  buf.toString().trim());
    }

public
static
GradsAttribute
parseAttribute
(
String
attrSpec
)
{
String
[
]
toks
=
attrSpec
.
split
(
"\\s+"
)
;
StringBuffer
buf
=
new
StringBuffer
(
)
;
for
(
int
i
=
4
;
i
<
toks
.
length
;
i
++
)
{
buf
.
append
(
toks
[
i
]
)
;
buf
.
append
(
" "
)
;
}
// toks[0] is "@"
return
new
GradsAttribute
(
toks
[
1
]
,
toks
[
2
]
,
toks
[
3
]
,
buf
.
toString
(
)
.
trim
(
)
)
;
}

Parse an attribute spec

@param attrSpec  the attribute spec (e.g. @ precip String units mm/day)

@return the associated attribute


int readTop(ucar.unidata.io.RandomAccessFile raf) throws IOException {
        int pos = 0;

        // long     actualSize = 0;
        raf.seek(pos);

        int readLen = 35;

        // Read in the contents of the NEXRAD Level III product head
        byte[] b = new byte[readLen];

        int rc = raf.read(b);

        if (rc != readLen) {
            return 0;
        }

        // check
        if ((convertunsignedByte2Short(b[0]) != 0x00) || (convertunsignedByte2Short(b[1]) != 0xF0)
                || (convertunsignedByte2Short(b[2]) != 0x09)) {
            return 0;
        }

        String pidd  = new String(b, 15, 5, CDM.utf8Charset);

        if (pidd.contains("NOWRA") || pidd.contains("USRAD") || pidd.contains("NEX")) {
            return 1;
        } else {
            return 0;
        }
    }

read the header of input file and parsing the NOWRAD part
@param raf    input file
@return        1 if checking passing
@throws IOException


public static int shortsToInt(short s1, short s2, boolean swapBytes) {
        byte[] b = new byte[4];

        b[0] = (byte) (s1 >>> 8);
        b[1] = (byte) (s1 >>> 0);
        b[2] = (byte) (s2 >>> 8);
        b[3] = (byte) (s2 >>> 0);

        return bytesToInt(b, false);
    }

public static int shortsToInt ( short s1 , short s2 , boolean swapBytes ) { byte [ ] b = new byte [ 4 ] ; b [ 0 ] = ( byte ) ( s1 >>> 8 ) ; b [ 1 ] = ( byte ) ( s1 >>> 0 ) ; b [ 2 ] = ( byte ) ( s2 >>> 8 ) ; b [ 3 ] = ( byte ) ( s2 >>> 0 ) ; return bytesToInt ( b , false ) ; }

convert two short into a integer
@param s1            short one
@param s2            short two
@param swapBytes      if swap bytes
@return    integer


public static int bytesToInt(byte[] bytes, boolean swapBytes) {
        byte a = bytes[0];
        byte b = bytes[1];
        byte c = bytes[2];
        byte d = bytes[3];

        if (swapBytes) {
            return ((a & 0xff)) + ((b & 0xff) << 8) + ((c & 0xff) << 16) + ((d & 0xff) << 24);
        } else {
            return ((a & 0xff) << 24) + ((b & 0xff) << 16) + ((c & 0xff) << 8) + ((d & 0xff));
        }
    }

public static int bytesToInt ( byte [ ] bytes , boolean swapBytes ) { byte a = bytes [ 0 ] ; byte b = bytes [ 1 ] ; byte c = bytes [ 2 ] ; byte d = bytes [ 3 ] ; if ( swapBytes ) { return ( ( a & 0xff ) ) + ( ( b & 0xff ) << 8 ) + ( ( c & 0xff ) << 16 ) + ( ( d & 0xff ) << 24 ) ; } else { return ( ( a & 0xff ) << 24 ) + ( ( b & 0xff ) << 16 ) + ( ( c & 0xff ) << 8 ) + ( ( d & 0xff ) ) ; } }

convert bytes into integer
@param bytes           bytes array
@param swapBytes       if need to swap
@return   integer


static public java.util.Date getDate(int julianDays, int msecs) {
        long total = ((long) (julianDays - 1)) * 24 * 3600 * 1000 + msecs;

        return new Date(total);
    }

static public java . util . Date getDate ( int julianDays , int msecs ) { long total = ( ( long ) ( julianDays - 1 ) ) * 24 * 3600 * 1000 + msecs ; return new Date ( total ) ; }

get jave date
@param julianDays
@param msecs
@return   java date


public static String makeValidNetcdfObjectName(String name) {
    StringBuilder sb = new StringBuilder(name);

    while (sb.length() > 0) {
      int cp = sb.codePointAt(0);

      // First char must be [a-z][A-Z][0-9]_ | UTF8
      if (cp <= 0x7f) {
        if (!('A' <= cp && cp <= 'Z')
                && !('a' <= cp && cp <= 'z')
                && !('0' <= cp && cp <= '9')
                && cp != '_') {
          sb.deleteCharAt(0);
          continue;
        }
      }
      break;
    }

    for (int pos = 1; pos < sb.length(); ++pos) {
      int cp = sb.codePointAt(pos);

      // handle simple 0x00-0x7F characters here
      if (cp <= 0x7F) {
        if (cp < ' ' || cp > 0x7E || cp == '/') {  // control char, DEL, or forward-slash
          sb.deleteCharAt(pos);
          --pos;
        }
      }
    }

    while (sb.length() > 0) {
      int cp = sb.codePointAt(sb.length() - 1);

      if (cp <= 0x7f && Character.isWhitespace(cp)) {
        sb.deleteCharAt(sb.length() - 1);
      } else {
        break;
      }
    }

    if (sb.length() == 0) {
      throw new IllegalArgumentException(String.format("Illegal NetCDF object name: '%s'", name));
    }

    return sb.toString();
  }

Convert a name to a legal netcdf-3 name.

@param name  the name to convert.
@return  the converted name.
@see #isValidNetcdfObjectName(String)

Convert a name to a legal netcdf - 3 name .


static public boolean isValidNetcdf3ObjectName(String name) {
    Matcher m = objectNamePatternOld.matcher(name);
    return m.matches();
  }

static public boolean isValidNetcdf3ObjectName ( String name ) { Matcher m = objectNamePatternOld . matcher ( name ) ; return m . matches ( ) ; }

Determine if the given name can be used for a Dimension, Attribute, or Variable name.
Should match makeValidNetcdf3ObjectName.
@param name test this.
@return  true if valid name.
@deprecated use isValidNetcdfObjectName

Determine if the given name can be used for a Dimension Attribute or Variable name . Should match makeValidNetcdf3ObjectName .


@Override
  public void openForWriting(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile ncfile,
                   ucar.nc2.util.CancelTask cancelTask) throws IOException {
    open(raf, ncfile, cancelTask);
  }

@ Override public void openForWriting ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { open ( raf , ncfile , cancelTask ) ; }


private ucar.ma2.Array readRecordData(ucar.nc2.Structure s, Section section) throws java.io.IOException {
    //if (s.isSubset())
    //  return readRecordDataSubset(s, section);

    // has to be 1D
    Range recordRange = section.getRange(0);

    // create the ArrayStructure
    StructureMembers members = s.makeStructureMembers();
    for (StructureMembers.Member m : members.getMembers()) {
      Variable v2 = s.findVariable(m.getName());
      N3header.Vinfo vinfo = (N3header.Vinfo) v2.getSPobject();
      m.setDataParam((int) (vinfo.begin - header.recStart));
    }

    // protect agains too large of reads
    if (header.recsize > Integer.MAX_VALUE)
      throw new IllegalArgumentException("Cant read records when recsize > "+Integer.MAX_VALUE);
    long nrecs = section.computeSize();
    if (nrecs * header.recsize > Integer.MAX_VALUE)
      throw new IllegalArgumentException("Too large read: nrecs * recsize= "+(nrecs * header.recsize) +"bytes exceeds "+Integer.MAX_VALUE);

    members.setStructureSize((int) header.recsize);
    ArrayStructureBB structureArray = new ArrayStructureBB(members, new int[]{recordRange.length()});

    // note dependency on raf; should probably defer to subclass
    // loop over records
    byte[] result = structureArray.getByteBuffer().array();
    int count = 0;
    for (int recnum : recordRange) {
      if (debugRecord) System.out.println(" read record " + recnum);
      raf.seek(header.recStart + recnum * header.recsize); // where the record starts

      if (recnum != header.numrecs - 1)
        raf.readFully(result, (int) (count * header.recsize), (int) header.recsize);
      else
        raf.read(result, (int) (count * header.recsize), (int) header.recsize); // "wart" allows file to be one byte short. since its always padding, we allow
      count++;
    }

    return structureArray;
  }

Read data from record structure. For N3, this is the only possible structure, and there can be no nesting.
Read all variables for each record, put in ByteBuffer.

@param s the record structure
@param section the record range to read
@return an ArrayStructure, with all the data read in.
@throws IOException on error

Read data from record structure . For N3 this is the only possible structure and there can be no nesting . Read all variables for each record put in ByteBuffer .


private ucar.ma2.Array readRecordDataSubset(ucar.nc2.Structure s, Section section) throws java.io.IOException {
    Range recordRange = section.getRange(0);
    int nrecords = recordRange.length();

    // create the ArrayStructureMA
    StructureMembers members = s.makeStructureMembers();
    for (StructureMembers.Member m : members.getMembers()) {
      Variable v2 = s.findVariable(m.getName());
      N3header.Vinfo vinfo = (N3header.Vinfo) v2.getSPobject();
      m.setDataParam((int) (vinfo.begin - header.recStart)); // offset from start of record

      // construct the full shape
      int rank = m.getShape().length;
      int[] fullShape = new int[rank + 1];
      fullShape[0] = nrecords;  // the first dimension
      System.arraycopy(m.getShape(), 0, fullShape, 1, rank); // the remaining dimensions

      Array data = Array.factory(m.getDataType(), fullShape);
      m.setDataArray( data);
      m.setDataObject( data.getIndexIterator());
    }

    //LOOK this is all wrong - why using recsize ???
    return null;
    /* members.setStructureSize(recsize);
    ArrayStructureMA structureArray = new ArrayStructureMA(members, new int[]{nrecords});

    // note dependency on raf; should probably defer to subclass
    // loop over records
    byte[] record = new byte[ recsize];
    ByteBuffer bb = ByteBuffer.wrap(record);
    for (int recnum = recordRange.first(); recnum <= recordRange.last(); recnum += recordRange.stride()) {
      if (debugRecord) System.out.println(" readRecordDataSubset recno= " + recnum);

      // read one record
      raf.seek(recStart + recnum * recsize); // where the record starts
      if (recnum != numrecs - 1)
        raf.readFully(record, 0, recsize);
      else
        raf.read(record, 0, recsize); // "wart" allows file to be one byte short. since its always padding, we allow

      // transfer desired variable(s) to result array(s)
      for (StructureMembers.Member m : members.getMembers()) {
        IndexIterator dataIter = (IndexIterator) m.getDataObject();
        IospHelper.copyFromByteBuffer(bb, m, dataIter);
      }
    }

    return structureArray;  */
  }

Read data from record structure, that has been subsetted.
Read one record at at time, put requested variable into ArrayStructureMA.

@param s the record structure
@param section the record range to read
@return an ArrayStructure, with all the data read in.
@throws IOException on error

Read data from record structure that has been subsetted . Read one record at at time put requested variable into ArrayStructureMA .


protected void fillNonRecordVariables() throws IOException {
    // run through each variable
    for (Variable v : ncfile.getVariables()) {
      if (v.isUnlimited()) continue;
      try {
        writeData(v, v.getShapeAsSection(), makeConstantArray(v));
      } catch (InvalidRangeException e) {
        e.printStackTrace();  // shouldnt happen
      }
    }
  }

protected
void
fillNonRecordVariables
(
)
throws
IOException
{
// run through each variable
for
(
Variable
v
:
ncfile
.
getVariables
(
)
)
{
if
(
v
.
isUnlimited
(
)
)
continue
;
try
{
writeData
(
v
,
v
.
getShapeAsSection
(
)
,
makeConstantArray
(
v
)
)
;
}
catch
(
InvalidRangeException
e
)
{
e
.
printStackTrace
(
)
;
// shouldnt happen
}
}
}


public GradsTimeStruct makeTimeStruct(int timeIndex) {
        double   tVal     = getValues()[timeIndex];
        Date     d        = DateUnit.getStandardDate(tVal + " " + getUnit());
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(java.util.TimeZone.getTimeZone("GMT"));
        calendar.setTime(d);
        return makeTimeStruct(calendar);
    }

public
GradsTimeStruct
makeTimeStruct
(
int
timeIndex
)
{
double
tVal
=
getValues
(
)
[
timeIndex
]
;
Date
d
=
DateUnit
.
getStandardDate
(
tVal
+
" "
+
getUnit
(
)
)
;
Calendar
calendar
=
Calendar
.
getInstance
(
)
;
calendar
.
setTimeZone
(
java
.
util
.
TimeZone
.
getTimeZone
(
"GMT"
)
)
;
calendar
.
setTime
(
d
)
;
return
makeTimeStruct
(
calendar
)
;
}

Make a time struct from the index.

@param timeIndex  the time value index

@return the corresponding TimeStruct


private GradsTimeStruct makeTimeStruct(Calendar calendar) {
        GradsTimeStruct ts = new GradsTimeStruct();
        ts.year   = calendar.get(Calendar.YEAR);
        ts.month  = calendar.get(Calendar.MONTH) + 1;  // MONTH is zero based
        ts.day    = calendar.get(Calendar.DAY_OF_MONTH);
        ts.hour   = calendar.get(Calendar.HOUR_OF_DAY);
        ts.minute = calendar.get(Calendar.MINUTE);
        ts.jday   = calendar.get(Calendar.DAY_OF_YEAR);
        return ts;
    }

private
GradsTimeStruct
makeTimeStruct
(
Calendar
calendar
)
{
GradsTimeStruct
ts
=
new
GradsTimeStruct
(
)
;
ts
.
year
=
calendar
.
get
(
Calendar
.
YEAR
)
;
ts
.
month
=
calendar
.
get
(
Calendar
.
MONTH
)
+
1
;
// MONTH is zero based
ts
.
day
=
calendar
.
get
(
Calendar
.
DAY_OF_MONTH
)
;
ts
.
hour
=
calendar
.
get
(
Calendar
.
HOUR_OF_DAY
)
;
ts
.
minute
=
calendar
.
get
(
Calendar
.
MINUTE
)
;
ts
.
jday
=
calendar
.
get
(
Calendar
.
DAY_OF_YEAR
)
;
return
ts
;
}

Make a GradsTimeStruct from the calendar state

@param calendar  the calendar

@return the corresponding GradsTimeStruct


public static boolean hasTimeTemplate(String template) {
        for (int i = 0; i < timeTemplates.length; i++) {
            if (template.indexOf(timeTemplates[i]) >= 0) {
                return true;
            }
        }
        return false;
    }

public static boolean hasTimeTemplate ( String template ) { for ( int i = 0 ; i < timeTemplates . length ; i ++ ) { if ( template . indexOf ( timeTemplates [ i ] ) >= 0 ) { return true ; } } return false ; }

Does this file definition have a time template in it?
@param template  the file template
@return true if it does


public void add(ServerSideFunction function) {
        if (function instanceof BoolFunction) {
            boolFunctions.put(function.getName(), function);
        }
        if (function instanceof BTFunction) {
            btFunctions.put(function.getName(), function);
        }
    }

public void add ( ServerSideFunction function ) { if ( function instanceof BoolFunction ) { boolFunctions . put ( function . getName ( ) , function ) ; } if ( function instanceof BTFunction ) { btFunctions . put ( function . getName ( ) , function ) ; } }

Adds a function to the library. The function will be inspected
to determine whether it is a boolean or BaseType function.

Adds a function to the library . The function will be inspected to determine whether it is a boolean or BaseType function .


public BoolFunction getBoolFunction(String name)
            throws NoSuchFunctionException {

        if (!boolFunctions.containsKey(name)) {
            loadNewFunction(name);
        }
        return (BoolFunction) boolFunctions.get(name);
    }

public BoolFunction getBoolFunction ( String name ) throws NoSuchFunctionException { if ( ! boolFunctions . containsKey ( name ) ) { loadNewFunction ( name ) ; } return ( BoolFunction ) boolFunctions . get ( name ) ; }

Retrieves a boolean function from the library. If the function
is not found the library will attempt to load it using the
mechanism described in the class documentation.

@param name The name of the function being requested.
@return Null if the function is not
in the library, and the attempt to load it fails.

Retrieves a boolean function from the library . If the function is not found the library will attempt to load it using the mechanism described in the class documentation .


public BTFunction getBTFunction(String name)
            throws NoSuchFunctionException {

        if (!btFunctions.containsKey(name)) {
            loadNewFunction(name);
        }
        return (BTFunction) btFunctions.get(name);
    }

public BTFunction getBTFunction ( String name ) throws NoSuchFunctionException { if ( ! btFunctions . containsKey ( name ) ) { loadNewFunction ( name ) ; } return ( BTFunction ) btFunctions . get ( name ) ; }

Retrieves a BaseType function from the library. If the function
is not found the library will attempt to load it using the
mechanism described in the class documentation.

@param name The name of the function being requested.
@return Null if the function is not
in the library, and the attempt to load it fails.

Retrieves a BaseType function from the library . If the function is not found the library will attempt to load it using the mechanism described in the class documentation .


protected void loadNewFunction(String name) {
        try {
            String fullName = prefix + name;
            Class value = Class.forName(fullName);
            if ((ServerSideFunction.class).isAssignableFrom(value)) {
                add((ServerSideFunction) value.newInstance());
                return;
            }
        } catch (ClassNotFoundException e) {
        } catch (IllegalAccessException e) {
        } catch (InstantiationException e) {
        }
    }

protected void loadNewFunction ( String name ) { try { String fullName = prefix + name ; Class value = Class . forName ( fullName ) ; if ( ( ServerSideFunction . class ) . isAssignableFrom ( value ) ) { add ( ( ServerSideFunction ) value . newInstance ( ) ) ; return ; } } catch ( ClassNotFoundException e ) { } catch ( IllegalAccessException e ) { } catch ( InstantiationException e ) { } }

Tries to load a function with the given name.

Tries to load a function with the given name .


public final String getLevelName(GridRecord gr) {

    if (cust != null) {
      String result = cust.getLevelNameShort( gr.getLevelType1());
      if (result != null) return result;
    }

    String levelUnit = getLevelUnit(gr);
    if (levelUnit != null) {
      int level1 = (int) gr.getLevel1();
      int level2 = (int) gr.getLevel2();
      if (levelUnit.equalsIgnoreCase("hPa")) {
        return "pressure";
      } else if (level1 == 1013) {
        return "mean sea level";
      } else if (level1 == 0) {
        return "tropopause";
      } else if (level1 == 1001) {
        return "surface";
      } else if (level2 != 0) {
        return "layer";
      }
    }

    return "";
  }

public
final
String
getLevelName
(
GridRecord
gr
)
{
if
(
cust
!=
)
{
String
result
=
cust
.
getLevelNameShort
(
gr
.
getLevelType1
(
)
)
;
if
(
result
!=
)
return
result
;
}
String
levelUnit
=
getLevelUnit
(
gr
)
;
if
(
levelUnit
!=
)
{
int
level1
=
(
int
)
gr
.
getLevel1
(
)
;
int
level2
=
(
int
)
gr
.
getLevel2
(
)
;
if
(
levelUnit
.
equalsIgnoreCase
(
"hPa"
)
)
{
return
"pressure"
;
}
else
if
(
level1
==
1013
)
{
return
"mean sea level"
;
}
else
if
(
level1
==
0
)
{
return
"tropopause"
;
}
else
if
(
level1
==
1001
)
{
return
"surface"
;
}
else
if
(
level2
!=
0
)
{
return
"layer"
;
}
}
return
""
;
}


public final String getLevelDescription(GridRecord gr) {
    if (cust != null) {
      String result = cust.getLevelDescription( gr.getLevelType1());
      if (result != null) return result;
    }

    // TODO:  flesh this out
    return getLevelName(gr);
  }

public
final
String
getLevelDescription
(
GridRecord
gr
)
{
if
(
cust
!=
)
{
String
result
=
cust
.
getLevelDescription
(
gr
.
getLevelType1
(
)
)
;
if
(
result
!=
)
return
result
;
}
// TODO:  flesh this out
return
getLevelName
(
gr
)
;
}


public final String getLevelUnit(GridRecord gr) {
    if (cust != null) {
      String result = cust.getLevelUnits( gr.getLevelType1());
      if (result != null) return result;
    }

    return visad.jmet.MetUnits.makeSymbol(((McIDASGridRecord) gr).getLevelUnitName());
  }

public final String getLevelUnit ( GridRecord gr ) { if ( cust != null ) { String result = cust . getLevelUnits ( gr . getLevelType1 ( ) ) ; if ( result != null ) return result ; } return visad . jmet . MetUnits . makeSymbol ( ( ( McIDASGridRecord ) gr ) . getLevelUnitName ( ) ) ; }


public final int getProjectionType(GridDefRecord gds) {
    String name = getProjectionName(gds).trim();
    switch (name) {
      case "MERC":
        return Mercator;
      case "CONF":
        return LambertConformal;
      case "PS":
        return PolarStereographic;
      default:
        return -1;
    }
  }

public final int getProjectionType ( GridDefRecord gds ) { String name = getProjectionName ( gds ) . trim ( ) ; switch ( name ) { case "MERC" : return Mercator ; case "CONF" : return LambertConformal ; case "PS" : return PolarStereographic ; default : return - 1 ; } }


public final boolean isVerticalCoordinate(GridRecord gr) {
    if (cust != null) {
      return cust.isVerticalCoordinate(gr.getLevelType1());
    }

    int type = gr.getLevelType1();
    if (((McIDASGridRecord) gr).hasGribInfo()) {

      if (type == 20) {
        return true;
      }
      if (type == 100) {
        return true;
      }
      if (type == 101) {
        return true;
      }
      if ((type >= 103) && (type <= 128)) {
        return true;
      }
      if (type == 141) {
        return true;
      }
      if (type == 160) {
        return true;
      }
    } else if (getLevelUnit(gr).equals("hPa")) {
      return true;
    }
    return false;
  }

public final boolean isVerticalCoordinate ( GridRecord gr ) { if ( cust != null ) { return cust . isVerticalCoordinate ( gr . getLevelType1 ( ) ) ; } int type = gr . getLevelType1 ( ) ; if ( ( ( McIDASGridRecord ) gr ) . hasGribInfo ( ) ) { if ( type == 20 ) { return true ; } if ( type == 100 ) { return true ; } if ( type == 101 ) { return true ; } if ( ( type >= 103 ) && ( type <= 128 ) ) { return true ; } if ( type == 141 ) { return true ; } if ( type == 160 ) { return true ; } } else if ( getLevelUnit ( gr ) . equals ( "hPa" ) ) { return true ; } return false ; }


public boolean isLayer(GridRecord gr) {
    if (cust != null) {
      return cust.isLayer( gr.getLevelType1());
    }

    if (gr.getLevel2() == 0) {
      return false;
    }
    return true;
  }

public boolean isLayer ( GridRecord gr ) { if ( cust != null ) { return cust . isLayer ( gr . getLevelType1 ( ) ) ; } if ( gr . getLevel2 ( ) == 0 ) { return false ; } return true ; }

Is this a layer?

@param gr record to check
@return true if a layer


static public CoordinateTransform makeCoordinateTransform (NetcdfDataset ds, AttributeContainer ctv, Formatter parseInfo, Formatter errInfo) {
    // standard name
    String transform_name = ctv.findAttValueIgnoreCase("transform_name", null);
    if (null == transform_name)
      transform_name = ctv.findAttValueIgnoreCase("Projection_Name", null);

    // these names are from CF - dont want to have to duplicate
    if (null == transform_name)
      transform_name = ctv.findAttValueIgnoreCase(CF.GRID_MAPPING_NAME, null);
    if (null == transform_name)
      transform_name = ctv.findAttValueIgnoreCase(CF.STANDARD_NAME, null);

    if (null == transform_name) {
      parseInfo.format("**Failed to find Coordinate Transform name from Variable= %s%n", ctv);
      return null;
    }

    transform_name = transform_name.trim();

    // do we have a transform registered for this ?
    Class builderClass = null;
    for (Transform transform : transformList) {
      if (transform.transName.equals(transform_name)) {
        builderClass = transform.transClass;
        break;
      }
    }
    if (null == builderClass) {
      parseInfo.format("**Failed to find CoordTransBuilder name= %s from Variable= %s%n", transform_name, ctv);
      return null;
    }

         // get an instance of that class
    Object builderObject;
    try {
      builderObject = builderClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      log.error("Cant create new instance "+builderClass.getName(), e);
      return null;
    }

    if (null == builderObject) { // cant happen - because this was tested in registerTransform()
      parseInfo.format("**Failed to build CoordTransBuilder object from class= %s for Variable= %s%n", builderClass.getName(), ctv);
      return null;
    }

    CoordinateTransform ct;
    if (builderObject instanceof VertTransformBuilderIF){
      VertTransformBuilderIF vertBuilder = (VertTransformBuilderIF) builderObject;
      vertBuilder.setErrorBuffer(errInfo);
      ct = vertBuilder.makeCoordinateTransform(ds, ctv);

    } else if (builderObject instanceof HorizTransformBuilderIF){
      HorizTransformBuilderIF horizBuilder = (HorizTransformBuilderIF) builderObject;
      horizBuilder.setErrorBuffer(errInfo);
      String units = AbstractTransformBuilder.getGeoCoordinateUnits(ds, ctv); // barfola
      ct = horizBuilder.makeCoordinateTransform(ctv, units);

    } else {
      log.error("Illegals class "+builderClass.getName());
      return null;
    }

    if (ct != null) {
      parseInfo.format(" Made Coordinate transform %s from variable %s: %s%n", transform_name, ctv.getName(), builderObject.getClass().getName());
    }

    return ct;
  }

Make a CoordinateTransform object from the parameters in a Coordinate Transform Variable, using an intrinsic or registered CoordTransBuilder.
@param ds enclosing dataset, only used for vertical transforms
@param ctv the Coordinate Transform Variable - container for the transform parameters
@param parseInfo pass back information about the parsing.
@param errInfo pass back error information.
@return CoordinateTransform, or null if failure.

Make a CoordinateTransform object from the parameters in a Coordinate Transform Variable using an intrinsic or registered CoordTransBuilder .


static public VariableDS makeDummyTransformVariable(NetcdfDataset ds, CoordinateTransform ct) {
    VariableDS v = new VariableDS( ds, null, null, ct.getName(), DataType.CHAR, "", null, null);
    List<Parameter> params = ct.getParameters();
    for (Parameter p : params) {
      if (p.isString())
        v.addAttribute(new Attribute(p.getName(), p.getStringValue()));
      else {
        double[] data = p.getNumericValues();
        Array dataA = Array.factory(DataType.DOUBLE, new int[]{data.length}, data);
        v.addAttribute(new Attribute(p.getName(), dataA));
      }
    }
    v.addAttribute( new Attribute(_Coordinate.TransformType, ct.getTransformType().toString()));

    // fake data
    Array data = Array.factory(DataType.CHAR, new int[] {}, new char[] {' '});
    v.setCachedData(data, true);

    return v;
  }

static
public
VariableDS
makeDummyTransformVariable
(
NetcdfDataset
ds
,
CoordinateTransform
ct
)
{
VariableDS
v
=
new
VariableDS
(
ds
,
,
,
ct
.
getName
(
)
,
DataType
.
CHAR
,
""
,
,
)
;
List
<
Parameter
>
params
=
ct
.
getParameters
(
)
;
for
(
Parameter
p
:
params
)
{
if
(
p
.
isString
(
)
)
v
.
addAttribute
(
new
Attribute
(
p
.
getName
(
)
,
p
.
getStringValue
(
)
)
)
;
else
{
double
[
]
data
=
p
.
getNumericValues
(
)
;
Array
dataA
=
Array
.
factory
(
DataType
.
DOUBLE
,
new
int
[
]
{
data
.
length
}
,
data
)
;
v
.
addAttribute
(
new
Attribute
(
p
.
getName
(
)
,
dataA
)
)
;
}
}
v
.
addAttribute
(
new
Attribute
(
_Coordinate
.
TransformType
,
ct
.
getTransformType
(
)
.
toString
(
)
)
)
;
// fake data
Array
data
=
Array
.
factory
(
DataType
.
CHAR
,
new
int
[
]
{
}
,
new
char
[
]
{
'
'
}
)
;
v
.
setCachedData
(
data
,
true
)
;
return
v
;
}

Create a "dummy" Coordinate Transform Variable based on the given CoordinateTransform.
This creates a scalar Variable with dummy data, and adds the Parameters of the CoordinateTransform
as attributes.
@param ds for this dataset
@param ct based on the CoordinateTransform
@return the Coordinate Transform Variable. You must add it to the dataset.

Create a dummy Coordinate Transform Variable based on the given CoordinateTransform . This creates a scalar Variable with dummy data and adds the Parameters of the CoordinateTransform as attributes .


static public ProjectionImpl makeProjection(CoverageTransform gct, Formatter errInfo) {
    // standard name
    String transform_name = gct.findAttValueIgnoreCase(CF.GRID_MAPPING_NAME, null);

    if (null == transform_name) {
      errInfo.format("**Failed to find Coordinate Transform name from GridCoordTransform= %s%n", gct);
      return null;
    }

    transform_name = transform_name.trim();

    // do we have a transform registered for this ?
    Class builderClass = null;
    for (Transform transform : transformList) {
      if (transform.transName.equals(transform_name)) {
        builderClass = transform.transClass;
        break;
      }
    }
    if (null == builderClass) {
      errInfo.format("**Failed to find CoordTransBuilder name= %s from GridCoordTransform= %s%n", transform_name, gct);
      return null;
    }

      // get an instance of that class
    HorizTransformBuilderIF builder;
    try {
      builder = (HorizTransformBuilderIF) builderClass.newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
      log.error("Cant create new instance "+builderClass.getName(), e);
      return null;
    }
    if (null == builder) { // cant happen - because this was tested in registerTransform()
      errInfo.format("**Failed to build CoordTransBuilder object from class= %s for GridCoordTransform= %s%n", builderClass.getName(), gct);
      return null;
    }

    String units = gct.findAttValueIgnoreCase(CDM.UNITS, null);
    builder.setErrorBuffer( errInfo);
    ProjectionCT ct = builder.makeCoordinateTransform(gct, units);
    assert ct != null;

    return ct.getProjection();
  }

Make a CoordinateTransform object from the parameters in a GridCoordTransform, using an intrinsic or
registered CoordTransBuilder.
@param errInfo pass back error information.
@return CoordinateTransform, or null if failure.

Make a CoordinateTransform object from the parameters in a GridCoordTransform using an intrinsic or registered CoordTransBuilder .


public static void main(String args[]) {
    boolean usePopup = false;

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-usePopup"))
        usePopup = true;
    }

    try {
      store = XMLStore.createFromFile("ThreddsDatasetChooser", null);
      p = store.getPreferences();
    } catch (IOException e) {
      System.out.println("XMLStore Creation failed " + e);
    }

    // put it together in a JFrame
    final JFrame frame = new JFrame("Thredds Dataset Chooser");
    frame.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        chooser.save();
        Rectangle bounds = frame.getBounds();
        p.putBeanObject(FRAME_SIZE, bounds);
        try {
          store.save();
        } catch (IOException ioe) {
          ioe.printStackTrace();
        }

        System.exit(0);
      }
    });

    chooser = new ThreddsDatasetChooser(p, null, frame, true, usePopup, false);
    chooser.setDoResolve(true);

    //
    frame.getContentPane().add(chooser);
    Rectangle bounds = (Rectangle) p.getBean(FRAME_SIZE, new Rectangle(50, 50, 800, 450));
    frame.setBounds(bounds);

    frame.pack();
    frame.setBounds(bounds);
    frame.setVisible(true);
  }

public
static
void
main
(
String
args
[
]
)
{
boolean
usePopup
=
false
;
for
(
int
i
=
0
;
i
<
args
.
length
;
i
++
)
{
if
(
args
[
i
]
.
equals
(
"-usePopup"
)
)
usePopup
=
true
;
}
try
{
store
=
XMLStore
.
createFromFile
(
"ThreddsDatasetChooser"
,
)
;
p
=
store
.
getPreferences
(
)
;
}
catch
(
IOException
e
)
{
System
.
out
.
println
(
"XMLStore Creation failed "
+
e
)
;
}
// put it together in a JFrame
final
JFrame
frame
=
new
JFrame
(
"Thredds Dataset Chooser"
)
;
frame
.
addWindowListener
(
new
WindowAdapter
(
)
{
public
void
windowClosing
(
WindowEvent
e
)
{
chooser
.
save
(
)
;
Rectangle
bounds
=
frame
.
getBounds
(
)
;
p
.
putBeanObject
(
FRAME_SIZE
,
bounds
)
;
try
{
store
.
save
(
)
;
}
catch
(
IOException
ioe
)
{
ioe
.
printStackTrace
(
)
;
}
System
.
exit
(
0
)
;
}
}
)
;
chooser
=
new
ThreddsDatasetChooser
(
p
,
,
frame
,
true
,
usePopup
,
false
)
;
chooser
.
setDoResolve
(
true
)
;
//
frame
.
getContentPane
(
)
.
add
(
chooser
)
;
Rectangle
bounds
=
(
Rectangle
)
p
.
getBean
(
FRAME_SIZE
,
new
Rectangle
(
50
,
50
,
800
,
450
)
)
;
frame
.
setBounds
(
bounds
)
;
frame
.
pack
(
)
;
frame
.
setBounds
(
bounds
)
;
frame
.
setVisible
(
true
)
;
}

Standalone application.

@param args recognized values:
<ul> <li> -usePopup to popup messages </ul>


public void save() {
    collectionNameTable.saveState(false);
    dataTable.saveState(false);
    prefs.putBeanObject("InfoWindowBounds", infoWindow.getBounds());
    prefs.putInt("splitPos", split.getDividerLocation());
  }

public void save ( ) { collectionNameTable . saveState ( false ) ; dataTable . saveState ( false ) ; prefs . putBeanObject ( "InfoWindowBounds" , infoWindow . getBounds ( ) ) ; prefs . putInt ( "splitPos" , split . getDividerLocation ( ) ) ; }


@Override
    public final Chronology withZone(DateTimeZone zone) {
        if (zone.equals(DateTimeZone.UTC)) return this.withUTC();
        throw new UnsupportedOperationException("Not supported yet.");
    }

@
Override
public
final
Chronology
withZone
(
DateTimeZone
zone
)
{
if
(
zone
.
equals
(
DateTimeZone
.
UTC
)
)
return
this
.
withUTC
(
)
;
throw
new
UnsupportedOperationException
(
"Not supported yet."
)
;
}

Throws UnsupportedOperationException unless the time zone is UTC


public void
    writeCount(long count)
            throws IOException
    {
        countbuffer.clear();
        countbuffer.putLong(count);
        byte[] countbuf = countbuffer.array();
        int len = countbuffer.position();
        writeBytes(countbuf, len);
        if(DEBUG) {
            System.err.printf("count: %d%n", count);
        }
    }

public
void
writeCount
(
long
count
)
throws
IOException
{
countbuffer
.
clear
(
)
;
countbuffer
.
putLong
(
count
)
;
byte
[
]
countbuf
=
countbuffer
.
array
(
)
;
int
len
=
countbuffer
.
position
(
)
;
writeBytes
(
countbuf
,
len
)
;
if
(
DEBUG
)
{
System
.
err
.
printf
(
"count: %d%n"
,
count
)
;
}
}

Write out a prefix count

@param count the count to write out
@throws IOException


public void
    writeAtomicArray(DapType daptype, Object values)
            throws IOException
    {
        assert values != null && values.getClass().isArray();
        ByteBuffer buf = SerialWriter.encodeArray(daptype, values, this.order);
        byte[] bytes = buf.array();
        int len = buf.position();
        writeBytes(bytes, len);
        if(DEBUG) {
            System.err.printf("%s: ", daptype.getShortName());
            for(int i = 0; i < len; i++) {
                int x = (int) (order == ByteOrder.BIG_ENDIAN ? bytes[i] : bytes[(len - 1) - i]);
                System.err.printf("%02x", (int) (x & 0xff));
            }
            System.err.println();
        }
    }

public
void
writeAtomicArray
(
DapType
daptype
,
Object
values
)
throws
IOException
{
assert
values
!=
&&
values
.
getClass
(
)
.
isArray
(
)
;
ByteBuffer
buf
=
SerialWriter
.
encodeArray
(
daptype
,
values
,
this
.
order
)
;
byte
[
]
bytes
=
buf
.
array
(
)
;
int
len
=
buf
.
position
(
)
;
writeBytes
(
bytes
,
len
)
;
if
(
DEBUG
)
{
System
.
err
.
printf
(
"%s: "
,
daptype
.
getShortName
(
)
)
;
for
(
int
i
=
0
;
i
<
len
;
i
++
)
{
int
x
=
(
int
)
(
order
==
ByteOrder
.
BIG_ENDIAN
bytes
[
i
]
:
bytes
[
(
len
1
)
i
]
)
;
System
.
err
.
printf
(
"%02x"
,
(
int
)
(
x
&
0xff
)
)
;
}
System
.
err
.
println
(
)
;
}
}

Write out an array of atomic values

@param daptype type of the values
@param values the array of values
@throws IOException


public void
    writeBytes(byte[] bytes, int len)
            throws IOException
    {
        outputBytes(bytes, 0, len);
        if(this.checksummode.enabled(ChecksumMode.DAP)) {
            this.checksum.update(bytes, 0, len);
            if(DUMPCSUM) {
                System.err.print("SSS ");
                for(int i = 0; i < len; i++) {
                    System.err.printf("%02x", bytes[i]);
                }
                System.err.println();
            }
        }
    }

public
void
writeBytes
(
byte
[
]
bytes
,
int
len
)
throws
IOException
{
outputBytes
(
bytes
,
0
,
len
)
;
if
(
this
.
checksummode
.
enabled
(
ChecksumMode
.
DAP
)
)
{
this
.
checksum
.
update
(
bytes
,
0
,
len
)
;
if
(
DUMPCSUM
)
{
System
.
err
.
print
(
"SSS "
)
;
for
(
int
i
=
0
;
i
<
len
;
i
++
)
{
System
.
err
.
printf
(
"%02x"
,
bytes
[
i
]
)
;
}
System
.
err
.
println
(
)
;
}
}
}

Write out a set of bytes

@param bytes
@param len
@throws IOException


public void
    outputBytes(byte[] bytes, int start, int count)
            throws IOException
    {
        if(DUMPDATA) {
            System.err.printf("output %d/%d:", start, count);
            for(int i = 0; i < count; i++) {
                System.err.printf(" %02x", bytes[i]);
            }
            System.err.println("");
            System.err.flush();
        }
        output.write(bytes, start, count);
    }

public
void
outputBytes
(
byte
[
]
bytes
,
int
start
,
int
count
)
throws
IOException
{
if
(
DUMPDATA
)
{
System
.
err
.
printf
(
"output %d/%d:"
,
start
,
count
)
;
for
(
int
i
=
0
;
i
<
count
;
i
++
)
{
System
.
err
.
printf
(
" %02x"
,
bytes
[
i
]
)
;
}
System
.
err
.
println
(
""
)
;
System
.
err
.
flush
(
)
;
}
output
.
write
(
bytes
,
start
,
count
)
;
}

Deliberate choke point for debugging

@param bytes
@param start
@param count
@throws IOException


void finishInit() {

      // some widgets from the GridUI
    np = ui.panz;
    vertPanel = ui.vertPanel;
    dataValueLabel = ui.dataValueLabel;
    posLabel = ui.positionLabel;

      // get last saved Projection
    project = (ProjectionImpl) store.getBean(LastProjectionName, null);
    if (project != null)
      setProjection( project);

      // get last saved MapArea
    ProjectionRect ma = (ProjectionRect) store.getBean(LastMapAreaName, null);
    if (ma != null)
      np.setMapArea( ma);

    makeEventManagement();

    // last thing
    /* get last dataset filename and reopen it
    String filename = (String) store.get(LastDatasetName);
    if (filename != null)
      setDataset(filename); */
  }


static public CalendarDateRange of(DateRange dr) {
    if (dr == null) return null;
    return CalendarDateRange.of( dr.getStart().getDate(), dr.getEnd().getDate());
  }

static public CalendarDateRange of ( DateRange dr ) { if ( dr == null ) return null ; return CalendarDateRange . of ( dr . getStart ( ) . getDate ( ) , dr . getEnd ( ) . getDate ( ) ) ; }

Does not handle non-standard calendars
@deprecated

Does not handle non - standard calendars


public static Grib2Gds factory(int template, byte[] data) {
    Grib2Gds result;
    switch (template) {
      case 0:
        result = new LatLon(data);
        break;
      case 1:
        result = new RotatedLatLon(data);
        break;
      case 10:
        result = new Mercator(data);
        break;
      case 20:
        result = new PolarStereographic(data);
        break;
      case 30:
        result = new LambertConformal(data, 30);
        break;
      case 31:
        result = new AlbersEqualArea(data);
        break;
      case 40:
        result = new GaussLatLon(data);
        break;
      case 50:  // Spherical Harmonic Coefficients BOGUS
        result = new GdsSpherical(data, template);
        break;
      case 90:
        result = new SpaceViewPerspective(data);
        break;

      // LOOK NCEP specific
      case 204:
        result = new CurvilinearOrthogonal(data);
        break;
      case 32769:
        result = new RotatedLatLon32769(data);
        break;

      default:
        throw new UnsupportedOperationException("Unsupported GDS type = " + template);
    }

    result.finish(); // stuff that cant be done in the constructor
    return result;
  }

reletive error in position - GRIB numbers sometimes miscoded


public int
    ddsparse(String text, DDS dds) throws ParseException
    {
        return dapparse(text, dds, null, null);
    }

public int ddsparse ( String text , DDS dds ) throws ParseException { return dapparse ( text , dds , null , null ) ; }


public int
    dasparse(String text, DAS das)
            throws ParseException
    {
        return dapparse(text, null, das, null);
    }

public int dasparse ( String text , DAS das ) throws ParseException { return dapparse ( text , null , das , null ) ; }


private void swapGridHeader(int[] gh) {
    McIDASUtil.flip(gh, 0, 5);
    McIDASUtil.flip(gh, 7, 7);
    McIDASUtil.flip(gh, 9, 10);
    McIDASUtil.flip(gh, 12, 14);
    McIDASUtil.flip(gh, 32, 51);
  }

private void swapGridHeader ( int [ ] gh ) { McIDASUtil . flip ( gh , 0 , 5 ) ; McIDASUtil . flip ( gh , 7 , 7 ) ; McIDASUtil . flip ( gh , 9 , 10 ) ; McIDASUtil . flip ( gh , 12 , 14 ) ; McIDASUtil . flip ( gh , 32 , 51 ) ; }

Swap the grid header, avoiding strings

@param gh grid header to swap


public float[] readGrid(McIDASGridRecord gr) throws IOException {

    float[] data;
    //try {
      int te = (gr.getOffsetToHeader() + 64) * 4;
      int rows = gr.getRows();
      int cols = gr.getColumns();
      rf.seek(te);

      float scale = (float) gr.getParamScale();

      data = new float[rows * cols];
      rf.order(needToSwap ? RandomAccessFile.LITTLE_ENDIAN : RandomAccessFile.BIG_ENDIAN);
      // int n = 0;
      // store such that 0,0 is in lower left corner...
      for (int nc = 0; nc < cols; nc++) {
        for (int nr = 0; nr < rows; nr++) {
          int temp = rf.readInt();  // check for missing value
          data[(rows - nr - 1) * cols + nc] = (temp
                  == McIDASUtil.MCMISSING)
                  ? Float.NaN
                  : ((float) temp) / scale;
        }
      }
      rf.order(RandomAccessFile.BIG_ENDIAN);
    //} catch (Exception esc) {
    //  System.out.println(esc);
    //}
    return data;
  }

Read the grid

@param gr the grid record
@return the data


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

  }

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

for testing purposes

@param args file name
@throws IOException problem reading file


private void writeAConstraint(String name, boolean isImplemented) {

		String defValue;

		if(isImplemented) defValue = "TRUE"; else defValue = "FALSE";

		fileOutput += "<ows:Constraint name=\"" + name + "\"> "
				+ "<ows:NoValues/> "
				+ "<ows:DefaultValue>" + defValue +"</ows:DefaultValue> "
						+ "</ows:Constraint>";
	}

private
void
writeAConstraint
(
String
name
,
boolean
isImplemented
)
{
String
defValue
;
if
(
isImplemented
)
defValue
=
"TRUE"
;
else
defValue
=
"FALSE"
;
fileOutput
+=
"<ows:Constraint name=\""
+
name
+
"\"> "
+
"<ows:NoValues/> "
+
"<ows:DefaultValue>"
+
defValue
+
"</ows:DefaultValue> "
+
"</ows:Constraint>"
;
}

Writes a constraint OWS element out.

@param name of the constraint
@boolean isImplemented or not


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


public void writeOperations() {
		fileOutput += "<ows:OperationsMetadata> ";
		for(WFSRequestType rt : operationList) {
			writeAOperation(rt);
		}

		// Write parameters
		fileOutput += "<ows:Parameter name=\"AcceptVersions\"> "
				+ "<ows:AllowedValues> "
				+ "<ows:Value>2.0.0</ows:Value>"
				+ "</ows:AllowedValues>"
				+ "</ows:Parameter>";

		fileOutput += "<ows:Parameter name=\"AcceptFormats\">"
				+ "<ows:AllowedValues> "
				+ "<ows:Value>text/xml</ows:Value>"
				+ "</ows:AllowedValues>"
				+ "</ows:Parameter>";

		fileOutput += "<ows:Parameter name=\"Sections\"> "
				+ "<ows:AllowedValues> "
				+ "<ows:Value>ServiceIdentification</ows:Value> "
				+ "<ows:Value>ServiceProvider</ows:Value> "
				+ "<ows:Value>OperationsMetadata</ows:Value> "
				+ "<ows:Value>FeatureTypeList</ows:Value> "
				+ "</ows:AllowedValues>"
				+ "</ows:Parameter>";

		fileOutput += "<ows:Parameter name=\"version\"> "
				+ "<ows:AllowedValues> "
				+ "<ows:Value>2.0.0</ows:Value>"
				+ "</ows:AllowedValues>"
				+ "</ows:Parameter>";

		// Write constraints
		writeAConstraint("ImplementsBasicWFS", true);
		writeAConstraint("ImplementsTransactionalWFS", false);
		writeAConstraint("ImplementsLockingWFS", false);
		writeAConstraint("KVPEncoding", false);
		writeAConstraint("XMLEncoding", true);
		writeAConstraint("SOAPEncoding", false);
		writeAConstraint("ImplementsInheritance", false);
		writeAConstraint("ImplementsRemoteResolve", false);
		writeAConstraint("ImplementsResultPaging", false);
		writeAConstraint("ImplementsStandardJoins", false);
		writeAConstraint("ImplementsSpatialJoins", false);
		writeAConstraint("ImplementsTemporalJoins", false);
		writeAConstraint("ImplementsFeatureVersioning", false);
		writeAConstraint("ManageStoredQueries", false);
		writeAConstraint("PagingIsTransactionSafe", false);
		writeAConstraint("QueryExpressions", false);

		fileOutput += "</ows:OperationsMetadata>";
	}

Takes all added operations and writes an operations metadata section.

Takes all added operations and writes an operations metadata section .


public void readAll(File dir, FileFilter ff, Closure closure, LogFilter logf, Stats stat) throws IOException {
    File[] files = dir.listFiles();
    if (files == null) {
      System.out.printf("Dir has no files= %s%n", dir);
      return;
    }
    List<File> list = Arrays.asList(files);
    Collections.sort(list);

    for (File f : list) {
      if ((ff != null) && !ff.accept(f)) continue;
      if (f.isDirectory())
        readAll(f, ff, closure, logf, stat);
      else
        scanLogFile(f, closure, logf, stat);
    }
  }

public
void
readAll
(
File
dir
,
FileFilter
ff
,
Closure
closure
,
LogFilter
logf
,
Stats
stat
)
throws
IOException
{
File
[
]
files
=
dir
.
listFiles
(
)
;
if
(
files
==
)
{
System
.
out
.
printf
(
"Dir has no files= %s%n"
,
dir
)
;
return
;
}
List
<
File
>
list
=
Arrays
.
asList
(
files
)
;
Collections
.
sort
(
list
)
;
for
(
File
f
:
list
)
{
if
(
(
ff
!=
)
&&
!
ff
.
accept
(
f
)
)
continue
;
if
(
f
.
isDirectory
(
)
)
readAll
(
f
,
ff
,
closure
,
logf
,
stat
)
;
else
scanLogFile
(
f
,
closure
,
logf
,
stat
)
;
}
}

Read all the files in a directory and process them. Files are sorted by filename.
@param dir read from this directory
@param ff files must pass this filter (may be null)
@param closure send each Log to this closure
@param logf filter out these Logs (may be null)
@param stat accumulate statistics (may be null)
@throws IOException on read error

Read all the files in a directory and process them . Files are sorted by filename .


public void scanLogFile(File file, Closure closure, LogFilter logf, Stats stat) throws IOException {
    try (InputStream ios = new FileInputStream(file)) {
      System.out.printf("-----Reading %s %n", file.getPath());

      BufferedReader dataIS = new BufferedReader(new InputStreamReader(ios,
              CDM.utf8Charset), 40 * 1000);
      int total = 0;
      int count = 0;
      while ((maxLines < 0) || (count < maxLines)) {
        Log log = parser.nextLog(dataIS);
        if (log == null) break;
        total++;

        if ((logf != null) && !logf.pass(log)) continue;

        closure.process(log);
        count++;
      }

      if (stat != null) {
        stat.total += total;
        stat.passed += count;
      }

      System.out.printf("----- %s total requests=%d passed=%d %n", file.getPath(), total, count);
    }
  }

Read a log file.
@param file file to read
@param closure send each Log to this closure
@param logf filter out these Logs (may be null)
@param stat accumulate statistics (may be null)
@throws IOException on read error


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

Get the grid packing type

@param gridNumber grid number
@return packing type or error number
@throws IOException problem reading file


public GempakGridRecord findGrid(String parm) {
    List<GridRecord> gridList = gridIndex.getGridRecords();
    if (gridList == null) {
      return null;
    }
    for (GridRecord grid : gridList) {
      GempakGridRecord gh = (GempakGridRecord) grid;
      if (gh.param.trim().equals(parm)) {
        return gh;
      }
    }
    return null;
  }

public GempakGridRecord findGrid ( String parm ) { List < GridRecord > gridList = gridIndex . getGridRecords ( ) ; if ( gridList == null ) { return null ; } for ( GridRecord grid : gridList ) { GempakGridRecord gh = ( GempakGridRecord ) grid ; if ( gh . param . trim ( ) . equals ( parm ) ) { return gh ; } } return null ; }

Find the first grid with this name

@param parm name of grid
@return the grid header or null


public float[] DM_RPKG(int isword, int nword, int decimalScale)
          throws IOException {
    // from DM_RPKG
    // read the data packing type
    float[] data;
    int ipktyp = DM_RINT(isword);
    int iiword = isword + 1;
    int lendat = nword - 1;
    if (ipktyp == MDGNON) {  // no packing
      data = new float[lendat];
      DM_RFLT(iiword, data);
      return data;
    }
    int iiw;
    int irw;
    if (ipktyp == MDGDIF) {
      iiw = 4;
      irw = 3;
    } else if (ipktyp == MDGRB2) {
      iiw = 4;
      irw = 1;
    } else {
      iiw = 3;
      irw = 2;
    }
    int[] iarray = new int[iiw];
    float[] rarray = new float[irw];
    DM_RINT(iiword, iarray);
    iiword = iiword + iiw;
    lendat = lendat - iiw;
    DM_RFLT(iiword, rarray);
    iiword = iiword + irw;
    lendat = lendat - irw;

    if (ipktyp == MDGRB2) {
      data = unpackGrib2Data(iiword, lendat, iarray, rarray);
      return data;
    }
    int nbits = iarray[0];
    int misflg = iarray[1];
    boolean miss = misflg != 0;
    int kxky = iarray[2];
    // int mword = kxky;
    int kx = 0;
    if (iiw == 4) {
      kx = iarray[3];
    }
    float ref = rarray[0];
    float scale = rarray[1];
    float difmin = 0;
    if (irw == 3) {
      difmin = rarray[2];
    }
    data = unpackData(iiword, lendat, ipktyp, kxky, nbits, ref, scale,
            miss, difmin, kx, decimalScale);
    return data;

  }

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

Unpack a packed grid

@param isword       starting word (1 based)
@param nword        number of words to read
@param decimalScale decimal scale
@return array of unpacked data or null;
@throws IOException problem reading data


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

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

Read packed data

@param iiword       Starting word  (FORTRAN 1 based)
@param nword        Number of words
@param ipktyp       Packing type
@param kxky         Number of grid points
@param nbits        Number of bits
@param ref          Reference minimum value of grid
@param scale        Scaling factor
@param miss         Missing data flag
@param difmin       Minimum value of differences
@param kx           Number of points in x direction
@param decimalScale scale of the values for the units
@return unpacked data
@throws IOException problem reading file


private synchronized float[] DP_UGRB(int[] idata, int kxky, int nbits,
                                       float qmin, float scale,
                                       boolean misflg, int decimalScale)
          throws IOException {
    float scaleFactor = (decimalScale == 0)
            ? 1.f
            : (float) Math.pow(10.0, -decimalScale);
    //
    //Check for valid input.
    //
    float[] grid = new float[kxky];
    if ((nbits <= 1) || (nbits > 31)) {
      return grid;
    }
    if (scale == 0.) {
      return grid;
    }

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

Unpack grib data packed into ints

@param idata        int array of packed data
@param kxky         number of output points
@param nbits        number of bits per point
@param qmin         minimum (reference) value
@param scale        parameter scale
@param misflg       missing flag
@param decimalScale scale of value to jive with units
@return the array of unpacked values
@throws IOException problem reading from the file


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

Read packed Grib1 data using ucar.grib code

@param iiword       Starting word  (FORTRAN 1 based)
@param nword        number of words
@param kxky         size of grid (kx*ky)
@param nbits        number of bits per word
@param ref          reference value
@param scale        scale value
@param miss         replace missing
@param decimalScale scale of the values
@return unpacked data
@throws IOException problem reading file

Read packed Grib1 data using ucar . grib code


private float[] unpackGrib2Data(int iiword, int lendat, int[] iarray, float[] rarray) throws IOException {

    long start = getOffset(iiword);
    rf.seek(start);
    Grib2Record gr = makeGribRecord(rf, start);
    float[] data = gr.readData(rf);

    if (((iarray[3] >> 6) & 1) == 0) {  // -y scanning - flip
      data = gb2_ornt(iarray[1], iarray[2], iarray[3], data);
    }

    return data;
  }

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

Read packed Grib2 data

@param iiword Starting word  (FORTRAN 1 based)
@param lendat Number of words
@param iarray integer packing info
@param rarray float packing info
@return unpacked data
@throws IOException problem reading file


public void printGrids() {
    List<GridRecord> gridList = gridIndex.getGridRecords();
    if (gridList == null)
      return;

    System.out.println("  NUM       TIME1              TIME2           LEVL1 LEVL2  VCORD PARM");
    for (GridRecord aGridList : gridList) {
      System.out.println(aGridList);
    }
  }


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

Get the next byte

@throws IOException problem reading the byte


public static CalendarDate of(Calendar cal, int year, int monthOfYear, int dayOfMonth, int hourOfDay, int minuteOfHour, int secondOfMinute) {
    Chronology base = Calendar.getChronology(cal);
    /* if (base == null)
      base = ISOChronology.getInstanceUTC(); // already in UTC
    else
      base = ZonedChronology.getInstance( base, DateTimeZone.UTC); // otherwise wrap it to be in UTC  */

    DateTime dt = new DateTime(year, monthOfYear, dayOfMonth, hourOfDay, minuteOfHour, secondOfMinute, base);
    if (!Calendar.isDefaultChronology(cal)) dt = dt.withChronology(Calendar.getChronology(cal));
    dt = dt.withZone(DateTimeZone.UTC);
    return new CalendarDate(cal, dt);
  }

Get Calendar date from fields. Uses UTZ time zone
@param cal calendar to use, or null for default
@param year any integer
@param monthOfYear 1-12
@param dayOfMonth 1-31
@param hourOfDay  0-23
@param minuteOfHour 0-59
@param secondOfMinute 0-59
@return CalendarDate

Get Calendar date from fields . Uses UTZ time zone


public static CalendarDate of(java.util.Date date) {
    DateTime dt = new DateTime(date, DateTimeZone.UTC) ;
    return new CalendarDate(null, dt);
  }

public static CalendarDate of ( java . util . Date date ) { DateTime dt = new DateTime ( date , DateTimeZone . UTC ) ; return new CalendarDate ( null , dt ) ; }

Create CalendarDate from a java.util.Date.
Uses standard Calendar.
@param date java.util.Date
@return CalendarDate in UTC

Create CalendarDate from a java . util . Date . Uses standard Calendar .


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

Create CalendarDate from msecs since epoch
Uses standard Calendar.
@param msecs milliseconds from 1970-01-01T00:00:00Z
@return CalendarDate in UTC

Create CalendarDate from msecs since epoch Uses standard Calendar .


public static CalendarDate of(Calendar cal, long msecs) {
    Chronology base = Calendar.getChronology(cal);
    DateTime dt = new DateTime(msecs, base) ;
    return new CalendarDate(cal, dt);
  }

public static CalendarDate of ( Calendar cal , long msecs ) { Chronology base = Calendar . getChronology ( cal ) ; DateTime dt = new DateTime ( msecs , base ) ; return new CalendarDate ( cal , dt ) ; }

Create CalendarDate from msecs since epoch
Uses the given  Calendar.
@param cal calendar to use, or null for default
@param msecs milliseconds from 1970-01-01T00:00:00Z
@return CalendarDate in UTC time zone.

Create CalendarDate from msecs since epoch Uses the given Calendar .


public static CalendarDate parseUdunits(String calendarName, String udunits) {
    int pos = udunits.indexOf(' ');
    if (pos < 0) return null;
    String valString = udunits.substring(0, pos).trim();
    String unitString = udunits.substring(pos+1).trim();

    CalendarDateUnit cdu = CalendarDateUnit.of(calendarName, unitString);
    double val = Double.parseDouble(valString);
    return cdu.makeCalendarDate(val);
  }

public static CalendarDate parseUdunits ( String calendarName , String udunits ) { int pos = udunits . indexOf ( ' ' ) ; if ( pos < 0 ) return null ; String valString = udunits . substring ( 0 , pos ) . trim ( ) ; String unitString = udunits . substring ( pos + 1 ) . trim ( ) ; CalendarDateUnit cdu = CalendarDateUnit . of ( calendarName , unitString ) ; double val = Double . parseDouble ( valString ) ; return cdu . makeCalendarDate ( val ) ; }

Get CalendarDate from udunit date string
@param calendarName get Calendar from Calendar.get(calendarName). may be null
@param udunits must be value (space) udunits string
@return  CalendarDate


public long getDifference(CalendarDate o, CalendarPeriod.Field fld) {
    switch (fld) {
      case Millisec:
        return getDifferenceInMsecs(o);
      case Second:
        return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_SECOND);
      case Minute:
        return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_MINUTE);
      case Hour:
        return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_HOUR);
      case Day:
        return (long) (getDifferenceInMsecs(o) / MILLISECS_IN_DAY);

      case Month:
        int tmonth = getFieldValue(CalendarPeriod.Field.Month);
        int omonth = o.getFieldValue(CalendarPeriod.Field.Month);
        int years = (int) this.getDifference(o, CalendarPeriod.Field.Year);
        return tmonth-omonth + 12 * years;

      case Year:
        int tyear = getFieldValue(CalendarPeriod.Field.Year);
        int oyear = o.getFieldValue(CalendarPeriod.Field.Year);
        return tyear - oyear;
    }
    return dateTime.getMillis() - o.dateTime.getMillis();
  }

public long getDifference ( CalendarDate o , CalendarPeriod . Field fld ) { switch ( fld ) { case Millisec : return getDifferenceInMsecs ( o ) ; case Second : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_SECOND ) ; case Minute : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_MINUTE ) ; case Hour : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_HOUR ) ; case Day : return ( long ) ( getDifferenceInMsecs ( o ) / MILLISECS_IN_DAY ) ; case Month : int tmonth = getFieldValue ( CalendarPeriod . Field . Month ) ; int omonth = o . getFieldValue ( CalendarPeriod . Field . Month ) ; int years = ( int ) this . getDifference ( o , CalendarPeriod . Field . Year ) ; return tmonth - omonth + 12 * years ; case Year : int tyear = getFieldValue ( CalendarPeriod . Field . Year ) ; int oyear = o . getFieldValue ( CalendarPeriod . Field . Year ) ; return tyear - oyear ; } return dateTime . getMillis ( ) - o . dateTime . getMillis ( ) ; }

Get difference between two calendar dates in given Field units
@param o  other calendar date
@return  (this minus o) difference in units of this Field


protected CDMArrayAtomic
    createAtomicVar(DataCursor data)
            throws DapException
    {
        CDMArrayAtomic array = new CDMArrayAtomic(data);
        return array;
    }

protected CDMArrayAtomic createAtomicVar ( DataCursor data ) throws DapException { CDMArrayAtomic array = new CDMArrayAtomic ( data ) ; return array ; }

Create an Atomic Valued variable.

@return An Array object wrapping d4var.
@throws DapException


public void setup(HttpServletRequest req, HttpServletResponse resp)
            throws SendError
    {
        this.req = req;
        this.res = resp;
        if(!once)
            doonce(req);

        // Parse any query parameters
        try {
            this.params = new DownloadParameters(req);
        } catch (IOException ioe) {
            throw new SendError(res.SC_BAD_REQUEST, ioe);
        }
    }

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


static protected String escapeString(String s)
    {
        StringBuilder buf = new StringBuilder();
        for(int i = 0; i < s.length(); i++) {
            int c = s.charAt(i);
            switch (c) {
            case '"':
                buf.append("\\\"");
                break;
            case '\\':
                buf.append("\\\\");
                break;
            case '\n':
                buf.append('\n');
                break;
            case '\r':
                buf.append('\r');
                break;
            case '\t':
                buf.append('\r');
                break;
            case '\f':
                buf.append('\f');
                break;
            default:
                if(c < ' ')
                    buf.append(String.format("\\x%02x", (c & 0xff)));
                else
                    buf.append((char) c);
                break;
            }
        }
        return buf.toString();
    }

static protected String escapeString ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; switch ( c ) { case ' ' : buf . append ( "\\\"" ) ; break ; case ' ' : buf . append ( "\\\\" ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; case ' ' : buf . append ( ' ' ) ; break ; default : if ( c < ' ' ) buf . append ( String . format ( "\\x%02x" , ( c & 0xff ) ) ) ; else buf . append ( ( char ) c ) ; break ; } } return buf . toString ( ) ; }

Given a typical string, insert backslashes
before '"' and '\\' characters and control characters.

Given a typical string insert backslashes before and \\ characters and control characters .


static public List<Slice>
    createSlices(List<Range> rangelist)
            throws dap4.core.util.DapException
    {
        List<Slice> slices = new ArrayList<Slice>(rangelist.size());
        for(int i = 0; i < rangelist.size(); i++) {
            Range r = rangelist.get(i);
            // r does not store last
            int stride = r.stride();
            int first = r.first();
            int n = r.length();
            int stop = first + (n * stride);
            Slice cer = new Slice(first, stop - 1, stride);
            slices.add(cer);
        }
        return slices;
    }

static
public
List
<
Slice
>
createSlices
(
List
<
Range
>
rangelist
)
throws
dap4
.
core
.
util
.
DapException
{
List
<
Slice
>
slices
=
new
ArrayList
<
Slice
>
(
rangelist
.
size
(
)
)
;
for
(
int
i
=
0
;
i
<
rangelist
.
size
(
)
;
i
++
)
{
Range
r
=
rangelist
.
get
(
i
)
;
// r does not store last
int
stride
=
r
.
stride
(
)
;
int
first
=
r
.
first
(
)
;
int
n
=
r
.
length
(
)
;
int
stop
=
first
+
(
n
*
stride
)
;
Slice
cer
=
new
Slice
(
first
,
stop
1
,
stride
)
;
slices
.
add
(
cer
)
;
}
return
slices
;
}

Convert a list of ucar.ma2.Range to a list of Slice
More or less the inverst of create CDMRanges

@param rangelist the set of ucar.ma2.Range
@result the equivalent list of Slice

Convert a list of ucar . ma2 . Range to a list of Slice More or less the inverst of create CDMRanges


static public NetcdfFile unwrapfile(NetcdfFile file)
    {
        for(; ; ) {
            if(file instanceof NetcdfDataset) {
                NetcdfDataset ds = (NetcdfDataset) file;
                file = ds.getReferencedFile();
                if(file == null) break;
            } else break;
        }
        return file;
    }

static public NetcdfFile unwrapfile ( NetcdfFile file ) { for ( ; ; ) { if ( file instanceof NetcdfDataset ) { NetcdfDataset ds = ( NetcdfDataset ) file ; file = ds . getReferencedFile ( ) ; if ( file == null ) break ; } else break ; } return file ; }

NetcdfDataset can wrap a NetcdfFile.
Goal of this procedure is to get down to the
lowest level NetcdfFile instance.

@param file NetcdfFile or NetcdfDataset
@return the lowest level NetcdfFile instance

NetcdfDataset can wrap a NetcdfFile . Goal of this procedure is to get down to the lowest level NetcdfFile instance .


static public boolean
    containsVLEN(List<Dimension> dimset)
    {
        if(dimset == null) return false;
        for(Dimension dim : dimset) {
            if(dim.isVariableLength())
                return true;
        }
        return false;
    }

static public boolean containsVLEN ( List < Dimension > dimset ) { if ( dimset == null ) return false ; for ( Dimension dim : dimset ) { if ( dim . isVariableLength ( ) ) return true ; } return false ; }

Test if any dimension is variable length


static public int[]
    computeEffectiveShape(List<DapDimension> dimset)
    {
        if(dimset == null || dimset.size() == 0)
            return new int[0];
        int effectiverank = dimset.size();
        int[] shape = new int[effectiverank];
        for(int i = 0; i < effectiverank; i++) {
            shape[i] = (int) dimset.get(i).getSize();
        }
        return shape;
    }

static public int [ ] computeEffectiveShape ( List < DapDimension > dimset ) { if ( dimset == null || dimset . size ( ) == 0 ) return new int [ 0 ] ; int effectiverank = dimset . size ( ) ; int [ ] shape = new int [ effectiverank ] ; for ( int i = 0 ; i < effectiverank ; i ++ ) { shape [ i ] = ( int ) dimset . get ( i ) . getSize ( ) ; } return shape ; }

Compute the shape inferred from a set of slices.
'Effective' means that any trailing vlen will be
ignored.

@param dimset from which to generate shape
@return

Compute the shape inferred from a set of slices . Effective means that any trailing vlen will be ignored .


public Date add( Date d) {
    Calendar cal = Calendar.getInstance();
    cal.setTime( d);
    cal.add( Calendar.SECOND, (int) getValueInSeconds());
    return cal.getTime();
  }

public Date add ( Date d ) { Calendar cal = Calendar . getInstance ( ) ; cal . setTime ( d ) ; cal . add ( Calendar . SECOND , ( int ) getValueInSeconds ( ) ) ; return cal . getTime ( ) ; }

Add the time amount to the given Date, return a new Date.
@param d add to this Date
@return Date with getValueInSeconds() added to it.

Add the time amount to the given Date return a new Date .


@Override
    protected Unit myMultiplyBy(final Unit that) throws MultiplyException {
        return that instanceof ScaledUnit
                ? new ScaledUnit(getScale() * ((ScaledUnit) that).getScale(),
                        getUnit().multiplyBy(((ScaledUnit) that).getUnit()))
                : new ScaledUnit(getScale(), getUnit().multiplyBy(that));
    }

@ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { return that instanceof ScaledUnit ? new ScaledUnit ( getScale ( ) * ( ( ScaledUnit ) that ) . getScale ( ) , getUnit ( ) . multiplyBy ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( getScale ( ) , getUnit ( ) . multiplyBy ( that ) ) ; }

Multiplies this unit by another unit.

@param that
The other unit.
@return The product of this unit and the other unit.
@throws MultiplyException
Can't multiply these units together.


@Override
    protected Unit myDivideBy(final Unit that) throws OperationException {
        return that instanceof ScaledUnit
                ? new ScaledUnit(getScale() / ((ScaledUnit) that).getScale(),
                        getUnit().divideBy(((ScaledUnit) that).getUnit()))
                : new ScaledUnit(getScale(), getUnit().divideBy(that));
    }

@ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit ( getScale ( ) / ( ( ScaledUnit ) that ) . getScale ( ) , getUnit ( ) . divideBy ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( getScale ( ) , getUnit ( ) . divideBy ( that ) ) ; }

Divides this unit by another unit.

@param that
The other unit.
@return The quotient of this unit divided by the other unit.
@throws OperationException
Can't divide these units.


@Override
    protected Unit myDivideInto(final Unit that) throws OperationException {
        return that instanceof ScaledUnit
                ? new ScaledUnit(((ScaledUnit) that).getScale() / getScale(),
                        getUnit().divideInto(((ScaledUnit) that).getUnit()))
                : new ScaledUnit(1 / getScale(), getUnit().divideInto(that));
    }

@ Override protected Unit myDivideInto ( final Unit that ) throws OperationException { return that instanceof ScaledUnit ? new ScaledUnit ( ( ( ScaledUnit ) that ) . getScale ( ) / getScale ( ) , getUnit ( ) . divideInto ( ( ( ScaledUnit ) that ) . getUnit ( ) ) ) : new ScaledUnit ( 1 / getScale ( ) , getUnit ( ) . divideInto ( that ) ) ; }

Divides this unit into another unit.

@param that
The other unit.
@return The quotient of this unit divided into the other unit.
@throws OperationException
Can't divide these units.


@Override
    protected Unit myRaiseTo(final int power) throws RaiseException {
        return new ScaledUnit(Math.pow(getScale(), power), getUnit().raiseTo(
                power));
    }

@ Override protected Unit myRaiseTo ( final int power ) throws RaiseException { return new ScaledUnit ( Math . pow ( getScale ( ) , power ) , getUnit ( ) . raiseTo ( power ) ) ; }

Raises this unit to a power.

@param power
The power.
@return The result of raising this unit to the power.
@throws RaiseException
Can't raise this unit to a power.


public double toDerivedUnit(final double amount) throws ConversionException {
        if (!(_unit instanceof DerivableUnit)) {
            throw new ConversionException(this, getDerivedUnit());
        }
        return ((DerivableUnit) _unit).toDerivedUnit(amount * getScale());
    }

public double toDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) _unit ) . toDerivedUnit ( amount * getScale ( ) ) ; }

Converts a numeric value from this unit to the underlying derived unit.

@param amount
The numeric value in this unit.
@return The equivalent value in the underlying derived unit.
@throws ConversionException
Can't convert value to the underlying derived unit.

Converts a numeric value from this unit to the underlying derived unit .


public float[] toDerivedUnit(final float[] input, final float[] output)
            throws ConversionException {
        final float scale = (float) getScale();
        for (int i = input.length; --i >= 0;) {
            output[i] = input[i] * scale;
        }
        if (!(_unit instanceof DerivableUnit)) {
            throw new ConversionException(this, getDerivedUnit());
        }
        return ((DerivableUnit) getUnit()).toDerivedUnit(output, output);
    }

public float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { final float scale = ( float ) getScale ( ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = input [ i ] * scale ; } if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . toDerivedUnit ( output , output ) ; }

Converts numeric values from this unit to the underlying derived unit.

@param input
The numeric values in this unit.
@param output
The equivalent values in the underlying derived unit.
@return output.
@throws ConversionException
Can't convert values to the underlying derived unit.

Converts numeric values from this unit to the underlying derived unit .


public double fromDerivedUnit(final double amount)
            throws ConversionException {
        if (!(_unit instanceof DerivableUnit)) {
            throw new ConversionException(getDerivedUnit(), this);
        }
        return ((DerivableUnit) getUnit()).fromDerivedUnit(amount) / getScale();
    }

public double fromDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( amount ) / getScale ( ) ; }

Converts a numeric value from the underlying derived unit to this unit.

@param amount
The numeric value in the underlying derived unit.
@return The equivalent value in this unit.
@throws ConversionException
Can't convert value.

Converts a numeric value from the underlying derived unit to this unit .


public String getCanonicalString() {
        return DerivedUnitImpl.DIMENSIONLESS.equals(_unit)
                ? Double.toString(getScale())
                : Double.toString(getScale()) + " " + _unit.toString();
    }

public
String
getCanonicalString
(
)
{
return
DerivedUnitImpl
.
DIMENSIONLESS
.
equals
(
_unit
)
Double
.
toString
(
getScale
(
)
)
:
Double
.
toString
(
getScale
(
)
)
+
" "
+
_unit
.
toString
(
)
;
}

Returns the canonical string representation of the unit.

@return The canonical string representation.

Returns the canonical string representation of the unit .


public Array readData(SectionIterable want) throws IOException, InvalidRangeException {
    if (vindex instanceof PartitionCollectionImmutable.VariableIndexPartitioned)
      return readDataFromPartition((PartitionCollectionImmutable.VariableIndexPartitioned) vindex, want);
    else
      return readDataFromCollection(vindex, want);
  }

public Array readData ( SectionIterable want ) throws IOException , InvalidRangeException { if ( vindex instanceof PartitionCollectionImmutable . VariableIndexPartitioned ) return readDataFromPartition ( ( PartitionCollectionImmutable . VariableIndexPartitioned ) vindex , want ) ; else return readDataFromCollection ( vindex , want ) ; }

Read the section of data described by want
@param want which data do you want?
@return data as an Array


public Array readData2(CoordsSet want, RangeIterator yRange, RangeIterator xRange) throws IOException {
    if (vindex instanceof PartitionCollectionImmutable.VariableIndexPartitioned)
      return readDataFromPartition2((PartitionCollectionImmutable.VariableIndexPartitioned) vindex, want, yRange, xRange);
    else
      return readDataFromCollection2(vindex, want, yRange, xRange);
  }

public Array readData2 ( CoordsSet want , RangeIterator yRange , RangeIterator xRange ) throws IOException { if ( vindex instanceof PartitionCollectionImmutable . VariableIndexPartitioned ) return readDataFromPartition2 ( ( PartitionCollectionImmutable . VariableIndexPartitioned ) vindex , want , yRange , xRange ) ; else return readDataFromCollection2 ( vindex , want , yRange , xRange ) ; }

Coordinate based subsetting for Coverage


@Override
  public PointFeatureCollection flatten(List<String> stationNames, CalendarDateRange dateRange, List<VariableSimpleIF> varList) throws IOException {
    if ((stationNames == null) || (stationNames.size() == 0))
      return new StationTimeSeriesCollectionFlattened(this, dateRange);

    List<StationFeature> subsetStations = getStationHelper().getStationFeaturesFromNames(stationNames);
    return new StationTimeSeriesCollectionFlattened(new StationSubset(this, subsetStations), dateRange);
  }

@ Override public PointFeatureCollection flatten ( List < String > stationNames , CalendarDateRange dateRange , List < VariableSimpleIF > varList ) throws IOException { if ( ( stationNames == null ) || ( stationNames . size ( ) == 0 ) ) return new StationTimeSeriesCollectionFlattened ( this , dateRange ) ; List < StationFeature > subsetStations = getStationHelper ( ) . getStationFeaturesFromNames ( stationNames ) ; return new StationTimeSeriesCollectionFlattened ( new StationSubset ( this , subsetStations ) , dateRange ) ; }


public InvService findService(String name) {
    if (name == null) return null;

    for (InvService s : services) {
      if (name.equals(s.getName())) return s;

      // look for nested servers
      if (s.getServiceType() == ServiceType.COMPOUND) {
        InvService result = s.findNestedService(name);
        if (result != null) return result;
      }
    }

    return null;
  }

public
InvService
findService
(
String
name
)
{
if
(
name
==
)
return
;
for
(
InvService
s
:
services
)
{
if
(
name
.
equals
(
s
.
getName
(
)
)
)
return
s
;
// look for nested servers
if
(
s
.
getServiceType
(
)
==
ServiceType
.
COMPOUND
)
{
InvService
result
=
s
.
findNestedService
(
name
)
;
if
(
result
!=
)
return
result
;
}
}
return
;
}

Find the named service declared in the top level of this catalog.

@param name match this name
@return service that matches the given name, or null if none found.

Find the named service declared in the top level of this catalog .


public int getGateSize(int datatype) {
    switch (datatype) {
      case REFLECTIVITY:
        return ((int) reflect_gate_size);

      case VELOCITY_HI:
      case VELOCITY_LOW:
      case SPECTRUM_WIDTH:
        return ((int) doppler_gate_size);
      //high resolution
      case REFLECTIVITY_HIGH:
        return ((int) reflectHR_gate_size);
      case VELOCITY_HIGH:
        return ((int) velocityHR_gate_size);
      case SPECTRUM_WIDTH_HIGH:
        return ((int) spectrumHR_gate_size);
      case DIFF_REFLECTIVITY_HIGH:
        return ((int) zdrHR_gate_size);
      case DIFF_PHASE:
        return ((int) phiHR_gate_size);
      case CORRELATION_COEFFICIENT:
        return ((int) rhoHR_gate_size);

    }
    return -1;
  }

public
int
getGateSize
(
int
datatype
)
{
switch
(
datatype
)
{
case
REFLECTIVITY
:
return
(
(
int
)
reflect_gate_size
)
;
case
VELOCITY_HI
:
case
VELOCITY_LOW
:
case
SPECTRUM_WIDTH
:
return
(
(
int
)
doppler_gate_size
)
;
//high resolution
case
REFLECTIVITY_HIGH
:
return
(
(
int
)
reflectHR_gate_size
)
;
case
VELOCITY_HIGH
:
return
(
(
int
)
velocityHR_gate_size
)
;
case
SPECTRUM_WIDTH_HIGH
:
return
(
(
int
)
spectrumHR_gate_size
)
;
case
DIFF_REFLECTIVITY_HIGH
:
return
(
(
int
)
zdrHR_gate_size
)
;
case
DIFF_PHASE
:
return
(
(
int
)
phiHR_gate_size
)
;
case
CORRELATION_COEFFICIENT
:
return
(
(
int
)
rhoHR_gate_size
)
;
}
return
1
;
}

This method returns the gate size in meters

@param datatype which type of data : REFLECTIVITY, VELOCITY_HI, VELOCITY_LO, SPECTRUM_WIDTH
@return the gate size in meters


public int getGateStart(int datatype) {
    switch (datatype) {
      case REFLECTIVITY:
        return ((int) reflect_first_gate);

      case VELOCITY_HI:
      case VELOCITY_LOW:
      case SPECTRUM_WIDTH:
        return ((int) doppler_first_gate);
      //high resolution
      case REFLECTIVITY_HIGH:
        return ((int) reflectHR_first_gate);
      case VELOCITY_HIGH:
        return ((int) velocityHR_first_gate);
      case SPECTRUM_WIDTH_HIGH:
        return ((int) spectrumHR_first_gate);
      case DIFF_REFLECTIVITY_HIGH:
        return ((int) zdrHR_first_gate);
      case DIFF_PHASE:
        return ((int) phiHR_first_gate);
      case CORRELATION_COEFFICIENT:
        return ((int) rhoHR_first_gate);

    }
    return -1;
  }

public
int
getGateStart
(
int
datatype
)
{
switch
(
datatype
)
{
case
REFLECTIVITY
:
return
(
(
int
)
reflect_first_gate
)
;
case
VELOCITY_HI
:
case
VELOCITY_LOW
:
case
SPECTRUM_WIDTH
:
return
(
(
int
)
doppler_first_gate
)
;
//high resolution
case
REFLECTIVITY_HIGH
:
return
(
(
int
)
reflectHR_first_gate
)
;
case
VELOCITY_HIGH
:
return
(
(
int
)
velocityHR_first_gate
)
;
case
SPECTRUM_WIDTH_HIGH
:
return
(
(
int
)
spectrumHR_first_gate
)
;
case
DIFF_REFLECTIVITY_HIGH
:
return
(
(
int
)
zdrHR_first_gate
)
;
case
DIFF_PHASE
:
return
(
(
int
)
phiHR_first_gate
)
;
case
CORRELATION_COEFFICIENT
:
return
(
(
int
)
rhoHR_first_gate
)
;
}
return
1
;
}

This method returns the starting gate in meters

@param datatype which type of data : REFLECTIVITY, VELOCITY_HI, VELOCITY_LO, SPECTRUM_WIDTH
@return the starting gate in meters


public int getGateCount(int datatype) {
    switch (datatype) {
      case REFLECTIVITY:
        return ((int) reflect_gate_count);

      case VELOCITY_HI:
      case VELOCITY_LOW:
      case SPECTRUM_WIDTH:
        return ((int) doppler_gate_count);
      // hight resolution
      case REFLECTIVITY_HIGH:
        return ((int) reflectHR_gate_count);
      case VELOCITY_HIGH:
        return ((int) velocityHR_gate_count);
      case SPECTRUM_WIDTH_HIGH:
        return ((int) spectrumHR_gate_count);
      case DIFF_REFLECTIVITY_HIGH:
        return ((int) zdrHR_gate_count);
      case DIFF_PHASE:
        return ((int) phiHR_gate_count);
      case CORRELATION_COEFFICIENT:
        return ((int) rhoHR_gate_count);
    }
    return 0;
  }

public
int
getGateCount
(
int
datatype
)
{
switch
(
datatype
)
{
case
REFLECTIVITY
:
return
(
(
int
)
reflect_gate_count
)
;
case
VELOCITY_HI
:
case
VELOCITY_LOW
:
case
SPECTRUM_WIDTH
:
return
(
(
int
)
doppler_gate_count
)
;
// hight resolution
case
REFLECTIVITY_HIGH
:
return
(
(
int
)
reflectHR_gate_count
)
;
case
VELOCITY_HIGH
:
return
(
(
int
)
velocityHR_gate_count
)
;
case
SPECTRUM_WIDTH_HIGH
:
return
(
(
int
)
spectrumHR_gate_count
)
;
case
DIFF_REFLECTIVITY_HIGH
:
return
(
(
int
)
zdrHR_gate_count
)
;
case
DIFF_PHASE
:
return
(
(
int
)
phiHR_gate_count
)
;
case
CORRELATION_COEFFICIENT
:
return
(
(
int
)
rhoHR_gate_count
)
;
}
return
0
;
}

This method returns the number of gates

@param datatype which type of data : REFLECTIVITY, VELOCITY_HI, VELOCITY_LO, SPECTRUM_WIDTH
@return the number of gates


public void writeXML(NetcdfDataset ncd, OutputStream os, boolean showCoords, String uri) throws IOException {

    // Output the document, use standard formatter
    //XMLOutputter fmt = new XMLOutputter("  ", true);
    //fmt.setLineSeparator("\n");
    XMLOutputter fmt = new XMLOutputter( Format.getPrettyFormat());
    fmt.output(makeDocument(ncd, showCoords, uri), os);
  }

Write a NetcdfDataset as an NcML-G document to the specified stream.

@param ncd write this dataset; should have opened with "add coordinates".
@param os write to this OutputStream
@param showCoords show 1D coordinate values
@param uri use this url, if null use getLocation()
@throws IOException on io error

Write a NetcdfDataset as an NcML - G document to the specified stream .


public Dimension preferredLayoutSize(Container target) {
      synchronized (target.getTreeLock()) {
            Dimension dim = new Dimension(0, 0);

            for (int i = 0 ; i < target.getComponentCount() ; i++) {
              Component m = target.getComponent(i);
              if (m.isVisible()) {
                Dimension d = m.getPreferredSize();

                // original
                // dim.height = Math.max(dim.height, d.height);
                //if (i > 0) { dim.width += hgap; }
                // dim.width += d.width;

                // new  way
                Point p = m.getLocation();
                dim.width =  Math.max(dim.width,  p.x+d.width);
                dim.height = Math.max(dim.height, p.y+d.height);
              }
            }
        Insets insets = target.getInsets();
        dim.width += insets.left + insets.right + getHgap()*2;
        dim.height += insets.top + insets.bottom + getVgap()*2;
        return dim;
      }
    }

deal with having components on more than one line


static CrawlableDataset verifyDescendantDataset( CrawlableDataset ancestorCrDs,
                                                   String path,
                                                   CrawlableDatasetFilter filter )
  {
    // Make sure requested path is descendant of ancestor dataset.
    if ( ! ancestorCrDs.isCollection() )
      throw new IllegalArgumentException( "Ancestor dataset <" + ancestorCrDs.getPath() + "> not a collection." );
    if ( ! path.startsWith( ancestorCrDs.getPath() ) )
      throw new IllegalArgumentException( "Dataset path <" + path + "> not descendant of given dataset <" + ancestorCrDs.getPath() + ">." );

    // If path and ancestor are the same, return ancestor.
    if ( path.length() == ancestorCrDs.getPath().length() )
      return ancestorCrDs;

    // Crawl into the dataset collection through each level of the given path
    // checking that each level is accepted by the given CrawlableDatasetFilter.
    String remainingPath = path.substring( ancestorCrDs.getPath().length() );
    if ( remainingPath.startsWith( "/" ) )
      remainingPath = remainingPath.substring( 1 );

    String[] pathSegments = remainingPath.split( "/" );
    CrawlableDataset curCrDs = ancestorCrDs;
    for ( int i = 0; i < pathSegments.length; i++ )
    {
      curCrDs = curCrDs.getDescendant( pathSegments[i]);
      if ( filter != null )
        if ( ! filter.accept( curCrDs ) )
          return null;
    }
    // Only check complete path for existence since speed of check depends on implementation.
    if ( ! curCrDs.exists() )
      return null;
    return curCrDs;
  }

Return the requested dataset if it is the ancestor dataset or an allowed
descendant of the ancestor dataset, otherwise return null. The given
filter determines whether a dataset is allowed or not.

@param ancestorCrDs the dataset from which the requested dataset must be descended (or self).
@param path the path of the requested dataset.
@param filter the CrawlableDatasetFilter that determines which datasets are allowed.
@return the CrawlableDataset that represents the given path or null.

@throws NullPointerException if the given path or ancestor dataset are null.
@throws IllegalArgumentException if the abstract dataset is not a descendant of the ancestor dataset.

Return the requested dataset if it is the ancestor dataset or an allowed descendant of the ancestor dataset otherwise return null . The given filter determines whether a dataset is allowed or not .


public InvCatalogImpl generateProxyDsResolverCatalog( CrawlableDataset catalogCrDs, ProxyDatasetHandler pdh ) throws IOException
  {
    throw new java.lang.UnsupportedOperationException( "This method not supported by SimpleCatalogBuilder.");
  }


static public CalendarDateUnit of(String calendarName, String udunitString) {
    Calendar calt = Calendar.get(calendarName);
    if (calt == null) calt = Calendar.getDefault();
    return new CalendarDateUnit(calt, udunitString);
  }

static public CalendarDateUnit of ( String calendarName , String udunitString ) { Calendar calt = Calendar . get ( calendarName ) ; if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , udunitString ) ; }

Create a CalendarDateUnit from a calendar name and a udunit string = "unit since calendarDate"
@param calendarName must match a calendar enum, or one of its aliases, see ucar.nc2.time.Calendar.get()
@param udunitString "unit since calendarDate"
@return CalendarDateUnit
@throws IllegalArgumentException if udunitString is not paresable

Create a CalendarDateUnit from a calendar name and a udunit string = unit since calendarDate


static public CalendarDateUnit withCalendar(Calendar calt, String udunitString) {
    if (calt == null) calt = Calendar.getDefault();
    return new CalendarDateUnit(calt, udunitString);
  }

static public CalendarDateUnit withCalendar ( Calendar calt , String udunitString ) { if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , udunitString ) ; }

Create a CalendarDateUnit from a calendar and a udunit string = "unit since calendarDate"
@param calt use this Calendar, or null for default calendar
@param udunitString "unit since calendarDate"
@return CalendarDateUnit
@throws IllegalArgumentException if udunitString is not paresable

Create a CalendarDateUnit from a calendar and a udunit string = unit since calendarDate


static public CalendarDateUnit of(Calendar calt, CalendarPeriod.Field periodField, CalendarDate baseDate) {
    if (calt == null) calt = Calendar.getDefault();
    return new CalendarDateUnit(calt, periodField, baseDate);
  }

static public CalendarDateUnit of ( Calendar calt , CalendarPeriod . Field periodField , CalendarDate baseDate ) { if ( calt == null ) calt = Calendar . getDefault ( ) ; return new CalendarDateUnit ( calt , periodField , baseDate ) ; }

Create a CalendarDateUnit from a calendar, a CalendarPeriod.Field, and a base date
@param calt use this Calendar, or null for default calendar
@param periodField a CalendarPeriod.Field like Hour or second
@param baseDate "since baseDate"
@return CalendarDateUnit

Create a CalendarDateUnit from a calendar a CalendarPeriod . Field and a base date