Input: / * protected Variable findVariableWithStandardNameAndNotDimension ( NetcdfDataset ds String standard_name Dimension outer Formatter errlog ) { for ( Variable v : ds . getVariables () ) { String stdName = ds . findAttValueIgnoreCase ( v CF . STANDARD_NAME null ) ; if (( stdName ! = null ) && stdName . equals ( standard_name ) && v . getRank () > 0 && !v . getDimension ( 0 ) . equals ( outer )) return v ; } return null ; } [CODESPLIT] protected String matchAxisTypeAndDimension ( NetcdfDataset ds , AxisType type , final Dimension outer , final Dimension inner ) { Variable var = CoordSysEvaluator . findCoordByType ( ds , type , new CoordSysEvaluator . Predicate ( ) { @ Override public boolean match ( CoordinateAxis axis ) { return ( ( axis . getRank ( ) == 2 ) && outer . equals ( axis . getDimension ( 0 ) ) && inner . equals ( axis . getDimension ( 1 ) ) ) ; } } ) ; if ( var == null ) return null ; return var . getShortName ( ) ; }


Input: read in the index index raf already open ; return null on failure [CODESPLIT] @ Nullable static Grib1Collection readFromIndex ( String name , RandomAccessFile raf , FeatureCollectionConfig config , org . slf4j . Logger logger ) { Grib1CollectionBuilderFromIndex builder = new Grib1CollectionBuilderFromIndex ( name , config , logger ) ; if ( ! builder . readIndex ( raf ) ) return null ; if ( builder . gc . getFiles ( ) . size ( ) == 0 ) { logger . warn ( "Grib1CollectionBuilderFromIndex {}: has no files, force recreate " , builder . gc . getName ( ) ) ; return null ; } return new Grib1Collection ( builder . gc ) ; }


Input: Add listener : action event sent if apply button is pressed [CODESPLIT] public void addActionListener ( ActionListener l ) { listenerList . add ( java . awt . event . ActionListener . class , l ) ; }


Input: Remove listener [CODESPLIT] public void removeActionListener ( ActionListener l ) { listenerList . remove ( java . awt . event . ActionListener . class , l ) ; }


Input:
Call Field . accept () on all Fields . This puts any edits into the Store and fires PropertyChangeEvents if any values change and sends an ActionEvent to any listeners . [CODESPLIT] public boolean accept ( ) { StringBuffer buff = new StringBuffer ( "Invalid field value " ) ; boolean ok = true ; for ( Object o : flds . values ( ) ) ok &= ( ( Field ) o ) . accept ( buff ) ; if ( ! ok ) { try { JOptionPane . showMessageDialog ( PrefPanel . findActiveFrame ( ) , buff . toString ( ) ) ; } catch ( HeadlessException e ) { } return false ; } /* store the text widths if they exist
    if (storeData != null) {
      Preferences substore = prefs.node("sizes");
      iter = flds.values().iterator();
      while (iter.hasNext()) {
        Field fld = (Field) iter.next();
        JComponent comp = fld.getEditComponent();
        substore.putInt(fld.getName(), (int) comp.getPreferredSize().getWidth());
      }
    } */ fireEvent ( new ActionEvent ( this , 0 , "Accept" ) ) ; return true ; }


Input: Find the field with the specified name . [CODESPLIT] public Field getField ( String name ) { Field fld = flds . get ( name ) ; if ( fld == null ) return null ; return ( fld instanceof FieldResizable ) ? ( ( FieldResizable ) fld ) . getDelegate ( ) : fld ; }


Input: Get current value of the named field [CODESPLIT] public Object getFieldValue ( String name ) { Field fld = getField ( name ) ; if ( fld == null ) throw new IllegalArgumentException ( "no field named " + name ) ; return fld . getValue ( ) ; }


Input: Set the current value of the named field [CODESPLIT] public void setFieldValue ( String name , Object value ) { Field fld = getField ( name ) ; if ( fld == null ) throw new IllegalArgumentException ( "no field named " + name ) ; fld . setValue ( value ) ; }


Input: Add a field created by the user . [CODESPLIT] public Field addField ( Field fld ) { addField ( fld , cursorCol , cursorRow , null ) ; cursorRow ++ ; return fld ; }


Input: Add a boolean field as a checkbox . [CODESPLIT] public Field . CheckBox addCheckBoxField ( String fldName , String label , boolean defValue ) { Field . CheckBox fld = new Field . CheckBox ( fldName , label , defValue , storeData ) ; addField ( fld ) ; return fld ; }


Input: Add a field that edits a date [CODESPLIT] public Field . Date addDateField ( String fldName , String label , Date defValue ) { Field . Date fld = new Field . Date ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }


Input: Add a field that edits a double [CODESPLIT] public Field . Double addDoubleField ( String fldName , String label , double defValue ) { Field . Double fld = new Field . Double ( fldName , label , defValue , - 1 , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }


Input: Add a field that edits an integer [CODESPLIT] public Field . Int addIntField ( String fldName , String label , int defValue ) { Field . Int fld = new Field . Int ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }


Input: Add a password text field . [CODESPLIT] public Field . Password addPasswordField ( String fldName , String label , String defValue ) { Field . Password fld = new Field . Password ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }


Input: Add a text field . [CODESPLIT] public Field . Text addTextField ( String fldName , String label , String defValue ) { Field . Text fld = new Field . Text ( fldName , label , defValue , storeData ) ; addField ( new FieldResizable ( fld , this ) ) ; return fld ; }


Input: Add a text combobox field . [CODESPLIT] public Field . TextCombo addTextComboField ( String fldName , String label , java . util . Collection defValues , int nKeep , boolean editable ) { Field . TextCombo fld = new Field . TextCombo ( fldName , label , defValues , nKeep , storeData ) ; addField ( fld ) ; fld . setEditable ( editable ) ; return fld ; }


Input: Add a TextArea field . [CODESPLIT] public Field . TextArea addTextAreaField ( String fldName , String label , String def , int nrows ) { Field . TextArea fld = new Field . TextArea ( fldName , label , def , nrows , storeData ) ; addField ( fld ) ; return fld ; }


Input: Add a heading at the specified row . this spans all columns [CODESPLIT] public void addHeading ( String heading , int row ) { layoutComponents . add ( new LayoutComponent ( heading , 0 , row , null ) ) ; }


Input: Add a Component . [CODESPLIT] public void addComponent ( Component comp , int col , int row , String constraint ) { layoutComponents . add ( new LayoutComponent ( comp , col , row , constraint ) ) ; }


Input: Add a seperator after the last field added . [CODESPLIT] public void addEmptyRow ( int row , int size ) { layoutComponents . add ( new LayoutComponent ( null , size , row , null ) ) ; }


Input: Call when finished adding components to the PrefPanel . [CODESPLIT] public void finish ( boolean addButtons , String where ) { if ( finished ) throw new IllegalStateException ( "PrefPanel " + name + ": already called finish()" ) ; StringBuilder sbuff = new StringBuilder ( ) ; // column layout, first sort by col Collections . sort ( layoutComponents , new Comparator < LayoutComponent > ( ) { public int compare ( LayoutComponent o1 , LayoutComponent o2 ) { return o1 . col - o2 . col ; } public boolean equals ( Object o1 ) { return o1 == this ; } } ) ; // now create column layout spec and x cell constraint sbuff . setLength ( 0 ) ; int currCol = - 1 ; Iterator iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; if ( lc . col > currCol ) { if ( currCol >= 0 ) sbuff . append ( ", 5dlu, " ) ; else sbuff . append ( "3dlu, " ) ; sbuff . append ( "right:default, 3dlu, default:grow" ) ; currCol += 2 ; } lc . ccLabel . gridX = 2 * lc . col + 2 ; lc . cc . gridX = 2 * lc . col + 4 ; } String colSpec = sbuff . toString ( ) ; if ( debugLayout ) System . out . println ( " column layout = " + colSpec ) ; int ncols = 2 * currCol ; // row layout, first sort by row Collections . sort ( layoutComponents , new Comparator < LayoutComponent > ( ) { public int compare ( LayoutComponent o1 , LayoutComponent o2 ) { return o1 . row - o2 . row ; } public boolean equals ( Object o1 ) { return o1 == this ; } } ) ; // now adjust for any headings, put into y cell constraint int incr = 0 ; iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; if ( ( lc . comp instanceof String ) && ( lc . row > 0 ) ) // its a header, not in first position incr ++ ; // leave space by adding a row lc . cc . gridY = lc . row + incr + 1 ; // adjust downward lc . ccLabel . gridY = lc . cc . gridY ; if ( debugLayout ) System . out . println ( lc + " constraint = " + lc . cc ) ; } // now create row layout spec sbuff . setLength ( 0 ) ; int currRow = - 1 ; iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; while ( lc . row > currRow ) { if ( ( lc . comp instanceof String ) && ( lc . row > 0 ) ) { sbuff . append ( ", 5dlu, default" ) ; } else if ( ( lc . comp == null ) ) { sbuff . append ( ", " ) . append ( lc . col ) . append ( "dlu" ) ; } else { if ( currRow >= 0 ) sbuff . append ( ", " ) ; sbuff . append ( "default" ) ; } currRow ++ ; } } String rowSpec = sbuff . toString ( ) ; if ( debugLayout ) System . out . println ( " row layout = " + rowSpec ) ; // the jgoodies form layout FormLayout layout = new FormLayout ( colSpec , rowSpec ) ; PanelBuilder builder = new PanelBuilder ( layout ) ; builder . setDefaultDialogBorder ( ) ; CellConstraints cc = new CellConstraints ( ) ; // now add each component with correct constraint iter = layoutComponents . iterator ( ) ; while ( iter . hasNext ( ) ) { LayoutComponent lc = ( LayoutComponent ) iter . next ( ) ; if ( lc . comp instanceof Field ) { Field fld = ( Field ) lc . comp ; builder . addLabel ( fld . getLabel ( ) + ":" , lc . ccLabel ) ; Component comp = fld . getEditComponent ( ) ; if ( lc . comp instanceof Field . TextArea ) comp = new JScrollPane ( comp ) ; builder . add ( comp , lc . cc ) ; } else if ( lc . comp instanceof String ) { String header = ( String ) lc . comp ; builder . addSeparator ( header , cc . xyw ( 1 , lc . cc . gridY , ncols ) ) ; } else if ( lc . comp instanceof Component ) { builder . add ( ( Component ) lc . comp , lc . cc ) ; } } mainPanel = builder . getPanel ( ) ; // button panel JPanel buttPanel = new JPanel ( ) ; JButton acceptButton = new JButton ( "Apply" ) ; buttPanel . add ( acceptButton , null ) ; for ( JComponent auxButton : auxButtons ) buttPanel . ( auxButton , null ) ; // button listeners acceptButton . addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { accept ( ) ; } } ) ; setLayout ( new BorderLayout ( ) ) ; add ( mainPanel , BorderLayout . CENTER ) ; if ( addButtons ) { if ( where . equals ( BorderLayout . SOUTH ) ) { JPanel south = new JPanel ( ) ; south . setLayout ( new BoxLayout ( south , BoxLayout . Y_AXIS ) ) ; south . add ( new JSeparator ( SwingConstants . HORIZONTAL ) ) ; south . add ( buttPanel ) ; add ( south , BorderLayout . SOUTH ) ; } else add ( buttPanel , where ) ; } finished = true ; }


Input: thanks to Heinz M . Kabutz [CODESPLIT] static public Frame findActiveFrame ( ) { Frame [ ] frames = JFrame . getFrames ( ) ; for ( Frame frame : frames ) { if ( frame . isVisible ( ) ) return frame ; } return null ; }


Input: Read the value ( parameters are ignored ) . [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws IOException { if ( localVal == null ) // read first time setData ( ncVar . read ( ) ) ; setValue ( localVal ) ; setRead ( true ) ; return ( false ) ; }


Input: Get the cell spacing . An exception is thrown if the cell spacing is not constant . [CODESPLIT] public float getCellSpacing ( ) throws DescriptorException { float [ ] cellRanges = myCELV . getCellRanges ( ) ; // // use the first cell spacing as our expected value // float cellSpacing = cellRanges [ 1 ] - cellRanges [ 0 ] ; // // Check the rest of the cells against the expected value, allowing // 1% fudge // for ( int i = 2 ; i < cellRanges . length ; i ++ ) { float space = cellRanges [ i ] - cellRanges [ i - 1 ] ; if ( ! Misc . nearlyEquals ( space , cellSpacing ) && ( Math . abs ( space / cellSpacing - 1.0 ) > 0.01 ) ) { throw new DescriptorException ( "variable cell spacing" ) ; } } return cellSpacing ; }


Input: Returns the array of Factor - s constituting this dimension . [CODESPLIT] public final Factor [ ] getFactors ( ) { final Factor [ ] factors = new Factor [ _factors . length ] ; System . arraycopy ( _factors , 0 , factors , 0 , factors . length ) ; return factors ; }


Input: Multiplies this dimension by another dimension . [CODESPLIT] protected Factor [ ] mult ( final Dimension that ) { // relys on _factors always sorted final Factor [ ] factors1 = _factors ; final Factor [ ] factors2 = that . _factors ; int i1 = 0 ; int i2 = 0 ; int k = 0 ; Factor [ ] newFactors = new Factor [ factors1 . length + factors2 . length ] ; for ( ; ; ) { if ( i1 == factors1 . length ) { final int n = factors2 . length - i2 ; System . arraycopy ( factors2 , i2 , newFactors , k , n ) ; k += n ; break ; } if ( i2 == factors2 . length ) { final int n = factors1 . length - i1 ; System . arraycopy ( factors1 , i1 , newFactors , k , n ) ; k += n ; break ; } final Factor f1 = factors1 [ i1 ] ; final Factor f2 = factors2 [ i2 ] ; final int comp = f1 . getID ( ) . compareTo ( f2 . getID ( ) ) ; if ( comp < 0 ) { newFactors [ k ++ ] = f1 ; i1 ++ ; } else if ( comp == 0 ) { final int exponent = f1 . getExponent ( ) + f2 . getExponent ( ) ; if ( exponent != 0 ) { newFactors [ k ++ ] = new Factor ( f1 , exponent ) ; } i1 ++ ; i2 ++ ; } else { newFactors [ k ++ ] = f2 ; i2 ++ ; } } if ( k < newFactors . length ) { final Factor [ ] tmp = new Factor [ k ] ; System . arraycopy ( newFactors , 0 , tmp , 0 , k ) ; newFactors = tmp ; } return newFactors ; }


Input: Raises this dimension to a power . [CODESPLIT] protected Factor [ ] pow ( final int power ) { Factor [ ] factors ; if ( power == 0 ) { factors = new Factor [ 0 ] ; } else { factors = getFactors ( ) ; if ( power != 1 ) { for ( int i = factors . length ; -- i >= 0 ; ) { factors [ i ] = factors [ i ] . pow ( power ) ; } } } return factors ; }


Input: Indicates if this Dimension is the reciprocal of another dimension . [CODESPLIT] public final boolean isReciprocalOf ( final Dimension that ) { final Factor [ ] theseFactors = _factors ; final Factor [ ] thoseFactors = that . _factors ; boolean isReciprocalOf ; if ( theseFactors . length != thoseFactors . length ) { isReciprocalOf = false ; } else { int i ; for ( i = theseFactors . length ; -- i >= 0 ; ) { if ( ! theseFactors [ i ] . isReciprocalOf ( thoseFactors [ i ] ) ) { break ; } } isReciprocalOf = i < 0 ; } return isReciprocalOf ; }


Input: Indicates if this dimension is dimensionless . A dimension is dimensionless if it has no Factor - s or if all Factor - s are themselves dimensionless . [CODESPLIT] public final boolean isDimensionless ( ) { for ( int i = _factors . length ; -- i >= 0 ; ) { if ( ! _factors [ i ] . isDimensionless ( ) ) { return false ; } } return true ; }


Input: wml2 : Collection / wml2 : observationMember [CODESPLIT] public static OMObservationPropertyType initObservationMember ( OMObservationPropertyType observationMember , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { // om:OM_Observation NcOMObservationType . initOmObservation ( observationMember . addNewOMObservation ( ) , stationFeat , dataVar ) ; return observationMember ; }


Input:
/ * Notify all listeners that have registered interest for notification on this event type . The event instance is lazily created using the parameters passed into the fire method . [CODESPLIT] protected void fireTreeNodesChanged ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { // Guaranteed to return a non-null array
 Object [ ] listeners = listenerList . getListenerList ( ) ; TreeModelEvent e = null ; // Process the listeners last to first, notifying
 // those that are interested in this event
 for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == TreeModelListener . class ) { // Lazily create the event:
 if ( e == null ) e = new TreeModelEvent ( source , path , childIndices , children ) ; ( ( TreeModelListener ) listeners [ i + 1 ] ) . treeNodesChanged ( e ) ; } } }


Input:
/ * Notify all listeners that have registered interest for notification on this event type . The event instance is lazily created using the parameters passed into the fire method . [CODESPLIT] protected void fireTreeNodesInserted ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { // Guaranteed to return a non-null array
 Object [ ] listeners = listenerList . getListenerList ( ) ; TreeModelEvent e = null ; // Process the listeners last to first, notifying
 // those that are interested in this event
 for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == TreeModelListener . class ) { // Lazily create the event:
 if ( e == null ) e = new TreeModelEvent ( source , path , childIndices , children ) ; ( ( TreeModelListener ) listeners [ i + 1 ] ) . treeNodesInserted ( e ) ; } } }


Input:
/ * Notify all listeners that have registered interest for notification on this event type . The event instance is lazily created using the parameters passed into the fire method . [CODESPLIT] protected void fireTreeNodesRemoved ( Object source , Object [ ] path , int [ ] childIndices , Object [ ] children ) { // Guaranteed to return a non-null array
 Object [ ] listeners = listenerList . getListenerList ( ) ; TreeModelEvent e = null ; // Process the listeners last to first, notifying
 // those that are interested in this event
 for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 ) { if ( listeners [ i ] == TreeModelListener . class ) { // Lazily create the event:
 if ( e == null ) e = new TreeModelEvent ( source , path , childIndices , children ) ; ( ( TreeModelListener ) listeners [ i + 1 ] ) . treeNodesRemoved ( e ) ; } } }


Input:
Persist info ( ncoords coordValues ) from joinExisting since that can be expensive to recreate . [CODESPLIT] public void persistWrite ( ) throws IOException { if ( diskCache2 == null ) return ; String cacheName = getCacheName ( ) ; if ( cacheName == null ) return ; if ( cacheName . startsWith ( "file:" ) ) // LOOK
 cacheName = cacheName . substring ( 5 ) ; File cacheFile = diskCache2 . getCacheFile ( cacheName ) ; if ( cacheFile == null ) throw new IllegalStateException ( ) ; // only write out if something changed after the cache file was last written, or if the file has been deleted
 if ( ! cacheDirty && cacheFile . exists ( ) ) return ; FileChannel channel = null ; try { File dir = cacheFile . getParentFile ( ) ; if ( ! dir . exists ( ) ) { if ( ! dir . mkdirs ( ) ) logger . error ( "Cant make cache directory= " + cacheFile ) ; } // Get a file channel for the file
 FileOutputStream fos = new FileOutputStream ( cacheFile ) ; channel = fos . getChannel ( ) ; // Try acquiring the lock without blocking. This method returns
 // null or throws an exception if the file is already locked.
 FileLock lock ; try { lock = channel . tryLock ( ) ; } catch ( OverlappingFileLockException e ) { // File is already locked in this thread or virtual machine
 return ; // give up
 } if ( lock == null ) return ; PrintWriter out = new PrintWriter ( new OutputStreamWriter ( fos , CDM . utf8Charset ) ) ; out . print ( "<?xml version='1.0' encoding='UTF-8'?>\n" ) ; out . print ( "<aggregation xmlns='http://www.unidata.ucar.edu/namespaces/netcdf/ncml-2.2' version='3' " ) ; out . print ( "type='" + type + "' " ) ; if ( dimName != null ) out . print ( "dimName='" + dimName + "' " ) ; if ( datasetManager . getRecheck ( ) != null ) out . print ( "recheckEvery='" + datasetManager . getRecheck ( ) + "' " ) ; out . print ( ">\n" ) ; List < Dataset > nestedDatasets = getDatasets ( ) ; for ( Dataset dataset : nestedDatasets ) { DatasetOuterDimension dod = ( DatasetOuterDimension ) dataset ; if ( dod . getId ( ) == null ) logger . warn ( "id is null" ) ; out . print ( "  <netcdf id='" + dod . getId ( ) + "' " ) ; out . print ( "ncoords='" + dod . getNcoords ( null ) + "' >\n" ) ; for ( CacheVar pv : cacheList ) { Array data = pv . getData ( dod . getId ( ) ) ; if ( data != null ) { out . print ( "    <cache varName='" + pv . varName + "' >" ) ; while ( data . hasNext ( ) ) out . printf ( "%s " , data . next ( ) ) ; out . print ( "</cache>\n" ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( " wrote array = " + pv . varName + " nelems= " + data . getSize ( ) + " for " + dataset . getLocation ( ) ) ; } } out . print ( "  </netcdf>\n" ) ; } out . print ( "</aggregation>\n" ) ; out . close ( ) ; // this also closes the  channel and releases the lock
 long time = datasetManager . getLastScanned ( ) ; if ( time == 0 ) time = System . currentTimeMillis ( ) ; // no scans (eg all static) will have a 0
 if ( ! cacheFile . setLastModified ( time ) ) logger . warn ( "FAIL to set lastModified on {}" , cacheFile . getPath ( ) ) ; cacheDirty = false ; if ( logger . isDebugEnabled ( ) ) logger . debug ( "Aggregation persisted = " + cacheFile . getPath ( ) + " lastModified= " + new Date ( datasetManager . getLastScanned ( ) ) ) ; } finally { if ( channel != null ) channel . close ( ) ; } }


Input:
read info from the persistent XML file if it exists [CODESPLIT] protected void persistRead ( ) { if ( diskCache2 == null ) return ; String cacheName = getCacheName ( ) ; if ( cacheName == null ) return ; if ( cacheName . startsWith ( "file:" ) ) // LOOK
 cacheName = cacheName . substring ( 5 ) ; File cacheFile = diskCache2 . getCacheFile ( cacheName ) ; if ( cacheFile == null ) throw new IllegalStateException ( ) ; if ( ! cacheFile . exists ( ) ) return ; long lastWritten = cacheFile . lastModified ( ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( " Try to Read cache {} " + cacheFile . getPath ( ) ) ; Element aggElem ; try { aggElem = ucar . nc2 . util . xml . Parse . readRootElement ( "file:" + cacheFile . getPath ( ) ) ; } catch ( IOException e ) { if ( debugCache ) System . out . println ( " No cache for " + cacheName + " - " + e . getMessage ( ) ) ; return ; } String version = aggElem . getAttributeValue ( "version" ) ; if ( ( version == null ) || ! version . equals ( "3" ) ) return ; // dont read old cache files, recreate
 // use a map to find datasets to avoid O(n**2) searching
 Map < String , Dataset > map = new HashMap < String , Dataset > ( ) ; for ( Dataset ds : getDatasets ( ) ) { map . put ( ds . getId ( ) , ds ) ; } List < Element > ncList = aggElem . getChildren ( "netcdf" , Catalog . ncmlNS ) ; for ( Element netcdfElemNested : ncList ) { String id = netcdfElemNested . getAttributeValue ( "id" ) ; DatasetOuterDimension dod = ( DatasetOuterDimension ) map . get ( id ) ; if ( null == dod ) { // this should mean that the dataset has been deleted. so not a problem
 if ( logger . isDebugEnabled ( ) ) logger . debug ( " have cache but no dataset= {}" , id ) ; continue ; } if ( logger . isDebugEnabled ( ) ) logger . debug ( " use cache for dataset= {}" , id ) ; MFile mfile = dod . getMFile ( ) ; if ( mfile != null && mfile . getLastModified ( ) > lastWritten ) { // skip datasets that have changed
 if ( logger . isDebugEnabled ( ) ) logger . debug ( " dataset was changed= {}" , mfile ) ; continue ; } if ( dod . ncoord == 0 ) { String ncoordsS = netcdfElemNested . getAttributeValue ( "ncoords" ) ; try { dod . ncoord = Integer . parseInt ( ncoordsS ) ; if ( logger . isDebugEnabled ( ) ) logger . debug ( " Read the cache; ncoords = {}" , dod . ncoord ) ; } catch ( NumberFormatException e ) { logger . error ( "bad ncoord attribute on dataset=" + id ) ; } } // if (dod.coordValue != null) continue; // allow ncml to override
 List < Element > cacheElemList = netcdfElemNested . getChildren ( "cache" , Catalog . ncmlNS ) ; for ( Element cacheElemNested : cacheElemList ) { String varName = cacheElemNested . getAttributeValue ( "varName" ) ; CacheVar pv = findCacheVariable ( varName ) ; if ( pv != null ) { String sdata = cacheElemNested . getText ( ) ; if ( sdata . length ( ) == 0 ) continue ; if ( logger . isDebugEnabled ( ) ) logger . debug ( " read data for var = " + varName + " size= " + sdata . length ( ) ) ; //long start = System.nanoTime();
 String [ ] vals = sdata . split ( " " ) ; //double took = .001 * .001 * .001 * (System.nanoTime() - start);
 //if (debugPersist) System.out.println("  split took = " + took + " sec; ");
 try { //start = System.nanoTime();
 Array data = Array . makeArray ( pv . dtype , vals ) ; //took = .001 * .001 * .001 * (System.nanoTime() - start);
 //if (debugPersist) System.out.println("  makeArray took = " + took + " sec nelems= "+data.getSize());
 pv . putData ( id , data ) ; countCacheUse ++ ; } catch ( Exception e ) { logger . warn ( "Error reading cached data " , e ) ; } } else { logger . warn ( "not a cache var=" + varName ) ; } } } }


Input: has the name getCacheName () [CODESPLIT] private String getCacheName ( ) { String cacheName = ncDataset . getLocation ( ) ; if ( cacheName == null ) cacheName = ncDataset . getCacheName ( ) ; return cacheName ; }


Input: Make a key from ( center subcenter version ) that provides correct sort order . [CODESPLIT] static int makeKey ( int center , int subcenter , int version ) { if ( center < 0 ) center = 255 ; if ( subcenter < 0 ) subcenter = 255 ; if ( version < 0 ) version = 255 ; return center * 1000 * 1000 + subcenter * 1000 + version ; }


Input: Get a Grib1ParamTables object optionally specifying a parameter table or lookup table specific to this dataset . [CODESPLIT] public static Grib1ParamTables factory ( String paramTablePath , String lookupTablePath ) throws IOException { if ( paramTablePath == null && lookupTablePath == null ) return new Grib1ParamTables ( ) ; Lookup lookup = null ; Grib1ParamTableReader override = null ; Grib1ParamTableReader table ; if ( paramTablePath != null ) { table = localTableHash . get ( paramTablePath ) ; if ( table == null ) { table = new Grib1ParamTableReader ( paramTablePath ) ; localTableHash . put ( paramTablePath , table ) ; override = table ; } } if ( lookupTablePath != null ) { lookup = new Lookup ( ) ; if ( ! lookup . readLookupTable ( lookupTablePath ) ) throw new FileNotFoundException ( "cant read lookup table=" + lookupTablePath ) ; } return new Grib1ParamTables ( lookup , override ) ; }


Input: Get a Grib1Tables object optionally specifiying a parameter table in XML specific to this dataset . [CODESPLIT] public static Grib1ParamTables factory ( org . jdom2 . Element paramTableElem ) { if ( paramTableElem == null ) return new Grib1ParamTables ( ) ; return new Grib1ParamTables ( null , new Grib1ParamTableReader ( paramTableElem ) ) ; }


Input:
Debugging only [CODESPLIT] public Grib1ParamTableReader getParameterTable ( int center , int subcenter , int tableVersion ) { Grib1ParamTableReader result = null ; if ( lookup != null ) result = lookup . getParameterTable ( center , subcenter , tableVersion ) ; if ( result == null ) result = standardLookup . getParameterTable ( center , subcenter , tableVersion ) ; // standard tables
 return result ; }


Input: Add all tables in list to standard tables [CODESPLIT] public static boolean addParameterTableLookup ( String lookupFilename ) throws IOException { Lookup lookup = new Lookup ( ) ; if ( ! lookup . readLookupTable ( lookupFilename ) ) return false ; synchronized ( lock ) { standardLookup . tables . addAll ( standardTablesStart , lookup . tables ) ; standardTablesStart += lookup . tables . size ( ) ; } return true ; }


Input: Add table to standard tables for a specific center subcenter and version . [CODESPLIT] public static void addParameterTable ( int center , int subcenter , int tableVersion , String tableFilename ) { Grib1ParamTableReader table = new Grib1ParamTableReader ( center , subcenter , tableVersion , tableFilename ) ; synchronized ( lock ) { standardLookup . tables . add ( standardTablesStart , table ) ; standardTablesStart ++ ; } }


Input: Multiply this unit by another unit . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { if ( ! that . isDimensionless ( ) ) { throw new MultiplyException ( that ) ; } return that instanceof ScaledUnit ? new ScaledUnit ( ( ( ScaledUnit ) that ) . getScale ( ) , this ) : this ; }


Input: Divide this unit by another unit . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws DivideException { if ( ! that . isDimensionless ( ) ) { throw new DivideException ( that ) ; } return that instanceof ScaledUnit ? new ScaledUnit ( 1.0 / ( ( ScaledUnit ) that ) . getScale ( ) , this ) : this ; }


Input: Raise this unit to a power . [CODESPLIT] @ Override protected Unit myRaiseTo ( final int power ) throws RaiseException { if ( power == 0 ) { return DerivedUnitImpl . DIMENSIONLESS ; } if ( power == 1 ) { return this ; } throw new RaiseException ( this ) ; }


Input: Converts values in this unit to the equivalent values in the convertible derived unit . [CODESPLIT] public float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = ( float ) ( Math . exp ( input [ i ] * lnBase ) ) ; } return reference . toDerivedUnit ( output , output ) ; }


Input: Converts values in the convertible derived unit to the equivalent values in this unit . [CODESPLIT] public float [ ] fromDerivedUnit ( final float [ ] input , final float [ ] output ) throws ConversionException { reference . fromDerivedUnit ( input , output ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] = ( float ) ( Math . log ( output [ i ] ) / lnBase ) ; } return output ; }


Input: Is this a valid file? [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { // quick test raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . seek ( 0 ) ; String got = raf . readString ( V5D . length ( ) ) ; if ( got . equals ( V5D ) ) { return true ; } else { // more rigorous test V5DStruct vv ; try { vv = V5DStruct . v5dOpenFile ( raf ) ; } catch ( BadFormException bfe ) { vv = null ; } return vv != null ; } }


Input: Open the service provider for reading . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; if ( unitTable == null ) { initUnitTable ( ) ; } if ( v5dstruct == null ) { makeFile ( raf , ncfile , cancelTask ) ; } }


Input: Make the netcdf file [CODESPLIT] private void makeFile ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { ncfile . empty ( ) ; int [ ] sizes = new int [ 5 ] ; int [ ] map_proj = new int [ 1 ] ; String [ ] varnames = new String [ MAXVARS ] ; String [ ] varunits = new String [ MAXVARS ] ; int [ ] n_levels = new int [ MAXVARS ] ; int [ ] vert_sys = new int [ 1 ] ; float [ ] vertargs = new float [ MAXVERTARGS ] ; double [ ] times = new double [ MAXTIMES ] ; float [ ] projargs = new float [ MAXPROJARGS ] ; try { v5dstruct = V5DStruct . v5d_open ( raf , sizes , n_levels , varnames , varunits , map_proj , projargs , vert_sys , vertargs , times ) ; } catch ( BadFormException bfe ) { throw new IOException ( "Vis5DIosp.makeFile: bad file " + bfe . getMessage ( ) ) ; } if ( sizes [ 0 ] < 1 ) { throw new IOException ( "Vis5DIosp.makeFile: bad file" ) ; } int nr = sizes [ 0 ] ; int nc = sizes [ 1 ] ; int nl = sizes [ 2 ] ; int ntimes = sizes [ 3 ] ; int nvars = sizes [ 4 ] ; // System.out.println("nr: "+nr); // System.out.println("nc: "+nc); // System.out.println("nl: "+nl); // System.out.println("ntimes: "+ntimes); // System.out.println("nvars: "+nvars); Dimension time = new Dimension ( TIME , ntimes , true ) ; Dimension row = new Dimension ( ROW , nr , true ) ; Dimension col = new Dimension ( COLUMN , nc , true ) ; ncfile . addDimension ( null , time ) ; ncfile . addDimension ( null , row ) ; ncfile . addDimension ( null , col ) ; // time Variable timeVar = new Variable ( ncfile , null , null , TIME ) ; timeVar . setDataType ( DataType . DOUBLE ) ; timeVar . setDimensions ( TIME ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , "seconds since 1900-01-01 00:00:00" ) ) ; timeVar . addAttribute ( new Attribute ( "long_name" , TIME ) ) ; timeVar . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Time . toString ( ) ) ) ; Array varArray = new ArrayDouble . D1 ( ntimes ) ; for ( int i = 0 ; i < ntimes ; i ++ ) { ( ( ArrayDouble . D1 ) varArray ) . set ( i , times [ i ] ) ; } timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; // rows and columns Variable rowVar = new Variable ( ncfile , null , null , ROW ) ; rowVar . setDataType ( DataType . INT ) ; rowVar . setDimensions ( ROW ) ; varArray = new ArrayInt . D1 ( nr , false ) ; for ( int i = 0 ; i < nr ; i ++ ) { ( ( ArrayInt . D1 ) varArray ) . set ( i , i ) ; } rowVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , rowVar ) ; Variable colVar = new Variable ( ncfile , null , null , COLUMN ) ; colVar . setDataType ( DataType . INT ) ; colVar . setDimensions ( COLUMN ) ; varArray = new ArrayInt . D1 ( nc , false ) ; for ( int i = 0 ; i < nc ; i ++ ) { ( ( ArrayInt . D1 ) varArray ) . set ( i , i ) ; } colVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , colVar ) ; // sanity check on levels Hashtable < Integer , Object > var_table = new Hashtable <> ( ) ; boolean have3D = false ; for ( int i = 0 ; i < nvars ; i ++ ) { int nlevs = n_levels [ i ] ; if ( ! have3D && ( nlevs > 1 ) ) { have3D = true ; } var_table . put ( nlevs , new Object ( ) ) ; } int n_var_groups = var_table . size ( ) ; if ( n_var_groups > 2 ) { throw new IOException ( "Vis5DIosp.makeFile: more than two variable groups by n_levels" ) ; } else if ( n_var_groups == 0 ) { throw new IOException ( "Vis5DIosp.makeFile: number of variable groups == 0" ) ; } Variable vert = null ; if ( have3D ) { Dimension lev = new Dimension ( LEVEL , nl , true ) ; ncfile . addDimension ( null , lev ) ; vert = makeVerticalVariable ( vert_sys [ 0 ] , nl , vertargs ) ; if ( vert != null ) { ncfile . addVariable ( null , vert ) ; } } varTable = new Hashtable <> ( ) ; String dim3D = TIME + " " + LEVEL + " " + COLUMN + " " + ROW ; String dim2D = TIME + " " + COLUMN + " " + ROW ; //String coords3D = TIME + " " + vert.getName() + " " + LAT + " " + LON; String coords3D = "unknown" ; if ( vert != null ) { coords3D = TIME + " Height " + LAT + " " + LON ; } String coords2D = TIME + " " + LAT + " " + LON ; for ( int i = 0 ; i < nvars ; i ++ ) { Variable v = new Variable ( ncfile , null , null , varnames [ i ] ) ; if ( n_levels [ i ] > 1 ) { v . setDimensions ( dim3D ) ; v . addAttribute ( new Attribute ( CF . COORDINATES , coords3D ) ) ; } else { v . setDimensions ( dim2D ) ; v . addAttribute ( new Attribute ( CF . COORDINATES , coords2D ) ) ; } v . setDataType ( DataType . FLOAT ) ; String units = varunits [ i ] . trim ( ) ; if ( units . equals ( "" ) ) { // see if its in the unitTable String key = varnames [ i ] . trim ( ) . toLowerCase ( ) ; units = unitTable . get ( key ) ; } if ( units != null ) { v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; } // TODO: do two vars with the same name have different values? // check agaist duplicat variable names if ( varTable . get ( v ) == null ) { varTable . put ( v , i ) ; ncfile . addVariable ( null , v ) ; } } double [ ] [ ] proj_args = Set . floatToDouble ( new float [ ] [ ] { projargs } ) ; addLatLonVariables ( map_proj [ 0 ] , proj_args [ 0 ] , nr , nc ) ; // Vis5DGridDefRecord gridDef = new Vis5DGridDefRecord(map_proj[0], proj_args[0], nr, nc); ncfile . addAttribute ( null , new Attribute ( "Conventions" , "CF-1.0" ) ) ; ncfile . finish ( ) ; }


Input: Read the data for the variable [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { // long startTime = System.currentTimeMillis(); Integer varIdx = varTable . get ( v2 ) ; if ( varIdx == null ) { throw new IOException ( "unable to find variable index" ) ; } int count = 0 ; int [ ] shape = v2 . getShape ( ) ; boolean haveZ = shape . length == 4 ; int nt = shape [ count ++ ] ; int nz = haveZ ? shape [ count ++ ] : 1 ; int ny = shape [ count ++ ] ; int nx = shape [ count ] ; count = 0 ; Range timeRange = section . getRange ( count ++ ) ; Range zRange = haveZ ? section . getRange ( count ++ ) : null ; Range yRange = section . getRange ( count ++ ) ; Range xRange = section . getRange ( count ) ; int grid_size = nx * ny * nz ; Array dataArray = Array . factory ( DataType . FLOAT , section . getShape ( ) ) ; IndexIterator ii = dataArray . getIndexIterator ( ) ; // loop over time for ( int timeIdx : timeRange ) { float [ ] data = new float [ grid_size ] ; float [ ] ranges = new float [ 2 ] ; try { v5dstruct . v5d_read ( timeIdx , varIdx , ranges , data ) ; } catch ( BadFormException bfe ) { throw new IOException ( "Vis5DIosp.readData: " + bfe . getMessage ( ) ) ; } if ( ( ranges [ 0 ] >= 0.99E30 ) && ( ranges [ 1 ] <= - 0.99E30 ) ) { //range_sets[j] = new Linear1DSet(0.0, 1.0, 255); } else if ( ranges [ 0 ] > ranges [ 1 ] ) { throw new IOException ( "Vis5DIosp.readData: bad read " + v2 . getFullName ( ) ) ; } // invert the rows float [ ] tmp_data = new float [ grid_size ] ; if ( zRange == null ) { int cnt = 0 ; for ( int mm = 0 ; mm < ny ; mm ++ ) { int start = ( mm + 1 ) * nx - 1 ; for ( int nn = 0 ; nn < nx ; nn ++ ) { tmp_data [ cnt ++ ] = data [ start -- ] ; } } } else { int cnt = 0 ; for ( int ll = 0 ; ll < nz ; ll ++ ) { for ( int mm = 0 ; mm < ny ; mm ++ ) { int start = ( ( mm + 1 ) * nx - 1 ) + nx * ny * ll ; for ( int nn = 0 ; nn < nx ; nn ++ ) { tmp_data [ cnt ++ ] = data [ start -- ] ; } } } } data = tmp_data ; // copy the data into the array for ( float aData : data ) { ii . setFloatNext ( aData ) ; } } // long end = System.currentTimeMillis() - startTime; return dataArray ; }


Input: Initialize the unit table . This is used if there are no units in the file . [CODESPLIT] private static void initUnitTable ( ) { unitTable = new Hashtable <> ( ) ; // temperatures unitTable . put ( "t" , "K" ) ; unitTable . put ( "td" , "K" ) ; unitTable . put ( "thte" , "K" ) ; // winds unitTable . put ( "u" , "m/s" ) ; unitTable . put ( "v" , "m/s" ) ; unitTable . put ( "w" , "m/s" ) ; // pressure unitTable . put ( "p" , "hPa" ) ; unitTable . put ( "mmsl" , "hPa" ) ; // moisture unitTable . put ( "rh" , "%" ) ; // misc unitTable . put ( "rhfz" , "%" ) ; unitTable . put ( "zagl" , "m" ) ; }


Input: Create a vertical dimension variable based on the info . Based on visad . data . vis5d . Vis5DVerticalSystem . [CODESPLIT] private Variable makeVerticalVariable ( int vert_sys , int n_levels , float [ ] vert_args ) throws IOException { String vert_unit = null ; String vert_type ; ArrayFloat . D1 data = new ArrayFloat . D1 ( n_levels ) ; AxisType axisType = null ; switch ( vert_sys ) { case ( 0 ) : vert_unit = null ; vert_type = "height" ; break ; case ( 1 ) : case ( 2 ) : vert_unit = "km" ; vert_type = "altitude" ; axisType = AxisType . Height ; break ; case ( 3 ) : vert_unit = "mbar" ; vert_type = "pressure" ; axisType = AxisType . Pressure ; break ; default : throw new IOException ( "vert_sys unknown" ) ; } Variable vertVar = new Variable ( ncfile , null , null , vert_type ) ; vertVar . setDimensions ( LEVEL ) ; vertVar . setDataType ( DataType . FLOAT ) ; if ( vert_unit != null ) { vertVar . addAttribute ( new Attribute ( CDM . UNITS , vert_unit ) ) ; } if ( axisType != null ) { vertVar . addAttribute ( new Attribute ( _Coordinate . AxisType , axisType . toString ( ) ) ) ; } switch ( vert_sys ) { case ( 0 ) : case ( 1 ) : for ( int i = 0 ; i < n_levels ; i ++ ) { data . set ( i , vert_args [ 0 ] + vert_args [ 1 ] * i ) ; } break ; case ( 2 ) : // Altitude in km - non-linear for ( int i = 0 ; i < n_levels ; i ++ ) { data . set ( i , vert_args [ i ] ) ; } break ; case ( 3 ) : // heights of pressure surfaces in km - non-linear try { Vis5DVerticalSystem . Vis5DVerticalCoordinateSystem vert_cs = new Vis5DVerticalSystem . Vis5DVerticalCoordinateSystem ( ) ; float [ ] [ ] pressures = new float [ 1 ] [ n_levels ] ; System . arraycopy ( vert_args , 0 , pressures [ 0 ] , 0 , n_levels ) ; for ( int i = 0 ; i < n_levels ; i ++ ) { pressures [ 0 ] [ i ] *= 1000 ; // km->m } pressures = vert_cs . fromReference ( pressures ) ; // convert to pressures for ( int i = 0 ; i < n_levels ; i ++ ) { data . set ( i , pressures [ 0 ] [ i ] ) ; } } catch ( VisADException ve ) { throw new IOException ( "unable to make vertical system" ) ; } break ; } vertVar . setCachedData ( data , false ) ; return vertVar ; }


Input:
Add lat / lon variables to the file [CODESPLIT] private void addLatLonVariables ( int map_proj , double [ ] proj_args , int nr , int nc ) throws IOException { //Vis5DGridDefRecord.printProjArgs(map_proj, proj_args); Vis5DGridDefRecord vgd = new Vis5DGridDefRecord ( map_proj , proj_args , nr , nc ) ; GridHorizCoordSys ghc = new GridHorizCoordSys ( vgd , new Vis5DLookup ( ) , null ) ; Vis5DCoordinateSystem coord_sys ; try { coord_sys = new Vis5DCoordinateSystem ( map_proj , proj_args , nr , nc ) ; Variable lat = new Variable ( ncfile , null , null , LAT ) ; lat . setDimensions ( COLUMN + " " + ROW ) ; lat . setDataType ( DataType . DOUBLE ) ; lat . addAttribute ( new Attribute ( "long_name" , "latitude" ) ) ; lat . addAttribute ( new Attribute ( CDM . UNITS , CDM . LAT_UNITS ) ) ; lat . addAttribute ( new Attribute ( CF . STANDARD_NAME , "latitude" ) ) ; lat . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lat . toString ( ) ) ) ; ncfile . addVariable ( null , lat ) ; Variable lon = new Variable ( ncfile , null , null , LON ) ; lon . setDimensions ( COLUMN + " " + ROW ) ; lon . setDataType ( DataType . DOUBLE ) ; lon . addAttribute ( new Attribute ( CDM . UNITS , CDM . LON_UNITS ) ) ; lon . addAttribute ( new Attribute ( "long_name" , "longitude" ) ) ; lon . addAttribute ( new Attribute ( CF . STANDARD_NAME , "longitude" ) ) ; lon . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Lon . toString ( ) ) ) ; ncfile . addVariable ( null , lon ) ; int [ ] shape = new int [ ] { nc , nr } ; Array latArray = Array . factory ( DataType . DOUBLE , shape ) ; Array lonArray = Array . factory ( DataType . DOUBLE , shape ) ; double [ ] [ ] rowcol = new double [ 2 ] [ nr * nc ] ; for ( int x = 0 ; x < nc ; x ++ ) { for ( int y = 0 ; y < nr ; y ++ ) { int index = x * nr + y ; rowcol [ 0 ] [ index ] = y ; rowcol [ 1 ] [ index ] = x ; } } double [ ] [ ] latlon = coord_sys . toReference ( rowcol ) ; Index latIndex = latArray . getIndex ( ) ; Index lonIndex = lonArray . getIndex ( ) ; /*
            for (int y = 0; y < nr; y++) {
                for (int x = 0; x < nc; x++) {
                    int index = y * nc + x;
            */ for ( int x = 0 ; x < nc ; x ++ ) { for ( int y = 0 ; y < nr ; y ++ ) { int index = x * nr + y ; /*
                    latArray.setDouble(latIndex.set(x, y), latlon[0][index]);
                    lonArray.setDouble(lonIndex.set(x, y), latlon[1][index]);
                    */ latArray . setDouble ( index , latlon [ 0 ] [ index ] ) ; lonArray . setDouble ( index , latlon [ 1 ] [ index ] ) ; } } lat . setCachedData ( latArray , false ) ; lon . setCachedData ( lonArray , false ) ; } catch ( VisADException ve ) { throw new IOException ( "Vis5DIosp.addLatLon: " + ve . getMessage ( ) ) ; } }


Input: Read and set the descriptor name size and endianness and return the entire contents of the descriptor ( including the name and size ) as a byte array . The file position will be left at the beginning of the next descriptor ( or at the end of file ) . [CODESPLIT] protected byte [ ] readDescriptor ( RandomAccessFile file , boolean littleEndianData , String expectedName ) throws DescriptorException { this . file = file ; this . littleEndianData = littleEndianData ; this . expectedName = expectedName ; verbose = getDefaultVerboseState ( expectedName ) ; byte [ ] data ; try { // // find the next descriptor with our expected name // findNext ( file ) ; // // keep track of the start of this descriptor // long startpos = file . getFilePointer ( ) ; // // get the name and descriptor size // byte [ ] header = new byte [ 8 ] ; file . readFully ( header ) ; descName = new String ( header , 0 , 4 , CDM . utf8Charset ) ; int size = grabInt ( header , 4 ) ; // // now back up to the start of the descriptor and read the entire // thing into a byte array // file . seek ( startpos ) ; data = new byte [ size ] ; file . readFully ( data ) ; } catch ( java . io . IOException ex ) { throw new DescriptorException ( ex ) ; } // // now check the name we got against the expected name // if ( ! descName . equals ( expectedName ) ) throw new DescriptorException ( "Got descriptor name '" + descName + "' when expecting name '" + expectedName + "'" ) ; return data ; }


Input: Skip the current DORADE descriptor in the file leaving the file position at the beginning of the next descriptor ( or at the end of file ) . [CODESPLIT] protected static void skipDescriptor ( RandomAccessFile file , boolean littleEndianData ) throws DescriptorException , java . io . IOException { try { file . readFully ( new byte [ 4 ] ) ; // skip name byte [ ] lenBytes = new byte [ 4 ] ; file . readFully ( lenBytes ) ; int descLen = grabInt ( lenBytes , 0 , littleEndianData ) ; file . readFully ( new byte [ descLen - 8 ] ) ; } catch ( java . io . EOFException eofex ) { return ; // just leave the file at EOF } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } }


Input: Return the name of the DORADE descriptor at the current location in the file . The current location will not be changed . [CODESPLIT] protected static String peekName ( RandomAccessFile file ) throws DescriptorException { try { long filepos = file . getFilePointer ( ) ; byte [ ] nameBytes = new byte [ 4 ] ; if ( file . read ( nameBytes ) == - 1 ) return null ; // EOF file . seek ( filepos ) ; return new String ( nameBytes , CDM . utf8Charset ) ; } catch ( IOException ex ) { throw new DescriptorException ( ex ) ; } }


Input: Determine if the given DORADE sweepfile contains little - endian data ( in violation of the DORADE definition ... ) . [CODESPLIT] public static boolean sweepfileIsLittleEndian ( RandomAccessFile file ) throws DescriptorException { int descLen ; try { file . seek ( 0 ) ; // // skip the 4-byte descriptor name // byte [ ] bytes = new byte [ 4 ] ; file . readFully ( bytes ) ; // // get the descriptor length // descLen = file . readInt ( ) ; file . seek ( 0 ) ; } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } return ( descLen < 0 || descLen > 0xffffff ) ; }


Input: Unpack a two - byte integer from the given byte array . [CODESPLIT] protected short grabShort ( byte [ ] bytes , int offset ) { int ndx0 = offset + ( littleEndianData ? 1 : 0 ) ; int ndx1 = offset + ( littleEndianData ? 0 : 1 ) ; // careful that we only allow sign extension on the highest order byte return ( short ) ( bytes [ ndx0 ] << 8 | ( bytes [ ndx1 ] & 0xff ) ) ; }


Input: Unpack a four - byte integer from the given byte array . [CODESPLIT] protected static int grabInt ( byte [ ] bytes , int offset , boolean littleEndianData ) { int ndx0 = offset + ( littleEndianData ? 3 : 0 ) ; int ndx1 = offset + ( littleEndianData ? 2 : 1 ) ; int ndx2 = offset + ( littleEndianData ? 1 : 2 ) ; int ndx3 = offset + ( littleEndianData ? 0 : 3 ) ; // careful that we only allow sign extension on the highest order byte return ( bytes [ ndx0 ] << 24 | ( bytes [ ndx1 ] & 0xff ) << 16 | ( bytes [ ndx2 ] & 0xff ) << 8 | ( bytes [ ndx3 ] & 0xff ) ) ; }


Input: Unpack a four - byte IEEE float from the given byte array . [CODESPLIT] protected float grabFloat ( byte [ ] bytes , int offset ) throws DescriptorException { try { byte [ ] src ; if ( littleEndianData ) { src = new byte [ 4 ] ; src [ 0 ] = bytes [ offset + 3 ] ; src [ 1 ] = bytes [ offset + 2 ] ; src [ 2 ] = bytes [ offset + 1 ] ; src [ 3 ] = bytes [ offset ] ; offset = 0 ; } else { src = bytes ; } DataInputStream stream = new DataInputStream ( new ByteArrayInputStream ( src , offset , 4 ) ) ; return stream . readFloat ( ) ; } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } }


Input: Unpack an eight - byte IEEE float from the given byte array . [CODESPLIT] protected double grabDouble ( byte [ ] bytes , int offset ) throws DescriptorException { try { byte [ ] src ; if ( littleEndianData ) { src = new byte [ 8 ] ; src [ 0 ] = bytes [ offset + 7 ] ; src [ 1 ] = bytes [ offset + 6 ] ; src [ 2 ] = bytes [ offset + 5 ] ; src [ 3 ] = bytes [ offset + 4 ] ; src [ 4 ] = bytes [ offset + 3 ] ; src [ 5 ] = bytes [ offset + 2 ] ; src [ 6 ] = bytes [ offset + 1 ] ; src [ 7 ] = bytes [ offset ] ; offset = 0 ; } else { src = bytes ; } DataInputStream stream = new DataInputStream ( new ByteArrayInputStream ( src , offset , 8 ) ) ; return stream . readDouble ( ) ; } catch ( Exception ex ) { throw new DescriptorException ( ex ) ; } }


Input: Get the default verbose state for new <code > DoradeDescriptor< / code > - s of the given name . [CODESPLIT] public static boolean getDefaultVerboseState ( String descriptorName ) { Boolean classVerboseState = classVerboseStates . get ( descriptorName . toUpperCase ( ) ) ; if ( classVerboseState != null ) return classVerboseState ; else return defaultVerboseState ; }


Input: Gets an instance of this database . [CODESPLIT] public static synchronized StandardUnitDB instance ( ) throws UnitDBException { if ( instance == null ) { try { instance = new StandardUnitDB ( ) ; } catch ( Exception e ) { throw new UnitDBException ( "Couldn't create standard unit-database" , e ) ; } } return instance ; }


Input: Adds a derived unit to the database . [CODESPLIT] private void au ( final String name , final String definition ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { au ( name , definition , null ) ; }


Input: Adds a derived unit to the database . [CODESPLIT] private void au ( final String name , final String definition , final String symbol , final String plural ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { final Unit unit = format . parse ( definition , this ) ; if ( unit == null ) { throw new NoSuchUnitException ( definition ) ; } addUnit ( unit . clone ( UnitName . newUnitName ( name , plural , symbol ) ) ) ; }


Input: Adds an alias for a unit to the database . [CODESPLIT] private void aa ( final String alias , final String name ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { aa ( alias , name , null ) ; }


Input: Adds a symbol for a unit to the database . [CODESPLIT] private void as ( final String symbol , final String name ) throws UnitExistsException , NoSuchUnitException , UnitParseException , SpecificationException , UnitDBException , PrefixDBException , OperationException , NameException , UnitSystemException { addSymbol ( symbol , name ) ; }


Input: Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final UnitDB db = StandardUnitDB . instance ( ) ; System . out . println ( "db.get(\"meter\")=" + db . get ( "meter" ) ) ; System . out . println ( "db.get(\"meters\")=" + db . get ( "meters" ) ) ; System . out . println ( "db.get(\"metre\")=" + db . get ( "metre" ) ) ; System . out . println ( "db.get(\"metres\")=" + db . get ( "metres" ) ) ; System . out . println ( "db.get(\"m\")=" + db . get ( "m" ) ) ; System . out . println ( "db.get(\"newton\")=" + db . get ( "newton" ) ) ; System . out . println ( "db.get(\"Cel\")=" + db . get ( "Cel" ) ) ; System . out . println ( "db.get(\"Roentgen\")=" + db . get ( "Roentgen" ) ) ; System . out . println ( "db.get(\"rad\")=" + db . get ( "rad" ) ) ; System . out . println ( "db.get(\"rd\")=" + db . get ( "rd" ) ) ; System . out . println ( "db.get(\"perches\")=" + db . get ( "perches" ) ) ; System . out . println ( "db.get(\"jiffies\")=" + db . get ( "jiffies" ) ) ; System . out . println ( "db.get(\"foo\")=" + db . get ( "foo" ) ) ; }


Input:
/ try to figure out if we need to add file : to the location when writing [CODESPLIT] static public String canonicalizeWrite ( String location ) { try { URI refURI = URI . create ( location ) ; if ( refURI . isAbsolute ( ) ) return location ; } catch ( Exception e ) { //return "file:" + location;
 } return "file:" + location ; }


Input:
This augments URI . resolve () by also dealing with file : URIs . If baseURi is not a file : scheme then URI . resolve is called . Otherwise the last / is found in the base and the ref is appended to it . <p > For file : baseURLS : only reletive URLS not starting with / are supported . This is apparently different from the behavior of URI . resolve () so may be trouble but it allows NcML absolute location to be specified without the file : prefix . <p / > Example : <pre > base : file : // my / guide / collections / designfaq . ncml ref : sub / my . nc resolved : file : // my / guide / collections / sub / my . nc < / pre > [CODESPLIT] public static String resolve ( String baseUri , String relativeUri ) { if ( ( baseUri == null ) || ( relativeUri == null ) ) return relativeUri ; if ( relativeUri . startsWith ( "file:" ) ) return relativeUri ; // deal with a base file URL
 if ( baseUri . startsWith ( "file:" ) ) { // the case where the reletiveURL is absolute.
 // unfortunately, we may get an Exception
 try { URI uriRelative = URI . create ( relativeUri ) ; if ( uriRelative . isAbsolute ( ) ) return relativeUri ; } catch ( Exception e ) { // empty
 } if ( ( relativeUri . length ( ) > 0 ) && ( relativeUri . charAt ( 0 ) == ' ' ) ) return baseUri + relativeUri ; if ( ( relativeUri . length ( ) > 0 ) && ( relativeUri . charAt ( 0 ) == ' ' ) ) return relativeUri ; baseUri = StringUtil2 . substitute ( baseUri , "\\" , "/" ) ; // assumes forward slash
 int pos = baseUri . lastIndexOf ( ' ' ) ; if ( pos > 0 ) { String baseDir = baseUri . substring ( 0 , pos + 1 ) ; if ( relativeUri . equals ( "." ) ) { return baseDir ; } else { return baseDir + relativeUri ; } } } // non-file URLs
 //relativeUri = canonicalizeRead(relativeUri);
 try { URI relativeURI = URI . create ( relativeUri ) ; if ( relativeURI . isAbsolute ( ) ) return relativeUri ; //otherwise let the URI class resolve it
 URI baseURI = URI . create ( baseUri ) ; URI resolvedURI = baseURI . resolve ( relativeURI ) ; return resolvedURI . toASCIIString ( ) ; } catch ( IllegalArgumentException e ) { return relativeUri ; } }


Input: Factory method for creating a unit converter . [CODESPLIT] public static Converter create ( Unit fromUnit , Unit toUnit ) throws ConversionException { return fromUnit . getConverterTo ( toUnit ) ; }


Input: writing data [CODESPLIT] public void writeRecord ( PointFeature sobs , StructureData sdata ) throws IOException { writeRecord ( sobs . getObservationTime ( ) , sobs . getObservationTimeAsCalendarDate ( ) , sobs . getLocation ( ) , sdata ) ; }


Input: Add listener : ListSelectionEvent sent when a new row is selected [CODESPLIT] public void addListSelectionListener ( ListSelectionListener l ) { listeners . add ( javax . swing . event . ListSelectionListener . class , l ) ; }


Input: Remove listener [CODESPLIT] public void removeListSelectionListener ( ListSelectionListener l ) { listeners . remove ( javax . swing . event . ListSelectionListener . class , l ) ; }


Input: Set the data as a collection of StructureData . [CODESPLIT] public void setStructureData ( List < StructureData > structureData ) throws IOException { dataModel = new StructureDataModel ( structureData ) ; initTable ( dataModel ) ; }


Input: Set the data as a collection of PointFeature . [CODESPLIT] public void setPointFeatureData ( List < PointFeature > obsData ) throws IOException { dataModel = new PointFeatureDataModel ( obsData ) ; initTable ( dataModel ) ; }


Input: Draws all the features that are within the graphics clip rectangle using the previously set displayProjection . [CODESPLIT] public void draw ( java . awt . Graphics2D g , AffineTransform pixelAT ) { g . setColor ( color ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setStroke ( new java . awt . BasicStroke ( 0.0f ) ) ; Rectangle2D clipRect = ( Rectangle2D ) g . getClip ( ) ; Iterator siter = getShapes ( g , pixelAT ) ; while ( siter . hasNext ( ) ) { Shape s = ( Shape ) siter . next ( ) ; Rectangle2D shapeBounds = s . getBounds2D ( ) ; if ( shapeBounds . intersects ( clipRect ) ) g . draw ( s ) ; } }


Input: get the set of shapes to draw convert projections if need be [CODESPLIT] protected Iterator getShapes ( java . awt . Graphics2D g , AffineTransform normal2device ) { if ( shapeList != null ) return shapeList . iterator ( ) ; if ( Debug . isSet ( "projection/LatLonShift" ) ) System . out . println ( "projection/LatLonShift GisFeatureRenderer.getShapes called" ) ; ProjectionImpl dataProject = getDataProjection ( ) ; // a list of GisFeatureAdapter-s List featList = getFeatures ( ) ; shapeList = new ArrayList ( featList . size ( ) ) ; Iterator iter = featList . iterator ( ) ; while ( iter . hasNext ( ) ) { AbstractGisFeature feature = ( AbstractGisFeature ) iter . next ( ) ; Shape shape ; if ( dataProject == null ) shape = feature . getShape ( ) ; else if ( dataProject . isLatLon ( ) ) { // always got to run it through if its lat/lon shape = feature . getProjectedShape ( displayProject ) ; //System.out.println("getShapes dataProject.isLatLon() "+displayProject); } else if ( dataProject == displayProject ) { shape = feature . getShape ( ) ; //System.out.println("getShapes dataProject == displayProject"); } else { shape = feature . getProjectedShape ( dataProject , displayProject ) ; //System.out.println("getShapes dataProject != displayProject"); } shapeList . add ( shape ) ; } return shapeList . iterator ( ) ; }


Input: wml2 : Collection / wml2 : metadata / wml2 : DocumentMetadata [CODESPLIT] public static DocumentMetadataType initDocumentMetadata ( DocumentMetadataType documentMetadata ) { // @gml:id String id = MarshallingUtil . createIdForType ( DocumentMetadataType . class ) ; documentMetadata . setId ( id ) ; // wml2:generationDate DateTime generationDate = MarshallingUtil . fixedGenerationDate ; if ( generationDate == null ) { generationDate = new DateTime ( ) ; // Initialized to "now". } documentMetadata . setGenerationDate ( generationDate . toGregorianCalendar ( ) ) ; return documentMetadata ; }


Input: time ( nruns ntimes ) - > time ( ntimes ) with dependent reftime ( ntime ) coordinate [CODESPLIT] private void makeUniqueTimeCoordinate2D ( NetcdfFile ncfile , Group g , CoordinateTime2D time2D ) { CoordinateRuntime runtime = time2D . getRuntimeCoordinate ( ) ; int countU = 0 ; for ( int run = 0 ; run < time2D . getNruns ( ) ; run ++ ) { CoordinateTimeAbstract timeCoord = time2D . getTimeCoordinate ( run ) ; countU += timeCoord . getSize ( ) ; } int ntimes = countU ; String tcName = time2D . getName ( ) ; ncfile . addDimension ( g , new Dimension ( tcName , ntimes ) ) ; Variable v = ncfile . addVariable ( g , new Variable ( ncfile , g , null , tcName , DataType . DOUBLE , tcName ) ) ; String units = runtime . getUnit ( ) ; // + " since " + runtime.getFirstDate(); v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; v . addAttribute ( new Attribute ( CF . STANDARD_NAME , CF . TIME ) ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , Grib . GRIB_VALID_TIME ) ) ; v . addAttribute ( new Attribute ( CF . CALENDAR , Calendar . proleptic_gregorian . toString ( ) ) ) ; // the data is not generated until asked for to save space if ( ! time2D . isTimeInterval ( ) ) { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . offU , time2D , null ) ) ; } else { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . intvU , time2D , null ) ) ; // bounds for intervals String bounds_name = tcName + "_bounds" ; Variable bounds = ncfile . addVariable ( g , new Variable ( ncfile , g , null , bounds_name , DataType . DOUBLE , tcName + " 2" ) ) ; v . addAttribute ( new Attribute ( CF . BOUNDS , bounds_name ) ) ; bounds . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; bounds . addAttribute ( new Attribute ( CDM . LONG_NAME , "bounds for " + tcName ) ) ; bounds . setSPobject ( new Time2Dinfo ( Time2DinfoType . boundsU , time2D , null ) ) ; } if ( runtime . getNCoords ( ) != 1 ) { // for this case we have to generate a separate reftime, because have to use the same dimension String refName = "ref" + tcName ; if ( g . findVariable ( refName ) == null ) { Variable vref = ncfile . addVariable ( g , new Variable ( ncfile , g , null , refName , DataType . DOUBLE , tcName ) ) ; vref . addAttribute ( new Attribute ( CF . STANDARD_NAME , CF . TIME_REFERENCE ) ) ; vref . addAttribute ( new Attribute ( CDM . LONG_NAME , Grib . GRIB_RUNTIME ) ) ; vref . addAttribute ( new Attribute ( CF . CALENDAR , Calendar . proleptic_gregorian . toString ( ) ) ) ; vref . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; vref . setSPobject ( new Time2Dinfo ( Time2DinfoType . isUniqueRuntime , time2D , null ) ) ; } } }


Input: / * non unique time case 3 ) time ( nruns ntimes ) with reftime ( nruns ) [CODESPLIT] private void makeTimeCoordinate2D ( NetcdfFile ncfile , Group g , CoordinateTime2D time2D , GribCollectionImmutable . Type gctype ) { CoordinateRuntime runtime = time2D . getRuntimeCoordinate ( ) ; int ntimes = time2D . getNtimes ( ) ; String tcName = time2D . getName ( ) ; String dims = runtime . getName ( ) + " " + tcName ; int dimLength = ntimes ; ncfile . addDimension ( g , new Dimension ( tcName , dimLength ) ) ; Variable v = ncfile . addVariable ( g , new Variable ( ncfile , g , null , tcName , DataType . DOUBLE , dims ) ) ; String units = runtime . getUnit ( ) ; // + " since " + runtime.getFirstDate(); v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; v . addAttribute ( new Attribute ( CF . STANDARD_NAME , CF . TIME ) ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , Grib . GRIB_VALID_TIME ) ) ; v . addAttribute ( new Attribute ( CF . CALENDAR , Calendar . proleptic_gregorian . toString ( ) ) ) ; // the data is not generated until asked for to save space if ( ! time2D . isTimeInterval ( ) ) { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . off , time2D , null ) ) ; } else { v . setSPobject ( new Time2Dinfo ( Time2DinfoType . intv , time2D , null ) ) ; // bounds for intervals String bounds_name = tcName + "_bounds" ; Variable bounds = ncfile . addVariable ( g , new Variable ( ncfile , g , null , bounds_name , DataType . DOUBLE , dims + " 2" ) ) ; v . addAttribute ( new Attribute ( CF . BOUNDS , bounds_name ) ) ; bounds . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; bounds . addAttribute ( new Attribute ( CDM . LONG_NAME , "bounds for " + tcName ) ) ; bounds . setSPobject ( new Time2Dinfo ( Time2DinfoType . bounds , time2D , null ) ) ; } }


Input: only for the 2d times [CODESPLIT] private Array makeLazyTime1Darray ( Variable v2 , Time2Dinfo info ) { int length = info . time1D . getSize ( ) ; double [ ] data = new double [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { data [ i ] = Double . NaN ; } // coordinate values switch ( info . which ) { case reftime : CoordinateRuntime rtc = ( CoordinateRuntime ) info . time1D ; int count = 0 ; for ( double val : rtc . getOffsetsInTimeUnits ( ) ) { data [ count ++ ] = val ; } return Array . factory ( DataType . DOUBLE , v2 . getShape ( ) , data ) ; case timeAuxRef : CoordinateTimeAbstract time = ( CoordinateTimeAbstract ) info . time1D ; count = 0 ; List < Double > masterOffsets = gribCollection . getMasterRuntime ( ) . getOffsetsInTimeUnits ( ) ; for ( int masterIdx : time . getTime2runtime ( ) ) { data [ count ++ ] = masterOffsets . get ( masterIdx - 1 ) ; } return Array . factory ( DataType . DOUBLE , v2 . getShape ( ) , data ) ; default : throw new IllegalStateException ( "makeLazyTime1Darray must be reftime or timeAuxRef" ) ; } }


Input: only for the 2d times [CODESPLIT] private Array makeLazyTime2Darray ( Variable coord , Time2Dinfo info ) { CoordinateTime2D time2D = info . time2D ; CalendarPeriod timeUnit = time2D . getTimeUnit ( ) ; int nruns = time2D . getNruns ( ) ; int ntimes = time2D . getNtimes ( ) ; int length = ( int ) coord . getSize ( ) ; if ( info . which == Time2DinfoType . bounds ) { length *= 2 ; } double [ ] data = new double [ length ] ; for ( int i = 0 ; i < length ; i ++ ) { data [ i ] = Double . NaN ; } int count ; // coordinate values switch ( info . which ) { case off : for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTime coordTime = ( CoordinateTime ) time2D . getTimeCoordinate ( runIdx ) ; int timeIdx = 0 ; for ( int val : coordTime . getOffsetSorted ( ) ) { data [ runIdx * ntimes + timeIdx ] = timeUnit . getValue ( ) * val + time2D . getOffset ( runIdx ) ; timeIdx ++ ; } } break ; case offU : count = 0 ; for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTime coordTime = ( CoordinateTime ) time2D . getTimeCoordinate ( runIdx ) ; for ( int val : coordTime . getOffsetSorted ( ) ) { data [ count ++ ] = timeUnit . getValue ( ) * val + time2D . getOffset ( runIdx ) ; } } break ; case intv : for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; int timeIdx = 0 ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ runIdx * ntimes + timeIdx ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; // use upper bounds for coord value timeIdx ++ ; } } break ; case intvU : count = 0 ; for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ count ++ ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; // use upper bounds for coord value } } break ; case is1Dtime : CoordinateRuntime runtime = time2D . getRuntimeCoordinate ( ) ; count = 0 ; for ( double val : runtime . getOffsetsInTimeUnits ( ) ) { // convert to udunits data [ count ++ ] = val ; } break ; case isUniqueRuntime : // the aux runtime coordinate CoordinateRuntime runtimeU = time2D . getRuntimeCoordinate ( ) ; List < Double > runOffsets = runtimeU . getOffsetsInTimeUnits ( ) ; count = 0 ; for ( int run = 0 ; run < time2D . getNruns ( ) ; run ++ ) { CoordinateTimeAbstract timeCoord = time2D . getTimeCoordinate ( run ) ; for ( int time = 0 ; time < timeCoord . getNCoords ( ) ; time ++ ) { data [ count ++ ] = runOffsets . get ( run ) ; } } break ; case bounds : for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; int timeIdx = 0 ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ runIdx * ntimes * 2 + timeIdx ] = timeUnit . getValue ( ) * tinv . getBounds1 ( ) + time2D . getOffset ( runIdx ) ; data [ runIdx * ntimes * 2 + timeIdx + 1 ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; timeIdx += 2 ; } } break ; case boundsU : count = 0 ; for ( int runIdx = 0 ; runIdx < nruns ; runIdx ++ ) { CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) time2D . getTimeCoordinate ( runIdx ) ; for ( TimeCoordIntvValue tinv : timeIntv . getTimeIntervals ( ) ) { data [ count ++ ] = timeUnit . getValue ( ) * tinv . getBounds1 ( ) + time2D . getOffset ( runIdx ) ; data [ count ++ ] = timeUnit . getValue ( ) * tinv . getBounds2 ( ) + time2D . getOffset ( runIdx ) ; } } break ; default : throw new IllegalStateException ( ) ; } return Array . factory ( DataType . DOUBLE , coord . getShape ( ) , data ) ; }


Input: ////////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { long start = System . currentTimeMillis ( ) ; // see if its time2D - then generate data on the fly if ( v2 . getSPobject ( ) instanceof Time2Dinfo ) { Time2Dinfo info = ( Time2Dinfo ) v2 . getSPobject ( ) ; Array data = makeLazyCoordinateData ( v2 , info ) ; Section sectionFilled = Section . fill ( section , v2 . getShape ( ) ) ; return data . sectionNoReduce ( sectionFilled . getRanges ( ) ) ; } try { Array result ; GribCollectionImmutable . VariableIndex vindex = ( GribCollectionImmutable . VariableIndex ) v2 . getSPobject ( ) ; GribDataReader dataReader = GribDataReader . factory ( gribCollection , vindex ) ; SectionIterable sectionIter = new SectionIterable ( section , v2 . getShape ( ) ) ; result = dataReader . readData ( sectionIter ) ; long took = System . currentTimeMillis ( ) - start ; return result ; } catch ( IOException ioe ) { logger . error ( "Failed to readData " , ioe ) ; throw ioe ; } }


Input: LOOK - needs to be a directory or maybe an MFILE collection [CODESPLIT] public void execute ( String filename ) throws IOException { File input = new File ( filename ) ; out . format ( "BufrSplitter on %s length=%d%n" , input . getPath ( ) , input . length ( ) ) ; try ( InputStream is = new FileInputStream ( input ) ) { processStream ( is ) ; } }


Input: process all the bytes in the stream [CODESPLIT] public void processStream ( InputStream is ) throws IOException { int pos = - 1 ; Buffer b = null ; while ( true ) { b = ( pos < 0 ) ? readBuffer ( is ) : readBuffer ( is , b , pos ) ; pos = processBuffer ( b , is ) ; if ( b . done ) break ; } }


Input: read into dest byte array until buffer is full or end of stream [CODESPLIT] private boolean readBuffer ( InputStream is , byte [ ] dest , int start , int want ) throws IOException { int done = 0 ; while ( done < want ) { int got = is . read ( dest , start + done , want - done ) ; if ( got < 0 ) return false ; done += got ; } if ( showRead ) System . out . println ( "Read buffer at " + bytesRead + " len=" + done ) ; bytesRead += done ; return true ; }


Input: read into new Buffer until buffer is full or end of stream [CODESPLIT] private Buffer readBuffer ( InputStream is ) throws IOException { Buffer b = new Buffer ( ) ; int want = BUFFSIZE ; while ( b . have < want ) { int got = is . read ( b . buff , b . have , want - b . have ) ; if ( got < 0 ) { b . done = true ; break ; } b . have += got ; } if ( showRead ) System . out . println ( "Read buffer at " + bytesRead + " len=" + b . have ) ; bytesRead += b . have ; return b ; }


Input: read into new Buffer until buffer is full or end of stream [CODESPLIT] private Buffer readBuffer ( InputStream is , Buffer prev , int pos ) throws IOException { Buffer b = new Buffer ( ) ; // copy remains of last buffer here int remain = prev . have - pos ; //if (remain > BUFFSIZE /2) //  out.format(" remain = "+remain+" bytesRead="+bytesRead); System . arraycopy ( prev . buff , pos , b . buff , 0 , remain ) ; b . have = remain ; int want = BUFFSIZE ; while ( b . have < want ) { int got = is . read ( b . buff , b . have , want - b . have ) ; if ( got < 0 ) { b . done = true ; break ; } b . have += got ; } if ( showRead ) System . out . println ( "Read buffer at " + bytesRead + " len=" + b . have ) ; bytesRead += b . have ; return b ; }


Input:
Get more bytes into buffer . Stop when endSequence is found . [CODESPLIT] private void getMoreBytes ( ) throws IOException { currentOffset = 0 ; // reset current array offset to 0
 int bytesRead = 0 ; // bytes read so far
 int lookingFor = 0 ; // character in endSequence to look for
 for ( ; bytesRead < lineBuf . length ; bytesRead ++ ) { int c = in . read ( ) ; if ( c == - 1 ) break ; // break on EOL and return what we have so far
 lineBuf [ bytesRead ] = ( byte ) c ; if ( lineBuf [ bytesRead ] == endSequence [ lookingFor ] ) { lookingFor ++ ; if ( lookingFor == endSequence . length ) { endFound = true ; break ; } } else if ( lineBuf [ bytesRead ] == endSequence [ 0 ] ) { // CHANGED JC
 lookingFor = 1 ; } else { lookingFor = 0 ; } } bytesRemaining = bytesRead ; // number of bytes we've read
 }


Input:
Reads up to len bytes of data from this input stream into an array of bytes . This method blocks until some input is available . [CODESPLIT] public int read ( byte b [ ] , int off , int len ) throws IOException { if ( len <= 0 ) { return 0 ; } int c = read ( ) ; if ( c == - 1 ) return - 1 ; b [ off ] = ( byte ) c ; // We've read one byte successfully, let's try for more
 int i = 1 ; try { for ( ; i < len ; i ++ ) { c = read ( ) ; if ( c == - 1 ) { break ; } b [ off + i ] = ( byte ) c ; } } catch ( IOException e ) { } return i ; }


Input: Skips over and discards n bytes of data from the input stream . [CODESPLIT] public long skip ( long n ) { if ( bytesRemaining >= n ) { bytesRemaining -= n ; return n ; } else { int oldBytesRemaining = bytesRemaining ; bytesRemaining = 0 ; return oldBytesRemaining ; } }


Input: reading [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile ncfile , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; mySweep = new DoradeSweep ( raf . getRandomAccessFile ( ) ) ; headerParser = new Doradeheader ( ) ; headerParser . read ( mySweep , ncfile , null ) ; ncfile . finish ( ) ; }


Input: Tests this class . [CODESPLIT] public static void main ( String [ ] args ) throws Exception { System . out . println ( "new QuantityDimension() = \"" + new QuantityDimension ( ) + ' ' ) ; QuantityDimension timeDimension = new QuantityDimension ( BaseQuantity . TIME ) ; System . out . println ( "timeDimension = \"" + timeDimension + ' ' ) ; QuantityDimension lengthDimension = new QuantityDimension ( BaseQuantity . LENGTH ) ; System . out . println ( "lengthDimension = \"" + lengthDimension + ' ' ) ; System . out . println ( "lengthDimension.isReciprocalOf(timeDimension) = \"" + lengthDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; QuantityDimension hertzDimension = timeDimension . raiseTo ( - 1 ) ; System . out . println ( "hertzDimension = \"" + hertzDimension + ' ' ) ; System . out . println ( "hertzDimension.isReciprocalOf(timeDimension) = \"" + hertzDimension . isReciprocalOf ( timeDimension ) + ' ' ) ; System . out . println ( "lengthDimension.divideBy(timeDimension) = \"" + lengthDimension . divideBy ( timeDimension ) + ' ' ) ; System . out . println ( "lengthDimension.divideBy(timeDimension).raiseTo(2) = \"" + lengthDimension . divideBy ( timeDimension ) . raiseTo ( 2 ) + ' ' ) ; }


Input: Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array orogArray = readArray ( orogVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; int [ ] shape2D = orogArray . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; Index orogIndex = orogArray . getIndex ( ) ; ArrayDouble . D3 height = new ArrayDouble . D3 ( nz , ny , nx ) ; for ( int z = 0 ; z < nz ; z ++ ) { double az = aArray . getDouble ( aIndex . set ( z ) ) ; double bz = bArray . getDouble ( bIndex . set ( z ) ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { double orog = orogArray . getDouble ( orogIndex . set ( y , x ) ) ; height . set ( z , y , x , az + bz * orog ) ; } } } return height ; }


Input: Get the 1D vertical coordinate array for this time step and point [CODESPLIT] public D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array orogArray = readArray ( orogVar , timeIndex ) ; if ( null == aArray ) { aArray = aVar . read ( ) ; bArray = bVar . read ( ) ; } int nz = ( int ) aArray . getSize ( ) ; Index aIndex = aArray . getIndex ( ) ; Index bIndex = bArray . getIndex ( ) ; Index orogIndex = orogArray . getIndex ( ) ; ArrayDouble . D1 height = new ArrayDouble . D1 ( nz ) ; for ( int z = 0 ; z < nz ; z ++ ) { double az = aArray . getDouble ( aIndex . set ( z ) ) ; double bz = bArray . getDouble ( bIndex . set ( z ) ) ; double orog = orogArray . getDouble ( orogIndex . set ( yIndex , xIndex ) ) ; height . set ( z , az + bz * orog ) ; } return height ; }


Input: Match levels [CODESPLIT] boolean matchLevels ( List < GridRecord > records ) { // first create a new list List < LevelCoord > levelList = new ArrayList < LevelCoord > ( records . size ( ) ) ; for ( GridRecord record : records ) { LevelCoord lc = new LevelCoord ( record . getLevel1 ( ) , record . getLevel2 ( ) ) ; if ( ! levelList . contains ( lc ) ) { levelList . add ( lc ) ; } } Collections . sort ( levelList ) ; if ( positive . equals ( "down" ) ) { Collections . reverse ( levelList ) ; } // gotta equal existing list return levelList . equals ( levels ) ; }


Input: Add this coord as a dimension to the netCDF file [CODESPLIT] void addDimensionsToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( ! isVertDimensionUsed ( ) ) return ; int nlevs = levels . size ( ) ; if ( coordValues != null ) nlevs = coordValues . length ; ncfile . addDimension ( g , new Dimension ( getVariableName ( ) , nlevs , true ) ) ; }


Input:
Add this coord as a variable in the netCDF file [CODESPLIT] void addToNetcdfFile ( NetcdfFile ncfile , Group g ) { if ( ! isVertDimensionUsed ( ) ) { typicalRecord = null ; // allow gc return ; } if ( g == null ) { g = ncfile . getRootGroup ( ) ; } // coordinate axis Variable v = new Variable ( ncfile , g , null , getVariableName ( ) ) ; v . setDataType ( DataType . DOUBLE ) ; String desc = getLevelDesc ( ) ; v . addAttribute ( new Attribute ( "long_name" , desc ) ) ; v . addAttribute ( new Attribute ( "units" , lookup . getLevelUnit ( typicalRecord ) ) ) ; // positive attribute needed for CF-1 Height and Pressure if ( positive != null ) { v . addAttribute ( new Attribute ( "positive" , positive ) ) ; } if ( units != null ) { AxisType axisType ; if ( SimpleUnit . isCompatible ( "millibar" , units ) ) { axisType = AxisType . Pressure ; } else if ( SimpleUnit . isCompatible ( "m" , units ) ) { axisType = AxisType . Height ; } else { axisType = AxisType . GeoZ ; } addExtraAttributes ( v ) ; v . addAttribute ( new Attribute ( _Coordinate . AxisType , axisType . toString ( ) ) ) ; } if ( coordValues == null ) { coordValues = new double [ levels . size ( ) ] ; for ( int i = 0 ; i < levels . size ( ) ; i ++ ) { LevelCoord lc = ( LevelCoord ) levels . get ( i ) ; coordValues [ i ] = lc . mid ; } } Array dataArray = Array . factory ( DataType . DOUBLE , new int [ ] { coordValues . length } , coordValues ) ; v . setDimensions ( getVariableName ( ) ) ; v . setCachedData ( dataArray , true ) ; ncfile . addVariable ( g , v ) ; if ( usesBounds ) { Dimension bd = ucar . nc2 . dataset . DatasetConstructor . getBoundsDimension ( ncfile ) ; String bname = getVariableName ( ) + "_bounds" ; v . addAttribute ( new Attribute ( "bounds" , bname ) ) ; v . addAttribute ( new Attribute ( _Coordinate . ZisLayer , "true" ) ) ; Variable b = new Variable ( ncfile , g , null , bname ) ; b . setDataType ( DataType . DOUBLE ) ; b . setDimensions ( getVariableName ( ) + " " + bd . getShortName ( ) ) ; b . addAttribute ( new Attribute ( "long_name" , "bounds for " + v . getFullName ( ) ) ) ; b . addAttribute ( new Attribute ( "units" , lookup . getLevelUnit ( typicalRecord ) ) ) ; Array boundsArray = Array . factory ( DataType . DOUBLE , new int [ ] { coordValues . length , 2 } ) ; ucar . ma2 . Index ima = boundsArray . getIndex ( ) ; for ( int i = 0 ; i < coordValues . length ; i ++ ) { LevelCoord lc = ( LevelCoord ) levels . get ( i ) ; boundsArray . setDouble ( ima . set ( i , 0 ) , lc . value1 ) ; boundsArray . setDouble ( ima . set ( i , 1 ) , lc . value2 ) ; } b . setCachedData ( boundsArray , true ) ; ncfile . addVariable ( g , b ) ; } if ( factors != null ) { // check if already created if ( g == null ) { g = ncfile . getRootGroup ( ) ; } if ( g . findVariable ( "hybrida" ) != null ) return ; v . addAttribute ( new Attribute ( "standard_name" , "atmosphere_hybrid_sigma_pressure_coordinate" ) ) ; v . addAttribute ( new Attribute ( "formula_terms" , "ap: hybrida b: hybridb ps: Pressure" ) ) ; // create  hybrid factor variables // add hybrida variable Variable ha = new Variable ( ncfile , g , null , "hybrida" ) ; ha . setDataType ( DataType . DOUBLE ) ; ha . addAttribute ( new Attribute ( "long_name" , "level_a_factor" ) ) ; ha . addAttribute ( new Attribute ( "units" , "" ) ) ; ha . setDimensions ( getVariableName ( ) ) ; // add data int middle = factors . length / 2 ; double [ ] adata ; double [ ] bdata ; if ( levels . size ( ) < middle ) { // only partial data wanted adata = new double [ levels . size ( ) ] ; bdata = new double [ levels . size ( ) ] ; } else { adata = new double [ middle ] ; bdata = new double [ middle ] ; } for ( int i = 0 ; i < middle && i < levels . size ( ) ; i ++ ) adata [ i ] = factors [ i ] ; Array haArray = Array . factory ( DataType . DOUBLE , new int [ ] { adata . length } , adata ) ; ha . setCachedData ( haArray , true ) ; ncfile . addVariable ( g , ha ) ; // add hybridb variable Variable hb = new Variable ( ncfile , g , null , "hybridb" ) ; hb . setDataType ( DataType . DOUBLE ) ; hb . addAttribute ( new Attribute ( "long_name" , "level_b_factor" ) ) ; hb . addAttribute ( new Attribute ( "units" , "" ) ) ; hb . setDimensions ( getVariableName ( ) ) ; // add data for ( int i = 0 ; i < middle && i < levels . size ( ) ; i ++ ) bdata [ i ] = factors [ i + middle ] ; Array hbArray = Array . factory ( DataType . DOUBLE , new int [ ] { bdata . length } , bdata ) ; hb . setCachedData ( hbArray , true ) ; ncfile . addVariable ( g , hb ) ; /*  // TODO: delete next time modifying code
      double[] adata = new double[ middle ];
      for( int i = 0; i < middle; i++ )
        adata[ i ] = factors[ i ];
      Array haArray = Array.factory(DataType.DOUBLE, new int[]{adata.length}, adata);
      ha.setCachedData(haArray, true);
      ncfile.addVariable(g, ha);

      // add hybridb variable
      Variable hb = new Variable(ncfile, g, null, "hybridb");
      hb.setDataType(DataType.DOUBLE);
      hb.addAttribute(new Attribute("long_name",  "level_b_factor" ));
      //hb.addAttribute(new Attribute("standard_name", "atmosphere_hybrid_sigma_pressure_coordinate" ));
      hb.addAttribute(new Attribute("units", ""));
      hb.setDimensions(getVariableName());
      // add data
      double[] bdata = new double[ middle ];
      for( int i = 0; i < middle; i++ )
        bdata[ i ] = factors[ i + middle ];
      Array hbArray = Array.factory(DataType.DOUBLE, new int[]{bdata.length}, bdata);
      hb.setCachedData(hbArray, true);
      ncfile.addVariable(g, hb);
      */ } // allow gc // typicalRecord = null; }


Input: Get the coordinate index for the record [CODESPLIT] private int coordIndex ( GridRecord record ) { double val = record . getLevel1 ( ) ; double val2 = record . getLevel2 ( ) ; if ( usesBounds && ( val > val2 ) ) { val = record . getLevel2 ( ) ; val2 = record . getLevel1 ( ) ; } for ( int i = 0 ; i < levels . size ( ) ; i ++ ) { LevelCoord lc = ( LevelCoord ) levels . get ( i ) ; if ( usesBounds ) { if ( ucar . nc2 . util . Misc . nearlyEquals ( lc . value1 , val ) && ucar . nc2 . util . Misc . nearlyEquals ( lc . value2 , val2 ) ) { return i ; } } else { if ( ucar . nc2 . util . Misc . nearlyEquals ( lc . value1 , val ) ) { return i ; } } } return - 1 ; }


Input: checking the file [CODESPLIT] public boolean isValidFile ( ucar . unidata . io . RandomAccessFile raf ) { NOWRadheader localHeader = new NOWRadheader ( ) ; return ( localHeader . isValidFile ( raf ) ) ; }


Input:
Open the file and read the header part [CODESPLIT] public void open ( ucar . unidata . io . RandomAccessFile raf , ucar . nc2 . NetcdfFile file , ucar . nc2 . util . CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; headerParser = new NOWRadheader ( ) ; try { headerParser . read ( this . raf , ncfile ) ; } catch ( Exception e ) { } // myInfo = headerParser.getVarInfo();
 pcode = 0 ; ncfile . finish ( ) ; }


Input:
Read the data for each variable passed in [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { // subset
 Object data ; Array outputData ; byte [ ] vdata = null ; NOWRadheader . Vinfo vinfo ; ByteBuffer bos ; List < Range > ranges = section . getRanges ( ) ; vinfo = ( NOWRadheader . Vinfo ) v2 . getSPobject ( ) ; vdata = headerParser . getData ( ( int ) vinfo . hoff ) ; bos = ByteBuffer . wrap ( vdata ) ; data = readOneScanData ( bos , vinfo , v2 . getShortName ( ) ) ; outputData = Array . factory ( v2 . getDataType ( ) , v2 . getShape ( ) , data ) ; outputData = outputData . flip ( 1 ) ; // outputData = outputData.flip(2);
 return ( outputData . sectionNoReduce ( ranges ) . copy ( ) ) ; // return outputData;
 }


Input:
all the work is here so can be called recursively [CODESPLIT] public Object readOneScanData ( ByteBuffer bos , NOWRadheader . Vinfo vinfo , String vName ) throws IOException , InvalidRangeException { int doff = ( int ) vinfo . hoff ; int npixel = vinfo . yt * vinfo . xt ; byte [ ] rdata = null ; byte [ ] ldata = new byte [ vinfo . xt ] ; byte [ ] pdata = new byte [ npixel ] ; byte [ ] b2 = new byte [ 2 ] ; bos . position ( doff ) ; // begining of image data
 if ( ( DataType . unsignedByteToShort ( bos . get ( ) ) != 0xF0 ) || ( bos . get ( ) != 0x0C ) ) { return null ; } int ecode ; int color ; int datapos ; int offset = 0 ; int roffset = 0 ; boolean newline = true ; int linenum = 0 ; while ( true ) { // line number
 if ( newline ) { bos . get ( b2 ) ; linenum = ( DataType . unsignedByteToShort ( b2 [ 1 ] ) << 8 ) + DataType . unsignedByteToShort ( b2 [ 0 ] ) ; // System.out.println("Line Number = " + linenum);
 } // int linenum = bytesToInt(b2[0], b2[1], true);
 // System.out.println("Line Number = " + linenum);
 // if(linenum == 1225)
 //   System.out.println(" HHHHH");
 short b = DataType . unsignedByteToShort ( bos . get ( ) ) ; color = b & 0xF ; ecode = b >> 4 ; datapos = bos . position ( ) ; int datarun ; if ( ecode == 0xF ) { byte bb1 = bos . get ( datapos - 2 ) ; byte bb2 = bos . get ( datapos ) ; if ( ( color == 0x0 ) && ( bb1 == 0x00 ) && ( bb2 == 0x00 ) ) { datapos += 1 ; } bos . position ( datapos ) ; datarun = 0 ; } else if ( ecode == 0xE ) { byte b0 = bos . get ( datapos ) ; datarun = DataType . unsignedByteToShort ( b0 ) + 1 ; datapos += 1 ; bos . position ( datapos ) ; } else if ( ecode == 0xD ) { b2 [ 0 ] = bos . get ( datapos ) ; b2 [ 1 ] = bos . get ( datapos + 1 ) ; datarun = ( DataType . unsignedByteToShort ( b2 [ 1 ] ) << 8 ) + DataType . unsignedByteToShort ( b2 [ 0 ] ) + 1 ; datapos += 2 ; bos . position ( datapos ) ; } else { datarun = ecode + 1 ; } // move the unpacked data in the data line
 rdata = new byte [ datarun ] ; for ( int i = 0 ; i < datarun ; i ++ ) { rdata [ i ] = ( byte ) color ; } System . arraycopy ( rdata , 0 , ldata , roffset , datarun ) ; roffset = roffset + datarun ; // System.out.println("run ecode = " + ecode + " and data run " + datarun + " and totalrun " + roffset);
 // check to see if the beginning of the next line or at the end of the file
 short c0 = DataType . unsignedByteToShort ( bos . get ( ) ) ; if ( c0 == 0x00 ) { short c1 = DataType . unsignedByteToShort ( bos . get ( ) ) ; short c2 = DataType . unsignedByteToShort ( bos . get ( ) ) ; // System.out.println("c1 and c2 " + c1 + " " + c2);
 if ( ( c0 == 0x00 ) && ( c1 == 0xF0 ) && ( c2 == 0x0C ) ) { // beginning of next line
 //  System.out.println("linenum   " + linenum + "   and this line total " + roffset);
 //  if (roffset != 3661) {
 //      System.out.println("ERROR missing data, this line total only " + roffset);
 //  }
 System . arraycopy ( ldata , 0 , pdata , offset , roffset ) ; offset = offset + vinfo . xt ; roffset = 0 ; newline = true ; ldata = new byte [ vinfo . xt ] ; } else if ( ( c1 == 0xF0 ) && ( c2 == 0x02 ) ) { // end of the file
 break ; } else { datapos = bos . position ( ) - 3 ; bos . position ( datapos ) ; newline = false ; } } else { newline = false ; datapos = bos . position ( ) ; bos . position ( datapos - 1 ) ; } } return pdata ; }


Input: Read data from encoded values and run len into regular data array [CODESPLIT] public byte [ ] readOneRowData ( byte [ ] ddata , int rLen , int xt ) throws IOException , InvalidRangeException { int run ; byte [ ] bdata = new byte [ xt ] ; int nbin = 0 ; int total = 0 ; for ( run = 0 ; run < rLen ; run ++ ) { int drun = DataType . unsignedByteToShort ( ddata [ run ] ) >> 4 ; byte dcode1 = ( byte ) ( DataType . unsignedByteToShort ( ddata [ run ] ) & 0Xf ) ; for ( int i = 0 ; i < drun ; i ++ ) { bdata [ nbin ++ ] = dcode1 ; total ++ ; } } if ( total < xt ) { for ( run = total ; run < xt ; run ++ ) { bdata [ run ] = 0 ; } } return bdata ; }


Input: take advantage of the work already done by NetcdfDataset [CODESPLIT] private void createFromDataset ( NetcdfDataset ncd ) { // get coordinate variables, disjunct from variables for ( CoordinateAxis axis : ncd . getCoordinateAxes ( ) ) { coordvars . put ( axis . getShortName ( ) , axis ) ; } // dup the variable set ddsvars = new ArrayList <> ( 50 ) ; // collect grid array variables and set of coordinate variables used in grids for ( Variable v : ncd . getVariables ( ) ) { if ( coordvars . containsKey ( v . getShortName ( ) ) ) continue ; // skip coordinate variables ddsvars . add ( v ) ; boolean isgridarray = ( v . getRank ( ) > 1 ) && ( v . getDataType ( ) != DataType . STRUCTURE ) && ( v . getParentStructure ( ) == null ) ; if ( ! isgridarray ) continue ; List < Dimension > dimset = v . getDimensions ( ) ; int rank = dimset . size ( ) ; for ( int i = 0 ; isgridarray && i < rank ; i ++ ) { Dimension dim = dimset . get ( i ) ; if ( dim . getShortName ( ) == null ) isgridarray = false ; else { Variable gv = coordvars . get ( dim . getShortName ( ) ) ; if ( gv == null ) isgridarray = false ; } } if ( isgridarray ) { gridarrays . put ( v . getFullName ( ) , v ) ; for ( Dimension dim : dimset ) { Variable gv = coordvars . get ( dim . getShortName ( ) ) ; if ( gv != null ) used . put ( gv . getFullName ( ) , gv ) ; } } } // Create the set of coordinates for ( Variable cv : ncd . getCoordinateAxes ( ) ) { BaseType bt = createVariable ( ncd , cv ) ; addVariable ( bt ) ; } // Create the set of variables for ( Variable cv : ddsvars ) { BaseType bt = createVariable ( ncd , cv ) ; addVariable ( bt ) ; } }


Input: turn Variable into opendap variable [CODESPLIT] private BaseType createVariable ( NetcdfFile ncfile , Variable v ) { BaseType bt ; if ( v . getRank ( ) == 0 ) // scalar bt = createScalarVariable ( ncfile , v ) ; else if ( v . getDataType ( ) == DataType . CHAR ) { if ( v . getRank ( ) > 1 ) bt = new NcSDCharArray ( v ) ; else bt = new NcSDString ( v ) ; } else if ( v . getDataType ( ) == DataType . STRING ) { if ( v . getRank ( ) == 0 ) bt = new NcSDString ( v ) ; else bt = new NcSDArray ( v , new NcSDString ( v ) ) ; } else // non-char multidim array bt = createArray ( ncfile , v ) ; return bt ; }


Input: Returns a clone of this <code > ?< / code > . See BaseType . cloneDAG () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { NcDDS d = ( NcDDS ) super . cloneDAG ( map ) ; d . coordvars = coordvars ; return d ; }


Input: called by Navigation [CODESPLIT] void fireMapAreaEvent ( ) { if ( debugZoom ) System . out . println ( "NP.fireMapAreaEvent " ) ; // decide if we need a new Projection: for LatLonProjection only if ( project . isLatLon ( ) ) { LatLonProjection llproj = ( LatLonProjection ) project ; ProjectionRect box = getMapArea ( ) ; double center = llproj . getCenterLon ( ) ; double lonBeg = LatLonPointImpl . lonNormal ( box . getMinX ( ) , center ) ; double lonEnd = lonBeg + box . getMaxX ( ) - box . getMinX ( ) ; boolean showShift = Debug . isSet ( "projection/LatLonShift" ) || debugNewProjection ; if ( showShift ) System . out . println ( "projection/LatLonShift: min,max = " + box . getMinX ( ) + " " + box . getMaxX ( ) + " beg,end= " + lonBeg + " " + lonEnd + " center = " + center ) ; if ( ( lonBeg < center - 180 ) || ( lonEnd > center + 180 ) ) { // got to do it double wx0 = box . getX ( ) + box . getWidth ( ) / 2 ; llproj . setCenterLon ( wx0 ) ; // shift cylinder seam double newWx0 = llproj . getCenterLon ( ) ; // normalize wx0 to [-180,180] setWorldCenterX ( newWx0 ) ; // tell navigation panel to shift if ( showShift ) System . out . println ( "projection/LatLonShift: shift center to " + wx0 + "->" + newWx0 ) ; // send projection event instead of map area event lmProject . sendEvent ( new NewProjectionEvent ( this , llproj ) ) ; return ; } } // send new map area event lmMapArea . sendEvent ( new NewMapAreaEvent ( this , getMapArea ( ) ) ) ; }


Input: Set the Map Area . [CODESPLIT] public void setMapArea ( ProjectionRect ma ) { if ( debugBB ) System . out . println ( "NP.setMapArea " + ma ) ; navigate . setMapArea ( ma ) ; }


Input: Set the Map Area by converting LatLonRect to a ProjectionRect . [CODESPLIT] public void setMapArea ( LatLonRect llbb ) { if ( debugBB ) System . out . println ( "NP.setMapArea (ll) " + llbb ) ; navigate . setMapArea ( project . latLonToProjBB ( llbb ) ) ; }


Input: set the center point of the MapArea [CODESPLIT] public void setLatLonCenterMapArea ( double lat , double lon ) { ProjectionPoint center = project . latLonToProj ( lat , lon ) ; ProjectionRect ma = getMapArea ( ) ; ma . setX ( center . getX ( ) - ma . getWidth ( ) / 2 ) ; ma . setY ( center . getY ( ) - ma . getHeight ( ) / 2 ) ; setMapArea ( ma ) ; }


Input: Set the Projection change the Map Area to the projection s default . [CODESPLIT] public void setProjectionImpl ( ProjectionImpl p ) { // transfer selection region to new coord system if ( geoSelection != null ) { LatLonRect geoLL = project . projToLatLonBB ( geoSelection ) ; setGeoSelection ( p . latLonToProjBB ( geoLL ) ) ; } // switch projections project = p ; navigate . setMapArea ( project . getDefaultMapArea ( ) ) ; if ( Debug . isSet ( "projection/set" ) || debugNewProjection ) System . out . println ( "projection/set NP=" + project ) ; // transfer reference point to new coord system if ( hasReference ) { refWorld . setLocation ( project . latLonToProj ( refLatLon ) ) ; } }


Input: Add all of the toolbar s actions to a menu . [CODESPLIT] public void addActionsToMenu ( JMenu menu ) { BAMutil . addActionToMenu ( menu , zoomIn ) ; BAMutil . addActionToMenu ( menu , zoomOut ) ; BAMutil . addActionToMenu ( menu , zoomBack ) ; BAMutil . addActionToMenu ( menu , zoomDefault ) ; menu . addSeparator ( ) ; BAMutil . addActionToMenu ( menu , moveUp ) ; BAMutil . addActionToMenu ( menu , moveDown ) ; BAMutil . addActionToMenu ( menu , moveRight ) ; BAMutil . addActionToMenu ( menu , moveLeft ) ; menu . addSeparator ( ) ; BAMutil . addActionToMenu ( menu , setReferenceAction ) ; }


Input: from panning so wait delay msecs before doing the redraw . [CODESPLIT] private void redrawLater ( int delay ) { boolean already = ( redrawTimer != null ) && ( redrawTimer . isRunning ( ) ) ; if ( debugThread ) System . out . println ( "redrawLater isRunning= " + already ) ; if ( already ) return ; // initialize Timer the first time if ( redrawTimer == null ) { redrawTimer = new javax . swing . Timer ( 0 , new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { drawG ( ) ; redrawTimer . stop ( ) ; // one-shot timer } } ) ; } // start the timer running redrawTimer . setDelay ( delay ) ; redrawTimer . start ( ) ; }


Input: sets whether the user can zoom / pan on this NavigatedPanel . Default = true . [CODESPLIT] public void setChangeable ( boolean mode ) { if ( mode == changeable ) return ; changeable = mode ; if ( toolbar != null ) toolbar . setEnabled ( mode ) ; }


Input: note : I believe that the RepaintManager is not used on JPanel subclasses ??? [CODESPLIT] public void repaint ( long tm , int x , int y , int width , int height ) { if ( debugDraw ) System . out . println ( "REPAINT " + repaintCount + " x " + x + " y " + y + " width " + width + " heit " + height ) ; if ( debugThread ) System . out . println ( " thread = " + Thread . currentThread ( ) ) ; repaintCount ++ ; super . repaint ( tm , x , y , width , height ) ; }


Input: System - triggered redraw . [CODESPLIT] public void paintComponent ( Graphics g ) { if ( debugDraw ) System . out . println ( "System called paintComponent clip= " + g . getClipBounds ( ) ) ; draw ( ( Graphics2D ) g ) ; }


Input: User must get this Graphics2D and draw into it when panel needs redrawing [CODESPLIT] public Graphics2D getBufferedImageGraphics ( ) { if ( bImage == null ) return null ; Graphics2D g2 = bImage . createGraphics ( ) ; // set clipping rectangle into boundingBox navigate . getMapArea ( boundingBox ) ; if ( debugBB ) System . out . println ( " getBufferedImageGraphics BB = " + boundingBox ) ; // set graphics attributes g2 . setTransform ( navigate . getTransform ( ) ) ; g2 . setStroke ( new BasicStroke ( 0.0f ) ) ; // default stroke size is one pixel g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_SPEED ) ; Rectangle2D hr = new Rectangle2D . Double ( ) ; hr . setRect ( boundingBox . getX ( ) , boundingBox . getY ( ) , boundingBox . getWidth ( ) , boundingBox . getHeight ( ) ) ; g2 . setClip ( hr ) ; // normalized coord system, because transform is applied g2 . setBackground ( backColor ) ; return g2 ; }


Input: This calculates the Affine Transform that maps the current map area ( in Projection Coordinates ) to a display area ( in arbitrary units ) . @param rotate should the page be rotated? @param displayX upper right corner of display area @param displayY upper right corner of display area @param displayWidth display area @param displayHeight display area [CODESPLIT] public AffineTransform calcTransform ( boolean rotate , double displayX , double displayY , double displayWidth , double displayHeight ) { return navigate . calcTransform ( rotate , displayX , displayY , displayWidth , displayHeight ) ; }