Input: / * message Partition { required string name = 1 ; // name is used in TDS - eg the subdirectory when generated by TimePartitionCollections required string filename = 2 ; // the gribCollection . ncx2 file required string directory = 3 ; // top directory optional uint64 lastModified = 4 ; } [CODESPLIT] private PartitionCollectionMutable . Partition makePartition ( GribCollectionProto . Partition proto ) { long partitionDateMillisecs = proto . getPartitionDate ( ) ; CalendarDate partitionDate = partitionDateMillisecs > 0 ? CalendarDate . of ( partitionDateMillisecs ) : null ; return pc . addPartition ( proto . getName ( ) , proto . getFilename ( ) , proto . getLastModified ( ) , proto . getLength ( ) , null , partitionDate ) ; }


Input: return an integer type value ( including long but not floats ) [CODESPLIT] public Object nextInteger ( DapType basetype ) throws DapException { TypeSort atomtype = basetype . getTypeSort ( ) ; if ( ! atomtype . isIntegerType ( ) ) throw new DapException ( "Unexpected type: " + basetype ) ; boolean unsigned = atomtype . isUnsigned ( ) ; switch ( atomtype ) { case Int8 : return new byte [ ] { ( byte ) ( random . nextInt ( 1 << 8 ) - ( 1 << 7 ) ) } ; case UInt8 : return new byte [ ] { ( byte ) ( random . nextInt ( 1 << 8 ) & 0xFF ) } ; case Int16 : return new short [ ] { ( short ) ( random . nextInt ( 1 << 16 ) - ( 1 << 15 ) ) } ; case UInt16 : return new short [ ] { ( short ) ( random . nextInt ( 1 << 16 ) ) } ; case Int32 : return new int [ ] { random . nextInt ( ) } ; case UInt32 : long l = random . nextLong ( ) ; l = l & 0xFFFFFFFF ; return new int [ ] { ( int ) l } ; case Int64 : return new long [ ] { random . nextLong ( ) } ; case UInt64 : return new long [ ] { new BigInteger ( 64 , random ) . longValue ( ) } ; } throw new DapException ( "Unexpected type: " + basetype ) ; }


Input: return a float type value [CODESPLIT] public Object nextFloat ( DapType basetype ) throws DapException { TypeSort atomtype = basetype . getTypeSort ( ) ; switch ( atomtype ) { case Float32 : return new float [ ] { random . nextFloat ( ) } ; case Float64 : return new double [ ] { random . nextDouble ( ) } ; default : break ; } throw new DapException ( "Unexpected type: " + basetype ) ; }


Input: Return an integer in range 1 .. max inclusive . [CODESPLIT] public int nextCount ( int max ) throws DapException { int min = 1 ; if ( max < min || min < 1 ) throw new DapException ( "bad range" ) ; int range = ( max + 1 ) - min ; // min..max+1 -> 0..(max+1)-min int n = random . nextInt ( range ) ; //  0..(max+1)-min n = n + min ; // min..(max+1) if ( DEBUG ) System . err . println ( "RandomValue.nextCount: " + n ) ; return n ; }


Input: Close all resources ( files sockets etc ) associated with this file . [CODESPLIT] @ Override public synchronized void close ( ) throws java . io . IOException { if ( closed ) return ; closed = true ; // avoid circular calls dsp = null ; // nodemap = null;  unused? }


Input: Do a bulk read on a list of Variables and return a corresponding list of Array that contains the results of a full read on each Variable . TODO : optimize to make only a single server call and cache the results . [CODESPLIT] @ Override public List < Array > readArrays ( List < Variable > variables ) throws IOException { List < Array > result = new ArrayList < Array > ( ) ; for ( Variable variable : variables ) { result . add ( variable . read ( ) ) ; } return result ; }


Input: Primary read entry point . This is the primary implementor of Variable . read . [CODESPLIT] @ Override protected Array readData ( Variable cdmvar , Section section ) throws IOException , InvalidRangeException { // The section is applied wrt to the DataDMR, so it // takes into account any constraint used in forming the dataDMR. // We use the Section to produce a view of the underlying variable array. assert this . dsp != null ; Array result = arraymap . get ( cdmvar ) ; if ( result == null ) throw new IOException ( "No data for variable: " + cdmvar . getFullName ( ) ) ; if ( section != null ) { if ( cdmvar . getRank ( ) != section . getRank ( ) ) throw new InvalidRangeException ( String . format ( "Section rank != %s rank" , cdmvar . getFullName ( ) ) ) ; List < Range > ranges = section . getRanges ( ) ; // Case out the possibilities if ( CDMUtil . hasVLEN ( ranges ) ) { ranges = ranges . subList ( 0 , ranges . size ( ) - 1 ) ; // may produce empty list } if ( ranges . size ( ) > 0 && ! CDMUtil . isWhole ( ranges , cdmvar ) ) result = result . sectionNoReduce ( ranges ) ; } return result ; }


Input: Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException { val = source . readInt ( ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 ) ; }


Input: filesystem can t be re - created either . [CODESPLIT] private static FileSystemProvider getProvider ( URI uri ) throws IOException { if ( fsproviders . containsKey ( uri . getScheme ( ) ) ) { return fsproviders . get ( uri . getScheme ( ) ) ; } else { FileSystem fs ; try { fs = FileSystems . newFileSystem ( uri , new HashMap < String , Object > ( ) , Thread . currentThread ( ) . getContextClassLoader ( ) ) ; } catch ( FileSystemAlreadyExistsException e ) { fs = FileSystems . getFileSystem ( uri ) ; } fsproviders . put ( uri . getScheme ( ) , fs . provider ( ) ) ; return fs . provider ( ) ; } }


Input: this is the old Gempak table not as precise [CODESPLIT] private static void readStationTable ( ) throws IOException { stationTableHash = new HashMap < String , Station > ( ) ; ClassLoader cl = Level2VolumeScan . class . getClassLoader ( ) ; InputStream is = cl . getResourceAsStream ( "resources/nj22/tables/nexrad.tbl" ) ; List < TableParser . Record > recs = TableParser . readTable ( is , "3,15,46, 54,60d,67d,73d" , 50000 ) ; for ( TableParser . Record record : recs ) { Station s = new Station ( ) ; s . id = "K" + record . get ( 0 ) ; s . name = record . get ( 2 ) + " " + record . get ( 3 ) ; s . lat = ( Double ) record . get ( 4 ) * .01 ; s . lon = ( Double ) record . get ( 5 ) * .01 ; s . elev = ( Double ) record . get ( 6 ) ; stationTableHash . put ( s . id , s ) ; if ( showStations ) System . out . println ( " station= " + s ) ; } }


Input: ////////////////////////////////// [CODESPLIT] static private int parseLine ( String line ) throws IOException { int balony = 0 ; Matcher matcher = dataPattern . matcher ( line ) ; if ( matcher . matches ( ) ) { for ( int i = 1 ; i <= matcher . groupCount ( ) ; i ++ ) { String r = matcher . group ( i ) ; if ( r == null ) continue ; int value = ( int ) Long . parseLong ( r . trim ( ) ) ; balony += value ; } } else { System . out . printf ( "Fail on %s%n" , line ) ; } return balony ; }


Input: debug [CODESPLIT] static private NetcdfFile open ( String filename ) throws IOException { Ghcnm iosp = new Ghcnm ( ) ; RandomAccessFile raf = new RandomAccessFile ( filename , "r" ) ; NetcdfFile ncfile = new NetcdfFileSubclass ( iosp , filename ) ; iosp . open ( raf , ncfile , null ) ; return ncfile ; }


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 { ArrayDouble . D3 data = original . getCoordinateArray ( timeIndex ) ; int [ ] origin = new int [ 3 ] ; int [ ] shape = new int [ 3 ] ; shape [ 0 ] = subsetList . get ( 0 ) . length ( ) ; shape [ 1 ] = 1 ; shape [ 2 ] = 1 ; origin [ 0 ] = timeIndex ; if ( isTimeDependent ( ) && ( t_range != null ) ) { origin [ 0 ] = t_range . element ( timeIndex ) ; } origin [ 1 ] = yIndex ; origin [ 2 ] = xIndex ; Array section = data . section ( origin , shape ) ; return ( ArrayDouble . D1 ) section . reduce ( ) ; }


Input: Used by CoordinateND . makeSparseArray ; not used by CoordinateTime2D [CODESPLIT] @ Override public int getIndex ( T gr ) { Integer result = valMap . get ( extract ( gr ) ) ; return ( result == null ) ? 0 : result ; }


Input:
//////////////////////////////////////////// [CODESPLIT] public static void main ( String args [ ] ) throws HTTPException { // prefs storage
 try { String prefStore = ucar . util . prefs . XMLStore . makeStandardFilename ( ".unidata" , "TdsMonitor.xml" ) ; store = ucar . util . prefs . XMLStore . createFromFile ( prefStore , null ) ; prefs = store . getPreferences ( ) ; Debug . setStore ( prefs . node ( "Debug" ) ) ; } catch ( IOException e ) { System . out . println ( "XMLStore Creation failed " + e ) ; } // initializations
 BAMutil . setResourcePath ( "/resources/nj22/ui/icons/" ) ; // put UI in a JFrame
 frame = new JFrame ( "TDS Monitor" ) ; ui = new TdsMonitor ( prefs , frame ) ; frame . setIconImage ( BAMutil . getImage ( "netcdfUI" ) ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { if ( ! done ) ui . exit ( ) ; } } ) ; frame . getContentPane ( ) . add ( ui ) ; Rectangle bounds = ( Rectangle ) prefs . getBean ( FRAME_SIZE , new Rectangle ( 50 , 50 , 800 , 450 ) ) ; frame . setBounds ( bounds ) ; frame . pack ( ) ; frame . setBounds ( bounds ) ; frame . setVisible ( true ) ; }


Input: reminder for subclasses to set this [CODESPLIT] protected void removeDataVariable ( String varName ) { Iterator iter = dataVariables . iterator ( ) ; while ( iter . hasNext ( ) ) { VariableSimpleIF v = ( VariableSimpleIF ) iter . next ( ) ; if ( v . getShortName ( ) . equals ( varName ) ) iter . remove ( ) ; } }


Input: convert cloud height to meters [CODESPLIT] private String cloud_hgt2_meters ( String height ) { if ( height . equals ( "999" ) ) { return "30000" ; } else { //		$meters = 30 * $height ; return Integer . toString ( 30 * Integer . parseInt ( height ) ) ; } }


Input:
/ * Class FXY enElementName BUFR_Unit BUFR_Scale BUFR_ReferenceValue BUFR_DataWidth_Bits CREX_Unit CREX_Scale CREX_DataWidth 20 20009 General weather indicator ( TAF / METAR ) Code table 0 0 4 Code table 0 2 [CODESPLIT] private void writeDiff ( TableB wmo , TableB t , Formatter out ) { out . format ( "#%n# BUFR diff written from %s against %s %n#%n" , t . getName ( ) , wmo . getName ( ) ) ; out . format ( "Class,FXY,enElementName,BUFR_Unit,BUFR_Scale,BUFR_ReferenceValue,BUFR_DataWidth_Bits%n" ) ; List < TableB . Descriptor > listDesc = new ArrayList <> ( t . getDescriptors ( ) ) ; Collections . sort ( listDesc ) ; for ( TableB . Descriptor d1 : listDesc ) { TableB . Descriptor d2 = wmo . getDescriptor ( d1 . getId ( ) ) ; if ( ( d2 == null ) || ( d1 . getScale ( ) != d2 . getScale ( ) ) || ( d1 . getRefVal ( ) != d2 . getRefVal ( ) ) || ( d1 . getDataWidth ( ) != d2 . getDataWidth ( ) ) ) { short fxy = d1 . getId ( ) ; //        int f = (fxy & 0xC000) >> 14;
 int x = ( fxy & 0x3F00 ) >> 8 ; int y = fxy & 0xFF ; out . format ( "%d,%2d%03d,\"%s\",%s,%d,%d,%d%n" , x , x , y , d1 . getName ( ) , d1 . getUnits ( ) , d1 . getScale ( ) , d1 . getRefVal ( ) , d1 . getDataWidth ( ) ) ; } } out . flush ( ) ; }


Input:
here is where agg variables get read [CODESPLIT] @ Override public Array reallyRead ( Variable mainv , Section section , CancelTask cancelTask ) throws IOException , InvalidRangeException { FmrcInvLite . Gridset . Grid gridLite = ( FmrcInvLite . Gridset . Grid ) mainv . getSPobject ( ) ; // read the original type - if its been promoted to a new type, the conversion happens after this read
 DataType dtype = ( mainv instanceof VariableDS ) ? ( ( VariableDS ) mainv ) . getOriginalDataType ( ) : mainv . getDataType ( ) ; Array allData = Array . factory ( dtype , section . getShape ( ) ) ; int destPos = 0 ; // assumes the first two dimensions are runtime and time: LOOK: ensemble ??
 List < Range > ranges = section . getRanges ( ) ; Range runRange = ranges . get ( 0 ) ; Range timeRange = ranges . get ( 1 ) ; List < Range > innerSection = ranges . subList ( 2 , ranges . size ( ) ) ; // keep track of open file - must be local variable for thread safety
 HashMap < String , NetcdfDataset > openFilesRead = new HashMap <> ( ) ; try { // iterate over the desired runs
 for ( int runIdx : runRange ) { //Date runDate = vstate.runTimes.get(runIdx);
 // iterate over the desired forecast times
 for ( int timeIdx : timeRange ) { Array result = null ; // find the inventory for this grid, runtime, and hour
 TimeInventory . Instance timeInv = gridLite . getInstance ( runIdx , timeIdx ) ; if ( timeInv != null ) { if ( debugRead ) System . out . printf ( "HIT %d %d " , runIdx , timeIdx ) ; result = read ( timeInv , gridLite . name , innerSection , openFilesRead ) ; // may return null
 result = MAMath . convert ( result , dtype ) ; // just in case it need to be converted
 } // missing data
 if ( result == null ) { int [ ] shape = new Section ( innerSection ) . getShape ( ) ; result = ( ( VariableDS ) mainv ) . getMissingDataArray ( shape ) ; // fill with missing values
 if ( debugRead ) System . out . printf ( "MISS %d %d " , runIdx , timeIdx ) ; } if ( debugRead ) System . out . printf ( "%d %d reallyRead %s %d bytes start at %d total size is %d%n" , runIdx , timeIdx , mainv . getFullName ( ) , result . getSize ( ) , destPos , allData . getSize ( ) ) ; Array . arraycopy ( result , 0 , allData , destPos , ( int ) result . getSize ( ) ) ; destPos += result . getSize ( ) ; } } return allData ; } finally { // close any files used during this operation
 closeAll ( openFilesRead ) ; } }


Input: rest of stuff for construction / deserialization [CODESPLIT] private void constructTransient ( ) { useColors = colors ; edge = new double [ ncolors ] ; hist = new int [ ncolors + 1 ] ; lm = new ListenerManager ( "java.beans.PropertyChangeListener" , "java.beans.PropertyChangeEvent" , "propertyChange" ) ; missingDataColor = Color . white ; }


Input: Set the number of colors in the colorscale . [CODESPLIT] public void setNumColors ( int n ) { if ( n != ncolors ) { colors = new Color [ n ] ; int prevn = Math . min ( ncolors , n ) ; System . arraycopy ( useColors , 0 , colors , 0 , prevn ) ; for ( int i = ncolors ; i < n ; i ++ ) colors [ i ] = Color . white ; useColors = colors ; ncolors = n ; edge = new double [ ncolors ] ; hist = new int [ ncolors + 1 ] ; } }


Input: / * Get the color at the given index or the missing data color . [CODESPLIT] public Color getColor ( int i ) { if ( i >= 0 && i < ncolors ) return useColors [ i ] ; else if ( i == ncolors && hasMissingData ) return missingDataColor ; else throw new IllegalArgumentException ( "Color Scale getColor " + i ) ; }


Input:
Set the data min / max interval . The color intervals are set based on this . A PropertyChangeEvent is sent when this is called . Currently the intervals are calculated in the following way ( where incr = ( max - min ) / ( n - 2 )) : <pre > <p / > edge data interval 0 min value < = min 1 min + incr min < = value < min + incr 2 min + 2 * incr min + incr < = value < min + 2 * incr ith min + i * incr min + ( i - 1 ) * incr < = value < min + i * incr n - 2 max min + ( n - 3 ) * incr < = value < max n - 1 max max < value n value = missingDataValue < / pre > [CODESPLIT] public void setMinMax ( double min , double max ) { this . min = min ; this . max = max ; interval = ( max - min ) / ( ncolors - 2 ) ; // set edges
 for ( int i = 0 ; i < ncolors ; i ++ ) edge [ i ] = min + i * interval ; lm . sendEvent ( new PropertyChangeEvent ( this , "ColorScaleLimits" , null , this ) ) ; } /**
   * This is an optimization for counting the number of colors in each interval.
   * the histpogram is populated by calls to getIndexFromValue().
   *
   * @return the index with the maximum histogram count.
   */ public int getHistMax ( ) { int max = 0 , maxi = 0 ; for ( int i = 0 ; i <= ncolors ; i ++ ) if ( hist [ i ] > max ) { max = hist [ i ] ; maxi = i ; } return maxi ; } /**
   * reset the histogram.
   */ public void resetHist  ( ) { for ( int i = 0 ; i <= ncolors ; i ++ ) hist [ i ] = 0 ; } public String toString  ( ) { return name ; } public Object clone  ( ) { ColorScale cl = new ColorScale ( name , colors ) ; /*try {
      cl = (ColorScale) super.clone();
    } catch(CloneNotSupportedException e) {
      return null;
    } // ignore

    // non primitive fields must be cloned separately
    cl.name = new String(name);
    cl.set(this);
    cl.construct();  */ return ( Object ) cl ; } /////////// private ////////////////////
 // this is for editing a colorscale
 private void editModeBegin  ( ) { Color [ ] editColors = new Color [ ncolors ] ; System . arraycopy ( colors , 0 , editColors , 0 , ncolors ) ; useColors = editColors ; } private void editModeEnd  ( boolean accept ) { if ( accept ) { System . arraycopy ( useColors , 0 , colors , 0 , ncolors ) ; } useColors = colors ; } private void setColor  ( int i , Color c ) { if ( i >= 0 && i < ncolors ) useColors [ i ] = c ; } /* private void set( ColorScale cs) {
   set(cs.getColors());
 } */ private void setColors  ( Color [ ] c ) { ncolors = c . length ; colors = new Color [ ncolors ] ; System . arraycopy ( c , 0 , colors , 0 , ncolors ) ; edge = new double [ ncolors ] ; hist = new int [ ncolors + 1 ] ; useColors = colors ; // ??
 } // serialization
 private void readObject  ( ObjectInputStream s ) throws IOException , ClassNotFoundException { s . readInt ( ) ; this . name = s . readUTF ( ) ; this . colors = ( Color [ ] ) s . readObject ( ) ; this . ncolors = colors . length ; constructTransient ( ) ; } private void writeObject  ( ObjectOutputStream s ) throws IOException { s . writeInt ( objectVersion ) ; s . writeUTF ( this . name ) ; s . writeObject ( this . colors ) ; } // heres the swing component part of a ColorScale: static so its not part of serialization
 // originally designed to allow popup editor to change colors; this has been disabled; all
 // changes made by COlorManager. design could be cleaned up, but maybe I want that back later?
 public static class Panel extends JPanel { private int type ; private int size = 50 ; private ColorScale cs ; private JLabel unitLabel = new JLabel ( "unit" , SwingConstants . CENTER ) ; private JPanel lpanel ; private boolean editable = false ; private int selected = - 1 ; private int nColorInterval ; private String [ ] label ; private boolean useLabel = true ; private FontUtil . StandardFont sf = FontUtil . getStandardFont ( 10 ) ; public Panel ( Component parent ) { this ( parent , ColorScale . VERTICAL , null ) ; } public Panel ( Component parent , ColorScale cscale ) { this ( parent , ColorScale . VERTICAL , cscale ) ; } public Panel ( Component parent , int type , ColorScale cscale ) { this . cs = ( cscale == null ) ? new ColorScale ( "default" ) : cscale ; this . type = type ; if ( type == ColorScale . VERTICAL ) { setPreferredSize ( new Dimension ( size , 400 ) ) ; setLayout ( new BoxLayout ( this , BoxLayout . Y_AXIS ) ) ; } else { setPreferredSize ( new Dimension ( 400 , size ) ) ; setLayout ( new BoxLayout ( this , BoxLayout . X_AXIS ) ) ; } setListener ( ) ; nColorInterval = cs . getNumColors ( ) ; for ( int i = 0 ; i < nColorInterval ; i ++ ) { ColorInterval intv = new ColorInterval ( nColorInterval - i - 1 ) ; add ( intv ) ; } lpanel = new JPanel ( ) ; lpanel . add ( unitLabel ) ; //unitLabel.setBorder( new javax.swing.border.EtchedBorder());
 if ( type == ColorScale . VERTICAL ) lpanel . setPreferredSize ( new Dimension ( size , 0 ) ) ; else lpanel . setPreferredSize ( new Dimension ( 0 , size ) ) ; add ( lpanel ) ; label = new String [ nColorInterval ] ; calcLabels ( ) ; /* creates a popup men, attaches it to this Panel
     PopupMenu popupMenu = new PopupMenu(this, "options");
     popupMenu.add("Edit", new AbstractAction() {
       public void actionPerformed(ActionEvent e) {
         System.out.println("popup edit action");
         dialog.show();
       }
     }); */ } private void calcLabels ( ) { label [ 0 ] = "<" + Format . d ( cs . getEdge ( 0 ) , sigfig ) ; for ( int i = 1 ; i < nColorInterval - 1 ; i ++ ) { label [ i ] = Format . d ( cs . getEdge ( i ) , sigfig ) ; } label [ nColorInterval - 1 ] = ">" + Format . d ( cs . getEdge ( nColorInterval - 2 ) , sigfig ) ; } private void setListener ( ) { // listen for changes so we can redraw
 cs . addPropertyChangeListener ( new java . beans . PropertyChangeListener ( ) { public void propertyChange ( java . beans . PropertyChangeEvent e ) { if ( e . getPropertyName ( ) . equals ( "ColorScaleLimits" ) ) calcLabels ( ) ; repaint ( ) ; } } ) ; } public ColorScale getColorScale ( ) { return cs ; } // change the current cscale
 public void setColorScale ( ColorScale cscale ) { if ( nColorInterval != cscale . getNumColors ( ) ) { removeAll ( ) ; nColorInterval = cscale . getNumColors ( ) ; label = new String [ nColorInterval ] ; for ( int i = 0 ; i < nColorInterval ; i ++ ) { ColorInterval intv = new ColorInterval ( nColorInterval - i - 1 ) ; add ( intv ) ; label [ i ] = "none" ; } add ( lpanel ) ; revalidate ( ) ; } this . cs = cscale ; setListener ( ) ; calcLabels ( ) ; repaint ( ) ; } // set existing colorscale to have new colors
 public void setColors ( Color [ ] c ) { if ( nColorInterval != c . length ) { removeAll ( ) ; nColorInterval = c . length ; label = new String [ nColorInterval ] ; for ( int i = 0 ; i < nColorInterval ; i ++ ) { ColorInterval intv = new ColorInterval ( nColorInterval - i - 1 ) ; add ( intv ) ; label [ i ] = "none" ; } add ( lpanel ) ; revalidate ( ) ; } cs . setColors ( c ) ; cs . editModeBegin ( ) ; // again
 if ( debugColors ) { for ( int i = 0 ; i < cs . getNumColors ( ) ; i ++ ) System . out . println ( cs . getColor ( i ) ) ; } calcLabels ( ) ; repaint ( ) ; } public void setColor ( Color c ) { cs . setColor ( selected , c ) ; } //public void setEditable( boolean b) { editable = b; }
 public void setEditMode ( boolean on , boolean accept ) { if ( on ) { editable = true ; cs . editModeBegin ( ) ; } else { cs . editModeEnd ( accept ) ; if ( accept ) setColorScale ( cs ) ; selected = - 1 ; editable = false ; } repaint ( ) ; } public void setSelected ( int i ) { selected = i ; } public void setShowText ( boolean b ) { useLabel = b ; } /*private void edit(int which) {
      if (!editable)
        return;
      selected = which;
      repaint();
      cs.setEditMode(true);
      //dialog.show();
    }*/ public void setUnitString ( String s ) { unitLabel . setText ( s ) ; //System.out.println("new text = "+s);
 //unitLabel.repaint(s);
 } public void print ( Graphics2D g , double x , double y , double width , double height ) { int n = cs . getNumColors ( ) ; double size = ( type == ColorScale . VERTICAL ) ? height / n : width / n ; int count = 0 ; for ( int i = 0 ; i < getComponentCount ( ) ; i ++ ) { Component c = getComponent ( i ) ; if ( c instanceof ColorInterval ) { ColorInterval intv = ( ColorInterval ) c ; if ( type == ColorScale . VERTICAL ) intv . printV ( g , ( int ) x , ( int ) ( y + count * size ) , ( int ) width , ( int ) size ) ; else { double xpos = x + width - ( count + 1 ) * size ; intv . printH ( g , ( int ) xpos , ( int ) y , ( int ) size , ( int ) height ) ; } count ++ ; } } } /* private class OkListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
        selected = -1;
        cs.accept();
        repaint();
      }
    }  // end inner class OkListener

    private class CancelListener implements ActionListener {
      public void actionPerformed(ActionEvent e) {
        selected = -1;
        cs.cancel();
        repaint();
      }
    } // end inner class CancelListener  */ private class ColorInterval extends JComponent { private int rank ; ColorInterval ( int r ) { this . rank = r ; //setPreferredSize( new Dimension(40,40));
 addMouseListener ( new MouseAdapter ( ) { public void mousePressed ( MouseEvent e ) { if ( editable ) { selected = rank ; Panel . this . repaint ( ) ; } } } ) ; } public void printV ( Graphics2D g , int x , int y , int width , int height ) { int textSize = 15 ; // LOOK : neeed to calculate this
 g . setColor ( cs . getColor ( rank ) ) ; g . fillRect ( x , y + textSize , width , height - textSize ) ; //g.setColor( Color.black);
 //g.drawRect( x, y+textSize, width, height-textSize);
 if ( useLabel ) { g . setColor ( Color . black ) ; g . setFont ( sf . getFont ( ) ) ; g . drawString ( label [ rank ] , x + 3 , y + 10 ) ; } } public void printH ( Graphics2D g , int x , int y , int width , int height ) { int textSize = 15 ; // LOOK : neeed to calculate this
 g . setColor ( cs . getColor ( rank ) ) ; g . fillRect ( x , y + textSize , width , height - 2 * textSize ) ; g . setColor ( Color . white ) ; g . drawRect ( x , y + textSize , width , height - 2 * textSize ) ; if ( useLabel ) { g . setColor ( Color . black ) ; g . setFont ( sf . getFont ( ) ) ; if ( rank % 2 == 0 ) // even
 g . drawString ( label [ rank ] , x , y + textSize ) ; else g . drawString ( label [ rank ] , x , y + height ) ; } } public void paintComponent ( Graphics g ) { Rectangle b = getBounds ( ) ; g . setColor ( cs . getColor ( rank ) ) ; g . fillRect ( 0 , 0 , b . width - 1 , b . height - 1 ) ; g . setColor ( ( selected == rank ) ? Color . magenta : Color . black ) ; g . drawRect ( 0 , 0 , b . width - 1 , b . height - 1 ) ; if ( selected == rank ) { g . drawLine ( 0 , 0 , b . width , b . height ) ; g . drawLine ( 0 , b . height , b . width , 0 ) ; } if ( useLabel ) { g . setColor ( Color . black ) ; g . setFont ( sf . getFont ( ) ) ; g . drawString ( label [ rank ] , 3 , 10 ) ; } } } // end inner class ColorInterval
 } // end inner class ColorScale.Panel
 }


Input:
Prints the value of all variables in this vector . This method is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space ) { int len = vals . length ; for ( int i = 0 ; i < len - 1 ; i ++ ) { os . print ( vals [ i ] ) ; os . print ( ", " ) ; } // print last value, if any, without trailing comma
 if ( len > 0 ) os . print ( vals [ len - 1 ] ) ; }


Input: Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { for ( int i = 0 ; i < vals . length ; i ++ ) { sink . writeDouble ( vals [ i ] ) ; } }


Input: / * set the bounds of the world coordinates . The point ( world . getX () world . getY () ) is mapped to the lower left point of the screen . The point ( world . getX () + world . Width () world . getY () + world . Height () ) is mapped to the upper right corner . Therefore if coords decrease as you go up world . Height () should be negetive . [CODESPLIT] public void setWorldBounds ( ScaledPanel . Bounds world ) { worldBounds . set ( world ) ; transform = null ; if ( debugBounds ) System . out . println ( "  setWorldBounds = " + worldBounds ) ; }


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 graphics attributes if ( transform == null ) transform = calcTransform ( screenBounds , worldBounds ) ; g2 . setTransform ( transform ) ; g2 . setStroke ( new BasicStroke ( 0.0f ) ) ; // default stroke size is one pixel g2 . setRenderingHint ( RenderingHints . KEY_RENDERING , RenderingHints . VALUE_RENDER_SPEED ) ; g2 . setBackground ( backColor ) ; g2 . setClip ( worldBounds . getRect ( ) ) ; return g2 ; }


Input: System - triggered redraw . [CODESPLIT] public void paintComponent ( Graphics g ) { if ( bImage != null ) g . drawImage ( bImage , 0 , 0 , backColor , imageObs ) ; }


Input: map world coords to screen coords . [CODESPLIT] private AffineTransform calcTransform ( Rectangle2D screen , Bounds world ) { // scale to limiting dimension double xs = screen . getWidth ( ) / ( world . getRight ( ) - world . getLeft ( ) ) ; double ys = screen . getHeight ( ) / ( world . getLower ( ) - world . getUpper ( ) ) ; AffineTransform cat = new AffineTransform ( ) ; cat . setToScale ( xs , ys ) ; cat . translate ( - world . getLeft ( ) , - world . getUpper ( ) ) ; if ( debugTransform ) { System . out . println ( "TPanel calcTransform = " ) ; System . out . println ( "  screen = " + screen ) ; System . out . println ( "  world = " + world ) ; System . out . println ( "  transform = " + cat . getScaleX ( ) + " " + cat . getShearX ( ) + " " + cat . getTranslateX ( ) ) ; System . out . println ( "              " + cat . getShearY ( ) + " " + cat . getScaleY ( ) + " " + cat . getTranslateY ( ) ) ; Point2D src = new Point2D . Double ( world . getLeft ( ) , world . getUpper ( ) ) ; Point2D dst = new Point2D . Double ( 0.0 , 0.0 ) ; System . out . println ( "  upper left pt = " + src ) ; System . out . println ( "  transform = " + cat . transform ( src , dst ) ) ; src = new Point2D . Double ( world . getRight ( ) , world . getLower ( ) ) ; System . out . println ( "  lower right pt = " + src ) ; System . out . println ( "  transform = " + cat . transform ( src , dst ) ) ; } return cat ; }


Input: Given a session url AuthScope and a Method url AuthScope Indicate it the are compatible as defined as follows . The method AuthScope is <i > compatible< / i > with the session AuthScope if its host + port is the same as the session s host + port and its scheme is compatible where e . g . http is compatible with https . The scope realm is ignored . [CODESPLIT] static boolean authscopeCompatible ( AuthScope ss , AuthScope ms ) { assert ( ss . getScheme ( ) != null && ms . getScheme ( ) != null ) ; if ( ! ss . getHost ( ) . equalsIgnoreCase ( ms . getHost ( ) ) ) return false ; if ( ss . getPort ( ) != ms . getPort ( ) ) return false ; String sss = ss . getScheme ( ) . toLowerCase ( ) ; String mss = ms . getScheme ( ) . toLowerCase ( ) ; if ( ! sss . equals ( mss ) ) { // Do some special casing if ( sss . endsWith ( "s" ) ) sss = sss . substring ( 0 , sss . length ( ) - 1 ) ; if ( mss . endsWith ( "s" ) ) mss = mss . substring ( 0 , mss . length ( ) - 1 ) ; if ( ! sss . equals ( mss ) ) return false ; } return true ; }


Input: Given a session url AuthScope and a Method url AuthScope return a new AuthScope that is the upgrade / merge of the other two . Here upgrade changes the scheme ( only ) to move http - > https . Assumes authscopeCompatible () is true . [CODESPLIT] static AuthScope authscopeUpgrade ( AuthScope ss , AuthScope ms ) { assert ( HTTPAuthUtil . authscopeCompatible ( ss , ms ) ) ; String sss = ss . getScheme ( ) . toLowerCase ( ) ; String mss = ms . getScheme ( ) . toLowerCase ( ) ; String upgrade = sss ; if ( sss . startsWith ( "http" ) && mss . startsWith ( "http" ) ) { if ( sss . equals ( "https" ) || mss . equals ( "https" ) ) upgrade = "https" ; } AuthScope host = new AuthScope ( ss . getHost ( ) , ss . getPort ( ) , AuthScope . ANY_REALM , upgrade ) ; return host ; }


Input: Create an AuthScope from a URI ; remove any principal [CODESPLIT] static AuthScope uriToAuthScope ( URI uri ) { assert ( uri != null ) ; return new AuthScope ( uri . getHost ( ) , uri . getPort ( ) , AuthScope . ANY_REALM , uri . getScheme ( ) ) ; }


Input: compares GDS for duplicates [CODESPLIT] public void finish ( ) { if ( gcs . size ( ) == 1 ) return ; if ( gcs . size ( ) == 2 ) { List hcs = getHorizCoordSys ( ) ; GridDefRecord . compare ( ( GridDefRecord ) hcs . get ( 0 ) , ( GridDefRecord ) hcs . get ( 1 ) ) ; } }


Input: Indicates if this Factor is the reciprocal of another Factor . [CODESPLIT] public boolean isReciprocalOf ( final Factor that ) { return getBase ( ) . equals ( that . getBase ( ) ) && getExponent ( ) == - that . getExponent ( ) ; }


Input: wml2 : defaultPointMetadata / wml2 : DefaultTVPMeasurementMetadata [CODESPLIT] public static TVPMeasurementMetadataType initDefaultTVPMeasurementMetadata ( TVPMeasurementMetadataType defaultTVPMeasurementMetadata , VariableSimpleIF dataVar ) { // wml2:uom UnitReference uom = NcUnitReference . initUom ( defaultTVPMeasurementMetadata . addNewUom ( ) , dataVar ) ; if ( uom == null ) { defaultTVPMeasurementMetadata . unsetUom ( ) ; } // wml2:interpolationType NcReferenceType . initInterpolationType ( defaultTVPMeasurementMetadata . addNewInterpolationType ( ) ) ; return defaultTVPMeasurementMetadata ; }


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


Input:
Gather context information for the given HTTP request and return a log message appropriate for logging at the start of the request . <p / > <p > The following context information is gathered : <ul > <li > ID - an identifier for the current thread ; < / li > <li > host - the remote host ( IP address or host name ) ; < / li > <li > userid - the id of the remote user ; < / li > <li > startTime - the system time in millis when this request is started ( i . e . when this method is called ) ; and< / li > <li > request - The HTTP request e . g . GET / index . html HTTP / 1 . 1 . < / li > < / ul > <p / > <p > Call this method at the start of each HttpServlet doXXX () method ( e . g . doGet () doPut () ) or Spring MVC Controller handle () method . [CODESPLIT] public static String setupRequestContext ( HttpServletRequest req ) { // Setup context.
 //HttpSession session = req.getSession(false);
 /* MDC.put("host", req.getRemoteHost());
    MDC.put("ident", (session == null) ? "-" : session.getId());
    MDC.put("userid", req.getRemoteUser() != null ? req.getRemoteUser() : "-"); */ MDC . put ( "ID" , Long . toString ( logServerAccessId . incrementAndGet ( ) ) ) ; MDC . put ( "startTime" , Long . toString ( System . currentTimeMillis ( ) ) ) ; String query = req . getQueryString ( ) ; query = ( query != null ) ? "?" + query : "" ; Formatter request = new Formatter ( ) ; request . format ( "\"%s %s%s %s\"" , req . getMethod ( ) , req . getRequestURI ( ) , query , req . getProtocol ( ) ) ; MDC . put ( "request" , request . toString ( ) ) ; return "Remote host: " + req . getRemoteHost ( ) + " - Request: " + request . toString ( ) ; }


Input:
Gather context information for the current non - request thread and return a log message appropriate for logging . <p / > <p > The following context information is gathered : <ul > <li > ID - an identifier for the current thread ; and< / li > <li > startTime - the system time in millis when this method is called . < / li > < / ul > <p / > <p > Call this method only for non - request servlet activities e . g . during init () or destroy () . [CODESPLIT] public static String setupNonRequestContext ( ) { // Setup context.
 MDC . put ( "ID" , Long . toString ( logServerAccessId . incrementAndGet ( ) ) ) ; MDC . put ( "startTime" , Long . toString ( System . currentTimeMillis ( ) ) ) ; return "Non-request thread opening." ; }


Input: API [CODESPLIT] public String generate ( String dataseturl ) throws IOException { StringWriter sw = new StringWriter ( ) ; IndentWriter printer = new IndentWriter ( sw ) ; printer . marginPrintln ( "<DatasetServices" ) ; printer . indent ( 2 ) ; printer . marginPrintln ( "xmlns=\"http://xml.opendap.org/ns/DAP/4.0/dataset-services#\">" ) ; printer . outdent ( ) ; printer . marginPrint ( "<DapVersion>" ) ; printer . print ( DapProtocol . X_DAP_VERSION ) ; printer . println ( "</DapVersion>" ) ; printer . marginPrint ( "<ServerSoftwareVersion>" ) ; printer . print ( DapProtocol . X_DAP_SERVER ) ; printer . println ( "</ServerSoftwareVersion>" ) ; printer . marginPrintln ( "<Service title=\"DAP4 Dataset Services\"" ) ; printer . indent ( 3 ) ; printer . marginPrintln ( "role=\"http://services.opendap.org/dap4/dataset-services\">" ) ; printer . outdent ( 3 ) ; printer . indent ( ) ; printer . marginPrint ( "<link type=\"" ) ; printer . print ( DapProtocol . contenttypes . get ( RequestMode . DSR ) . contenttype ) ; printer . println ( "\"" ) ; printer . indent ( 2 ) ; printer . marginPrint ( "href=\"" ) ; printer . print ( dataseturl ) ; printer . println ( "\">" ) ; printer . outdent ( 2 ) ; printer . indent ( ) ; printer . marginPrintln ( "<alt type=\"text/xml\"/>" ) ; printer . outdent ( ) ; printer . marginPrintln ( "</link>" ) ; printer . marginPrintln ( "<link type=\"text/xml\"" ) ; printer . indent ( 2 ) ; printer . marginPrint ( "href=\"" ) ; printer . print ( dataseturl ) ; printer . println ( ".xml\"/>" ) ; printer . outdent ( 2 ) ; printer . outdent ( ) ; printer . marginPrintln ( "</Service>" ) ; printer . marginPrintln ( "<Service title=\"DAP4 Dataset Metadata\"" ) ; printer . indent ( 3 ) ; printer . marginPrintln ( "role=\"http://services.opendap.org/dap4/dataset-metadata\">" ) ; printer . outdent ( 3 ) ; printer . indent ( ) ; printer . marginPrint ( "<link type=\"" ) ; printer . print ( DapProtocol . contenttypes . get ( RequestMode . DMR ) . contenttype ) ; printer . println ( "\"" ) ; printer . indent ( 2 ) ; printer . marginPrint ( "href=\"" ) ; printer . print ( dataseturl ) ; printer . println ( ".dmr\">" ) ; printer . outdent ( 2 ) ; printer . indent ( ) ; printer . marginPrintln ( "<alt type=\"text/xml\"/>" ) ; printer . outdent ( ) ; printer . marginPrintln ( "</link>" ) ; printer . marginPrintln ( "<link type=\"text/xml\"" ) ; printer . indent ( 2 ) ; printer . marginPrint ( "href=\"" ) ; printer . print ( dataseturl ) ; printer . println ( ".dmr.xml\"/>" ) ; printer . outdent ( 2 ) ; printer . outdent ( ) ; printer . marginPrintln ( "</Service>" ) ; printer . marginPrintln ( "<Service title=\"DAP4 Dataset Data\"" ) ; printer . indent ( 2 ) ; printer . marginPrintln ( "role=\"http://services.opendap.org/dap4/data\">" ) ; printer . outdent ( 2 ) ; printer . indent ( ) ; printer . marginPrint ( "<link type=\"" ) ; printer . print ( DapProtocol . contenttypes . get ( RequestMode . DAP ) . contenttype ) ; printer . println ( "\"" ) ; printer . indent ( 2 ) ; printer . marginPrint ( "href=\"" ) ; printer . print ( dataseturl ) ; printer . println ( ".dap\"/>" ) ; printer . outdent ( 2 ) ; printer . outdent ( ) ; printer . marginPrintln ( "</Service>" ) ; printer . outdent ( ) ; printer . marginPrintln ( "</DatasetServices>" ) ; printer . flush ( ) ; printer . close ( ) ; sw . close ( ) ; return sw . toString ( ) ; }


Input: Return a catalog for the given directory . [CODESPLIT] public InvCatalog getDirCatalog ( File directory , String filterPattern , boolean sortInIncreasingOrder , boolean addDatasetSize ) { return ( this . getDirCatalog ( directory , filterPattern , sortInIncreasingOrder , null , addDatasetSize , null , null , null ) ) ; }


Input: Find which index holds the value want [CODESPLIT] public int findIdx ( int want ) { if ( isConstant ) return ( want == start ) ? 0 : - 1 ; if ( isSequential ) return want - start ; if ( isSorted ) { return Arrays . binarySearch ( raw , want ) ; } // linear search for ( int i = 0 ; i < raw . length ; i ++ ) if ( raw [ i ] == want ) return i ; return - 1 ; }


Input: Create an InvMetadata content object from an XML document at a named URL . The content object is an ArrayList of CatalogGenConfig instances . [CODESPLIT] private Object readMetadataContentFromURL ( InvDataset dataset , String urlString ) throws java . net . MalformedURLException , java . io . IOException { // @todo This isn't used anywhere. Remove? Document doc ; try { SAXBuilder builder = new SAXBuilder ( true ) ; doc = builder . build ( urlString ) ; } catch ( JDOMException e ) { log . error ( "CatGenConfigMetadataFactory parsing error= \n" + e . getMessage ( ) ) ; throw new java . io . IOException ( "CatGenConfigMetadataFactory parsing error= " + e . getMessage ( ) ) ; } if ( showParsedXML ) { XMLOutputter xmlOut = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; System . out . println ( "*** catalog/showParsedXML = \n" + xmlOut . outputString ( doc ) + "\n*******" ) ; } return ( readMetadataContentJdom ( dataset , doc . getRootElement ( ) ) ) ; }


Input: Create an InvMetadata content object from an org . w3c . dom . Element . The content object is an ArrayList of CatalogGenConfig instances . [CODESPLIT] public Object readMetadataContent ( InvDataset dataset , org . jdom2 . Element mdataElement ) { log . debug ( "readMetadataContent(): ." ) ; // convert to JDOM element //Element mdataElement = builder.build( mdataDomElement ); return readMetadataContentJdom ( dataset , mdataElement ) ; }


Input: Serialize the InvMetadata content object to a org . w3c . dom . Element [CODESPLIT] public void addMetadataContent ( org . jdom2 . Element mdataJdomElement , Object contentObject ) { // convert to JDOM element //Element mdataJdomElement = builder.build( mdataElement ); ArrayList catGenConfigList = ( ArrayList ) contentObject ; Iterator iter = catGenConfigList . iterator ( ) ; while ( iter . hasNext ( ) ) { CatalogGenConfig cgc = ( CatalogGenConfig ) iter . next ( ) ; mdataJdomElement . addContent ( createCatGenConfigElement ( cgc ) ) ; } }


Input: Validate the content object . [CODESPLIT] public boolean validateMetadataContent ( Object contentObject , StringBuilder out ) { boolean ok = true ; ArrayList catGenConfigList = ( ArrayList ) contentObject ; Iterator iter = catGenConfigList . iterator ( ) ; while ( iter . hasNext ( ) ) { CatalogGenConfig catGenConf = ( CatalogGenConfig ) iter . next ( ) ; ok &= catGenConf . validate ( out ) ; } return ok ; }


Input: Given a metadata JDOM element return metadata content object ( ArrayList of CatalogGenConfig ) . <p / > From the given metadata JDOM element build ( and return ) an ArrayList of CatalogGenConfig instances . [CODESPLIT] private Object readMetadataContentJdom ( InvDataset dataset , Element mdataElement ) { Namespace catGenConfigNamespace = null ; ArrayList catGenConfigList = new ArrayList ( ) ; // Get the "catalogGenConfig" children elements with // CatalogGenConfig namespace first and then with THREDDS namespace. Iterator iter = mdataElement . getChildren ( "catalogGenConfig" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) . iterator ( ) ; if ( ! iter . hasNext ( ) ) iter = mdataElement . getChildren ( "catalogGenConfig" , mdataElement . getNamespace ( ) ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Element catGenConfigElement = ( Element ) iter . next ( ) ; if ( debug ) { log . debug ( "readMetadataContent=" + catGenConfigElement ) ; } catGenConfigList . add ( readCatGenConfigElement ( dataset , catGenConfigElement ) ) ; } return ( catGenConfigList ) ; }


Input: Return a CatalogGenConfig when given a catalogGenConfig JDOM element . [CODESPLIT] private CatalogGenConfig readCatGenConfigElement ( InvDataset parentDataset , Element catGenConfElement ) { String type = catGenConfElement . getAttributeValue ( "type" ) ; CatalogGenConfig catGenConf = new CatalogGenConfig ( parentDataset , type ) ; // get any datasetSource elements java . util . List list = catGenConfElement . getChildren ( "datasetSource" , catGenConfElement . getNamespace ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Element dsSourceElement = ( Element ) list . get ( i ) ; catGenConf . setDatasetSource ( readDatasetSourceElement ( parentDataset , dsSourceElement ) ) ; } // @todo Start only allowing datasetSource elements in catalogGenConfig elements. //    // get any datasetNamer elements //    list = catGenConfElement.getChildren( "datasetNamer", catGenConfElement.getNamespace() ); //    for (int i=0; i< list.size(); i++) //    { //      Element dsNamerElement = (Element) list.get(i); // //      catGenConf.addDatasetNamer( readDatasetNamerElement( parentDataset, //                                                           dsNamerElement)); //    } return ( catGenConf ) ; }


Input: Return a DatasetSource when given a datasetSource JDOM element . [CODESPLIT] private DatasetSource readDatasetSourceElement ( InvDataset parentDataset , Element dsSourceElement ) { String name = dsSourceElement . getAttributeValue ( "name" ) ; String type = dsSourceElement . getAttributeValue ( "type" ) ; String structure = dsSourceElement . getAttributeValue ( "structure" ) ; String accessPoint = dsSourceElement . getAttributeValue ( "accessPoint" ) ; String createCatalogRefs = dsSourceElement . getAttributeValue ( "createCatalogRefs" ) ; // get the resultService element Element resultServiceElement = dsSourceElement . getChild ( "resultService" , dsSourceElement . getNamespace ( ) ) ; ResultService resultService = readResultServiceElement ( parentDataset , resultServiceElement ) ; DatasetSource dsSource = DatasetSource . newDatasetSource ( name , DatasetSourceType . getType ( type ) , DatasetSourceStructure . getStructure ( structure ) , accessPoint , resultService ) ; if ( createCatalogRefs != null ) { dsSource . setCreateCatalogRefs ( Boolean . valueOf ( createCatalogRefs ) . booleanValue ( ) ) ; } // get any datasetNamer elements java . util . List list = dsSourceElement . getChildren ( "datasetNamer" , dsSourceElement . getNamespace ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Element dsNamerElement = ( Element ) list . get ( i ) ; dsSource . addDatasetNamer ( readDatasetNamerElement ( parentDataset , dsNamerElement ) ) ; } // get any datasetFilter elements list = dsSourceElement . getChildren ( "datasetFilter" , dsSourceElement . getNamespace ( ) ) ; for ( int i = 0 ; i < list . size ( ) ; i ++ ) { Element dsFilterElement = ( Element ) list . get ( i ) ; dsSource . addDatasetFilter ( readDatasetFilterElement ( dsSource , dsFilterElement ) ) ; } return ( dsSource ) ; }


Input: Return a DatasetNamer when given a datasetNamer JDOM element . [CODESPLIT] private DatasetNamer readDatasetNamerElement ( InvDataset parentDataset , Element dsNamerElement ) { String name = dsNamerElement . getAttributeValue ( "name" ) ; String addLevel = dsNamerElement . getAttributeValue ( "addLevel" ) ; String type = dsNamerElement . getAttributeValue ( "type" ) ; String matchPattern = dsNamerElement . getAttributeValue ( "matchPattern" ) ; String substitutePattern = dsNamerElement . getAttributeValue ( "substitutePattern" ) ; String attribContainer = dsNamerElement . getAttributeValue ( "attribContainer" ) ; String attribName = dsNamerElement . getAttributeValue ( "attribName" ) ; DatasetNamer dsNamer = new DatasetNamer ( parentDataset , name , addLevel , type , matchPattern , substitutePattern , attribContainer , attribName ) ; return ( dsNamer ) ; }


Input: Return a DatasetFilter when given a datasetFilter JDOM element . [CODESPLIT] private DatasetFilter readDatasetFilterElement ( DatasetSource parentDatasetSource , Element dsFilterElement ) { String name = dsFilterElement . getAttributeValue ( "name" ) ; String type = dsFilterElement . getAttributeValue ( "type" ) ; String matchPattern = dsFilterElement . getAttributeValue ( "matchPattern" ) ; DatasetFilter dsFilter = new DatasetFilter ( parentDatasetSource , name , DatasetFilter . Type . getType ( type ) , matchPattern ) ; String matchPatternTarget = dsFilterElement . getAttributeValue ( "matchPatternTarget" ) ; dsFilter . setMatchPatternTarget ( matchPatternTarget ) ; if ( dsFilterElement . getAttributeValue ( "applyToCollectionDatasets" ) != null ) { boolean applyToCollectionDatasets = Boolean . valueOf ( dsFilterElement . getAttributeValue ( "applyToCollectionDatasets" ) ) . booleanValue ( ) ; dsFilter . setApplyToCollectionDatasets ( applyToCollectionDatasets ) ; } if ( dsFilterElement . getAttributeValue ( "applyToAtomicDatasets" ) != null ) { boolean applyToAtomicDatasets = Boolean . valueOf ( dsFilterElement . getAttributeValue ( "applyToAtomicDatasets" ) ) . booleanValue ( ) ; dsFilter . setApplyToAtomicDatasets ( applyToAtomicDatasets ) ; } if ( dsFilterElement . getAttributeValue ( "rejectMatchingDatasets" ) != null ) { boolean rejectMatchingDatasets = Boolean . valueOf ( dsFilterElement . getAttributeValue ( "rejectMatchingDatasets" ) ) . booleanValue ( ) ; dsFilter . setRejectMatchingDatasets ( rejectMatchingDatasets ) ; } return ( dsFilter ) ; }


Input: Return a ResultService when given a resultService JDOM element . [CODESPLIT] private ResultService readResultServiceElement ( InvDataset parentDataset , Element resultServiceElement ) { String name = resultServiceElement . getAttributeValue ( "name" ) ; String serviceType = resultServiceElement . getAttributeValue ( "serviceType" ) ; String base = resultServiceElement . getAttributeValue ( "base" ) ; String suffix = resultServiceElement . getAttributeValue ( "suffix" ) ; String accessPointHeader = resultServiceElement . getAttributeValue ( "accessPointHeader" ) ; return ( new ResultService ( name , ServiceType . getType ( serviceType ) , base , suffix , accessPointHeader ) ) ; }


Input: Create a catalogGenConfig JDOM element [CODESPLIT] private org . jdom2 . Element createCatGenConfigElement ( CatalogGenConfig cgc ) { // @todo Need to deal with the 0.6 and 1.0 namespaces. Element cgcElem = new Element ( "catalogGenConfig" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( cgc != null ) { if ( cgc . getType ( ) != null ) { cgcElem . setAttribute ( "type" , cgc . getType ( ) . toString ( ) ) ; } // Add 'datasetSource' element DatasetSource dsSource = cgc . getDatasetSource ( ) ; cgcElem . addContent ( createDatasetSourceElement ( dsSource ) ) ; } return ( cgcElem ) ; }


Input: Create a DatasetSource JDOM element [CODESPLIT] private org . jdom2 . Element createDatasetSourceElement ( DatasetSource dsSource ) { Element dssElem = new Element ( "datasetSource" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( dsSource != null ) { // Add 'name' attribute. if ( dsSource . getName ( ) != null ) { dssElem . setAttribute ( "name" , dsSource . getName ( ) ) ; } // Add 'type' attribute. if ( dsSource . getType ( ) != null ) { dssElem . setAttribute ( "type" , dsSource . getType ( ) . toString ( ) ) ; } // Add 'structure' attribute. if ( dsSource . getStructure ( ) != null ) { dssElem . setAttribute ( "structure" , dsSource . getStructure ( ) . toString ( ) ) ; } // Add 'accessPoint' attribute. if ( dsSource . getAccessPoint ( ) != null ) { dssElem . setAttribute ( "accessPoint" , dsSource . getAccessPoint ( ) ) ; } // Add 'createCatalogRefs' attribute. dssElem . setAttribute ( "createCatalogRefs" , Boolean . toString ( dsSource . isCreateCatalogRefs ( ) ) ) ; // Add 'resultService' element ResultService rs = dsSource . getResultService ( ) ; dssElem . addContent ( createResultServiceElement ( rs ) ) ; // Add 'datasetNamer' elements java . util . List list = dsSource . getDatasetNamerList ( ) ; for ( int j = 0 ; j < list . size ( ) ; j ++ ) { DatasetNamer dsNamer = ( DatasetNamer ) list . get ( j ) ; dssElem . addContent ( createDatasetNamerElement ( dsNamer ) ) ; } // Add 'datasetFilter' elements list = dsSource . getDatasetFilterList ( ) ; for ( int j = 0 ; j < list . size ( ) ; j ++ ) { DatasetFilter dsFilter = ( DatasetFilter ) list . get ( j ) ; dssElem . addContent ( createDatasetFilterElement ( dsFilter ) ) ; } } return ( dssElem ) ; }


Input: Create a DatasetNamer JDOM element [CODESPLIT] private org . jdom2 . Element createDatasetNamerElement ( DatasetNamer dsNamer ) { Element dsnElem = new Element ( "datasetNamer" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( dsNamer != null ) { // Add 'name' attribute. if ( dsNamer . getName ( ) != null ) { dsnElem . setAttribute ( "name" , dsNamer . getName ( ) ) ; } // Add 'addLevel' attribute. dsnElem . setAttribute ( "addLevel" , Boolean . toString ( dsNamer . getAddLevel ( ) ) ) ; // Add 'type' attribute. if ( dsNamer . getType ( ) != null ) { dsnElem . setAttribute ( "type" , dsNamer . getType ( ) . toString ( ) ) ; } // Add 'matchPattern' attribute. if ( dsNamer . getMatchPattern ( ) != null ) { dsnElem . setAttribute ( "matchPattern" , dsNamer . getMatchPattern ( ) ) ; } // Add 'subsitutePattern' attribute. if ( dsNamer . getSubstitutePattern ( ) != null ) { dsnElem . setAttribute ( "substitutePattern" , dsNamer . getSubstitutePattern ( ) ) ; } // Add 'attribContainer' attribute. if ( dsNamer . getAttribContainer ( ) != null ) { dsnElem . setAttribute ( "attribContainer" , dsNamer . getAttribContainer ( ) ) ; } // Add 'attribName' attribute. if ( dsNamer . getAttribName ( ) != null ) { dsnElem . setAttribute ( "attribName" , dsNamer . getAttribName ( ) ) ; } } return ( dsnElem ) ; }


Input: Create a DatasetFilter JDOM element [CODESPLIT] private org . jdom2 . Element createDatasetFilterElement ( DatasetFilter dsFilter ) { Element dsfElem = new Element ( "datasetFilter" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( dsFilter != null ) { // Add 'name' attribute. if ( dsFilter . getName ( ) != null ) { dsfElem . setAttribute ( "name" , dsFilter . getName ( ) ) ; } // Add 'type' attribute. if ( dsFilter . getType ( ) != null ) { dsfElem . setAttribute ( "type" , dsFilter . getType ( ) . toString ( ) ) ; } // Add 'matchPattern' attribute. if ( dsFilter . getMatchPattern ( ) != null ) { dsfElem . setAttribute ( "matchPattern" , dsFilter . getMatchPattern ( ) ) ; } // Add 'matchPatternTarget' attribute. if ( dsFilter . getMatchPatternTarget ( ) != null ) { dsfElem . setAttribute ( "matchPatternTarget" , dsFilter . getMatchPatternTarget ( ) ) ; } // Add 'applyToCollectionDatasets' attribute. dsfElem . setAttribute ( "applyToCollectionDatasets" , String . valueOf ( dsFilter . isApplyToCollectionDatasets ( ) ) ) ; // Add 'applyToAtomicDatasets' attribute. dsfElem . setAttribute ( "applyToAtomicDatasets" , String . valueOf ( dsFilter . isApplyToAtomicDatasets ( ) ) ) ; // Add 'rejectMatchingDatasets' attribute. dsfElem . setAttribute ( "rejectMatchingDatasets" , String . valueOf ( dsFilter . isRejectMatchingDatasets ( ) ) ) ; } return ( dsfElem ) ; }


Input: Create a ResultService JDOM element [CODESPLIT] private org . jdom2 . Element createResultServiceElement ( ResultService resultService ) { Element rsElem = new Element ( "resultService" , CATALOG_GEN_CONFIG_NAMESPACE_0_5 ) ; if ( resultService != null ) { // Add 'name' attribute. if ( resultService . getName ( ) != null ) { rsElem . setAttribute ( "name" , resultService . getName ( ) ) ; } // Add 'serviceType' attribute. if ( resultService . getServiceType ( ) != null ) { rsElem . setAttribute ( "serviceType" , resultService . getServiceType ( ) . toString ( ) ) ; } // Add 'base' attribute. if ( resultService . getBase ( ) != null ) { rsElem . setAttribute ( "base" , resultService . getBase ( ) ) ; } // Add 'suffix' attribute. if ( resultService . getSuffix ( ) != null ) { rsElem . setAttribute ( "suffix" , resultService . getSuffix ( ) ) ; } // Add 'accessPointHeader' attribute. if ( resultService . getAccessPointHeader ( ) != null ) { rsElem . setAttribute ( "accessPointHeader" , resultService . getAccessPointHeader ( ) ) ; } } return ( rsElem ) ; }


Input: Return the value of the named flag . If it doesnt exist it will be added to the store and the menu with a value of false . [CODESPLIT] static public boolean isSet ( String flagName ) { if ( store == null ) return false ; NamePart np = partit ( flagName ) ; if ( debug ) { try { if ( ( np . storeName . length ( ) > 0 ) && ! store . nodeExists ( np . storeName ) ) System . out . println ( "Debug.isSet create node = " + flagName + " " + np ) ; else if ( null == store . node ( np . storeName ) . get ( np . keyName , null ) ) System . out . println ( "Debug.isSet create flag = " + flagName + " " + np ) ; } catch ( BackingStoreException e ) { } } // add it if it doesnt already exist boolean value = store . node ( np . storeName ) . getBoolean ( np . keyName , false ) ; store . node ( np . storeName ) . putBoolean ( np . keyName , value ) ; return value ; }


Input: Construct cascading pull - aside menus using the values of the debug flags in the Preferences object . [CODESPLIT] static public void constructMenu ( JMenu topMenu ) { if ( debug ) System . out . println ( "Debug.constructMenu " ) ; if ( topMenu . getItemCount ( ) > 0 ) topMenu . removeAll ( ) ; try { addToMenu ( topMenu , store ) ; // recursive } catch ( BackingStoreException e ) { } topMenu . revalidate ( ) ; }


Input: recursive menu adding [CODESPLIT] static private void addToMenu ( JMenu menu , Preferences prefs ) throws BackingStoreException { if ( debug ) System . out . println ( " addMenu " + prefs . name ( ) ) ; String [ ] keys = prefs . keys ( ) ; for ( String key : keys ) { boolean bval = prefs . getBoolean ( key , false ) ; String fullname = prefs . absolutePath ( ) + "/" + key ; menu . add ( new DebugMenuItem ( fullname , key , bval ) ) ; // menu leaf if ( debug ) System . out . println ( "   leaf= <" + key + "><" + fullname + ">" ) ; } String [ ] kidName = prefs . childrenNames ( ) ; for ( String aKidName : kidName ) { Preferences pkid = prefs . node ( aKidName ) ; JMenu subMenu = new JMenu ( pkid . name ( ) ) ; menu . add ( subMenu ) ; addToMenu ( subMenu , pkid ) ; } }


Input:
Add parameters from the table [CODESPLIT] public void addParameters ( String tbl ) throws IOException { try ( InputStream is = getInputStream ( tbl ) ) { if ( is == null ) { throw new IOException ( "Unable to open " + tbl ) ; } String content = readContents ( is ) ; // LOOK this is silly - should just read one line at a time
 // List           lines   = StringUtil.split(content, "\n", false);
 String [ ] lines = content . split ( "\n" ) ; List < String [ ] > result = new ArrayList <> ( ) ; for ( String line : lines ) { //String line  = (String) lines.get(i);
 String tline = line . trim ( ) ; if ( tline . length ( ) == 0 ) { continue ; } if ( tline . startsWith ( "!" ) ) { continue ; } String [ ] words = new String [ indices . length ] ; for ( int idx = 0 ; idx < indices . length ; idx ++ ) { if ( indices [ idx ] >= tline . length ( ) ) { continue ; } if ( indices [ idx ] + lengths [ idx ] > tline . length ( ) ) { words [ idx ] = line . substring ( indices [ idx ] ) ; } else { words [ idx ] = line . substring ( indices [ idx ] , indices [ idx ] + lengths [ idx ] ) ; } //if (trimWords) {
 words [ idx ] = words [ idx ] . trim ( ) ; //}
 } result . add ( words ) ; } for ( String [ ] aResult : result ) { GempakParameter p = makeParameter ( aResult ) ; if ( p != null ) { if ( p . getName ( ) . contains ( "(" ) ) { templateParamMap . put ( p . getName ( ) , p ) ; } else { paramMap . put ( p . getName ( ) , p ) ; } } } } }


Input:
Make a parameter from the tokens [CODESPLIT] private GempakParameter makeParameter ( String [ ] words ) { int num = 0 ; String description ; if ( words [ 0 ] != null ) { num = ( int ) Double . parseDouble ( words [ 0 ] ) ; } if ( ( words [ 3 ] == null ) || words [ 3 ] . equals ( "" ) ) { // no param name
 return null ; } String name = words [ 3 ] ; if ( name . contains ( "-" ) ) { int first = name . indexOf ( "-" ) ; int last = name . lastIndexOf ( "-" ) ; StringBuilder buf = new StringBuilder ( name . substring ( 0 , first ) ) ; buf . append ( "(" ) ; for ( int i = first ; i <= last ; i ++ ) { buf . append ( "\\d" ) ; } buf . append ( ")" ) ; buf . append ( name . substring ( last + 1 ) ) ; name = buf . toString ( ) ; } if ( ( words [ 1 ] == null ) || words [ 1 ] . equals ( "" ) ) { description = words [ 3 ] ; } else { description = words [ 1 ] ; } String unit = words [ 2 ] ; if ( unit != null ) { unit = unit . replaceAll ( "\\*\\*" , "" ) ; if ( unit . equals ( "-" ) ) { unit = "" ; } } int decimalScale ; try { decimalScale = Integer . parseInt ( words [ 4 ] . trim ( ) ) ; } catch ( NumberFormatException ne ) { decimalScale = 0 ; } return new GempakParameter ( num , name , description , unit , decimalScale ) ; }


Input:
Get the parameter for the given name [CODESPLIT] public GempakParameter getParameter ( String name ) { GempakParameter param = paramMap . get ( name ) ; if ( param == null ) { // try the regex list
 Set < String > keys = templateParamMap . keySet ( ) ; if ( ! keys . isEmpty ( ) ) { for ( String key : keys ) { Pattern p = Pattern . compile ( key ) ; Matcher m = p . matcher ( name ) ; if ( m . matches ( ) ) { //System.out.println("found match " + key + " for " + name);
 String value = m . group ( 1 ) ; GempakParameter match = templateParamMap . get ( key ) ; param = new GempakParameter ( match . getNumber ( ) , name , match . getDescription ( ) + " (" + value + " hour)" , match . getUnit ( ) , match . getDecimalScale ( ) ) ; paramMap . put ( name , param ) ; break ; } } } } return param ; }


Input:
Test [CODESPLIT] public static void main ( String [ ] args ) throws IOException { GempakParameterTable pt = new GempakParameterTable ( ) ; //pt.addParameters("resources/nj22/tables/gempak/wmogrib3.tbl");
 pt . addParameters ( "resources/nj22/tables/gempak/params.tbl" ) ; if ( args . length > 0 ) { String param = args [ 0 ] ; GempakParameter parm = pt . getParameter ( param ) ; if ( parm != null ) { System . out . println ( "Found " + param + ": " + parm ) ; } } }


Input: Read in the bytes from the given InputStream and construct and return a String . Closes the InputStream argument . [CODESPLIT] private String readContents ( InputStream is ) throws IOException { return new String ( readBytes ( is ) , CDM . utf8Charset ) ; }


Input: Read the bytes in the given input stream . [CODESPLIT] private byte [ ] readBytes ( InputStream is ) throws IOException { int totalRead = 0 ; byte [ ] content = new byte [ 1000000 ] ; while ( true ) { int howMany = is . read ( content , totalRead , content . length - totalRead ) ; if ( howMany < 0 ) { break ; } if ( howMany == 0 ) { continue ; } totalRead += howMany ; if ( totalRead >= content . length ) { byte [ ] tmp = content ; int newLength = ( ( content . length < 25000000 ) ? content . length * 2 : content . length + 5000000 ) ; content = new byte [ newLength ] ; System . arraycopy ( tmp , 0 , content , 0 , totalRead ) ; } } is . close ( ) ; byte [ ] results = new byte [ totalRead ] ; System . arraycopy ( content , 0 , results , 0 , totalRead ) ; return results ; }


Input:
Get the input stream to the given resource [CODESPLIT] private InputStream getInputStream ( String resourceName ) throws IOException { // Try class loader to get resource
 ClassLoader cl = GempakParameterTable . class . getClassLoader ( ) ; InputStream s = cl . getResourceAsStream ( resourceName ) ; if ( s != null ) { return s ; } //Try the file system
 File f = new File ( resourceName ) ; if ( f . exists ( ) ) { s = new FileInputStream ( f ) ; } if ( s != null ) { return s ; } //Try it as a url
 Matcher m = Pattern . compile ( " " ) . matcher ( resourceName ) ; String encodedUrl = m . replaceAll ( "%20" ) ; URL dataUrl = new URL ( encodedUrl ) ; URLConnection connection = dataUrl . openConnection ( ) ; return connection . getInputStream ( ) ; }


Input: wml2 : defaultPointMetadata / wml2 : DefaultTVPMeasurementMetadata / wml2 : uom [CODESPLIT] public static UnitReference initUom ( UnitReference uom , VariableSimpleIF dataVar ) { // @code String udunits = dataVar . getUnitsString ( ) ; if ( udunits == null ) { // Variable may not have a "units" attribute. return null ; } String ucum = ErddapEDUnits . udunitsToUcum ( udunits ) ; uom . setCode ( ucum ) ; return uom ; }


Input: _more_ [CODESPLIT] protected static double getMetersConversionFactor ( String unitsString ) throws Exception { SimpleUnit unit = SimpleUnit . factoryWithExceptions ( unitsString ) ; return unit . convertTo ( 1.0 , SimpleUnit . meterUnit ) ; }


Input: _more_ [CODESPLIT] public String getDetailInfo ( ) { StringBuffer sbuff = new StringBuffer ( ) ; sbuff . append ( "TrajectoryObsDataset\n" ) ; sbuff . append ( "  adapter   = " + getClass ( ) . getName ( ) + "\n" ) ; sbuff . append ( "  trajectories:" + "\n" ) ; for ( Iterator it = this . getTrajectoryIds ( ) . iterator ( ) ; it . hasNext ( ) ; ) { sbuff . append ( "      " + ( String ) it . next ( ) + "\n" ) ; } sbuff . append ( super . getDetailInfo ( ) ) ; return sbuff . toString ( ) ; }


Input: _more_ [CODESPLIT] public boolean syncExtend ( ) { if ( ! this . netcdfDataset . hasUnlimitedDimension ( ) ) { return false ; } try { if ( ! this . netcdfDataset . syncExtend ( ) ) { return false ; } } catch ( IOException e ) { return false ; } // Update number of points in this TrajectoryObsDataset and in the child TrajectoryObsDatatype. int newNumPoints = this . trajectoryDim . getLength ( ) ; if ( this . trajectoryNumPoint >= newNumPoints ) { return false ; } this . trajectoryNumPoint = newNumPoints ; ( ( Trajectory ) this . trajectory ) . setNumPoints ( this . trajectoryNumPoint ) ; // Update end date in this TrajectoryObsDataset and in the child TrajectoryObsDatatype. try { endDate = trajectory . getTime ( trajectoryNumPoint - 1 ) ; } catch ( IOException e ) { return false ; } ( ( Trajectory ) trajectory ) . setEndDate ( endDate ) ; return true ; }


Input: but we can define a stronger contract . [CODESPLIT] @ Override public PointFeature next ( ) throws NoSuchElementException { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( "The iteration has no more elements." ) ; } PointFeature pointFeat = pointIter . next ( ) ; assert pointFeat != null : "hasNext() should have been false. WTF?" ; calcBounds ( pointFeat ) ; return pointFeat ; }


Input: Make the level values from the specifications [CODESPLIT] protected double [ ] makeLevelValues ( ) { double [ ] vals = new double [ getSize ( ) ] ; for ( int i = 0 ; i < getSize ( ) ; i ++ ) { vals [ i ] = i ; } return vals ; }


Input: Replace the ensemble template parameter in a filename [CODESPLIT] public String replaceFileTemplate ( String filespec , int ensIndex ) { return filespec . replaceAll ( ENS_TEMPLATE_ID , getEnsembleNames ( ) . get ( ensIndex ) ) ; }


Input: Set extra information used by station obs datasets . [CODESPLIT] public void setStationInfo ( String stnIdVName , String stnDescVName ) { this . stnIdVName = stnIdVName ; this . stnDescVName = stnDescVName ; Variable stationVar = ncfile . findVariable ( stnIdVName ) ; stationIdType = stationVar . getDataType ( ) ; }


Input: This reads through all the records in the dataset and constructs a list of RecordPointObs or RecordStationObs . It does not cache the data . <p > If stnIdVName is not null its a StationDataset then construct a Station HashMap of StationImpl objects . Add the RecordStationObs into the list of obs for that station . [CODESPLIT] public ArrayList readAllCreateObs ( CancelTask cancel ) throws IOException { // see if its a station or point dataset boolean hasStations = stnIdVName != null ; if ( hasStations ) stnHash = new HashMap < Object , ucar . unidata . geoloc . Station > ( ) ; // get min and max date and lat,lon double minDate = Double . MAX_VALUE ; double maxDate = - Double . MAX_VALUE ; double minLat = Double . MAX_VALUE ; double maxLat = - Double . MAX_VALUE ; double minLon = Double . MAX_VALUE ; double maxLon = - Double . MAX_VALUE ; // read all the data, create a RecordObs ArrayList records = new ArrayList ( ) ; int recno = 0 ; try ( StructureDataIterator ii = recordVar . getStructureIterator ( ) ) { while ( ii . hasNext ( ) ) { StructureData sdata = ii . next ( ) ; StructureMembers members = sdata . getStructureMembers ( ) ; Object stationId = null ; if ( hasStations ) { if ( stationIdType == DataType . INT ) { int stationNum = sdata . getScalarInt ( stnIdVName ) ; stationId = new Integer ( stationNum ) ; } else stationId = sdata . getScalarString ( stnIdVName ) . trim ( ) ; } String desc = ( stnDescVName == null ) ? null : sdata . getScalarString ( stnDescVName ) ; double lat = sdata . convertScalarDouble ( latVName ) ; double lon = sdata . convertScalarDouble ( lonVName ) ; double alt = ( altVName == null ) ? Double . NaN : altScaleFactor * sdata . convertScalarDouble ( altVName ) ; double obsTime = sdata . convertScalarDouble ( members . findMember ( obsTimeVName ) ) ; double nomTime = ( nomTimeVName == null ) ? obsTime : sdata . convertScalarDouble ( members . findMember ( nomTimeVName ) ) ; //double obsTime = sdata.convertScalarDouble( members.findMember( obsTimeVName) ); //double nomTime = (nomTimeVName == null) ? obsTime : sdata.convertScalarDouble( members.findMember( nomTimeVName)); if ( hasStations ) { StationImpl stn = ( StationImpl ) stnHash . get ( stationId ) ; if ( stn == null ) { stn = new StationImpl ( stationId . toString ( ) , desc , lat , lon , alt ) ; stnHash . put ( stationId , stn ) ; } RecordStationObs stnObs = new RecordStationObs ( stn , obsTime , nomTime , recno ) ; records . add ( stnObs ) ; stn . addObs ( stnObs ) ; } else { records . add ( new RecordPointObs ( new ucar . unidata . geoloc . EarthLocationImpl ( lat , lon , alt ) , obsTime , nomTime , recno ) ) ; } // track date range and bounding box minDate = Math . min ( minDate , obsTime ) ; maxDate = Math . max ( maxDate , obsTime ) ; minLat = Math . min ( minLat , lat ) ; maxLat = Math . max ( maxLat , lat ) ; minLon = Math . min ( minLon , lon ) ; maxLon = Math . max ( maxLon , lon ) ; recno ++ ; if ( ( cancel != null ) && cancel . isCancel ( ) ) return null ; } } boundingBox = new LatLonRect ( new LatLonPointImpl ( minLat , minLon ) , new LatLonPointImpl ( maxLat , maxLon ) ) ; return records ; }


Input: Register for PropertyChange events when the value of the Field changes . When accept () is called you will get a new PropertyChangeEvent ( this fldName oldValue newValue ) where the oldValue newValue will be String Integer Boolean etc . [CODESPLIT] public void addPropertyChangeListener ( PropertyChangeListener pcl ) { if ( listenerList == null ) listenerList = new javax . swing . event . EventListenerList ( ) ; listenerList . add ( PropertyChangeListener . class , pcl ) ; }


Input: See if edit value is valid put error message in buff . [CODESPLIT] protected boolean validate ( StringBuffer buff ) { if ( ! _validate ( buff ) ) return false ; Object editValue = getEditValue ( ) ; if ( editValue == null ) return false ; for ( FieldValidator v : validators ) { if ( ! v . validate ( this , editValue , buff ) ) return false ; } if ( acceptIfDifferent ( editValue ) ) { setEditValue ( validValue ) ; sendEvent ( ) ; } return true ; }


Input: Get current value from editComponent save to store . If different from old value fire PropertyChangeEvent . Return false if invalid format add error message to buff if not null . [CODESPLIT] protected boolean accept ( StringBuffer buff ) { if ( ! validate ( buff ) ) { validate ( buff ) ; return false ; } if ( acceptIfDifferent ( getEditValue ( ) ) ) { setStoreValue ( validValue ) ; sendEvent ( ) ; } return true ; }


Input:
See if this value is different from current accepted value ( using equals () ) ; If so set old value to accepted value then accepted value to this value . [CODESPLIT] protected boolean acceptIfDifferent ( Object newValue ) { // System.out.println("isDifferent "+newValue+" "+value);
 if ( ( newValue == null ) && ( validValue == null ) ) return false ; if ( ( validValue != null ) && validValue . equals ( newValue ) ) return false ; previousValue = getValue ( ) ; validValue = newValue ; return true ; }


Input: / * Get value from store put value into editComponent [CODESPLIT] protected void restoreValue ( Object defValue ) { if ( storeData != null ) { validValue = getStoreValue ( defValue ) ; setEditValue ( validValue ) ; } }


Input: The value in the store has changed : update the edit component send event if its different from previous [CODESPLIT] protected void setNewValueFromStore ( ) { Object newValue = getStoreValue ( validValue ) ; if ( acceptIfDifferent ( newValue ) ) { setEditValue ( newValue ) ; sendEvent ( ) ; } }


Input: send PropertyChangeEvent [CODESPLIT] protected void sendEvent ( ) { if ( listenerList != null ) { PropertyChangeEvent event = new PropertyChangeEvent ( this , name , previousValue , getValue ( ) ) ; Object [ ] listeners = listenerList . getListenerList ( ) ; for ( int i = listeners . length - 2 ; i >= 0 ; i -= 2 )  ( ( PropertyChangeListener ) listeners [ i + 1 ] ) . propertyChange ( event ) ; } }


Input: An integer input field with an associated CDM . UNITS label . [CODESPLIT] static private void showFormatInfo ( JFormattedTextField tf ) { JFormattedTextField . AbstractFormatter ff = tf . getFormatter ( ) ; System . out . println ( "AbstractFormatter  " + ff . getClass ( ) . getName ( ) ) ; if ( ff instanceof NumberFormatter ) { NumberFormatter nf = ( NumberFormatter ) ff ; Format f = nf . getFormat ( ) ; System . out . println ( " Format  = " + f . getClass ( ) . getName ( ) ) ; if ( f instanceof NumberFormat ) { NumberFormat nfat = ( NumberFormat ) f ; System . out . println ( " getMinimumIntegerDigits=" + nfat . getMinimumIntegerDigits ( ) ) ; System . out . println ( " getMaximumIntegerDigits=" + nfat . getMaximumIntegerDigits ( ) ) ; System . out . println ( " getMinimumFractionDigits=" + nfat . getMinimumFractionDigits ( ) ) ; System . out . println ( " getMaximumFractionDigits=" + nfat . getMaximumFractionDigits ( ) ) ; } if ( f instanceof DecimalFormat ) { DecimalFormat df = ( DecimalFormat ) f ; System . out . println ( " Pattern  = " + df . toPattern ( ) ) ; } } }


Input:
/ * This dorks with Double . toString () : [CODESPLIT] private static String formatDouble ( double d , int min_sigFigs , int fixed_decimals ) { String s = java . lang . Double . toString ( d ) ; if ( java . lang . Double . isNaN ( d ) ) return s ; // extract the sign
 String sign ; String unsigned ; if ( s . startsWith ( "-" ) || s . startsWith ( "+" ) ) { sign = s . substring ( 0 , 1 ) ; unsigned = s . substring ( 1 ) ; } else { sign = "" ; unsigned = s ; } // deal with exponential notation
 String mantissa ; String exponent ; int eInd = unsigned . indexOf ( ' ' ) ; if ( eInd == - 1 ) eInd = unsigned . indexOf ( ' ' ) ; if ( eInd == - 1 ) { mantissa = unsigned ; exponent = "" ; } else { mantissa = unsigned . substring ( 0 , eInd ) ; exponent = unsigned . substring ( eInd ) ; } // deal with decimal point
 StringBuffer number , fraction ; int dotInd = mantissa . indexOf ( ' ' ) ; if ( dotInd == - 1 ) { number = new StringBuffer ( mantissa ) ; fraction = new StringBuffer ( "" ) ; } else { number = new StringBuffer ( mantissa . substring ( 0 , dotInd ) ) ; fraction = new StringBuffer ( mantissa . substring ( dotInd + 1 ) ) ; } // number of significant figures
 int numFigs = number . length ( ) ; int fracFigs = fraction . length ( ) ; // can do either fixed_decimals or min_sigFigs
 if ( fixed_decimals != - 1 ) { if ( fixed_decimals == 0 ) { fraction . setLength ( 0 ) ; } else if ( fixed_decimals > fracFigs ) { int want = fixed_decimals - fracFigs ; for ( int i = 0 ; i < want ; i ++ ) fraction . append ( "0" ) ; } else if ( fixed_decimals < fracFigs ) { int chop = fracFigs - fixed_decimals ; // LOOK should round !!
 fraction . setLength ( fraction . length ( ) - chop ) ; } fracFigs = fixed_decimals ; } else { // Don't count leading zeros in the fraction, if no number
 if ( ( numFigs == 0 || number . toString ( ) . equals ( "0" ) ) && fracFigs > 0 ) { numFigs = 0 ; number = new StringBuffer ( "" ) ; for ( int i = 0 ; i < fraction . length ( ) ; ++ i ) { if ( fraction . charAt ( i ) != ' ' ) break ; -- fracFigs ; } } // Don't count trailing zeroes in the number if no fraction
 if ( ( fracFigs == 0 ) && numFigs > 0 ) { for ( int i = number . length ( ) - 1 ; i > 0 ; i -- ) { if ( number . charAt ( i ) != ' ' ) break ; -- numFigs ; } } // deal with min sig figures
 int sigFigs = numFigs + fracFigs ; if ( sigFigs > min_sigFigs ) { // Want fewer figures in the fraction; chop (should round? )
 int chop = Math . min ( sigFigs - min_sigFigs , fracFigs ) ; fraction . setLength ( fraction . length ( ) - chop ) ; fracFigs -= chop ; } } /*int sigFigs = numFigs + fracFigs;
    if (sigFigs > max_sigFigs) {

      if (numFigs >= max_sigFigs) {  // enough sig figs in just the number part
        fraction.setLength( 0 );
        for ( int i=max_sigFigs; i<numFigs; ++i )
          number.setCharAt( i, '0' );  // should round?
      } else {

        // Want fewer figures in the fraction; chop (should round? )
        int chop = sigFigs - max_sigFigs;
        fraction.setLength( fraction.length() - chop );
      }
    }

    /* may want a fixed decimal place
    if (dec_places != -1) {

      if (dec_places == 0) {
        fraction.setLength( 0 );
        fracFigs = 0;
      } else if (dec_places > fracFigs) {
        int want = dec_places - fracFigs;
        for (int i=0; i<want; i++)
          fraction.append("0");
      } else if (dec_places < fracFigs) {
        int chop = fracFigs - dec_places;
        fraction.setLength( fraction.length() - chop );
        fracFigs = dec_places;
      }

    } */ if ( fraction . length ( ) == 0 ) return sign + number + exponent ; else return sign + number + "." + fraction + exponent ; } }


Input:
Read the bit map array . [CODESPLIT] @ Nullable public byte [ ] getBitmap ( RandomAccessFile raf ) throws IOException { // no bitMap
 if ( bitMapIndicator == 255 ) return null ; // LOOK: bitMapIndicator=254 == previously defined bitmap
 if ( bitMapIndicator == 254 ) logger . debug ( "HEY bitMapIndicator=254 previously defined bitmap" ) ; if ( bitMapIndicator != 0 ) { throw new UnsupportedOperationException ( "Grib2 Bit map section pre-defined (provided by center) = " + bitMapIndicator ) ; } raf . seek ( startingPosition ) ; int length = GribNumbers . int4 ( raf ) ; raf . skipBytes ( 2 ) ; byte [ ] data = new byte [ length - 6 ] ; raf . readFully ( data ) ; return data ; }


Input: / * message Catalog { uint64 catId = 1 ; // sequence no string catLocation = 2 ; bool isRoot = 3 ; uint64 lastRead = 4 ; } [CODESPLIT] public void writeExternal ( DataOutputStream out ) throws IOException { ConfigCatalogExtProto . Catalog . Builder builder = ConfigCatalogExtProto . Catalog . newBuilder ( ) ; builder . setCatId ( catId ) ; builder . setCatLocation ( catRelLocation ) ; builder . setIsRoot ( isRoot ) ; builder . setLastRead ( lastRead ) ; ConfigCatalogExtProto . Catalog index = builder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; out . writeInt ( b . length ) ; out . write ( b ) ; total_count ++ ; total_nbytes += b . length + 4 ; }


Input: Find the known DataFormatType that matches the given name ( ignoring case ) or null if the name is unknown . [CODESPLIT] public static DataFormatType findType ( String name ) { if ( name == null ) return null ; for ( DataFormatType m : members ) { if ( m . name . equalsIgnoreCase ( name ) ) return m ; } return null ; }


Input: Return a DataFormatType for the given name by either matching a known type ( ignoring case ) or creating an unknown type . [CODESPLIT] public static DataFormatType getType ( String name ) { if ( name == null ) return null ; DataFormatType t = findType ( name ) ; return t != null ? t : new DataFormatType ( name , false ) ; }


Input: gml : Point [CODESPLIT] public static PointType initPoint ( PointType point , StationTimeSeriesFeature stationFeat ) { // @gml:id String id = MarshallingUtil . createIdForType ( PointType . class ) ; point . setId ( id ) ; // gml:pos NcDirectPositionType . initPos ( point . addNewPos ( ) , stationFeat ) ; return point ; }


Input: allow calling from outside [CODESPLIT] public void setNetcdfFile ( NetcdfFile ncf ) { this . ncfile = ncf ; this . filename = ncf . getLocation ( ) ; final GetDataRunnable runner = new GetDataRunnable ( ) { public void run ( Object o ) throws IOException { final StringWriter sw = new StringWriter ( 50000 ) ; NCdumpW . print ( ncfile , command , sw , task ) ; result = sw . toString ( ) ; } } ; task = new GetDataTask ( runner , filename , null ) ; stopButton . startProgressMonitorTask ( task ) ; }


Input: / * 1 ) single runtime 1a timeOffset 1b time or timeRange 1c none = constant runtime dataset 2 ) multiple runtimes 2a timeOffset = constant offset dataset 2b time ( not range ) = constant forecast dataset [CODESPLIT] public Optional < List < CoverageCoordAxis > > subset ( SubsetParams params , AtomicBoolean isConstantForcast , boolean makeCFcompliant ) { List < CoverageCoordAxis > result = new ArrayList <> ( ) ; Optional < CoverageCoordAxis > axiso = runAxis . subset ( params ) ; if ( ! axiso . isPresent ( ) ) return Optional . empty ( axiso . getErrorMessage ( ) ) ; CoverageCoordAxis1D runAxisSubset = ( CoverageCoordAxis1D ) axiso . get ( ) ; result . add ( runAxisSubset ) ; // subset on timeOffset (1a, 1c, 2a) if ( params . hasTimeOffsetParam ( ) || ! params . hasTimeParam ( ) ) { axiso = timeOffset . subset ( params ) ; if ( ! axiso . isPresent ( ) ) return Optional . empty ( axiso . getErrorMessage ( ) ) ; CoverageCoordAxis timeOffsetSubset = axiso . get ( ) ; result . add ( timeOffsetSubset ) ; if ( makeCFcompliant ) // add a time cordinate result . add ( makeCFTimeCoord ( runAxisSubset , ( CoverageCoordAxis1D ) timeOffsetSubset ) ) ; // possible the twoD time case, if nruns > 1 return Optional . of ( result ) ; } // subset on time, # runtimes = 1 (1b) if ( runAxisSubset . getNcoords ( ) == 1 ) { double val = runAxisSubset . getCoordMidpoint ( 0 ) ; // not sure runAxis is needed. maybe use runtimeSubset CalendarDate runDate = runAxisSubset . makeDate ( val ) ; Optional < TimeOffsetAxis > too = timeOffset . subsetFromTime ( params , runDate ) ; if ( ! too . isPresent ( ) ) return Optional . empty ( too . getErrorMessage ( ) ) ; TimeOffsetAxis timeOffsetSubset = too . get ( ) ; result . add ( timeOffsetSubset ) ; if ( makeCFcompliant ) result . add ( makeCFTimeCoord ( runAxisSubset , timeOffsetSubset ) ) ; return Optional . of ( result ) ; } // tricky case 2b time (point only not range) = constant forecast dataset // data reader has to skip around the 2D times // 1) the runtimes may be subset by whats available // 2) timeOffset could become an aux coordinate // 3) time coordinate becomes a scalar, isConstantForcast . set ( true ) ; CalendarDate dateWanted ; if ( params . isTrue ( SubsetParams . timePresent ) ) dateWanted = CalendarDate . present ( ) ; else dateWanted = ( CalendarDate ) params . get ( SubsetParams . time ) ; if ( dateWanted == null ) throw new IllegalStateException ( "Must have time parameter" ) ; double wantOffset = runAxisSubset . convert ( dateWanted ) ; // forecastDate offset from refdate double start = timeOffset . getStartValue ( ) ; double end = timeOffset . getEndValue ( ) ; CoordAxisHelper helper = new CoordAxisHelper ( timeOffset ) ; // brute force search LOOK specialize for regular ? List < Integer > runtimeIdx = new ArrayList <> ( ) ; // list of runtime indexes that have this forecast // List<Integer> offsetIdx = new ArrayList<>();  // list of offset indexes that have this forecast List < Double > offset = new ArrayList <> ( ) ; // corresponding offset from start of run for ( int i = 0 ; i < runAxisSubset . getNcoords ( ) ; i ++ ) { // public double getOffsetInTimeUnits(CalendarDate convertFrom, CalendarDate convertTo); double runOffset = runAxisSubset . getCoordMidpoint ( i ) ; if ( end + runOffset < wantOffset ) continue ; if ( wantOffset < start + runOffset ) break ; int idx = helper . search ( wantOffset - runOffset ) ; if ( idx >= 0 ) { runtimeIdx . add ( i ) ; // the ith runtime // offsetIdx.add(idx);   // the idx time offset offset . add ( wantOffset - runOffset ) ; // the offset from the runtime } } // here are the runtimes int ncoords = runtimeIdx . size ( ) ; double [ ] runValues = new double [ ncoords ] ; double [ ] offsetValues = new double [ ncoords ] ; int count = 0 ; for ( int k = 0 ; k < ncoords ; k ++ ) { offsetValues [ count ] = offset . get ( k ) ; runValues [ count ++ ] = runAxisSubset . getCoordMidpoint ( runtimeIdx . get ( k ) ) ; } CoverageCoordAxisBuilder runbuilder = new CoverageCoordAxisBuilder ( runAxisSubset ) . subset ( null , CoverageCoordAxis . Spacing . irregularPoint , ncoords , runValues ) ; // LOOK check for regular (in CovCoordAxis ?) CoverageCoordAxis1D runAxisSubset2 = new CoverageCoordAxis1D ( runbuilder ) ; CoverageCoordAxisBuilder timebuilder = new CoverageCoordAxisBuilder ( timeOffset ) . subset ( runAxisSubset2 . getName ( ) , CoverageCoordAxis . Spacing . irregularPoint , ncoords , offsetValues ) ; // aux coord (LOOK interval) ?? CoverageCoordAxis1D timeOffsetSubset = new TimeOffsetAxis ( timebuilder ) ; CoverageCoordAxis scalarTimeCoord = makeScalarTimeCoord ( wantOffset , runAxisSubset ) ; // nothing needed for CF, the run coordinate acts as the CF time independent coord. timeOffset is aux, forecastTime is scalar return Optional . of ( Lists . newArrayList ( runAxisSubset2 , timeOffsetSubset , scalarTimeCoord ) ) ; }


Input: Returns a string representation of the variables value . This is really foreshadowing functionality for Server types but as it may come in useful for clients it is added here . Simple types ( example : DFloat32 ) will return a single value . DConstuctor and DVector types will be flattened . DStrings and DURL s will have double quotes around them . [CODESPLIT] public void toASCII ( PrintWriter pw , boolean addName , String rootName , boolean newLine ) { if ( addName ) pw . print ( ", " ) ; pw . print ( ( new Float ( getValue ( ) ) ) . toString ( ) ) ; if ( newLine ) pw . print ( "\n" ) ; }


Input: Debugging flags . This is a way to decouple setting flags from particular implementations . [CODESPLIT] static public void setDebugFlags ( ucar . nc2 . util . DebugFlags debugFlag ) { debugCE = debugFlag . isSet ( "DODS/constraintExpression" ) ; debugServerCall = debugFlag . isSet ( "DODS/serverCall" ) ; debugOpenResult = debugFlag . isSet ( "DODS/debugOpenResult" ) ; debugDataResult = debugFlag . isSet ( "DODS/debugDataResult" ) ; debugCharArray = debugFlag . isSet ( "DODS/charArray" ) ; debugConstruct = debugFlag . isSet ( "DODS/constructNetcdf" ) ; debugPreload = debugFlag . isSet ( "DODS/preload" ) ; debugTime = debugFlag . isSet ( "DODS/timeCalls" ) ; showNCfile = debugFlag . isSet ( "DODS/showNCfile" ) ; debugAttributes = debugFlag . isSet ( "DODS/attributes" ) ; debugCached = debugFlag . isSet ( "DODS/cache" ) ; }


Input: Create the canonical form of the URL . If the urlName starts with http : or https : change it to start with dods : otherwise leave it alone . [CODESPLIT] public static String canonicalURL ( String urlName ) { if ( urlName . startsWith ( "http:" ) ) return "dods:" + urlName . substring ( 5 ) ; if ( urlName . startsWith ( "https:" ) ) return "dods:" + urlName . substring ( 6 ) ; return urlName ; }


Input:
/ * parse the DDS creating a tree of DodsV objects private ArrayList parseDDS ( DDS dds ) throws IOException { ArrayList dodsVlist = new ArrayList () ; [CODESPLIT] private void parseGlobalAttributes ( DAS das , DodsV root , DODSNetcdfFile dodsfile ) { List < DODSAttribute > atts = root . attributes ; for ( ucar . nc2 . Attribute ncatt : atts ) { rootGroup . addAttribute ( ncatt ) ; } // loop over attribute tables, collect global attributes Enumeration tableNames = das . getNames ( ) ; while ( tableNames . hasMoreElements ( ) ) { String tableName = ( String ) tableNames . nextElement ( ) ; AttributeTable attTable = das . getAttributeTableN ( tableName ) ; if ( attTable == null ) continue ; // should probably never happen /* if (tableName.equals("NC_GLOBAL") || tableName.equals("HDF_GLOBAL")) {
        java.util.Enumeration attNames = attTable.getNames();
        while (attNames.hasMoreElements()) {
          String attName = (String) attNames.nextElement();
          dods.dap.Attribute att = attTable.getAttribute(attName);

          DODSAttribute ncatt = new DODSAttribute( attName, att);
          addAttribute( null, ncatt);
        }

          } else */ if ( tableName . equals ( "DODS_EXTRA" ) ) { Enumeration attNames = attTable . getNames ( ) ; while ( attNames . hasMoreElements ( ) ) { String attName = ( String ) attNames . nextElement ( ) ; if ( attName . equals ( "Unlimited_Dimension" ) ) { opendap . dap . Attribute att = attTable . getAttribute ( attName ) ; DODSAttribute ncatt = new DODSAttribute ( attName , att ) ; setUnlimited ( ncatt . getStringValue ( ) ) ; } else logger . warn ( " Unknown DODS_EXTRA attribute = " + attName + " " + location ) ; } } else if ( tableName . equals ( "EXTRA_DIMENSION" ) ) { Enumeration attNames = attTable . getNames ( ) ; while ( attNames . hasMoreElements ( ) ) { String attName = ( String ) attNames . nextElement ( ) ; opendap . dap . Attribute att = attTable . getAttribute ( attName ) ; DODSAttribute ncatt = new DODSAttribute ( attName , att ) ; int length = ncatt . getNumericValue ( ) . intValue ( ) ; Dimension extraDim = new Dimension ( attName , length ) ; addDimension ( null , extraDim ) ; } } /* else if (null == root.findDodsV( tableName, false)) {
  addAttributes(attTable.getName(), attTable);
      } */ } }


Input: Go thru the variables / structure - variables and their attributes and move to the proper groups . [CODESPLIT] protected void reGroup ( ) throws DAP2Exception { assert ( RC . getUseGroups ( ) ) ; Group rootgroup = this . getRootGroup ( ) ; // Start by moving global attributes // An issue to be addressed is that some attributes that should be attached // to variables, instead get made global with name var.att. Object [ ] gattlist = rootgroup . getAttributes ( ) . toArray ( ) ; for ( Object att : gattlist ) { Attribute ncatt = ( Attribute ) att ; String dodsname = ncatt . getDODSName ( ) ; NamePieces pieces = parseName ( dodsname ) ; if ( pieces . var != null ) { // Figure out which variable to which this attribute should be moved. // In the event that there is no matching // variable, then keep the attribute as is. String searchname = pieces . var ; if ( pieces . prefix != null ) searchname = pieces . prefix + ' ' + searchname ; Variable v = findVariable ( searchname ) ; if ( v != null ) { // move attribute rootgroup . remove ( ncatt ) ; v . addAttribute ( ncatt ) ; // change attribute name to remove var. String newname = pieces . name ; ncatt . setName ( newname ) ; } } else if ( pieces . prefix != null ) { // We have a true group global name to move to proper group // convert prefix to an actual group Group g = rootgroup . makeRelativeGroup ( this , dodsname , true ) ; rootgroup . remove ( ncatt ) ; g . addAttribute ( ncatt ) ; if ( OLDGROUPCODE ) { ncatt . setName ( pieces . name ) ; } } } Object [ ] varlist = rootgroup . getVariables ( ) . toArray ( ) ; if ( false ) { // This should have been done by computegroup() // Now move variables for ( Object var : varlist ) { if ( var instanceof DODSVariable ) { DODSVariable v = ( DODSVariable ) var ; reGroupVariable ( rootgroup , v ) ; } else throw new DAP2Exception ( "regroup: unexpected variable type: " + var . getClass ( ) . getCanonicalName ( ) ) ; } } // In theory, we should be able to fix variable attributes // by just removing the group prefix. However, there is the issue // that attribute names sometimes have as a suffix varname.attname. // So, we should use that to adjust the attribute to attach to that // variable. for ( Object var : varlist ) { reGroupVariableAttributes ( rootgroup , ( Variable ) var ) ; } }


Input: Utility to decompose a name [CODESPLIT] NamePieces parseName ( String name ) { NamePieces pieces = new NamePieces ( ) ; int dotpos = name . lastIndexOf ( ' ' ) ; int slashpos = name . lastIndexOf ( ' ' ) ; if ( slashpos < 0 && dotpos < 0 ) { pieces . name = name ; } else if ( slashpos >= 0 && dotpos < 0 ) { pieces . prefix = name . substring ( 0 , slashpos ) ; pieces . name = name . substring ( slashpos + 1 , name . length ( ) ) ; } else if ( slashpos < 0 && dotpos >= 0 ) { pieces . var = name . substring ( 0 , dotpos ) ; pieces . name = name . substring ( dotpos + 1 , name . length ( ) ) ; } else { //slashpos >= 0 && dotpos >= 0) if ( slashpos > dotpos ) { pieces . prefix = name . substring ( 0 , slashpos ) ; pieces . name = name . substring ( slashpos + 1 , name . length ( ) ) ; } else { //slashpos < dotpos) pieces . prefix = name . substring ( 0 , slashpos ) ; pieces . var = name . substring ( slashpos + 1 , dotpos ) ; pieces . name = name . substring ( dotpos + 1 , name . length ( ) ) ; } } // fixup if ( pieces . prefix != null && pieces . prefix . length ( ) == 0 ) pieces . prefix = null ; if ( pieces . var != null && pieces . var . length ( ) == 0 ) pieces . var = null ; if ( pieces . name . length ( ) == 0 ) pieces . name = null ; return pieces ; }


Input: //////////////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private void constructTopVariables ( DodsV rootDodsV , CancelTask cancelTask ) throws IOException { List < DodsV > topVariables = rootDodsV . children ; for ( DodsV dodsV : topVariables ) { if ( dodsV . bt instanceof DConstructor ) continue ; addVariable ( rootGroup , null , dodsV ) ; if ( cancelTask != null && cancelTask . isCancel ( ) ) return ; } }


Input: recursively make new variables : all new variables come through here [CODESPLIT] Variable addVariable ( Group parentGroup , Structure parentStructure , DodsV dodsV ) throws IOException { Variable v = makeVariable ( parentGroup , parentStructure , dodsV ) ; if ( v != null ) { addAttributes ( v , dodsV ) ; if ( parentStructure != null ) parentStructure . addMemberVariable ( v ) ; else { parentGroup = computeGroup ( v . getDODSName ( ) , v , parentGroup ) ; parentGroup . addVariable ( v ) ; } dodsV . isDone = true ; } return v ; }


Input: make a structure into a group if its scalar and all parents are groups [CODESPLIT] private boolean isGroup ( DStructure dstruct ) { BaseType parent = ( BaseType ) dstruct . getParent ( ) ; if ( parent == null ) return true ; if ( parent instanceof DStructure ) return isGroup ( ( DStructure ) parent ) ; return true ; }


Input: / * private void addAttributes ( String tableName AttributeTable attTable ) { [CODESPLIT] private void addAttributes ( Variable v , DodsV dodsV ) { List < DODSAttribute > atts = dodsV . attributes ; for ( Attribute ncatt : atts ) { v . addAttribute ( ncatt ) ; } // this is the case where its (probably) a Grid, and so _Coordinate.Axes has been assigned, but if // theres also a coordinates attribute, need to add that info Attribute axes = v . findAttribute ( CF . COORDINATES ) ; Attribute _axes = v . findAttribute ( _Coordinate . Axes ) ; if ( ( null != axes ) && ( null != _axes ) ) { v . addAttribute ( combineAxesAttrs ( axes , _axes ) ) ; } }


Input: Checks to see if this is netcdf char array . [CODESPLIT] Dimension getNetcdfStrlenDim ( DODSVariable v ) { AttributeTable table = das . getAttributeTableN ( v . getFullName ( ) ) ; // LOOK this probably doesnt work for nested variables if ( table == null ) return null ; opendap . dap . Attribute dodsAtt = table . getAttribute ( "DODS" ) ; if ( dodsAtt == null ) return null ; AttributeTable dodsTable = dodsAtt . getContainerN ( ) ; if ( dodsTable == null ) return null ; opendap . dap . Attribute att = dodsTable . getAttribute ( "strlen" ) ; if ( att == null ) return null ; String strlen = att . getValueAtN ( 0 ) ; opendap . dap . Attribute att2 = dodsTable . getAttribute ( "dimName" ) ; String dimName = ( att2 == null ) ? null : att2 . getValueAtN ( 0 ) ; if ( debugCharArray ) System . out . println ( v . getFullName ( ) + " has strlen= " + strlen + " dimName= " + dimName ) ; int dimLength ; try { dimLength = Integer . parseInt ( strlen ) ; } catch ( NumberFormatException e ) { logger . warn ( "DODSNetcdfFile " + location + " var = " + v . getFullName ( ) + " error on strlen attribute = " + strlen ) ; return null ; } if ( dimLength <= 0 ) return null ; // LOOK what about unlimited ?? return new Dimension ( dimName , dimLength , dimName != null ) ; }


Input: If an equivilent shared dimension already exists use it else add d to shared dimensions . Equivilent is same name and length . [CODESPLIT] Dimension getSharedDimension ( Group group , Dimension d ) { if ( d . getShortName ( ) == null ) return d ; if ( group == null ) group = rootGroup ; for ( Dimension sd : group . getDimensions ( ) ) { if ( sd . getShortName ( ) . equals ( d . getShortName ( ) ) && sd . getLength ( ) == d . getLength ( ) ) return sd ; } d . setShared ( true ) ; group . addDimension ( d ) ; return d ; }


Input: construct list of dimensions to use [CODESPLIT] List < Dimension > constructDimensions ( Group group , opendap . dap . DArray dodsArray ) { if ( group == null ) group = rootGroup ; List < Dimension > dims = new ArrayList < Dimension > ( ) ; Enumeration enumerate = dodsArray . getDimensions ( ) ; while ( enumerate . hasMoreElements ( ) ) { opendap . dap . DArrayDimension dad = ( opendap . dap . DArrayDimension ) enumerate . nextElement ( ) ; String name = dad . getEncodedName ( ) ; if ( name != null ) name = StringUtil2 . unescape ( name ) ; Dimension myd ; if ( name == null ) { // if no name, make an anonymous dimension myd = new Dimension ( null , dad . getSize ( ) , false ) ; } else { // see if shared if ( RC . getUseGroups ( ) ) { if ( name . indexOf ( ' ' ) >= 0 ) { // place dimension in proper group group = group . makeRelativeGroup ( this , name , true ) ; // change our name name = name . substring ( name . lastIndexOf ( ' ' ) + 1 ) ; } } myd = group . findDimension ( name ) ; if ( myd == null ) { // add as shared myd = new Dimension ( name , dad . getSize ( ) ) ; group . addDimension ( myd ) ; } else if ( myd . getLength ( ) != dad . getSize ( ) ) { // make a non-shared dimension myd = new Dimension ( name , dad . getSize ( ) , false ) ; } // else use existing, shared dimension } dims . add ( myd ) ; // add it to the list } return dims ; }


Input: full name [CODESPLIT] private String makeDODSname ( DodsV dodsV ) { DodsV parent = dodsV . parent ; if ( parent . bt != null ) return ( makeDODSname ( parent ) + "." + dodsV . bt . getEncodedName ( ) ) ; return dodsV . bt . getEncodedName ( ) ; }


Input: Get the DODS data class corresponding to the Netcdf data type . This is the inverse of convertToNCType () . [CODESPLIT] static public int convertToDODSType ( DataType dataType ) { if ( dataType == DataType . STRING ) return opendap . dap . Attribute . STRING ; if ( dataType == DataType . BYTE ) return opendap . dap . Attribute . BYTE ; if ( dataType == DataType . FLOAT ) return opendap . dap . Attribute . FLOAT32 ; if ( dataType == DataType . DOUBLE ) return opendap . dap . Attribute . FLOAT64 ; if ( dataType == DataType . SHORT ) return opendap . dap . Attribute . INT16 ; if ( dataType == DataType . USHORT ) return opendap . dap . Attribute . UINT16 ; if ( dataType == DataType . INT ) return opendap . dap . Attribute . INT32 ; if ( dataType == DataType . UINT ) return opendap . dap . Attribute . UINT32 ; if ( dataType == DataType . BOOLEAN ) return opendap . dap . Attribute . BYTE ; if ( dataType == DataType . LONG ) return opendap . dap . Attribute . INT32 ; // LOOK no LONG type! // shouldnt happen return opendap . dap . Attribute . STRING ; }


Input: Get the Netcdf data type corresponding to the DODS data type . This is the inverse of convertToDODSType () . [CODESPLIT] static public DataType convertToNCType ( int dodsDataType , boolean isUnsigned ) { switch ( dodsDataType ) { case opendap . dap . Attribute . BYTE : return isUnsigned ? DataType . UBYTE : DataType . BYTE ; case opendap . dap . Attribute . FLOAT32 : return DataType . FLOAT ; case opendap . dap . Attribute . FLOAT64 : return DataType . DOUBLE ; case opendap . dap . Attribute . INT16 : return DataType . SHORT ; case opendap . dap . Attribute . UINT16 : return DataType . USHORT ; case opendap . dap . Attribute . INT32 : return DataType . INT ; case opendap . dap . Attribute . UINT32 : return DataType . UINT ; default : return DataType . STRING ; } }