Input: / * <! -- group of elements can be used in a dataset or in metadata elements -- > <xsd : group name = threddsMetadataGroup > <xsd : choice > <xsd : element name = documentation type = documentationType / > <xsd : element ref = metadata / > <xsd : element ref = property / > [CODESPLIT] protected void readThreddsMetadataGroup ( Map < String , Object > flds , DatasetBuilder dataset , Element parent ) { List < Element > list ; // look for creators - kind of a Source list = parent . getChildren ( "creator" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Creators , readSource ( e ) ) ; } // look for contributors list = parent . getChildren ( "contributor" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Contributors , readContributor ( e ) ) ; } // look for dates list = parent . getChildren ( "date" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Dates , readDate ( e , null ) ) ; } // look for documentation list = parent . getChildren ( "documentation" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Documentation , readDocumentation ( e ) ) ; } // look for keywords - kind of a controlled vocabulary list = parent . getChildren ( "keyword" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Keywords , readControlledVocabulary ( e ) ) ; } // look for metadata elements list = parent . getChildren ( "metadata" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . MetadataOther , readMetadata ( flds , dataset , e ) ) ; } // look for projects - kind of a controlled vocabulary list = parent . getChildren ( "project" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Projects , readControlledVocabulary ( e ) ) ; } // look for properties list = parent . getChildren ( "property" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Properties , readProperty ( e ) ) ; } // look for publishers - kind of a Source list = parent . getChildren ( "publisher" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . Publishers , readSource ( e ) ) ; } // look for variables list = parent . getChildren ( "variables" , Catalog . defNS ) ; for ( Element e : list ) { DatasetBuilder . addToList ( flds , Dataset . VariableGroups , readVariables ( e ) ) ; } // can only be one each of these kinds ThreddsMetadata . GeospatialCoverage gc = readGeospatialCoverage ( parent . getChild ( "geospatialCoverage" , Catalog . defNS ) ) ; if ( gc != null ) { flds . put ( Dataset . GeospatialCoverage , gc ) ; } DateRange tc = readTimeCoverage ( parent . getChild ( "timeCoverage" , Catalog . defNS ) ) ; if ( tc != null ) { flds . put ( Dataset . TimeCoverage , tc ) ; } Element serviceNameElem = parent . getChild ( "serviceName" , Catalog . defNS ) ; if ( serviceNameElem != null ) { flds . put ( Dataset . ServiceName , serviceNameElem . getText ( ) ) ; } Element authElem = parent . getChild ( "authority" , Catalog . defNS ) ; if ( authElem != null ) { flds . put ( Dataset . Authority , authElem . getText ( ) ) ; } Element dataTypeElem = parent . getChild ( "dataType" , Catalog . defNS ) ; if ( dataTypeElem != null ) { String dataTypeName = dataTypeElem . getText ( ) ; flds . put ( Dataset . FeatureType , dataTypeName ) ; if ( ( dataTypeName != null ) && ( dataTypeName . length ( ) > 0 ) ) { FeatureType dataType = FeatureType . getType ( dataTypeName . toUpperCase ( ) ) ; if ( dataType == null ) { errlog . format ( " ** warning: non-standard feature type = '%s'%n" , dataTypeName ) ; logger . debug ( " ** warning: non-standard feature type = '{}'" , dataTypeName ) ; } } } Element dataFormatElem = parent . getChild ( "dataFormat" , Catalog . defNS ) ; if ( dataFormatElem != null ) { String dataFormatTypeName = dataFormatElem . getText ( ) ; if ( ( dataFormatTypeName != null ) && ( dataFormatTypeName . length ( ) > 0 ) ) { DataFormatType dataFormatType = DataFormatType . getType ( dataFormatTypeName ) ; if ( dataFormatType == null ) { errlog . format ( " ** warning: non-standard dataFormat type = '%s'%n" , dataFormatTypeName ) ; logger . debug ( " ** warning: non-standard dataFormat type = '{}'" , dataFormatTypeName ) ; } flds . put ( Dataset . DataFormatType , dataFormatTypeName ) ; } } long size = readDataSize ( parent ) ; if ( size > 0 ) { flds . put ( Dataset . DataSize , size ) ; } // LOOK: we seem to have put a variableMap element not contained by <variables> ThreddsMetadata . UriResolved mapUri = readUri ( parent . getChild ( "variableMap" , Catalog . defNS ) , "variableMap" ) ; if ( mapUri != null ) { flds . put ( Dataset . VariableMapLinkURI , mapUri ) ; } }


Input: ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected Documentation readDocumentation ( Element s ) { String href = s . getAttributeValue ( "href" , Catalog . xlinkNS ) ; String title = s . getAttributeValue ( "title" , Catalog . xlinkNS ) ; String type = s . getAttributeValue ( "type" ) ; // not XLink type String content = s . getTextNormalize ( ) ; URI uri = null ; if ( href != null ) { try { uri = Catalog . resolveUri ( baseURI , href ) ; } catch ( Exception e ) { errlog . format ( " ** Invalid documentation href = '%s' err='%s'%n" , href , e . getMessage ( ) ) ; logger . debug ( " ** Invalid documentation href = '{}' err='{}'" , href , e . getMessage ( ) ) ; } } return new Documentation ( href , uri , title , type , content ) ; }


Input: / * <xsd : element name = metadata > <xsd : complexType > <xsd : choice > <xsd : group ref = threddsMetadataGroup minOccurs = 0 maxOccurs = unbounded / > <xsd : any namespace = ##other minOccurs = 0 maxOccurs = unbounded processContents = lax / > < / xsd : choice > [CODESPLIT] protected ThreddsMetadata . MetadataOther readMetadata ( Map < String , Object > flds , DatasetBuilder dataset , Element mdataElement ) { // there are 6 cases to deal with: threddsNamespace vs not & inline vs Xlink & (if thredds) inherited or not Namespace namespace ; List inlineElements = mdataElement . getChildren ( ) ; if ( inlineElements . size ( ) > 0 ) { // look at the namespace of the children, if they exist namespace = ( ( Element ) inlineElements . get ( 0 ) ) . getNamespace ( ) ; } else { namespace = mdataElement . getNamespace ( ) ; // will be thredds } String mtype = mdataElement . getAttributeValue ( "metadataType" ) ; String href = mdataElement . getAttributeValue ( "href" , Catalog . xlinkNS ) ; String title = mdataElement . getAttributeValue ( "title" , Catalog . xlinkNS ) ; String inheritedS = mdataElement . getAttributeValue ( "inherited" ) ; boolean inherited = ( inheritedS != null ) && inheritedS . equalsIgnoreCase ( "true" ) ; boolean isThreddsNamespace = ( ( mtype == null ) || mtype . equalsIgnoreCase ( "THREDDS" ) ) && namespace . getURI ( ) . equals ( Catalog . CATALOG_NAMESPACE_10 ) ; // the case where its not ThreddsMetadata if ( ! isThreddsNamespace ) { if ( inlineElements . size ( ) > 0 ) { // just hold onto the jdom elements as the "content" return new ThreddsMetadata . MetadataOther ( mtype , namespace . getURI ( ) , namespace . getPrefix ( ) , inherited , mdataElement ) ; } else { // otherwise it must be an Xlink return new ThreddsMetadata . MetadataOther ( href , title , mtype , namespace . getURI ( ) , namespace . getPrefix ( ) , inherited ) ; } } // the case where its ThreddsMetadata Map < String , Object > useFlds ; if ( inherited ) { // the case where its inherited ThreddsMetadata: gonna put stuff in the tmi. ThreddsMetadata tmi = ( ThreddsMetadata ) dataset . get ( Dataset . ThreddsMetadataInheritable ) ; if ( tmi == null ) { tmi = new ThreddsMetadata ( ) ; dataset . put ( Dataset . ThreddsMetadataInheritable , tmi ) ; } useFlds = tmi . getFlds ( ) ; } else { // the case where its non-inherited ThreddsMetadata: gonna put stuff directly into the dataset useFlds = flds ; } readThreddsMetadataGroup ( useFlds , dataset , mdataElement ) ; // also need to capture any XLinks. see http://www.unidata.ucar.edu/software/thredds/v4.6/tds/catalog/InvCatalogSpec.html#metadataElement // in this case we just suck it in as if it was inline if ( href != null ) { try { URI xlinkUri = Catalog . resolveUri ( baseURI , href ) ; Element remoteMdata = readMetadataFromUrl ( xlinkUri ) ; return readMetadata ( useFlds , dataset , remoteMdata ) ; } catch ( Exception ioe ) { errlog . format ( "Cant read in referenced metadata %s err=%s%n" , href , ioe . getMessage ( ) ) ; logger . debug ( "Can't read in referenced metadata {} err={}}" , href , ioe . getMessage ( ) ) ; } } return null ; // ThreddsMetadata.MetadataOther was directly added }


Input: / * <xsd : complexType name = sourceType > <xsd : sequence > <xsd : element name = name type = controlledVocabulary / > [CODESPLIT] protected ThreddsMetadata . Source readSource ( Element elem ) { if ( elem == null ) { return null ; } ThreddsMetadata . Vocab name = readControlledVocabulary ( elem . getChild ( "name" , Catalog . defNS ) ) ; Element contact = elem . getChild ( "contact" , Catalog . defNS ) ; if ( contact == null ) { errlog . format ( " ** Parse error: Missing contact element in = '%s'%n" , elem . getName ( ) ) ; logger . debug ( " ** Parse error: Missing contact element in = '{}'" , elem . getName ( ) ) ; return null ; } return new ThreddsMetadata . Source ( name , contact . getAttributeValue ( "url" ) , contact . getAttributeValue ( "email" ) ) ; }


Input: / * <xsd : complexType name = timeCoverageType > <xsd : sequence > <xsd : attribute name = calendar type = xsd : string / > <xsd : choice minOccurs = 2 maxOccurs = 3 > <xsd : element name = start type = dateTypeFormatted / > <xsd : element name = end type = dateTypeFormatted / > <xsd : element name = duration type = duration / > < / xsd : choice > <xsd : element name = resolution type = duration minOccurs = 0 / > < / xsd : sequence > < / xsd : complexType > [CODESPLIT] protected DateRange readTimeCoverage ( Element tElem ) { if ( tElem == null ) { return null ; } Calendar calendar = readCalendar ( tElem . getAttributeValue ( "calendar" ) ) ; DateType start = readDate ( tElem . getChild ( "start" , Catalog . defNS ) , calendar ) ; DateType end = readDate ( tElem . getChild ( "end" , Catalog . defNS ) , calendar ) ; TimeDuration duration = readDuration ( tElem . getChild ( "duration" , Catalog . defNS ) ) ; TimeDuration resolution = readDuration ( tElem . getChild ( "resolution" , Catalog . defNS ) ) ; try { return new DateRange ( start , end , duration , resolution ) ; } catch ( java . lang . IllegalArgumentException e ) { errlog . format ( " ** warning: TimeCoverage error ='%s'%n" , e . getMessage ( ) ) ; logger . debug ( " ** warning: TimeCoverage error ='{}'" , e . getMessage ( ) ) ; return null ; } }


Input: / * <xsd : element name = variables > <xsd : complexType > <xsd : choice > <xsd : element ref = variable minOccurs = 0 maxOccurs = unbounded / > <xsd : element ref = variableMap minOccurs = 0 / > < / xsd : choice > <xsd : attribute name = vocabulary type = variableNameVocabulary use = optional / > <xsd : attributeGroup ref = XLink / > < / xsd : complexType > < / xsd : element > [CODESPLIT] protected ThreddsMetadata . VariableGroup readVariables ( Element varsElem ) { if ( varsElem == null ) { return null ; } String vocab = varsElem . getAttributeValue ( "vocabulary" ) ; ThreddsMetadata . UriResolved variableVocabUri = readUri ( varsElem , "Variables vocabulary" ) ; java . util . List < Element > vlist = varsElem . getChildren ( "variable" , Catalog . defNS ) ; ThreddsMetadata . UriResolved variableMap = readUri ( varsElem . getChild ( "variableMap" , Catalog . defNS ) , "Variables Map" ) ; if ( ( variableMap != null ) && vlist . size ( ) > 0 ) { // cant do both errlog . format ( " ** Catalog error: cant have variableMap and variable in same element '%s'%n" , varsElem ) ; } List < ThreddsMetadata . Variable > variables = new ArrayList <> ( ) ; for ( Element e : vlist ) { variables . add ( readVariable ( e ) ) ; } return new ThreddsMetadata . VariableGroup ( vocab , variableVocabUri , variableMap , variables ) ; }


Input: A time span as defined in the W3C XML Schema 1 . 0 specification : PnYnMnDTnHnMnS where nY represents the number of years nM the number of months nD the number of days T is the date / time separator nH the number of hours nM the number of minutes and nS the number of seconds . The number of seconds can include decimal digits to arbitrary precision . [CODESPLIT] static public TimeDuration parseW3CDuration ( String text ) throws java . text . ParseException { TimeDuration td = new TimeDuration ( ) ; text = ( text == null ) ? "" : text . trim ( ) ; td . text = text ; try { DatatypeFactory factory = DatatypeFactory . newInstance ( ) ; Duration d = factory . newDuration ( text ) ; //long secs = d.getTimeInMillis(new Date()) / 1000; Calendar c = Calendar . getInstance ( ) ; c . set ( 1900 , 0 , 1 , 0 , 0 , 0 ) ; long secs = d . getTimeInMillis ( c . getTime ( ) ) / 1000 ; td . timeUnit = new TimeUnit ( secs + " secs" ) ; } catch ( Exception e ) { throw new java . text . ParseException ( e . getMessage ( ) , 0 ) ; } return td ; }


Input: test [CODESPLIT] private static void doDuration ( String s ) { try { System . out . println ( "start = (" + s + ")" ) ; TimeDuration d = new TimeDuration ( s ) ; System . out . println ( "duration = (" + d . toString ( ) + ")" ) ; } catch ( java . text . ParseException e ) { e . printStackTrace ( ) ; } }


Input: / * public long sendData ( WritableByteChannel wbc StructureData sdata ) throws IOException { long size = 0 ; ByteBuffer bb = IospHelper . copyToByteBuffer ( sdata ) ; byte [] datab = bb . array () ; size + = writeBytes ( wbc NcStream . MAGIC_DATA ) ; // magic size + = NcStream . writeVInt ( wbc datab . length ) ; // data len size + = writeBytes ( wbc datab ) ; // data return size ; } [CODESPLIT] private int writeBytes ( WritableByteChannel wbc , byte [ ] b ) throws IOException { return wbc . write ( ByteBuffer . wrap ( b ) ) ; }


Input: Get the parameter with id . If not found look in default table . [CODESPLIT] public Grib1Parameter getParameter ( int id ) { if ( parameters == null ) { parameters = readParameterTable ( ) ; } return parameters . get ( id ) ; }


Input: Get the parameter with id but dont look in default table . [CODESPLIT] public Grib1Parameter getLocalParameter ( int id ) { if ( parameters == null ) { parameters = readParameterTable ( ) ; } return parameters . get ( id ) ; }


Input: reading [CODESPLIT] private synchronized Map < Integer , Grib1Parameter > readParameterTable ( ) { if ( path == null ) { throw new IllegalStateException ( name ) ; } try { if ( name . startsWith ( "table_2_" ) || name . startsWith ( "local_table_2_" ) ) { return readParameterTableEcmwf ( ) ; // ecmwf } else if ( name . startsWith ( "US058" ) ) { return readParameterTableXml ( new FnmocParser ( ) ) ; // FNMOC } else if ( name . endsWith ( ".tab" ) ) { return readParameterTableTab ( ) ; // wgrib format } else if ( name . endsWith ( ".wrf" ) ) { return readParameterTableSplit ( "\\|" , new int [ ] { 0 , 3 , 1 , 2 } ) ; // WRF AMPS } else if ( name . endsWith ( ".h" ) ) { return readParameterTableNcl ( ) ; // NCL } else if ( name . endsWith ( ".dss" ) ) { return readParameterTableSplit ( "\t" , new int [ ] { 0 , - 1 , 1 , 2 } ) ; // NCAR DSS } else if ( name . endsWith ( ".xml" ) ) { return readParameterTableXml ( new DssParser ( Namespace . NO_NAMESPACE ) ) ; // NCAR DSS XML format } else if ( name . startsWith ( "2.98" ) ) { return readParameterTableEcmwfEcCodes ( ) ; // ecmwf from ecCodes package } else { throw new RuntimeException ( "Grib1ParamTableReader: Dont know how to read " + name + " file=" + path ) ; } } catch ( IOException ioError ) { logger . warn ( "An error occurred in Grib1ParamTable while trying to open the parameter table {}:{}" , path , ioError . getMessage ( ) ) ; throw new RuntimeException ( ioError ) ; } }


Input: / * WMO standard table 2 : Version Number 3 . Codes and data units for FM 92 - X Ext . GRIB . ...................... 001 P Pressure Pa Pa ...................... 002 MSL Mean sea level pressure Pa Pa ...................... 003 None Pressure tendency Pa s ** - 1 Pa s ** - 1 ...................... 004 PV Potential vorticity K m ** 2 kg ** - 1 s ** - 1 K m ** 2 kg ** - 1 s ** - 1 ...................... 005 None ICAO Standard Atmosphere reference height m m [CODESPLIT] private Map < Integer , Grib1Parameter > readParameterTableEcmwf ( ) throws IOException { HashMap < Integer , Grib1Parameter > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { String line = br . readLine ( ) ; if ( line == null ) { throw new FileNotFoundException ( path + " is empty" ) ; } if ( ! line . startsWith ( "..." ) ) { this . desc = line ; // maybe ?? } while ( line != null && ! line . startsWith ( "..." ) ) { line = br . readLine ( ) ; // skip } while ( true ) { line = br . readLine ( ) ; if ( line == null ) { break ; // done with the file } if ( ( line . length ( ) == 0 ) || line . startsWith ( "#" ) ) { continue ; } if ( line . startsWith ( "..." ) ) { // ...  may have already been read line = br . readLine ( ) ; if ( line == null ) { break ; } } String num = line . trim ( ) ; line = br . readLine ( ) ; String name = ( line != null ) ? line . trim ( ) : null ; line = br . readLine ( ) ; String desc = ( line != null ) ? line . trim ( ) : null ; line = br . readLine ( ) ; String units1 = ( line != null ) ? line . trim ( ) : null ; // optional notes line = br . readLine ( ) ; String notes = ( line == null || line . startsWith ( "..." ) ) ? null : line . trim ( ) ; if ( desc != null && desc . equalsIgnoreCase ( "undefined" ) ) { continue ; // skip } int p1 ; try { p1 = Integer . parseInt ( num ) ; } catch ( Exception e ) { logger . warn ( "Cant parse " + num + " in file " + path ) ; continue ; } Grib1Parameter parameter = new Grib1Parameter ( this , p1 , name , desc , units1 ) ; result . put ( parameter . getNumber ( ) , parameter ) ; logger . debug ( " %s (%s)%n" , parameter , notes ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe } }


Input: This method will read in ECMWF grib1 tables . Note that these tables are generated locally by Unidata and come directly from the ECMWF GRIB - API package localConcepts files . They are generated by : <p > ucar . nc2 . grib . grib1 . tables . EcmwfLocalConcepts <p > The original localConcepts files are located in : <p / > grib / src / main / sources / ecmwfEcCodes / <p / > Since we write the table file that are ultimately read by CDM the format is controled and is the following : <p > paramNum shortName [ description ] ( units ) <p > for example <p > 251 atte [ Adiabatic tendency of temperature ] ( K ) [CODESPLIT] private Map < Integer , Grib1Parameter > readParameterTableEcmwfEcCodes ( ) throws IOException { HashMap < Integer , Grib1Parameter > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { String line = br . readLine ( ) ; if ( line == null ) { throw new FileNotFoundException ( path + " is empty" ) ; } // create table name from file name String [ ] splitPath = path . split ( "/" ) ; String tableNum = splitPath [ splitPath . length - 1 ] . replace ( ".table" , "" ) ; this . desc = "ECMWF GRIB API TABLE " + tableNum ; // skip header while ( line != null && ! line . startsWith ( "#" ) ) { line = br . readLine ( ) ; // skip } // keep going until the end of the file is reached (line == null) while ( true ) { // exmaple: 251 atte [Adiabatic tendency of temperature] (K) line = br . readLine ( ) ; if ( line == null ) { break ; // done with the file } if ( ( line . length ( ) == 0 ) || line . startsWith ( "#" ) ) { continue ; } // get unit - (K) String [ ] tmpUnitArray = line . split ( "\\(" ) ; String tmpUnit = tmpUnitArray [ tmpUnitArray . length - 1 ] ; int lastUnitIndex ; while ( ( lastUnitIndex = tmpUnit . lastIndexOf ( ")" ) ) > 0 ) { tmpUnit = tmpUnit . substring ( 0 , lastUnitIndex ) . trim ( ) ; } String unit = tmpUnit . trim ( ) ; // unit = Util.cleanUnit(unit); // fixes some common unit mistakes  // jcaron - just use unit as it is // get parameter number - 251 String [ ] lineArray = line . trim ( ) . split ( "\\s+" ) ; // all and any white space String num = lineArray [ 0 ] ; // get shortName - atte String name = lineArray [ 1 ] . trim ( ) ; //if (name.equals("~")) {}; - todo create name from long name(?) // get description. bracketed by [] - [Adiabatic Tendency of temperature] int startDesc = line . indexOf ( "[" ) ; int endDesc = line . indexOf ( "]" ) ; String desc = line . substring ( startDesc , endDesc ) . trim ( ) ; // stuff information into a Grib1Parameter object int p1 ; try { p1 = Integer . parseInt ( num ) ; } catch ( Exception e ) { logger . warn ( "Cant parse " + num + " in file " + path ) ; continue ; } Grib1Parameter parameter = new Grib1Parameter ( this , p1 , name , desc , unit ) ; result . put ( parameter . getNumber ( ) , parameter ) ; logger . debug ( " %s%n" , parameter ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe } }


Input: order : num name desc unit [CODESPLIT] private Map < Integer , Grib1Parameter > readParameterTableSplit ( String regexp , int [ ] order ) throws IOException { HashMap < Integer , Grib1Parameter > result = new HashMap <> ( ) ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( is , StandardCharsets . UTF_8 ) ) ) { // rdg - added the 0 line length check to cover the case of blank lines at the end of the parameter table file. while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } if ( ( line . length ( ) == 0 ) || line . startsWith ( "#" ) ) { continue ; } String [ ] flds = line . split ( regexp ) ; int p1 = Integer . parseInt ( flds [ order [ 0 ] ] . trim ( ) ) ; // must have a number String name = ( order [ 1 ] >= 0 ) ? flds [ order [ 1 ] ] . trim ( ) : null ; String desc = flds [ order [ 2 ] ] . trim ( ) ; String units = ( flds . length > order [ 3 ] ) ? flds [ order [ 3 ] ] . trim ( ) : "" ; Grib1Parameter parameter = new Grib1Parameter ( this , p1 , name , desc , units ) ; result . put ( parameter . getNumber ( ) , parameter ) ; logger . debug ( " %s%n" , parameter ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe } }


Input: Adds a prefix to the database by name . [CODESPLIT] public void addName ( final String name , final double value ) throws PrefixExistsException { final Prefix prefix = new PrefixName ( name , value ) ; nameSet . add ( prefix ) ; }


Input: Adds a prefix symbol to the database . [CODESPLIT] public void addSymbol ( final String symbol , final double value ) throws PrefixExistsException { final Prefix prefix = new PrefixSymbol ( symbol , value ) ; symbolSet . add ( prefix ) ; valueMap . put ( new Double ( value ) , prefix ) ; }


Input: Returns the prefix from the given set with the given identifier . [CODESPLIT] private static Prefix getPrefix ( final String string , final Set < Prefix > set ) { for ( final Iterator < Prefix > iter = set . iterator ( ) ; iter . hasNext ( ) ; ) { final Prefix prefix = iter . next ( ) ; final int comp = prefix . compareTo ( string ) ; if ( comp == 0 ) { return prefix ; } if ( comp > 0 ) { break ; } } return null ; }


Input: check its an acceptable form of email [CODESPLIT] protected boolean emailOK ( ThreddsMetadata . Source p ) { String email = p . getEmail ( ) ; return email . indexOf ( ' ' ) >= 0 ; // should really do a regexp }


Input: test [CODESPLIT] private static void doOne ( InvCatalogFactory fac , String url ) { System . out . println ( "***read " + url ) ; try { InvCatalogImpl cat = fac . readXML ( url ) ; StringBuilder buff = new StringBuilder ( ) ; boolean isValid = cat . check ( buff , false ) ; System . out . println ( "catalog <" + cat . getName ( ) + "> " + ( isValid ? "is" : "is not" ) + " valid" ) ; System . out . println ( " validation output=\n" + buff ) ; // System.out.println(" catalog=\n" + fac.writeXML(cat)); ADNWriter w = new ADNWriter ( ) ; StringBuilder sbuff = new StringBuilder ( ) ; w . writeDatasetEntries ( cat , "C:/temp/adn3" , sbuff ) ; System . out . println ( " messages=\n" + sbuff ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }


Input: Peek ahead [CODESPLIT] private char peek ( ) throws ParseException { try { reader . mark ( 10 ) ; int aChar = reader . read ( ) ; reader . reset ( ) ; if ( aChar < 0 ) { return ( char ) 0 ; } else { return ( char ) aChar ; } } catch ( java . io . IOException e1 ) { throw new ParseException ( "Strange io error " + e1 , position ) ; } }


Input: _more_ [CODESPLIT] private char getChar ( ) throws ParseException { try { int val = reader . read ( ) ; position ++ ; if ( val < 0 ) { throw new ParseException ( "unexpected eof of srtext" , position ) ; } return ( char ) val ; } catch ( java . io . IOException e1 ) { throw new ParseException ( e1 . toString ( ) , position ) ; } }


Input: _more_ [CODESPLIT] private void eatLiteral ( String literal ) throws ParseException { int n = literal . length ( ) ; for ( int i = 0 ; i < n ; i ++ ) { char v = getChar ( ) ; if ( v != literal . charAt ( i ) ) { throw new ParseException ( "bad srtext" , position ) ; } } }


Input: _more_ [CODESPLIT] private double eatReal ( ) throws ParseException { StringBuilder b = new StringBuilder ( ) ; for ( ; ; ) { char t = peek ( ) ; if ( Character . isDigit ( t ) || ( t == ' ' ) || ( t == ' ' ) || ( t == ' ' ) || ( t == ' ' ) || ( t == ' ' ) ) { b . append ( getChar ( ) ) ; } else { break ; } } try { return Double . parseDouble ( b . toString ( ) ) ; } catch ( NumberFormatException e1 ) { throw new ParseException ( "bad number" + e1 , position ) ; } }


Input: _more_ [CODESPLIT] private String eatString ( ) throws ParseException { StringBuilder b = new StringBuilder ( ) ; if ( getChar ( ) != ' ' ) { throw new ParseException ( "expected string" , position ) ; } for ( ; ; ) { char t = getChar ( ) ; if ( t == ' ' ) { break ; } b . append ( t ) ; } return b . toString ( ) ; }


Input: _more_ [CODESPLIT] private String eatTerm ( ) throws ParseException { StringBuilder b = new StringBuilder ( ) ; for ( ; ; ) { char val = peek ( ) ; if ( ! Character . isJavaIdentifierPart ( val ) ) { break ; } b . append ( getChar ( ) ) ; } return b . toString ( ) ; }


Input: _more_ [CODESPLIT] private void parseProjcs ( ) throws ParseException { eatLiteral ( "PROJCS[" ) ; projName = eatString ( ) ; eatComma ( ) ; parseGeogcs ( ) ; for ( ; ; ) { char next = getChar ( ) ; if ( next == ' ' ) { break ; } else if ( next != ' ' ) { throw new ParseException ( "expected , or ]" , position ) ; } else { String term = eatTerm ( ) ; if ( "PARAMETER" . equals ( term ) ) { eatParameter ( ) ; } else if ( "UNIT" . equals ( term ) ) { eatProjcsUnit ( ) ; } else if ( "PROJECTION" . equals ( term ) ) { eatProjectionType ( ) ; } } } }


Input: _more_ [CODESPLIT] private void eatParameter ( ) throws ParseException { eatOpenBrace ( ) ; String parameterName = eatString ( ) ; eatComma ( ) ; Double value = eatReal ( ) ; eatCloseBrace ( ) ; parameters . put ( parameterName . toLowerCase ( ) , value ) ; }


Input: _more_ [CODESPLIT] private void parseGeogcs ( ) throws ParseException { eatLiteral ( "GEOGCS[" ) ; geogcsName = eatString ( ) ; for ( ; ; ) { char t = getChar ( ) ; if ( t == ' ' ) { break ; } else if ( t != ' ' ) { throw new ParseException ( "expected , or ]" , position ) ; } else { String term = eatTerm ( ) ; if ( "DATUM" . equals ( term ) ) { eatDatum ( ) ; } else if ( "PRIMEM" . equals ( term ) ) { eatPrimem ( ) ; } else if ( "UNIT" . equals ( term ) ) { eatUnit ( ) ; } } } }


Input: _more_ [CODESPLIT] private void eatSpheroid ( ) throws ParseException { eatLiteral ( "SPHEROID" ) ; eatOpenBrace ( ) ; spheroidName = eatString ( ) ; eatComma ( ) ; majorAxis = eatReal ( ) ; eatComma ( ) ; inverseMinor = eatReal ( ) ; eatCloseBrace ( ) ; }


Input: Get the value of the projection parameter . An IllegalArgument exception is thrown if the parameter is not found . [CODESPLIT] public double getParameter ( String name ) { Double val = ( Double ) parameters . get ( name . toLowerCase ( ) ) ; if ( val == null ) { throw new IllegalArgumentException ( "no parameter called " + name ) ; } return val . doubleValue ( ) ; }


Input:
Convert OGC spatial reference WKT to a ProjectionImpl . An IllegalArgumentException may be thrown if a parameter is missing . [CODESPLIT] public static ProjectionImpl convertWKTToProjection ( WKTParser srp ) { if ( ! srp . isPlanarProjection ( ) ) { return new ucar . unidata . geoloc . projection . LatLonProjection ( ) ; } else { String projectionType = srp . getProjectionType ( ) ; double falseEasting = 0 ; double falseNorthing = 0 ; ProjectionImpl proj = null ; if ( srp . hasParameter ( "False_Easting" ) ) { falseEasting = srp . getParameter ( "False_Easting" ) ; } if ( srp . hasParameter ( "False_Northing" ) ) { falseNorthing = srp . getParameter ( "False_Northing" ) ; } if ( ( falseEasting != 0.0 ) || ( falseNorthing != 0.0 ) ) { double scalef = 1.0 ; if ( srp . getProjUnitName ( ) != null ) { try { SimpleUnit unit = SimpleUnit . factoryWithExceptions ( srp . getProjUnitName ( ) ) ; scalef = unit . convertTo ( srp . getProjUnitValue ( ) , SimpleUnit . kmUnit ) ; } catch ( Exception e ) { System . out . println ( srp . getProjUnitValue ( ) + " " + srp . getProjUnitName ( ) + " not convertible to km" ) ; } } falseEasting *= scalef ; falseNorthing *= scalef ; } if ( srp . getProjName ( ) . contains ( "UTM_Zone_" ) ) return processUTM ( srp ) ; if ( "Transverse_Mercator" . equals ( projectionType ) ) { double lat0 = srp . getParameter ( "Latitude_Of_Origin" ) ; double scale = srp . getParameter ( "Scale_Factor" ) ; double tangentLon = srp . getParameter ( "Central_Meridian" ) ; proj = new TransverseMercator ( lat0 , tangentLon , scale , falseEasting , falseNorthing ) ; } else if ( "Lambert_Conformal_Conic" . equals ( projectionType ) ) { double lon0 = srp . getParameter ( "Central_Meridian" ) ; double par1 = srp . getParameter ( "Standard_Parallel_1" ) ; double par2 = par1 ; if ( srp . hasParameter ( "Standard_Parallel_2" ) ) { par2 = srp . getParameter ( "Standard_Parallel_2" ) ; } double lat0 = srp . getParameter ( "Latitude_Of_Origin" ) ; return new LambertConformal ( lat0 , lon0 , par1 , par2 , falseEasting , falseNorthing ) ; } else if ( "Albers" . equals ( projectionType ) ) { double lon0 = srp . getParameter ( "Central_Meridian" ) ; double par1 = srp . getParameter ( "Standard_Parallel_1" ) ; double par2 = par1 ; if ( srp . hasParameter ( "Standard_Parallel_2" ) ) { par2 = srp . getParameter ( "Standard_Parallel_2" ) ; } double lat0 = srp . getParameter ( "Latitude_Of_Origin" ) ; return new AlbersEqualArea ( lat0 , lon0 , par1 , par2 , falseEasting , falseNorthing ) ; } else if ( "Stereographic" . equals ( projectionType ) ) { double lont = srp . getParameter ( "Central_Meridian" ) ; double scale = srp . getParameter ( "Scale_Factor" ) ; double latt = srp . getParameter ( "Latitude_Of_Origin" ) ; return new Stereographic ( latt , lont , scale , falseEasting , falseNorthing ) ; } else if ( "Mercator" . equals ( projectionType ) ) { double lat0 = srp . getParameter ( "Latitude_Of_Origin" ) ; double lon0 = srp . getParameter ( "Central_Meridian" ) ; proj = new Mercator ( lon0 , lat0 , falseEasting , falseNorthing ) ; } else if ( "Universal_Transverse_Mercator" . equals ( projectionType ) ) { //throw new java.text.ParseException(
 //    "UTM adapter not implemented yet", 0);
 } return proj ; } }


Input: Calculate the CRC of the entire byte array [CODESPLIT] public long calcCRC ( ) { long crc ; if ( rawData == null ) crc = predefinedGridDefinitionCenter << 16 + predefinedGridDefinition ; else { CRC32 crc32 = new CRC32 ( ) ; crc32 . update ( rawData ) ; crc = crc32 . getValue ( ) ; } return crc ; }


Input: is a thin grid [CODESPLIT] public final boolean isThin ( ) { if ( rawData == null ) return false ; int octet5 = getOctet ( 5 ) ; int nv = getOctet ( 4 ) ; return ( octet5 != 255 ) && ( nv == 0 || nv == 255 ) ; }


Input:
Gets the number of points in each line for Quasi / Thin grids List of numbers of points in each row ( length = NROWS x 2 octets where NROWS is the total number of rows defined within the grid description ) [CODESPLIT] private int [ ] getNptsInLine ( Grib1Gds gds ) { int numPts ; if ( ( gds . getScanMode ( ) & 32 ) == 0 ) { // bit3 = 0 : Adjacent points in i direction are consecutive
 numPts = gds . getNy ( ) ; } else { // bit3 = 1 : Adjacent points in j direction are consecutive
 numPts = gds . getNx ( ) ; } int [ ] parallels = new int [ numPts ] ; int offset = getOctet ( 5 ) ; for ( int i = 0 ; i < numPts ; i ++ ) { parallels [ i ] = GribNumbers . int2 ( getOctet ( offset ++ ) , getOctet ( offset ++ ) ) ; } return parallels ; }


Input: /////////////////////////////////////////////// [CODESPLIT] public boolean hasVerticalCoordinateParameters ( ) { if ( rawData == null ) return false ; int octet5 = getOctet ( 5 ) ; int nv = getOctet ( 4 ) ; return ( octet5 != 255 ) && ( nv != 0 && nv != 255 ) ; }


Input: Selected DataCursor API overrides [CODESPLIT] @ Override public int fieldIndex ( String name ) throws DapException { DapStructure ds ; if ( getTemplate ( ) . getSort ( ) . isCompound ( ) ) ds = ( DapStructure ) getTemplate ( ) ; else if ( getTemplate ( ) . getSort ( ) . isVar ( ) && ( ( ( DapVariable ) getTemplate ( ) ) . getBaseType ( ) . getSort ( ) . isCompound ( ) ) ) ds = ( DapStructure ) ( ( DapVariable ) getTemplate ( ) ) . getBaseType ( ) ; else throw new DapException ( "Attempt to get field name on non-compound object" ) ; int i = ds . indexByName ( name ) ; if ( i < 0 ) throw new DapException ( "Unknown field name: " + name ) ; return i ; }


Input: Utilities [CODESPLIT] static public Scheme schemeFor ( DapVariable field ) { DapType ftype = field . getBaseType ( ) ; Scheme scheme = null ; boolean isscalar = field . getRank ( ) == 0 ; if ( ftype . getTypeSort ( ) . isAtomic ( ) ) scheme = Scheme . ATOMIC ; else { if ( ftype . getTypeSort ( ) . isStructType ( ) ) scheme = Scheme . STRUCTARRAY ; else if ( ftype . getTypeSort ( ) . isSeqType ( ) ) scheme = Scheme . SEQARRAY ; } return scheme ; }


Input: Returns { @code true } if we should add 2D latitude & longitude variables to the output file . This method could return { @code false } for several reasons : [CODESPLIT] private boolean shouldAddLatLon2D ( boolean tryToAddLatLon2D , CoverageCollection subsetDataset ) { if ( ! tryToAddLatLon2D ) { // We don't even want 2D lat/lon vars. return false ; } HorizCoordSys horizCoordSys = subsetDataset . getHorizCoordSys ( ) ; if ( horizCoordSys . isLatLon2D ( ) ) { // We already have 2D lat/lon vars. return false ; } if ( ! horizCoordSys . isProjection ( ) ) { // CRS doesn't contain a projection, meaning we can't calc 2D lat/lon vars. return false ; } Projection proj = horizCoordSys . getTransform ( ) . getProjection ( ) ; if ( proj instanceof LatLonProjection ) { // Projection is a "fake"; we already have lat/lon. return false ; } return true ; }


Input:
code table 5 - 2010 edition of WMO manual on codes [CODESPLIT] public static String getTimeTypeName ( int timeRangeIndicator ) { String timeRange ; switch ( timeRangeIndicator ) { /* Forecast product valid for reference time + P1 (P1 > 0), or
        Uninitialized analysis product for reference time (P1 = 0), or
        Image product for reference time (P1 = 0) */ case 0 : timeRange = "Uninitialized analysis / image product / forecast product valid for RT + P1" ; break ; // Initialized analysis product for reference time (P1 = 0)
 case 1 : timeRange = "Initialized analysis product for reference time" ; break ; // Product with a valid time ranging between reference time + P1 and reference time + P2
 case 2 : timeRange = "product valid, interval = (RT + P1) to (RT + P2)" ; break ; // Average (reference time + P1 to reference time + P2)
 case 3 : timeRange = "Average, interval = (RT + P1) to (RT + P2)" ; break ; /* Accumulation  (reference  time  +  P1  to  reference  time  +  P2)  product  considered  valid  at
        reference time + P2 */ case 4 : timeRange = "Accumulation, interval = (RT + P1) to (RT + P2)" ; break ; /* Difference  (reference  time  +  P2  minus  reference  time  +  P1)  product  considered  valid  at
        reference time + P2 */ case 5 : timeRange = "Difference, interval = (RT + P2) - (RT + P1)" ; break ; // Average (reference time - P1 to reference time - P2)
 case 6 : timeRange = "Average, interval = (RT - P1) to (RT - P2)" ; break ; // Average (reference time - P1 to reference time + P2)
 case 7 : timeRange = "Average, interval = (RT - P1) to (RT + P2)" ; break ; // P1 occupies octets 19 and 20; product valid at reference time + P1
 case 10 : timeRange = "product valid at RT + P1" ; break ; /* Climatological  mean  value:  multiple  year  averages  of  quantities  which  are  themselves
        means over some period of time (P2) less than a year. The reference time (R) indicates the
        date and time of the start of a period of time, given by R to R + P2, over which a mean is
        formed; N indicates the number of such period-means that are averaged together to form
        the  climatological  value,  assuming  that  the  N  period-mean  fields  are  separated  by  one
        year. The reference time indicates the start of the N-year climatology.

        If P1 = 0 then the data averaged in the basic interval P2 are assumed to be continuous, i.e. all available data
        are simply averaged together.

        If P1 = 1 (the unit of time  octet 18, Code table 4  is not
        relevant here) then the data averaged together in the basic interval P2 are valid only at the
        time (hour, minute) given in the reference time, for all the days included in the P2 period.
        The units of P2 are given by the contents of octet 18 and Code table 4 */ case 51 : timeRange = "Climatological mean values from RT to (RT + P2)" ; // if (p1 == 0) timeRange += " continuous";
 break ; /* Average  of  N  forecasts  (or  initialized  analyses);  each  product  has  forecast  period  of  P1
        (P1 = 0 for initialized analyses); products have reference times at intervals of P2, beginning
        at the given reference time */ case 113 : timeRange = "Average of N forecasts, intervals = (refTime + i * P2, refTime + i * P2 + P1)" ; break ; /* Accumulation of N forecasts (or initialized analyses); each product has forecast period of
        P1  (P1  =  0  for  initialized  analyses);  products  have  reference  times  at  intervals  of  P2,
        beginning at the given reference time */ case 114 : timeRange = "Accumulation of N forecasts, intervals = (refTime + i * P2, refTime + i * P2 + P1)" ; break ; /* Average of N forecasts, all with the same reference time; the first has a forecast period of
         P1, the remaining forecasts follow at intervals of P2 */ case 115 : timeRange = "Average of N forecasts, intervals = (refTime, refTime + P1 + i * P2)" ; break ; /* Accumulation  of  N  forecasts,  all  with  the  same  reference  time;  the  first  has  a  forecast
        period of P1, the remaining forecasts follow at intervals of P2 */ case 116 : timeRange = "Accumulation of N forecasts, intervals = (refTime, refTime + P1 + i * P2)" ; break ; /* Average of N forecasts; the first has a forecast period of P1, the subsequent ones have
        forecast periods reduced from the previous one by an interval of P2; the reference time for
        the first is given in octets 13 to 17, the subsequent ones have reference times increased
        from the previous one by an interval of P2. Thus all the forecasts have the same valid time,
        given by the initial reference time + P1 */ case 117 : timeRange = "Average of N forecasts, intervals = (refTime + i * P2, refTime + P1)" ; break ; /* Temporal  variance,  or  covariance,  of  N  initialized  analyses;  each  product  has  forecast
        period of P1 = 0; products have reference times at intervals of P2, beginning at the given
        reference time */ case 118 : timeRange = "Temporal variance or covariance of N initialized analyses, timeCoord = (refTime + i * P2)" ; break ; /* Standard deviation of N forecasts, all with the same reference time with respect to the time
        average of forecasts; the first forecast has a forecast period of P1, the remaining forecasts
        follow at intervals of P2 */ case 119 : timeRange = "Standard Deviation of N forecasts, timeCoord = (refTime + P1 + i * P2)" ; break ; // ECMWF "Average of N Forecast" added 11/21/2014. pretend its WMO standard. maybe should move to ecmwf ??
 // see "http://emoslib.sourcearchive.com/documentation/000370.dfsg.2/grchk1_8F-source.html"
 // C     Add Time range indicator = 120 Average of N Forecast. Each product
 // C             is an accumulation from forecast lenght P1 to forecast
 // C              lenght P2, with reference times at intervals P2-P1
 case 120 : timeRange = "Average of N Forecasts (ECMWF), accumulation from forecast P1 to P2, with reference times at intervals P2-P1" ; break ; // Average of N uninitialized analyses, starting at the reference time, at intervals of P2
 case 123 : timeRange = "Average of N uninitialized analyses, intervals = (refTime, refTime + i * P2)" ; break ; // Accumulation of N uninitialized analyses, starting at the reference time, at intervals of P2
 case 124 : timeRange = "Accumulation of N uninitialized analyses, intervals = (refTime, refTime + i * P2)" ; break ; /* Standard deviation of N forecasts, all with the same reference time with respect to time
        average of the time tendency of forecasts; the first forecast has a forecast period of P1,
        the remaining forecasts follow at intervals of P2 */ case 125 : timeRange = "Standard deviation of N forecasts, intervals = (refTime, refTime + P1 + i * P2)" ; break ; default : timeRange = "Unknown Time Range Indicator " + timeRangeIndicator ; } return timeRange ; }


Input: A string representation of the time coordinate whether its an interval or not . [CODESPLIT] public String getTimeCoord ( ) { if ( isInterval ( ) ) { int [ ] intv = getInterval ( ) ; return intv [ 0 ] + "-" + intv [ 1 ] ; } return Integer . toString ( getForecastTime ( ) ) ; }


Input: Append an error message to the message log . Call check () to get the log when everything is done . [CODESPLIT] public void appendErrorMessage ( String message , boolean fatal ) { errLog . append ( message ) ; errLog . append ( "\n" ) ; fatalError = fatalError || fatal ; }


Input: Utilities [CODESPLIT] protected String [ ] getparamset ( String key ) throws IOException { String [ ] values = this . params . get ( key ) ; return ( values == null ? new String [ 0 ] : values ) ; }


Input:
Set the offsets based on m . getSizeBytes () . Also sets members . setStructureSize () . [CODESPLIT] public static int setOffsets ( StructureMembers members ) { int offset = 0 ; for ( StructureMembers . Member m : members . getMembers ( ) ) { m . setDataParam ( offset ) ; offset += m . getSizeBytes ( ) ; // set inner offsets (starts again at 0)
 if ( m . getStructureMembers ( ) != null ) setOffsets ( m . getStructureMembers ( ) ) ; } members . setStructureSize ( offset ) ; return offset ; }


Input: Sets the next polygon which make up the multipolygon which this polygon is a part of . If next is a CFPolygon automatically connects the other polygon to this polygon as well . [CODESPLIT] public void setNext ( Polygon next ) { if ( next instanceof CFPolygon ) { setNext ( ( CFPolygon ) next ) ; } else this . next = next ; }


Input: Sets the previous polygon which makes up the multipolygon which this polygon is a part of . If prev is a CFPolygon automatically connect the other polygon to this polygon as well . [CODESPLIT] public void setPrev ( Polygon prev ) { if ( prev instanceof CFPolygon ) { setPrev ( ( CFPolygon ) prev ) ; } else this . prev = prev ; }


Input:
Given a dataset variable and index automatically sets up a previously constructed polygon . If the specified polygon is not found in the dataset returns null [CODESPLIT] public Polygon setupPolygon ( NetcdfDataset dataset , Variable polyvar , int index ) { this . points . clear ( ) ; Array xPts = null ; Array yPts = null ; Variable nodeCounts = null ; Variable partNodeCounts = null ; Variable interiorRings = null ; List < CoordinateAxis > axes = dataset . getCoordinateAxes ( ) ; CoordinateAxis x = null ; CoordinateAxis y = null ; String [ ] nodeCoords = polyvar . findAttributeIgnoreCase ( CF . NODE_COORDINATES ) . getStringValue ( ) . split ( " " ) ; // Look for x and y
 for ( CoordinateAxis ax : axes ) { if ( ax . getFullName ( ) . equals ( nodeCoords [ 0 ] ) ) x = ax ; if ( ax . getFullName ( ) . equals ( nodeCoords [ 1 ] ) ) y = ax ; } // Affirm node counts
 String nodeCoStr = polyvar . findAttValueIgnoreCase ( CF . NODE_COUNT , "" ) ; if ( ! nodeCoStr . equals ( "" ) ) { nodeCounts = dataset . findVariable ( nodeCoStr ) ; } else return null ; // Affirm part node counts
 String pNodeCoStr = polyvar . findAttValueIgnoreCase ( CF . PART_NODE_COUNT , "" ) ; if ( ! pNodeCoStr . equals ( "" ) ) { partNodeCounts = dataset . findVariable ( pNodeCoStr ) ; } // Affirm interior rings
 String interiorRingsStr = polyvar . findAttValueIgnoreCase ( CF . PART_NODE_COUNT , "" ) ; if ( ! interiorRingsStr . equals ( "" ) ) { interiorRings = dataset . findVariable ( interiorRingsStr ) ; } SimpleGeometryIndexFinder indexFinder = new SimpleGeometryIndexFinder ( nodeCounts ) ; //Get beginning and ending indicies for this polygon
 int lower = indexFinder . getBeginning ( index ) ; int upper = indexFinder . getEnd ( index ) ; try { xPts = x . read ( lower + ":" + upper ) . reduce ( ) ; yPts = y . read ( lower + ":" + upper ) . reduce ( ) ; IndexIterator itrX = xPts . getIndexIterator ( ) ; IndexIterator itrY = yPts . getIndexIterator ( ) ; // No multipolygons just read in the whole thing
 if ( partNodeCounts == null ) { this . next = null ; this . prev = null ; this . isInteriorRing = false ; // x and y should have the same shape, will add some handling on this
 while ( itrX . hasNext ( ) ) { this . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; } switch ( polyvar . getRank ( ) ) { case 2 : this . setData ( polyvar . read ( CFSimpleGeometryHelper . getSubsetString ( polyvar , index ) ) . reduce ( ) ) ; break ; case 1 : this . setData ( polyvar . read ( "" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations
 } } // If there are multipolygons then take the upper and lower of it and divy it up
 else { Polygon tail = this ; Array pnc = partNodeCounts . read ( ) ; Array ir = null ; IndexIterator pncItr = pnc . getIndexIterator ( ) ; if ( interiorRings != null ) ir = interiorRings . read ( ) ; // In part node count search for the right index to begin looking for "part node counts"
 int pncInd = 0 ; int pncEnd = 0 ; while ( pncEnd < lower ) { pncEnd += pncItr . getIntNext ( ) ; pncInd ++ ; } // Now the index is found, use part node count and the index to find each part node count of each individual part
 while ( lower < upper ) { int smaller = pnc . getInt ( pncInd ) ; // Set interior ring if needed
 if ( interiorRings != null ) { int interiorRingValue = ir . getInt ( pncInd ) ; switch ( interiorRingValue ) { case 0 : this . setInteriorRing ( false ) ; break ; case 1 : this . setInteriorRing ( true ) ; break ; // will handle default case
 } } else this . isInteriorRing = false ; while ( smaller > 0 ) { tail . addPoint ( itrX . getDoubleNext ( ) , itrY . getDoubleNext ( ) ) ; smaller -- ; } // Set data of each
 switch ( polyvar . getRank ( ) ) { case 2 : tail . setData ( polyvar . read ( CFSimpleGeometryHelper . getSubsetString ( polyvar , index ) ) . reduce ( ) ) ; break ; case 1 : tail . setData ( polyvar . read ( "" + index ) ) ; break ; default : throw new InvalidDataseriesException ( InvalidDataseriesException . RANK_MISMATCH ) ; // currently do not support anything but dataseries and scalar associations
 } lower += tail . getPoints ( ) . size ( ) ; pncInd ++ ; tail . setNext ( new CFPolygon ( ) ) ; tail = tail . getNext ( ) ; } //Clean up
 tail = tail . getPrev ( ) ; if ( tail != null ) tail . setNext ( null ) ; } } catch ( IOException | InvalidRangeException | InvalidDataseriesException e ) { cfpl . error ( e . getMessage ( ) ) ; return null ; } return this ; }


Input: Get named property . [CODESPLIT] public String findProperty ( String name ) { InvProperty result = null ; for ( InvProperty p : properties ) { if ( p . getName ( ) . equals ( name ) ) result = p ; } return ( result == null ) ? null : result . getValue ( ) ; }


Input: See if the service Base is reletive [CODESPLIT] public boolean isRelativeBase ( ) { if ( getServiceType ( ) == ServiceType . COMPOUND ) return true ; if ( uri == null ) { try { uri = new java . net . URI ( base ) ; } catch ( java . net . URISyntaxException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } } return ! uri . isAbsolute ( ) ; }


Input: set current projection if found else deselect [CODESPLIT] public void setCurrentProjection ( ProjectionImpl proj ) { int row ; if ( 0 <= ( row = model . search ( proj ) ) ) { if ( debug ) System . out . println ( " PTsetCurrentProjection found = " + row ) ; selectedRow = row ; setRowSelectionInterval ( row , row ) ; } else { if ( debug ) System . out . println ( " PTsetCurrentProjection not found = " + row ) ; selectedRow = - 1 ; clearSelection ( ) ; } }


Input: normal case already handled this is the case where a time has been specified and only one runtime [CODESPLIT] public Optional < TimeOffsetAxis > subsetFromTime ( SubsetParams params , CalendarDate runDate ) { CoordAxisHelper helper = new CoordAxisHelper ( this ) ; CoverageCoordAxisBuilder builder = null ; if ( params . isTrue ( SubsetParams . timePresent ) ) { double offset = getOffsetInTimeUnits ( runDate , CalendarDate . present ( ) ) ; builder = helper . subsetClosest ( offset ) ; } CalendarDate dateWanted = ( CalendarDate ) params . get ( SubsetParams . time ) ; if ( dateWanted != null ) { // convertFrom, convertTo double offset = getOffsetInTimeUnits ( runDate , dateWanted ) ; builder = helper . subsetClosest ( offset ) ; } Integer stride = ( Integer ) params . get ( SubsetParams . timeStride ) ; if ( stride == null || stride < 0 ) stride = 1 ; CalendarDateRange dateRange = ( CalendarDateRange ) params . get ( SubsetParams . timeRange ) ; if ( dateRange != null ) { double min = getOffsetInTimeUnits ( runDate , dateRange . getStart ( ) ) ; double max = getOffsetInTimeUnits ( runDate , dateRange . getEnd ( ) ) ; Optional < CoverageCoordAxisBuilder > buildero = helper . subset ( min , max , stride ) ; if ( buildero . isPresent ( ) ) builder = buildero . get ( ) ; else return Optional . empty ( buildero . getErrorMessage ( ) ) ; } assert ( builder != null ) ; // all the offsets are reletive to rundate builder . setReferenceDate ( runDate ) ; return Optional . of ( new TimeOffsetAxis ( builder ) ) ; }


Input: Register an IOServiceProvider using its class string name . [CODESPLIT] static public void registerIOProvider ( String className ) throws IllegalAccessException , InstantiationException , ClassNotFoundException { Class ioClass = NetcdfFile . class . getClassLoader ( ) . loadClass ( className ) ; registerIOProvider ( ioClass ) ; }


Input: Register an IOServiceProvider . A new instance will be created when one of its files is opened . [CODESPLIT] static public void registerIOProvider ( Class iospClass , boolean last ) throws IllegalAccessException , InstantiationException { IOServiceProvider spi ; spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; // fail fast if ( userLoads && ! last ) registeredProviders . add ( 0 , spi ) ; // put user stuff first else registeredProviders . add ( spi ) ; }


Input: Register an IOServiceProvider . A new instance will be created when one of its files is opened . This differs from the above in that it specifically locates the target iosp and inserts the new one in front of it in order to override the target . If the iospclass is already registered remove it and reinsert . If the target class is not present then insert at front of the registry [CODESPLIT] static public void registerIOProviderPreferred ( Class iospClass , Class target ) throws IllegalAccessException , InstantiationException { iospDeRegister ( iospClass ) ; // forcibly de-register int pos = - 1 ; for ( int i = 0 ; i < registeredProviders . size ( ) ; i ++ ) { IOServiceProvider candidate = registeredProviders . get ( i ) ; if ( candidate . getClass ( ) == target ) { if ( pos < i ) pos = i ; break ; // this is where is must be placed } } if ( pos < 0 ) pos = 0 ; IOServiceProvider spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; // fail fast registeredProviders . add ( pos , spi ) ; // insert before target }


Input: See if a specific IOServiceProvider is registered [CODESPLIT] static public boolean iospRegistered ( Class iospClass ) { for ( IOServiceProvider spi : registeredProviders ) { if ( spi . getClass ( ) == iospClass ) return true ; } return false ; }


Input: See if a specific IOServiceProvider is registered and if so remove it . [CODESPLIT] 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 ; }


Input: debugging [CODESPLIT] static public void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugSPI = debugFlag . isSet ( "NetcdfFile/debugSPI" ) ; debugCompress = debugFlag . isSet ( "NetcdfFile/debugCompress" ) ; debugStructureIterator = debugFlag . isSet ( "NetcdfFile/structureIterator" ) ; N3header . disallowFileTruncation = debugFlag . isSet ( "NetcdfFile/disallowFileTruncation" ) ; N3header . debugHeaderSize = debugFlag . isSet ( "NetcdfFile/debugHeaderSize" ) ; showRequest = debugFlag . isSet ( "NetcdfFile/showRequest" ) ; }


Input: Open an existing file ( read only ) with option of cancelling . [CODESPLIT] static public NetcdfFile open ( String location , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { return open ( location , - 1 , cancelTask ) ; }


Input: Open an existing file ( read only ) with option of cancelling setting the RandomAccessFile buffer size for efficiency with an optional special object for the iosp . [CODESPLIT] static public NetcdfFile open ( String location , int buffer_size , ucar . nc2 . util . CancelTask cancelTask , Object iospMessage ) throws IOException { ucar . unidata . io . RandomAccessFile raf = getRaf ( location , buffer_size ) ; try { return open ( raf , location , cancelTask , iospMessage ) ; } catch ( Throwable t ) { raf . close ( ) ; throw new IOException ( t ) ; } }


Input: Find out if the file can be opened but dont actually open it . Experimental . [CODESPLIT] 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 ( ) ; } }


Input: Open an existing file ( read only ) specifying which IOSP is to be used . [CODESPLIT] static public NetcdfFile open ( String location , String iospClassName , int bufferSize , CancelTask cancelTask , Object iospMessage ) throws ClassNotFoundException , IllegalAccessException , InstantiationException , IOException { Class iospClass = NetcdfFile . class . getClassLoader ( ) . loadClass ( iospClassName ) ; IOServiceProvider spi = ( IOServiceProvider ) iospClass . newInstance ( ) ; // fail fast // send before iosp is opened if ( iospMessage != null ) spi . sendIospMessage ( iospMessage ) ; if ( bufferSize <= 0 ) bufferSize = default_buffersize ; ucar . unidata . io . RandomAccessFile raf = ucar . unidata . io . RandomAccessFile . acquire ( canonicalizeUriString ( location ) , bufferSize ) ; NetcdfFile result = new NetcdfFile ( spi , raf , location , cancelTask ) ; // send after iosp is opened if ( iospMessage != null ) spi . sendIospMessage ( iospMessage ) ; return result ; }


Input: Removes the { @code file : } or { @code file : // } prefix from the location if necessary . Also replaces back slashes with forward slashes . [CODESPLIT] public static String canonicalizeUriString ( String location ) { // get rid of file prefix, if any String uriString = location . trim ( ) ; if ( uriString . startsWith ( "file://" ) ) uriString = uriString . substring ( 7 ) ; else if ( uriString . startsWith ( "file:" ) ) uriString = uriString . substring ( 5 ) ; // get rid of crappy microsnot \ replace with happy / return StringUtil2 . replace ( uriString , ' ' , "/" ) ; }


Input: Open an in - memory netcdf file with a specific iosp . [CODESPLIT] 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 ) ; }


Input: Open an in - memory netcdf file . [CODESPLIT] 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 ) ; }


Input: Read a local CDM file into memory . All reads are then done from memory . [CODESPLIT] 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 ( ) ) ; }


Input: Read a remote CDM file into memory . All reads are then done from memory . [CODESPLIT] public static NetcdfFile openInMemory ( URI uri ) throws IOException { URL url = uri . toURL ( ) ; byte [ ] contents = IO . readContentsToByteArray ( url . openStream ( ) ) ; return openInMemory ( uri . toString ( ) , contents ) ; }


Input: Close all resources ( files sockets etc ) associated with this file . If the underlying file was acquired it will be released otherwise closed . if isClosed () already nothing will happen [CODESPLIT] public synchronized void close ( ) throws java . io . IOException { if ( cache != null ) { if ( cache . release ( this ) ) return ; } try { if ( null != spi ) { // log.warn("NetcdfFile.close called for ncfile="+this.hashCode()+" for iosp="+spi.hashCode()); spi . close ( ) ; } } finally { spi = null ; } }


Input: Find a Group with the specified ( full ) name . An embedded / is interpreted as separating group names . [CODESPLIT] public Group findGroup ( String fullName ) { if ( fullName == null || fullName . length ( ) == 0 ) return rootGroup ; Group g = rootGroup ; StringTokenizer stoke = new StringTokenizer ( fullName , "/" ) ; while ( stoke . hasMoreTokens ( ) ) { String groupName = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; g = g . findGroup ( groupName ) ; if ( g == null ) return null ; } return g ; }


Input: Find a Variable with the specified ( escaped full ) name . It may possibly be nested in multiple groups and / or structures . An embedded . is interpreted as structure . member . An embedded / is interpreted as group / variable . If the name actually has a . you must escape it ( call NetcdfFile . escapeName ( varname )) Any other chars may also be escaped as they are removed before testing . [CODESPLIT] public Variable findVariable ( String fullNameEscaped ) { if ( fullNameEscaped == null || fullNameEscaped . isEmpty ( ) ) { return null ; } Group g = rootGroup ; String vars = fullNameEscaped ; // break into group/group and var.var int pos = fullNameEscaped . lastIndexOf ( ' ' ) ; if ( pos >= 0 ) { String groups = fullNameEscaped . substring ( 0 , pos ) ; vars = fullNameEscaped . substring ( pos + 1 ) ; StringTokenizer stoke = new StringTokenizer ( groups , "/" ) ; while ( stoke . hasMoreTokens ( ) ) { String token = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; g = g . findGroup ( token ) ; if ( g == null ) return null ; } } // heres var.var - tokenize respecting the possible escaped '.' List < String > snames = EscapeStrings . tokenizeEscapedName ( vars ) ; if ( snames . size ( ) == 0 ) return null ; String varShortName = NetcdfFile . makeNameUnescaped ( snames . get ( 0 ) ) ; Variable v = g . findVariable ( varShortName ) ; if ( v == null ) return null ; int memberCount = 1 ; while ( memberCount < snames . size ( ) ) { if ( ! ( v instanceof Structure ) ) return null ; String name = NetcdfFile . makeNameUnescaped ( snames . get ( memberCount ++ ) ) ; v = ( ( Structure ) v ) . findVariable ( name ) ; if ( v == null ) return null ; } return v ; }


Input: Finds a Dimension with the specified full name . It may be nested in multiple groups . An embedded / is interpreted as a group separator . A leading slash indicates the root group . That slash may be omitted but the { @code fullName } will be treated as if it were there . In other words the first name token in { @code fullName } is treated as the short name of a Group or Dimension relative to the root group . [CODESPLIT] public Dimension findDimension ( String fullName ) { if ( fullName == null || fullName . isEmpty ( ) ) { return null ; } Group group = rootGroup ; String dimShortName = fullName ; // break into group/group and dim int pos = fullName . lastIndexOf ( ' ' ) ; if ( pos >= 0 ) { String groups = fullName . substring ( 0 , pos ) ; dimShortName = fullName . substring ( pos + 1 ) ; StringTokenizer stoke = new StringTokenizer ( groups , "/" ) ; while ( stoke . hasMoreTokens ( ) ) { String token = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; group = group . findGroup ( token ) ; if ( group == null ) { return null ; } } } return group . findDimensionLocal ( dimShortName ) ; }


Input: Look up global Attribute by ( full ) name . [CODESPLIT] public Attribute findGlobalAttribute ( String name ) { for ( Attribute a : gattributes ) { if ( name . equals ( a . getShortName ( ) ) ) return a ; } return null ; }


Input: Look up global Attribute by name ignore case . [CODESPLIT] public Attribute findGlobalAttributeIgnoreCase ( String name ) { for ( Attribute a : gattributes ) { if ( name . equalsIgnoreCase ( a . getShortName ( ) ) ) return a ; } return null ; }


Input: Find an attribute with the specified ( escaped full ) name . It may possibly be nested in multiple groups and / or structures . An embedded . is interpreted as structure . member . An embedded / is interpreted as group / group or group / variable . An embedded @ is interpreted as variable@attribute If the name actually has a . you must escape it ( call NetcdfFile . escapeName ( varname )) Any other chars may also be escaped as they are removed before testing . [CODESPLIT] public Attribute findAttribute ( String fullNameEscaped ) { if ( fullNameEscaped == null || fullNameEscaped . length ( ) == 0 ) { return null ; } int posAtt = fullNameEscaped . indexOf ( ' ' ) ; if ( posAtt < 0 || posAtt >= fullNameEscaped . length ( ) - 1 ) return null ; if ( posAtt == 0 ) { return findGlobalAttribute ( fullNameEscaped . substring ( 1 ) ) ; } String path = fullNameEscaped . substring ( 0 , posAtt ) ; String attName = fullNameEscaped . substring ( posAtt + 1 ) ; // find the group Group g = rootGroup ; int pos = path . lastIndexOf ( ' ' ) ; String varName = ( pos > 0 && pos < path . length ( ) - 1 ) ? path . substring ( pos + 1 ) : null ; if ( pos >= 0 ) { String groups = path . substring ( 0 , pos ) ; StringTokenizer stoke = new StringTokenizer ( groups , "/" ) ; while ( stoke . hasMoreTokens ( ) ) { String token = NetcdfFile . makeNameUnescaped ( stoke . nextToken ( ) ) ; g = g . findGroup ( token ) ; if ( g == null ) return null ; } } if ( varName == null ) // group attribute return g . findAttribute ( attName ) ; // heres var.var - tokenize respecting the possible escaped '.' List < String > snames = EscapeStrings . tokenizeEscapedName ( varName ) ; if ( snames . size ( ) == 0 ) return null ; String varShortName = NetcdfFile . makeNameUnescaped ( snames . get ( 0 ) ) ; Variable v = g . findVariable ( varShortName ) ; if ( v == null ) return null ; int memberCount = 1 ; while ( memberCount < snames . size ( ) ) { if ( ! ( v instanceof Structure ) ) return null ; String name = NetcdfFile . makeNameUnescaped ( snames . get ( memberCount ++ ) ) ; v = ( ( Structure ) v ) . findVariable ( name ) ; if ( v == null ) return null ; } return v . findAttribute ( attName ) ; }


Input: Find a String - valued global or variable Attribute by Attribute name ( ignore case ) return the Value of the Attribute . If not found return defaultValue [CODESPLIT] public String findAttValueIgnoreCase ( Variable v , String attName , String defaultValue ) { String attValue = null ; Attribute att ; if ( v == null ) att = rootGroup . findAttributeIgnoreCase ( attName ) ; else att = v . findAttributeIgnoreCase ( attName ) ; if ( ( att != null ) && att . isString ( ) ) attValue = att . getStringValue ( ) ; if ( null == attValue ) // not found, use default attValue = defaultValue ; return attValue ; }


Input: CDL representation of Netcdf header info non strict [CODESPLIT] 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 ) ; }


Input: Write CDL representation to OutputStream . [CODESPLIT] public void writeCDL ( OutputStream out , boolean strict ) { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( out , CDM . utf8Charset ) ) ; toStringStart ( pw , strict ) ; toStringEnd ( pw ) ; pw . flush ( ) ; }


Input: Write CDL representation to PrintWriter . [CODESPLIT] public void writeCDL ( PrintWriter pw , boolean strict ) { toStringStart ( pw , strict ) ; toStringEnd ( pw ) ; pw . flush ( ) ; }


Input: the actual work is here [CODESPLIT] protected void writeCDL ( Formatter f , Indent indent , boolean strict ) { toStringStart ( f , indent , strict ) ; f . format ( "%s}%n" , indent ) ; }


Input: Write the NcML representation : dont show coodinate values [CODESPLIT] public void writeNcML ( java . io . OutputStream os , String uri ) throws IOException { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; Element netcdfElem = ncmlWriter . makeNetcdfElement ( this , uri ) ; ncmlWriter . writeToStream ( netcdfElem , os ) ; }


Input: Write the NcML representation : dont show coodinate values [CODESPLIT] public void writeNcML ( java . io . Writer writer , String uri ) throws IOException { NcMLWriter ncmlWriter = new NcMLWriter ( ) ; Element netcdfElem = ncmlWriter . makeNetcdfElement ( this , uri ) ; ncmlWriter . writeToWriter ( netcdfElem , writer ) ; }


Input: / * Check if file has changed and reread metadata if needed . All previous object references ( variables dimensions etc ) may become invalid - you must re - obtain . DO NOT USE THIS ROUTINE YET - NOT FULLY TESTED [CODESPLIT] @ Override public long getLastModified ( ) { if ( spi != null && spi instanceof AbstractIOServiceProvider ) { AbstractIOServiceProvider aspi = ( AbstractIOServiceProvider ) spi ; return aspi . getLastModified ( ) ; } return 0 ; }


Input: Add an attribute to a group . [CODESPLIT] public Attribute addAttribute ( Group parent , Attribute att ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; if ( parent == null ) parent = rootGroup ; parent . addAttribute ( att ) ; return att ; }


Input: Add optional String attribute to a group . [CODESPLIT] 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 ; }


Input: Add a group to the parent group . [CODESPLIT] public Group addGroup ( Group parent , Group g ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; if ( parent == null ) parent = rootGroup ; parent . addGroup ( g ) ; return g ; }


Input: Add a shared Dimension to a Group . [CODESPLIT] public Dimension addDimension ( Group parent , Dimension d ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; if ( parent == null ) parent = rootGroup ; parent . addDimension ( d ) ; return d ; }


Input: Remove a shared Dimension from a Group by name . [CODESPLIT] public boolean removeDimension ( Group g , String dimName ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; if ( g == null ) g = rootGroup ; return g . removeDimension ( dimName ) ; }


Input: Add a Variable to the given group . [CODESPLIT] 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 ; }


Input: Create a new Variable and add to the given group . [CODESPLIT] 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 ; }


Input: Create a new Variable of type Datatype . CHAR and add to the given group . [CODESPLIT] 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 ; }


Input: Remove a Variable from the given group by name . [CODESPLIT] public boolean removeVariable ( Group g , String varName ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; if ( g == null ) g = rootGroup ; return g . removeVariable ( varName ) ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Make this immutable . [CODESPLIT] public NetcdfFile setImmutable ( ) { if ( immutable ) return this ; immutable = true ; setImmutable ( rootGroup ) ; variables = Collections . unmodifiableList ( variables ) ; dimensions = Collections . unmodifiableList ( dimensions ) ; gattributes = Collections . unmodifiableList ( gattributes ) ; return this ; }


Input: Completely empty the objects in the netcdf file . Used for rereading the file on a sync () . [CODESPLIT] public void empty ( ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; variables = new ArrayList <> ( ) ; gattributes = new ArrayList <> ( ) ; dimensions = new ArrayList <> ( ) ; rootGroup = makeRootGroup ( ) ; // addedRecordStructure = false; }


Input: Finish constructing the object model . This construsts the global variables attributes and dimensions . It also looks for coordinate variables . [CODESPLIT] public void finish ( ) { if ( immutable ) throw new IllegalStateException ( "Cant modify" ) ; variables = new ArrayList <> ( ) ; dimensions = new ArrayList <> ( ) ; gattributes = new ArrayList <> ( ) ; finishGroup ( rootGroup ) ; }


Input:
/ * Do not call this directly use Variable . read () !! Ranges must be filled ( no nulls ) [CODESPLIT] protected Array readData ( ucar . nc2 . Variable v , Section ranges ) throws IOException , InvalidRangeException { long start = 0 ; if ( showRequest ) { log . info ( "Data request for variable: {} section {}..." , v . getFullName ( ) , ranges ) ; start = System . currentTimeMillis ( ) ; } /* if (unlocked) {
      String info = cache.getInfo(this);
      throw new IllegalStateException("File is unlocked - cannot use\n" + info);
    } */ if ( spi == null ) { throw new IOException ( "spi is null, perhaps file has been closed. Trying to read variable " + v . getFullName ( ) ) ; } Array result = spi . readData ( v , ranges ) ; if ( showRequest ) { long took = System . currentTimeMillis ( ) - start ; log . info ( " ...took= {} msecs" , took ) ; } return result ; }


Input:
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 . [CODESPLIT] 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 ) ; }


Input: Read data from a top level Variable and send data to a WritableByteChannel . Experimental . [CODESPLIT] 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 ) ; }


Input: 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 . [CODESPLIT] 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 ; }


Input: Read a variable using the given section specification . [CODESPLIT] 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 ) ; }


Input:
debugging - do not use [CODESPLIT] public static void main ( String [ ] arg ) throws Exception { //NetcdfFile.registerIOProvider( ucar.nc2.grib.GribServiceProvider.class); int wide = 20 ; Formatter f = new Formatter ( System . out ) ; f . format ( " %" + wide + "s %n" , "test" ) ; f . format ( " %20s %n" , "asiuasdipuasiud" ) ; /*
    try {
      String filename = "R:/testdata2/hdf5/npoess/ExampleFiles/AVAFO_NPP_d2003125_t10109_e101038_b9_c2005829155458_devl_Tst.h5";
      NetcdfFile ncfile = NetcdfFile.open(filename);
      //Thread.currentThread().sleep( 60 * 60 * 1000); // pause to examine in profiler

      ncfile.close();

    } catch (Exception e) {
      e.printStackTrace();
    }            */ }


Input: Create a valid CDM object name . Control chars ( < 0x20 ) are not allowed . Trailing and leading blanks are not allowed and are stripped off . A space is converted into an underscore _ . A forward slash / is converted into an underscore _ . [CODESPLIT] static public String makeValidCdmObjectName ( String shortName ) { if ( shortName == null ) return null ; return StringUtil2 . makeValidCdmObjectName ( shortName ) ; }


Input: Given a CDMNode create its full name with appropriate backslash escaping of the specified characters . [CODESPLIT] 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 ( ) ; }


Input: Create a synthetic full name from a group plus a string [CODESPLIT] 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 ( ) ; }


Input: inclusion is an OR [CODESPLIT] private boolean include ( MFile mfile ) { if ( includeFilters == null ) return true ; for ( MFileFilter filter : includeFilters ) { if ( filter . accept ( mfile ) ) return true ; } return false ; }


Input: exclusion is an AND [CODESPLIT] private boolean exclude ( MFile mfile ) { if ( excludeFilters == null ) return false ; for ( MFileFilter filter : excludeFilters ) { if ( filter . accept ( mfile ) ) return true ; } return false ; }


Input: all AND filters must be satisfied [CODESPLIT] private boolean andFilter ( MFile mfile ) { if ( andFilters == null ) return true ; for ( MFileFilter filter : andFilters ) { if ( ! filter . accept ( mfile ) ) return false ; } return true ; }


Input: Accessors [CODESPLIT] public DAP_T get ( CDM_T cdm ) { cdm = ( CDM_T ) CDMNode . unwrap ( cdm ) ; int lh = cdm . localhash ( ) ; return dapmap . get ( lh ) ; }


Input: Given a CDM_T < - > DAP_T pair insert into the maps [CODESPLIT] public void put ( CDM_T cdm , DAP_T dap ) { assert ( dap != null && cdm != null ) ; cdm = ( CDM_T ) CDMNode . unwrap ( cdm ) ; int lh = cdm . localhash ( ) ; dapmap . put ( lh , dap ) ; cdmmap . put ( dap , cdm ) ; }


Input: Given a DAP_T < - > CDM_T pair remove from the maps [CODESPLIT] public void remove ( CDM_T cdm , DAP_T dap ) { assert ( dap != null && cdm != null ) ; cdm = ( CDM_T ) CDMNode . unwrap ( cdm ) ; dapmap . remove ( cdm . localhash ( ) ) ; cdmmap . remove ( dap ) ; }


Input: Returns the attribute type as a <code > String< / code > . [CODESPLIT] public final String getTypeString ( ) { switch ( type ) { case CONTAINER : return "Container" ; case ALIAS : return "Alias" ; case BYTE : return "Byte" ; case INT16 : return "Int16" ; case UINT16 : return "UInt16" ; case INT32 : return "Int32" ; case UINT32 : return "UInt32" ; case FLOAT32 : return "Float32" ; case FLOAT64 : return "Float64" ; case STRING : return "String" ; case URL : return "Url" ; //    case BOOLEAN: return "Boolean"; default : return "" ; } }


Input: Returns the attribute type as a <code > String< / code > . [CODESPLIT] public static final int getTypeVal ( String s ) { if ( s . equalsIgnoreCase ( "Container" ) ) return CONTAINER ; else if ( s . equalsIgnoreCase ( "Byte" ) ) return BYTE ; else if ( s . equalsIgnoreCase ( "Int16" ) ) return INT16 ; else if ( s . equalsIgnoreCase ( "UInt16" ) ) return UINT16 ; else if ( s . equalsIgnoreCase ( "Int32" ) ) return INT32 ; else if ( s . equalsIgnoreCase ( "UInt32" ) ) return UINT32 ; else if ( s . equalsIgnoreCase ( "Float32" ) ) return FLOAT32 ; else if ( s . equalsIgnoreCase ( "Float64" ) ) return FLOAT64 ; else if ( s . equalsIgnoreCase ( "String" ) ) return STRING ; else if ( s . equalsIgnoreCase ( "URL" ) ) return URL ; else return UNKNOWN ; }


Input: Returns the attribute value at <code > index< / code > . [CODESPLIT] public String getValueAt ( int index ) throws NoSuchAttributeException { checkVectorUsage ( ) ; return ( String ) ( ( Vector ) attr ) . elementAt ( index ) ; }


Input: Returns the attribute value at <code > index< / code > . [CODESPLIT] public String getValueAtN ( int index ) { if ( ! ( attr instanceof Vector ) ) return null ; return ( String ) ( ( Vector ) attr ) . elementAt ( index ) ; }


Input: Append a value to this attribute . [CODESPLIT] public void appendValue ( String value , boolean check ) throws NoSuchAttributeException , AttributeBadValueException { checkVectorUsage ( ) ; if ( check ) value = forceValue ( type , value ) ; ( ( Vector ) attr ) . addElement ( value ) ; }


Input: Check if the value is legal for a given type . [CODESPLIT] 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. } }


Input: Check if the value is legal for a given type and try to convert to specified type . [CODESPLIT] 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 ; }


Input: Check if string is a valid Byte . [CODESPLIT] 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." ) ; } }


Input: Check if string is a valid Int16 . [CODESPLIT] 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 ; } }


Input: Check if string is a valid Int32 . [CODESPLIT] 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 ; } }


Input: Check if string is a valid UInt32 . [CODESPLIT] 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 > 0xFFFFFFFF L ) return false ; else return true ; } catch ( NumberFormatException e ) { return false ; } }


Input: Check if string is a valid Float32 . [CODESPLIT] 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 ; } }


Input: Check if string is a valid Float64 . [CODESPLIT] 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 ; } }


Input: Returns a clone of this <code > Attribute< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { Attribute a = ( Attribute ) super . cloneDAG ( map ) ; // assume type, is_alias, and aliased_to have been cloned already if ( type == CONTAINER ) a . attr = ( AttributeTable ) cloneDAG ( map , ( ( AttributeTable ) attr ) ) ; else a . attr = ( ( Vector ) attr ) . clone ( ) ; // ok, attr is a vector of strings return a ; }


Input:
Get the data type of an attribute . Make it unsigned if the variable is unsigned . [CODESPLIT] 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 ; }


Input: Returns a distinct integer for each of the { @link DataType#isNumeric () numeric } data types that can be used to ( roughly ) order them by the range of the DataType . { @code BYTE < UBYTE < SHORT < USHORT < INT < UINT < LONG < ULONG < FLOAT < DOUBLE } . { @code - 1 } will be returned for all non - numeric data types . [CODESPLIT] public static int rank ( DataType dataType ) { if ( dataType == null ) { return - 1 ; } switch ( dataType ) { case BYTE : return 0 ; case UBYTE : return 1 ; case SHORT : return 2 ; case USHORT : return 3 ; case INT : return 4 ; case UINT : return 5 ; case LONG : return 6 ; case ULONG : return 7 ; case FLOAT : return 8 ; case DOUBLE : return 9 ; default : return - 1 ; } }


Input: Returns the data type that is the largest among the arguments . Relative sizes of data types are determined via { @link #rank ( DataType ) } . [CODESPLIT] public static DataType largestOf ( DataType ... dataTypes ) { DataType widest = null ; for ( DataType dataType : dataTypes ) { if ( widest == null ) { widest = dataType ; } else if ( rank ( dataType ) > rank ( widest ) ) { widest = dataType ; } } return widest ; }


Input: Returns the smallest numeric data type that : <ol > <li > can hold a larger integer than { @code dataType } can< / li > <li > if integral has the same signedness as { @code dataType } < / li > < / ol > The relative sizes of data types are determined in a manner consistent with { @link #rank ( DataType ) } . <p / > <table border = 1 > <tr > <th > Argument< / th > <th > Result< / th > < / tr > <tr > <td > BYTE< / td > <td > SHORT< / td > < / tr > <tr > <td > UBYTE< / td > <td > USHORT< / td > < / tr > <tr > <td > SHORT< / td > <td > INT< / td > < / tr > <tr > <td > USHORT< / td > <td > UINT< / td > < / tr > <tr > <td > INT< / td > <td > LONG< / td > < / tr > <tr > <td > UINT< / td > <td > ULONG< / td > < / tr > <tr > <td > LONG< / td > <td > DOUBLE< / td > < / tr > <tr > <td > ULONG< / td > <td > DOUBLE< / td > < / tr > <tr > <td > Any other data type< / td > <td > Just return argument< / td > < / tr > < / table > <p / > The returned type is intended to be just big enough to hold the result of performing an unsigned conversion of a value of the smaller type . For example the { @code byte } value { @code - 106 } equals { @code 150 } when interpreted as unsigned . That won t fit in a ( signed ) { @code byte } but it will fit in a { @code short } . [CODESPLIT] public static DataType nextLarger ( DataType dataType ) { switch ( dataType ) { case BYTE : return SHORT ; case UBYTE : return USHORT ; case SHORT : return INT ; case USHORT : return UINT ; case INT : return LONG ; case UINT : return ULONG ; case LONG : return DOUBLE ; case ULONG : return DOUBLE ; default : return dataType ; } }


Input: Returns true if this is a gridded dataset that is accessible via WMS . [CODESPLIT] @ Override public boolean isViewable ( Dataset ds ) { Access access = ds . getAccess ( ServiceType . WMS ) ; return access != null && ( ThreddsConfig . getBoolean ( "WMS.allow" , false ) ) ; }


Input: Return true if the given String is a valid single - line String . <p > <p > A string will be considered a valid single - line string if it does not contain any characters from these Unicode general categories : <p > <ul > <li > Cc - Other Control< / li > <li > Cf - Other Format< / li > <li > Cs - Other Surrogate< / li > <li > Co - Other Private Use< / li > <li > Cn - Other Not Assigned< / li > <li > Zl - Separator Line< / li > <li > Zp - Separator Paragraph< / li > < / ul > <p > <p > Or in other words allow : Letters Numbers Marks Punctuation Symbols and Space separators . [CODESPLIT] public static boolean validSingleLineString ( String singleLineString ) { if ( singleLineString == null ) return false ; Matcher m = INVALID_CHARACTERS_FOR_SINGLE_LINE_STRING_PATTERN . matcher ( singleLineString ) ; return ! m . find ( ) ; }


Input: Return true if the given String is a valid path . <p > <p > A String is considered a valid path if : <ul > <li > when passed to validSingleLineString ( String ) true is returned and <li > it does not contain any parent path segments ( .. / ) . < / li > < / li > < / ul > [CODESPLIT] @ SuppressWarnings ( { "SimplifiableIfStatement" } ) public static boolean validPath ( String path ) { if ( path == null ) return false ; // Don't allow ".." directories in path. if ( path . indexOf ( "/../" ) != - 1 || path . equals ( ".." ) || path . startsWith ( "../" ) || path . endsWith ( "/.." ) ) return false ; return validSingleLineString ( path ) ; }


Input: Return true if the given String is a valid File path . <p > <p > A String is considered a valid File path if : <ul > <li > when passed to validPath ( String ) true is returned ; and< / li > <li > it does not contain the Java File path separator ( java . io . File . pathSeparatorChar ) which is system dependant . < / li > < / ul > [CODESPLIT] @ SuppressWarnings ( { "SimplifiableIfStatement" } ) public static boolean validFilePath ( String path ) { if ( path == null ) return false ; if ( path . indexOf ( File . pathSeparatorChar ) != - 1 ) return false ; return validPath ( path ) ; }


Input: Return true if the given String is a valid ID string . <p > <p > A String is considered a valid ID string if : <ul > <li > it contains no space separator characters ( Unicode general category Zs - Separator Space ) ; and< / li > <li > true is returned when the string is passed to validSingleLineString ( String ) . < / li > < / ul > [CODESPLIT] public static boolean validIdString ( String id ) { if ( id == null ) return false ; Matcher m = INVALID_CHARACTERS_FOR_ID_STRING_PATTERN . matcher ( id ) ; return ! ( m . find ( ) || ! validSingleLineString ( id ) ) ; }


Input: Return true if the given String contains any less than ( < ) or greater than ( > ) characters ; otherwise return false . [CODESPLIT] public static boolean containsAngleBracketCharacters ( String string ) { if ( string == null ) return false ; if ( string . indexOf ( "<" ) == - 1 && string . indexOf ( ">" ) == - 1 ) return false ; return true ; }


Input: Return true if the given String contains any ampersand ( & ) characters ; otherwise return false . [CODESPLIT] public static boolean containsAmpersandCharacters ( String string ) { if ( string == null ) return false ; if ( string . indexOf ( "&" ) == - 1 ) return false ; return true ; }


Input: Return true if the given String contains any backslash ( \ ) characters ; otherwise return false . [CODESPLIT] public static boolean containsBackslashCharacters ( String string ) { if ( string == null ) return false ; if ( string . indexOf ( "\\" ) == - 1 ) return false ; return true ; }


Input: Return true if the given String is true or false ignoring case . [CODESPLIT] @ 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" ) ; }


Input: Return true if the given String is an alphanumeric string . [CODESPLIT] public static boolean validAlphanumericString ( String alphNumString ) { if ( alphNumString == null ) return false ; Matcher m = VALID_CHARACTERS_FOR_ALPHANUMERIC_STRING_PATTERN . matcher ( alphNumString ) ; return m . matches ( ) ; }


Input: Return true if the given String is an alphanumeric string and one of the valid strings in the constrained set . [CODESPLIT] 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 ; }


Input: Return true if the given path does not ascend into parent directory . [CODESPLIT] @ 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 ; }


Input: Check that the given string is a valid percentHexOctets string . The string is considered valid if it only contains a sequence of % prefixed two character strings where each two character string is composed only of US - ASCII digits and upper - or lower - case A - F . <p > For example : %31%32 or %7b%7d%7E [CODESPLIT] public static boolean validPercentHexOctetsString ( String percentHexOctetsString ) { if ( percentHexOctetsString == null ) return false ; Matcher m = VALID_PERCENT_HEX_OCTETS_PATTERN . matcher ( percentHexOctetsString ) ; return m . matches ( ) ; }


Input: 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 . [CODESPLIT] 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 ( ) ; }


Input: adds a param and value . [CODESPLIT] public final void addParam ( String key , String value ) { //System.out.println(" adding " + key + " = " + value); paramStr . put ( key . trim ( ) , value ) ; paramsValues = paramsValues + "\t" + key + "\t" + value ; }