Input:
Write an Html representation of the given dataset .
 With datasetEvents catrefEvents = true this is used to construct an HTML page on the client ( eg using HtmlPage ) ; the client then detects URL clicks and processes .
 With datasetEvents catrefEvents = false this is used to construct an HTML page on the server . ( eg using HtmlPage ) ; the client then detects URL clicks and processes . [CODESPLIT] public void writeHtmlDescription ( Formatter out , Dataset ds , boolean complete , boolean isServer , boolean datasetEvents , boolean catrefEvents , boolean resolveRelativeUrls ) { if ( ds == null ) return ; if ( complete ) { out . format ( "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"%n" ) ; out . format ( "        \"http://www.w3.org/TR/html4/loose.dtd\">%n" ) ; out . format ( "%n" ) ; out . format ( "%n" ) ; out . format ( "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\">%n" ) ; out . format ( "%n" ) ; out . format ( "%n" ) ; } out . format ( "
Dataset: %s
%n
" , ds . getName ( ) ) ; if ( ds . getDataFormatName ( ) != null ) out . format ( "
Data format: %s
%n" , htmlEscaper . escape ( ds . getDataFormatName ( ) ) ) ; if ( ( ds . getDataSize ( ) > 0 ) ) out . format ( "
Data size: %s
%n" , Format . formatByteSize ( ds . getDataSize ( ) ) ) ; if ( ds . getFeatureTypeName ( ) != null ) out . format ( "
Feature type: %s
%n" , htmlEscaper . escape ( ds . getFeatureTypeName ( ) ) ) ; if ( ds . getCollectionType ( ) != null ) out . format ( "
Collection type: %s
%n" , htmlEscaper . escape ( ds . getCollectionType ( ) ) ) ; if ( ds . isHarvest ( ) ) out . format ( "
Harvest: true
%n" ) ; if ( ds . getAuthority ( ) != null ) out . format ( "
Naming Authority: %s
%n%n" , htmlEscaper . escape ( ds . getAuthority ( ) ) ) ; if ( ds . getId ( ) != null ) out . format ( "
ID: %s
%n" , htmlEscaper . escape ( ds . getId ( ) ) ) ; if ( ds . getRestrictAccess ( ) != null ) out . format ( "
RestrictAccess: %s
%n" , htmlEscaper . escape ( ds . getRestrictAccess ( ) ) ) ; if ( ds instanceof CatalogRef ) { CatalogRef catref = ( CatalogRef ) ds ; String href = resolveRelativeUrls | catrefEvents ? resolve ( ds , catref . getXlinkHref ( ) ) : catref . getXlinkHref ( ) ; if ( catrefEvents ) href = "catref:" + href ; out . format ( "
CatalogRef: %s
%n" , makeHref ( href , null , null ) ) ; } out . format ( "
%n" ) ; java . util . List < Documentation > docs = ds . getDocumentation ( ) ; if ( docs . size ( ) > 0 ) { out . format ( "
Documentation:
%n
%n" ) ; for ( Documentation doc : docs ) { String type = ( doc . getType ( ) == null ) ? "" : "" + htmlEscaper . escape ( doc . getType ( ) ) + ": " ; String inline = doc . getInlineContent ( ) ; if ( ( inline != null ) && ( inline . length ( ) > 0 ) ) out . format ( "
%s %s
%n" , type , htmlEscaper . escape ( inline ) ) ; if ( doc . hasXlink ( ) ) { out . format ( "
%s %s
%n" , type , makeHref ( doc . getXlinkHref ( ) , null , doc . getXlinkTitle ( ) ) ) ; } } out . format ( "
%n" ) ; } java . util . List < Access > access = ds . getAccess ( ) ; if ( access . size ( ) > 0 ) { out . format ( "
Access:
%n
%n" ) ; for ( Access a : access ) { Service s = a . getService ( ) ; String urlString = resolveRelativeUrls || datasetEvents ? a . getStandardUrlName ( ) : a . getUnresolvedUrlName ( ) ; String queryString = null ; // String fullUrlString = urlString; if ( datasetEvents ) urlString = "dataset:" + urlString ; ServiceType stype = s . getType ( ) ; if ( isServer && stype != null ) switch ( stype ) { case OPENDAP : case DODS : urlString = urlString + ".html" ; break ; case DAP4 : urlString = urlString + ".dmr.xml" ; break ; case WCS : queryString = "service=WCS&version=1.0.0&request=GetCapabilities" ; break ; case WMS : queryString = "service=WMS&version=1.3.0&request=GetCapabilities" ; break ; case NCML : case UDDC : case ISO : String catalogUrl = ds . getCatalogUrl ( ) ; String datasetId = ds . getId ( ) ; if ( catalogUrl != null && datasetId != null ) { if ( catalogUrl . indexOf ( ' ' ) > 0 ) catalogUrl = catalogUrl . substring ( 0 , catalogUrl . lastIndexOf ( ' ' ) ) ; /* try {
                  catalogUrl = URLEncoder.encode(catalogUrl, "UTF-8");
                  datasetId = URLEncoder.encode(datasetId, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
                } */ queryString = "catalog=" + urlParamEscaper . escape ( catalogUrl ) + "&dataset=" + urlParamEscaper . escape ( datasetId ) ; } break ; case NetcdfSubset : urlString = urlString + "/dataset.html" ; break ; case CdmRemote : queryString = "req=cdl" ; break ; case CdmrFeature : queryString = "req=form" ; } out . format ( "
 %s: %s
%n" , s . getServiceTypeName ( ) , makeHref ( urlString , queryString , null ) ) ; } out . format ( "
%n" ) ; } java . util . List < ThreddsMetadata . Contributor > contributors = ds . getContributors ( ) ; if ( contributors . size ( ) > 0 ) { out . format ( "
Contributors:
%n
%n" ) ; for ( ThreddsMetadata . Contributor t : contributors ) { String role = ( t . getRole ( ) == null ) ? "" : " (" + htmlEscaper . escape ( t . getRole ( ) ) + ") " ; out . format ( "
%s %s
%n" , htmlEscaper . escape ( t . getName ( ) ) , role ) ; } out . format ( "
%n" ) ; } java . util . List < ThreddsMetadata . Vocab > keywords = ds . getKeywords ( ) ; if ( keywords . size ( ) > 0 ) { out . format ( "
Keywords:
%n
%n" ) ; for ( ThreddsMetadata . Vocab t : keywords ) { String vocab = ( t . getVocabulary ( ) == null ) ? "" : " (" + htmlEscaper . escape ( t . getVocabulary ( ) ) + ") " ; out . format ( "
%s %s
%n" , htmlEscaper . escape ( t . getText ( ) ) , vocab ) ; } out . format ( "
%n" ) ; } java . util . List < DateType > dates = ds . getDates ( ) ; if ( dates . size ( ) > 0 ) { out . format ( "
Dates:
%n
%n" ) ; for ( DateType d : dates ) { String type = ( d . getType ( ) == null ) ? "" : " (" + htmlEscaper . escape ( d . getType ( ) ) + ") " ; out . format ( "
%s %s
%n" , htmlEscaper . escape ( d . getText ( ) ) , type ) ; } out . format ( "
%n" ) ; } java . util . List < ThreddsMetadata . Vocab > projects = ds . getProjects ( ) ; if ( projects . size ( ) > 0 ) { out . format ( "
Projects:
%n
%n" ) ; for ( ThreddsMetadata . Vocab t : projects ) { String vocab = ( t . getVocabulary ( ) == null ) ? "" : " (" + htmlEscaper . escape ( t . getVocabulary ( ) ) + ") " ; out . format ( "
%s %s
%n" , htmlEscaper . escape ( t . getText ( ) ) , vocab ) ; } out . format ( "
%n" ) ; } java . util . List < ThreddsMetadata . Source > creators = ds . getCreators ( ) ; if ( creators . size ( ) > 0 ) { out . format ( "
Creators:
%n
%n" ) ; for ( ThreddsMetadata . Source t : creators ) { out . format ( "
%s
%n" , htmlEscaper . escape ( t . getName ( ) ) ) ; out . format ( "
email: %s
%n" , htmlEscaper . escape ( t . getEmail ( ) ) ) ; if ( t . getUrl ( ) != null ) { String newUrl = resolveRelativeUrls ? makeHrefResolve ( ds , t . getUrl ( ) , null ) : makeHref ( t . getUrl ( ) , null , null ) ; out . format ( "
 %s
%n" , newUrl ) ; } out . format ( "

%n" ) ; } out . format ( "
%n" ) ; } java . util . List < ThreddsMetadata . Source > publishers = ds . getPublishers ( ) ; if ( publishers . size ( ) > 0 ) { out . format ( "
Publishers:
%n
%n" ) ; for ( ThreddsMetadata . Source t : publishers ) { out . format ( "
%s
%n" , htmlEscaper . escape ( t . getName ( ) ) ) ; out . format ( "
email: %s%n" , htmlEscaper . escape ( t . getEmail ( ) ) ) ; if ( t . getUrl ( ) != null ) { String urlLink = resolveRelativeUrls ? makeHrefResolve ( ds , t . getUrl ( ) , null ) : makeHref ( t . getUrl ( ) , null , null ) ; out . format ( "
 %s
%n" , urlLink ) ; } out . format ( "
%n" ) ; } out . format ( "
%n" ) ; } /*
     4.2:

Variables:

Vocabulary [DIF]:

Reflectivity =   = EARTH SCIENCE > Spectral/Engineering > Radar > Radar Reflectivity (db)

Velocity =   = EARTH SCIENCE > Spectral/Engineering > Radar > Doppler Velocity (m/s)

SpectrumWidth =   = EARTH SCIENCE > Spectral/Engineering > Radar > Doppler Spectrum Width (m/s)

     4.3:

Variables:

Vocabulary [CF-1.0]:

d3d (meters)  =  3D Depth at Nodes

         = depth_at_nodes

depth (meters)  =  Bathymetry = depth

eta (m)  =   =

temp (Celsius)  =  Temperature

         = sea_water_temperature

u (m/s)  =  Eastward Water

          Velocity

         = eastward_sea_water_velocity

v (m/s)  =  Northward Water

          Velocity

         = northward_sea_water_velocity

      */ java . util . List < ThreddsMetadata . VariableGroup > vars = ds . getVariables ( ) ; if ( vars . size ( ) > 0 ) { out . format ( "
Variables:
%n
%n" ) ; for ( ThreddsMetadata . VariableGroup t : vars ) { out . format ( "
Vocabulary [" ) ; if ( t . getVocabUri ( ) != null ) { ThreddsMetadata . UriResolved uri = t . getVocabUri ( ) ; String vocabLink = resolveRelativeUrls ? makeHref ( uri . resolved . toString ( ) , null , t . getVocabulary ( ) ) : makeHref ( uri . href , null , t . getVocabulary ( ) ) ; out . format ( vocabLink ) ; } else { out . format ( htmlEscaper . escape ( t . getVocabulary ( ) ) ) ; } out . format ( "]:%n
%n" ) ; java . util . List < ThreddsMetadata . Variable > vlist = t . getVariableList ( ) ; if ( vlist . size ( ) > 0 ) { for ( ThreddsMetadata . Variable v : vlist ) { String units = ( v . getUnits ( ) == null || v . getUnits ( ) . length ( ) == 0 ) ? "" : " (" + v . getUnits ( ) + ") " ; out . format ( "
%s = " , htmlEscaper . escape ( v . getName ( ) + units ) ) ; if ( v . getDescription ( ) != null ) out . format ( " %s = " , htmlEscaper . escape ( v . getDescription ( ) ) ) ; if ( v . getVocabularyName ( ) != null ) out . format ( "%s" , htmlEscaper . escape ( v . getVocabularyName ( ) ) ) ; out . format ( "%n" ) ; } } out . format ( "
%n" ) ; } out . format ( "
%n" ) ; } // LOOK what about VariableMapLink string ?? if ( ds . getVariableMapLink ( ) != null ) { out . format ( "
Variables:
%n" ) ; ThreddsMetadata . UriResolved uri = ds . getVariableMapLink ( ) ; out . format ( "

%s

%n" , makeHref ( uri . resolved . toASCIIString ( ) , null , "VariableMap" ) ) ; } ThreddsMetadata . GeospatialCoverage gc = ds . getGeospatialCoverage ( ) ; if ( gc != null ) { out . format ( "
GeospatialCoverage:
%n
%n" ) ; // if (gc.isGlobal()) out.format("
 Global %n"); out . format ( "
 Longitude:  %s
%n" , rangeString ( gc . getEastWestRange ( ) ) ) ; out . format ( "
 Latitude:  %s
%n" , rangeString ( gc . getNorthSouthRange ( ) ) ) ; if ( gc . getUpDownRange ( ) != null ) { out . format ( "
 Altitude:  %s (positive is %s)
%n" , rangeString ( gc . getUpDownRange ( ) ) , gc . getZPositive ( ) ) ; } java . util . List < ThreddsMetadata . Vocab > nlist = gc . getNames ( ) ; if ( ( nlist != null ) && ( nlist . size ( ) > 0 ) ) { out . format ( "
  Names:
%n" ) ; for ( ThreddsMetadata . Vocab elem : nlist ) { out . format ( "
%s
%n" , htmlEscaper . escape ( elem . getText ( ) ) ) ; } out . format ( "
%n" ) ; } out . format ( "
%n" ) ; } DateRange tc = ds . getTimeCoverage ( ) ; if ( tc != null ) { out . format ( "
TimeCoverage:
%n
%n" ) ; DateType start = tc . getStart ( ) ; if ( start != null ) out . format ( "
  Start:  %s
%n" , start . toString ( ) ) ; DateType end = tc . getEnd ( ) ; if ( end != null ) { out . format ( "
  End:  %s
%n" , end . toString ( ) ) ; } TimeDuration duration = tc . getDuration ( ) ; if ( duration != null ) out . format ( "
  Duration:  %s
%n" , htmlEscaper . escape ( duration . toString ( ) ) ) ; TimeDuration resolution = tc . getResolution ( ) ; if ( resolution != null ) { out . format ( "
  Resolution:  %s
%n" , htmlEscaper . escape ( resolution . toString ( ) ) ) ; } out . format ( "
%n" ) ; } java . util . List < ThreddsMetadata . MetadataOther > metadata = ds . getMetadataOther ( ) ; boolean gotSomeMetadata = false ; for ( ThreddsMetadata . MetadataOther m : metadata ) { if ( m . getXlinkHref ( ) != null ) gotSomeMetadata = true ; } if ( gotSomeMetadata ) { out . format ( "
Metadata:
%n
%n" ) ; for ( ThreddsMetadata . MetadataOther m : metadata ) { String type = ( m . getType ( ) == null ) ? "" : m . getType ( ) ; if ( m . getXlinkHref ( ) != null ) { String title = ( m . getTitle ( ) == null ) ? "Type " + type : m . getTitle ( ) ; String mdLink = resolveRelativeUrls ? makeHrefResolve ( ds , m . getXlinkHref ( ) , title ) : makeHref ( m . getXlinkHref ( ) , null , title ) ; out . format ( "
 %s
%n" , mdLink ) ; } //else { //out.format("

"+m.getMetadataType()+" "+m.getContentObject()+"
%n"); //} } out . format ( "
%n" ) ; } java . util . List < Property > propsOrg = ds . getProperties ( ) ; java . util . List < Property > props = new ArrayList <> ( ds . getProperties ( ) . size ( ) ) ; for ( Property p : propsOrg ) { if ( ! p . getName ( ) . startsWith ( "viewer" ) ) // eliminate the viewer properties from the html view props . add ( p ) ; } if ( props . size ( ) > 0 ) { out . format ( "
Properties:
%n
%n" ) ; for ( Property p : props ) { if ( p . getName ( ) . equals ( "attachments" ) ) { // LOOK whats this ? String attachLink = resolveRelativeUrls ? makeHrefResolve ( ds , p . getValue ( ) , p . getName ( ) ) : makeHref ( p . getValue ( ) , null , p . getName ( ) ) ; out . format ( "
%s
%n" , attachLink ) ; } else { out . format ( "
%s = \"%s\"
%n" , htmlEscaper . escape ( p . getName ( ) ) , htmlEscaper . escape ( p . getValue ( ) ) ) ; } } out . format ( "
%n" ) ; } if ( complete ) out . format ( "" ) ; }


Input: resolve reletive URLS against the catalog URL . [CODESPLIT] public String resolve ( Dataset ds , String href ) { Catalog cat = ds . getParentCatalog ( ) ; if ( cat != null ) { try { java . net . URI uri = cat . resolveUri ( href ) ; href = uri . toString ( ) ; } catch ( java . net . URISyntaxException e ) { return "DatasetHtmlWriter: error parsing URL= " + href ; } } return href ; }


Input: Parse the localConcept files needed to create grib1 tables for use by the CDM . [CODESPLIT] private void parseLocalConcept ( String filename , String conceptName ) throws IOException { try ( InputStream is = new FileInputStream ( filename ) ) { addLocalConcept ( is , conceptName ) ; } }


Input:
Add the information from a localConcept file to super HashMap localConcepts [CODESPLIT] private void addLocalConcept ( InputStream is , String conceptName ) throws IOException { /*
        example entry from name.def:

        #Total precipitation of at least 5 mm
        'Total precipitation of at least 5 mm' = {
             table2Version = 131 ;
             indicatorOfParameter = 61 ;
            }
         */ try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( is , ENCODING ) ) ) { String line = br . readLine ( ) ; while ( ! line . startsWith ( "#" ) ) line = br . readLine ( ) ; // skip while ( true ) { HashMap < String , String > items = new HashMap <> ( ) ; line = br . readLine ( ) ; if ( line == null ) break ; // done with the file if ( ( line . length ( ) == 0 ) || line . startsWith ( "#" ) ) continue ; line = cleanLine ( line ) ; if ( line . contains ( "{" ) ) { String paramName = line . split ( "=" ) [ 0 ] . trim ( ) ; line = br . readLine ( ) ; if ( line == null ) break ; // done with the file line = cleanLine ( line ) ; while ( line . contains ( "=" ) ) { String [ ] kvp = line . split ( "=" ) ; items . put ( kvp [ 0 ] . trim ( ) , kvp [ 1 ] . trim ( ) ) ; line = br . readLine ( ) ; if ( line == null ) break ; // done with the file line = cleanLine ( line ) ; } String tableVersion = items . get ( TABLE_VERSION_ID ) ; String parameterNumber = items . get ( PARAM_NUM_ID ) ; storeConcept ( tableVersion , parameterNumber , conceptName , paramName ) ; } } } }


Input: clean the string representation of a line in the localConcept file . Basic removal of tabs semicolons single quotes etc . [CODESPLIT] private String cleanLine ( String lineIn ) { String lineOut ; lineOut = lineIn . replaceAll ( "'" , "" ) ; lineOut = lineOut . replaceAll ( "\t" , "" ) ; lineOut = lineOut . replaceAll ( ";" , "" ) ; return lineOut . trim ( ) ; }


Input: Store localConcept information in super HashMap localConcepts [CODESPLIT] private void storeConcept ( String tableVersion , String parameterNumber , String key , String value ) { HashMap < String , HashMap < String , String > > tmpTable ; if ( localConcepts . containsKey ( tableVersion ) ) { tmpTable = localConcepts . get ( tableVersion ) ; if ( tmpTable . containsKey ( parameterNumber ) ) { HashMap < String , String > tmpParam = tmpTable . get ( parameterNumber ) ; if ( ! tmpParam . containsKey ( key ) ) { tmpParam . put ( key , value ) ; } else { System . out . println ( "already has key value pair: " + key + ":" + value ) ; } } else { HashMap < String , String > tmpParam = new HashMap <> ( 4 ) ; tmpParam . put ( key , value ) ; tmpTable . put ( parameterNumber , tmpParam ) ; } } else { tmpTable = new HashMap <> ( ) ; HashMap < String , String > tmpParam = new HashMap <> ( 4 ) ; tmpParam . put ( key , value ) ; tmpTable . put ( parameterNumber , tmpParam ) ; } localConcepts . put ( tableVersion , tmpTable ) ; }


Input: Write out grib1 tables based on localConcepts files - these are the tables that the CDM will read . [CODESPLIT] private void writeGrib1Tables ( ) throws IOException { SimpleDateFormat dateFormat = new SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ssz" ) ; Calendar cal = Calendar . getInstance ( ) ; String writeDate = dateFormat . format ( cal . getTime ( ) ) ; String grib1Info ; List < String > tableNums = new ArrayList <> ( ) ; HashMap < String , String > paramInfo ; Path dir = Paths . get ( ecmwfLocalConceptsLoc . replace ( "sources/" , "resources/resources/grib1/" ) ) ; for ( String tableNum : localConcepts . keySet ( ) ) { tableNums . add ( tableNum ) ; String fileName = "2.98." + tableNum + ".table" ; System . out . println ( "Writing: " + fileName ) ; Path newFile = dir . resolve ( fileName ) ; Files . deleteIfExists ( newFile ) ; Files . createFile ( newFile ) ; try ( BufferedWriter writer = Files . newBufferedWriter ( newFile , ENCODING ) ) { writer . write ( "# Generated by " + this . getClass ( ) . getCanonicalName ( ) + " on " + writeDate ) ; writer . newLine ( ) ; for ( String paramNum : localConcepts . get ( tableNum ) . keySet ( ) ) { paramInfo = localConcepts . get ( tableNum ) . get ( paramNum ) ; String shortName = paramInfo . get ( SHORTNAME_ID ) ; String description = paramInfo . get ( DESCRIPTION_ID ) ; String units = paramInfo . get ( UNIT_ID ) ; grib1Info = paramNum + " " + shortName + " [" + description + "] (" + units + ")" ; writer . write ( grib1Info ) ; writer . newLine ( ) ; } } } writeLookupTableFile ( tableNums , dir , writeDate ) ; }


Input: Write the lookupTables . txt file which basically registers all of the new grib1 tables with the CDM [CODESPLIT] private void writeLookupTableFile ( List < String > tableNums , Path dir , String writeDate ) throws IOException { System . out . println ( "Writing: lookupTables.txt" ) ; Collections . sort ( tableNums ) ; Path lookupTableReg = dir . resolve ( "lookupTables.txt" ) ; Files . deleteIfExists ( lookupTableReg ) ; Files . createFile ( lookupTableReg ) ; try ( BufferedWriter writer = Files . newBufferedWriter ( lookupTableReg , ENCODING ) ) { writer . write ( "# Generated by " + this . getClass ( ) . getCanonicalName ( ) + " on " + writeDate ) ; writer . newLine ( ) ; for ( String tn : tableNums ) { String tableName = "2.98." + tn + ".table" ; String reg = "98:\t-1:\t" + tn + ":\t" + tableName ; writer . write ( reg ) ; writer . newLine ( ) ; } } }


Input: Quick prinout to System . out of the different parameter metadata fields [CODESPLIT] private void showLocalConcepts ( ) { for ( String tableNum : localConcepts . keySet ( ) ) { for ( String paramNum : localConcepts . get ( tableNum ) . keySet ( ) ) { for ( String key : localConcepts . get ( tableNum ) . get ( paramNum ) . keySet ( ) ) { System . out . println ( key + ":" + localConcepts . get ( tableNum ) . get ( paramNum ) . get ( key ) ) ; } } } }


Input: Generate grib1 tables for the CDM based on the localConcept files from ECMWF GRIB - API [CODESPLIT] public static void main ( String [ ] args ) { EcmwfLocalConcepts ec = new EcmwfLocalConcepts ( ) ; try { ec . writeGrib1Tables ( ) ; System . out . println ( "Finished!" ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }


Input: //////////////////////////////////////////////////// Static ////////////////////////////////////////////////////// [CODESPLIT] public void respond ( HttpServletResponse res , FeatureDataset ft , String requestPathInfo , SubsetParams queryParams , SupportedFormat format ) throws Exception { write ( ) ; }


Input: TODO : This needs testing . [CODESPLIT] public static List < VariableSimpleIF > getWantedVariables ( FeatureDatasetPoint fdPoint , SubsetParams ncssParams ) throws VariableNotContainedInDatasetException { List < String > vars = ncssParams . getVariables ( ) ; if ( vars . size ( ) == 1 && vars . get ( 0 ) . equals ( "all" ) ) { return fdPoint . getDataVariables ( ) ; // Return all variables. } // restrict to these variables Map < String , VariableSimpleIF > dataVarsMap = new HashMap <> ( ) ; for ( VariableSimpleIF dataVar : fdPoint . getDataVariables ( ) ) { dataVarsMap . put ( dataVar . getShortName ( ) , dataVar ) ; } List < String > allVarNames = new ArrayList <> ( dataVarsMap . keySet ( ) ) ; List < VariableSimpleIF > wantedVars = new ArrayList <> ( ) ; for ( String varName : vars ) { if ( allVarNames . contains ( varName ) ) { VariableSimpleIF var = dataVarsMap . get ( varName ) ; wantedVars . add ( var ) ; } else { throw new VariableNotContainedInDatasetException ( "Variable: " + varName + " is not contained in the requested dataset" ) ; } } return wantedVars ; }


Input: TODO : This needs testing . [CODESPLIT] public static CalendarDateRange getWantedDateRange ( SubsetParams ncssParams ) throws NcssException { if ( ncssParams . isTrue ( SubsetParams . timePresent ) ) { // present CalendarDate time = CalendarDate . present ( ) ; CalendarPeriod timeWindow = ncssParams . getTimeWindow ( ) ; if ( timeWindow == null ) timeWindow = CalendarPeriod . Hour ; return CalendarDateRange . of ( time . subtract ( timeWindow ) , time . add ( timeWindow ) ) ; } else if ( ncssParams . getTime ( ) != null ) { // Means we want just one single time. CalendarDate time = ncssParams . getTime ( ) ; CalendarPeriod timeWindow = ncssParams . getTimeWindow ( ) ; if ( timeWindow == null ) timeWindow = CalendarPeriod . Hour ; // To prevent features from being too agressively excluded, we are accepting times that are within // an hour of the specified time. // LOOK: Do we really need the +- increment? //CalendarDate startR = CalendarDate.parseISOformat(null, time); //startR = startR.subtract(CalendarPeriod.Hour); //CalendarDate endR = CalendarDate.parseISOformat(null, time); //endR = endR.add(CalendarPeriod.Hour); return CalendarDateRange . of ( time . subtract ( timeWindow ) , time . add ( timeWindow ) ) ; } else if ( ncssParams . getTimeRange ( ) != null ) { return ncssParams . getTimeRange ( ) ; } else if ( ncssParams . isTrue ( SubsetParams . timeAll ) ) { // Client explicitly requested all times. return null ; // "null" means that we want ALL times, i.e. "do not subset". } else { // Client didn't specify a time parameter. return null ; // Do not subset. } }


Input: ////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { StructureDataRegexp . Vinfo vinfo = ( StructureDataRegexp . Vinfo ) v2 . getSPobject ( ) ; return new ArraySequence ( vinfo . sm , new SeqIter ( vinfo ) , vinfo . nelems ) ; }


Input: ///////////////////////////////////////// [CODESPLIT] private void readIndex ( String indexFilename ) throws IOException { try ( FileInputStream fin = new FileInputStream ( indexFilename ) ) { if ( ! NcStream . readAndTest ( fin , MAGIC_START_IDX . getBytes ( CDM . utf8Charset ) ) ) throw new IllegalStateException ( "bad index file" ) ; int version = fin . read ( ) ; if ( version != 1 ) throw new IllegalStateException ( "Bad version = " + version ) ; int count = NcStream . readVInt ( fin ) ; for ( int i = 0 ; i < count ; i ++ ) { int size = NcStream . readVInt ( fin ) ; byte [ ] pb = new byte [ size ] ; NcStream . readFully ( fin , pb ) ; StationIndex si = decodeStationIndex ( pb ) ; map . put ( si . stnId , si ) ; } } System . out . println ( " read index map size=" + map . values ( ) . size ( ) ) ; }


Input: Reads an Error description from the named InputStream . This method calls a generated parser to interpret an ASCII representation of an <code > Error< / code > and regenerate it as a <code > DAP2Exception< / code > . [CODESPLIT] public final boolean parse ( InputStream stream ) { Dap2Parser parser = new Dap2Parser ( new DefaultFactory ( ) ) ; String text ; try { text = DConnect2 . captureStream ( stream ) ; if ( parser . errparse ( text , this ) != Dap2Parser . DapERR ) return false ; } catch ( ParseException pe ) { this . initCause ( pe ) ; } catch ( IOException pe ) { this . initCause ( pe ) ; } return true ; }


Input:
Print the Error message on the given <code > PrintWriter< / code > . This code can be used by servlets to throw DAP2Exception to client . [CODESPLIT] public void print ( PrintWriter os ) { os . println ( "Error {" ) ; os . println ( "    code = " + errorCode + ";" ) ; if ( errorMessage != null ) os . println ( "    message = " + dumpword ( errorMessage ) + ";" ) ; //if(programType > 0) os.println("    program_type = " + programType + ";");
 if ( programSource != null ) os . println ( "    program = " + dumpword ( programSource ) + ";" ) ; os . println ( "};" ) ; }


Input: ///////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void showFile ( TableBean bean ) { infoTA . setText ( "Table:" + bean . getPath ( ) + "\n" ) ; try ( InputStream is = GribResourceReader . getInputStream ( bean . getPath ( ) ) ) { infoTA . appendLine ( IO . readContents ( is ) ) ; infoWindow . setVisible ( true ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } }


Input: Find the DatasetSourceType that matches this name . [CODESPLIT] public static DatasetSourceType getType ( String name ) { if ( name == null ) return null ; return ( ( DatasetSourceType ) hash . get ( name ) ) ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest / wml2 : MonitoringPoint / gml : identifier [CODESPLIT] public static CodeWithAuthorityType initIdentifier ( CodeWithAuthorityType identifier , StationTimeSeriesFeature stationFeat ) { // @codespace identifier . setCodeSpace ( "http://unidata.ucar.edu/" ) ; // TEXT identifier . setStringValue ( stationFeat . getName ( ) ) ; return identifier ; }


Input: Factory method for this abstract class . @param name @param type @param structure @param accessPoint [CODESPLIT] public static final DatasetSource newDatasetSource ( String name , DatasetSourceType type , DatasetSourceStructure structure , String accessPoint , ResultService resultService ) { if ( type == null ) { String tmpMsg = "DatasetSource type cannot be null" ; logger . error ( "newDatasetSource(): " + tmpMsg ) ; throw new IllegalArgumentException ( tmpMsg ) ; } DatasetSource tmpDsSource = null ; if ( type == DatasetSourceType . getType ( "Local" ) ) { tmpDsSource = new LocalDatasetSource ( ) ; } else if ( type == DatasetSourceType . getType ( "DodsDir" ) ) { tmpDsSource = new DodsDirDatasetSource ( ) ; } else if ( type == DatasetSourceType . getType ( "DodsFileServer" ) ) { tmpDsSource = new DodsFileServerDatasetSource ( ) ; } else if ( type == DatasetSourceType . getType ( "GrADSDataServer" ) ) { tmpDsSource = new GrADSDataServerDatasetSource ( ) ; } else { String tmpMsg = "Unsupported DatasetSource type <" + type . toString ( ) + ">." ; logger . error ( "newDatasetSource(): " + tmpMsg ) ; throw new IllegalArgumentException ( tmpMsg ) ; } tmpDsSource . setName ( name ) ; tmpDsSource . setStructure ( structure ) ; tmpDsSource . setAccessPoint ( accessPoint ) ; tmpDsSource . setResultService ( resultService ) ; // Test validity and append messages to log. logger . debug ( "DatasetSource(): constructor done." ) ; StringBuilder log = new StringBuilder ( ) ; if ( tmpDsSource . validate ( log ) ) { logger . debug ( "DatasetSource(): new DatasetSource is valid: {}" , log . toString ( ) ) ; } else { logger . debug ( "DatasetSource(): new DatasetSource is invalid: {}" , log . toString ( ) ) ; } return ( tmpDsSource ) ; }


Input: Crawl this DatasetSource and generate a new InvCatalog return the top - level InvDataset . [CODESPLIT] public InvDataset expand ( ) throws IOException { // Get the new catalog being generated and its top-level dataset. this . resultingCatalog = this . createSkeletonCatalog ( prefixUrlPath ) ; this . accessPointDataset = ( InvDataset ) this . resultingCatalog . getDatasets ( ) . get ( 0 ) ; // IOException thrown by createSkeletonCatalog() so this check should not be necessary. if ( ! this . isCollection ( this . accessPointDataset ) ) { String tmpMsg = "The access point dataset <" + this . accessPointDataset . getName ( ) + "> must be a collection dataset." ; logger . warn ( "expand(): {}" , tmpMsg ) ; throw new IOException ( tmpMsg ) ; } // Recurse into directory structure and expand. expandRecursive ( this . accessPointDataset ) ; // Finish the catalog. ( ( InvCatalogImpl ) this . resultingCatalog ) . finish ( ) ; // Remove empty collection datasets. @todo HACK - should use filters instead. this . recursivelyRemoveEmptyCollectionDatasets ( this . accessPointDataset ) ; // Return the top-level dataset. return ( this . accessPointDataset ) ; }


Input: Crawl this DatasetSource and generate a new InvCatalog with all datasets named sorted and organized as defined by this DatasetSource return the newly generated InvCatalog . [CODESPLIT] public InvCatalog fullExpand ( ) throws IOException { logger . debug ( "fullExpand(): expanding DatasetSource named \"{}\"" , this . getName ( ) ) ; InvDataset topDs = this . expand ( ) ; InvCatalog generatedCat = topDs . getParentCatalog ( ) ; // Add metadata to all datasets. for ( Iterator it = this . getDatasetEnhancerList ( ) . iterator ( ) ; it . hasNext ( ) ; ) { DatasetEnhancer1 dsE = ( DatasetEnhancer1 ) it . next ( ) ; dsE . addMetadata ( topDs ) ; } // Name all datasets. logger . debug ( "fullExpand(): naming the datasets." ) ; this . nameDatasets ( ( InvDatasetImpl ) topDs ) ; // Sort all datasets logger . debug ( "fullExpand(): sorting the datasets." ) ; this . sortDatasets ( topDs ) ; // Return the generated catalog ( ( InvCatalogImpl ) generatedCat ) . finish ( ) ; return ( generatedCat ) ; }


Input: Use the list of dsNamers to name the given list of datasets . [CODESPLIT] private void nameDatasets ( InvDatasetImpl datasetContainer ) { if ( this . getDatasetNamerList ( ) . isEmpty ( ) ) return ; if ( this . isFlatten ( ) ) { logger . debug ( "nameDatasets(): structure is FLAT calling nameDatasetList()" ) ; this . nameDatasetList ( datasetContainer ) ; } else { logger . debug ( "nameDatasets(): structure is DIRECTORY_TREE calling" + " nameDatasetTree() on each dataset in dataset container" ) ; InvDatasetImpl curDs = null ; for ( int j = 0 ; j < datasetContainer . getDatasets ( ) . size ( ) ; j ++ ) { curDs = ( InvDatasetImpl ) datasetContainer . getDatasets ( ) . get ( j ) ; this . nameDatasetTree ( curDs ) ; } } return ; }


Input: Name the datasets contained in the given dataset . The given dataset contains a flat list of datasets . [CODESPLIT] private void nameDatasetList ( InvDatasetImpl dataset ) { // Create temporary dataset in which to hold named datasets. InvDatasetImpl namedDs = new InvDatasetImpl ( dataset , "nameDatastList() temp dataset" , null , null , null ) ; // InvDatasetImpl(parentDs, name, dataType, serviceName, urlPath) dataset . addDataset ( namedDs ) ; // Loop through the DatasetNamers DatasetNamer curNamer = null ; for ( int i = 0 ; i < this . datasetNamerList . size ( ) ; i ++ ) { curNamer = ( DatasetNamer ) this . datasetNamerList . get ( i ) ; logger . debug ( "nameDatasetList(): trying namer ({})" , curNamer . getName ( ) ) ; // If the current DatasetNamer adds a new level, create a new dataset. InvDatasetImpl addLevelDs = null ; if ( curNamer . getAddLevel ( ) ) { addLevelDs = new InvDatasetImpl ( null , curNamer . getName ( ) , null , null , null ) ; } // Iterate over remaining unnamed datasets. InvDatasetImpl curDs = null ; java . util . Iterator dsIter = dataset . getDatasets ( ) . iterator ( ) ; while ( dsIter . hasNext ( ) ) { curDs = ( InvDatasetImpl ) dsIter . next ( ) ; logger . debug ( "nameDatasetList(): try namer on this ds ({}-{})" , curDs . getName ( ) , curDs . getUrlPath ( ) ) ; // Try to name the current dataset. if ( curNamer . nameDataset ( curDs ) ) { logger . debug ( "nameDatasetList(): ds named ({})" , curDs . getName ( ) ) ; // If adding a level, add named datasets to the added level dataset. if ( curNamer . getAddLevel ( ) ) { addLevelDs . addDataset ( curDs ) ; } // Otherwise, add the named datasets to namedDs. else { namedDs . addDataset ( curDs ) ; } // Remove the now-named dataset from list of unnamed datasets. dsIter . remove ( ) ; } } // END - InvDatasetImpl loop // If the namer added a level and a dataset was named by this namer, add the // new level to the list of named datasets. if ( curNamer . getAddLevel ( ) ) { if ( addLevelDs . hasNestedDatasets ( ) ) { namedDs . addDataset ( addLevelDs ) ; } } } // END - DatasetNamer loop namedDs . finish ( ) ; // Once all datasets are named (or unnamable with these DatasetNamers), // add all the datasets in namedDs back into the given containerDataset. if ( logger . isDebugEnabled ( ) ) { logger . debug ( "nameDatasetList(): number of unnamed datasets is " + dataset . getDatasets ( ) . size ( ) + "." ) ; logger . debug ( "nameDatasetList(): add named datasets back to container." ) ; } for ( int i = 0 ; i < namedDs . getDatasets ( ) . size ( ) ; i ++ ) { dataset . addDataset ( ( InvDatasetImpl ) namedDs . getDatasets ( ) . get ( i ) ) ; } dataset . removeDataset ( namedDs ) ; return ; }


Input: Name the datasets in the given dataset hierarchy using this DatasetSource s list of datasetNamers . [CODESPLIT] private void nameDatasetTree ( InvDatasetImpl dataset ) { // If dataset does not have a name, try naming it with dsNamers. // @todo Rethink naming of directories (look at how DatasetFilter deals with collection vs atomic datasets). if ( dataset . getName ( ) . equals ( "" ) || ! dataset . hasAccess ( ) ) { logger . debug ( "nameDatasetTree(): naming dataset ({})..." , dataset . getUrlPath ( ) ) ; DatasetNamer dsN = null ; for ( int i = 0 ; i < this . datasetNamerList . size ( ) ; i ++ ) { dsN = ( DatasetNamer ) this . datasetNamerList . get ( i ) ; if ( dsN . nameDataset ( dataset ) ) { logger . debug ( "nameDatasetTree(): ... used namer ({})" , dsN . getName ( ) ) ; break ; } } } // Try to name any child datasets. InvDatasetImpl curDs = null ; for ( int j = 0 ; j < dataset . getDatasets ( ) . size ( ) ; j ++ ) { curDs = ( InvDatasetImpl ) dataset . getDatasets ( ) . get ( j ) ; logger . debug ( "nameDatasetTree(): recurse to name child dataset ({})" , curDs . getUrlPath ( ) ) ; this . nameDatasetTree ( curDs ) ; } return ; }


Input:
method to invoke with a filename or URL of a picture that is to be loaded and scaled in a new thread . This is handy to update the screen while the loading chuggs along in the background . Make sure you invoked setScaleFactor or setScaleSize before invoking this method . <p / > Step 1 : Am I already loading what I need somewhere? If yes - > use it . Has it finished loading? If no - > wait for it If yes - > use it Else - > load it [CODESPLIT] public void loadAndScalePictureInThread ( URL imageUrl , int priority , double rotation ) { this . imageUrl = imageUrl ; boolean alreadyLoading = false ; Tools . log ( "ScalablePicture.loadAndScalePictureInThread: checking if picture " + imageUrl + " is already being loaded." ) ; if ( ( sourcePicture != null ) && ( sourcePicture . getUrl ( ) . toString ( ) . equals ( imageUrl . toString ( ) ) ) ) { Tools . log ( "ScalablePicture.loadAndScalePictureInThread: the SourcePicture is already loading the sourcePictureimage" ) ; alreadyLoading = true ; } else if ( PictureCache . isInCache ( imageUrl ) ) { // in case the old image has a listener connected remove it
 //  fist time round the sourcePicture is still null therefore the if.
 if ( sourcePicture != null ) sourcePicture . removeListener ( this ) ; sourcePicture = PictureCache . getSourcePicture ( imageUrl ) ; String status = sourcePicture . getStatusMessage ( ) ; if ( status == null ) status = "" ; Tools . log ( "ScalablePicture.loadAndScalePictureInThread: Picture in cache! Status: " + status ) ; if ( sourcePicture . getRotation ( ) == rotation ) { alreadyLoading = true ; Tools . log ( "ScalablePicture.loadAndScalePictureInThread: Picture was even rotated to the correct angle!" ) ; } else { alreadyLoading = false ; Tools . log ( "ScalablePicture.loadAndScalePictureInThread: Picture was in cache but with wrong rotation. Forcing reload." ) ; } } if ( alreadyLoading ) { switch ( sourcePicture . getStatusCode ( ) ) { case SourcePicture . UNINITIALISED : alreadyLoading = false ; Tools . log ( "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: UNINITIALISED" ) ; break ; case SourcePicture . ERROR : alreadyLoading = false ; Tools . log ( "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: ERROR" ) ; break ; case SourcePicture . LOADING : Tools . log ( "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: LOADING" ) ; sourcePicture . addListener ( this ) ; setStatus ( LOADING , "Loading: " + imageUrl . toString ( ) ) ; sourceLoadProgressNotification ( SourcePicture . LOADING_PROGRESS , sourcePicture . getPercentLoaded ( ) ) ; scaleAfterLoad = true ; break ; case SourcePicture . ROTATING : Tools . log ( "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: ROTATING" ) ; setStatus ( LOADING , "Rotating: " + imageUrl . toString ( ) ) ; sourceLoadProgressNotification ( SourcePicture . LOADING_PROGRESS , sourcePicture . getPercentLoaded ( ) ) ; scaleAfterLoad = true ; break ; case SourcePicture . READY : Tools . log ( "ScalablePicture.loadAndScalePictureInThread: pictureStatus was: READY. Sending SCALING status." ) ; setStatus ( SCALING , "Scaling: " + imageUrl . toString ( ) ) ; createScaledPictureInThread ( priority ) ; break ; default : Tools . log ( "ScalablePicture.loadAndScalePictureInThread: Don't know what status this is:" + Integer . toString ( sourcePicture . getStatusCode ( ) ) ) ; break ; } } // if the image is not already there then load it.
 if ( ! alreadyLoading ) { if ( sourcePicture != null ) sourcePicture . removeListener ( this ) ; sourcePicture = new SourcePicture ( ) ; sourcePicture . addListener ( this ) ; setStatus ( LOADING , "Loading: " + imageUrl . toString ( ) ) ; scaleAfterLoad = true ; sourcePicture . loadPictureInThread ( imageUrl , priority , rotation ) ; // when the thread is done it sends a sourceStatusChange message to us
 } }


Input: Synchroneous method to load the image . It should only be called by something which is a thread itself such as the HtmlDistillerThread . Since this intended for large batch operations this bypasses the cache . [CODESPLIT] public void loadPictureImd ( URL imageUrl , double rotation ) { Tools . log ( "loadPictureImd invoked with URL: " + imageUrl . toString ( ) ) ; if ( sourcePicture != null ) sourcePicture . removeListener ( this ) ; sourcePicture = new SourcePicture ( ) ; sourcePicture . addListener ( this ) ; setStatus ( LOADING , "Loading: " + imageUrl . toString ( ) ) ; scaleAfterLoad = true ; sourcePicture . loadPicture ( imageUrl , rotation ) ; }


Input:
stops all picture loading except if the Url we desire is being loaded [CODESPLIT] public void stopLoadingExcept ( URL url ) { if ( sourcePicture != null ) { boolean isCurrentlyLoading = sourcePicture . stopLoadingExcept ( url ) ; if ( ! isCurrentlyLoading ) { // sourcePicture.removeListener( this );
 } PictureCache . stopBackgroundLoadingExcept ( url ) ; } }


Input:
method that is invoked by the SourcePictureListener interface . Usually this will be called by the SourcePicture telling the ScalablePicture that it has completed loading . The ScalablePicture should then change it s own status and tell the ScalableListeners what s up . [CODESPLIT] public void sourceStatusChange ( int statusCode , String statusMessage , SourcePicture sp ) { //Tools.log("ScalablePicture.sourceStatusChange: status received from SourceImage: " + statusMessage);
 switch ( statusCode ) { case SourcePicture . UNINITIALISED : Tools . log ( "ScalablePicture.sourceStatusChange: pictureStatus was: UNINITIALISED message: " + statusMessage ) ; setStatus ( UNINITIALISED , statusMessage ) ; break ; case SourcePicture . ERROR : Tools . log ( "ScalablePicture.sourceStatusChange: pictureStatus was: ERROR message: " + statusMessage ) ; setStatus ( ERROR , statusMessage ) ; sourcePicture . removeListener ( this ) ; break ; case SourcePicture . LOADING : Tools . log ( "ScalablePicture.sourceStatusChange: pictureStatus was: LOADING message: " + statusMessage ) ; setStatus ( LOADING , statusMessage ) ; break ; case SourcePicture . ROTATING : Tools . log ( "ScalablePicture.sourceStatusChange: pictureStatus was: ROTATING message: " + statusMessage ) ; setStatus ( LOADING , statusMessage ) ; break ; case SourcePicture . READY : Tools . log ( "ScalablePicture.sourceStatusChange: pictureStatus was: READY message: " + statusMessage ) ; setStatus ( LOADED , statusMessage ) ; sourcePicture . removeListener ( this ) ; if ( scaleAfterLoad ) { createScaledPictureInThread ( Thread . MAX_PRIORITY ) ; scaleAfterLoad = false ; } break ; default : Tools . log ( "ScalablePicture.sourceStatusChange: Don't recognize this status: " + statusMessage ) ; break ; } }


Input: pass on the update on the loading Progress to the listening objects [CODESPLIT] public void sourceLoadProgressNotification ( int statusCode , int percentage ) { Enumeration e = scalablePictureStatusListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . sourceLoadProgressNotification ( statusCode , percentage ) ; } }


Input: method that creates the scaled image in the background in it s own thread . [CODESPLIT] public void createScaledPictureInThread ( int priority ) { setStatus ( SCALING , "Scaling picture." ) ; ScaleThread t = new ScaleThread ( this ) ; t . setPriority ( priority ) ; t . start ( ) ; }


Input: return the size of the scaled image or Zero if there is none [CODESPLIT] public Dimension getScaledSize ( ) { if ( scaledPicture != null ) return new Dimension ( scaledPicture . getWidth ( ) , scaledPicture . getHeight ( ) ) ; else return new Dimension ( 0 , 0 ) ; }


Input: return the size of the scaled image as a neatly formatted text or Zero if there is none [CODESPLIT] public String getScaledSizeString ( ) { if ( scaledPicture != null ) return Integer . toString ( scaledPicture . getWidth ( ) ) + " x " + Integer . toString ( scaledPicture . getHeight ( ) ) ; else return "0 x 0" ; }


Input:
This static method writes the indicated renderedImage ( BufferedImage ) to the indicated file . [CODESPLIT] public static void writeJpg ( File writeFile , RenderedImage renderedImage , float jpgQuality ) { Iterator writers = ImageIO . getImageWritersByFormatName ( "jpg" ) ; ImageWriter writer = ( ImageWriter ) writers . next ( ) ; JPEGImageWriteParam params = new JPEGImageWriteParam ( null ) ; params . setCompressionMode ( ImageWriteParam . MODE_EXPLICIT ) ; params . setCompressionQuality ( jpgQuality ) ; params . setProgressiveMode ( ImageWriteParam . MODE_DISABLED ) ; params . setDestinationType ( new ImageTypeSpecifier ( java . awt . image . IndexColorModel . getRGBdefault ( ) , IndexColorModel . getRGBdefault ( ) . createCompatibleSampleModel ( 16 , 16 ) ) ) ; try ( ImageOutputStream ios = ImageIO . createImageOutputStream ( new FileOutputStream ( writeFile ) ) ) { writer . setOutput ( ios ) ; writer . write ( null , new IIOImage ( renderedImage , null , null ) , params ) ; ios . close ( ) ; } catch ( IOException e ) { //Tools.log("ScalablePicture.writeJpg caught IOException: " +  e.getMessage() + "\nwhile writing " + writeFile.toString());
 e . printStackTrace ( ) ; } //writer = null;
 writer . dispose ( ) ; //1.4.1 documentation says to do this.
 }


Input: Method that sets the status of the ScalablePicture object and notifies intereasted objects of a change in status ( not built yet ) . [CODESPLIT] private void setStatus ( int statusCode , String statusMessage ) { String filename = ( imageUrl == null ) ? "" : imageUrl . toString ( ) ; Tools . log ( "ScalablePicture.setStatus: sending: " + statusMessage + " to all Listeners from Image: " + filename ) ; pictureStatusCode = statusCode ; pictureStatusMessage = statusMessage ; Enumeration e = scalablePictureStatusListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . scalableStatusChange ( pictureStatusCode , pictureStatusMessage ) ; } }


Input: Initialize the file read in all the metadata ( ala DM_OPEN ) [CODESPLIT] public static GempakSoundingFileReader getInstance ( RandomAccessFile raf , boolean fullCheck ) throws IOException { GempakSoundingFileReader gsfr = new GempakSoundingFileReader ( ) ; gsfr . init ( raf , fullCheck ) ; return gsfr ; }


Input:
Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( ! super . init ( fullCheck ) ) { return false ; } // Modeled after SN_OFIL
 if ( dmLabel . kftype != MFSN ) { logError ( "not a sounding data file " ) ; return false ; } DMPart part = getPart ( SNDT ) ; if ( part != null ) { // merged file
 subType = MERGED ; String vertName = part . params . get ( 0 ) . kprmnm ; switch ( vertName ) { case "PRES" : ivert = PRES_COORD ; break ; case "THTA" : ivert = THTA_COORD ; break ; case "HGHT" : case "MHGT" : case "DHGT" : ivert = HGHT_COORD ; break ; default : logError ( "unknown vertical coordinate in merged file" ) ; return false ; } } else { unmergedParts = SN_CKUA ( ) ; boolean haveUnMerged = ! unmergedParts . isEmpty ( ) ; if ( ! haveUnMerged ) { logError ( "unknown sounding file type - not merged/unmerged" ) ; return false ; } else { ivert = PRES_COORD ; subType = UNMERGED ; } } if ( ! readStationsAndTimes ( true ) ) { logError ( "Unable to read stations and times" ) ; return false ; } return true ; }


Input: Get the list of merged parts in this file [CODESPLIT] public List < String > getMergedParts ( ) { List < String > list = new ArrayList <> ( 1 ) ; list . add ( SNDT ) ; return list ; }


Input: Print the list of dates in the file [CODESPLIT] public void printOb ( int row , int col ) { GempakStation station = getStations ( ) . get ( col - 1 ) ; String time = getDateString ( row - 1 ) ; StringBuilder builder = new StringBuilder ( "\n" ) ; builder . append ( makeHeader ( station , time ) ) ; builder . append ( "\n" ) ; boolean merge = getFileSubType ( ) . equals ( MERGED ) ; List < String > parts ; if ( merge ) { parts = new ArrayList <> ( ) ; parts . add ( SNDT ) ; } else { parts = unmergedParts ; } for ( String part : parts ) { RData rd ; try { rd = DM_RDTR ( row , col , part ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; rd = null ; } if ( rd == null ) { continue ; } if ( ! merge ) { builder . append ( "    " ) ; builder . append ( part ) ; builder . append ( "    " ) ; builder . append ( time . substring ( time . indexOf ( "/" ) + 1 ) ) ; } builder . append ( "\n" ) ; if ( ! merge ) { builder . append ( "\t" ) ; } List < GempakParameter > params = getParameters ( part ) ; for ( GempakParameter parm : params ) { builder . append ( StringUtil2 . padLeft ( parm . getName ( ) , 7 ) ) ; builder . append ( "\t" ) ; } builder . append ( "\n" ) ; if ( ! merge ) { builder . append ( "\t" ) ; } float [ ] data = rd . data ; int numParams = params . size ( ) ; int numLevels = data . length / numParams ; for ( int j = 0 ; j < numLevels ; j ++ ) { for ( int i = 0 ; i < numParams ; i ++ ) { builder . append ( StringUtil2 . padLeft ( Format . formatDouble ( data [ j * numParams + i ] , 7 , 1 ) , 7 ) ) ; builder . append ( "\t" ) ; } builder . append ( "\n" ) ; if ( ! merge ) { builder . append ( "\t" ) ; } } builder . append ( "\n" ) ; } builder . append ( "\n" ) ; System . out . println ( builder . toString ( ) ) ; }


Input: Make the header for the text report [CODESPLIT] private String makeHeader ( GempakStation stn , String date ) { StringBuilder builder = new StringBuilder ( ) ; builder . append ( "STID = " ) ; builder . append ( StringUtil2 . padRight ( ( stn . getSTID ( ) . trim ( ) + stn . getSTD2 ( ) . trim ( ) ) , 8 ) ) ; builder . append ( "\t" ) ; builder . append ( "STNM = " ) ; builder . append ( Format . i ( stn . getSTNM ( ) , 6 ) ) ; builder . append ( "\t" ) ; builder . append ( "TIME = " ) ; builder . append ( date ) ; builder . append ( "\n" ) ; builder . append ( "SLAT = " ) ; builder . append ( Format . d ( stn . getLatitude ( ) , 5 ) ) ; builder . append ( "\t" ) ; builder . append ( "SLON = " ) ; builder . append ( Format . d ( stn . getLongitude ( ) , 5 ) ) ; builder . append ( "\t" ) ; builder . append ( "SELV = " ) ; builder . append ( Format . d ( stn . getAltitude ( ) , 5 ) ) ; builder . append ( "\n" ) ; return builder . toString ( ) ; }


Input:
This subroutine checks the parts in a sounding data set for the unmerged data types . [CODESPLIT] private List < String > SN_CKUA ( ) { List < String > types = new ArrayList <> ( ) ; boolean above = false ; boolean done = false ; String partToCheck ; while ( ! done ) { // check for mandatory groups
 for ( int group = 0 ; group < belowGroups . length ; group ++ ) { if ( above ) { partToCheck = aboveGroups [ group ] ; } else { partToCheck = belowGroups [ group ] ; } if ( checkForValidGroup ( partToCheck , parmLists [ group ] ) ) { types . add ( partToCheck ) ; } } if ( ! above ) { above = true ; } else { done = true ; } } return types ; }


Input: Check for valid groups [CODESPLIT] private boolean checkForValidGroup ( String partToCheck , String [ ] params ) { DMPart part = getPart ( partToCheck ) ; if ( part == null ) { return false ; } int i = 0 ; for ( DMParam parm : part . params ) { if ( ! ( parm . kprmnm . equals ( params [ i ++ ] ) ) ) { return false ; } } return true ; }


Input: Run the program [CODESPLIT] public static void main ( String [ ] args ) throws IOException { if ( args . length == 0 ) { System . out . println ( "need to supply a GEMPAK sounding file name" ) ; System . exit ( 1 ) ; } try { GempakParameters . addParameters ( "resources/nj22/tables/gempak/params.tbl" ) ; } catch ( Exception e ) { System . out . println ( "unable to init param tables" ) ; } GempakSoundingFileReader gsfr = getInstance ( getFile ( args [ 0 ] ) , true ) ; System . out . println ( "Type = " + gsfr . getFileType ( ) ) ; gsfr . printFileLabel ( ) ; gsfr . printKeys ( ) ; gsfr . printHeaders ( ) ; gsfr . printParts ( ) ; gsfr . printDates ( ) ; gsfr . printStations ( false ) ; int row = 1 ; int col = 1 ; if ( args . length > 1 ) { row = Integer . parseInt ( args [ 1 ] ) ; } if ( args . length > 2 ) { try { col = Integer . parseInt ( args [ 2 ] ) ; } catch ( Exception npe ) { col = gsfr . findStationIndex ( args [ 2 ] ) ; if ( col == - 1 ) { System . out . println ( "couldn't find station " + args [ 2 ] ) ; System . exit ( 1 ) ; } System . out . println ( "found station at column " + col ) ; } } gsfr . printOb ( row , col ) ; }


Input:
Set the cache root directory . Create it if it doesnt exist . [CODESPLIT] static public void setRootDirectory ( String cacheDir ) { if ( ! cacheDir . endsWith ( "/" ) ) cacheDir = cacheDir + "/" ; root = StringUtil2 . replace ( cacheDir , ' ' , "/" ) ; // no nasty backslash
 makeRootDirectory ( ) ; }


Input: Make sure that the current root directory exists . [CODESPLIT] static public void makeRootDirectory ( ) { File dir = new File ( root ) ; if ( ! dir . exists ( ) ) if ( ! dir . mkdirs ( ) ) throw new IllegalStateException ( "DiskCache.setRootDirectory(): could not create root directory <" + root + ">." ) ; checkExist = true ; }


Input:
Get a File if it exists . If not get a File that can be written to . If alwaysInCache look only in the cache otherwise look in the normal location first then in the cache . <p > [CODESPLIT] static public File getFile ( String fileLocation , boolean alwaysInCache ) { if ( alwaysInCache ) { return getCacheFile ( fileLocation ) ; } else { File f = new File ( fileLocation ) ; if ( f . exists ( ) ) return f ; // now comes the tricky part to make sure we can open and write to it
 try { if ( ! simulateUnwritableDir && f . createNewFile ( ) ) { boolean ret = f . delete ( ) ; assert ret ; return f ; } } catch ( IOException e ) { // cant write to it - drop through
 } return getCacheFile ( fileLocation ) ; } }


Input: Get a file in the cache . File may or may not exist . We assume its always writeable . If it does exist set its LastModifiedDate to current time . [CODESPLIT] static public File getCacheFile ( String fileLocation ) { File f = new File ( makeCachePath ( fileLocation ) ) ; if ( f . exists ( ) ) { if ( ! f . setLastModified ( System . currentTimeMillis ( ) ) ) logger . warn ( "Failed to setLastModified on " + f . getPath ( ) ) ; } if ( ! checkExist ) { File dir = f . getParentFile ( ) ; if ( ! dir . exists ( ) && ! dir . mkdirs ( ) ) logger . warn ( "Failed to mkdirs on " + dir . getPath ( ) ) ; checkExist = true ; } return f ; }


Input:
Make the cache filename [CODESPLIT] static private String makeCachePath ( String fileLocation ) { Escaper urlPathEscaper = UrlEscapers . urlPathSegmentEscaper ( ) ; fileLocation = fileLocation . replace ( ' ' , ' ' ) ; // LOOK - use better normalization code  eg Spring StringUtils
 String cachePath = urlPathEscaper . escape ( fileLocation ) ; return root + cachePath ; }


Input: Remove all files with date < cutoff . [CODESPLIT] static public void cleanCache ( Date cutoff , StringBuilder sbuff ) { if ( sbuff != null ) sbuff . append ( "CleanCache files before " ) . append ( cutoff ) . append ( "\n" ) ; File dir = new File ( root ) ; File [ ] children = dir . listFiles ( ) ; if ( children == null ) return ; for ( File file : children ) { Date lastMod = new Date ( file . lastModified ( ) ) ; if ( lastMod . before ( cutoff ) ) { boolean ret = file . delete ( ) ; if ( sbuff != null ) { sbuff . append ( " delete " ) . append ( file ) . append ( " (" ) . append ( lastMod ) . append ( ")\n" ) ; if ( ! ret ) sbuff . append ( "Error deleting " ) . append ( file ) . append ( "\n" ) ; } } } }


Input: Remove files if needed to make cache have less than maxBytes bytes file sizes . This will remove files in sort order defined by fileComparator . The first files in the sort order are kept until the max bytes is exceeded then they are deleted . [CODESPLIT] static public void cleanCache ( long maxBytes , Comparator < File > fileComparator , StringBuilder sbuff ) { if ( sbuff != null ) sbuff . append ( "DiskCache clean maxBytes= " ) . append ( maxBytes ) . append ( "on dir " ) . append ( root ) . append ( "\n" ) ; File dir = new File ( root ) ; long total = 0 , total_delete = 0 ; File [ ] files = dir . listFiles ( ) ; if ( files != null ) { List < File > fileList = Arrays . asList ( files ) ; Collections . sort ( fileList , fileComparator ) ; for ( File file : fileList ) { if ( file . length ( ) + total > maxBytes ) { total_delete += file . length ( ) ; if ( sbuff != null ) sbuff . append ( " delete " ) . append ( file ) . append ( " (" ) . append ( file . length ( ) ) . append ( ")\n" ) ; if ( ! file . delete ( ) && sbuff != null ) sbuff . append ( "Error deleting " ) . append ( file ) . append ( "\n" ) ; } else { total += file . length ( ) ; } } } if ( sbuff != null ) { sbuff . append ( "Total bytes deleted= " ) . append ( total_delete ) . append ( "\n" ) ; sbuff . append ( "Total bytes left in cache= " ) . append ( total ) . append ( "\n" ) ; } }


Input: debug [CODESPLIT] static void make ( String filename ) throws IOException { File want = DiskCache . getCacheFile ( filename ) ; System . out . println ( "make=" + want . getPath ( ) + "; exists = " + want . exists ( ) ) ; if ( ! want . exists ( ) ) { boolean ret = want . createNewFile ( ) ; assert ret ; } System . out . println ( " canRead= " + want . canRead ( ) + " canWrite = " + want . canWrite ( ) + " lastMod = " + new Date ( want . lastModified ( ) ) ) ; System . out . println ( " original=" + filename ) ; }


Input: Get the named Icon from the default resource ( jar file ) . [CODESPLIT] public static ImageIcon getIcon ( String name , boolean errMsg ) { ImageIcon ii = Resource . getIcon ( defaultResourcePath + name + ".gif" , errMsg ) ; if ( ii == null ) Resource . getIcon ( defaultResourcePath + name + ".png" , errMsg ) ; return ii ; }


Input: Get the named Image from the default resource ( jar file ) . [CODESPLIT] public static Image getImage ( String name ) { Image ii ; if ( name . endsWith ( ".png" ) || name . endsWith ( ".jpg" ) || name . endsWith ( ".gif" ) ) ii = Resource . getImage ( defaultResourcePath + name ) ; else ii = Resource . getImage ( defaultResourcePath + name + ".gif" ) ; return ii ; }


Input: Make a buttcon = button with an Icon [CODESPLIT] public static AbstractButton makeButtcon ( Icon icon , Icon selected , String tooltip , boolean is_toggle ) { AbstractButton butt ; if ( is_toggle ) butt = new JToggleButton ( ) ; else butt = new JButton ( ) ; if ( debug ) System . out . println ( "   makeButtcon" + icon + " " + selected + " " + tooltip + " " + is_toggle ) ; if ( icon != null ) butt . setIcon ( icon ) ; if ( selected != null ) { if ( is_toggle ) { butt . setSelectedIcon ( selected ) ; } else { butt . setRolloverIcon ( selected ) ; butt . setRolloverSelectedIcon ( selected ) ; butt . setPressedIcon ( selected ) ; butt . setRolloverEnabled ( true ) ; } } butt . setMaximumSize ( new Dimension ( 28 , 28 ) ) ; // kludge butt . setPreferredSize ( new Dimension ( 28 , 28 ) ) ; butt . setToolTipText ( tooltip ) ; butt . setFocusPainted ( false ) ; return butt ; }


Input: Make a buttcon = button with an Icon [CODESPLIT] public static AbstractButton makeButtcon ( String iconName , String tooltip , boolean is_toggle ) { Icon icon = getIcon ( iconName , false ) ; Icon iconSel = getIcon ( iconName + "Sel" , false ) ; return makeButtcon ( icon , iconSel , tooltip , is_toggle ) ; }


Input: NB : doesnt add action to MenuItem [CODESPLIT] private static JMenuItem makeMenuItemFromAction ( Action act ) { // this prevents null pointer exception if user didnt call setProperties() Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; Integer mnu = ( Integer ) act . getValue ( BAMutil . MNEMONIC ) ; int mnemonic = ( tog == null ) ? - 1 : mnu . intValue ( ) ; Integer acc = ( Integer ) act . getValue ( BAMutil . ACCEL ) ; int accel = ( acc == null ) ? 0 : acc . intValue ( ) ; return makeMenuItem ( ( Icon ) act . getValue ( Action . SMALL_ICON ) , ( Icon ) act . getValue ( BAMutil . SELECTED_ICON ) , ( String ) act . getValue ( Action . SHORT_DESCRIPTION ) , is_toggle , mnemonic , accel < 0 ? 0 : accel ) ; }


Input:
creates a MenuItem using the given Action and adds it to the given Menu . Uses Properties that have been set on the Action ( see setActionProperties () ) . All are optional except for Action . SHORT_DESCRIPTION :
 Action . SHORT_DESCRIPTION String MenuItem text ( required ) Action . SMALL_ICON Icon the Icon to Use BAMutil . SELECTED_ICON Icon the Icon when selected ( optional ) BAMutil . TOGGLE Boolean true if its a toggle BAMutil . MNEMONIC Integer menu item shortcut BAMutil . ACCEL Integer menu item global keyboard accelerator

 The Action is triggered when the MenuItem is selected . Enabling and disabling the Action does the same for the MenuItem . For toggles state is maintained in the Action and MenuItem state changes when the Action state changes .

 The point of all this is that once you set it up you work exclusively with the action object and all changes are automatically reflected in the UI . [CODESPLIT] public static JMenuItem addActionToMenu ( JMenu menu , Action act , int menuPos ) { JMenuItem mi = makeMenuItemFromAction ( act ) ; if ( menuPos >= 0 ) menu . add ( mi , menuPos ) ; else menu . add ( mi ) ; Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; // set state for toggle buttons if ( is_toggle ) { if ( debugToggle ) System . out . println ( "addActionToMenu: " + act . getValue ( Action . SHORT_DESCRIPTION ) + " " + act . getValue ( BAMutil . STATE ) ) ; Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; if ( state == null ) state = Boolean . FALSE ; act . putValue ( BAMutil . STATE , state ) ; mi . setSelected ( state . booleanValue ( ) ) ; } // add event listeners Action myAct = is_toggle ? new ToggleAction ( act ) : act ; mi . addActionListener ( myAct ) ; act . addPropertyChangeListener ( new myActionChangedListener ( mi ) ) ; return mi ; }


Input: NB : doesnt add action to button [CODESPLIT] private static AbstractButton _makeButtconFromAction ( Action act ) { // this prevents null pointer exception if user didnt call setProperties() Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; return makeButtcon ( ( Icon ) act . getValue ( Action . SMALL_ICON ) , ( Icon ) act . getValue ( BAMutil . SELECTED_ICON ) , ( String ) act . getValue ( Action . SHORT_DESCRIPTION ) , is_toggle ) ; }


Input:
creates an AbstractButton using the given Action and adds it to the given Container at the position .. Uses Properties that have been set on the Action ( see setActionProperties () ) . All are optional except for Action . SMALL_ICON :
 Action . SMALL_ICON Icon the Icon to Use ( required ) BAMutil . SELECTED_ICON Icon the Icon when selected ( optional ) Action . SHORT_DESCRIPTION String tooltip BAMutil . TOGGLE Boolean true if its a toggle

 The Action is triggered when the Button is selected . Enabling and disabling the Action does the same for the Button . For toggles state is maintained in the Action and the Button state changes when the Action state changes .

 The point of all this is that once you set it up you work exclusively with the action object and all changes are automatically reflected in the UI . [CODESPLIT] public static AbstractButton addActionToContainerPos ( Container c , Action act , int pos ) { AbstractButton butt = _makeButtconFromAction ( act ) ; if ( pos < 0 ) c . add ( butt ) ; else c . add ( butt , pos ) ; if ( debug ) System . out . println ( " addActionToContainerPos " + act + " " + butt + " " + pos ) ; Boolean tog = ( Boolean ) act . getValue ( BAMutil . TOGGLE ) ; boolean is_toggle = ( tog == null ) ? false : tog . booleanValue ( ) ; // set state for toggle buttons if ( is_toggle ) { if ( debugToggle ) System . out . println ( "addActionToContainerPos: " + act . getValue ( Action . SHORT_DESCRIPTION ) + " " + act . getValue ( BAMutil . STATE ) ) ; Boolean state = ( Boolean ) act . getValue ( BAMutil . STATE ) ; if ( state == null ) state = Boolean . FALSE ; act . putValue ( BAMutil . STATE , state ) ; butt . setSelected ( state . booleanValue ( ) ) ; } // add event listsners Action myAct = is_toggle ? new ToggleAction ( act ) : act ; butt . addActionListener ( myAct ) ; act . addPropertyChangeListener ( new myActionChangedListener ( butt ) ) ; return butt ; }


Input: Standard way to set Properties for Actions . This also looks for an Icon <icon_name > Sel and if it exists : 1 ) sets SelectedIcon if its a toggle or 2 ) sets the Icon when selected ( optional ) if its not a toggle [CODESPLIT] public static void setActionProperties ( AbstractAction act , String icon_name , String action_name , boolean is_toggle , int mnemonic , int accel ) { if ( icon_name != null ) { act . putValue ( Action . SMALL_ICON , getIcon ( icon_name , true ) ) ; act . putValue ( BAMutil . SELECTED_ICON , getIcon ( icon_name + "Sel" , false ) ) ; } act . putValue ( Action . SHORT_DESCRIPTION , action_name ) ; act . putValue ( Action . LONG_DESCRIPTION , action_name ) ; act . putValue ( BAMutil . TOGGLE , new Boolean ( is_toggle ) ) ; act . putValue ( BAMutil . MNEMONIC , new Integer ( mnemonic ) ) ; act . putValue ( BAMutil . ACCEL , new Integer ( accel ) ) ; }


Input: Standard way to set Properties and state for Toggle Actions . * [CODESPLIT] public static void setActionPropertiesToggle ( AbstractAction act , String icon_name , String action_name , boolean toggleValue , int mnemonic , int accel ) { setActionProperties ( act , icon_name , action_name , true , mnemonic , accel ) ; act . putValue ( BAMutil . STATE , new Boolean ( toggleValue ) ) ; }


Input: LOOK could do better : all and maybe HashSet<Name > [CODESPLIT] public static List < StationFeature > getStationsInSubset ( StationTimeSeriesFeatureCollection stationFeatCol , SubsetParams ncssParams ) throws IOException { List < StationFeature > wantedStations ; // verify SpatialSelection has some stations if ( ncssParams . getStations ( ) != null ) { List < String > stnNames = ncssParams . getStations ( ) ; if ( stnNames . get ( 0 ) . equals ( "all" ) ) { wantedStations = stationFeatCol . getStationFeatures ( ) ; } else { wantedStations = stationFeatCol . getStationFeatures ( stnNames ) ; } } else if ( ncssParams . getLatLonBoundingBox ( ) != null ) { LatLonRect llrect = ncssParams . getLatLonBoundingBox ( ) ; wantedStations = stationFeatCol . getStationFeatures ( llrect ) ; } else if ( ncssParams . getLatLonPoint ( ) != null ) { Station closestStation = findClosestStation ( stationFeatCol , ncssParams . getLatLonPoint ( ) ) ; List < String > stnList = new ArrayList <> ( ) ; stnList . add ( closestStation . getName ( ) ) ; wantedStations = stationFeatCol . getStationFeatures ( stnList ) ; } else { // Want all. wantedStations = stationFeatCol . getStationFeatures ( ) ; } return wantedStations ; }


Input: / * Find the station closest to the specified point . The metric is ( lat - lat0 ) ** 2 + ( cos ( lat0 ) * ( lon - lon0 )) ** 2 [CODESPLIT] public static Station findClosestStation ( StationTimeSeriesFeatureCollection stationFeatCol , LatLonPoint pt ) throws IOException { double lat = pt . getLatitude ( ) ; double lon = pt . getLongitude ( ) ; double cos = Math . cos ( Math . toRadians ( lat ) ) ; List < StationFeature > stations = stationFeatCol . getStationFeatures ( ) ; Station min_station = stations . get ( 0 ) ; double min_dist = Double . MAX_VALUE ; for ( Station s : stations ) { double lat1 = s . getLatitude ( ) ; double lon1 = LatLonPointImpl . lonNormal ( s . getLongitude ( ) , lon ) ; double dy = Math . toRadians ( lat - lat1 ) ; double dx = cos * Math . toRadians ( lon - lon1 ) ; double dist = dy * dy + dx * dx ; if ( dist < min_dist ) { min_dist = dist ; min_station = s ; } } return min_station ; }


Input: contains a BUFR table entry [CODESPLIT] static public boolean isBufrTable ( short fxy ) { int f = ( fxy & 0xC000 ) >> 14 ; int x = ( fxy & 0x3F00 ) >> 8 ; int y = ( fxy & 0xFF ) ; return ( f == 0 ) && ( x == 0 ) && ( y < 13 ) ; }


Input: Create a coordinate axis from an existing Variable . [CODESPLIT] static public CoordinateAxis factory ( NetcdfDataset ncd , VariableDS vds ) { if ( ( vds . getRank ( ) == 0 ) || ( vds . getRank ( ) == 1 ) || ( vds . getRank ( ) == 2 && vds . getDataType ( ) == DataType . CHAR ) ) { return new CoordinateAxis1D ( ncd , vds ) ; } else if ( vds . getRank ( ) == 2 ) return new CoordinateAxis2D ( ncd , vds ) ; else return new CoordinateAxis ( ncd , vds ) ; }


Input: Make a copy with an independent cache . [CODESPLIT] public CoordinateAxis copyNoCache ( ) { CoordinateAxis axis = new CoordinateAxis ( ncd , getParentGroup ( ) , getShortName ( ) , getDataType ( ) , getDimensionsString ( ) , getUnitsString ( ) , getDescription ( ) ) ; // other state axis . axisType = this . axisType ; axis . boundaryRef = this . boundaryRef ; axis . isContiguous = this . isContiguous ; axis . positive = this . positive ; axis . cache = new Variable . Cache ( ) ; // decouple cache return axis ; }


Input: Does the axis have numeric values . [CODESPLIT] public boolean isNumeric ( ) { return ( getDataType ( ) != DataType . CHAR ) && ( getDataType ( ) != DataType . STRING ) && ( getDataType ( ) != DataType . STRUCTURE ) ; }


Input:
Get a string representation [CODESPLIT] public void getInfo ( Formatter buf ) { buf . format ( "%-30s" , getNameAndDimensions ( ) ) ; buf . format ( "%-20s" , getUnitsString ( ) ) ; if ( axisType != null ) { buf . format ( "%-10s" , axisType . toString ( ) ) ; } buf . format ( "%s" , getDescription ( ) ) ; /* if (isNumeric) {
     boolean debugCoords = ucar.util.prefs.ui.Debug.isSet("Dataset/showCoordValues");
     int ndigits = debugCoords ? 9 : 4;
     for (int i=0; i< getNumElements(); i++) {
       buf.append(Format.d(getCoordValue(i), ndigits));
       buf.append(" ");
     }
     if (debugCoords) {
       buf.append("\n      ");
       for (int i=0; i<=getNumElements(); i++) {
         buf.append(Format.d(getCoordEdge(i), ndigits));
         buf.append(" ");
       }
     }
   } else {
     for (int i=0; i< getNumElements(); i++) {
       buf.append(getCoordName(i));
       buf.append(" ");
     }
   } */ //buf.append("\n"); }


Input: needed by time coordinates [CODESPLIT] public ucar . nc2 . time . Calendar getCalendarFromAttribute ( ) { Attribute cal = findAttribute ( CF . CALENDAR ) ; String s = ( cal == null ) ? null : cal . getStringValue ( ) ; if ( s == null ) { // default for CF and COARDS Attribute convention = ( ncd == null ) ? null : ncd . getRootGroup ( ) . findAttribute ( CDM . CONVENTIONS ) ; if ( convention != null ) { String hasName = convention . getStringValue ( ) ; int version = CF1Convention . getVersion ( hasName ) ; if ( version >= 0 ) { return Calendar . gregorian ; //if (version < 7 ) return Calendar.gregorian; //if (version >= 7 ) return Calendar.proleptic_gregorian; // } if ( COARDSConvention . isMine ( hasName ) ) return Calendar . gregorian ; } } return ucar . nc2 . time . Calendar . get ( s ) ; }


Input: Sort the rowList : note rowList changed not a copy of it . [CODESPLIT] public void sort ( int colNo , boolean reverse ) { model . sort ( colNo , reverse ) ; jtable . setRowSelectionInterval ( 0 , 0 ) ; ensureRowIsVisible ( 0 ) ; }


Input: Replace the rowList with this one . [CODESPLIT] public void setList ( ArrayList rowList ) { this . list = rowList ; if ( list . size ( ) > 0 ) jtable . setRowSelectionInterval ( 0 , 0 ) ; else jtable . clearSelection ( ) ; model . sort ( ) ; jtable . revalidate ( ) ; }


Input: Remove elem from rowList update the table . Searches for match using object identity ( == ) [CODESPLIT] public void removeRow ( Object elem ) { Iterator iter = list . iterator ( ) ; while ( iter . hasNext ( ) ) { Object row = iter . next ( ) ; if ( row == elem ) { iter . remove ( ) ; break ; } } jtable . revalidate ( ) ; }


Input: Get the currently selected row . [CODESPLIT] public TableRow getSelected ( ) { if ( list . size ( ) == 0 ) return null ; int sel = jtable . getSelectedRow ( ) ; if ( sel >= 0 ) return ( TableRow ) list . get ( sel ) ; else return null ; }


Input: Set the current selection to this row . [CODESPLIT] public void setSelected ( int row ) { if ( ( row < 0 ) || ( row >= list . size ( ) ) ) return ; if ( debug ) System . out . println ( "JTableSorted setSelected " + row ) ; jtable . setRowSelectionInterval ( row , row ) ; ensureRowIsVisible ( row ) ; }


Input: Increment or decrement the current selection by one row . [CODESPLIT] public void incrSelected ( boolean increment ) { if ( list . size ( ) == 0 ) return ; int curr = jtable . getSelectedRow ( ) ; if ( increment && ( curr < list . size ( ) - 1 ) ) setSelected ( curr + 1 ) ; else if ( ! increment && ( curr > 0 ) ) setSelected ( curr - 1 ) ; }


Input: for each column get the model index [CODESPLIT] public int [ ] getModelIndex ( ) { int [ ] modelIndex = new int [ colName . length ] ; TableColumnModel tcm = jtable . getColumnModel ( ) ; for ( int i = 0 ; i < colName . length ; i ++ ) { TableColumn tc = tcm . getColumn ( i ) ; modelIndex [ i ] = tc . getModelIndex ( ) ; } return modelIndex ; }


Input: /////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void ensureRowIsVisible ( int nRow ) { Rectangle visibleRect = jtable . getCellRect ( nRow , 0 , true ) ; if ( visibleRect != null ) { visibleRect . x = scrollPane . getViewport ( ) . getViewPosition ( ) . x ; jtable . scrollRectToVisible ( visibleRect ) ; jtable . repaint ( ) ; } }


Input: this . [CODESPLIT] private CalendarPeriod findRangeAdjustment ( String fmtString ) { if ( fmtString . contains ( "H" ) || fmtString . contains ( "k" ) ) return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Hour ) ; else if ( fmtString . contains ( "d" ) ) return CalendarPeriod . of ( 1 , CalendarPeriod . Field . Day ) ; else if ( fmtString . contains ( "M" ) ) return CalendarPeriod . of ( 31 , CalendarPeriod . Field . Day ) ; else return CalendarPeriod . of ( 366 , CalendarPeriod . Field . Day ) ; }


Input: LOOK fake [CODESPLIT] @ Override public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { IOServiceProvider iosp = ncd . getIosp ( ) ; return ( iosp != null && iosp instanceof BufrIosp2 ) ? true : null ; }


Input: set current value - no event [CODESPLIT] private void setSelectedIndex ( int idx ) { if ( zAxis == null ) return ; eventOK = false ; currentIdx = idx ; slider . setValue ( world2slider ( zAxis . getCoordValue ( currentIdx ) ) ) ; eventOK = true ; }


Input:
Push Parse input from external lexer [CODESPLIT] public int push_parse ( int yylextoken , Object yylexval ) throws DapException , DapException { if ( ! this . push_parse_initialized ) { push_parse_initialize ( ) ; yycdebug ( "Starting parse\n" ) ; yyerrstatus_ = 0 ; } else label = YYGETTOKEN ; boolean push_token_consumed = true ; for ( ; ; ) switch ( label ) { /* New state.  Unlike in the C/C++ skeletons, the state is already
           pushed when we come here.  */ case YYNEWSTATE : yycdebug ( "Entering state " + yystate + "\n" ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; /* Accept?  */ if ( yystate == yyfinal_ ) { label = YYACCEPT ; break ; } /* Take a decision.  First try without lookahead.  */ yyn = yypact_ [ yystate ] ; if ( yy_pact_value_is_default_ ( yyn ) ) { label = YYDEFAULT ; break ; } /* Fall Through */ case YYGETTOKEN : /* Read a lookahead token.  */ if ( yychar == yyempty_ ) { if ( ! push_token_consumed ) return YYPUSH_MORE ; yycdebug ( "Reading a token: " ) ; yychar = yylextoken ; yylval = yylexval ; push_token_consumed = false ; } /* Convert token to internal form.  */ if ( yychar <= Lexer . EOF ) { yychar = yytoken = Lexer . EOF ; yycdebug ( "Now at end of input.\n" ) ; } else { yytoken = yytranslate_ ( yychar ) ; yy_symbol_print ( "Next token is" , yytoken , yylval ) ; } /* If the proper action on seeing token YYTOKEN is to reduce or to
           detect an error, take that action.  */ yyn += yytoken ; if ( yyn < 0 || yylast_ < yyn || yycheck_ [ yyn ] != yytoken ) label = YYDEFAULT ; /* <= 0 means reduce or error.  */ else if ( ( yyn = yytable_ [ yyn ] ) <= 0 ) { if ( yy_table_value_is_error_ ( yyn ) ) label = YYERRLAB ; else { yyn = - yyn ; label = YYREDUCE ; } } else { /* Shift the lookahead token.  */ yy_symbol_print ( "Shifting" , yytoken , yylval ) ; /* Discard the token being shifted.  */ yychar = yyempty_ ; /* Count tokens shifted since error; after three, turn off error
               status.  */ if ( yyerrstatus_ > 0 ) -- yyerrstatus_ ; yystate = yyn ; yystack . push ( yystate , yylval ) ; label = YYNEWSTATE ; } break ; /*-----------------------------------------------------------.
      | yydefault -- do the default action for the current state.  |
      `-----------------------------------------------------------*/ case YYDEFAULT : yyn = yydefact_ [ yystate ] ; if ( yyn == 0 ) label = YYERRLAB ; else label = YYREDUCE ; break ; /*-----------------------------.
      | yyreduce -- Do a reduction.  |
      `-----------------------------*/ case YYREDUCE : yylen = yyr2_ [ yyn ] ; label = yyaction ( yyn , yystack , yylen ) ; yystate = yystack . stateAt ( 0 ) ; break ; /*------------------------------------.
      | yyerrlab -- here on detecting error |
      `------------------------------------*/ case YYERRLAB : /* If not already recovering from an error, report this error.  */ if ( yyerrstatus_ == 0 ) { ++ yynerrs_ ; if ( yychar == yyempty_ ) yytoken = yyempty_ ; yyerror ( yysyntax_error ( yystate , yytoken ) ) ; } if ( yyerrstatus_ == 3 ) { /* If just tried and failed to reuse lookahead token after an
         error, discard it.  */ if ( yychar <= Lexer . EOF ) { /* Return failure if at end of input.  */ if ( yychar == Lexer . EOF ) { label = YYABORT ; break ; } } else yychar = yyempty_ ; } /* Else will try to reuse lookahead token after shifting the error
           token.  */ label = YYERRLAB1 ; break ; /*-------------------------------------------------.
      | errorlab -- error raised explicitly by YYERROR.  |
      `-------------------------------------------------*/ case YYERROR : /* Do not reclaim the symbols of the rule which action triggered
           this YYERROR.  */ yystack . pop ( yylen ) ; yylen = 0 ; yystate = yystack . stateAt ( 0 ) ; label = YYERRLAB1 ; break ; /*-------------------------------------------------------------.
      | yyerrlab1 -- common code for both syntax error and YYERROR.  |
      `-------------------------------------------------------------*/ case YYERRLAB1 : yyerrstatus_ = 3 ; /* Each real token shifted decrements this.  */ for ( ; ; ) { yyn = yypact_ [ yystate ] ; if ( ! yy_pact_value_is_default_ ( yyn ) ) { yyn += yyterror_ ; if ( 0 <= yyn && yyn <= yylast_ && yycheck_ [ yyn ] == yyterror_ ) { yyn = yytable_ [ yyn ] ; if ( 0 < yyn ) break ; } } /* Pop the current state because it cannot handle the
             * error token.  */ if ( yystack . height == 0 ) { label = YYABORT ; break ; } yystack . pop ( ) ; yystate = yystack . stateAt ( 0 ) ; if ( yydebug > 0 ) yystack . print ( yyDebugStream ) ; } if ( label == YYABORT ) /* Leave the switch.  */ break ; /* Shift the error token.  */ yy_symbol_print ( "Shifting" , yystos_ [ yyn ] , yylval ) ; yystate = yyn ; yystack . push ( yyn , yylval ) ; label = YYNEWSTATE ; break ; /* Accept.  */ case YYACCEPT : this . push_parse_initialized = false ; return YYACCEPT ; /* Abort.  */ case YYABORT : this . push_parse_initialized = false ; return YYABORT ; } }


Input: ( Re - ) Initialize the state of the push parser . [CODESPLIT] public void push_parse_initialize ( ) { /* Lookahead and lookahead in internal form.  */ this . yychar = yyempty_ ; this . yytoken = 0 ; /* State.  */ this . yyn = 0 ; this . yylen = 0 ; this . yystate = 0 ; this . yystack = new YYStack ( ) ; this . label = YYNEWSTATE ; /* Error handling.  */ this . yynerrs_ = 0 ; /* Semantic value of the lookahead.  */ this . yylval = null ; yystack . push ( this . yystate , this . yylval ) ; this . push_parse_initialized = true ; }


Input: Compares elements in a <code > Vector< / code > of <code > BaseType< / code > s and throw a <code > BadSemanticsException< / code > if there are any duplicate elements . [CODESPLIT] static void uniqueNames ( Vector v , String varName , String typeName ) throws BadSemanticsException { String [ ] names = sortedNames ( v ) ; // DEBUG: print out names //for(int i=0; i<names.length; i++) { //  LogStream.err.println("names[" + i + "] = " + names[i]); //} // look for any instance of consecutive names that are == for ( int i = 1 ; i < names . length ; i ++ ) { if ( names [ i - 1 ] . equals ( names [ i ] ) ) { throw new BadSemanticsException ( "The variable `" + names [ i ] + "' is used more than once in " + typeName + " `" + varName + "'" ) ; } } }


Input: Takes a <code > Vector< / code > of <code > BaseType< / code > s retrieves their names into an array of <code > String< / code > s and performs a Quick Sort on that array . [CODESPLIT] static String [ ] sortedNames ( Vector v ) throws BadSemanticsException { String [ ] names = new String [ v . size ( ) ] ; int count = 0 ; for ( Enumeration e = v . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; String tempName = bt . getEncodedName ( ) ; if ( tempName == null ) throw new BadSemanticsException ( bt . getClass ( ) . getName ( ) + " variable with no name" ) ; names [ count ++ ] = tempName ; } // DEBUG: print out names //for(int i=0; i<names.length; i++) { //  LogStream.err.println("names[" + i + "] = " + names[i]); //} // assert that size is correct if ( count != names . length ) throw new IndexOutOfBoundsException ( "Vector size changed unexpectedly" ) ; quickSort ( names , 0 , names . length - 1 ) ; return names ; }


Input: Internal recursive method to perform Quick Sort on name array . [CODESPLIT] static private void quickSort ( String a [ ] , int lo0 , int hi0 ) { int lo = lo0 ; int hi = hi0 ; String mid ; if ( hi0 > lo0 ) { // Arbitrarily establishing partition element as the array midpoint */ //Coverity[FB.IM_AVERAGE_COMPUTATION_COULD_OVERFLOW] mid = a [ ( lo0 + hi0 ) / 2 ] ; // loop through the array until indices cross while ( lo <= hi ) { // find the first element that is >= the partition element // starting from the left index. while ( ( lo < hi0 ) && ( a [ lo ] . compareTo ( mid ) < 0 ) ) ++ lo ; // find an element that is <= the partition element // starting from the right index. while ( ( hi > lo0 ) && ( a [ hi ] . compareTo ( mid ) > 0 ) ) -- hi ; // if the indexes have not crossed, swap if ( lo <= hi ) { swap ( a , lo , hi ) ; ++ lo ; -- hi ; } } // If the right index has not reached the left side of array, // sort the left partition. if ( lo0 < hi ) quickSort ( a , lo0 , hi ) ; // If the left index has not reached the right side of array, // sort the right partition. if ( lo < hi0 ) quickSort ( a , lo , hi0 ) ; } }


Input: Private method to swap two elements in the array [CODESPLIT] static private void swap ( String a [ ] , int i , int j ) { String T ; T = a [ i ] ; a [ i ] = a [ j ] ; a [ j ] = T ; }


Input: This function escapes non - printable characters and quotes . This is used to make <code > printVal< / code > output <code > DString< / code > data in the same way as the C ++ version . Since Java supports Unicode this will need to be altered if it s desired to print <code > DString< / code > as UTF - 8 or some other character encoding . [CODESPLIT] static String escattr ( String s ) { StringBuffer buf = new StringBuffer ( s . length ( ) ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { char c = s . charAt ( i ) ; if ( c == ' ' || ( c >= ' ' && c <= ' ' ) ) { // printable ASCII character buf . append ( c ) ; } else { // non-printable ASCII character: print as unsigned octal integer // padded with leading zeros buf . append ( ' ' ) ; String numVal = Integer . toString ( ( int ) c & 0xFF , 8 ) ; for ( int pad = 0 ; pad < ( 3 - numVal . length ( ) ) ; pad ++ ) buf . append ( ' ' ) ; buf . append ( numVal ) ; } } return buf . toString ( ) ; }


Input: Make MFileOS if file exists otherwise return null [CODESPLIT] static public MFileOS getExistingFile ( String filename ) { if ( filename == null ) return null ; File file = new File ( filename ) ; if ( file . exists ( ) ) return new MFileOS ( file ) ; return null ; }


Input:
Transform a real longitude and latitude into the rotated longitude ( X ) and rotated latitude ( Y ) . [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl destPoint ) { /*
    Tor's algorithm
    public double[] fwd(double[] lonlat)
      return transform(lonlat, lonpole, polerotate, sinDlat);
    */ double [ ] lonlat = new double [ 2 ] ; lonlat [ 0 ] = latlon . getLongitude ( ) ; lonlat [ 1 ] = latlon . getLatitude ( ) ; double [ ] rlonlat = rotate ( lonlat , lonpole , polerotate , sinDlat ) ; if ( destPoint == null ) destPoint = new ProjectionPointImpl ( rlonlat [ 0 ] , rlonlat [ 1 ] ) ; else destPoint . setLocation ( rlonlat [ 0 ] , rlonlat [ 1 ] ) ; if ( show ) System . out . println ( "LatLon= " + latlon + " proj= " + destPoint ) ; return destPoint ; }


Input:
Transform a rotated longitude ( X ) and rotated latitude ( Y ) into a real longitude - latitude pair . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint ppt , LatLonPointImpl destPoint ) { /*
    Tor's algorithm
    public double[] inv(double[] lonlat)
      return rotate(lonlat, -polerotate, -lonpole, -sinDlat);
    */ double [ ] lonlat = new double [ 2 ] ; lonlat [ 0 ] = ppt . getX ( ) ; lonlat [ 1 ] = ppt . getY ( ) ; double [ ] rlonlat = rotate ( lonlat , - polerotate , - lonpole , - sinDlat ) ; if ( destPoint == null ) destPoint = new LatLonPointImpl ( rlonlat [ 1 ] , rlonlat [ 0 ] ) ; else destPoint . set ( rlonlat [ 1 ] , rlonlat [ 0 ] ) ; if ( show ) System . out . println ( "Proj= " + ppt + " latlon= " + destPoint ) ; return destPoint ; }


Input:
Tor s transform algorithm renamed to rotate for clarity [CODESPLIT] private double [ ] rotate ( double [ ] lonlat , double rot1 , double rot2 , double s ) { /* original code
      double e = DEG2RAD * (lonlat[0] - rot1); //east
      double n = DEG2RAD * lonlat[1]; //north
      double cn = Math.cos(n);
      double x = cn * Math.cos(e);
      double y = cn * Math.sin(e);
      double z = Math.sin(n);
      double x2 = cosDlat * x + s * z;
      double z2 = -s * x + cosDlat * z;
      double R = Math.sqrt(x2 * x2 + y * y);
      double e2 = Math.atan2(y, x2);
      double n2 = Math.atan2(z2, R);
      double rlon = RAD2DEG * e2 - rot2;
      double rlat = RAD2DEG * n2;
      return new double[]{rlon, rlat};
     */ double e = Math . toRadians ( lonlat [ 0 ] - rot1 ) ; //east
 double n = Math . toRadians ( lonlat [ 1 ] ) ; //north
 double cn = Math . cos ( n ) ; double x = cn * Math . cos ( e ) ; double y = cn * Math . sin ( e ) ; double z = Math . sin ( n ) ; double x2 = cosDlat * x + s * z ; double z2 = - s * x + cosDlat * z ; double R = Math . sqrt ( x2 * x2 + y * y ) ; double e2 = Math . atan2 ( y , x2 ) ; double n2 = Math . atan2 ( z2 , R ) ; double rlon = Math . toDegrees ( e2 ) - rot2 ; double rlat = Math . toDegrees ( n2 ) ; return new double [ ] { rlon , rlat } ; }


Input: Create an XMLStore reading from the specified filename . [CODESPLIT] static public XMLStore createFromFile ( String fileName , XMLStore storedDefaults ) throws java . io . IOException { File prefsFile = new File ( fileName ) ; // open file if it exists InputStream primIS = null , objIS = null ; if ( prefsFile . exists ( ) && prefsFile . length ( ) > 0 ) { primIS = new BufferedInputStream ( new FileInputStream ( prefsFile ) ) ; objIS = new BufferedInputStream ( new FileInputStream ( prefsFile ) ) ; } if ( debugWhichStore ) System . out . println ( "XMLStore read from file " + fileName ) ; XMLStore store = new XMLStore ( primIS , objIS , storedDefaults ) ; store . prefsFile = prefsFile ; return store ; }


Input: Create an XMLStore reading from an input stream . Because of some peculiariteis you must open the input stream wtice and pass both in . [CODESPLIT] static public XMLStore createFromInputStream ( InputStream is1 , InputStream is2 , XMLStore storedDefaults ) throws java . io . IOException { if ( debugWhichStore ) System . out . println ( "XMLStore read from input stream " + is1 ) ; return new XMLStore ( is1 , is2 , storedDefaults ) ; }


Input: Create a read - only XMLStore reading from the specified resource opened as a Resource stream using the XMLStore ClassLoader . This allows you to find files that are in jar files on the application CLASSPATH . [CODESPLIT] static public XMLStore createFromResource ( String resourceName , XMLStore storedDefaults ) throws java . io . IOException { // open files if exist Class c = XMLStore . class ; InputStream primIS = c . getResourceAsStream ( resourceName ) ; InputStream objIS = c . getResourceAsStream ( resourceName ) ; // debug //    InputStream debugIS = c.getResourceAsStream(fileName); //  System.out.println("Resource stream= "+fileName); //thredds.util.IO.copy(debugIS, System.out); if ( primIS == null ) { //System.out.println("classLoader="+new XMLStore().getClass().getClassLoader()); throw new java . io . IOException ( "XMLStore.createFromResource cant find <" + resourceName + ">" ) ; } if ( debugWhichStore ) System . out . println ( "XMLStore read from resource " + resourceName ) ; return new XMLStore ( primIS , objIS , storedDefaults ) ; }


Input: Convenience routine for creating an XMLStore file in a standard place . [CODESPLIT] static public String makeStandardFilename ( String appName , String storeName ) { // the directory String userHome = null ; try { userHome = System . getProperty ( "user.home" ) ; } catch ( Exception e ) { System . out . println ( "XMLStore.makeStandardFilename: error System.getProperty(user.home) " + e ) ; } if ( null == userHome ) userHome = "." ; String dirFilename = userHome + "/" + appName ; File f = new File ( dirFilename ) ; if ( ! f . exists ( ) ) { boolean ok = f . mkdirs ( ) ; // now ready for file creation in writeXML if ( ! ok ) System . out . println ( "Error creating directories: " + f . getAbsolutePath ( ) ) ; } return dirFilename + "/" + storeName ; }


Input: Save the current state of the Preferences tree to disk using the original filename . The XMLStore must have been constructed from a writeable XML file . [CODESPLIT] public void save ( ) throws java . io . IOException { if ( prefsFile == null ) throw new UnsupportedOperationException ( "XMLStore is read-only" ) ; // get temporary file to write to File prefTemp ; String parentFilename = prefsFile . getParent ( ) ; if ( parentFilename == null ) { prefTemp = File . createTempFile ( "pref" , ".xml" ) ; } else { File parentFile = new File ( parentFilename ) ; prefTemp = File . createTempFile ( "pref" , ".xml" , parentFile ) ; } prefTemp . deleteOnExit ( ) ; // save to the temp file FileOutputStream fos = new FileOutputStream ( prefTemp , false ) ; save ( fos ) ; fos . close ( ) ; // success - rename files Path xmlBackup = Paths . get ( prefsFile . getAbsolutePath ( ) + ".bak" ) ; Path prefsPath = prefsFile . toPath ( ) ; if ( Files . exists ( prefsPath ) ) Files . move ( prefsPath , xmlBackup , StandardCopyOption . REPLACE_EXISTING ) ; Files . move ( prefTemp . toPath ( ) , prefsFile . toPath ( ) , StandardCopyOption . REPLACE_EXISTING ) ; }


Input: Save the current state of the Preferences tree to the given OutputStream . [CODESPLIT] public void save ( OutputStream out ) throws java . io . IOException { outputExceptionMessage = null ; // the OutputMunger strips off the XMLEncoder header OutputMunger bos = new OutputMunger ( out ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( bos , CDM . utf8Charset ) ) ; XMLEncoder beanEncoder = new XMLEncoder ( bos ) ; beanEncoder . setExceptionListener ( new ExceptionListener ( ) { public void exceptionThrown ( Exception exception ) { System . out . println ( "XMLStore.save() got Exception: abort saving the preferences!" ) ; exception . printStackTrace ( ) ; outputExceptionMessage = exception . getMessage ( ) ; } } ) ; pw . printf ( "<?xml version='1.0' encoding='UTF-8'?>%n" ) ; pw . printf ( "<preferences EXTERNAL_XML_VERSION='1.0'>%n" ) ; if ( ! rootPrefs . isUserNode ( ) ) pw . printf ( "  <root type='system'>%n" ) ; else pw . printf ( "  <root type='user'>%n" ) ; Indent indent = new Indent ( 2 ) ; indent . incr ( ) ; writeXmlNode ( bos , pw , rootPrefs , beanEncoder , indent ) ; if ( outputExceptionMessage != null ) throw new IOException ( outputExceptionMessage ) ; pw . printf ( "  </root>%n" ) ; pw . printf ( "</preferences>%n" ) ; pw . flush ( ) ; }


Input: Write out an atomic variable . [CODESPLIT] protected void writeAtomicVariable ( DataCursor data , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) data . getTemplate ( ) ; assert ( this . ce . references ( template ) ) ; DapType basetype = template . getBaseType ( ) ; // get the slices from constraint List < Slice > slices = ce . getConstrainedSlices ( template ) ; if ( slices == null ) throw new DapException ( "Unknown variable: " + template . getFQN ( ) ) ; Object values = data . read ( slices ) ; dst . writeAtomicArray ( basetype , values ) ; }


Input: Write out a scalar or array structure instance [CODESPLIT] protected void writeStructure ( DataCursor data , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) data . getTemplate ( ) ; DapStructure ds = ( DapStructure ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; List < Slice > slices = ce . getConstrainedSlices ( template ) ; Odometer odom = Odometer . factory ( slices ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; DataCursor [ ] instance = ( DataCursor [ ] ) data . read ( index ) ; writeStructure1 ( instance [ 0 ] , dst ) ; } }


Input: Write out a single structure instance [CODESPLIT] protected void writeStructure1 ( DataCursor instance , SerialWriter dst ) throws IOException { assert instance . getScheme ( ) == DataCursor . Scheme . STRUCTURE ; DapVariable template = ( DapVariable ) instance . getTemplate ( ) ; assert ( this . ce . references ( template ) ) ; DapStructure ds = ( DapStructure ) template . getBaseType ( ) ; List < DapVariable > fields = ds . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; if ( ! this . ce . references ( field ) ) continue ; // not in the view DataCursor df = ( DataCursor ) instance . readField ( i ) ; writeVariable ( df , dst ) ; } }


Input: Write out a single or array sequence instance [CODESPLIT] protected void writeSequence ( DataCursor data , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) data . getTemplate ( ) ; DapSequence ds = ( DapSequence ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; List < Slice > slices = ce . getConstrainedSlices ( template ) ; Odometer odom = Odometer . factory ( slices ) ; if ( false ) while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; DataCursor [ ] instance = ( DataCursor [ ] ) data . read ( index ) ; writeSequence1 ( instance [ 0 ] , dst ) ; } else { DataCursor [ ] instances = ( DataCursor [ ] ) data . read ( slices ) ; for ( int i = 0 ; i < instances . length ; i ++ ) { writeSequence1 ( instances [ i ] , dst ) ; } } }


Input: Write out a single Sequence of records ( Eventually use any filter in the DapVariable ) [CODESPLIT] protected void writeSequence1 ( DataCursor instance , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) instance . getTemplate ( ) ; DapSequence seq = ( DapSequence ) template . getBaseType ( ) ; assert ( this . ce . references ( template ) ) ; long nrecs = instance . getRecordCount ( ) ; dst . writeCount ( nrecs ) ; for ( long i = 0 ; i < nrecs ; i ++ ) { DataCursor record = instance . readRecord ( i ) ; writeRecord ( record , dst ) ; } }


Input: Write out a single Record instance . [CODESPLIT] protected void writeRecord ( DataCursor record , SerialWriter dst ) throws IOException { DapVariable template = ( DapVariable ) record . getTemplate ( ) ; DapSequence seq = ( DapSequence ) template . getBaseType ( ) ; List < DapVariable > fields = seq . getFields ( ) ; for ( int i = 0 ; i < fields . size ( ) ; i ++ ) { DapVariable field = fields . get ( i ) ; if ( ! this . ce . references ( field ) ) continue ; // not in the view DataCursor df = ( DataCursor ) record . readField ( i ) ; writeVariable ( df , dst ) ; } }


Input:
Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( _Debug ) System . out . println ( "asciiSeq.toASCII(" + addName + ",'" + rootName + "')  getName(): " + getEncodedName ( ) ) ; //System.out.println("this: " + this + " Has "+allValues.size() + " elements.");
 if ( rootName != null ) rootName += "." + getEncodedName ( ) ; else rootName = getEncodedName ( ) ; pw . print ( toASCIIFlatName ( rootName ) ) ; /*
        for(Enumeration e1 = allValues.elements(); e1.hasMoreElements(); ) {
            // get next instance vector
            Vector v = (Vector)e1.nextElement();
            for(Enumeration e2 = v.elements(); e2.hasMoreElements(); ) {
                // get next instance variable
                BaseType bt = (BaseType)e2.nextElement();

        pw.print(bt.toASCIIFlatName(rootName)+",");
            }
        break;
        }
*/ pw . println ( "" ) ; int i = 0 ; for ( Enumeration e1 = allValues . elements ( ) ; e1 . hasMoreElements ( ) ; ) { int j = 0 ; // get next instance vector
 Vector v = ( Vector ) e1 . nextElement ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable
 toASCII ta = ( toASCII ) e2 . nextElement ( ) ; if ( j > 0 ) pw . print ( ", " ) ; ta . toASCII ( pw , false , rootName , false ) ; j ++ ; } pw . println ( "" ) ; } if ( newLine ) pw . print ( "\n" ) ; }


Input: ////////////////////////////////////// [CODESPLIT] CoverageCoordAxisBuilder subset ( String dependsOn , CoverageCoordAxis . Spacing spacing , int ncoords , double [ ] values ) { assert values != null ; if ( dependsOn != null ) { this . dependenceType = CoverageCoordAxis . DependenceType . dependent ; setDependsOn ( dependsOn ) ; } this . spacing = spacing ; this . ncoords = ncoords ; this . reader = null ; this . values = values ; this . isSubset = true ; return this ; }


Input:
is this a valid BUFR file . [CODESPLIT] static public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { raf . seek ( 0 ) ; if ( ! raf . searchForward ( matcher , 40 * 1000 ) ) return false ; // must find "BUFR" in first 40k
 raf . skipBytes ( 4 ) ; BufrIndicatorSection is = new BufrIndicatorSection ( raf ) ; if ( is . getBufrEdition ( ) > 4 ) return false ; // if(is.getBufrLength() > MAX_MESSAGE_SIZE) return false;
 return ! ( is . getBufrLength ( ) > raf . length ( ) ) ; }


Input: Get the WMO Station ID as a string [CODESPLIT] public String getWmoId ( ) { String wmoID = "" ; if ( ! ( stnm == GempakConstants . IMISSD ) ) { wmoID = String . valueOf ( ( int ) ( stnm / 10 ) ) ; } return wmoID ; }