static public boolean iospRegistered(Class iospClass) {
    for (IOServiceProvider spi : registeredProviders) {
      if (spi.getClass() == iospClass) return true;
    }
    return false;
  }

static public boolean iospRegistered ( Class iospClass ) { for ( IOServiceProvider spi : registeredProviders ) { if ( spi . getClass ( ) == iospClass ) return true ; } return false ; }

See if a specific IOServiceProvider is registered

@param iospClass Class for which to search


static public boolean iospDeRegister(Class iospClass) {
      for (int i=0;i<registeredProviders.size();i++) {
        IOServiceProvider spi = registeredProviders.get(i);
        if (spi.getClass() == iospClass) {
          registeredProviders.remove(i);
          return true;
        }
      }
      return false;
  }

static public boolean iospDeRegister ( Class iospClass ) { for ( int i = 0 ; i < registeredProviders . size ( ) ; i ++ ) { IOServiceProvider spi = registeredProviders . get ( i ) ; if ( spi . getClass ( ) == iospClass ) { registeredProviders . remove ( i ) ; return true ; } } return false ; }

See if a specific IOServiceProvider is registered and if so, remove it.

@param iospClass Class for which to search  and remove
@return true if class was present

See if a specific IOServiceProvider is registered and if so remove it .


static public boolean canOpen(String location) throws IOException {
    ucar.unidata.io.RandomAccessFile raf = null;
    try {
      raf = getRaf(location, -1);
      return (raf != null) && canOpen(raf);
    } finally {
      if (raf != null) raf.close();
    }
  }

static public boolean canOpen ( String location ) throws IOException { ucar . unidata . io . RandomAccessFile raf = null ; try { raf = getRaf ( location , - 1 ) ; return ( raf != null ) && canOpen ( raf ) ; } finally { if ( raf != null ) raf . close ( ) ; } }

Find out if the file can be opened, but dont actually open it.
Experimental.

@param location same as open
@return true if can be opened
@throws IOException on read error

Find out if the file can be opened but dont actually open it . Experimental .


public static NetcdfFile openInMemory(String name, byte[] data, String iospClassName) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {

    ucar.unidata.io.InMemoryRandomAccessFile raf = new ucar.unidata.io.InMemoryRandomAccessFile(name, data);
    Class iospClass = NetcdfFile.class.getClassLoader().loadClass(iospClassName);
    IOServiceProvider spi = (IOServiceProvider) iospClass.newInstance();

    return new NetcdfFile(spi, raf, name, null);
  }

public static NetcdfFile openInMemory ( String name , byte [ ] data , String iospClassName ) throws IOException , ClassNotFoundException , IllegalAccessException , InstantiationException { ucar . unidata . io . InMemoryRandomAccessFile raf = new ucar . unidata . io . InMemoryRandomAccessFile ( name , data ) ; Class iospClass = NetcdfFile . class . getClassLoader ( ) . loadClass ( iospClassName ) ; IOServiceProvider spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; return new NetcdfFile ( spi , raf , name , null ) ; }

Open an in-memory netcdf file, with a specific iosp.

@param name          name of the dataset. Typically use the filename or URI.
@param data          in-memory netcdf file
@param iospClassName fully qualified class name of the IOSP class to handle this file
@return NetcdfFile object, or null if cant find IOServiceProver
@throws IOException            if read error
@throws ClassNotFoundException cannat find iospClassName in the class path
@throws InstantiationException if class cannot be instantiated
@throws IllegalAccessException if class is not accessible

Open an in - memory netcdf file with a specific iosp .


public static NetcdfFile openInMemory(String name, byte[] data) throws IOException {
    ucar.unidata.io.InMemoryRandomAccessFile raf = new ucar.unidata.io.InMemoryRandomAccessFile(name, data);
    return open(raf, name, null, null);
  }

public static NetcdfFile openInMemory ( String name , byte [ ] data ) throws IOException { ucar . unidata . io . InMemoryRandomAccessFile raf = new ucar . unidata . io . InMemoryRandomAccessFile ( name , data ) ; return open ( raf , name , null , null ) ; }

Open an in-memory netcdf file.

@param name name of the dataset. Typically use the filename or URI.
@param data in-memory netcdf file
@return memory-resident NetcdfFile
@throws java.io.IOException if error


public static NetcdfFile openInMemory(String filename) throws IOException {
    File file = new File(filename);
    ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
    try (InputStream in = new BufferedInputStream(new FileInputStream(filename))) {
      IO.copy(in, bos);
    }
    return openInMemory(filename, bos.toByteArray());
  }

public static NetcdfFile openInMemory ( String filename ) throws IOException { File file = new File ( filename ) ; ByteArrayOutputStream bos = new ByteArrayOutputStream ( ( int ) file . length ( ) ) ; try ( InputStream in = new BufferedInputStream ( new FileInputStream ( filename ) ) ) { IO . copy ( in , bos ) ; } return openInMemory ( filename , bos . toByteArray ( ) ) ; }

Read a local CDM file into memory. All reads are then done from memory.

@param filename location of CDM file, must be a local file.
@return a NetcdfFile, which is completely in memory
@throws IOException if error reading file

Read a local CDM file into memory . All reads are then done from memory .


public static NetcdfFile openInMemory(URI uri) throws IOException {
    URL url = uri.toURL();
    byte[] contents = IO.readContentsToByteArray(url.openStream());
    return openInMemory(uri.toString(), contents);
  }

public static NetcdfFile openInMemory ( URI uri ) throws IOException { URL url = uri . toURL ( ) ; byte [ ] contents = IO . readContentsToByteArray ( url . openStream ( ) ) ; return openInMemory ( uri . toString ( ) , contents ) ; }

Read a remote CDM file into memory. All reads are then done from memory.

@param uri location of CDM file, must be accessible through url.toURL().openStream().
@return a NetcdfFile, which is completely in memory
@throws IOException if error reading file

Read a remote CDM file into memory . All reads are then done from memory .


public Attribute findGlobalAttributeIgnoreCase(String name) {
    for (Attribute a : gattributes) {
      if (name.equalsIgnoreCase(a.getShortName()))
        return a;
    }
    return null;
  }

public Attribute findGlobalAttributeIgnoreCase ( String name ) { for ( Attribute a : gattributes ) { if ( name . equalsIgnoreCase ( a . getShortName ( ) ) ) return a ; } return null ; }

Look up global Attribute by name, ignore case.

@param name the name of the attribute
@return the attribute, or null if not found

Look up global Attribute by name ignore case .


public String toNcML(String url) throws IOException {
    NcMLWriter ncmlWriter = new NcMLWriter();
    ncmlWriter.setWriteVariablesPredicate(NcMLWriter.writeNoVariablesPredicate);

    Element netcdfElement = ncmlWriter.makeNetcdfElement(this, url);
    return ncmlWriter.writeToString(netcdfElement);
  }

public String toNcML ( String url ) throws IOException { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; ncmlWriter . setWriteVariablesPredicate ( NcMLWriter . writeNoVariablesPredicate ) ; Element netcdfElement = ncmlWriter . makeNetcdfElement ( this , url ) ; return ncmlWriter . writeToString ( netcdfElement ) ; }

CDL representation of Netcdf header info, non strict

CDL representation of Netcdf header info non strict


public void writeCDL(OutputStream out, boolean strict) {
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, CDM.utf8Charset));
    toStringStart(pw, strict);
    toStringEnd(pw);
    pw.flush();
  }

public void writeCDL ( OutputStream out , boolean strict ) { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( out , CDM . utf8Charset ) ) ; toStringStart ( pw , strict ) ; toStringEnd ( pw ) ; pw . flush ( ) ; }

Write CDL representation to OutputStream.

@param out    write to this OutputStream
@param strict if true, make it stricly CDL, otherwise, add a little extra info

Write CDL representation to OutputStream .


public void writeCDL(PrintWriter pw, boolean strict) {
    toStringStart(pw, strict);
    toStringEnd(pw);
    pw.flush();
  }

public void writeCDL ( PrintWriter pw , boolean strict ) { toStringStart ( pw , strict ) ; toStringEnd ( pw ) ; pw . flush ( ) ; }

Write CDL representation to PrintWriter.

@param pw     write to this PrintWriter
@param strict if true, make it stricly CDL, otherwise, add a little extra info

Write CDL representation to PrintWriter .


protected void writeCDL(Formatter f, Indent indent, boolean strict) {
    toStringStart(f, indent, strict);
    f.format("%s}%n", indent);
  }

protected void writeCDL ( Formatter f , Indent indent , boolean strict ) { toStringStart ( f , indent , strict ) ; f . format ( "%s}%n" , indent ) ; }


public Attribute addAttribute(Group parent, Attribute att) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (parent == null) parent = rootGroup;
    parent.addAttribute(att);
    return att;
  }

public
Attribute
addAttribute
(
Group
parent
,
Attribute
att
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
parent
==
)
parent
=
rootGroup
;
parent
.
addAttribute
(
att
)
;
return
att
;
}

Add an attribute to a group.

@param parent add to this group. If group is null, use root group
@param att    add this attribute
@return the attribute that was added


public Attribute addAttribute(Group parent, String name, String value) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (value == null) return null;
    if (parent == null) parent = rootGroup;
    Attribute att = new Attribute(name, value);
    parent.addAttribute(att);
    return att;
  }

public
Attribute
addAttribute
(
Group
parent
,
String
name
,
String
value
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
value
==
)
return
;
if
(
parent
==
)
parent
=
rootGroup
;
Attribute
att
=
new
Attribute
(
name
,
value
)
;
parent
.
addAttribute
(
att
)
;
return
att
;
}

Add optional String attribute to a group.

@param parent add to this group. If group is null, use root group
@param name attribute name, may not be null
@param value attribute value, may be null, in which case, do not addd
@return the attribute that was added

Add optional String attribute to a group .


public Group addGroup(Group parent, Group g) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (parent == null) parent = rootGroup;
    parent.addGroup(g);
    return g;
  }

public
Group
addGroup
(
Group
parent
,
Group
g
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
parent
==
)
parent
=
rootGroup
;
parent
.
addGroup
(
g
)
;
return
g
;
}

Add a group to the parent group.

@param parent add to this group. If group is null, use root group
@param g      add this group
@return the group that was added


public Dimension addDimension(Group parent, Dimension d) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (parent == null) parent = rootGroup;
    parent.addDimension(d);
    return d;
  }

public
Dimension
addDimension
(
Group
parent
,
Dimension
d
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
parent
==
)
parent
=
rootGroup
;
parent
.
addDimension
(
d
)
;
return
d
;
}

Add a shared Dimension to a Group.

@param parent add to this group. If group is null, use root group
@param d      add this Dimension
@return the dimension that was added


public boolean removeDimension(Group g, String dimName) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (g == null) g = rootGroup;
    return g.removeDimension(dimName);
  }

public
boolean
removeDimension
(
Group
g
,
String
dimName
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
g
==
)
g
=
rootGroup
;
return
g
.
removeDimension
(
dimName
)
;
}

Remove a shared Dimension from a Group by name.

@param g       remove from this group. If group is null, use root group
@param dimName name of Dimension to remove.
@return true if found and removed.

Remove a shared Dimension from a Group by name .


public Variable addVariable(Group g, Variable v) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (g == null) g = rootGroup;
    if (v != null) g.addVariable(v);
    return v;
  }

public
Variable
addVariable
(
Group
g
,
Variable
v
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
g
==
)
g
=
rootGroup
;
if
(
v
!=
)
g
.
addVariable
(
v
)
;
return
v
;
}

Add a Variable to the given group.

@param g add to this group. If group is null, use root group
@param v add this Variable
@return the variable that was added


public Variable addVariable(Group g, String shortName, DataType dtype, String dims) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (g == null) g = rootGroup;
    Variable v = new Variable(this, g, null, shortName);
    v.setDataType(dtype);
    v.setDimensions(dims);
    g.addVariable(v);
    return v;
  }

public
Variable
addVariable
(
Group
g
,
String
shortName
,
DataType
dtype
,
String
dims
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
g
==
)
g
=
rootGroup
;
Variable
v
=
new
Variable
(
this
,
g
,
,
shortName
)
;
v
.
setDataType
(
dtype
)
;
v
.
setDimensions
(
dims
)
;
g
.
addVariable
(
v
)
;
return
v
;
}

Create a new Variable, and add to the given group.

@param g         add to this group. If group is null, use root group
@param shortName short name of the Variable
@param dtype     data type of the Variable
@param dims      list of dimension names
@return the new Variable

Create a new Variable and add to the given group .


public Variable addStringVariable(Group g, String shortName, String dims, int strlen) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (g == null) g = rootGroup;
    String dimName = shortName + "_strlen";
    addDimension(g, new Dimension(dimName, strlen));
    Variable v = new Variable(this, g, null, shortName);
    v.setDataType(DataType.CHAR);
    v.setDimensions(dims + " " + dimName);
    g.addVariable(v);
    return v;
  }

public
Variable
addStringVariable
(
Group
g
,
String
shortName
,
String
dims
,
int
strlen
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
g
==
)
g
=
rootGroup
;
String
dimName
=
shortName
+
"_strlen"
;
addDimension
(
g
,
new
Dimension
(
dimName
,
strlen
)
)
;
Variable
v
=
new
Variable
(
this
,
g
,
,
shortName
)
;
v
.
setDataType
(
DataType
.
CHAR
)
;
v
.
setDimensions
(
dims
+
" "
+
dimName
)
;
g
.
addVariable
(
v
)
;
return
v
;
}

Create a new Variable of type Datatype.CHAR, and add to the given group.

@param g         add to this group. If group is null, use root group
@param shortName short name of the Variable
@param dims      list of dimension names
@param strlen    dimension length of the inner (fastest changing) dimension
@return the new Variable

Create a new Variable of type Datatype . CHAR and add to the given group .


public boolean removeVariable(Group g, String varName) {
    if (immutable) throw new IllegalStateException("Cant modify");
    if (g == null) g = rootGroup;
    return g.removeVariable(varName);
  }

public
boolean
removeVariable
(
Group
g
,
String
varName
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
if
(
g
==
)
g
=
rootGroup
;
return
g
.
removeVariable
(
varName
)
;
}

Remove a Variable from the given group by name.

@param g       remove from this group. If group is null, use root group
@param varName name of variable to remove.
@return true is variable found and removed

Remove a Variable from the given group by name .


public Object sendIospMessage(Object message) {
    if (null == message) return null;

    if (message == IOSP_MESSAGE_ADD_RECORD_STRUCTURE) {
      Variable v = rootGroup.findVariable("record");
      boolean gotit = (v != null) && (v instanceof Structure);
      return gotit || makeRecordStructure();

    } else if (message == IOSP_MESSAGE_REMOVE_RECORD_STRUCTURE) {
      Variable v = rootGroup.findVariable("record");
      boolean gotit = (v != null) && (v instanceof Structure);
      if (gotit) {
        rootGroup.remove(v);
        variables.remove(v);
        removeRecordStructure();
      }
      return (gotit);
    }

    if (spi != null)
      return spi.sendIospMessage(message);
    return null;
  }

public Object sendIospMessage ( Object message ) { if ( null == message ) return null ; if ( message == IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) { Variable v = rootGroup . findVariable ( "record" ) ; boolean gotit = ( v != null ) && ( v instanceof Structure ) ; return gotit || makeRecordStructure ( ) ; } else if ( message == IOSP_MESSAGE_REMOVE_RECORD_STRUCTURE ) { Variable v = rootGroup . findVariable ( "record" ) ; boolean gotit = ( v != null ) && ( v instanceof Structure ) ; if ( gotit ) { rootGroup . remove ( v ) ; variables . remove ( v ) ; removeRecordStructure ( ) ; } return ( gotit ) ; } if ( spi != null ) return spi . sendIospMessage ( message ) ; return null ; }

Generic way to send a "message" to the underlying IOSP.
This message is sent after the file is open. To affect the creation of the file, you must send into the factory method.

@param message iosp specific message
Special:

NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE : tells Netcdf-3 files to make record (unlimited) variables into a structure.
return true if it has a Nectdf-3 record structure

@return iosp specific return, may be null

Generic way to send a message to the underlying IOSP . This message is sent after the file is open . To affect the creation of the file you must send into the factory method .


protected Boolean makeRecordStructure() {
    if (immutable) throw new IllegalStateException("Cant modify");

    Boolean didit = false;
    if ((spi != null) && (spi instanceof N3iosp) && hasUnlimitedDimension()) {
      didit = (Boolean) spi.sendIospMessage(IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
    }
    return didit;
  }

protected
Boolean
makeRecordStructure
(
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
Boolean
didit
=
false
;
if
(
(
spi
!=
)
&&
(
spi
instanceof
N3iosp
)
&&
hasUnlimitedDimension
(
)
)
{
didit
=
(
Boolean
)
spi
.
sendIospMessage
(
IOSP_MESSAGE_ADD_RECORD_STRUCTURE
)
;
}
return
didit
;
}

If there is an unlimited dimension, make all variables that use it into a Structure.
A Variable called "record" is added.
You can then access these through the record structure.

@return true if it has a Nectdf-3 record structure

If there is an unlimited dimension make all variables that use it into a Structure . A Variable called record is added . You can then access these through the record structure .


public void finish() {
    if (immutable) throw new IllegalStateException("Cant modify");
    variables = new ArrayList<>();
    dimensions = new ArrayList<>();
    gattributes = new ArrayList<>();
    finishGroup(rootGroup);
  }

public
void
finish
(
)
{
if
(
immutable
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
variables
=
new
ArrayList
<>
(
)
;
dimensions
=
new
ArrayList
<>
(
)
;
gattributes
=
new
ArrayList
<>
(
)
;
finishGroup
(
rootGroup
)
;
}

Finish constructing the object model.
This construsts the "global" variables, attributes and dimensions.
It also looks for coordinate variables.

Finish constructing the object model . This construsts the global variables attributes and dimensions . It also looks for coordinate variables .


public Array readSection(String variableSection) throws IOException, InvalidRangeException {
    /* if (unlocked)
      throw new IllegalStateException("File is unlocked - cannot use"); */

    ParsedSectionSpec cer = ParsedSectionSpec.parseVariableSection(this, variableSection);
    if (cer.child == null) {
      return cer.v.read(cer.section);
    }

    if (spi == null)
      return IospHelper.readSection(cer);
    else
      // allow iosp to optimize
      return spi.readSection(cer);
  }

Read a variable using the given section specification.
The result is always an array of the type of the innermost variable.
Its shape is the accumulation of all the shapes of its parent structures.

@param variableSection the constraint expression.
@return data requested
@throws IOException           if error
@throws InvalidRangeException if variableSection is invalid
@see SectionSpecification

Read a variable using the given section specification . The result is always an array of the type of the innermost variable . Its shape is the accumulation of all the shapes of its parent structures .


protected long readToByteChannel(ucar.nc2.Variable v, Section section, WritableByteChannel wbc)
          throws java.io.IOException, ucar.ma2.InvalidRangeException {

    //if (unlocked)
    //  throw new IllegalStateException("File is unlocked - cannot use");

    if ((spi == null) || v.hasCachedData())
      return IospHelper.copyToByteChannel(v.read(section), wbc);

    return spi.readToByteChannel(v, section, wbc);
  }

Read data from a top level Variable and send data to a WritableByteChannel. Experimental.

@param v       a top-level Variable
@param section the section of data to read.
There must be a Range for each Dimension in the variable, in order.
Note: no nulls allowed. IOSP may not modify.
@param wbc     write data to this WritableByteChannel
@return the number of bytes written to the channel
@throws java.io.IOException            if read error
@throws ucar.ma2.InvalidRangeException if invalid section

Read data from a top level Variable and send data to a WritableByteChannel . Experimental .


public java.util.List<Array> readArrays(java.util.List<Variable> variables) throws IOException {
    java.util.List<Array> result = new java.util.ArrayList<>();
    for (Variable variable : variables)
      result.add(variable.read());
    return result;
  }

public java . util . List < Array > readArrays ( java . util . List < Variable > variables ) throws IOException { java . util . List < Array > result = new java . util . ArrayList <> ( ) ; for ( Variable variable : variables ) result . ( variable . read ( ) ) ; return result ; }

Do a bulk read on a list of Variables and
return a corresponding list of Array that contains the results
of a full read on each Variable.
This is mostly here so DODSNetcdf can override it with one call to the server.

@param variables List of type Variable
@return List of Array, one for each Variable in the input.
@throws IOException if read error

Do a bulk read on a list of Variables and return a corresponding list of Array that contains the results of a full read on each Variable . This is mostly here so DODSNetcdf can override it with one call to the server .


public Array read(String variableSection, boolean flatten) throws IOException, InvalidRangeException {
    if (!flatten)
      throw new UnsupportedOperationException("NetdfFile.read(String variableSection, boolean flatten=false)");
    return readSection(variableSection);
  }

Read a variable using the given section specification.

@param variableSection the constraint expression.
@param flatten         MUST BE TRUE
@return Array data read.
@throws IOException           if error
@throws InvalidRangeException if variableSection is invalid
@see SectionSpecification
@deprecated use readSection(), flatten=false no longer supported

Read a variable using the given section specification .


static protected String makeFullName(CDMNode node, String reservedChars) {
    Group parent = node.getParentGroup();
    if (((parent == null) || parent.isRoot())
            && !node.isMemberOfStructure()) // common case?
      return EscapeStrings.backslashEscape(node.getShortName(), reservedChars);
    StringBuilder sbuff = new StringBuilder();
    appendGroupName(sbuff, parent, reservedChars);
    appendStructureName(sbuff, node, reservedChars);
    return sbuff.toString();
  }

static
protected
String
makeFullName
(
CDMNode
node
,
String
reservedChars
)
{
Group
parent
=
node
.
getParentGroup
(
)
;
if
(
(
(
parent
==
)
||
parent
.
isRoot
(
)
)
&&
!
node
.
isMemberOfStructure
(
)
)
// common case?
return
EscapeStrings
.
backslashEscape
(
node
.
getShortName
(
)
,
reservedChars
)
;
StringBuilder
sbuff
=
new
StringBuilder
(
)
;
appendGroupName
(
sbuff
,
parent
,
reservedChars
)
;
appendStructureName
(
sbuff
,
node
,
reservedChars
)
;
return
sbuff
.
toString
(
)
;
}

Given a CDMNode, create its full name  with
appropriate backslash escaping of the specified characters.

@param node          the cdm node
@param reservedChars the set of characters to escape
@return full name

Given a CDMNode create its full name with appropriate backslash escaping of the specified characters .


protected String makeFullNameWithString(Group parent, String name) {
    name = makeValidPathName(name); // escape for use in full name
    StringBuilder sbuff = new StringBuilder();
    appendGroupName(sbuff, parent, null);
    sbuff.append(name);
    return sbuff.toString();
  }

protected
String
makeFullNameWithString
(
Group
parent
,
String
name
)
{
name
=
makeValidPathName
(
name
)
;
// escape for use in full name
StringBuilder
sbuff
=
new
StringBuilder
(
)
;
appendGroupName
(
sbuff
,
parent
,
)
;
sbuff
.
append
(
name
)
;
return
sbuff
.
toString
(
)
;
}

Create a synthetic full name from a group plus a string

@param parent parent group
@param name   synthetic name string
@return synthetic name


private boolean include(MFile mfile) {
    if (includeFilters == null) return true;
    for (MFileFilter filter : includeFilters) {
      if (filter.accept(mfile))
        return true;
    }
    return false;
  }

private boolean include ( MFile mfile ) { if ( includeFilters == null ) return true ; for ( MFileFilter filter : includeFilters ) { if ( filter . accept ( mfile ) ) return true ; } return false ; }


private boolean exclude(MFile mfile) {
    if (excludeFilters == null) return false;
    for (MFileFilter filter : excludeFilters) {
      if (filter.accept(mfile))
        return true;
    }
    return false;
  }

private boolean exclude ( MFile mfile ) { if ( excludeFilters == null ) return false ; for ( MFileFilter filter : excludeFilters ) { if ( filter . accept ( mfile ) ) return true ; } return false ; }


private boolean andFilter(MFile mfile) {
    if (andFilters == null) return true;
    for (MFileFilter filter : andFilters) {
      if (!filter.accept(mfile))
        return false;
    }
    return true;
  }

private boolean andFilter ( MFile mfile ) { if ( andFilters == null ) return true ; for ( MFileFilter filter : andFilters ) { if ( ! filter . accept ( mfile ) ) return false ; } return true ; }


public void appendValue(String value, boolean check)
            throws NoSuchAttributeException, AttributeBadValueException
    {

        checkVectorUsage();
        if(check)
            value = forceValue(type, value);

        ((Vector) attr).addElement(value);
    }

public void appendValue ( String value , boolean check ) throws NoSuchAttributeException , AttributeBadValueException { checkVectorUsage ( ) ; if ( check ) value = forceValue ( type , value ) ; ( ( Vector ) attr ) . addElement ( value ) ; }

Append a value to this attribute.

@param value the attribute String to add.
@param check if true, check the validity of he attribute's value, if
false don't.
@throws AttributeBadValueException thrown if the value is not a legal
member of type


private static void dispatchCheckValue(int type, String value)
            throws AttributeBadValueException
    {

        switch (type) {

        case BYTE:
            if(!checkByte(value))
                throw new AttributeBadValueException("`" + value + "' is not a Byte value.");
            break;

        case INT16:
            if(!checkShort(value))
                throw new AttributeBadValueException("`" + value + "' is not an Int16 value.");
            break;

        case UINT16:
            if(!checkUShort(value))
                throw new AttributeBadValueException("`" + value + "' is not an UInt16 value.");
            break;

        case INT32:
            if(!checkInt(value))
                throw new AttributeBadValueException("`" + value + "' is not an Int32 value.");
            break;

        case UINT32:
            if(!checkUInt(value))
                throw new AttributeBadValueException("`" + value + "' is not an UInt32 value.");
            break;

        case FLOAT32:
            if(!checkFloat(value))
                throw new AttributeBadValueException("`" + value + "' is not a Float32 value.");
            break;

        case FLOAT64:
            if(!checkDouble(value))
                throw new AttributeBadValueException("`" + value + "' is not a Float64 value.");
            break;

        //    case BOOLEAN:
        //      if(!checkBoolean(value))
        //	throw new AttributeBadValueException("`" + value + "' is not a Boolean value.");
        //      break;

        default:
            // Assume UNKNOWN, CONTAINER, STRING, and URL are okay.
        }
    }

Check if the value is legal for a given type.

@param type  the type of the value.
@param value the value String.
@throws AttributeBadValueException if the value is not a legal
member of type

Check if the value is legal for a given type .


private static String forceValue(int type, String value)
            throws AttributeBadValueException
    {
        try {
            dispatchCheckValue(type, value);
        } catch (AttributeBadValueException abe) {
            if(type == BYTE) {// Try again: allow e.g. negative byte values
                short val = Short.parseShort(value);
                if(val > 255 && val < -128)
                    throw new AttributeBadValueException("Cannot convert to byte: " + value);
                value = Integer.toString((val&0xFF));
            }
        }
        return value;
    }

Check if the value is legal for a given type
and try to convert to specified type.

@param type  the type of the value.
@param value the value String.
@return original or converted value
@throws AttributeBadValueException if the value is not a legal
member of type

Check if the value is legal for a given type and try to convert to specified type .


private static final boolean checkByte(String s)
            throws AttributeBadValueException
    {
        try {
            // Byte.parseByte() can't be used because values > 127 are allowed
            short val = Short.parseShort(s);
            if(DebugValueChecking) {
                log.debug("Attribute.checkByte() - string: '" + s + "'   value: " + val);
            }
            if(val > 0xFF || val < 0)
                return false;
            else
                return true;
        } catch (NumberFormatException e) {
            throw new AttributeBadValueException("`" + s + "' is not a Byte value.");
        }
    }

Check if string is a valid Byte.

@param s the String to check.
@return true if the value is legal.


private static final boolean checkShort(String s)
    {
        try {
            short val = Short.parseShort(s);
            if(DebugValueChecking) {
                DAPNode.log.debug("Attribute.checkShort() - string: '" + s + "'   value: " + val);
            }
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

private
static
final
boolean
checkShort
(
String
s
)
{
try
{
short
val
=
Short
.
parseShort
(
s
)
;
if
(
DebugValueChecking
)
{
DAPNode
.
log
.
debug
(
"Attribute.checkShort() - string: '"
+
s
+
"'   value: "
+
val
)
;
}
return
true
;
}
catch
(
NumberFormatException
e
)
{
return
false
;
}
}

Check if string is a valid Int16.

@param s the String to check.
@return true if the value is legal.


private static final boolean checkInt(String s)
    {
        try {
            //Coverity[FB.DLS_DEAD_LOCAL_STORE]
            int val = Integer.parseInt(s);
            if(DebugValueChecking) {
                DAPNode.log.debug("Attribute.checkInt() - string: '" + s + "'   value: " + val);
            }
            return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

private
static
final
boolean
checkInt
(
String
s
)
{
try
{
//Coverity[FB.DLS_DEAD_LOCAL_STORE]
int
val
=
Integer
.
parseInt
(
s
)
;
if
(
DebugValueChecking
)
{
DAPNode
.
log
.
debug
(
"Attribute.checkInt() - string: '"
+
s
+
"'   value: "
+
val
)
;
}
return
true
;
}
catch
(
NumberFormatException
e
)
{
return
false
;
}
}

Check if string is a valid Int32.

@param s the String to check.
@return true if the value is legal.


private static final boolean checkUInt(String s)
    {
        // Note: Because there is no Unsigned class in Java, use Long instead.
        try {
            long val = Long.parseLong(s);
            if(DebugValueChecking) {
                DAPNode.log.debug("Attribute.checkUInt() - string: '" + s + "'   value: " + val);
            }
            if(val > 0xFFFFFFFFL)
                return false;
            else
                return true;
        } catch (NumberFormatException e) {
            return false;
        }
    }

Check if string is a valid UInt32.

@param s the String to check.
@return true if the value is legal.


private static final boolean checkFloat(String s)
    {
        try {
            //Coverity[FB.DLS_DEAD_LOCAL_STORE]=
            float val = Float.parseFloat(s);
            if(DebugValueChecking) {
                DAPNode.log.debug("Attribute.checkFloat() - string: '" + s + "'   value: " + val);
            }
            return true;
        } catch (NumberFormatException e) {
            if(s.equalsIgnoreCase("nan") || s.equalsIgnoreCase("inf"))
                return true;

            return false;
        }
    }

private
static
final
boolean
checkFloat
(
String
s
)
{
try
{
//Coverity[FB.DLS_DEAD_LOCAL_STORE]=
float
val
=
Float
.
parseFloat
(
s
)
;
if
(
DebugValueChecking
)
{
DAPNode
.
log
.
debug
(
"Attribute.checkFloat() - string: '"
+
s
+
"'   value: "
+
val
)
;
}
return
true
;
}
catch
(
NumberFormatException
e
)
{
if
(
s
.
equalsIgnoreCase
(
"nan"
)
||
s
.
equalsIgnoreCase
(
"inf"
)
)
return
true
;
return
false
;
}
}

Check if string is a valid Float32.

@param s the String to check.
@return true if the value is legal.


private static final boolean checkDouble(String s)
    {
        try {
            //Coverity[FB.DLS_DEAD_LOCAL_STORE]
            double val = Double.parseDouble(s);
            if(DebugValueChecking) {
                DAPNode.log.debug("Attribute.checkDouble() - string: '" + s + "'   value: " + val);
            }
            return true;
        } catch (NumberFormatException e) {
            if(s.equalsIgnoreCase("nan") || s.equalsIgnoreCase("inf"))
                return true;

            return false;
        }
    }

private
static
final
boolean
checkDouble
(
String
s
)
{
try
{
//Coverity[FB.DLS_DEAD_LOCAL_STORE]
double
val
=
Double
.
parseDouble
(
s
)
;
if
(
DebugValueChecking
)
{
DAPNode
.
log
.
debug
(
"Attribute.checkDouble() - string: '"
+
s
+
"'   value: "
+
val
)
;
}
return
true
;
}
catch
(
NumberFormatException
e
)
{
if
(
s
.
equalsIgnoreCase
(
"nan"
)
||
s
.
equalsIgnoreCase
(
"inf"
)
)
return
true
;
return
false
;
}
}

Check if string is a valid Float64.

@param s the String to check.
@return true if the value is legal.


private DataType getAttributeDataType(Attribute attribute) {
    DataType dataType = attribute.getDataType();
    if (signedness == Signedness.UNSIGNED) {
      // If variable is unsigned, make its integral attributes unsigned too.
      dataType = dataType.withSignedness(signedness);
    }
    return dataType;
  }

Get the data type of an attribute. Make it unsigned if the variable is unsigned.

Get the data type of an attribute . Make it unsigned if the variable is unsigned .


@Override
  public boolean isViewable(Dataset ds) {
    Access access = ds.getAccess(ServiceType.WMS);
    return access != null && (ThreddsConfig.getBoolean("WMS.allow", false));
  }

@ Override public boolean isViewable ( Dataset ds ) { Access access = ds . getAccess ( ServiceType . WMS ) ; return access != null && ( ThreddsConfig . getBoolean ( "WMS.allow" , false ) ) ; }

Returns true if this is a gridded dataset that is accessible via WMS.

Returns true if this is a gridded dataset that is accessible via WMS .


@SuppressWarnings({"SimplifiableIfStatement"})
  public static boolean validBooleanString(String boolString) {
    if (boolString == null)
      return false;
    Matcher m = VALID_CHARACTERS_FOR_BOOLEAN_STRING_PATTERN.matcher(boolString);
    if (!m.matches())
      return false;
    return boolString.equalsIgnoreCase("true")
            || boolString.equalsIgnoreCase("false");
  }

Return true if the given String is "true" or "false", ignoring case.

@param boolString the String to validate.
@return true if the given String is "true" or "false", ignoring case.

Return true if the given String is true or false ignoring case .


public static boolean validAlphanumericString(String alphNumString) {
    if (alphNumString == null)
      return false;
    Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN.matcher(alphNumString);
    return m.matches();
  }

Return true if the given String is an alphanumeric string.

@param alphNumString the String to validate.
@return true if the given String is an alphanumeric string.

Return true if the given String is an alphanumeric string .


public static boolean validAlphanumericStringConstrainedSet(String alphNumString,
                                                              String[] constrainedSet,
                                                              boolean ignoreCase) {
    if (alphNumString == null || constrainedSet == null || constrainedSet.length == 0)
      return false;
    Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN.matcher(alphNumString);
    if (!m.matches())
      return false;
    for (String s : constrainedSet) {
      if (ignoreCase ? alphNumString.equalsIgnoreCase(s) : alphNumString.equals(s))
        return true;
    }
    return false;
  }

Return true if the given String is an alphanumeric string and one of
the valid strings in the constrained set.

@param alphNumString  the String to validate.
@param constrainedSet the set of valid strings
@param ignoreCase     if true ignore the case of the letters
@return true if the given String is an alphanumeric string.

Return true if the given String is an alphanumeric string and one of the valid strings in the constrained set .


@SuppressWarnings({"UnnecessaryContinue"})
  public static boolean descendOnlyFilePath(String path) {
    String[] pathSegments = path.split("/");
    //String[] newPathSegments = new String[pathSegments.length];
    int i = 0;
    for (int indxOrigSegs = 0; indxOrigSegs < pathSegments.length; indxOrigSegs++) {
      String s = pathSegments[indxOrigSegs];
      if (s.equals("."))
        continue;
      else if (s.equals("..")) {
        if (i == 0)
          return false;
        i--;
      } else {
        //newPathSegments[i] = s;
        i++;
      }
    }

    return true;
  }

Return true if the given path does not ascend into parent directory.

@param path the path to check
@return true if the given path does not ascend into parent directory.

Return true if the given path does not ascend into parent directory .


public static String unicodeCodePoint2PercentHexString(int codePoint, String charsetName) {
    if (!Character.isDefined(codePoint))
      throw new IllegalArgumentException(String.format("Given code point [U+%1$04X - %1$d] not assigned to an abstract character.", codePoint));
    if (Character.getType(codePoint) == Character.SURROGATE)
      throw new IllegalArgumentException(String.format("Given code point [U+%1$04X - %1$d] is an unencodable (by itself) surrogate character.", codePoint));

    Charset charset = Charset.availableCharsets().get(charsetName);
    if (charset == null)
      throw new IllegalArgumentException(String.format("Unsupported charset [%s].", charsetName));

    char[] chars = Character.toChars(codePoint);
    ByteBuffer byteBuffer = null;
    try {
      byteBuffer = charset.newEncoder().encode(CharBuffer.wrap(chars));
    } catch (CharacterCodingException e) {
      String message = String.format("Given code point [U+%1$04X - %1$d] cannot be encode in given charset [%2$s].", codePoint, charsetName);
      throw new IllegalArgumentException(message, e);
    }
    byteBuffer.rewind();
    StringBuilder encodedString = new StringBuilder();
    for (int i = 0; i < byteBuffer.limit(); i++) {
      String asHex = Integer.toHexString(byteBuffer.get() & 0xFF);
      encodedString.append("%").append(asHex.length() == 1 ? "0" : "").append(asHex);
    }

    return encodedString.toString();
  }

Return the percentHexOctets string that represents the given Unicode
code point in the given character set or null if the given character
set cannot encode the given code point.

@param codePoint   the given Unicode code point
@param charsetName the name of the character set.
@return the percentHexOctets string that represents the given Unicode code point in the given character set.
@throws IllegalArgumentException if the code point is not defined or the the character set is not supported.

Return the percentHexOctets string that represents the given Unicode code point in the given character set or null if the given character set cannot encode the given code point .


public final String getParam(String key) {
    String value = paramStr.get(key);
    if(value == null) { // check the dbl and int tables
        Double result = paramDbl.get(key);
        if (result != null) {
            value = result.toString();
        } else {
            Integer intResult = paramInt.get(key);
            if (intResult != null) {
                value = intResult.toString();
            }
        }
        // save it back off to the string table for next time
        if (value != null) {
            paramStr.put(key, value);
        }
    }
    if (debug && value == null) {
        System.out.println( key +" value not found");
    }
    return value;
  }

gets a param and value.

@param key name of the param
@return the value or null


public static boolean compare( GridDefRecord local, GridDefRecord other ) {
    java.util.Set<String> keys = local.getKeys();
    java.util.Set<String> okeys = other.getKeys();
    if( keys.size() != okeys.size() )
      return false;

    for( String key : keys ) {
      if( key.equals(WIND_FLAG) || key.equals(RESOLUTION) || key.equals(VECTOR_COMPONENT_FLAG)
        || key.equals(GDS_KEY))
        continue;

      String val = local.getParam( key );
      String oval = other.getParam( key );   //

      if( val.matches( "^[0-9]+\\.[0-9]*")) {
        //double
        double d = local.getDouble( key );
        double od = other.getDouble( key );
        if( ! Misc.nearlyEquals(d, od) )
          return false;
      } else if( val.matches( "^[0-9]+")) {
        // int
        if( !val.equals( oval ))
          return false;
      } else {
        // String
        if( !val.equals( oval ))
          return false;
      }
    }
    return true;
  }

public
static
boolean
compare
(
GridDefRecord
local
,
GridDefRecord
other
)
{
java
.
util
.
Set
<
String
>
keys
=
local
.
getKeys
(
)
;
java
.
util
.
Set
<
String
>
okeys
=
other
.
getKeys
(
)
;
if
(
keys
.
size
(
)
!=
okeys
.
size
(
)
)
return
false
;
for
(
String
key
:
keys
)
{
if
(
key
.
equals
(
WIND_FLAG
)
||
key
.
equals
(
RESOLUTION
)
||
key
.
equals
(
VECTOR_COMPONENT_FLAG
)
||
key
.
equals
(
GDS_KEY
)
)
continue
;
String
val
=
local
.
getParam
(
key
)
;
String
oval
=
other
.
getParam
(
key
)
;
//
if
(
val
.
matches
(
"^[0-9]+\\.[0-9]*"
)
)
{
//double
double
d
=
local
.
getDouble
(
key
)
;
double
od
=
other
.
getDouble
(
key
)
;
if
(
!
Misc
.
nearlyEquals
(
d
,
od
)
)
return
false
;
}
else
if
(
val
.
matches
(
"^[0-9]+"
)
)
{
// int
if
(
!
val
.
equals
(
oval
)
)
return
false
;
}
else
{
// String
if
(
!
val
.
equals
(
oval
)
)
return
false
;
}
}
return
true
;
}

Compare GridDefRecords, the numerics will use nearlyEquals so values that
differ in 3 or 4th decimal places will return equal. This is being coded
because the NDFD model dx differ in the 3 decimal place otherwise equal.

Compare GridDefRecords the numerics will use nearlyEquals so values that differ in 3 or 4th decimal places will return equal . This is being coded because the NDFD model dx differ in the 3 decimal place otherwise equal .


public void process(InputStream is) throws IOException {
    int pos = -1;
    Buffer b = null;

    while (true) {
      b = (pos < 0) ? readBuffer(is) : readBuffer(is, b, pos);
      pos = process(b, is);
      if (b.done) break;
    }
  }

public void process ( InputStream is ) throws IOException { int pos = - 1 ; Buffer b = null ; while ( true ) { b = ( pos < 0 ) ? readBuffer ( is ) : readBuffer ( is , b , pos ) ; pos = process ( b , is ) ; if ( b . done ) break ; } }

Step 1 - read and extract a Bufr Message


private int process(Buffer b, InputStream is) throws IOException {
    int start = 0;
    while (start < b.have) {
      int matchPos = matcher.indexOf(b.buff, start, b.have - start);

      // didnt find "BUFR" match
      if (matchPos < 0) {
        if (start == 0) // discard all but last 3 bytes
          return b.have - 3;
        else
          return start; // indicates part of the buffer thats not processed
      }

      // do we have the length already read ??
      if (matchPos + 6 >= b.have) {
        return start; // this will save the end of the buffer and read more in.
      }

      // read BUFR message length
      int b1 = (b.buff[matchPos + 4] & 0xff);
      int b2 = (b.buff[matchPos + 5] & 0xff);
      int b3 = (b.buff[matchPos + 6] & 0xff);
      int messLen = b1 << 16 | b2 << 8 | b3;
      // System.out.println("match at=" + matchPos + " len= " + messLen);

      // create a task for this message
      //int headerLen = matchPos - start;
      MessageTask task = new MessageTask(messLen);
      task.header = extractHeader(start, matchPos, b);

      // copy message bytes into it
      int last = matchPos + messLen;
      if (last > b.have) {
        task.have = b.have - matchPos;
        System.arraycopy(b.buff, matchPos, task.mess, 0, task.have);

        // read the rest of the message
        if (!readBuffer(is, task.mess, task.have, task.len - task.have)) {
          System.out.println("Failed to read remaining BUFR message");
          break;
        }

      } else {
        task.have = task.len;
        System.arraycopy(b.buff, matchPos, task.mess, 0, task.have);
      }

      boolean ok = true;

      // check on ending
      for (int i = task.len - 4; i < task.len; i++) {
        int bb = task.mess[i];
        if (bb != 55) {
          //System.out.println("Missing End of BUFR message at pos=" + i + " " + bb);
          ok = false;
          bad_msgs++;
        }
      }

      try {
        if (ok) messQ.put(task);
        total_msgs++;
        //System.out.println(" added message " + task.id + " start=" + matchPos + " end= " + (matchPos + messLen));
      } catch (InterruptedException e) {
        System.out.println(" interrupted queue put - assume process exit");
        break;
      }

      start = matchPos + messLen + 1;
    }

    return -1;
  }


String removeQuotes(String s)
    {
        if (s.startsWith("\"") && s.endsWith("\""))
            return s.substring(1, s.length() - 1);
        else
            return s;
    }

String removeQuotes ( String s ) { if ( s . startsWith ( "\"" ) && s . endsWith ( "\"" ) ) return s . substring ( 1 , s . length ( ) - 1 ) ; else return s ; }

Remove double quotes from around a string. If there's not both start
and ending quotes, does nothing.

@param s The source string.
@return The string without double quotes.

Remove double quotes from around a string . If there s not both start and ending quotes does nothing .


void markStackedVariables(Stack s)
    {
        // Reverse the stack.
        Stack bts = new Stack();
        // LogStream.err.println("Variables to be marked:");
        while (!s.empty()) {
            // LogStream.err.println(((BaseType)s.peek()).getName());
            bts.push(s.pop());
        }

        // For each but the last stack element, set the projection.
        // setProject(true, false) for a ctor type sets the projection for
        // the ctor itself but *does not* set the projection for all its
        // children. Thus, if a user wants the variable S.X, and S contains Y
        // and Z too, S's projection will be set (so serialize will descend
        // into S) but X, Y and Z's projection remain clear. In this example,
        // X's projection is set by the code that follows the while loop.
        // 1/28/2000 jhrg
        while (bts.size() > 1) {
            ServerMethods ct = (ServerMethods) bts.pop();
            ct.setProject(true, false);
        }

        // For the last element, project the entire variable.
        ServerMethods bt = (ServerMethods) bts.pop();
        bt.setProject(true, true);
    }

Given a stack of BaseType variables, mark these as part of the
current projection. This function assumes that if the TOS contains a
Ctor type variable, all of its members are to be projected. Also
assume  all variables under the TOS are Ctor variables and
only the ctor itself is to be projected; the member within the Ctor
that is part of the projection will be on the stack, too.

Given a stack of BaseType variables mark these as part of the current projection . This function assumes that if the TOS contains a Ctor type variable all of its members are to be projected . Also assume all variables under the TOS are Ctor variables and only the ctor itself is to be projected ; the member within the Ctor that is part of the projection will be on the stack too .


boolean writeNcml(String location) {
        boolean err = false;

        closeOpenFiles();

        try {
            final String result;
            ds = openDataset(location, addCoords, null);
            if (ds == null) {
                editor.setText("Failed to open <" + location + ">");
            }
            else {
                final NcMLWriter ncmlWriter = new NcMLWriter();
                final Element netcdfElem = ncmlWriter.makeNetcdfElement(ds, null);
                result = ncmlWriter.writeToString(netcdfElem);

                editor.setText(result);
                editor.setCaretPosition(0);
            }
        }
        catch (Exception e) {
            final StringWriter sw = new StringWriter(10000);
            e.printStackTrace();
            e.printStackTrace(new PrintWriter(sw));
            editor.setText(sw.toString());
            err = true;
        }

        return !err;
    }

boolean
writeNcml
(
String
location
)
{
boolean
err
=
false
;
closeOpenFiles
(
)
;
try
{
final
String
result
;
ds
=
openDataset
(
location
,
addCoords
,
)
;
if
(
ds
==
)
{
editor
.
setText
(
"Failed to open <"
+
location
+
">"
)
;
}
else
{
final
NcMLWriter
ncmlWriter
=
new
NcMLWriter
(
)
;
final
Element
netcdfElem
=
ncmlWriter
.
makeNetcdfElement
(
ds
,
)
;
result
=
ncmlWriter
.
writeToString
(
netcdfElem
)
;
editor
.
setText
(
result
)
;
editor
.
setCaretPosition
(
0
)
;
}
}
catch
(
Exception
e
)
{
final
StringWriter
sw
=
new
StringWriter
(
10000
)
;
e
.
printStackTrace
(
)
;
e
.
printStackTrace
(
new
PrintWriter
(
sw
)
)
;
editor
.
setText
(
sw
.
toString
(
)
)
;
err
=
true
;
}
return
!
err
;
}


private static String getValueFromThreddsConfig(String key, String alternateKey, String defaultValue) {
    String value = ThreddsConfig.get(key, null);
    if (value == null && alternateKey != null)
      value = ThreddsConfig.get(alternateKey, null);
    if (value == null)
      value = defaultValue;
    return value;
  }

private static String getValueFromThreddsConfig ( String key , String alternateKey , String defaultValue ) { String value = ThreddsConfig . get ( key , null ) ; if ( value == null && alternateKey != null ) value = ThreddsConfig . get ( alternateKey , null ) ; if ( value == null ) value = defaultValue ; return value ; }

static so can be called from static enum classes


public String writeCDL(boolean strict) {
    Formatter out = new Formatter();
    writeCDL(out, new Indent(2), strict);
    return out.toString();
  }

public String writeCDL ( boolean strict ) { Formatter out = new Formatter ( ) ; writeCDL ( out , new Indent ( 2 ) , strict ) ; return out . toString ( ) ; }

String representation.

@param strict if true, write in strict adherence to CDL definition.
@return CDL representation.


@Override
  protected StationHelper createStationHelper() throws IOException {
    // read in all the stations with the "stations" query
    StationHelper stationHelper = new StationHelper();

    try (InputStream in = CdmRemote.sendQuery(null, uri, "req=stations")) {
      PointStream.MessageType mtype = PointStream.readMagic(in);
      if (mtype != PointStream.MessageType.StationList) {
        throw new RuntimeException("Station Request: bad response");
      }

      int len = NcStream.readVInt(in);
      byte[] b = new byte[len];
      NcStream.readFully(in, b);
      PointStreamProto.StationList stationsp = PointStreamProto.StationList.parseFrom(b);
      for (ucar.nc2.ft.point.remote.PointStreamProto.Station sp : stationsp.getStationsList()) {
//        Station s = new StationImpl(sp.getId(), sp.getDesc(), sp.getWmoId(), sp.getLat(), sp.getLon(), sp.getAlt());
        stationHelper.addStation(new StationFeatureStream(null, null));    // LOOK WRONG
      }
      return stationHelper;
    }
  }


protected boolean validate( StringBuilder out)
  {
    this.isValid = true;

    // If log from construction has content, append to validation output msg.
    if (this.log.length() > 0) {
      out.append( this.log);
    }

    // Check that 'accessPointHeader' attribute is not null.
    if ( this.getAccessPointHeader() == null)
    {
      this.isValid = false;
      out.append( " ** ResultService (1): a null 'accessPointHeader' is invalid.");
    }

    return( this.isValid);
  }

Validate this ResultService object. Return true if valid, false if invalid.

@param out StringBuffer with validation messages.
@return boolean true if valid, false if invalid

Validate this ResultService object . Return true if valid false if invalid .


public float getAzimuth() {
    if (message_type != 1) return -1.0f;

    if(Cinrad2IOServiceProvider.isSC)
      return 360.0f * azimuth_ang / 65536.0f;
    else if(Cinrad2IOServiceProvider.isCC)
      return 360.0f * azimuth_ang / 512.0f;
    else if(Cinrad2IOServiceProvider.isCC20)
      return  azimuth_ang * 0.01f;

    return 180.0f * azimuth_ang / 32768.0f;
  }

public float getAzimuth ( ) { if ( message_type != 1 ) return - 1.0f ; if ( Cinrad2IOServiceProvider . isSC ) return 360.0f * azimuth_ang / 65536.0f ; else if ( Cinrad2IOServiceProvider . isCC ) return 360.0f * azimuth_ang / 512.0f ; else if ( Cinrad2IOServiceProvider . isCC20 ) return azimuth_ang * 0.01f ; return 180.0f * azimuth_ang / 32768.0f ; }

Get the azimuth in degrees

@return   azimuth angle in degrees 0 = true north, 90 = east


public float getElevation() {
      if (message_type != 1) return -1.0f;
      if(Cinrad2IOServiceProvider.isSC)
        return 120.0f * elevation_ang / 65536.0f;
      else if(Cinrad2IOServiceProvider.isCC)
        return elevation_ang * 0.01f;
      else if(Cinrad2IOServiceProvider.isCC20)
        return elevation_ang * 0.01f;

      return 180.0f * elevation_ang / 32768.0f;
    }

public float getElevation ( ) { if ( message_type != 1 ) return - 1.0f ; if ( Cinrad2IOServiceProvider . isSC ) return 120.0f * elevation_ang / 65536.0f ; else if ( Cinrad2IOServiceProvider . isCC ) return elevation_ang * 0.01f ; else if ( Cinrad2IOServiceProvider . isCC20 ) return elevation_ang * 0.01f ; return 180.0f * elevation_ang / 32768.0f ; }

Get the elevation angle in degrees

@return  elevation angle in degrees 0 = parellel to pedestal base, 90 = perpendicular


public float[] getLatitudes() {
    if (myASIBs == null)
      return null;
    float[] lats = new float[nRays];
    for (int i = 0; i < nRays; i++)
      lats[i] = myASIBs[i].getLatitude();
    return lats;
  }

public float [ ] getLatitudes ( ) { if ( myASIBs == null ) return null ; float [ ] lats = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) lats [ i ] = myASIBs [ i ] . getLatitude ( ) ; return lats ; }

Get the array of per-ray latitudes.  If we do not have per-ray position
information, null is returned.

@return an array of per-ray latitudes, or null if no per-ray position
information is available.

Get the array of per - ray latitudes . If we do not have per - ray position information null is returned .


public float[] getLongitudes() {
    if (myASIBs == null)
      return null;
    float[] lons = new float[nRays];
    for (int i = 0; i < nRays; i++)
      lons[i] = myASIBs[i].getLongitude();
    return lons;
  }

public float [ ] getLongitudes ( ) { if ( myASIBs == null ) return null ; float [ ] lons = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) lons [ i ] = myASIBs [ i ] . getLongitude ( ) ; return lons ; }

Get the array of per-ray longitudes.  If we do not have per-ray position
information, null is returned.

@return an array of per-ray longitudes, or null if no per-ray position
information is available.

Get the array of per - ray longitudes . If we do not have per - ray position information null is returned .


public float[] getAltitudes() {
    if (myASIBs == null)
      return null;
    float[] alts = new float[nRays];
    for (int i = 0; i < nRays; i++)
      alts[i] = myASIBs[i].getAltitude();
    return alts;
  }

public float [ ] getAltitudes ( ) { if ( myASIBs == null ) return null ; float [ ] alts = new float [ nRays ] ; for ( int i = 0 ; i < nRays ; i ++ ) alts [ i ] = myASIBs [ i ] . getAltitude ( ) ; return alts ; }

Get the array of per-ray altitudes.  If we do not have per-ray position
information, null is returned.

@return an array of per-ray altitudes in km MSL, or null if no per-ray
position information is available.

Get the array of per - ray altitudes . If we do not have per - ray position information null is returned .


public float[] getAzimuths() {
    if (azimuths == null) {
      azimuths = new float[nRays];
      for (int r = 0; r < nRays; r++) {
        azimuths[r] = myRYIBs[r].getAzimuth();
      }
    }
    return azimuths;
  }

public float [ ] getAzimuths ( ) { if ( azimuths == null ) { azimuths = new float [ nRays ] ; for ( int r = 0 ; r < nRays ; r ++ ) { azimuths [ r ] = myRYIBs [ r ] . getAzimuth ( ) ; } } return azimuths ; }

Get the array of azimuths for this sweep.

@return the array of azimuths for this sweep
@see #getNRays()

Get the array of azimuths for this sweep .


public float[] getElevations() {
    if (elevations == null) {
      elevations = new float[nRays];
      for (int r = 0; r < nRays; r++) {
        elevations[r] = myRYIBs[r].getElevation();
      }
    }
    return elevations;
  }

public float [ ] getElevations ( ) { if ( elevations == null ) { elevations = new float [ nRays ] ; for ( int r = 0 ; r < nRays ; r ++ ) { elevations [ r ] = myRYIBs [ r ] . getElevation ( ) ; } } return elevations ; }

Get the array of elevations for this sweep.

@return the array of elevations for this sweep
@see #getNRays()

Get the array of elevations for this sweep .


public Structure select( List<String> memberNames) {
    Structure result = (Structure) copy();
    List<Variable> members = new ArrayList<>();
    for (String name : memberNames) {
      Variable m = findVariable(name);
      if (null != m) members.add(m);
    }
    result.setMemberVariables(members);
    result.isSubset = true;
    return result;
  }

public Structure select ( List < String > memberNames ) { Structure result = ( Structure ) copy ( ) ; List < Variable > members = new ArrayList <> ( ) ; for ( String name : memberNames ) { Variable m = findVariable ( name ) ; if ( null != m ) members . add ( m ) ; } result . setMemberVariables ( members ) ; result . isSubset = true ; return result ; }

Create a subset of the Structure consisting only of the given member variables
@param memberNames list of Variable names, already a member
@return Structure containing just those members


public Structure select( String varName) {
    List<String> memberNames = new ArrayList<>(1);
    memberNames.add(varName);
    return  select(memberNames);
  }

public Structure select ( String varName ) { List < String > memberNames = new ArrayList <> ( 1 ) ; memberNames . add ( varName ) ; return select ( memberNames ) ; }

Create a subset of the Structure consisting only of the one member variable
@param varName name of member Variable
@return containing just that member


public Variable addMemberVariable( Variable v) {
    if (isImmutable()) throw new IllegalStateException("Cant modify");
    members.add( v);
    memberHash.put( v.getShortName(), v);
    v.setParentStructure( this);
    return v;
  }

public
Variable
addMemberVariable
(
Variable
v
)
{
if
(
isImmutable
(
)
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
members
.
add
(
v
)
;
memberHash
.
put
(
v
.
getShortName
(
)
,
v
)
;
v
.
setParentStructure
(
this
)
;
return
v
;
}

Add a member variable
@param v add this variable as a member of this structure
@return the added variable


public void setMemberVariables( List<Variable> vars) {
    if (isImmutable()) throw new IllegalStateException("Cant modify");
    members = new ArrayList<>();
    memberHash = new HashMap<>(2*vars.size());
    for (Variable v : vars) {
      addMemberVariable(v);
    }
  }

public
void
setMemberVariables
(
List
<
Variable
>
vars
)
{
if
(
isImmutable
(
)
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
members
=
new
ArrayList
<>
(
)
;
memberHash
=
new
HashMap
<>
(
2
*
vars
.
size
(
)
)
;
for
(
Variable
v
:
vars
)
{
addMemberVariable
(
v
)
;
}
}

Set the list of member variables.
@param vars this is the list of member variables


@Override
  public void setParentGroup(Group group) {
    if (isImmutable())
        throw new IllegalStateException("Cant modify");
    super.setParentGroup(group);
    if(members != null)
    {
        for (Variable v : members) {
          v.setParentGroup(group);
        }
    }
  }

@
Override
public
void
setParentGroup
(
Group
group
)
{
if
(
isImmutable
(
)
)
throw
new
IllegalStateException
(
"Cant modify"
)
;
super
.
setParentGroup
(
group
)
;
if
(
members
!=
)
{
for
(
Variable
v
:
members
)
{
v
.
setParentGroup
(
group
)
;
}
}
}

Set the parent group of this Structure, and all member variables.

Set the parent group of this Structure and all member variables .


public void calcElementSize() {
    int total = 0;
    for (Variable v : members) {
      total += v.getElementSize() * v.getSize();
    }
    elementSize = total;
  }

public void calcElementSize ( ) { int total = 0 ; for ( Variable v : members ) { total += v . getElementSize ( ) * v . getSize ( ) ; } elementSize = total ; }

Force recalculation of size of one element of this structure - equals the sum of sizes of its members.
This is used only by low level classes like IOSPs.

Force recalculation of size of one element of this structure - equals the sum of sizes of its members . This is used only by low level classes like IOSPs .


public StructureData readStructure(int index) throws IOException, ucar.ma2.InvalidRangeException {
    Section section = null; // works for scalars i think

    if (getRank() == 1) {
      section = new Section().appendRange(index,index);

    } else if (getRank() > 1) {
      Index ii = Index.factory(shape); // convert to nD index
      ii.setCurrentCounter(index);
      int[] origin = ii.getCurrentCounter();
      section = new Section();
      for (int anOrigin : origin)
        section.appendRange(anOrigin, anOrigin);
    }

    Array dataArray = read(section);
    ArrayStructure data = (ArrayStructure) dataArray;
    return data.getStructureData(0);
  }

public
StructureData
readStructure
(
int
index
)
throws
IOException
,
ucar
.
ma2
.
InvalidRangeException
{
Section
section
=
;
// works for scalars i think
if
(
getRank
(
)
==
1
)
{
section
=
new
Section
(
)
.
appendRange
(
index
,
index
)
;
}
else
if
(
getRank
(
)
>
1
)
{
Index
ii
=
Index
.
factory
(
shape
)
;
// convert to nD index
ii
.
setCurrentCounter
(
index
)
;
int
[
]
origin
=
ii
.
getCurrentCounter
(
)
;
section
=
new
Section
(
)
;
for
(
int
anOrigin
:
origin
)
section
.
appendRange
(
anOrigin
,
anOrigin
)
;
}
Array
dataArray
=
read
(
section
)
;
ArrayStructure
data
=
(
ArrayStructure
)
dataArray
;
return
data
.
getStructureData
(
0
)
;
}

Use this when this is a one dimensional array of Structures, or you are doing the index calculation yourself for
a multidimension array. This will read only the ith structure, and return the data as a StructureData object.
@param index index into 1D array
@return ith StructureData
@throws java.io.IOException on read error
@throws ucar.ma2.InvalidRangeException if index out of range

Use this when this is a one dimensional array of Structures or you are doing the index calculation yourself for a multidimension array . This will read only the ith structure and return the data as a StructureData object .


public ArrayStructure readStructure(int start, int count) throws IOException, ucar.ma2.InvalidRangeException {
    if (getRank() != 1) throw new java.lang.UnsupportedOperationException("not a vector structure");
    int[] origin = new int[] {start};
    int[] shape = new int[] {count};
    if (NetcdfFile.debugStructureIterator)
      System.out.println("readStructure "+start+" "+count);
    return (ArrayStructure) read(origin, shape);
  }

public
ArrayStructure
readStructure
(
int
start
,
int
count
)
throws
IOException
,
ucar
.
ma2
.
InvalidRangeException
{
if
(
getRank
(
)
!=
1
)
throw
new
java
.
lang
.
UnsupportedOperationException
(
"not a vector structure"
)
;
int
[
]
origin
=
new
int
[
]
{
start
}
;
int
[
]
shape
=
new
int
[
]
{
count
}
;
if
(
NetcdfFile
.
debugStructureIterator
)
System
.
out
.
println
(
"readStructure "
+
start
+
" "
+
count
)
;
return
(
ArrayStructure
)
read
(
origin
,
shape
)
;
}

For rank 1 array of Structures, read count Structures and return the data as an ArrayStructure.
Use only when this is a one dimensional array of Structures.
@param start start at this index
@param count return this many StructureData
@return the StructureData recordsfrom start to start+count-1
@throws java.io.IOException on read error
@throws ucar.ma2.InvalidRangeException if start, count out of range

For rank 1 array of Structures read count Structures and return the data as an ArrayStructure . Use only when this is a one dimensional array of Structures .


public StructureDataIterator getStructureIterator(int bufferSize) throws java.io.IOException {
    return (getRank() < 2) ? new Structure.IteratorRank1(bufferSize) : new Structure.Iterator(bufferSize);
  }

public StructureDataIterator getStructureIterator ( int bufferSize ) throws java . io . IOException { return ( getRank ( ) < 2 ) ? new Structure . IteratorRank1 ( bufferSize ) : new Structure . Iterator ( bufferSize ) ; }

Get an efficient iterator over all the data in the Structure.

This is the efficient way to get all the data, it can be much faster than reading one record at a time,
and is optimized for large datasets.
This is accomplished by buffering bufferSize amount of data at once.

<pre>Example:

StructureDataIterator ii = structVariable.getStructureIterator(100 * 1000);
while (ii.hasNext()) {
StructureData sdata = ii.next();
}
</pre>
@param bufferSize size in bytes to buffer, set < 0 to use default size
@return StructureDataIterator over type StructureData
@throws java.io.IOException on read error

Get an efficient iterator over all the data in the Structure .


static public String getDataCategory(int cat) {
    if (tableA == null) init();
    String result = tableA.get(cat);
    return result != null ? result : "Unknown category=" + cat;
  }

static
public
String
getDataCategory
(
int
cat
)
{
if
(
tableA
==
)
init
(
)
;
String
result
=
tableA
.
get
(
cat
)
;
return
result
!=
result
:
"Unknown category="
+
cat
;
}

data category name, from table A

@param cat data category
@return category name, or null if not found


public String getClassName() {
    String className = getClass().getName();
    int index = className.lastIndexOf(".");
    if (index >= 0) {
      className = className.substring(index + 1);
    }
    return className;
  }

public String getClassName ( ) { String className = getClass ( ) . getName ( ) ; int index = className . lastIndexOf ( "." ) ; if ( index >= 0 ) { className = className . substring ( index + 1 ) ; } return className ; }

Get the name of the type of the projection.

@return the class name

Get the name of the type of the projection .


protected void addParameter(String name, String value) {
    atts.add(new Parameter(name, value));
  }

protected void addParameter ( String name , String value ) { atts . add ( new Parameter ( name , value ) ) ; }

Add an attribute to this projection

@param name  name of the attribute
@param value attribute value as a string


public static String getHeader() {
    StringBuilder headerB = new StringBuilder(60);
    headerB.append("Name");
    Format.tab(headerB, 20, true);
    headerB.append("Class");
    Format.tab(headerB, 40, true);
    headerB.append("Parameters");
    return headerB.toString();
  }

public static String getHeader ( ) { StringBuilder headerB = new StringBuilder ( 60 ) ; headerB . append ( "Name" ) ; Format . tab ( headerB , 20 , true ) ; headerB . append ( "Class" ) ; Format . tab ( headerB , 40 , true ) ; headerB . append ( "Parameters" ) ; return headerB . toString ( ) ; }

Get a header for display.

@return human readable header for display


ProjectionRect latLonToProjBB2(LatLonRect latlonRect) {
    double minx, maxx, miny, maxy;

    LatLonPointImpl llpt = latlonRect.getLowerLeftPoint();
    LatLonPointImpl urpt = latlonRect.getUpperRightPoint();
    LatLonPointImpl lrpt = latlonRect.getLowerRightPoint();
    LatLonPointImpl ulpt = latlonRect.getUpperLeftPoint();

    if (isLatLon()) {
      minx = getMinOrMaxLon(llpt.getLongitude(), ulpt.getLongitude(), true);
      miny = Math.min(llpt.getLatitude(), lrpt.getLatitude());
      maxx = getMinOrMaxLon(urpt.getLongitude(), lrpt.getLongitude(), false);
      maxy = Math.min(ulpt.getLatitude(), urpt.getLatitude());

    } else {
      ProjectionPoint ll = latLonToProj(llpt, new ProjectionPointImpl());
      ProjectionPoint ur = latLonToProj(urpt, new ProjectionPointImpl());
      ProjectionPoint lr = latLonToProj(lrpt, new ProjectionPointImpl());
      ProjectionPoint ul = latLonToProj(ulpt, new ProjectionPointImpl());

      minx = Math.min(ll.getX(), ul.getX());
      miny = Math.min(ll.getY(), lr.getY());
      maxx = Math.max(ur.getX(), lr.getX());
      maxy = Math.max(ul.getY(), ur.getY());
    }

    return new ProjectionRect(minx, miny, maxx, maxy);
  }

ProjectionRect latLonToProjBB2 ( LatLonRect latlonRect ) { double minx , maxx , miny , maxy ; LatLonPointImpl llpt = latlonRect . getLowerLeftPoint ( ) ; LatLonPointImpl urpt = latlonRect . getUpperRightPoint ( ) ; LatLonPointImpl lrpt = latlonRect . getLowerRightPoint ( ) ; LatLonPointImpl ulpt = latlonRect . getUpperLeftPoint ( ) ; if ( isLatLon ( ) ) { minx = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; miny = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; maxx = getMinOrMaxLon ( urpt . getLongitude ( ) , lrpt . getLongitude ( ) , false ) ; maxy = Math . min ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; } else { ProjectionPoint ll = latLonToProj ( llpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint ur = latLonToProj ( urpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint lr = latLonToProj ( lrpt , new ProjectionPointImpl ( ) ) ; ProjectionPoint ul = latLonToProj ( ulpt , new ProjectionPointImpl ( ) ) ; minx = Math . min ( ll . getX ( ) , ul . getX ( ) ) ; miny = Math . min ( ll . getY ( ) , lr . getY ( ) ) ; maxx = Math . max ( ur . getX ( ) , lr . getX ( ) ) ; maxy = Math . max ( ul . getY ( ) , ur . getY ( ) ) ; } return new ProjectionRect ( minx , miny , maxx , maxy ) ; }

Alternate way to calculate latLonToProjBB, originally in GridCoordSys.
Difficult to do this in a general way.

@param latlonRect desired lat/lon rectangle
@return a ProjectionRect

Alternate way to calculate latLonToProjBB originally in GridCoordSys . Difficult to do this in a general way .


public static int getVersion(String hasConvName) {
    int result = extractVersion(hasConvName);
    if (result >= 0) return result;
    List<String> names = breakupConventionNames(hasConvName);
    for (String name : names) {
      result = extractVersion(name);
      if (result >= 0) return result;
    }
    return -1;
  }

public static int getVersion ( String hasConvName ) { int result = extractVersion ( hasConvName ) ; if ( result >= 0 ) return result ; List < String > names = breakupConventionNames ( hasConvName ) ; for ( String name : names ) { result = extractVersion ( name ) ; if ( result >= 0 ) return result ; } return - 1 ; }

Get which CF version this is, ie CF-1.x
@param hasConvName extract from convention name or list of names
@return version, or -1 if not CF

Get which CF version this is ie CF - 1 . x


public static String getZisPositive(String zaxisName, String vertCoordUnits) {
    if (vertCoordUnits == null) return CF.POSITIVE_UP;
    if (vertCoordUnits.isEmpty()) return CF.POSITIVE_UP;

    if (SimpleUnit.isCompatible("millibar", vertCoordUnits))
      return CF.POSITIVE_DOWN;

    if (SimpleUnit.isCompatible("m", vertCoordUnits))
      return CF.POSITIVE_UP;

    // dunno - make it up
    return CF.POSITIVE_UP;
  }

public
static
String
getZisPositive
(
String
zaxisName
,
String
vertCoordUnits
)
{
if
(
vertCoordUnits
==
)
return
CF
.
POSITIVE_UP
;
if
(
vertCoordUnits
.
isEmpty
(
)
)
return
CF
.
POSITIVE_UP
;
if
(
SimpleUnit
.
isCompatible
(
"millibar"
,
vertCoordUnits
)
)
return
CF
.
POSITIVE_DOWN
;
if
(
SimpleUnit
.
isCompatible
(
"m"
,
vertCoordUnits
)
)
return
CF
.
POSITIVE_UP
;
// dunno - make it up
return
CF
.
POSITIVE_UP
;
}

Guess the value of ZisPositive based on z axis name and units

@param zaxisName      z coordinate axis name
@param vertCoordUnits z coordinate axis name
@return CF.POSITIVE_UP or CF.POSITIVE_DOWN


public boolean delete() {
    if (nextFile == null) return false;
    fileList.remove( nextFile);
    File f = new File("C:/tmp/deleted/"+nextFile.getName());
    return nextFile.renameTo(f);
  }

public boolean delete ( ) { if ( nextFile == null ) return false ; fileList . remove ( nextFile ) ; File f = new File ( "C:/tmp/deleted/" + nextFile . getName ( ) ) ; return nextFile . renameTo ( f ) ; }


private void setColorScaleParams() {
    if (dataMinMaxType == ColorScale.MinMaxType.hold && !isNewField)
      return;
    isNewField = false;

    GeoReferencedArray dataArr = readHSlice(wantLevel, wantTime, wantEnsemble, wantRunTime);

    //else
    //  dataArr = makeVSlice(stridedGrid, wantSlice, wantTime, wantEnsemble, wantRunTime);

    if (dataArr != null) {
      MAMath.MinMax minmax = MAMath.getMinMaxSkipMissingData(dataArr.getData(), dataState.grid);
      colorScale.setMinMax(minmax.min, minmax.max);
      colorScale.setGeoGrid(dataState.grid);
    }
  }


public void renderPlanView(java.awt.Graphics2D g, AffineTransform dFromN) {
    if ((dataState.grid == null) || (colorScale == null) || (drawProjection == null))
      return;

    if (!drawGrid && !drawContours)
      return;

    // no anitaliasing
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF);

    dataH = readHSlice(wantLevel, wantTime, wantEnsemble, wantRunTime);
    if (dataH == null)
      return;

    setColorScaleParams();

    if (drawGrid)
      drawGridHoriz(g, dataH);
    //if (drawContours)
    //  drawContours(g, dataH.transpose(0, 1), dFromN);
    if (drawGridLines)
      drawGridLines(g, dataH);
    if (drawBB)
      drawGridBB(g, this.dataState.coverageDataset.getLatlonBoundingBox());
  }

Do the rendering to the given Graphics2D object.

@param g      Graphics2D object: has clipRect and AffineTransform set.
@param dFromN transforms "Normalized Device" to Device coordinates

Do the rendering to the given Graphics2D object .


boolean isChildOf(H5Group that) {
      if (parent == null) return false;
      if (parent == that) return true;
      return parent.isChildOf(that);
    }

boolean isChildOf ( H5Group that ) { if ( parent == null ) return false ; if ( parent == that ) return true ; return parent . isChildOf ( that ) ; }


public static MessageType getType(String name) {
      if (name == null) return null;
      return hash.get(name);
    }

public static MessageType getType ( String name ) { if ( name == null ) return null ; return hash . get ( name ) ; }

Find the MessageType that matches this name.

@param name find DataTYpe with this name.
@return DataType or null if no match.

Find the MessageType that matches this name .


public static void installInAllColumns(JTable table, int alignment) {
        // We don't want to set up completely new cell renderers: rather, we want to use the existing ones but just
        // change their alignment.
        for (int colViewIndex = 0; colViewIndex < table.getColumnCount(); ++colViewIndex) {
            installInOneColumn(table, colViewIndex, alignment);
        }
    }

Installs alignment decorators in all of the table's columns.

@param table  a table.
@param alignment  one of the following constants:

{@link SwingConstants#LEFT}

{@link SwingConstants#CENTER} (the default for image-only labels)

{@link SwingConstants#RIGHT}

{@link SwingConstants#LEADING} (the default for text-only labels)

{@link SwingConstants#TRAILING}

Installs alignment decorators in all of the table s columns .


public CoinbaseBuilder withApiKey(String api_key, String api_secret) {
    	this.api_key = api_key;
    	this.api_secret = api_secret;
    	return this;
    }

public CoinbaseBuilder withApiKey ( String api_key , String api_secret ) { this . api_key = api_key ; this . api_secret = api_secret ; return this ; }

Specify the HMAC api key and secret to be used for authenticated requests

Having more than one client with the same api/secret globally is unsupported
and will result in sporadic auth errors as the nonce is calculated from the system time.

@param api_key the HMAC API Key
@param api_secret the HMAC API Secret

@return this CoinbaseBuilder object


public static Label of(String value) {
        return new Label(value, false, false, false, false, null, null);
    }

public static Label of ( String value ) { return new Label ( value , false , false , false , false , null , null ) ; }

Create a simple label. Create newlines with \n.

@param value the label text
@return the Label

Create a simple label . Create newlines with \ n .


public static Label lines(Justification just, String... lines) {
        final String sep = just == LEFT ? "\\l" : just == RIGHT ? "\\r" : "\n";
        final String value = Stream.of(lines).map(line -> line + sep).collect(joining());
        return new Label(value, false, false, false, false, null, null);
    }

public static Label lines ( Justification just , String ... lines ) { final String sep = just == LEFT ? "\\l" : just == RIGHT ? "\\r" : "\n" ; final String value = Stream . of ( lines ) . map ( line -> line + sep ) . collect ( joining ( ) ) ; return new Label ( value , false , false , false , false , null , null ) ; }

Create a simple multiline label.

@param just  the text justification
@param lines the text lines
@return the Label


public static Label html(String value) {
        return new Label(value, true, false, false, false, null, null);
    }

public static Label html ( String value ) { return new Label ( value , true , false , false , false , null , null ) ; }

Create a HTML label.

@param value the HTML code
@return the Label
@see www.graphviz.org


public Socket connect(Properties props, String socketPathFormat) throws IOException {
    // Gather parameters
    final String csqlInstanceName = props.getProperty(CLOUD_SQL_INSTANCE_PROPERTY);
    final List<String> ipTypes = listIpTypes(props.getProperty("ipTypes", DEFAULT_IP_TYPES));
    final boolean forceUnixSocket = System.getenv("CLOUD_SQL_FORCE_UNIX_SOCKET") != null;

    // Validate parameters
    Preconditions.checkArgument(
        csqlInstanceName != null,
        "cloudSqlInstance property not set. Please specify this property in the JDBC URL or the "
            + "connection Properties with value in form \"project:region:instance\"");

    // GAE Standard runtimes provide a connection path at "/cloudsql/<CONNECTION_NAME>"
    if (forceUnixSocket || runningOnGaeStandard()) {
      logger.info(
          String.format(
              "Connecting to Cloud SQL instance [%s] via unix socket.", csqlInstanceName));
      UnixSocketAddress socketAddress =
          new UnixSocketAddress(new File(String.format(socketPathFormat, csqlInstanceName)));
      return UnixSocketChannel.open(socketAddress).socket();
    }

    logger.info(
        String.format("Connecting to Cloud SQL instance [%s] via SSL socket.", csqlInstanceName));
    return getInstance().createSslSocket(csqlInstanceName, ipTypes);
  }

Creates a socket representing a connection to a Cloud SQL instance.

<p>Depending on the environment, it may return either a SSL Socket or a Unix Socket.

@param props Properties used to configure the connection.
@return the newly created Socket.
@throws IOException if error occurs during socket creation.

Creates a socket representing a connection to a Cloud SQL instance .


private static List<String> listIpTypes(String cloudSqlIpTypes) {
    String[] rawTypes = cloudSqlIpTypes.split(",");
    ArrayList<String> result = new ArrayList<>(rawTypes.length);
    for (int i = 0; i < rawTypes.length; i++) {
      if (rawTypes[i].trim().equalsIgnoreCase("PUBLIC")) {
        result.add(i, "PRIMARY");
      } else {
        result.add(i, rawTypes[i].trim().toUpperCase());
      }
    }
    return result;
  }

private static List < String > listIpTypes ( String cloudSqlIpTypes ) { String [ ] rawTypes = cloudSqlIpTypes . split ( "," ) ; ArrayList < String > result = new ArrayList <> ( rawTypes . length ) ; for ( int i = 0 ; i < rawTypes . length ; i ++ ) { if ( rawTypes [ i ] . trim ( ) . equalsIgnoreCase ( "PUBLIC" ) ) { result . add ( i , "PRIMARY" ) ; } else { result . add ( i , rawTypes [ i ] . trim ( ) . toUpperCase ( ) ) ; } } return result ; }

Converts the string property of IP types to a list by splitting by commas, and upper-casing.

Converts the string property of IP types to a list by splitting by commas and upper - casing .


public <T extends Closeable> T connect(
      String host, int portNumber, Properties props, int loginTimeout) throws IOException {
    @SuppressWarnings("unchecked")
    T socket =
        (T)
            CoreSocketFactory.getInstance()
                .connect(props, CoreSocketFactory.MYSQL_SOCKET_FILE_FORMAT);
    return socket;
  }

public < T extends Closeable > T connect ( String host , int portNumber , Properties props , int loginTimeout ) throws IOException { @ SuppressWarnings ( "unchecked" ) T socket = ( T ) CoreSocketFactory . getInstance ( ) . connect ( props , CoreSocketFactory . MYSQL_SOCKET_FILE_FORMAT ) ; return socket ; }

Implements the interface for com.mysql.cj.protocol.SocketFactory for mysql-connector-java prior
to version 8.0.13. This change is required for backwards compatibility.

Implements the interface for com . mysql . cj . protocol . SocketFactory for mysql - connector - java prior to version 8 . 0 . 13 . This change is required for backwards compatibility .


protected synchronized void purgeLogger(FluentLogger logger) {
		Iterator<Entry<FluentLogger, String>> it = loggers.entrySet().iterator();
		while (it.hasNext()) {
			if (it.next().getKey() == logger) {
				it.remove();
				return;
			}
		}
	}

protected synchronized void purgeLogger ( FluentLogger logger ) { Iterator < Entry < FluentLogger , String > > it = loggers . entrySet ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { if ( it . next ( ) . getKey ( ) == logger ) { it . remove ( ) ; return ; } } }

Purges an invalid logger from the cache.

Purges an invalid logger from the cache .


public Map<String, Class<?>> compileAll() throws Exception {
		if (sourceCodes.size() == 0) {
			throw new CompilationException("No source code to compile");
		}
		Collection<SourceCode> compilationUnits = sourceCodes.values();
		CompiledCode[] code;

		code = new CompiledCode[compilationUnits.size()];
		Iterator<SourceCode> iter = compilationUnits.iterator();
		for (int i = 0; i < code.length; i++) {
			code[i] = new CompiledCode(iter.next().getClassName());
		}
		DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<>();
		ExtendedStandardJavaFileManager fileManager = new ExtendedStandardJavaFileManager(javac.getStandardFileManager(null, null, null), classLoader);
		JavaCompiler.CompilationTask task = javac.getTask(null, fileManager, collector, options, null, compilationUnits);
		boolean result = task.call();
		if (!result || collector.getDiagnostics().size() > 0) {
			StringBuffer exceptionMsg = new StringBuffer();
			exceptionMsg.append("Unable to compile the source");
			boolean hasWarnings = false;
			boolean hasErrors = false;
			for (Diagnostic<? extends JavaFileObject> d : collector.getDiagnostics()) {
				switch (d.getKind()) {
				case NOTE:
				case MANDATORY_WARNING:
				case WARNING:
					hasWarnings = true;
					break;
				case OTHER:
				case ERROR:
				default:
					hasErrors = true;
					break;
				}
				exceptionMsg.append("\n").append("[kind=").append(d.getKind());
				exceptionMsg.append(", ").append("line=").append(d.getLineNumber());
				exceptionMsg.append(", ").append("message=").append(d.getMessage(Locale.US)).append("]");
			}
			if (hasWarnings && !ignoreWarnings || hasErrors) {
				throw new CompilationException(exceptionMsg.toString());
			}
		}

		Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
		for (String className : sourceCodes.keySet()) {
			classes.put(className, classLoader.loadClass(className));
		}
		return classes;
	}

public
Map
<
String
,
Class
<
>
>
compileAll
(
)
throws
Exception
{
if
(
sourceCodes
.
size
(
)
==
0
)
{
throw
new
CompilationException
(
"No source code to compile"
)
;
}
Collection
<
SourceCode
>
compilationUnits
=
sourceCodes
.
values
(
)
;
CompiledCode
[
]
code
;
code
=
new
CompiledCode
[
compilationUnits
.
size
(
)
]
;
Iterator
<
SourceCode
>
iter
=
compilationUnits
.
iterator
(
)
;
for
(
int
i
=
0
;
i
<
code
.
length
;
i
++
)
{
code
[
i
]
=
new
CompiledCode
(
iter
.
next
(
)
.
getClassName
(
)
)
;
}
DiagnosticCollector
<
JavaFileObject
>
collector
=
new
DiagnosticCollector
<>
(
)
;
ExtendedStandardJavaFileManager
fileManager
=
new
ExtendedStandardJavaFileManager
(
javac
.
getStandardFileManager
(
,
,
)
,
classLoader
)
;
JavaCompiler
.
CompilationTask
task
=
javac
.
getTask
(
,
fileManager
,
collector
,
options
,
,
compilationUnits
)
;
boolean
result
=
task
.
call
(
)
;
if
(
!
result
||
collector
.
getDiagnostics
(
)
.
size
(
)
>
0
)
{
StringBuffer
exceptionMsg
=
new
StringBuffer
(
)
;
exceptionMsg
.
append
(
"Unable to compile the source"
)
;
boolean
hasWarnings
=
false
;
boolean
hasErrors
=
false
;
for
(
Diagnostic
<
extends
JavaFileObject
>
d
:
collector
.
getDiagnostics
(
)
)
{
switch
(
d
.
getKind
(
)
)
{
case
NOTE
:
case
MANDATORY_WARNING
:
case
WARNING
:
hasWarnings
=
true
;
break
;
case
OTHER
:
case
ERROR
:
default
:
hasErrors
=
true
;
break
;
}
exceptionMsg
.
append
(
"\n"
)
.
append
(
"[kind="
)
.
append
(
d
.
getKind
(
)
)
;
exceptionMsg
.
append
(
", "
)
.
append
(
"line="
)
.
append
(
d
.
getLineNumber
(
)
)
;
exceptionMsg
.
append
(
", "
)
.
append
(
"message="
)
.
append
(
d
.
getMessage
(
Locale
.
US
)
)
.
append
(
"]"
)
;
}
if
(
hasWarnings
&&
!
ignoreWarnings
||
hasErrors
)
{
throw
new
CompilationException
(
exceptionMsg
.
toString
(
)
)
;
}
}
Map
<
String
,
Class
<
>
>
classes
=
new
HashMap
<
String
,
Class
<
>
>
(
)
;
for
(
String
className
:
sourceCodes
.
keySet
(
)
)
{
classes
.
put
(
className
,
classLoader
.
loadClass
(
className
)
)
;
}
return
classes
;
}

Compile all sources

@return Map containing instances of all compiled classes
@throws Exception


public Class<?> compile(String className, String sourceCode) throws Exception {
		return addSource(className, sourceCode).compileAll().get(className);
	}

public Class < ? > compile ( String className , String sourceCode ) throws Exception { return addSource ( className , sourceCode ) . compileAll ( ) . get ( className ) ; }

Compile single source

@param className
@param sourceCode
@return
@throws Exception


public InMemoryJavaCompiler addSource(String className, String sourceCode) throws Exception {
		sourceCodes.put(className, new SourceCode(className, sourceCode));
		return this;
	}

public InMemoryJavaCompiler addSource ( String className , String sourceCode ) throws Exception { sourceCodes . put ( className , new SourceCode ( className , sourceCode ) ) ; return this ; }

Add source code to the compiler

@param className
@param sourceCode
@return
@throws Exception
@see {@link #compileAll()}


private void readGraphicControlExt() {
    // Block size.
    read();
    // Packed fields.
    int packed = read();
    // Disposal method.
    header.currentFrame.dispose = (packed & 0x1c) >> 2;
    if (header.currentFrame.dispose == 0) {
      // Elect to keep old image if discretionary.
      header.currentFrame.dispose = 1;
    }
    header.currentFrame.transparency = (packed & 1) != 0;
    // Delay in milliseconds.
    int delayInHundredthsOfASecond = readShort();
    // TODO: consider allowing -1 to indicate show forever.
    if (delayInHundredthsOfASecond < MIN_FRAME_DELAY) {
      delayInHundredthsOfASecond = DEFAULT_FRAME_DELAY;
    }
    header.currentFrame.delay = delayInHundredthsOfASecond * 10;
    // Transparent color index
    header.currentFrame.transIndex = read();
    // Block terminator
    read();
  }

Reads Graphics Control Extension values.

Reads Graphics Control Extension values .


synchronized Bitmap getNextFrame() {
    if (header.frameCount <= 0 || framePointer < 0) {
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "unable to decode frame, frameCount=" + header.frameCount + " framePointer="
            + framePointer);
      }
      status = STATUS_FORMAT_ERROR;
    }
    if (status == STATUS_FORMAT_ERROR || status == STATUS_OPEN_ERROR) {
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "Unable to decode frame, status=" + status);
      }
      return null;
    }
    status = STATUS_OK;

    GifFrame currentFrame = header.frames.get(framePointer);
    GifFrame previousFrame = null;
    int previousIndex = framePointer - 1;
    if (previousIndex >= 0) {
      previousFrame = header.frames.get(previousIndex);
    }

    // Set the appropriate color table.
    act = currentFrame.lct != null ? currentFrame.lct : header.gct;
    if (act == null) {
      if (Log.isLoggable(TAG, Log.DEBUG)) {
        Log.d(TAG, "No Valid Color Table for frame #" + framePointer);
      }
      // No color table defined.
      status = STATUS_FORMAT_ERROR;
      return null;
    }

    // Reset the transparent pixel in the color table
    if (currentFrame.transparency) {
      // Prepare local copy of color table ("pct = act"), see #1068
      System.arraycopy(act, 0, pct, 0, act.length);
      // Forget about act reference from shared header object, use copied version
      act = pct;
      // Set transparent color if specified.
      act[currentFrame.transIndex] = 0;
    }

    // Transfer pixel data to image.
    return setPixels(currentFrame, previousFrame);
  }

Get the next frame in the animation sequence.

@return Bitmap representation of frame.

Get the next frame in the animation sequence .


public SelectableStringList selectablePersonsProperty() {
		if (selectablePersons == null) {
			selectablePersons = new SelectableItemList<>(
					FXCollections.observableArrayList(repository.getPersons()),
					person -> person.getFirstName() + " " + person.getLastName());
		}
		return selectablePersons;
	}

public
SelectableStringList
selectablePersonsProperty
(
)
{
if
(
selectablePersons
==
)
{
selectablePersons
=
new
SelectableItemList
<>
(
FXCollections
.
observableArrayList
(
repository
.
getPersons
(
)
)
,
person
->
person
.
getFirstName
(
)
+
" "
+
person
.
getLastName
(
)
)
;
}
return
selectablePersons
;
}

Persons in string representation.

@return persons


private void initListEvents() {
		this.listChangeListener = new ListChangeListener<SourceType>() {
			@Override
			public void onChanged(
					Change<? extends SourceType> listEvent) {

				// We have to stage delete events, because if we process them
				// separately, there will be unwanted ChangeEvents on the
				// targetList
				List<TargetType> deleteStaging = new ArrayList<>();

				while (listEvent.next()) {
					if (listEvent.wasUpdated()) {
						processUpdateEvent(listEvent);
					} else if (listEvent.wasReplaced()) {
						processReplaceEvent(listEvent, deleteStaging);
					} else if (listEvent.wasAdded()) {
						processAddEvent(listEvent);
					} else if (listEvent.wasRemoved()) {
						processRemoveEvent(listEvent, deleteStaging);
					}
				}

				// Process the staged elements
				processStagingLists(deleteStaging);
			}
		};
		modelListProperty().addListener(
				new WeakListChangeListener<>(listChangeListener));

	}

If the list changed we want the recreate the targetType representation


public Person getPersonById(final int id) {
		for (Person person : persons) {
			if (id == person.getId()) {
				return person;
			}
		}
		return null;
	}

public Person getPersonById ( final int id ) { for ( Person person : persons ) { if ( id == person . getId ( ) ) { return person ; } } return null ; }

Gets a Person.s

@param id of the person
@return person


void addMessage(Validator validator, List<? extends ValidationMessage> messages) {
		if(messages.isEmpty()) {
			return;
		}

		final int validatorHash = System.identityHashCode(validator);

		if(!validatorToMessagesMap.containsKey(validatorHash)){
			validatorToMessagesMap.put(validatorHash, new ArrayList<>());
		}

		final List<Integer> messageHashesOfThisValidator = validatorToMessagesMap.get(validatorHash);

		// add the hashCodes of the messages to the internal map
		messages.stream()
				.map(System::identityHashCode)
				.forEach(messageHashesOfThisValidator::add);

		// add the actual messages to the message list so that they are accessible by the user.
		getMessagesInternal().addAll(messages);
	}

Add a list of validation messages for the specified validator.

Add a list of validation messages for the specified validator .


public void setPersonId(int personId) {
		person = repository.getPersonById(personId);

		StringBinding salutationBinding
				= Bindings.when(person.genderProperty().isEqualTo(Gender.NOT_SPECIFIED))
				.then("Herr/Frau/* ")
				.otherwise(
						Bindings.when(person.genderProperty().isEqualTo(Gender.MALE))
						.then("Herr ").otherwise("Frau "));

		welcomeString.unbind();
		welcomeString.bind(Bindings.concat("Willkommen ", salutationBinding,
				person.firstNameProperty(), " ",
				person.lastNameProperty()));
	}

public
void
setPersonId
(
int
personId
)
{
person
=
repository
.
getPersonById
(
personId
)
;
StringBinding
salutationBinding
=
Bindings
.
when
(
person
.
genderProperty
(
)
.
isEqualTo
(
Gender
.
NOT_SPECIFIED
)
)
.
then
(
"Herr/Frau/* "
)
.
otherwise
(
Bindings
.
when
(
person
.
genderProperty
(
)
.
isEqualTo
(
Gender
.
MALE
)
)
.
then
(
"Herr "
)
.
otherwise
(
"Frau "
)
)
;
welcomeString
.
unbind
(
)
;
welcomeString
.
bind
(
Bindings
.
concat
(
"Willkommen "
,
salutationBinding
,
person
.
firstNameProperty
(
)
,
" "
,
person
.
lastNameProperty
(
)
)
)
;
}

Set Person id for the screen

@param personId for the screen


@SuppressWarnings("unchecked")
    public static <V extends View<? extends VM>, VM extends ViewModel> void createAndInjectViewModel(final V view,
            Consumer<ViewModel> newVmConsumer) {
        final Class<?> viewModelType = TypeResolver.resolveRawArgument(View.class, view.getClass());

        if (viewModelType == ViewModel.class) {
            // if no viewModel can be created, we have to check if the user has
            // tried to inject a ViewModel
            final List<Field> viewModelFields = ViewLoaderReflectionUtils.getViewModelFields(view.getClass());

            if (!viewModelFields.isEmpty()) {
                throw new RuntimeException("The given view of type <" + view.getClass()
                        + "> has no generic viewModel type declared but tries to inject a viewModel.");
            }
            return;
        }
        if (viewModelType == TypeResolver.Unknown.class) {
            return;
        }

        final Optional<Field> fieldOptional = getViewModelField(view.getClass(), viewModelType);
        if (fieldOptional.isPresent()) {
            Field field = fieldOptional.get();

            ReflectionUtils.accessMember(field, () -> {
                Object existingViewModel = field.get(view);

                if (existingViewModel == null) {
                    final Object newViewModel = DependencyInjector.getInstance().getInstanceOf(viewModelType);

                    field.set(view, newViewModel);

                    newVmConsumer.accept((ViewModel) newViewModel);
                }
            }, "Can't inject ViewModel of type <" + viewModelType + "> into the view <" + view + ">");

        }
    }

This method is used to create and inject the ViewModel for a given View
instance.

The following checks are done:

Check whether the View class specifies a ViewModel type as generic
type.

Check whether the View has a field with a matching ViewModel type and
the annotation {@link InjectViewModel}.

Check whether field in the view instance already contains a ViewModel
instance. In this case nothing will happen to the existing ViewModel
instance.

If a suitable field was found a new ViewModel instance will be created
and injected into the field. After that the given Consumer function will
be applied with the injected ViewModel instance as argument.

@param view
the view instance.
@param <V>
the generic type of the View.
@param <VM>
the generic type of the ViewModel.
@param newVmConsumer
a Consumer function that is applied when a new ViewModel
instance is created.

@throws RuntimeException
if there is a ViewModel field in the View with the
{@link InjectViewModel} annotation whose type doesn't match
the generic ViewModel type from the View class.

This method is used to create and inject the ViewModel for a given View instance .