int pcode_5( int[] pos, int hoff, int len, boolean isZ )
    {
      ArrayList dims =  new ArrayList();
      //int vlen =len;

      Dimension sDim = new Dimension("windBarbSize", len);
      ncfile.addDimension( null, sDim);
      dims.add( sDim);

      Structure dist = new Structure(ncfile, null, null, "vectorArrow");
      dist.setDimensions(dims);
      ncfile.addVariable(null, dist);
      dist.addAttribute( new Attribute(CDM.LONG_NAME, "Vector Arrow Data"));

      Variable i0 = new Variable(ncfile, null, dist, "x_start");
      i0.setDimensions((String)null);
      i0.setDataType(DataType.SHORT);
      i0.addAttribute( new Attribute(CDM.UNITS, "KM"));
      dist.addMemberVariable(i0);
      Variable j0 = new Variable(ncfile, null, dist, "y_start");
      j0.setDimensions((String)null);
      j0.setDataType(DataType.SHORT);
      j0.addAttribute( new Attribute(CDM.UNITS, "KM"));
      dist.addMemberVariable(j0);
      Variable direct = new Variable(ncfile, null, dist, "direction");
      direct.setDimensions((String)null);
      direct.setDataType(DataType.SHORT);
      direct.addAttribute( new Attribute(CDM.UNITS, "degree"));
      dist.addMemberVariable(direct);
      Variable speed = new Variable(ncfile, null, dist, "arrowLength");
      speed.setDimensions((String)null);
      speed.setDataType(DataType.SHORT);
      speed.addAttribute( new Attribute(CDM.UNITS, "pixels"));
      dist.addMemberVariable(speed);
      Variable speed1 = new Variable(ncfile, null, dist, "arrowHeadLength");
      speed1.setDimensions((String)null);
      speed1.setDataType(DataType.SHORT);
      speed1.addAttribute( new Attribute(CDM.UNITS, "pixels"));
      dist.addMemberVariable(speed1);

      int[] pos1 = new int[len];
      System.arraycopy(pos, 0, pos1, 0, len);
      dist.setSPobject( new Vinfo (0, 0, 0, 0, hoff, 0, isR, isZ, pos1, null, 4, 0));

      return 1;
    }

int
pcode_5
(
int
[
]
pos
,
int
hoff
,
int
len
,
boolean
isZ
)
{
ArrayList
dims
=
new
ArrayList
(
)
;
//int vlen =len;
Dimension
sDim
=
new
Dimension
(
"windBarbSize"
,
len
)
;
ncfile
.
addDimension
(
,
sDim
)
;
dims
.
add
(
sDim
)
;
Structure
dist
=
new
Structure
(
ncfile
,
,
,
"vectorArrow"
)
;
dist
.
setDimensions
(
dims
)
;
ncfile
.
addVariable
(
,
dist
)
;
dist
.
addAttribute
(
new
Attribute
(
CDM
.
LONG_NAME
,
"Vector Arrow Data"
)
)
;
Variable
i0
=
new
Variable
(
ncfile
,
,
dist
,
"x_start"
)
;
i0
.
setDimensions
(
(
String
)
)
;
i0
.
setDataType
(
DataType
.
SHORT
)
;
i0
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"KM"
)
)
;
dist
.
addMemberVariable
(
i0
)
;
Variable
j0
=
new
Variable
(
ncfile
,
,
dist
,
"y_start"
)
;
j0
.
setDimensions
(
(
String
)
)
;
j0
.
setDataType
(
DataType
.
SHORT
)
;
j0
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"KM"
)
)
;
dist
.
addMemberVariable
(
j0
)
;
Variable
direct
=
new
Variable
(
ncfile
,
,
dist
,
"direction"
)
;
direct
.
setDimensions
(
(
String
)
)
;
direct
.
setDataType
(
DataType
.
SHORT
)
;
direct
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"degree"
)
)
;
dist
.
addMemberVariable
(
direct
)
;
Variable
speed
=
new
Variable
(
ncfile
,
,
dist
,
"arrowLength"
)
;
speed
.
setDimensions
(
(
String
)
)
;
speed
.
setDataType
(
DataType
.
SHORT
)
;
speed
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"pixels"
)
)
;
dist
.
addMemberVariable
(
speed
)
;
Variable
speed1
=
new
Variable
(
ncfile
,
,
dist
,
"arrowHeadLength"
)
;
speed1
.
setDimensions
(
(
String
)
)
;
speed1
.
setDataType
(
DataType
.
SHORT
)
;
speed1
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"pixels"
)
)
;
dist
.
addMemberVariable
(
speed1
)
;
int
[
]
pos1
=
new
int
[
len
]
;
System
.
arraycopy
(
pos
,
0
,
pos1
,
0
,
len
)
;
dist
.
setSPobject
(
new
Vinfo
(
0
,
0
,
0
,
0
,
hoff
,
0
,
isR
,
isZ
,
pos1
,
,
4
,
0
)
)
;
return
1
;
}

construct a dataset for vector arrow data packet with code 5

@param pos, size, code, hoff, len, isZ

@return  1 if successful


int pcode_128( int[] pos, int[] size, int code, int hoff, int len, String structName, String abbre, boolean isZ )
     {
        //int vlen = len;

        ArrayList dims =  new ArrayList();
        Dimension sDim = new Dimension("textStringSize"+ abbre + code, len);
        ncfile.addDimension( null, sDim);
        dims.add( sDim);

        Structure dist = new Structure(ncfile, null, null, structName + abbre);
        dist.setDimensions(dims);
        ncfile.addVariable(null, dist);
        dist.addAttribute( new Attribute(CDM.LONG_NAME, "text and special symbol for code "+code));

        if(code == 8){
            Variable strVal = new Variable(ncfile, null, dist, "strValue");
            strVal.setDimensions((String)null);
            strVal.setDataType(DataType.SHORT);
            strVal.addAttribute( new Attribute(CDM.UNITS, ""));
            dist.addMemberVariable(strVal);
        }
        Variable i0 = new Variable(ncfile, null, dist, "x_start");
        i0.setDimensions((String)null);
        i0.setDataType(DataType.SHORT);
        i0.addAttribute( new Attribute(CDM.UNITS, "KM"));
        dist.addMemberVariable(i0);
        Variable j0 = new Variable(ncfile, null, dist, "y_start");
        j0.setDimensions((String)null);
        j0.setDataType(DataType.SHORT);
        j0.addAttribute( new Attribute(CDM.UNITS, "KM"));
        dist.addMemberVariable(j0);
        Variable tstr = new Variable(ncfile, null, dist, "textString" );
        tstr.setDimensions((String)null);
        tstr.setDataType(DataType.STRING);
        tstr.addAttribute( new Attribute(CDM.UNITS, ""));
        dist.addMemberVariable(tstr);

        int[] pos1 = new int[len];
        System.arraycopy(pos, 0, pos1, 0, len);
        dist.setSPobject( new Vinfo ( 0, 0, 0, 0, hoff, 0, isR, isZ, pos1, size, code, 0));
        return 1;
     }

int
pcode_128
(
int
[
]
pos
,
int
[
]
size
,
int
code
,
int
hoff
,
int
len
,
String
structName
,
String
abbre
,
boolean
isZ
)
{
//int vlen = len;
ArrayList
dims
=
new
ArrayList
(
)
;
Dimension
sDim
=
new
Dimension
(
"textStringSize"
+
abbre
+
code
,
len
)
;
ncfile
.
addDimension
(
,
sDim
)
;
dims
.
add
(
sDim
)
;
Structure
dist
=
new
Structure
(
ncfile
,
,
,
structName
+
abbre
)
;
dist
.
setDimensions
(
dims
)
;
ncfile
.
addVariable
(
,
dist
)
;
dist
.
addAttribute
(
new
Attribute
(
CDM
.
LONG_NAME
,
"text and special symbol for code "
+
code
)
)
;
if
(
code
==
8
)
{
Variable
strVal
=
new
Variable
(
ncfile
,
,
dist
,
"strValue"
)
;
strVal
.
setDimensions
(
(
String
)
)
;
strVal
.
setDataType
(
DataType
.
SHORT
)
;
strVal
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
""
)
)
;
dist
.
addMemberVariable
(
strVal
)
;
}
Variable
i0
=
new
Variable
(
ncfile
,
,
dist
,
"x_start"
)
;
i0
.
setDimensions
(
(
String
)
)
;
i0
.
setDataType
(
DataType
.
SHORT
)
;
i0
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"KM"
)
)
;
dist
.
addMemberVariable
(
i0
)
;
Variable
j0
=
new
Variable
(
ncfile
,
,
dist
,
"y_start"
)
;
j0
.
setDimensions
(
(
String
)
)
;
j0
.
setDataType
(
DataType
.
SHORT
)
;
j0
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
"KM"
)
)
;
dist
.
addMemberVariable
(
j0
)
;
Variable
tstr
=
new
Variable
(
ncfile
,
,
dist
,
"textString"
)
;
tstr
.
setDimensions
(
(
String
)
)
;
tstr
.
setDataType
(
DataType
.
STRING
)
;
tstr
.
addAttribute
(
new
Attribute
(
CDM
.
UNITS
,
""
)
)
;
dist
.
addMemberVariable
(
tstr
)
;
int
[
]
pos1
=
new
int
[
len
]
;
System
.
arraycopy
(
pos
,
0
,
pos1
,
0
,
len
)
;
dist
.
setSPobject
(
new
Vinfo
(
0
,
0
,
0
,
0
,
hoff
,
0
,
isR
,
isZ
,
pos1
,
size
,
code
,
0
)
)
;
return
1
;
}

construct a dataset for text and special symbol packets with code 1, 2, and 8

@param pos, size, code, hoff, len, structName, isZ

@return  1 if successful

construct a dataset for text and special symbol packets with code 1 2 and 8


int pcode_10n9( int[] pos, int[] dlen, int hoff, int len, boolean isZ )
     {

        ArrayList dims =  new ArrayList();
        Variable v  ;

        int vlen = 0;
        for(int i=0; i<len; i++ ){
           vlen = vlen + dlen[i];
        }

        Dimension sDim = new Dimension("unlinkedVectorSize", vlen);
        ncfile.addDimension( null, sDim);
        dims.add( sDim);

        Structure dist = new Structure(ncfile, null, null, "unlinkedVectorStruct");
        dist.setDimensions(dims);
        ncfile.addVariable(null, dist);
        dist.addAttribute( new Attribute(CDM.LONG_NAME, "Unlinked Vector Packet"));

        v = new Variable(ncfile, null, null, "iValue");
        v.setDataType(DataType.SHORT);
        v.setDimensions((String)null);
        dist.addMemberVariable(v);

        Variable ii0 = new Variable(ncfile, null, dist, "x_start");
        ii0.setDimensions((String)null);
        ii0.setDataType(DataType.SHORT);
        dist.addMemberVariable(ii0);
        Variable ii1 = new Variable(ncfile, null, dist, "y_start");
        ii1.setDimensions((String)null);
        ii1.setDataType(DataType.SHORT);
        dist.addMemberVariable(ii1);
        Variable jj0 = new Variable(ncfile, null, dist, "x_end");
        jj0.setDimensions((String)null);
        jj0.setDataType(DataType.SHORT);
        dist.addMemberVariable(jj0);
        Variable jj1 = new Variable(ncfile, null, dist, "y_end");
        jj1.setDimensions((String)null);
        jj1.setDataType(DataType.SHORT);
        dist.addMemberVariable(jj1);

        int[] pos1 = new int[len];
        int[] dlen1 = new int[len];
        System.arraycopy(pos, 0, pos1, 0, len);
        System.arraycopy(dlen, 0, dlen1, 0, len);
        dist.setSPobject( new Vinfo ( 0, 0, 0, 0, hoff, 0, isR, isZ, pos1, dlen1, 10, 0));
        return 1;
     }

int
pcode_10n9
(
int
[
]
pos
,
int
[
]
dlen
,
int
hoff
,
int
len
,
boolean
isZ
)
{
ArrayList
dims
=
new
ArrayList
(
)
;
Variable
v
;
int
vlen
=
0
;
for
(
int
i
=
0
;
i
<
len
;
i
++
)
{
vlen
=
vlen
+
dlen
[
i
]
;
}
Dimension
sDim
=
new
Dimension
(
"unlinkedVectorSize"
,
vlen
)
;
ncfile
.
addDimension
(
,
sDim
)
;
dims
.
add
(
sDim
)
;
Structure
dist
=
new
Structure
(
ncfile
,
,
,
"unlinkedVectorStruct"
)
;
dist
.
setDimensions
(
dims
)
;
ncfile
.
addVariable
(
,
dist
)
;
dist
.
addAttribute
(
new
Attribute
(
CDM
.
LONG_NAME
,
"Unlinked Vector Packet"
)
)
;
v
=
new
Variable
(
ncfile
,
,
,
"iValue"
)
;
v
.
setDataType
(
DataType
.
SHORT
)
;
v
.
setDimensions
(
(
String
)
)
;
dist
.
addMemberVariable
(
v
)
;
Variable
ii0
=
new
Variable
(
ncfile
,
,
dist
,
"x_start"
)
;
ii0
.
setDimensions
(
(
String
)
)
;
ii0
.
setDataType
(
DataType
.
SHORT
)
;
dist
.
addMemberVariable
(
ii0
)
;
Variable
ii1
=
new
Variable
(
ncfile
,
,
dist
,
"y_start"
)
;
ii1
.
setDimensions
(
(
String
)
)
;
ii1
.
setDataType
(
DataType
.
SHORT
)
;
dist
.
addMemberVariable
(
ii1
)
;
Variable
jj0
=
new
Variable
(
ncfile
,
,
dist
,
"x_end"
)
;
jj0
.
setDimensions
(
(
String
)
)
;
jj0
.
setDataType
(
DataType
.
SHORT
)
;
dist
.
addMemberVariable
(
jj0
)
;
Variable
jj1
=
new
Variable
(
ncfile
,
,
dist
,
"y_end"
)
;
jj1
.
setDimensions
(
(
String
)
)
;
jj1
.
setDataType
(
DataType
.
SHORT
)
;
dist
.
addMemberVariable
(
jj1
)
;
int
[
]
pos1
=
new
int
[
len
]
;
int
[
]
dlen1
=
new
int
[
len
]
;
System
.
arraycopy
(
pos
,
0
,
pos1
,
0
,
len
)
;
System
.
arraycopy
(
dlen
,
0
,
dlen1
,
0
,
len
)
;
dist
.
setSPobject
(
new
Vinfo
(
0
,
0
,
0
,
0
,
hoff
,
0
,
isR
,
isZ
,
pos1
,
dlen1
,
10
,
0
)
)
;
return
1
;
}

construct a dataset for linked vector packet, and unlinked vector packet

@param pos, dlen, hoff, len, isZ

@return  1 if successful

construct a dataset for linked vector packet and unlinked vector packet


public int[] getLevels(int nlevel, short[] th) {
        int [] levels = new int[nlevel];
        int ival;
        int isign;

        for ( int i = 0; i < nlevel; i++ ) {    /* calibrated data values        */
              ival = convertShort2unsignedInt(th[i]);

              if ( (ival & 0x00008000) == 0 ) {
                isign = -1;
                if ( (ival & 0x00000100) == 0 ) isign = 1;
                levels[i] = isign * ( ival & 0x000000FF );
              } else {
                levels[i] = -9999 + ( ival & 0x000000FF);
              }
        }

        return levels;
    }

public
int
[
]
getLevels
(
int
nlevel
,
short
[
]
th
)
{
int
[
]
levels
=
new
int
[
nlevel
]
;
int
ival
;
int
isign
;
for
(
int
i
=
0
;
i
<
nlevel
;
i
++
)
{
/* calibrated data values        */
ival
=
convertShort2unsignedInt
(
th
[
i
]
)
;
if
(
(
ival
&
0x00008000
)
==
0
)
{
isign
=
1
;
if
(
(
ival
&
0x00000100
)
==
0
)
isign
=
1
;
levels
[
i
]
=
isign
*
(
ival
&
0x000000FF
)
;
}
else
{
levels
[
i
]
=
9999
+
(
ival
&
0x000000FF
)
;
}
}
return
levels
;
}

get the table to calibrate data value

@param nlevel    number of level
@param th        thredshold value
@return


public int[] getDualpolLevels(  short[] th) {

        int inc = th.length;
        int [] levels = new int[ inc]; //th[2] ];
        for ( int i = 0; i < inc; i++ ) {    /* calibrated data values        */
            levels[i] = th[i];
        }

        return levels;
    }

public
int
[
]
getDualpolLevels
(
short
[
]
th
)
{
int
inc
=
th
.
length
;
int
[
]
levels
=
new
int
[
inc
]
;
//th[2] ];
for
(
int
i
=
0
;
i
<
inc
;
i
++
)
{
/* calibrated data values        */
levels
[
i
]
=
th
[
i
]
;
}
return
levels
;
}

get the calibrate data values for dualpol data
@param th
@return


void addVariable(String pName, String longName, NetcdfFile nc, ArrayList dims, String coordinates,
                    DataType dtype, String ut, long hoff, long hedsiz, boolean isZ, int nlevel, int[] levels, int iscale)
    {
        Variable v = new Variable(nc, null, null, pName);
        v.setDataType(dtype);
        v.setDimensions(dims);
        ncfile.addVariable(null, v);
        v.addAttribute( new Attribute(CDM.LONG_NAME, longName));
        v.addAttribute( new Attribute(CDM.UNITS, ut));
        v.addAttribute( new Attribute(_Coordinate.Axes, coordinates));
        v.setSPobject( new Vinfo (numX, numX0, numY, numY0, hoff, hedsiz, isR, isZ, null, levels, iscale, nlevel));

    }

void addVariable ( String pName , String longName , NetcdfFile nc , ArrayList dims , String coordinates , DataType dtype , String ut , long hoff , long hedsiz , boolean isZ , int nlevel , int [ ] levels , int iscale ) { Variable v = new Variable ( nc , null , null , pName ) ; v . setDataType ( dtype ) ; v . setDimensions ( dims ) ; ncfile . addVariable ( null , v ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; v . addAttribute ( new Attribute ( CDM . UNITS , ut ) ) ; v . addAttribute ( new Attribute ( _Coordinate . Axes , coordinates ) ) ; v . setSPobject ( new Vinfo ( numX , numX0 , numY , numY0 , hoff , hedsiz , isR , isZ , null , levels , iscale , nlevel ) ) ; }

adding new variable to the netcdf file
@param pName                 variable name
@param longName              variable long name
@param nc                    netcdf file
@param dims                  variable dimensions
@param coordinates            variable coordinate
@param dtype                 variable type
@param ut                     unit string
@param hoff                  header offset
@param hedsiz                header size
@param isZ                   is compressed file
@param nlevel                 calibrated level number
@param levels                 calibrate levels
@param iscale                 is scale variable


void addParameter(String pName, String longName, NetcdfFile nc, ArrayList dims, Attribute att,
                    DataType dtype, String ut, long hoff, long doff, boolean isZ, int y0)
    {
          String vName = pName;
          Variable vVar = new Variable(nc, null, null, vName);
          vVar.setDataType(dtype);
          if( dims != null ) vVar.setDimensions(dims);
          else vVar.setDimensions("");
          if(att != null ) vVar.addAttribute(att);
          vVar.addAttribute( new Attribute(CDM.UNITS, ut));
          vVar.addAttribute( new Attribute(CDM.LONG_NAME, longName));
          nc.addVariable(null, vVar);
          vVar.setSPobject( new Vinfo (numX, numX0, numY, y0, hoff, doff, isR, isZ, null, null, 0, 0));
    }

void addParameter ( String pName , String longName , NetcdfFile nc , ArrayList dims , Attribute att , DataType dtype , String ut , long hoff , long doff , boolean isZ , int y0 ) { String vName = pName ; Variable vVar = new Variable ( nc , null , null , vName ) ; vVar . setDataType ( dtype ) ; if ( dims != null ) vVar . setDimensions ( dims ) ; else vVar . setDimensions ( "" ) ; if ( att != null ) vVar . addAttribute ( att ) ; vVar . addAttribute ( new Attribute ( CDM . UNITS , ut ) ) ; vVar . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; nc . addVariable ( null , vVar ) ; vVar . setSPobject ( new Vinfo ( numX , numX0 , numY , y0 , hoff , doff , isR , isZ , null , null , 0 , 0 ) ) ; }

adding new parameter to the netcdf file
@param pName                variable name
@param longName             variable long name
@param nc                    netcdf file
@param dims                 variable dimensions
@param att                  attribute
@param dtype                data type
@param ut                   unit string
@param hoff                 header offset
@param doff                 data offset
@param isZ                  is compressed file
@param y0                   reserved


byte[] uncompressed( ByteBuffer buf, int offset, int uncomplen ) throws IOException
    {
        byte[] header = new byte[offset];
        buf.position(0);
        buf.get(header);
        byte[] out = new byte[offset+uncomplen];
        System.arraycopy(header, 0, out, 0, offset);

        CBZip2InputStream cbzip2 = new CBZip2InputStream();

        int numCompBytes = buf.remaining();
        byte[] bufc = new byte[numCompBytes];
        buf.get(bufc, 0, numCompBytes);

        ByteArrayInputStream bis = new ByteArrayInputStream(bufc, 2, numCompBytes - 2);

        //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis);
        cbzip2.setStream(bis);
        int total = 0;
        int nread;
        byte[] ubuff = new byte[40000];
        byte[] obuff = new byte[40000];
        try {
            while ((nread = cbzip2.read(ubuff)) != -1) {
              if (total + nread > obuff.length) {
                byte[] temp = obuff;
                obuff = new byte[temp.length * 2];
                System.arraycopy(temp, 0, obuff, 0, temp.length);
              }
              System.arraycopy(ubuff, 0, obuff, total, nread);
              total += nread;
            }
            if (obuff.length >= 0)
              System.arraycopy(obuff, 0, out, offset, total);
          } catch (BZip2ReadException ioe) {
            log.warn("Nexrad2IOSP.uncompress "+raf.getLocation(), ioe);
        }

        return out;

    }

uncompress the TDWR products
@param buf          compressed buffer
@param offset       data offset
@param uncomplen    uncompressed length
@return
@throws IOException


int getUInt( byte[] b, int num )
    {
        int            base=1;
        int            i;
        int            word=0;

        int bv[] = new int[num];

        for (i = 0; i<num; i++ )
        {
            bv[i] = convertunsignedByte2Short(b[i]);
        }

        /*
        ** Calculate the integer value of the byte sequence
        */

        for ( i = num-1; i >= 0; i-- ) {
            word += base * bv[i];
            base *= 256;
        }

        return word;
    }

get unsigned integer from byte array
@param b
@param num
@return


int getInt( byte[] b, int num )
    {
        int            base=1;
        int            i;
        int            word=0;

        int bv[] = new int[num];

        for (i = 0; i<num; i++ )
        {
        bv[i] = convertunsignedByte2Short(b[i]);
        }

        if( bv[0] > 127 )
        {
         bv[0] -= 128;
         base = -1;
        }
        /*
        ** Calculate the integer value of the byte sequence
        */

        for ( i = num-1; i >= 0; i-- ) {
        word += base * bv[i];
        base *= 256;
        }

        return word;

    }

get signed integer from bytes
@param b
@param num
@return


protected Object convert( byte[] barray, DataType dataType, int nelems, int byteOrder) {

        if (dataType == DataType.BYTE) {
          return barray;
        }

        if (dataType == DataType.CHAR) {
          return IospHelper.convertByteToChar( barray);
        }

        ByteBuffer bbuff = ByteBuffer.wrap( barray);
        if (byteOrder >= 0)
          bbuff.order( byteOrder == ucar.unidata.io.RandomAccessFile.LITTLE_ENDIAN? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);

        if (dataType == DataType.SHORT) {
          ShortBuffer tbuff = bbuff.asShortBuffer();
          short[] pa = new short[nelems];
          tbuff.get( pa);
          return pa;

        } else if (dataType == DataType.INT) {
          IntBuffer tbuff = bbuff.asIntBuffer();
          int[] pa = new int[nelems];
          tbuff.get( pa);
          return pa;

        } else if (dataType == DataType.FLOAT) {
          FloatBuffer tbuff = bbuff.asFloatBuffer();
          float[] pa = new float[nelems];
          tbuff.get( pa);
          return pa;

        } else if (dataType == DataType.DOUBLE) {
          DoubleBuffer tbuff = bbuff.asDoubleBuffer();
          double[] pa = new double[nelems];
          tbuff.get( pa);
          return pa;
        }

        throw new IllegalStateException();
    }

protected Object convert ( byte [ ] barray , DataType dataType , int nelems , int byteOrder ) { if ( dataType == DataType . BYTE ) { return barray ; } if ( dataType == DataType . CHAR ) { return IospHelper . convertByteToChar ( barray ) ; } ByteBuffer bbuff = ByteBuffer . wrap ( barray ) ; if ( byteOrder >= 0 ) bbuff . order ( byteOrder == ucar . unidata . io . RandomAccessFile . LITTLE_ENDIAN ? ByteOrder . LITTLE_ENDIAN : ByteOrder . BIG_ENDIAN ) ; if ( dataType == DataType . SHORT ) { ShortBuffer tbuff = bbuff . asShortBuffer ( ) ; short [ ] pa = new short [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . INT ) { IntBuffer tbuff = bbuff . asIntBuffer ( ) ; int [ ] pa = new int [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . FLOAT ) { FloatBuffer tbuff = bbuff . asFloatBuffer ( ) ; float [ ] pa = new float [ nelems ] ; tbuff . get ( pa ) ; return pa ; } else if ( dataType == DataType . DOUBLE ) { DoubleBuffer tbuff = bbuff . asDoubleBuffer ( ) ; double [ ] pa = new double [ nelems ] ; tbuff . get ( pa ) ; return pa ; } throw new IllegalStateException ( ) ; }

this converts a byte array to another primitive array
@param barray
@param dataType
@param nelems
@param byteOrder
@return


protected void
    doDMR(DapRequest drq, DapContext cxt)
            throws IOException
    {
        // Convert the url to an absolute path
        String realpath = getResourcePath(drq, drq.getDatasetPath());

        DSP dsp = DapCache.open(realpath, cxt);
        DapDataset dmr = dsp.getDMR();

        /* Annotate with our endianness */
        ByteOrder order = (ByteOrder) cxt.get(Dap4Util.DAP4ENDIANTAG);
        setEndianness(dmr, order);

        // Process any constraint view
        CEConstraint ce = null;
        String sce = drq.queryLookup(DapProtocol.CONSTRAINTTAG);
        ce = CEConstraint.compile(sce, dmr);
        setConstraint(dmr, ce);

        // Provide a PrintWriter for capturing the DMR.
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        // Get the DMR as a string
        DMRPrinter dapprinter = new DMRPrinter(dmr, ce, pw, drq.getFormat());
        if(cxt.get(Dap4Util.DAP4TESTTAG) != null)
            dapprinter.testprint();
        else
            dapprinter.print();
        pw.close();
        sw.close();

        String sdmr = sw.toString();
        if(DEBUG)
            System.err.println("Sending: DMR:\n" + sdmr);

        addCommonHeaders(drq);// Add relevant headers

        // Wrap the outputstream with a Chunk writer
        OutputStream out = drq.getOutputStream();
        ChunkWriter cw = new ChunkWriter(out, RequestMode.DMR, order);
        cw.cacheDMR(sdmr);
        cw.close();
    }

Process a DMR request.

@param cxt The dap context


protected DapRequest
    getRequestState(HttpServletRequest rq, HttpServletResponse rsp)
            throws IOException
    {
        return new DapRequest(this, rq, rsp);
    }

protected DapRequest getRequestState ( HttpServletRequest rq , HttpServletResponse rsp ) throws IOException { return new DapRequest ( this , rq , rsp ) ; }

Merge the servlet inputs into a single object
for easier transport as well as adding value.

@param rq  A Servlet request object
@param rsp A Servlet response object
@return the union of the
servlet request and servlet response arguments
from the servlet engine.

Merge the servlet inputs into a single object for easier transport as well as adding value .


protected void
    senderror(DapRequest drq, int httpcode, Throwable t)
            throws IOException
    {
        if(httpcode == 0) httpcode = HttpServletResponse.SC_BAD_REQUEST;
        ErrorResponse err = new ErrorResponse();
        err.setCode(httpcode);
        if(t == null) {
            err.setMessage("Servlet error: " + drq.getURL());
        } else {
            StringWriter sw = new StringWriter();
            PrintWriter p = new PrintWriter(sw);
            t.printStackTrace(p);
            p.close();
            sw.close();
            err.setMessage(sw.toString());
        }
        err.setContext(drq.getURL());
        String errormsg = err.buildXML();
        drq.getResponse().sendError(httpcode, errormsg);
    }

protected
void
senderror
(
DapRequest
drq
,
int
httpcode
,
Throwable
t
)
throws
IOException
{
if
(
httpcode
==
0
)
httpcode
=
HttpServletResponse
.
SC_BAD_REQUEST
;
ErrorResponse
err
=
new
ErrorResponse
(
)
;
err
.
setCode
(
httpcode
)
;
if
(
t
==
)
{
err
.
setMessage
(
"Servlet error: "
+
drq
.
getURL
(
)
)
;
}
else
{
StringWriter
sw
=
new
StringWriter
(
)
;
PrintWriter
p
=
new
PrintWriter
(
sw
)
;
t
.
printStackTrace
(
p
)
;
p
.
close
(
)
;
sw
.
close
(
)
;
err
.
setMessage
(
sw
.
toString
(
)
)
;
}
err
.
setContext
(
drq
.
getURL
(
)
)
;
String
errormsg
=
err
.
buildXML
(
)
;
drq
.
getResponse
(
)
.
sendError
(
httpcode
,
errormsg
)
;
}

Generate an error based on the parameters

@param drq      DapRequest
@param httpcode 0=>no code specified
@param t        exception that caused the error; may be null
@throws IOException


public boolean anchor(Point p) {
    firstStretch = true;
    anchorPt.x = p.x;
    anchorPt.y = p.y;

    stretchedPt.x = lastPt.x = anchorPt.x;
    stretchedPt.y = lastPt.y = anchorPt.y;

    return true;
  }

public boolean anchor ( Point p ) { firstStretch = true ; anchorPt . x = p . x ; anchorPt . y = p . y ; stretchedPt . x = lastPt . x = anchorPt . x ; stretchedPt . y = lastPt . y = anchorPt . y ; return true ; }


public void stretch(Point p) {
    lastPt.x      = stretchedPt.x;
    lastPt.y      = stretchedPt.y;
    stretchedPt.x = p.x;
    stretchedPt.y = p.y;

    Graphics2D g = (Graphics2D) component.getGraphics();
    if(g != null) {
     try {
       g.setXORMode(component.getBackground());
       if(firstStretch == true)
         firstStretch = false;
       else
         drawLast(g);
       drawNext(g);
     }
     finally {
       g.dispose();
     } // try
    } // if
  }

public
void
stretch
(
Point
p
)
{
lastPt
.
x
=
stretchedPt
.
x
;
lastPt
.
y
=
stretchedPt
.
y
;
stretchedPt
.
x
=
p
.
x
;
stretchedPt
.
y
=
p
.
y
;
Graphics2D
g
=
(
Graphics2D
)
component
.
getGraphics
(
)
;
if
(
g
!=
)
{
try
{
g
.
setXORMode
(
component
.
getBackground
(
)
)
;
if
(
firstStretch
==
true
)
firstStretch
=
false
;
else
drawLast
(
g
)
;
drawNext
(
g
)
;
}
finally
{
g
.
dispose
(
)
;
}
// try
}
// if
}

Erase the last rectangle and draw a new one from the anchor point to this point.

Erase the last rectangle and draw a new one from the anchor point to this point .


public Rectangle getBounds() {
    return new Rectangle(stretchedPt.x < anchorPt.x ?
                         stretchedPt.x : anchorPt.x,
                         stretchedPt.y < anchorPt.y ?
                         stretchedPt.y : anchorPt.y,
                         Math.abs(stretchedPt.x - anchorPt.x),
                         Math.abs(stretchedPt.y - anchorPt.y));
  }

public Rectangle getBounds ( ) { return new Rectangle ( stretchedPt . x < anchorPt . x ? stretchedPt . x : anchorPt . x , stretchedPt . y < anchorPt . y ? stretchedPt . y : anchorPt . y , Math . abs ( stretchedPt . x - anchorPt . x ) , Math . abs ( stretchedPt . y - anchorPt . y ) ) ; }


public Rectangle lastBounds() {
    return new Rectangle(
                lastPt.x < anchorPt.x ? lastPt.x : anchorPt.x,
                lastPt.y < anchorPt.y ? lastPt.y : anchorPt.y,
                Math.abs(lastPt.x - anchorPt.x),
                Math.abs(lastPt.y - anchorPt.y));
  }

public Rectangle lastBounds ( ) { return new Rectangle ( lastPt . x < anchorPt . x ? lastPt . x : anchorPt . x , lastPt . y < anchorPt . y ? lastPt . y : anchorPt . y , Math . abs ( lastPt . x - anchorPt . x ) , Math . abs ( lastPt . y - anchorPt . y ) ) ; }


private Date dateOnlyFormat(String text) throws java.text.ParseException {
    text = (text == null) ? "" : text.trim();
    dateOnlyFormat();
    return dateOnlyFormat.parse(text);
  }

private Date dateOnlyFormat ( String text ) throws java . text . ParseException { text = ( text == null ) ? "" : text . trim ( ) ; dateOnlyFormat ( ) ; return dateOnlyFormat . parse ( text ) ; }

Parse text in the format "yyyy-MM-dd"
@param text parse this text
@return equivalent Date
@throws java.text.ParseException if not formatted correctly


protected void replaceDataVars(StructureMembers sm) {
    for (StructureMembers.Member m : sm.getMembers()) {
      VariableSimpleIF org = this.cols.get(m.getName());
      int rank = org.getRank();
      List<Dimension> orgDims = org.getDimensions();
      // only keep the last n
      int n = m.getShape().length;
      List<Dimension> dims = orgDims.subList(rank-n, rank);
      VariableSimpleImpl result = new VariableSimpleImpl(org.getShortName(), org.getDescription(), org.getUnitsString(), org.getDataType(), dims);
      for (Attribute att : org.getAttributes()) result.add(att);
      this.cols.put(m.getName(), result);
    }
  }

protected
void
replaceDataVars
(
StructureMembers
sm
)
{
for
(
StructureMembers
.
Member
m
:
sm
.
getMembers
(
)
)
{
VariableSimpleIF
org
=
this
.
cols
.
get
(
m
.
getName
(
)
)
;
int
rank
=
org
.
getRank
(
)
;
List
<
Dimension
>
orgDims
=
org
.
getDimensions
(
)
;
// only keep the last n
int
n
=
m
.
getShape
(
)
.
length
;
List
<
Dimension
>
dims
=
orgDims
.
subList
(
rank
n
,
rank
)
;
VariableSimpleImpl
result
=
new
VariableSimpleImpl
(
org
.
getShortName
(
)
,
org
.
getDescription
(
)
,
org
.
getUnitsString
(
)
,
org
.
getDataType
(
)
,
dims
)
;
for
(
Attribute
att
:
org
.
getAttributes
(
)
)
result
.
(
att
)
;
this
.
cols
.
put
(
m
.
getName
(
)
,
result
)
;
}
}


public static void ensureArraySizeOkay(long tSize, String attributeTo) {
        if (tSize >= Integer.MAX_VALUE)
            throw new RuntimeException(memoryTooMuchData + "  " +
                MessageFormat.format(memoryArraySize, "" + tSize, "" + Integer.MAX_VALUE) +
                (attributeTo == null || attributeTo.length() == 0? "" : " (" + attributeTo + ")"));
    }

public
static
void
ensureArraySizeOkay
(
long
tSize
,
String
attributeTo
)
{
if
(
tSize
>=
Integer
.
MAX_VALUE
)
throw
new
RuntimeException
(
memoryTooMuchData
+
"  "
+
MessageFormat
.
format
(
memoryArraySize
,
""
+
tSize
,
""
+
Integer
.
MAX_VALUE
)
+
(
attributeTo
==
||
attributeTo
.
length
(
)
==
0
""
:
" ("
+
attributeTo
+
")"
)
)
;
}

Even if JavaBits is 64, the limit on an array size is Integer.MAX_VALUE.

<p>This is almost identical to EDStatic.ensureArraySizeOkay, but lacks tallying.

@param tSize
@param attributeTo for a WARNING or ERROR message, this is the string
to which this not-enough-memory issue should be attributed.

Even if JavaBits is 64 the limit on an array size is Integer . MAX_VALUE .


public static int int2(RandomAccessFile raf) throws IOException {
    int a = raf.read();
    int b = raf.read();

    return int2(a, b);
  }

public static int int2 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; return int2 ( a , b ) ; }

Convert 2 bytes into a signed integer.

@param raf read from here
@return integer value
@throws IOException on read error


public static int uint(RandomAccessFile raf) throws IOException {
     int a = raf.read();
     return (int) DataType.unsignedByteToShort((byte) a);
   }

public static int uint ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; return ( int ) DataType . unsignedByteToShort ( ( byte ) a ) ; }

Convert unsigned bytes into an integer.

@param raf read one byte from here
@return integer value
@throws IOException on read error

Convert unsigned bytes into an integer .


public static int int3(RandomAccessFile raf) throws IOException {
    int a = raf.read();
    int b = raf.read();
    int c = raf.read();

    return int3(a, b, c);
  }

public static int int3 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; return int3 ( a , b , c ) ; }

Convert 3 bytes into a signed integer.

@param raf read from here
@return integer value
@throws IOException on read error


public static int uint2(RandomAccessFile raf) throws IOException {
    int a = raf.read();
    int b = raf.read();

    return uint2(a, b);
  }

public static int uint2 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; return uint2 ( a , b ) ; }

Convert 2 bytes into an unsigned integer.

@param raf read from here
@return integer value
@throws IOException on read error

Convert 2 bytes into an unsigned integer .


public static int uint3(RandomAccessFile raf) throws IOException {
    int a = raf.read();
    int b = raf.read();
    int c = raf.read();

    return uint3(a, b, c);
  }

public static int uint3 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; return uint3 ( a , b , c ) ; }

Convert 3 bytes into an unsigned integer.

@param raf read from here
@return integer
@throws IOException on read error

Convert 3 bytes into an unsigned integer .


public static float float4(RandomAccessFile raf) throws IOException {
    int a = raf.read();
    int b = raf.read();
    int c = raf.read();
    int d = raf.read();

    return float4(a, b, c, d);
  }

public static float float4 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; int d = raf . read ( ) ; return float4 ( a , b , c , d ) ; }

Convert 4 bytes into a float value.

@param raf read from here
@return float value
@throws IOException on read error


public static float float4(int a, int b, int c, int d) {
    int sgn, mant, exp;

    mant = b << 16 | c << 8 | d;
    if (mant == 0) {
      return 0.0f;
    }

    sgn = -(((a & 128) >> 6) - 1);
    exp = (a & 127) - 64;

    return (float) (sgn * Math.pow(16.0, exp - 6) * mant);
  }

public static float float4 ( int a , int b , int c , int d ) { int sgn , mant , exp ; mant = b << 16 | c << 8 | d ; if ( mant == 0 ) { return 0.0f ; } sgn = - ( ( ( a & 128 ) >> 6 ) - 1 ) ; exp = ( a & 127 ) - 64 ; return ( float ) ( sgn * Math . pow ( 16.0 , exp - 6 ) * mant ) ; }

Convert 4 bytes to a float.

@param a first byte
@param b second byte
@param c third byte
@param d fourth byte
@return float


public static long int8(RandomAccessFile raf) throws IOException {
    int a = raf.read();
    int b = raf.read();
    int c = raf.read();
    int d = raf.read();
    int e = raf.read();
    int f = raf.read();
    int g = raf.read();
    int h = raf.read();

    return (1 - ((a & 128) >> 6))
            * ((long)(a & 127) << 56 | (long) b << 48 | (long) c << 40 | (long) d << 32 | e << 24
            | f << 16 | g << 8 | h);

  }

public static long int8 ( RandomAccessFile raf ) throws IOException { int a = raf . read ( ) ; int b = raf . read ( ) ; int c = raf . read ( ) ; int d = raf . read ( ) ; int e = raf . read ( ) ; int f = raf . read ( ) ; int g = raf . read ( ) ; int h = raf . read ( ) ; return ( 1 - ( ( a & 128 ) >> 6 ) ) * ( ( long ) ( a & 127 ) << 56 | ( long ) b << 48 | ( long ) c << 40 | ( long ) d << 32 | e << 24 | f << 16 | g << 8 | h ) ; }

Convert 8 bytes into a signed long.

@param raf RandomAccessFile
@return long value
@throws IOException on read error


public static int countBits(byte[] bitmap) {
    int bits = 0;
    for (byte b : bitmap) {
      short s = DataType.unsignedByteToShort(b);
      bits += Long.bitCount(s);
    }
    return bits;
  }

public static int countBits ( byte [ ] bitmap ) { int bits = 0 ; for ( byte b : bitmap ) { short s = DataType . unsignedByteToShort ( b ) ; bits += Long . bitCount ( s ) ; } return bits ; }


@Override
  public ProjectionImpl constructCopy() {
    ProjectionImpl result =  new LambertConformal(getOriginLat(), getOriginLon(), getParallelOne(), getParallelTwo(),
            getFalseEasting(), getFalseNorthing(), earth_radius);
    result.setDefaultMapArea(defaultMapArea);
    result.setName(name);
    return result;
  }

@ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new LambertConformal ( getOriginLat ( ) , getOriginLon ( ) , getParallelOne ( ) , getParallelTwo ( ) , getFalseEasting ( ) , getFalseNorthing ( ) , earth_radius ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }


public String toWKS() {
    StringBuilder sbuff = new StringBuilder();
    sbuff.append("PROJCS[\"").append(getName()).append("\",");
    if (true) {
      sbuff.append("GEOGCS[\"Normal Sphere (r=6371007)\",");
      sbuff.append("DATUM[\"unknown\",");
      sbuff.append("SPHEROID[\"sphere\",6371007,0]],");
    } else {
      sbuff.append("GEOGCS[\"WGS 84\",");
      sbuff.append("DATUM[\"WGS_1984\",");
      sbuff.append("SPHEROID[\"WGS 84\",6378137,298.257223563],");
      sbuff.append("TOWGS84[0,0,0,0,0,0,0]],");
    }
    sbuff.append("PRIMEM[\"Greenwich\",0],");
    sbuff.append("UNIT[\"degree\",0.0174532925199433]],");
    sbuff.append("PROJECTION[\"Lambert_Conformal_Conic_1SP\"],");
    sbuff.append("PARAMETER[\"latitude_of_origin\",").append(getOriginLat()).append("],");  // LOOK assumes getOriginLat = getParellel
    sbuff.append("PARAMETER[\"central_meridian\",").append(getOriginLon()).append("],");
    sbuff.append("PARAMETER[\"scale_factor\",1],");
    sbuff.append("PARAMETER[\"false_easting\",").append(falseEasting).append("],");
    sbuff.append("PARAMETER[\"false_northing\",").append(falseNorthing).append("],");

    return sbuff.toString();
  }


static public String
    entityEscape(String s, String wrt)
    {
        if(wrt == null)
            wrt = ENTITYESCAPES;
        StringBuilder escaped = new StringBuilder();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            int index = wrt.indexOf(c);
            if(index < 0)
                escaped.append(c);
            else switch (c) {
            case '&':
                escaped.append('&' + ENTITY_AMP + ';');
                break;
            case '<':
                escaped.append('&' + ENTITY_LT + ';');
                break;
            case '>':
                escaped.append('&' + ENTITY_GT + ';');
                break;
            case '"':
                escaped.append('&' + ENTITY_QUOT + ';');
                break;
            case '\'':
                escaped.append('&' + ENTITY_APOS + ';');
                break;
            case '\r':
            case '\t':
            case '\n':
                escaped.append(c);  // These are the only legal control chars
                break;
            case '\0':
                // What to do about nul? currrently we suppress it
                break;
            default:
                if(c >= ' ')
                    escaped.append(c);
                break;
            }
        }
        return escaped.toString();
    }

Escape selected characters in a string using XML entities

@param s   string to escape
@param wrt which chars to escape
@return escaped string


static public String
    backslashUnescape(String s)
    {
        StringBuilder clear = new StringBuilder();
        for(int i = 0; i < s.length(); ) {
            char c = s.charAt(i++);
            if(c == '\\') {
                c = s.charAt(i++);
                switch (c) {
                case 'r':
                    c = '\r';
                    break;
                case 'n':
                    c = '\n';
                    break;
                case 't':
                    c = '\t';
                    break;
                case 'f':
                    c = '\f';
                    break;
                default:
                    break;
                }
                clear.append(c);
            } else
                clear.append(c);
        }
        return clear.toString();
    }

static public String backslashUnescape ( String s ) { StringBuilder clear = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; ) { char c = s . charAt ( i ++ ) ; if ( c == ' ' ) { c = s . charAt ( i ++ ) ; switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : break ; } clear . append ( c ) ; } else clear . append ( c ) ; } return clear . toString ( ) ; }

Remove backslashed characters in a string


static public List<String>
    backslashsplit(String s, char sep)
    {
        List<String> path = new ArrayList<String>();
        int len = s.length();
        StringBuilder piece = new StringBuilder();
        int i = 0;
        for(; i <= len - 1; i++) {
            char c = s.charAt(i);
            if(c == '\\' && i < (len - 1)) {
                piece.append(c); // keep escapes in place
                piece.append(s.charAt(++i));
            } else if(c == sep) {
                path.add(piece.toString());
                piece.setLength(0);
            } else
                piece.append(c);
        }
        path.add(piece.toString());
        return path;
    }

static
public
List
<
String
>
backslashsplit
(
String
s
,
char
sep
)
{
List
<
String
>
path
=
new
ArrayList
<
String
>
(
)
;
int
len
=
s
.
length
(
)
;
StringBuilder
piece
=
new
StringBuilder
(
)
;
int
i
=
0
;
for
(
;
i
<=
len
1
;
i
++
)
{
char
c
=
s
.
charAt
(
i
)
;
if
(
c
==
'
'
&&
i
<
(
len
1
)
)
{
piece
.
append
(
c
)
;
// keep escapes in place
piece
.
append
(
s
.
charAt
(
++
i
)
)
;
}
else
if
(
c
==
sep
)
{
path
.
add
(
piece
.
toString
(
)
)
;
piece
.
setLength
(
0
)
;
}
else
piece
.
append
(
c
)
;
}
path
.
add
(
piece
.
toString
(
)
)
;
return
path
;
}

Split a string with respect to a separator
character and taking backslashes into consideration.

@param s   The string to split
@param sep The character on which to split
@return a List of strings (all with escaping still intact)
representing s split at unescaped instances of sep.

Split a string with respect to a separator character and taking backslashes into consideration .


private FmrcInv makeFmrcInv(Formatter debug) throws IOException {
    try {
      Map<CalendarDate, FmrInv> fmrMap = new HashMap<>(); // all files are grouped by run date in an FmrInv
      List<FmrInv> fmrList = new ArrayList<>(); // an fmrc is a collection of fmr

      // get the inventory, sorted by path
      for (MFile f : manager.getFilesSorted()) {
        Map<String, String> filesRunDateMap = ((MFileCollectionManager) manager).getFilesRunDateMap();
        CalendarDate runDate;

        if (!filesRunDateMap.isEmpty()) {
          // run time has been defined in NcML FMRC agg by the coord attribute,
          // so explicitly set it in the dataset using the _Coordinate.ModelBaseDate
          // global attribute, otherwise the run time offsets might be incorrectly
          // computed if the incorrect run date is found in GridDatasetInv.java (line
          // 177 with comment // Look: not really right )
          runDate = CalendarDate.parseISOformat(null, filesRunDateMap.get(f.getPath()));
          Element element = new Element("netcdf", ncNSHttps);
          Element runDateAttr = ncmlWriter.makeAttributeElement(new Attribute(_Coordinate.ModelRunDate, runDate.toString()));
          config.innerNcml = element.addContent(runDateAttr);
        }

        GridDatasetInv inv;
        try {
          inv = GridDatasetInv.open(manager, f, config.innerNcml); // inventory is discovered for each GDS
        } catch (IOException ioe) {
          logger.warn("Error opening " + f.getPath() + "(skipped)", ioe);
          continue; // skip
        }

        runDate = inv.getRunDate();
        if (debug != null) debug.format("  opened %s rundate = %s%n", f.getPath(), inv.getRunDateString());

        // add to fmr for that rundate
        FmrInv fmr = fmrMap.get(runDate);
        if (fmr == null) {
          fmr = new FmrInv(runDate);
          fmrMap.put(runDate, fmr);
          fmrList.add(fmr);
        }
        fmr.addDataset(inv, debug);
      }
      if (debug != null) debug.format("%n");

      // finish the FmrInv
      Collections.sort(fmrList);
      for (FmrInv fmr : fmrList) {
        fmr.finish();
        if (logger.isDebugEnabled())
          logger.debug("Fmrc:"+config.name+": made fmr with rundate="+fmr.getRunDate()+" nfiles= "+fmr.getFiles().size());
      }

      return new FmrcInv("fmrc:"+manager.getCollectionName(), fmrList, config.fmrcConfig.regularize);

    } catch (Throwable t) {
      logger.error("makeFmrcInv", t);
      throw new RuntimeException(t);
    }
  }


static public String getServiceSpecial(String path) {
    String ss = null;
    if (path.startsWith("/dqcServlet"))
      ss = "dqcServlet";
    else if (path.startsWith("/cdmvalidator"))
      ss = "cdmvalidator";
    return ss;
  }

static public String getServiceSpecial ( String path ) { String ss = null ; if ( path . startsWith ( "/dqcServlet" ) ) ss = "dqcServlet" ; else if ( path . startsWith ( "/cdmvalidator" ) ) ss = "cdmvalidator" ; return ss ; }


public int projectedComponents(boolean constrained) {
            int comp;

            if (constrained) {
                comp = ((DArray)arrayVar).isProject() ? 1 : 0;

                Enumeration e = mapVars.elements();

                while (e.hasMoreElements()) {
                    if (((DArray) e.nextElement()).isProject())
                        comp++;
                }
            } else {
                comp = 1 + mapVars.size();
            }

            return comp;
        }

public int projectedComponents ( boolean constrained ) { int comp ; if ( constrained ) { comp = ( ( DArray ) arrayVar ) . isProject ( ) ? 1 : 0 ; Enumeration e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { if ( ( ( DArray ) e . nextElement ( ) ) . isProject ( ) ) comp ++ ; } } else { comp = 1 + mapVars . size ( ) ; } return comp ; }

How many prohected components of this Grid object?

@return The number of projected components.


public final CalendarDate getReferenceTime() {
    int sec = (second < 0 || second > 59) ? 0 : second;
    return CalendarDate.of(null, year, month, day, hour, minute, sec);
  }

public final CalendarDate getReferenceTime ( ) { int sec = ( second < 0 || second > 59 ) ? 0 : second ; return CalendarDate . of ( null , year , month , day , hour , minute , sec ) ; }

return record header time as a CalendarDate

@return referenceTime


static public ArrayStructureBB factory(ArrayStructureBB org, Section section) {
    if (section == null || section.computeSize() == org.getSize())
      return org;
    return new ArrayStructureBBsection(org.getStructureMembers(), org.getShape(), org.getByteBuffer(), section);
  }

static public ArrayStructureBB factory ( ArrayStructureBB org , Section section ) { if ( section == null || section . computeSize ( ) == org . getSize ( ) ) return org ; return new ArrayStructureBBsection ( org . getStructureMembers ( ) , org . getShape ( ) , org . getByteBuffer ( ) , section ) ; }

Make a section of an ArrayStructureBB

@param org the original
@param section of the whole
@return original, if section is empty or the same saze as the original, else a section of the original


public static void main1(String[] args) {

    if (INDEX_DIR.exists()) {
      System.out.println("Cannot save index to '" + INDEX_DIR + "' directory, please delete it first");
      System.exit(1);
    }

    LuceneIndexer indexer = new LuceneIndexer();
    Date start = new Date();
    try {
      IndexWriter writer = new IndexWriter(INDEX_DIR, new StandardAnalyzer(), true);
      System.out.println("Indexing to directory '" + INDEX_DIR + "'...");
      indexer.indexDocs(writer, DOC_DIR);
      System.out.println("Optimizing...");
      writer.optimize();
      writer.close();

      Date end = new Date();
      System.out.println(end.getTime() - start.getTime() + " total milliseconds");

    } catch (IOException e) {
      System.out.println(" caught a " + e.getClass() + "\n with message: " + e.getMessage());
    }
  }

public
static
void
main1
(
String
[
]
args
)
{
if
(
INDEX_DIR
.
exists
(
)
)
{
System
.
out
.
println
(
"Cannot save index to '"
+
INDEX_DIR
+
"' directory, please delete it first"
)
;
System
.
exit
(
1
)
;
}
LuceneIndexer
indexer
=
new
LuceneIndexer
(
)
;
Date
start
=
new
Date
(
)
;
try
{
IndexWriter
writer
=
new
IndexWriter
(
INDEX_DIR
,
new
StandardAnalyzer
(
)
,
true
)
;
System
.
out
.
println
(
"Indexing to directory '"
+
INDEX_DIR
+
"'..."
)
;
indexer
.
indexDocs
(
writer
,
DOC_DIR
)
;
System
.
out
.
println
(
"Optimizing..."
)
;
writer
.
optimize
(
)
;
writer
.
close
(
)
;
Date
end
=
new
Date
(
)
;
System
.
out
.
println
(
end
.
getTime
(
)
start
.
getTime
(
)
+
" total milliseconds"
)
;
}
catch
(
IOException
e
)
{
System
.
out
.
println
(
" caught a "
+
e
.
getClass
(
)
+
"\n with message: "
+
e
.
getMessage
(
)
)
;
}
}

Index all text files under a directory .


private Grib1Record readRecord(Grib1IndexProto.Grib1Record p) {
    Grib1SectionIndicator is = new Grib1SectionIndicator(p.getGribMessageStart(), p.getGribMessageLength());
    Grib1SectionProductDefinition pds = new Grib1SectionProductDefinition(p.getPds().toByteArray());

    Grib1SectionGridDefinition gds = pds.gdsExists() ? gdsList.get(p.getGdsIdx()) : new Grib1SectionGridDefinition(pds);
    Grib1SectionBitMap bms = pds.bmsExists() ? new Grib1SectionBitMap(p.getBmsPos()) : null;

    Grib1SectionBinaryData dataSection = new Grib1SectionBinaryData(p.getDataPos(), p.getDataLen());
    return new Grib1Record(p.getHeader().toByteArray(), is, gds, pds, bms, dataSection);
  }

private Grib1Record readRecord ( Grib1IndexProto . Grib1Record p ) { Grib1SectionIndicator is = new Grib1SectionIndicator ( p . getGribMessageStart ( ) , p . getGribMessageLength ( ) ) ; Grib1SectionProductDefinition pds = new Grib1SectionProductDefinition ( p . getPds ( ) . toByteArray ( ) ) ; Grib1SectionGridDefinition gds = pds . gdsExists ( ) ? gdsList . get ( p . getGdsIdx ( ) ) : new Grib1SectionGridDefinition ( pds ) ; Grib1SectionBitMap bms = pds . bmsExists ( ) ? new Grib1SectionBitMap ( p . getBmsPos ( ) ) : null ; Grib1SectionBinaryData dataSection = new Grib1SectionBinaryData ( p . getDataPos ( ) , p . getDataLen ( ) ) ; return new Grib1Record ( p . getHeader ( ) . toByteArray ( ) , is , gds , pds , bms , dataSection ) ; }


public static boolean isMine(NetcdfFile ncfile) {
    return (null != ncfile.findGlobalAttribute("XORIG"))
            && (null != ncfile.findGlobalAttribute("YORIG"))
            && (null != ncfile.findGlobalAttribute("XCELL"))
            && (null != ncfile.findGlobalAttribute("YCELL"))
            && (null != ncfile.findGlobalAttribute("NCOLS"))
            && (null != ncfile.findGlobalAttribute("NROWS"));

    // M3IOVGGridConvention - is this true for this class ??
    // return ncFile.findGlobalAttribute( "VGLVLS" ) != null && isValidM3IOFile_( ncFile );

  }

Do we think this is a M3IO file.

@param ncfile the NetcdfFile to test
@return true if we think this is a M3IO file.


private CoordinateTransform makeUTMProjection(NetcdfDataset ds) {
    int zone = (int) findAttributeDouble(ds, "P_ALP");
    double ycent = findAttributeDouble(ds, "YCENT");
    //double lon0 = findAttributeDouble( "X_CENT");
    //double lat0 = findAttributeDouble( "Y_CENT");

    /**
     * Construct a UTM Projection.
     * @param zone - UTM zone
     * @param if ycent < 0, then isNorth = False
     */
    boolean isNorth = true;
    if (ycent < 0)
      isNorth = false;
    UtmProjection utm = new UtmProjection(zone, isNorth);

    return new ProjectionCT("UTM", "EPSG", utm);
  }

Intend to use EPSG system parameters

@param ds dataset
@return CoordinateTransform


public void reacquire() throws IOException {
    try {
      areaReader.af = new AreaFile(location);
    } catch (Throwable e) {
      throw new IOException(e);
    }
  }

public void reacquire ( ) throws IOException { try { areaReader . af = new AreaFile ( location ) ; } catch ( Throwable e ) { throw new IOException ( e ) ; } }

reacquire any resources like file handles


public boolean before(Date d) {
    if (isPresent()) return false;
    return date.isBefore(CalendarDate.of(d));
  }

public boolean before ( Date d ) { if ( isPresent ( ) ) return false ; return date . isBefore ( CalendarDate . of ( d ) ) ; }

Is this date before the given date. if isPresent, always false.

@param d test against this date
@return true if this date before the given date

Is this date before the given date . if isPresent always false .


public boolean before(DateType d) {
    if (d.isPresent()) return true;
    if (isPresent()) return false;
    return date.isBefore(d.getCalendarDate());
  }

public boolean before ( DateType d ) { if ( d . isPresent ( ) ) return true ; if ( isPresent ( ) ) return false ; return date . isBefore ( d . getCalendarDate ( ) ) ; }

Is this date before the given date. if d.isPresent, always true, else if this.isPresent, false.

@param d test against this date
@return true if this date before the given date

Is this date before the given date . if d . isPresent always true else if this . isPresent false .


public boolean after(Date d) {
    if (isPresent()) return true;
    return date.isAfter(CalendarDate.of(d));
  }

public boolean after ( Date d ) { if ( isPresent ( ) ) return true ; return date . isAfter ( CalendarDate . of ( d ) ) ; }

Is this date after the given date. if isPresent, always true.

@param d test against this date
@return true if this date after the given date

Is this date after the given date . if isPresent always true .


public final void setValue(int i, BaseType newVal) {
        vals[i] = newVal;
        BaseType parent = (BaseType)getTemplate().getParent();
        vals[i].setParent(parent);
    }

public final void setValue ( int i , BaseType newVal ) { vals [ i ] = newVal ; BaseType parent = ( BaseType ) getTemplate ( ) . getParent ( ) ; vals [ i ] . setParent ( parent ) ; }

Set the i'th value of the array.

@param i      the index of the value to set.
@param newVal the new value.


public void addCoordinateSystem( CoordinateSystem cs){
    if (cs == null)
      throw new RuntimeException("Attempted to add null CoordinateSystem to var " + forVar.getFullName());

    if (coordSys == null) coordSys = new ArrayList<>(5);
    coordSys.add(cs);
  }


public void setUnitsString( String units) {
    this.units = units;
    forVar.addAttribute( new Attribute(CDM.UNITS, units));
  }

public void setUnitsString ( String units ) { this . units = units ; forVar . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; }

Set the Unit String for this Variable. Default is to use the CDM.UNITS attribute.
@param units  unit string

Set the Unit String for this Variable . Default is to use the CDM . UNITS attribute .


public String getUnitsString() {
    String result = units;
    if ((result == null) && (forVar != null)) {
      Attribute att = forVar.findAttribute( CDM.UNITS);
      if (att == null) att = forVar.findAttributeIgnoreCase( CDM.UNITS);
      if ((att != null) && att.isString())
        result = att.getStringValue();
    }
    return (result == null) ? null : result.trim();
  }

public String getUnitsString ( ) { String result = units ; if ( ( result == null ) && ( forVar != null ) ) { Attribute att = forVar . findAttribute ( CDM . UNITS ) ; if ( att == null ) att = forVar . findAttributeIgnoreCase ( CDM . UNITS ) ; if ( ( att != null ) && att . isString ( ) ) result = att . getStringValue ( ) ; } return ( result == null ) ? null : result . trim ( ) ; }

Get the Unit String for the Variable. May be set explicitly, else look for attribute CDM.UNITS.
@return the Unit String for the Variable, or null if none.

Get the Unit String for the Variable . May be set explicitly else look for attribute CDM . UNITS .


public synchronized void init(ReadMode readMode, PreferencesExt prefs) {
    if (readMode == null)
      readMode = defaultReadMode;
    this.prefs = prefs;
    trackerNumber = prefs.getLong("trackerNumber", 1);
    numberCatalogs = prefs.getInt("numberCatalogs", 10);
    nextCatId = prefs.getLong("nextCatId", 1);

    makeDebugActions();
    this.contentRootPath = this.tdsContext.getThreddsDirectory();
    this.contextPath = tdsContext.getContextPath();

    reread(readMode, true);
  }

public synchronized void init ( ReadMode readMode , PreferencesExt prefs ) { if ( readMode == null ) readMode = defaultReadMode ; this . prefs = prefs ; trackerNumber = prefs . getLong ( "trackerNumber" , 1 ) ; numberCatalogs = prefs . getInt ( "numberCatalogs" , 10 ) ; nextCatId = prefs . getLong ( "nextCatId" , 1 ) ; makeDebugActions ( ) ; this . contentRootPath = this . tdsContext . getThreddsDirectory ( ) ; this . contextPath = tdsContext . getContextPath ( ) ; reread ( readMode , true ) ; }

called from TdsInit on spring-managed auto-wired bean

called from TdsInit on spring - managed auto - wired bean


private ConfigCatalog readCatalog(String catalogRelPath, String catalogFullPath)  {
    URI uri;
    try {
      // uri = new URI("file:" + StringUtil2.escape(catalogFullPath, "/:-_.")); // needed ?
      uri = new URI(this.contextPath + "/catalog/" + catalogRelPath);
    } catch (URISyntaxException e) {
      logCatalogInit.error(ERROR + "readCatalog(): URISyntaxException=" + e.getMessage());
      return null;
    }

    ConfigCatalogBuilder builder = new ConfigCatalogBuilder();
    try {
      // read the catalog
      logCatalogInit.info("-------readCatalog(): path=" + catalogRelPath);
      ConfigCatalog cat = (ConfigCatalog) builder.buildFromLocation(catalogFullPath, uri);
      if (builder.hasFatalError()) {
        logCatalogInit.error(ERROR + "   invalid catalog -- " + builder.getErrorMessage());
        return null;
      }

      if (builder.getErrorMessage().length() > 0)
        logCatalogInit.debug(builder.getErrorMessage());

      return cat;

    } catch (Throwable t) {
      logCatalogInit.error(ERROR + "  Exception on catalog=" + catalogFullPath + " " + t.getMessage() + "\n log=" + builder.getErrorMessage(), t);
      return null;
    }
  }

Does the actual work of reading a catalog.

@param catalogRelPath            reletive path starting from content root
@param catalogFullPath           absolute location on disk
@return the Catalog, or null if failure

Does the actual work of reading a catalog .


private void processDatasets(long catId, ReadMode readMode, String dirPath, List<Dataset> datasets, Set<String> idMap) throws IOException {
    if (exceedLimit) return;

    for (Dataset ds : datasets) {
      if (datasetTracker.trackDataset(catId, ds, callback)) countDatasets++;
      if (maxDatasetsProcess > 0 && countDatasets > maxDatasetsProcess) exceedLimit = true;

      // look for duplicate ids
      String id = ds.getID();
      if (id != null) {
        if (idMap.contains(id)) {
          logCatalogInit.error(ERROR + "Duplicate id on  '" + ds.getName() + "' id= '" + id + "'");
        } else {
          idMap.add(id);
        }
      }

      if ((ds instanceof DatasetScan) || (ds instanceof FeatureCollectionRef)) continue;
      if (ds instanceof CatalogScan) continue;

      if (ds instanceof CatalogRef) { // follow catalog refs
        CatalogRef catref = (CatalogRef) ds;
        String href = catref.getXlinkHref();
        // if (logCatalogInit.isDebugEnabled()) logCatalogInit.debug("  catref.getXlinkHref=" + href);

        // Check that catRef is relative
        if (!href.startsWith("http:")) {
          // Clean up relative URLs that start with "./"
          if (href.startsWith("./")) {
            href = href.substring(2);
          }

          String path;
          String contextPathPlus = this.contextPath + "/";
          if (href.startsWith(contextPathPlus)) {
            path = href.substring(contextPathPlus.length()); // absolute starting from content root
          } else if (href.startsWith("/")) {
            // Drop the catRef because it points to a non-TDS served catalog.
            logCatalogInit.error(ERROR + "Skipping catalogRef <xlink:href=" + href + ">. Reference is relative to the server outside the context path [" + contextPathPlus + "]. " +
                    "Parent catalog info: Name=\"" + catref.getParentCatalog().getName() + "\"; Base URI=\"" + catref.getParentCatalog().getUriString() + "\"; dirPath=\"" + dirPath + "\".");
            continue;
          } else {
            path = dirPath + href;  // reletive starting from current directory
          }

          CatalogExt ext = catalogTracker.get(path);
          long lastRead = (ext == null) ? 0 : ext.getLastRead();
          checkCatalogToRead(readMode, path, false, lastRead);
        }

      } else {
        // recurse through nested datasets
        processDatasets(catId, readMode, dirPath, ds.getDatasetsLocal(), idMap);
      }
    }
  }

dirPath = the directory path, reletive to the rootDir

dirPath = the directory path reletive to the rootDir


private void readCatsInDirectory(ReadMode readMode, String dirPath, Path directory) throws IOException {
    if (exceedLimit) return;

     // do any catalogs first
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory, "*.xml")) {
      for (Path p : ds) {
        if (!Files.isDirectory(p)) {
          // path must be relative to rootDir
          String filename = p.getFileName().toString();
          String path = dirPath.length() == 0 ? filename :  dirPath + "/" + filename;  // reletive starting from current directory

          CatalogExt ext = catalogTracker.get(path);
          long lastRead = (ext == null) ? 0 : ext.getLastRead();
          checkCatalogToRead(readMode, path, false, lastRead);
        }
      }
    }

    // now recurse into the directory
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
       for (Path dir : ds) {
         if (Files.isDirectory(dir)) {
           String dirPathChild = dirPath + "/" + dir.getFileName().toString();  // reletive starting from current directory
           readCatsInDirectory(readMode, dirPathChild, dir);
         }
       }
     }
   }

dirPath is the directory relative to rootDir, directory is absolute

dirPath is the directory relative to rootDir directory is absolute


static public boolean betweenLon(double lon, double lonBeg, double lonEnd) {
    lonBeg = lonNormal(lonBeg, lon);
    lonEnd = lonNormal(lonEnd, lon);
    return (lon >= lonBeg) && (lon <= lonEnd);
  }

static public boolean betweenLon ( double lon , double lonBeg , double lonEnd ) { lonBeg = lonNormal ( lonBeg , lon ) ; lonEnd = lonNormal ( lonEnd , lon ) ; return ( lon >= lonBeg ) && ( lon <= lonEnd ) ; }

Test if point lies between two longitudes, deal with wrapping.

@param lon    point to test
@param lonBeg beginning longitude
@param lonEnd ending longitude
@return true if lon is between lonBeg and lonEnd.
@deprecated

Test if point lies between two longitudes deal with wrapping .


static public String latToString(double lat, int ndec) {
    boolean is_north = (lat >= 0.0);
    if (!is_north)
      lat = -lat;

    String f = "%."+ndec+"f";

    Formatter latBuff = new Formatter();
    latBuff.format(f, lat);
    latBuff.format("%s", is_north ? "N" : "S");

    return latBuff.toString();
  }

static public String latToString ( double lat , int ndec ) { boolean is_north = ( lat >= 0.0 ) ; if ( ! is_north ) lat = - lat ; String f = "%." + ndec + "f" ; Formatter latBuff = new Formatter ( ) ; latBuff . format ( f , lat ) ; latBuff . format ( "%s" , is_north ? "N" : "S" ) ; return latBuff . toString ( ) ; }

Make a nicely formatted representation of a latitude, eg 40.34N or 12.9S.

@param lat       the latitude.
@param ndec      number of digits to right of decimal point
@return String representation.

Make a nicely formatted representation of a latitude eg 40 . 34N or 12 . 9S .


static public String lonToString(double lon, int ndec) {
    double wlon = lonNormal(lon);
    boolean is_east = (wlon >= 0.0);
    if (!is_east)
      wlon = -wlon;

    String f = "%."+ndec+"f";

    Formatter latBuff = new Formatter();
    latBuff.format(f, wlon);
    latBuff.format("%s", is_east ? "E" : "W");

    return latBuff.toString();
  }

static public String lonToString ( double lon , int ndec ) { double wlon = lonNormal ( lon ) ; boolean is_east = ( wlon >= 0.0 ) ; if ( ! is_east ) wlon = - wlon ; String f = "%." + ndec + "f" ; Formatter latBuff = new Formatter ( ) ; latBuff . format ( f , wlon ) ; latBuff . format ( "%s" , is_east ? "E" : "W" ) ; return latBuff . toString ( ) ; }

Make a nicely formatted representation of a longitude, eg 120.3W or 99.99E.

@param lon       the longitude.
@param ndec      number of digits to right of decimal point
@return String representation.

Make a nicely formatted representation of a longitude eg 120 . 3W or 99 . 99E .


public int compareTo(final BaseQuantity that) {
		int comp;
		if (this == that) {
			comp = 0;
		}
		else {
			comp = getName().compareToIgnoreCase(that.getName());
			if (comp == 0 && getSymbol() != null) {
				comp = getSymbol().compareTo(that.getSymbol());
			}
		}
		return comp;
	}

public int compareTo ( final BaseQuantity that ) { int comp ; if ( this == that ) { comp = 0 ; } else { comp = getName ( ) . compareToIgnoreCase ( that . getName ( ) ) ; if ( comp == 0 && getSymbol ( ) != null ) { comp = getSymbol ( ) . compareTo ( that . getSymbol ( ) ) ; } } return comp ; }

Compares this base quantity to another base quantity.

@param that
The BaseQuantity to compare against.
@return An integer that is negative, zero, or positive depending on
whether this BaseQuantity is less than, equal to, or greater than
that.

Compares this base quantity to another base quantity .


public DatasetNode getSelectedDataset() {
    InvCatalogTreeNode tnode = getSelectedNode();
    return tnode == null ? null : tnode.ds;
  }

public DatasetNode getSelectedDataset ( ) { InvCatalogTreeNode tnode = getSelectedNode ( ) ; return tnode == null ? null : tnode . ds ; }

Get the currently selected InvDataset.
@return selected InvDataset, or null if none.


public void setSelectedDataset(Dataset ds) {
    if (ds == null) return;
    TreePath path = makePath(ds);
    if (path == null) return;
    tree.setSelectionPath( path);
    tree.scrollPathToVisible( path);
  }

public void setSelectedDataset ( Dataset ds ) { if ( ds == null ) return ; TreePath path = makePath ( ds ) ; if ( path == null ) return ; tree . setSelectionPath ( path ) ; tree . scrollPathToVisible ( path ) ; }

Set the currently selected InvDataset.
@param ds select this InvDataset, must be already in the tree.
LOOK does this work ?? doesnt throw event


TreePath makeTreePath(TreeNode node) {
    ArrayList<TreeNode> path = new ArrayList<>();
    path.add( node);
    TreeNode parent = node.getParent();
    while (parent != null) {
      path.add(0, parent);
      parent = parent.getParent();
    }

    Object[] paths = path.toArray();
    return new TreePath(paths);
  }

TreePath makeTreePath ( TreeNode node ) { ArrayList < TreeNode > path = new ArrayList <> ( ) ; path . add ( node ) ; TreeNode parent = node . getParent ( ) ; while ( parent != null ) { path . add ( 0 , parent ) ; parent = parent . getParent ( ) ; } Object [ ] paths = path . toArray ( ) ; return new TreePath ( paths ) ; }

Create the TreePath corresponding to the given TreeNode.
@param node the TreeNode; already in the Tree.
@return the corresponding TreePath.

Create the TreePath corresponding to the given TreeNode .


public void openAll( boolean includeCatref) {
    if (catalog == null) return;
    open( (InvCatalogTreeNode) model.getRoot(), includeCatref);
    tree.repaint();
  }

public void openAll ( boolean includeCatref ) { if ( catalog == null ) return ; open ( ( InvCatalogTreeNode ) model . getRoot ( ) , includeCatref ) ; tree . repaint ( ) ; }

Open all nodes of the tree.
@param includeCatref open catrefs?


public void setCatalog(String location) {
    CatalogBuilder builder = new CatalogBuilder();

    try {
      Catalog cat = builder.buildFromLocation(location, null);
      setCatalog(cat);

    } catch (Exception ioe) {
      JOptionPane.showMessageDialog(this, "Error opening catalog location " + location+" err="+builder.getErrorMessage());
    }
  }

public
void
setCatalog
(
String
location
)
{
CatalogBuilder
builder
=
new
CatalogBuilder
(
)
;
try
{
Catalog
cat
=
builder
.
buildFromLocation
(
location
,
)
;
setCatalog
(
cat
)
;
}
catch
(
Exception
ioe
)
{
JOptionPane
.
showMessageDialog
(
this
,
"Error opening catalog location "
+
location
+
" err="
+
builder
.
getErrorMessage
(
)
)
;
}
}

Set the InvCatalog to display.
The catalog is read asynchronously and displayed if successfully read.
You must use a PropertyChangeEventListener to be notified if successful.

@param location The URL of the InvCatalog.

Set the InvCatalog to display . The catalog is read asynchronously and displayed if successfully read . You must use a PropertyChangeEventListener to be notified if successful .


public void setCatalog(Catalog catalog) {
    if (catalog == null) return;
    String catalogName = catalog.getBaseURI().toString();
    this.catalog = catalog;

    // send catalog event
    setCatalogURL( catalogName);

    // display tree
    // this sends TreeNode events
    model = new InvCatalogTreeModel(catalog);
    tree.setModel( model);

      // debug
    if (debugTree) {
      System.out.println("*** catalog/showJTree =");
      showNode(tree.getModel(), tree.getModel().getRoot());
      System.out.println("*** ");
    }

    // look for a specific dataset
    int pos = catalogName.indexOf('#');
    if (pos >= 0) {
      String id = catalogName.substring( pos+1);
      Dataset dataset = catalog.findDatasetByID( id);
      if (dataset != null) {
        setSelectedDataset(dataset);
        firePropertyChangeEvent( new PropertyChangeEvent(this, "Selection", null, dataset));
      }
    }

    // send catalog event
    firePropertyChangeEvent(new PropertyChangeEvent(this, "Catalog", null, catalogName));
  }

public
void
setCatalog
(
Catalog
catalog
)
{
if
(
catalog
==
)
return
;
String
catalogName
=
catalog
.
getBaseURI
(
)
.
toString
(
)
;
this
.
catalog
=
catalog
;
// send catalog event
setCatalogURL
(
catalogName
)
;
// display tree
// this sends TreeNode events
model
=
new
InvCatalogTreeModel
(
catalog
)
;
tree
.
setModel
(
model
)
;
// debug
if
(
debugTree
)
{
System
.
out
.
println
(
"*** catalog/showJTree ="
)
;
showNode
(
tree
.
getModel
(
)
,
tree
.
getModel
(
)
.
getRoot
(
)
)
;
System
.
out
.
println
(
"*** "
)
;
}
// look for a specific dataset
int
pos
=
catalogName
.
indexOf
(
'
'
)
;
if
(
pos
>=
0
)
{
String
id
=
catalogName
.
substring
(
pos
+
1
)
;
Dataset
dataset
=
catalog
.
findDatasetByID
(
id
)
;
if
(
dataset
!=
)
{
setSelectedDataset
(
dataset
)
;
firePropertyChangeEvent
(
new
PropertyChangeEvent
(
this
,
"Selection"
,
,
dataset
)
)
;
}
}
// send catalog event
firePropertyChangeEvent
(
new
PropertyChangeEvent
(
this
,
"Catalog"
,
,
catalogName
)
)
;
}

Set the catalog to be displayed. If ok, then a "Catalog" PropertyChangeEvent is sent.
@param catalog to be displayed

Set the catalog to be displayed . If ok then a Catalog PropertyChangeEvent is sent .


private String findAlias(NetcdfDataset ds, Variable v) {
    String alias = ds.findAttValueIgnoreCase(v, "coord_axis", null);
    if (alias == null)
      alias = ds.findAttValueIgnoreCase(v, "coord_alias", "");
    return alias;
  }

private String findAlias ( NetcdfDataset ds , Variable v ) { String alias = ds . findAttValueIgnoreCase ( v , "coord_axis" , null ) ; if ( alias == null ) alias = ds . findAttValueIgnoreCase ( v , "coord_alias" , "" ) ; return alias ; }

look for an coord_axis or coord_alias attribute


public int writeVInt(int i) throws IOException {
    int count = 0;
    while ((i & ~0x7F) != 0) {
      writeByte((byte) ((i & 0x7f) | 0x80));
      i >>>= 7;
      count++;
    }
    writeByte((byte) i);
    return count + 1;
  }

public int writeVInt ( int i ) throws IOException { int count = 0 ; while ( ( i & ~ 0x7F ) != 0 ) { writeByte ( ( byte ) ( ( i & 0x7f ) | 0x80 ) ) ; i >>>= 7 ; count ++ ; } writeByte ( ( byte ) i ) ; return count + 1 ; }

Writes an int in a variable-length format.  Writes between one and five
bytes.  Smaller values take fewer bytes.  Negative numbers are not
supported.

Writes an int in a variable - length format . Writes between one and five bytes . Smaller values take fewer bytes . Negative numbers are not supported .


public int writeChars(String s, int start, int length) throws IOException {
    final int end = start + length;
    int count = 0;
    for (int i = start; i < end; i++) {
      final int code = (int) s.charAt(i);
      if (code >= 0x01 && code <= 0x7F) {
        writeByte((byte) code);
        count++;
      } else if (((code >= 0x80) && (code <= 0x7FF)) || code == 0) {
        writeByte((byte) (0xC0 | (code >> 6)));
        writeByte((byte) (0x80 | (code & 0x3F)));
        count += 2;
      } else {
        writeByte((byte) (0xE0 | (code >>> 12)));
        writeByte((byte) (0x80 | ((code >> 6) & 0x3F)));
        writeByte((byte) (0x80 | (code & 0x3F)));
        count += 3;
      }
    }
    return count;
  }

public int writeChars ( String s , int start , int length ) throws IOException { final int end = start + length ; int count = 0 ; for ( int i = start ; i < end ; i ++ ) { final int code = ( int ) s . charAt ( i ) ; if ( code >= 0x01 && code <= 0x7F ) { writeByte ( ( byte ) code ) ; count ++ ; } else if ( ( ( code >= 0x80 ) && ( code <= 0x7FF ) ) || code == 0 ) { writeByte ( ( byte ) ( 0xC0 | ( code >> 6 ) ) ) ; writeByte ( ( byte ) ( 0x80 | ( code & 0x3F ) ) ) ; count += 2 ; } else { writeByte ( ( byte ) ( 0xE0 | ( code >>> 12 ) ) ) ; writeByte ( ( byte ) ( 0x80 | ( ( code >> 6 ) & 0x3F ) ) ) ; writeByte ( ( byte ) ( 0x80 | ( code & 0x3F ) ) ) ; count += 3 ; } } return count ; }

Writes a sequence of UTF-8 encoded characters from a string.

@param s      the source of the characters
@param start  the first character in the sequence
@param length the number of characters in the sequence

Writes a sequence of UTF - 8 encoded characters from a string .


public void readChars(char[] buffer, int start, int length) throws IOException {
    final int end = start + length;
    for (int i = start; i < end; i++) {
      byte b = readByte();
      if ((b & 0x80) == 0)
        buffer[i] = (char) (b & 0x7F);
      else if ((b & 0xE0) != 0xE0) {
        buffer[i] = (char) (((b & 0x1F) << 6)
            | (readByte() & 0x3F));
      } else
        buffer[i] = (char) (((b & 0x0F) << 12)
            | ((readByte() & 0x3F) << 6)
            | (readByte() & 0x3F));
    }
  }

public void readChars ( char [ ] buffer , int start , int length ) throws IOException { final int end = start + length ; for ( int i = start ; i < end ; i ++ ) { byte b = readByte ( ) ; if ( ( b & 0x80 ) == 0 ) buffer [ i ] = ( char ) ( b & 0x7F ) ; else if ( ( b & 0xE0 ) != 0xE0 ) { buffer [ i ] = ( char ) ( ( ( b & 0x1F ) << 6 ) | ( readByte ( ) & 0x3F ) ) ; } else buffer [ i ] = ( char ) ( ( ( b & 0x0F ) << 12 ) | ( ( readByte ( ) & 0x3F ) << 6 ) | ( readByte ( ) & 0x3F ) ) ; } }

Reads UTF-8 encoded characters into an array.

@param buffer the array to read characters into
@param start  the offset in the array to start storing characters
@param length the number of characters to read

Reads UTF - 8 encoded characters into an array .


public static void setDebugFlags(ucar.nc2.util.DebugFlags debugFlag) {
    debugRead = debugFlag.isSet("Grib/showRead");
    debugIndexOnly = debugFlag.isSet("Grib/indexOnly");
    debugIndexOnlyShow = debugFlag.isSet("Grib/indexOnlyShow");
    debugGbxIndexOnly = debugFlag.isSet("Grib/debugGbxIndexOnly");
  }

public static void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugRead = debugFlag . isSet ( "Grib/showRead" ) ; debugIndexOnly = debugFlag . isSet ( "Grib/indexOnly" ) ; debugIndexOnlyShow = debugFlag . isSet ( "Grib/indexOnlyShow" ) ; debugGbxIndexOnly = debugFlag . isSet ( "Grib/debugGbxIndexOnly" ) ; }

we are running with only ncx index files, no data

we are running with only ncx index files no data


public void addMember(Member m) {
    members.add(m);
    if (memberHash != null)
      memberHash.put(m.getName(), m);
  }

public void addMember ( Member m ) { members . add ( m ) ; if ( memberHash != null ) memberHash . put ( m . getName ( ) , m ) ; }


public int hideMember(Member m) {
    if (m == null) return -1;
    int index = members.indexOf(m);
    members.remove(m);
    if (memberHash != null) memberHash.remove(m.getName());
    return index;
  }

public int hideMember ( Member m ) { if ( m == null ) return - 1 ; int index = members . indexOf ( m ) ; members . remove ( m ) ; if ( memberHash != null ) memberHash . remove ( m . getName ( ) ) ; return index ; }

Remove the given member
@param m member
@return position that it used to occupy, or -1 if not found


public java.util.List<String> getMemberNames() {
    List<String> memberNames = new ArrayList<>();
    for (Member m : members) {
      memberNames.add(m.getName());
    }
    return memberNames;
  }

public java . util . List < String > getMemberNames ( ) { List < String > memberNames = new ArrayList <> ( ) ; for ( Member m : members ) { memberNames . add ( m . getName ( ) ) ; } return memberNames ; }

Get the names of the members.

@return List of type String.


public Member findMember(String memberName) {
    if (memberName == null) return null;

    if (memberHash == null) { // delay making the hash table until needed
      int initial_capacity = (int) (members.size() / .75) + 1;
      memberHash = new HashMap<>(initial_capacity);
      for (Member m : members)
        memberHash.put(m.getName(), m);
    }
    return memberHash.get(memberName);
  }

Find the member by its name.

@param memberName find by this name
@return Member matching the name, or null if not found


@Nullable
  public byte[] getBitmap(RandomAccessFile raf) throws IOException {
    if (startingPosition <= 0) {
      throw new IllegalStateException("Grib1 Bit map has bad starting position");
    }

    raf.seek(startingPosition);

    // octet 1-3 (length of section)
    int length = GribNumbers.uint3(raf);

    // octet 4 unused bits
    raf.read();   // unused

    // octets 5-6
    int bm = raf.readShort();
    if (bm != 0) {
      logger.warn("Grib1 Bit map section pre-defined (provided by center) bitmap number = {}", bm);
      return null;
    }

    // not sure if length is set correctly when pre-define bitmap is used, so  wait until that to test
    // seeing a -1, bail out
    if (length <= 6 || length > 10e6) {   // look max  ??
      return null;
    }

    // read the bits as integers
    int n = length - 6;
    byte[] data = new byte[n];
    raf.readFully(data);
    return data;
  }

Read the bitmap array when needed, return null if none.

Read the bitmap array when needed return null if none .


public void restoreState(PreferencesExt store) {
    if (store == null)
      return;

    int ncols = table.getColumnCount();

    // stored column order
    int[] modelIndex = (int[]) store.getBean("ColumnOrder", null);

    if ((modelIndex != null) && (modelIndex.length == ncols)) { // what about invisible ??

      // make invisible any not stored
      boolean[] visible = new boolean[ncols];
      for (int aModelIndex : modelIndex)
        if (aModelIndex < ncols)
          visible[aModelIndex] = true;

      // modify popup menu
      for (int i = 0; i < ncols; i++)
        if (!visible[i]) {
          //System.out.println( colName[i]+" hide "+i);
          acts[i].hideColumn();
          acts[i].putValue(BAMutil.STATE, new Boolean(false));
        }

      // now set the header order
      TableColumnModel tcm = table.getColumnModel();
      int n = Math.min(modelIndex.length, table.getColumnCount());
      for (int i = 0; i < n; i++) {
        TableColumn tc = tcm.getColumn(i);
        tc.setModelIndex(modelIndex[i]);
        String name = model.getColumnName(modelIndex[i]);
        tc.setHeaderValue(name);
        tc.setIdentifier(name);
        if (useThreads && (modelIndex[i] == threadCol)) {
          threadHeaderRenderer = new ThreadHeaderRenderer(threadCol);
          tc.setHeaderRenderer(threadHeaderRenderer);
        } else
          tc.setHeaderRenderer(new SortedHeaderRenderer(name, modelIndex[i]));
      }
    }

    // set the column widths
    Object colWidths = store.getBean("ColumnWidths", null);
    if (colWidths == null)
      return;
    int[] size = (int[]) colWidths;
    setColumnWidths(size);

    if (debug) {
      System.out.println(" read widths = ");
      for (int aSize : size)
        System.out.print(" " + aSize);
      System.out.println();
    }

    boolean isThreadsOn = store.getBoolean("isThreadsOn", false);
    if (useThreads) {
      model.setThreadsOn(isThreadsOn);
      threadHeaderRenderer.setOn(isThreadsOn);
    }

    int colNo = store.getInt("SortOnCol", 0);
    boolean reverse = store.getBoolean("SortReverse", false);
    model.setSortCol(colNo);
    model.setReverse(reverse);
    setSortCol(colNo, reverse);

    model.sort();
    table.fireDataChanged();
  }

  private void setColumnWidths(int[] sizes) {
    TableColumnModel tcm = table.getColumnModel();
    for (int i = 0; i < table.getColumnCount(); i++) {
      TableColumn tc = tcm.getColumn(i);
      int maxw = ((sizes == null) || (i >= sizes.length)) ? 10 : sizes[i];
      //     model.getPreferredWidthForColumn(tc) : sizes[i];
      tc.setPreferredWidth(maxw);
    }
    //table.sizeColumnsToFit(0);     //  must be called due to a JTable bug
  }

  public void setColOn(int colno, boolean state, int pos) {
    // System.out.println("setColOn "+colno+" "+state+" "+pos);
    acts[colno].putValue(BAMutil.STATE, new Boolean(state));
    if (state)
      acts[colno].addAtPos(pos);
    else
      acts[colno].hideColumn();
  }

Set the state from the last saved in the PreferencesExt.

@param store ok if null or empty

Set the state from the last saved in the PreferencesExt .


public Iterator getSelectedRows() {
    TreePath[] paths = table.getSelectionPaths();
    if ((paths == null) || (paths.length < 1))
      return null;

    HashSet set = new HashSet(2 * paths.length);
    for (TreePath path : paths) {
      model.addRowsToSetFromPath(table.getTree(), path, set);
    }

    return set.iterator();
  }

public Iterator getSelectedRows ( ) { TreePath [ ] paths = table . getSelectionPaths ( ) ; if ( ( paths == null ) || ( paths . length < 1 ) ) return null ; HashSet set = new HashSet ( 2 * paths . length ) ; for ( TreePath path : paths ) { model . addRowsToSetFromPath ( table . getTree ( ) , path , set ) ; } return set . iterator ( ) ; }

Get the currently selected rows.

@return an Iterator whose objects are TableRow


public int[] getModelIndex() {
    int[] modelIndex = new int[model.getColumnCount()];

    try {
      TableColumnModel tcm = table.getColumnModel();
      for (int i = 0; i < model.getColumnCount(); i++) {
        TableColumn tc = tcm.getColumn(i);
        modelIndex[i] = tc.getModelIndex();
      }
    } catch (java.lang.ArrayIndexOutOfBoundsException e) {
      //can happen when model size increases
    }

    return modelIndex;
  }

public
int
[
]
getModelIndex
(
)
{
int
[
]
modelIndex
=
new
int
[
model
.
getColumnCount
(
)
]
;
try
{
TableColumnModel
tcm
=
table
.
getColumnModel
(
)
;
for
(
int
i
=
0
;
i
<
model
.
getColumnCount
(
)
;
i
++
)
{
TableColumn
tc
=
tcm
.
getColumn
(
i
)
;
modelIndex
[
i
]
=
tc
.
getModelIndex
(
)
;
}
}
catch
(
java
.
lang
.
ArrayIndexOutOfBoundsException
e
)
{
//can happen when model size increases
}
return
modelIndex
;
}

this array translates the column index to the model index


public Array getArray(StructureMembers.Member m) {
    if (m == null) throw new IllegalArgumentException("member is null");
    return memberData.get(m);
  }

public
Array
getArray
(
StructureMembers
.
Member
m
)
{
if
(
m
==
)
throw
new
IllegalArgumentException
(
"member is null"
)
;
return
memberData
.
get
(
m
)
;
}

Get member data array of any type as an Array.
@param m get data from this StructureMembers.Member.
@return Array values.

Get member data array of any type as an Array .


public double getScalarDouble(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getDouble(Index.scalarIndexImmutable);
  }

public double getScalarDouble ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getDouble ( Index . scalarIndexImmutable ) ; }

Get member data of type double.
@param m get data from this StructureMembers.Member. Must be of type double.
@return scalar double value


public double[] getJavaArrayDouble(StructureMembers.Member m) {
    Array data = getArray(m);
    return (double []) data.getStorage();
  }

public double [ ] getJavaArrayDouble ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( double [ ] ) data . getStorage ( ) ; }

Get java double array for a member of type double.
@param m get data from this StructureMembers.Member. Must be of type double.
@return 1D java array of doubles

Get java double array for a member of type double .


public float getScalarFloat(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getFloat(Index.scalarIndexImmutable);
  }

public float getScalarFloat ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getFloat ( Index . scalarIndexImmutable ) ; }

Get member data of type float.
@param m get data from this StructureMembers.Member. Must be of type float.
@return scalar double value


public float[] getJavaArrayFloat(StructureMembers.Member m) {
    Array data = getArray(m);
    return (float []) data.getStorage();
  }

public float [ ] getJavaArrayFloat ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( float [ ] ) data . getStorage ( ) ; }

Get java float array for a member of type float.
@param m get data from this StructureMembers.Member. Must be of type float.
@return 1D java array of floats

Get java float array for a member of type float .


public byte getScalarByte(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getByte(Index.scalarIndexImmutable);
  }

public byte getScalarByte ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getByte ( Index . scalarIndexImmutable ) ; }

Get member data of type byte.
@param m get data from this StructureMembers.Member. Must be of type byte.
@return scalar byte value


public byte[] getJavaArrayByte(StructureMembers.Member m) {
    Array data = getArray(m);
    return (byte []) data.getStorage();
  }

public byte [ ] getJavaArrayByte ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( byte [ ] ) data . getStorage ( ) ; }

Get java byte array for a member of type byte.
@param m get data from this StructureMembers.Member. Must be of type byte.
@return 1D java array of bytes

Get java byte array for a member of type byte .


public int getScalarInt(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getInt(Index.scalarIndexImmutable);
  }

public int getScalarInt ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getInt ( Index . scalarIndexImmutable ) ; }

Get member data of type int.
@param m get data from this StructureMembers.Member. Must be of type int.
@return scalar int value


public int[] getJavaArrayInt(StructureMembers.Member m) {
    Array data = getArray(m);
    return (int []) data.getStorage();
  }

public int [ ] getJavaArrayInt ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( int [ ] ) data . getStorage ( ) ; }

Get java int array for a member of type int.
@param m get data from this StructureMembers.Member. Must be of type int.
@return 1D java array of ints

Get java int array for a member of type int .


public short getScalarShort(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getShort(Index.scalarIndexImmutable);
  }

public short getScalarShort ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getShort ( Index . scalarIndexImmutable ) ; }

Get member data of type short.
@param m get data from this StructureMembers.Member. Must be of type short.
@return scalar short value


public short[] getJavaArrayShort(StructureMembers.Member m) {
    Array data = getArray(m);
    return (short []) data.getStorage();
  }

public short [ ] getJavaArrayShort ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( short [ ] ) data . getStorage ( ) ; }

Get java short array for a member of type short.
@param m get data from this StructureMembers.Member. Must be of type short.
@return 1D java array of shorts

Get java short array for a member of type short .


public long getScalarLong(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getLong(Index.scalarIndexImmutable);
  }

public long getScalarLong ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getLong ( Index . scalarIndexImmutable ) ; }

Get member data of type long.
@param m get data from this StructureMembers.Member. Must be of type long.
@return scalar long value


public long[] getJavaArrayLong(StructureMembers.Member m) {
    Array data = getArray(m);
    return (long []) data.getStorage();
  }

public long [ ] getJavaArrayLong ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( long [ ] ) data . getStorage ( ) ; }

Get java long array for a member of type long.
@param m get data from this StructureMembers.Member. Must be of type long.
@return 1D java array of longs

Get java long array for a member of type long .


public char getScalarChar(StructureMembers.Member m) {
    Array data = getArray(m);
    return data.getChar(Index.scalarIndexImmutable);
  }

public char getScalarChar ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return data . getChar ( Index . scalarIndexImmutable ) ; }

Get member data of type char.
@param m get data from this StructureMembers.Member. Must be of type char.
@return scalar char value


public char[] getJavaArrayChar(StructureMembers.Member m) {
    Array data = getArray(m);
    return (char []) data.getStorage();
  }

public char [ ] getJavaArrayChar ( StructureMembers . Member m ) { Array data = getArray ( m ) ; return ( char [ ] ) data . getStorage ( ) ; }

Get java char array for a member of type char.
@param m get data from this StructureMembers.Member. Must be of type char.
@return 1D java array of chars

Get java char array for a member of type char .


public void doOneDataset( InvDataset ds) {
    if (debug) System.out.println("doDataset "+ds.getName());

    if (isDatasetUseable( ds, messBuffer)) {
      String id = StringUtil2.replace(ds.getID(), "/", "-");
      String fileOutName = fileDir+"/"+id+".dif.xml";
      try {
        OutputStream out = new BufferedOutputStream(new FileOutputStream( fileOutName));
        // writeOneEntry(ds, System.out, mess);
        writeOneEntry(ds, out, messBuffer);
        out.close();
        messBuffer.append(" OK on Write\n");
      } catch (IOException ioe) {
        messBuffer.append("DIFWriter failed on write " + ioe.getMessage() + "\n");
        log.error("DIFWriter failed on write "+ioe.getMessage(), ioe);
      }
    }
  }

public
void
doOneDataset
(
InvDataset
ds
)
{
if
(
debug
)
System
.
out
.
println
(
"doDataset "
+
ds
.
getName
(
)
)
;
if
(
isDatasetUseable
(
ds
,
messBuffer
)
)
{
String
id
=
StringUtil2
.
replace
(
ds
.
getID
(
)
,
"/"
,
"-"
)
;
String
fileOutName
=
fileDir
+
"/"
+
id
+
".dif.xml"
;
try
{
OutputStream
out
=
new
BufferedOutputStream
(
new
FileOutputStream
(
fileOutName
)
)
;
// writeOneEntry(ds, System.out, mess);
writeOneEntry
(
ds
,
out
,
messBuffer
)
;
out
.
close
(
)
;
messBuffer
.
append
(
" OK on Write\n"
)
;
}
catch
(
IOException
ioe
)
{
messBuffer
.
append
(
"DIFWriter failed on write "
+
ioe
.
getMessage
(
)
+
"\n"
)
;
log
.
error
(
"DIFWriter failed on write "
+
ioe
.
getMessage
(
)
,
ioe
)
;
}
}
}

Write a DIF record for a specific dataset
@param ds use this dataset


public boolean isDatasetUseable(InvDataset ds, StringBuilder sbuff) {
    boolean ok = true;
    sbuff.append("Dataset " + ds.getName() + " id = " + ds.getID() + ": ");

    if (!ds.isHarvest()) {
      ok = false;
      sbuff.append("Dataset " + ds.getName() + " id = " + ds.getID() + " has harvest = false\n");
    }

    if (ds.getName() == null) {
      ok = false;
      sbuff.append(" missing Name field\n");
    }

    if (ds.getUniqueID() == null) {
      ok = false;
      sbuff.append(" missing ID field\n");
    }

    ThreddsMetadata.Variables vs = ds.getVariables("DIF");
    if ((vs == null) || (vs.getVariableList().size() == 0))
      vs = ds.getVariables("GRIB-1");
    if ((vs == null) || (vs.getVariableList().size() == 0))
      vs = ds.getVariables("GRIB-2");
    if ((vs == null) || (vs.getVariableList().size() == 0)) {
      ok = false;
      sbuff.append(" missing Variables with DIF or GRIB compatible vocabulary\n");
    }

    List list = ds.getPublishers();
    if ((list == null) || (list.size() == 0)) {
      ok = false;
      sbuff.append(" must have publisher element that defines the data center\n");
    }

    String summary = ds.getDocumentation("summary");
    if (summary == null) {
      ok = false;
      sbuff.append(" must have documentation element of type summary\n");
    }

    sbuff.append(" useable= "+ok+"\n");
    return ok;
  }

See if a dataset is harvestable to a DIF record.

@param ds check this dataset.
@param sbuff  put status messages here.
@return true if a DIF record can be written

See if a dataset is harvestable to a DIF record .


public Dataset copyDataset(DatasetNode parent) {
    return new Dataset(parent, name, flds, accessBuilders, datasetBuilders);
  }

public Dataset copyDataset ( DatasetNode parent ) { return new Dataset ( parent , name , flds , accessBuilders , datasetBuilders ) ; }

make an immutable copy without changin DatasetBuilder


public void transferMetadata( DatasetNode from, boolean parentsAlso) {
    if (parentsAlso) {
      ThreddsMetadata inherit = getInheritableMetadata(); // make sure exists
      inheritMetadata(from, inherit.getFlds());
    }

    // local metadata
    for (Map.Entry<String, Object> entry : from.getFldIterator()) {
      if (parentsAlso && entry.getKey().equals(Dataset.ThreddsMetadataInheritable)) continue; // already did this
      if (Dataset.listFlds.contains(entry.getKey()))
        addToNewList(flds, entry.getKey(), entry.getValue());
      else
        flds.put(entry.getKey(), entry.getValue());
    }

    // tmi must be mutable, transfer if not
    ThreddsMetadata tmiOld = (ThreddsMetadata) get(Dataset.ThreddsMetadataInheritable);
    if (tmiOld != null && tmiOld.isImmutable()) {
      ThreddsMetadata tmiNew = new ThreddsMetadata(tmiOld);
      flds.put(Dataset.ThreddsMetadataInheritable, tmiNew);
    }
  }

public
void
transferMetadata
(
DatasetNode
from
,
boolean
parentsAlso
)
{
if
(
parentsAlso
)
{
ThreddsMetadata
inherit
=
getInheritableMetadata
(
)
;
// make sure exists
inheritMetadata
(
from
,
inherit
.
getFlds
(
)
)
;
}
// local metadata
for
(
Map
.
Entry
<
String
,
Object
>
entry
:
from
.
getFldIterator
(
)
)
{
if
(
parentsAlso
&&
entry
.
getKey
(
)
.
equals
(
Dataset
.
ThreddsMetadataInheritable
)
)
continue
;
// already did this
if
(
Dataset
.
listFlds
.
contains
(
entry
.
getKey
(
)
)
)
addToNewList
(
flds
,
entry
.
getKey
(
)
,
entry
.
getValue
(
)
)
;
else
flds
.
put
(
entry
.
getKey
(
)
,
entry
.
getValue
(
)
)
;
}
// tmi must be mutable, transfer if not
ThreddsMetadata
tmiOld
=
(
ThreddsMetadata
)
get
(
Dataset
.
ThreddsMetadataInheritable
)
;
if
(
tmiOld
!=
&&
tmiOld
.
isImmutable
(
)
)
{
ThreddsMetadata
tmiNew
=
new
ThreddsMetadata
(
tmiOld
)
;
flds
.
put
(
Dataset
.
ThreddsMetadataInheritable
,
tmiNew
)
;
}
}

transfer all metadata, optionally also inheritable metadata from parents

transfer all metadata optionally also inheritable metadata from parents


public ThreddsMetadata getInheritableMetadata() {
    ThreddsMetadata tmi = (ThreddsMetadata) get(Dataset.ThreddsMetadataInheritable);
    if (tmi == null) {
      tmi = new ThreddsMetadata();
      put(Dataset.ThreddsMetadataInheritable, tmi);
    }
    return tmi;
  }

public ThreddsMetadata getInheritableMetadata ( ) { ThreddsMetadata tmi = ( ThreddsMetadata ) get ( Dataset . ThreddsMetadataInheritable ) ; if ( tmi == null ) { tmi = new ThreddsMetadata ( ) ; put ( Dataset . ThreddsMetadataInheritable , tmi ) ; } return tmi ; }

get the inheritable ThreddsMetadata object. If doesnt exist, create new, empty one

get the inheritable ThreddsMetadata object . If doesnt exist create new empty one


void addProduct(GridRecord record) {
    records.add(record);
    if (firstRecord == null) {
      firstRecord = record;
    }
  }

void addProduct ( GridRecord record ) { records . add ( record ) ; if ( firstRecord == null ) { firstRecord = record ; } }

Add in a new product

@param record grid  to add


public void showMissing(Formatter f) {
    //System.out.println("  " +name+" ntimes (across)= "+ ntimes+" nlevs (down)= "+ nlevels+":");
    int count = 0, total = 0;
    f.format("  %s%n", name);
    for (int j = 0; j < nlevels; j++) {
      f.format("   ");
      for (int i = 0; i < ntimes; i++) {
        boolean missing = recordTracker[i * nlevels + j] == null;
        f.format("%s", missing ? "-" : "X");
        if (missing) count++;
        total++;
      }
      f.format("%n");
    }
    f.format("  MISSING= %d / %d for %s%n",count,total, name);
  }

Dump out the missing data
@param f write to this


public int showMissingSummary(Formatter f) {
    int count = 0;
    int total = recordTracker.length;

    for (int i = 0; i < total; i++) {
      if (recordTracker[i] == null)
        count++;
    }

    f.format("  MISSING= %d / %d for %s%n", count, total, name);
    return count;
  }

public
int
showMissingSummary
(
Formatter
f
)
{
int
count
=
0
;
int
total
=
recordTracker
.
length
;
for
(
int
i
=
0
;
i
<
total
;
i
++
)
{
if
(
recordTracker
[
i
]
==
)
count
++
;
}
f
.
format
(
"  MISSING= %d / %d for %s%n"
,
count
,
total
,
name
)
;
return
count
;
}

Dump out the missing data as a summary

@param f write to this
@return number of missing levels