Input:
Given a point in x y coordinate space find the x y index in the coordinate system . If outside the range the closest point is returned eg 0 or n - 1 depending on if the coordinate is too small or too large . [CODESPLIT] @ Override public int [ ] findXYindexFromCoordBounded ( double x_coord , double y_coord , int [ ] result ) { if ( result == null ) result = new int [ 2 ] ; if ( ( horizXaxis instanceof CoordinateAxis1D ) && ( horizYaxis instanceof CoordinateAxis1D ) ) { result [ 0 ] = ( ( CoordinateAxis1D ) horizXaxis ) . findCoordElementBounded ( x_coord ) ; result [ 1 ] = ( ( CoordinateAxis1D ) horizYaxis ) . findCoordElementBounded ( y_coord ) ; return result ; } else if ( ( horizXaxis instanceof CoordinateAxis2D ) && ( horizYaxis instanceof CoordinateAxis2D ) ) { if ( g2d == null ) g2d = new GridCoordinate2D ( ( CoordinateAxis2D ) horizYaxis , ( CoordinateAxis2D ) horizXaxis ) ; int [ ] result2 = new int [ 2 ] ; g2d . findCoordElement ( y_coord , x_coord , result2 ) ; // returns best guess
 result [ 0 ] = result2 [ 1 ] ; result [ 1 ] = result2 [ 0 ] ; return result ; } // cant happen
 throw new IllegalStateException ( "GridCoordSystem.findXYindexFromCoord" ) ; }


Input: Given a lat lon point find the x y index in the coordinate system . [CODESPLIT] @ Override public int [ ] findXYindexFromLatLon ( double lat , double lon , int [ ] result ) { Projection dataProjection = getProjection ( ) ; ProjectionPoint pp = dataProjection . latLonToProj ( new LatLonPointImpl ( lat , lon ) , new ProjectionPointImpl ( ) ) ; return findXYindexFromCoord ( pp . getX ( ) , pp . getY ( ) , result ) ; }


Input: Given a lat lon point find the x y index in the coordinate system . If outside the range the closest point is returned [CODESPLIT] @ Override public int [ ] findXYindexFromLatLonBounded ( double lat , double lon , int [ ] result ) { Projection dataProjection = getProjection ( ) ; ProjectionPoint pp = dataProjection . latLonToProj ( new LatLonPointImpl ( lat , lon ) , new ProjectionPointImpl ( ) ) ; return findXYindexFromCoordBounded ( pp . getX ( ) , pp . getY ( ) , result ) ; }


Input:
Get the x y bounding box in projection coordinates . [CODESPLIT] @ Override public ProjectionRect getBoundingBox ( ) { if ( mapArea == null ) { if ( ( horizXaxis == null ) || ! horizXaxis . isNumeric ( ) || ( horizYaxis == null ) || ! horizYaxis . isNumeric ( ) ) return null ; // impossible
 // x,y may be 2D
 if ( ! ( horizXaxis instanceof CoordinateAxis1D ) || ! ( horizYaxis instanceof CoordinateAxis1D ) ) { /*  could try to optimize this - just get cord=ners or something
        CoordinateAxis2D xaxis2 = (CoordinateAxis2D) horizXaxis;
        CoordinateAxis2D yaxis2 = (CoordinateAxis2D) horizYaxis;
        MAMath.MinMax
        */ mapArea = new ProjectionRect ( horizXaxis . getMinValue ( ) , horizYaxis . getMinValue ( ) , horizXaxis . getMaxValue ( ) , horizYaxis . getMaxValue ( ) ) ; } else { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) horizXaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) horizYaxis ; /* add one percent on each side if its a projection. WHY?
        double dx = 0.0, dy = 0.0;
        if (!isLatLon()) {
          dx = .01 * (xaxis1.getCoordEdge((int) xaxis1.getSize()) - xaxis1.getCoordEdge(0));
          dy = .01 * (yaxis1.getCoordEdge((int) yaxis1.getSize()) - yaxis1.getCoordEdge(0));
        }

        mapArea = new ProjectionRect(xaxis1.getCoordEdge(0) - dx, yaxis1.getCoordEdge(0) - dy,
            xaxis1.getCoordEdge((int) xaxis1.getSize()) + dx,
            yaxis1.getCoordEdge((int) yaxis1.getSize()) + dy); */ mapArea = new ProjectionRect ( xaxis1 . getCoordEdge ( 0 ) , yaxis1 . getCoordEdge ( 0 ) , xaxis1 . getCoordEdge ( ( int ) xaxis1 . getSize ( ) ) , yaxis1 . getCoordEdge ( ( int ) yaxis1 . getSize ( ) ) ) ; } } return mapArea ; }


Input: Get the Lat / Lon coordinates of the midpoint of a grid cell using the x y indices [CODESPLIT] @ Override public LatLonPoint getLatLon ( int xindex , int yindex ) { double x , y ; if ( horizXaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizXaxis ; x = horiz1D . getCoordValue ( xindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizXaxis ; x = horiz2D . getCoordValue ( yindex , xindex ) ; } if ( horizYaxis instanceof CoordinateAxis1D ) { CoordinateAxis1D horiz1D = ( CoordinateAxis1D ) horizYaxis ; y = horiz1D . getCoordValue ( yindex ) ; } else { CoordinateAxis2D horiz2D = ( CoordinateAxis2D ) horizYaxis ; y = horiz2D . getCoordValue ( yindex , xindex ) ; } return isLatLon ( ) ? new LatLonPointImpl ( y , x ) : getLatLon ( x , y ) ; }


Input:
Get Index Ranges for the given lat lon bounding box . For projection only an approximation based on latlon corners . Must have CoordinateAxis1D or 2D for x and y axis . [CODESPLIT] @ Override public List < Range > getRangesFromLatLonRect ( LatLonRect rect ) throws InvalidRangeException { double minx , maxx , miny , maxy ; ProjectionImpl proj = getProjection ( ) ; if ( proj != null && ! ( proj instanceof VerticalPerspectiveView ) && ! ( proj instanceof MSGnavigation ) && ! ( proj instanceof Geostationary ) ) { // LOOK kludge - how to do this generrally ??
 // first clip the request rectangle to the bounding box of the grid
 LatLonRect bb = getLatLonBoundingBox ( ) ; LatLonRect rect2 = bb . intersect ( rect ) ; if ( null == rect2 ) throw new InvalidRangeException ( "Request Bounding box does not intersect Grid " ) ; rect = rect2 ; } CoordinateAxis xaxis = getXHorizAxis ( ) ; CoordinateAxis yaxis = getYHorizAxis ( ) ; if ( isLatLon ( ) ) { LatLonPointImpl llpt = rect . getLowerLeftPoint ( ) ; LatLonPointImpl urpt = rect . getUpperRightPoint ( ) ; LatLonPointImpl lrpt = rect . getLowerRightPoint ( ) ; LatLonPointImpl ulpt = rect . getUpperLeftPoint ( ) ; minx = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; miny = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; maxx = getMinOrMaxLon ( urpt . getLongitude ( ) , lrpt . getLongitude ( ) , false ) ; maxy = Math . min ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // normalize to [minLon,minLon+360]
 double minLon = xaxis . getMinValue ( ) ; minx = LatLonPointImpl . lonNormalFrom ( minx , minLon ) ; maxx = LatLonPointImpl . lonNormalFrom ( maxx , minLon ) ; } else { ProjectionRect prect = getProjection ( ) . latLonToProjBB ( rect ) ; // allow projection to override
 minx = prect . getMinPoint ( ) . getX ( ) ; miny = prect . getMinPoint ( ) . getY ( ) ; maxx = prect . getMaxPoint ( ) . getX ( ) ; maxy = prect . getMaxPoint ( ) . getY ( ) ; /*
      see ProjectionImpl.latLonToProjBB2()
      Projection dataProjection = getProjection();
      ProjectionPoint ll = dataProjection.latLonToProj(llpt, new ProjectionPointImpl());
      ProjectionPoint ur = dataProjection.latLonToProj(urpt, new ProjectionPointImpl());
      ProjectionPoint lr = dataProjection.latLonToProj(lrpt, new ProjectionPointImpl());
      ProjectionPoint ul = dataProjection.latLonToProj(ulpt, new ProjectionPointImpl());

      minx = Math.min(ll.getX(), ul.getX());
      miny = Math.min(ll.getY(), lr.getY());
      maxx = Math.max(ur.getX(), lr.getX());
      maxy = Math.max(ul.getY(), ur.getY()); */ } if ( ( xaxis instanceof CoordinateAxis1D ) && ( yaxis instanceof CoordinateAxis1D ) ) { CoordinateAxis1D xaxis1 = ( CoordinateAxis1D ) xaxis ; CoordinateAxis1D yaxis1 = ( CoordinateAxis1D ) yaxis ; int minxIndex = xaxis1 . findCoordElementBounded ( minx ) ; int minyIndex = yaxis1 . findCoordElementBounded ( miny ) ; int maxxIndex = xaxis1 . findCoordElementBounded ( maxx ) ; int maxyIndex = yaxis1 . findCoordElementBounded ( maxy ) ; List < Range > list = new ArrayList <> ( ) ; list . add ( new Range ( Math . min ( minyIndex , maxyIndex ) , Math . max ( minyIndex , maxyIndex ) ) ) ; list . add ( new Range ( Math . min ( minxIndex , maxxIndex ) , Math . max ( minxIndex , maxxIndex ) ) ) ; return list ; } else if ( ( xaxis instanceof CoordinateAxis2D ) && ( yaxis instanceof CoordinateAxis2D ) && isLatLon ( ) ) { CoordinateAxis2D lon_axis = ( CoordinateAxis2D ) xaxis ; CoordinateAxis2D lat_axis = ( CoordinateAxis2D ) yaxis ; int shape [ ] = lon_axis . getShape ( ) ; int nj = shape [ 0 ] ; int ni = shape [ 1 ] ; int mini = Integer . MAX_VALUE , minj = Integer . MAX_VALUE ; int maxi = - 1 , maxj = - 1 ; // margolis 2/18/2010
 //minx = LatLonPointImpl.lonNormal( minx ); // <-- THIS IS NEW
 //maxx = LatLonPointImpl.lonNormal( maxx ); // <-- THIS IS NEW
 // brute force, examine every point LOOK BAD
 for ( int j = 0 ; j < nj ; j ++ ) { for ( int i = 0 ; i < ni ; i ++ ) { double lat = lat_axis . getCoordValue ( j , i ) ; double lon = lon_axis . getCoordValue ( j , i ) ; //lon = LatLonPointImpl.lonNormal( lon ); // <-- THIS IS NEW
 if ( ( lat >= miny ) && ( lat <= maxy ) && ( lon >= minx ) && ( lon <= maxx ) ) { if ( i > maxi ) maxi = i ; if ( i < mini ) mini = i ; if ( j > maxj ) maxj = j ; if ( j < minj ) minj = j ; //System.out.println(j+" "+i+" lat="+lat+" lon="+lon);
 } } } // this is the case where no points are included
 if ( ( mini > maxi ) || ( minj > maxj ) ) { mini = 0 ; minj = 0 ; maxi = - 1 ; maxj = - 1 ; } ArrayList < Range > list = new ArrayList <> ( ) ; list . add ( new Range ( minj , maxj ) ) ; list . add ( new Range ( mini , maxi ) ) ; return list ; } else { throw new IllegalArgumentException ( "must be 1D or 2D/LatLon " ) ; } }


Input: /////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public List < CalendarDate > getCalendarDates ( ) { if ( timeTaxis != null ) return timeTaxis . getCalendarDates ( ) ; else if ( getRunTimeAxis ( ) != null ) return makeCalendarDates2D ( ) ; else return new ArrayList <> ( ) ; }


Input:
Get the list of level names to be used for user selection . The ith one refers to the ith level coordinate . [CODESPLIT] public List < NamedObject > getLevels ( ) { if ( vertZaxis == null ) return new ArrayList <> ( 0 ) ; int n = ( int ) vertZaxis . getSize ( ) ; List < NamedObject > levels = new ArrayList <> ( n ) ; for ( int i = 0 ; i < n ; i ++ ) levels . ( new ucar . nc2 . util . NamedAnything ( vertZaxis . getCoordName ( i ) , vertZaxis . getUnitsString ( ) ) ) ; return levels ; } /**
   * Get the String name for the ith level(z) coordinate.
   *
   * @param index which level coordinate
   * @return level name
   */ public String getLevelName ( int index ) { if ( ( vertZaxis == null ) || ( index < 0 ) || ( index >= vertZaxis . getSize ( ) ) ) throw new IllegalArgumentException ( "getLevelName = " + index ) ; return vertZaxis . getCoordName ( index ) . trim ( ) ; } /**
   * Get the index corresponding to the level name.
   *
   * @param name level name
   * @return level index, or -1 if not found
   */ public int getLevelIndex  ( String name ) { if ( ( vertZaxis == null ) || ( name == null ) ) return - 1 ; for ( int i = 0 ; i < vertZaxis . getSize ( ) ; i ++ ) { if ( vertZaxis . getCoordName ( i ) . trim ( ) . equals ( name ) ) return i ; } return - 1 ; } /**
   * Get the list of time names, to be used for user selection.
   * The ith one refers to the ith time coordinate.
   *
   * @return List of ucar.nc2.util.NamedObject, or empty list.
   */ public List < NamedObject > getTimes  ( ) { List < CalendarDate > cdates = getCalendarDates ( ) ; List < NamedObject > times = new ArrayList <> ( cdates . size ( ) ) ; for ( CalendarDate cd : cdates ) { times . add ( new ucar . nc2 . util . NamedAnything ( cd . toString ( ) , "calendar date" ) ) ; } return times ; } ///////////////////////////////////////////////////////////////////////////
 // deprecated
 /**
   * Given a point in x,y coordinate space, find the x,y index in the coordinate system.
   *
   * @deprecated use findXYindexFromCoord
   */ public int [ ] findXYCoordElement  ( double x_coord , double y_coord , int [ ] result ) { return findXYindexFromCoord ( x_coord , y_coord , result ) ; } /**
   * Get the date range
   * @return date range
   * @deprecated  use getCalendarDateRange
   */ public DateRange getDateRange  ( ) { Date [ ] dates = getTimeDates ( ) ; if ( dates . length > 0 ) return new DateRange ( dates [ 0 ] , dates [ dates . length - 1 ] ) ; return null ; } /**
   * Get the list of times as Dates.
   * If 2D, return list of unique dates.
   *
   * @return array of java.util.Date, or Date[0].
   * @deprecated  use getCalendarDates
   */ public java . util . Date [ ] getTimeDates  ( ) { if ( ( timeTaxis != null ) && ( timeTaxis . getSize ( ) > 0 ) ) { return timeTaxis . getTimeDates ( ) ; } else if ( ( tAxis != null ) && ( tAxis . getSize ( ) > 0 ) ) { return makeTimes2D ( ) ; } return new Date [ 0 ] ; } private Date [ ] makeTimes2D  ( ) { Set < Date > dates = new HashSet <> ( ) ; try { // common case: see if it has a valid udunits unit
 String units = tAxis . getUnitsString ( ) ; if ( units != null && SimpleUnit . isDateUnit ( units ) && tAxis . getDataType ( ) . isNumeric ( ) ) { DateUnit du = new DateUnit ( units ) ; Array data = tAxis . read ( ) ; data . resetLocalIterator ( ) ; while ( data . hasNext ( ) ) { Date d = du . makeDate ( data . nextDouble ( ) ) ; dates . add ( d ) ; } } else if ( tAxis . getDataType ( ) == DataType . STRING ) { // otherwise, see if its a String or CHAR, and if we can parse the values as an ISO date
 DateFormatter formatter = new DateFormatter ( ) ; Array data = tAxis . read ( ) ; data . resetLocalIterator ( ) ; while ( data . hasNext ( ) ) { Date d = formatter . getISODate ( ( String ) data . next ( ) ) ; dates . add ( d ) ; } } else if ( tAxis . getDataType ( ) == DataType . CHAR ) { DateFormatter formatter = new DateFormatter ( ) ; ArrayChar data = ( ArrayChar ) tAxis . read ( ) ; ArrayChar . StringIterator iter = data . getStringIterator ( ) ; while ( iter . hasNext ( ) ) { Date d = formatter . getISODate ( iter . next ( ) ) ; dates . add ( d ) ; } } else { return new Date [ 0 ] ; } } catch ( Exception e ) { throw new RuntimeException ( e ) ; } // sorted list
 int n = dates . size ( ) ; Date [ ] dd = dates . toArray ( new Date [ n ] ) ; List < Date > dateList = Arrays . asList ( dd ) ; Collections . sort ( dateList ) ; Date [ ] timeDates = new Date [ n ] ; int count = 0 ; for ( Date d : dateList ) timeDates [ count ++ ] = ; return timeDates ; } /* old way
  private boolean makeTimes1D() {
    int n = (int) timeTaxis.getSize();
    timeDates = new Date[n];

    // common case: see if it has a valid udunits unit
    try {
      DateUnit du = null;
      String units = timeTaxis.getUnitsString();
      if (units != null)
        du = new DateUnit(units);
      for (int i = 0; i < n; i++) {
        Date d = du.makeDate(timeTaxis.getCoordValue(i));
        timeDates[i] = d;
      }
      isDate = true;
      return true;
    } catch (Exception e) {
      // ok to fall through
    }

    // otherwise, see if its a String, and if we can parse the values as an ISO date
    if ((timeTaxis.getDataType() == DataType.STRING) || (timeTaxis.getDataType() == DataType.CHAR)) {
      DateFormatter formatter = new DateFormatter();
      for (int i = 0; i < n; i++) {
        String coordValue = timeTaxis.getCoordName(i);
        Date d = formatter.getISODate(coordValue);
        if (d == null) {
          isDate = false;
          return false;
        } else {
          timeDates[i] = d;
        }
      }
      isDate = true;
      return true;
    }

    return false;
  }  */ /**
   * Get the string name for the ith time coordinate.
   *
   * @param index which time coordinate
   * @return time name.
   * @deprecated
   */ public String getTimeName  ( int index ) { List < CalendarDate > cdates = getCalendarDates ( ) ; if ( ( index < 0 ) || ( index >= cdates . size ( ) ) ) throw new IllegalArgumentException ( "getTimeName illegal index = " + index ) ; return cdates . get ( index ) . toString ( ) ; } /**
   * Get the index corresponding to the time name.
   *
   * @param name time name
   * @return time index, or -1 if not found
   * @deprecated
   */ public int getTimeIndex  ( String name ) { List < CalendarDate > cdates = getCalendarDates ( ) ; for ( int i = 0 ; i < cdates . size ( ) ; i ++ ) { if ( cdates . get ( i ) . toString ( ) . equals ( name ) ) return i ; } return - 1 ; } /**
   * Only works if coordsys has 1d time axis
   * @deprecated use CoordinateAxis1DTime.findTimeIndexFromDate
   */ public int findTimeIndexFromDate  ( java . util . Date d ) { if ( timeTaxis == null ) return - 1 ; return timeTaxis . findTimeIndexFromDate ( d ) ; } ///////////////////////////////////////////////////////////////////////
 // experimental
 static private double getMinOrMaxLon  ( double lon1 , double lon2 , boolean wantMin ) { double midpoint = ( lon1 + lon2 ) / 2 ; lon1 = LatLonPointImpl . lonNormal ( lon1 , midpoint ) ; lon2 = LatLonPointImpl . lonNormal ( lon2 , midpoint ) ; return wantMin ? Math . min ( lon1 , lon2 ) : Math . max ( lon1 , lon2 ) ; } static public LatLonRect getLatLonBoundingBox  ( Projection proj , double startx , double starty , double endx , double endy ) { if ( proj instanceof LatLonProjection ) { double deltaLat = endy - starty ; double deltaLon = endx - startx ; LatLonPoint llpt = new LatLonPointImpl ( starty , startx ) ; return new LatLonRect ( llpt , deltaLat , deltaLon ) ; } ProjectionRect bb = new ProjectionRect ( startx , starty , endx , endy ) ; // look at all 4 corners of the bounding box
 LatLonPointImpl llpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getLowerLeftPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPointImpl lrpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getLowerRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPointImpl urpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getUpperRightPoint ( ) , new LatLonPointImpl ( ) ) ; LatLonPointImpl ulpt = ( LatLonPointImpl ) proj . projToLatLon ( bb . getUpperLeftPoint ( ) , new LatLonPointImpl ( ) ) ; // Check if grid contains poles. LOOK disabled
 boolean includesNorthPole = false ; /* int[] resultNP = new int[2];
    resultNP = findXYindexFromLatLon(90.0, 0, null);
    if (resultNP[0] != -1 && resultNP[1] != -1)
      includesNorthPole = true;  */ boolean includesSouthPole = false ; /* int[] resultSP = new int[2];
    resultSP = findXYindexFromLatLon(-90.0, 0, null);
    if (resultSP[0] != -1 && resultSP[1] != -1)
      includesSouthPole = true;  */ LatLonRect llbb ; if ( includesNorthPole && ! includesSouthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( 90.0 , 0.0 ) ) ; // ??? lon=???
 llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; } else if ( includesSouthPole && ! includesNorthPole ) { llbb = new LatLonRect ( llpt , new LatLonPointImpl ( - 90.0 , - 180.0 ) ) ; // ??? lon=???
 llbb . extend ( lrpt ) ; llbb . extend ( urpt ) ; llbb . extend ( ulpt ) ; } else { double latMin = Math . min ( llpt . getLatitude ( ) , lrpt . getLatitude ( ) ) ; double latMax = Math . max ( ulpt . getLatitude ( ) , urpt . getLatitude ( ) ) ; // longitude is a bit tricky as usual
 double lonMin = getMinOrMaxLon ( llpt . getLongitude ( ) , ulpt . getLongitude ( ) , true ) ; double lonMax = getMinOrMaxLon ( lrpt . getLongitude ( ) , urpt . getLongitude ( ) , false ) ; llpt . set ( latMin , lonMin ) ; urpt . set ( latMax , lonMax ) ; llbb = new LatLonRect ( llpt , urpt ) ; } return llbb ; } }


Input:
return slider indicator position for currently selected item [CODESPLIT] protected int getItemPos ( ) { if ( nitems < 1 ) return - arrow_size ; // dont show indicator
 else if ( nitems == 1 ) return b . width / 2 ; // indicator in center
 int item = table . getSelectedRowIndex ( ) ; // selected item
 int eff_width = b . width - 2 * arrow_size ; // effective width
 int pixel = ( item * eff_width ) / ( nitems - 1 ) ; // divided into n-1 intervals
 return pixel + arrow_size ; }


Input:
return item selected by this pixel position [CODESPLIT] protected int getItem ( int pixel ) { if ( nitems < 2 ) return 0 ; int eff_width = b . width - 2 * arrow_size ; // effective width
 double fitem = ( ( double ) ( pixel - arrow_size ) * ( nitems - 1 ) ) / eff_width ; int item = ( int ) ( fitem + .5 ) ; item = Math . max ( Math . min ( item , nitems - 1 ) , 0 ) ; return item ; }


Input: Create standard name = topCollectionName + last directory [CODESPLIT] public static String makeCollectionName ( String topCollectionName , Path dir ) { int last = dir . getNameCount ( ) - 1 ; Path lastDir = dir . getName ( last ) ; String lastDirName = lastDir . toString ( ) ; return topCollectionName + "-" + lastDirName ; }


Input: Create standard name = topCollectionName + last directory [CODESPLIT] public static Path makeCollectionIndexPath ( String topCollectionName , Path dir , String suffix ) { String collectionName = makeCollectionName ( topCollectionName , dir ) ; return Paths . get ( dir . toString ( ) , collectionName + suffix ) ; }


Input: this idiom keeps the iterator from escaping so that we can use try - with - resource and ensure DirectoryStream closes . like ++ [CODESPLIT] public void iterateOverMFileCollection ( Visitor visit ) throws IOException { if ( debug ) System . out . printf ( " iterateOverMFileCollection %s " , collectionDir ) ; int count = 0 ; try ( DirectoryStream < Path > ds = Files . newDirectoryStream ( collectionDir , new MyStreamFilter ( ) ) ) { for ( Path p : ds ) { try { BasicFileAttributes attr = Files . readAttributes ( p , BasicFileAttributes . class ) ; if ( ! attr . isDirectory ( ) ) visit . consume ( new MFileOS7 ( p ) ) ; if ( debug ) System . out . printf ( "%d " , count ++ ) ; } catch ( IOException ioe ) { // catch error and skip file logger . error ( "Failed to read attributes from file found in Files.newDirectoryStream " , ioe ) ; } } } if ( debug ) System . out . printf ( "%d%n" , count ) ; }


Input:
copy remote files to localDir [CODESPLIT] public void getRemoteFiles ( final CancelTask _cancel ) { this . cancel = _cancel ; String urls = config . getServerPrefix ( ) + "/thredds/admin/log/" + type + "/" ; ta . append ( String . format ( "Download URL = %s%n" , urls ) ) ; String contents = null ; try ( HTTPMethod method = HTTPFactory . Get ( session , urls ) ) { int statusCode = method . execute ( ) ; if ( statusCode == 200 ) contents = method . getResponseAsString ( ) ; if ( ( contents == null ) || ( contents . length ( ) == 0 ) ) { ta . append ( String . format ( "Failed to get logs at URL = %s%n%n" , urls ) ) ; return ; } else { ta . append ( String . format ( "Logs at URL = %s%n%s%n" , urls , contents ) ) ; } } catch ( Throwable t ) { ta . append ( String . format ( "Failed to get logs at URL = %s error = %s%n%n" , urls , t . getMessage ( ) ) ) ; t . printStackTrace ( ) ; return ; } // update text area in background  http://technobuz.com/2009/05/update-jtextarea-dynamically/
 final String list = contents ; SwingWorker worker = new SwingWorker < String , Void > ( ) { @ Override protected String doInBackground ( ) throws Exception { try { ta . append ( String . format ( "Local log files stored in = %s%n%n" , localDir ) ) ; String [ ] lines = list . split ( "\n" ) ; for ( String line : lines ) { new RemoteLog ( line . trim ( ) ) ; if ( cancel . isCancel ( ) ) { break ; } } } catch ( Throwable t ) { t . printStackTrace ( ) ; } return null ; } public void done ( ) { if ( cancel . isCancel ( ) ) ta . append ( String . format ( "Download was cancelled for %s%n" , type ) ) ; else ta . append ( String . format ( "Download complete for %s%n" , type ) ) ; } } ; // do in background
 worker . execute ( ) ; }


Input: PointFeatureIterator . hasNext () doesn t guarantee idempotency but we do . [CODESPLIT] @ Override public boolean hasNext ( ) { if ( pointFeature != null ) { return true ; // pointFeature hasn't yet been consumed. } pointFeature = nextFilteredDataPoint ( ) ; if ( pointFeature == null ) { close ( ) ; return false ; } else { return true ; } }


Input: but we can define a stronger contract . [CODESPLIT] @ Override public PointFeature next ( ) throws NoSuchElementException { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( "This iterator has no more elements." ) ; } assert pointFeature != null ; PointFeature ret = pointFeature ; calcBounds ( ret ) ; pointFeature = null ; // Feature has been consumed. return ret ; }


Input: Returns the next point that satisfies the filter or { @code null } if no such point exists . [CODESPLIT] private PointFeature nextFilteredDataPoint ( ) { while ( origIter . hasNext ( ) ) { PointFeature pointFeat = origIter . next ( ) ; if ( filter . filter ( pointFeat ) ) { return pointFeat ; } } return null ; }


Input: LOOK maybe combine grib1 grib2 and bufr ?? [CODESPLIT] @ Override public String getSubCenterName ( int center , int subcenter ) { switch ( subcenter ) { case 0 : return null ; case 1 : return "FSL/FRD Regional Analysis and Prediction Branch" ; case 2 : return "FSL/FRD Local Analysis and Prediction Branch" ; } return super . getSubCenterName ( center , subcenter ) ; }


Input:
Convert a period string into a CalendarPeriod . Field . [CODESPLIT] public static CalendarPeriod . Field fromUnitString ( String udunit ) { udunit = udunit . trim ( ) ; udunit = udunit . toLowerCase ( ) ; if ( udunit . equals ( "s" ) ) return Field . Second ; if ( udunit . equals ( "ms" ) ) return Field . Millisec ; // eliminate plurals
 if ( udunit . endsWith ( "s" ) ) udunit = udunit . substring ( 0 , udunit . length ( ) - 1 ) ; switch ( udunit ) { case "second" : case "sec" : return Field . Second ; case "millisecond" : case "millisec" : case "msec" : return Field . Millisec ; case "minute" : case "min" : return Field . Minute ; case "hour" : case "hr" : case "h" : return Field . Hour ; case "day" : case "d" : return Field . Day ; case "month" : case "mon" : return Field . Month ; case "year" : case "yr" : return Field . Year ; default : throw new IllegalArgumentException ( "cant convert " + udunit + " to CalendarPeriod" ) ; } }


Input: minimize memory use by interning . wacko shit in GribPartitionBuilder TimeCoordinate whoduhthunk? [CODESPLIT] public static CalendarPeriod of ( int value , Field field ) { CalendarPeriod want = new CalendarPeriod ( value , field ) ; if ( cache == null ) return want ; CalendarPeriod got = cache . getIfPresent ( want ) ; if ( got != null ) return got ; cache . put ( want , want ) ; return want ; }


Input: Convert a udunit period string into a CalendarPeriod [CODESPLIT] public static CalendarPeriod of ( String udunit ) { int value ; String units ; String [ ] split = StringUtil2 . splitString ( udunit ) ; if ( split . length == 1 ) { value = 1 ; units = split [ 0 ] ; } else if ( split . length == 2 ) { try { value = Integer . parseInt ( split [ 0 ] ) ; } catch ( Throwable t ) { return null ; } units = split [ 1 ] ; } else return null ; CalendarPeriod . Field unit = CalendarPeriod . fromUnitString ( units ) ; return CalendarPeriod . of ( value , unit ) ; }


Input: Subtract two dates return difference in units of this period . If not even will round down and log a warning [CODESPLIT] public int subtract ( CalendarDate start , CalendarDate end ) { long diff = end . getDifferenceInMsecs ( start ) ; int thislen = millisecs ( ) ; if ( ( diff % thislen != 0 ) ) log . warn ( "roundoff error" ) ; return ( int ) ( diff / thislen ) ; }


Input: Get the conversion factor of the other CalendarPeriod to this one [CODESPLIT] public double getConvertFactor ( CalendarPeriod from ) { if ( field == CalendarPeriod . Field . Month || field == CalendarPeriod . Field . Year ) { log . warn ( " CalendarDate.convert on Month or Year" ) ; } return ( double ) from . millisecs ( ) / millisecs ( ) ; }


Input: Get the duration in milliseconds - + [CODESPLIT] public double getValueInMillisecs ( ) { if ( field == CalendarPeriod . Field . Month ) return 30.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value ; else if ( field == CalendarPeriod . Field . Year ) return 365.0 * 24.0 * 60.0 * 60.0 * 1000.0 * value ; else return millisecs ( ) ; }


Input:
start + offset = end [CODESPLIT] public int getOffset ( CalendarDate start , CalendarDate end ) { if ( start . equals ( end ) ) return 0 ; long start_millis = start . getDateTime ( ) . getMillis ( ) ; long end_millis = end . getDateTime ( ) . getMillis ( ) ; // 5 second slop
 Period p ; if ( start_millis < end_millis ) p = new Period ( start_millis , end_millis + 5000 , getPeriodType ( ) ) ; else p = new Period ( start_millis + 5000 , end_millis , getPeriodType ( ) ) ; return p . get ( getDurationFieldType ( ) ) ; }


Input: Is this a valid file? [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { try { gemreader = new GempakGridReader ( raf . getLocation ( ) ) ; return gemreader . init ( raf , false ) ; } catch ( Exception ioe ) { return false ; } }


Input: Open the service provider for reading . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; // debugProj = true; long start = System . currentTimeMillis ( ) ; if ( gemreader == null ) { gemreader = new GempakGridReader ( raf . getLocation ( ) ) ; } initTables ( ) ; gemreader . init ( raf , true ) ; GridIndex index = gemreader . getGridIndex ( ) ; open ( index , cancelTask ) ; if ( debugOpen ) { System . out . println ( " GridServiceProvider.open " + ncfile . getLocation ( ) + " took " + ( System . currentTimeMillis ( ) - start ) ) ; } }


Input: Open the index and create the netCDF file from that [CODESPLIT] protected void open ( GridIndex index , CancelTask cancelTask ) throws IOException { GempakLookup lookup = new GempakLookup ( ( GempakGridRecord ) index . getGridRecords ( ) . get ( 0 ) ) ; GridIndexToNC delegate = new GridIndexToNC ( index . filename ) ; //delegate.setUseDescriptionForVariableName(false); delegate . open ( index , lookup , 4 , ncfile , cancelTask ) ; ncfile . finish ( ) ; }


Input: Sync the file [CODESPLIT] public boolean sync ( ) throws IOException { if ( ( gemreader . getInitFileSize ( ) < raf . length ( ) ) && extendIndex ) { gemreader . init ( true ) ; GridIndex index = gemreader . getGridIndex ( ) ; // reconstruct the ncfile objects ncfile . empty ( ) ; open ( index , null ) ; return true ; } return false ; }


Input: Initialize the parameter tables . [CODESPLIT] private void initTables ( ) { try { GempakGridParameterTable . addParameters ( "resources/nj22/tables/gempak/wmogrib3.tbl" ) ; GempakGridParameterTable . addParameters ( "resources/nj22/tables/gempak/ncepgrib2.tbl" ) ; } catch ( Exception e ) { System . out . println ( "unable to init tables" ) ; } }


Input: Add a dataRootExt to in - memory tree . [CODESPLIT] private boolean put ( DataRootExt dateRootExt ) { map . put ( dateRootExt . getPath ( ) , dateRootExt ) ; return treeSet . add ( dateRootExt . getPath ( ) ) ; }


Input: Find the longest path match . [CODESPLIT] public String findLongestPathMatch ( String reqPath ) { SortedSet < String > tail = treeSet . tailSet ( reqPath ) ; if ( tail . isEmpty ( ) ) return null ; String after = tail . first ( ) ; if ( reqPath . startsWith ( after ) ) // common case return tail . first ( ) ; // have to check more, until no common starting chars for ( String key : tail ) { if ( reqPath . startsWith ( key ) ) return key ; // terminate when there's no match at all. if ( StringUtil2 . match ( reqPath , key ) == 0 ) break ; } return null ; }


Input: Find the longest DataRoot match . [CODESPLIT] public DataRoot findDataRoot ( String reqPath ) { String path = findLongestPathMatch ( reqPath ) ; if ( path == null ) return null ; DataRootExt dataRootExt = map . get ( path ) ; if ( dataRootExt == null ) { logger . error ( "DataRootPathMatcher found path {} but not in map" , path ) ; return null ; } return convert2DataRoot ( dataRootExt ) ; }


Input: convert a dataRootExt to a dataRoot [CODESPLIT] public @ Nonnull DataRoot convert2DataRoot ( DataRootExt dataRootExt ) { DataRoot dataRoot = dataRootExt . getDataRoot ( ) ; if ( dataRoot != null ) return dataRoot ; // otherwise must read the catalog that its in dataRoot = readDataRootFromCatalog ( dataRootExt ) ; dataRootExt . setDataRoot ( dataRoot ) ; return dataRoot ; }


Input: Finds datasetScan datasetFmrc Look for duplicate Ids ( give message ) . Dont follow catRefs . [CODESPLIT] public void extractDataRoots ( String catalogRelPath , List < Dataset > dsList , boolean checkDups , Map < String , String > idMap ) { for ( Dataset dataset : dsList ) { if ( dataset instanceof DatasetScan ) { DatasetScan ds = ( DatasetScan ) dataset ; addRoot ( ds , catalogRelPath , checkDups ) ; } else if ( dataset instanceof FeatureCollectionRef ) { FeatureCollectionRef fc = ( FeatureCollectionRef ) dataset ; addRoot ( fc , catalogRelPath , checkDups ) ; if ( idMap != null ) { String catWithSameFc = idMap . get ( fc . getCollectionName ( ) ) ; if ( catWithSameFc != null ) logCatalogInit . warn ( "*** ERROR: Duplicate featureCollection name {} in catalogs '{}' and '{}'" , fc . getCollectionName ( ) , catalogRelPath , catWithSameFc ) ; else idMap . put ( fc . getCollectionName ( ) , catalogRelPath ) ; } } else if ( dataset instanceof CatalogScan ) { CatalogScan catScan = ( CatalogScan ) dataset ; addRoot ( catScan , catalogRelPath , checkDups ) ; } if ( ! ( dataset instanceof CatalogRef ) ) { // recurse extractDataRoots ( catalogRelPath , dataset . getDatasetsLocal ( ) , checkDups , idMap ) ; } } }


Input: return requested CalendarDateRange . [CODESPLIT] public CalendarDateRange getCalendarDateRange ( Calendar cal ) { if ( dateRange == null ) return null ; if ( cal . equals ( Calendar . getDefault ( ) ) ) return dateRange ; // otherwise must reparse return makeCalendarDateRange ( cal ) ; }


Input: redo the variables against the shared coordinates [CODESPLIT] public List < Integer > reindex ( List < Coordinate > coords ) { List < Integer > result = new ArrayList <> ( ) ; for ( Coordinate coord : coords ) { Coordinate sub = swap . get ( coord ) ; Coordinate use = ( sub == null ) ? coord : sub ; Integer idx = indexMap . get ( use ) ; // index into unionCoords if ( idx == null ) { throw new IllegalStateException ( ) ; } result . add ( idx ) ; } return result ; }


Input:
Open an existing Netcdf file for writing data . Fill mode is true . Cannot add new objects you can only read / write data to existing Variables . [CODESPLIT] static public NetcdfFileWriter openExisting ( String location ) throws IOException { return new NetcdfFileWriter ( null , location , true , null ) ; // dont know the version yet
 }


Input: Create a new Netcdf file with fill mode true . [CODESPLIT] static public NetcdfFileWriter createNew ( Version version , String location , Nc4Chunking chunker ) throws IOException { return new NetcdfFileWriter ( version , location , false , chunker ) ; }


Input: // use these calls in define mode [CODESPLIT] public Dimension addDimension ( String dimName , int length ) { return addDimension ( null , dimName , length , false , false ) ; }


Input: Add a shared Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( Group g , String dimName , int length ) { return addDimension ( g , dimName , length , false , false ) ; }


Input: Add a shared Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( Group g , String dimName , int length , boolean isUnlimited , boolean isVariableLength ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( dimName ) ) throw new IllegalArgumentException ( "illegal dimension name " + dimName ) ; Dimension dim = new Dimension ( dimName , length , true , isUnlimited , isVariableLength ) ; ncfile . addDimension ( g , dim ) ; return dim ; }


Input: Rename a Dimension . Must be in define mode . [CODESPLIT] public Dimension renameDimension ( Group g , String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( newName ) ) throw new IllegalArgumentException ( "illegal dimension name " + newName ) ; if ( g == null ) g = ncfile . getRootGroup ( ) ; Dimension dim = g . findDimension ( oldName ) ; if ( null != dim ) dim . setName ( newName ) ; return dim ; }


Input: Add a Group to the file . Must be in define mode . If pass in null as the parent then the root group is returned and the name is ignored . This is how you get the root group . Note this is different from other uses of parent group . [CODESPLIT] public Group addGroup ( Group parent , String name ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( parent == null ) return ncfile . getRootGroup ( ) ; Group result = new Group ( ncfile , parent , name ) ; parent . addGroup ( result ) ; return result ; }


Input: Add a Global attribute to the file . Must be in define mode . [CODESPLIT] public Attribute addGroupAttribute ( Group g , Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( att . getShortName ( ) ) ) { String attName = createValidObjectName ( att . getShortName ( ) ) ; log . warn ( "illegal attribute name= " + att . getShortName ( ) + " change to " + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } return ncfile . addAttribute ( g , att ) ; }


Input: Add a EnumTypedef to the file . Must be in define mode . [CODESPLIT] public EnumTypedef addTypedef ( Group g , EnumTypedef td ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! version . isExtendedModel ( ) ) throw new IllegalArgumentException ( "Enum type only supported in extended model, this version is=" + version ) ; g . addEnumeration ( td ) ; return td ; }


Input: Delete a group Attribute . Must be in define mode . [CODESPLIT] public Attribute deleteGroupAttribute ( Group g , String attName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( g == null ) g = ncfile . getRootGroup ( ) ; Attribute att = g . findAttribute ( attName ) ; if ( null == att ) return null ; g . remove ( att ) ; return att ; }


Input: Rename a group Attribute . Must be in define mode . [CODESPLIT] public Attribute renameGroupAttribute ( Group g , String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( newName ) ) { String newnewName = createValidObjectName ( newName ) ; log . warn ( "illegal attribute name= " + newName + " change to " + newnewName ) ; newName = newnewName ; } if ( g == null ) g = ncfile . getRootGroup ( ) ; Attribute att = g . findAttribute ( oldName ) ; if ( null == att ) return null ; g . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; g . addAttribute ( att ) ; return att ; }


Input: Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( Group g , String shortName , DataType dataType , String dimString ) { Group parent = ( g == null ) ? ncfile . getRootGroup ( ) : g ; return addVariable ( g , null , shortName , dataType , Dimension . makeDimensionsList ( parent , dimString ) ) ; }


Input: Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( Group g , String shortName , DataType dataType , List < Dimension > dims ) { if ( g == null ) g = ncfile . getRootGroup ( ) ; Variable oldVar = g . findVariable ( shortName ) ; if ( oldVar != null ) return null ; return addVariable ( g , null , shortName , dataType , dims ) ; }


Input:
Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( Group g , Structure parent , String shortName , DataType dataType , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; DataType writeType = version . isExtendedModel ( ) ? dataType : dataType . withSignedness ( DataType . Signedness . SIGNED ) ; // use signed type for netcdf3
 boolean usingSignForUnsign = writeType != dataType ; if ( ! isValidDataType ( writeType ) ) throw new IllegalArgumentException ( "illegal dataType: " + dataType + " not supported in netcdf-3" ) ; // check unlimited if classic model
 if ( ! version . isExtendedModel ( ) ) { for ( int i = 0 ; i < dims . size ( ) ; i ++ ) { Dimension d = dims . get ( i ) ; if ( d . isUnlimited ( ) && ( i != 0 ) ) throw new IllegalArgumentException ( "Unlimited dimension " + d . getShortName ( ) + " must be first (outermost) in netcdf-3 " ) ; } } shortName = makeValidObjectName ( shortName ) ; Variable v ; if ( dataType == DataType . STRUCTURE ) { v = new Structure ( ncfile , g , parent , shortName ) ; } else { v = new Variable ( ncfile , g , parent , shortName ) ; } v . setDataType ( writeType ) ; v . setDimensions ( dims ) ; if ( usingSignForUnsign ) v . addAttribute ( new Attribute ( CDM . UNSIGNED , "true" ) ) ; long size = v . getSize ( ) * v . getElementSize ( ) ; if ( version == Version . netcdf3 && size > N3iosp . MAX_VARSIZE ) throw new IllegalArgumentException ( "Variable size in bytes " + size + " may not exceed " + N3iosp . MAX_VARSIZE ) ; //System.out.printf("Variable size in bytes " + size + " may not exceed " + N3iosp.MAX_VARSIZE);
 ncfile . addVariable ( g , v ) ; return v ; }


Input:
Adds a copy of the specified structure to the file ( netcdf4 only ) . DO NOT USE YET [CODESPLIT] public Structure addCopyOfStructure ( Group g , @ Nonnull Structure original , String shortName , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( original == null ) throw new NullPointerException ( "Original structure must be non-null" ) ; shortName = makeValidObjectName ( shortName ) ; if ( ! version . isExtendedModel ( ) ) throw new IllegalArgumentException ( "Structure type only supported in extended model, version=" + version ) ; Structure s = new Structure ( ncfile , g , null , shortName ) ; s . setDimensions ( dims ) ; for ( Variable m : original . getVariables ( ) ) { // LOOK no nested structs
 Variable nest = new Variable ( ncfile , g , s , m . getShortName ( ) ) ; nest . setDataType ( m . getDataType ( ) ) ; nest . setDimensions ( m . getDimensions ( ) ) ; nest . addAll ( m . getAttributes ( ) ) ; s . addMemberVariable ( nest ) ; } ncfile . addVariable ( g , s ) ; return s ; }


Input:
Add a variable with DataType = String to a netCDF - 3 file . Must be in define mode . The variable will be stored in the file as a CHAR variable . A new dimension with name stringVar . getShortName () _strlen is automatically added with length max_strlen as determined from the data contained in the stringVar . [CODESPLIT] public Variable addStringVariable ( Group g , Variable stringVar , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( stringVar . getShortName ( ) ) ) throw new IllegalArgumentException ( "illegal netCDF-3 variable name: " + stringVar . getShortName ( ) ) ; // convert STRING to CHAR
 int max_strlen = 0 ; Array data ; try { data = stringVar . read ( ) ; IndexIterator ii = data . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . getObjectNext ( ) ; max_strlen = Math . max ( max_strlen , s . length ( ) ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; String err = "No data found for Variable " + stringVar . getShortName ( ) + ". Cannot determine the lentgh of the new CHAR variable." ; log . error ( err ) ; System . out . println ( err ) ; } return addStringVariable ( g , stringVar . getShortName ( ) , dims , max_strlen ) ; }


Input: Add a variable with DataType = String to the file . Must be in define mode . The variable will be stored in the file as a CHAR variable . A new dimension with name varName_strlen is automatically added with length max_strlen . [CODESPLIT] public Variable addStringVariable ( Group g , String shortName , List < Dimension > dims , int max_strlen ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; shortName = makeValidObjectName ( shortName ) ; Variable v = new Variable ( ncfile , g , null , shortName ) ; v . setDataType ( DataType . CHAR ) ; Dimension d = addDimension ( g , shortName + "_strlen" , max_strlen ) ; List < Dimension > sdims = new ArrayList <> ( dims ) ; sdims . add ( d ) ; v . setDimensions ( sdims ) ; ncfile . addVariable ( g , v ) ; return v ; }


Input: Rename a Variable . Must be in define mode . [CODESPLIT] public Variable renameVariable ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Variable v = ncfile . findVariable ( oldName ) ; if ( null != v ) { String fullOldNameEscaped = v . getFullNameEscaped ( ) ; v . setName ( newName ) ; varRenameMap . put ( v . getFullNameEscaped ( ) , fullOldNameEscaped ) ; } return v ; }


Input: Add an attribute to the named Variable . Must be in define mode . [CODESPLIT] public boolean addVariableAttribute ( Variable v , Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isValidObjectName ( att . getShortName ( ) ) ) { String attName = createValidObjectName ( att . getShortName ( ) ) ; log . warn ( "illegal netCDF-3 attribute name= " + att . getShortName ( ) + " change to " + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } v . addAttribute ( att ) ; return true ; }


Input:
After you have added all of the Dimensions Variables and Attributes call create () to actually create the file . You must be in define mode . After this call you are no longer in define mode . [CODESPLIT] public void create ( ) throws java . io . IOException { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! isNewFile ) throw new UnsupportedOperationException ( "can only call create on a new file" ) ; ncfile . finish ( ) ; // ??
 spiw . setFill ( fill ) ; // ??
 spiw . create ( location , ncfile , extraHeader , preallocateSize , isLargeFile ) ; defineMode = false ; }


Input:
Set the redefine mode . Designed to emulate nc_redef ( redefineMode = true ) and nc_enddef ( redefineMode = false ) [CODESPLIT] public boolean setRedefineMode ( boolean redefineMode ) throws IOException { if ( redefineMode && ! defineMode ) { defineMode = true ; } else if ( ! redefineMode && defineMode ) { defineMode = false ; ncfile . finish ( ) ; // try to rewrite header, if it fails, then we have to rewrite entire file
 boolean ok = spiw . rewriteHeader ( isLargeFile ) ; // LOOK seems like we should be using isNewFile
 if ( ! ok ) rewrite ( ) ; return ! ok ; } return false ; }


Input:
rewrite entire file [CODESPLIT] private void rewrite ( ) throws IOException { // close existing file, rename and open as read-only
 spiw . flush ( ) ; spiw . close ( ) ; File prevFile = new File ( location ) ; if ( ! prevFile . exists ( ) ) { return ; } File tmpFile = new File ( location + ".tmp" ) ; if ( tmpFile . exists ( ) ) { boolean ok = tmpFile . delete ( ) ; if ( ! ok ) log . warn ( "rewrite unable to delete {}" , tmpFile . getPath ( ) ) ; } if ( ! prevFile . renameTo ( tmpFile ) ) { System . out . println ( prevFile . getPath ( ) + " prevFile.exists " + prevFile . exists ( ) + " canRead = " + prevFile . canRead ( ) ) ; System . out . println ( tmpFile . getPath ( ) + " tmpFile.exists " + tmpFile . exists ( ) + " canWrite " + tmpFile . canWrite ( ) ) ; throw new RuntimeException ( "Cant rename " + prevFile . getAbsolutePath ( ) + " to " + tmpFile . getAbsolutePath ( ) ) ; } NetcdfFile oldFile = NetcdfFile . open ( tmpFile . getPath ( ) ) ; /* use record dimension if it has one
    Structure recordVar = null;
    if (oldFile.hasUnlimitedDimension()) {
      oldFile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
      recordVar = (Structure) oldFile.findVariable("record");
      /* if (recordVar != null) {
        Boolean result = (Boolean) spiw.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
        if (!result)
          recordVar = null;
      }
      } */ // create new file with current set of objects
 spiw . create ( location , ncfile , extraHeader , preallocateSize , isLargeFile ) ; spiw . setFill ( fill ) ; //isClosed = false;
 /* wait till header is written before adding the record variable to the file
    if (recordVar != null) {
      Boolean result = (Boolean) spiw.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
      if (!result)
        recordVar = null;
    } */ FileWriter2 fileWriter2 = new FileWriter2 ( this ) ; for ( Variable v : ncfile . getVariables ( ) ) { String oldVarName = v . getFullName ( ) ; Variable oldVar = oldFile . findVariable ( oldVarName ) ; if ( oldVar != null ) { fileWriter2 . copyAll ( oldVar , v ) ; } else if ( varRenameMap . containsKey ( oldVarName ) ) { // var name has changed in ncfile - use the varRenameMap to find
 //  the correct variable name to request from oldFile
 String realOldVarName = varRenameMap . get ( oldVarName ) ; oldVar = oldFile . findVariable ( realOldVarName ) ; if ( oldVar != null ) { fileWriter2 . copyAll ( oldVar , v ) ; } } else { String message = "Cannot find variable " + oldVarName + " to copy to new file." ; log . warn ( message ) ; System . out . println ( message ) ; } } // delete old
 oldFile . close ( ) ; if ( ! tmpFile . delete ( ) ) throw new RuntimeException ( "Cant delete " + tmpFile . getAbsolutePath ( ) ) ; }


Input: For netcdf3 only take all unlimited variables and make them into a structure . [CODESPLIT] public Structure addRecordStructure ( ) { if ( version != Version . netcdf3 ) return null ; boolean ok = ( Boolean ) ncfile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ! ok ) throw new IllegalStateException ( "can't add record variable" ) ; return ( Structure ) ncfile . findVariable ( "record" ) ; }


Input: // use these calls to write data to the file [CODESPLIT] public void write ( String varname , Array values ) throws java . io . IOException , InvalidRangeException { write ( findVariable ( varname ) , values ) ; }


Input: Write data to the named variable origin assumed to be 0 . Must not be in define mode . [CODESPLIT] public void write ( Variable v , Array values ) throws java . io . IOException , InvalidRangeException { if ( ncfile != v . getNetcdfFile ( ) ) throw new IllegalArgumentException ( "Variable is not owned by this writer." ) ; write ( v , new int [ values . getRank ( ) ] , values ) ; }


Input: Write data to the named variable . Must not be in define mode . [CODESPLIT] public void write ( Variable v , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( defineMode ) throw new UnsupportedOperationException ( "in define mode" ) ; spiw . writeData ( v , new Section ( origin , values . getShape ( ) ) , values ) ; v . invalidateCache ( ) ; }


Input: Write String data to a CHAR variable origin assumed to be 0 . Must not be in define mode . [CODESPLIT] public void writeStringData ( Variable v , Array values ) throws java . io . IOException , InvalidRangeException { writeStringData ( v , new int [ values . getRank ( ) ] , values ) ; }


Input:
Write String data to a CHAR variable . Must not be in define mode . [CODESPLIT] public void writeStringData ( Variable v , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( values . getElementType ( ) != String . class ) throw new IllegalArgumentException ( "Must be ArrayObject of String " ) ; if ( v . getDataType ( ) != DataType . CHAR ) throw new IllegalArgumentException ( "variable " + v . getFullName ( ) + " is not type CHAR" ) ; int rank = v . getRank ( ) ; int strlen = v . getShape ( rank - 1 ) ; // turn it into an ArrayChar
 ArrayChar cvalues = ArrayChar . makeFromStringArray ( ( ArrayObject ) values , strlen ) ; int [ ] corigin = new int [ rank ] ; System . arraycopy ( origin , 0 , corigin , 0 , rank - 1 ) ; write ( v , corigin , cvalues ) ; }


Input: close the file . [CODESPLIT] public synchronized void close ( ) throws java . io . IOException { if ( spiw != null ) { setRedefineMode ( false ) ; flush ( ) ; spiw . close ( ) ; spiw = null ; } }


Input: Abort writing to this file . The file is closed . [CODESPLIT] public void abort ( ) throws java . io . IOException { if ( spiw != null ) { spiw . close ( ) ; spiw = null ; } }


Input: write XML using the bean properties of the contained object [CODESPLIT] public void writeProperties ( PrintWriter out ) throws IOException { if ( p == null ) p = BeanParser . getParser ( o . getClass ( ) ) ; p . writeProperties ( o , out ) ; }


Input: extract info from underlying feature dataset [CODESPLIT] public ThreddsMetadata extract ( Dataset threddsDataset ) throws IOException { ThreddsMetadata metadata = new ThreddsMetadata ( ) ; Map < String , Object > flds = metadata . getFlds ( ) ; try ( DataFactory . Result result = new DataFactory ( ) . openFeatureDataset ( threddsDataset , null ) ) { if ( result . fatalError ) { logger . warn ( " openFeatureDataset failed, errs=%s%n" , result . errLog ) ; return null ; } if ( result . featureType . isCoverageFeatureType ( ) ) { GridDataset gridDataset = ( GridDataset ) result . featureDataset ; // LOOK wrong flds . put ( Dataset . GeospatialCoverage , extractGeospatial ( gridDataset ) ) ; CalendarDateRange tc = extractCalendarDateRange ( gridDataset ) ; if ( tc != null ) flds . put ( Dataset . TimeCoverage , tc ) ; ThreddsMetadata . VariableGroup vars = extractVariables ( threddsDataset . getDataFormatName ( ) , gridDataset ) ; if ( vars != null ) flds . put ( Dataset . VariableGroups , vars ) ; } else if ( result . featureType . isPointFeatureType ( ) ) { PointDatasetImpl pobsDataset = ( PointDatasetImpl ) result . featureDataset ; LatLonRect llbb = pobsDataset . getBoundingBox ( ) ; if ( null != llbb ) flds . put ( Dataset . GeospatialCoverage , new ThreddsMetadata . GeospatialCoverage ( llbb , null , 0.0 , 0.0 ) ) ; CalendarDateRange tc = extractCalendarDateRange ( pobsDataset ) ; if ( tc != null ) flds . put ( Dataset . TimeCoverage , tc ) ; ThreddsMetadata . VariableGroup vars = extractVariables ( pobsDataset ) ; if ( vars != null ) flds . put ( Dataset . VariableGroups , vars ) ; } } catch ( IOException ioe ) { logger . error ( "Error opening dataset " + threddsDataset . getName ( ) , ioe ) ; } return metadata ; }


Input: ///////////////////////////////////////////////////////////////////////////// [CODESPLIT] public ThreddsMetadata . GeospatialCoverage extractGeospatial ( FeatureDatasetPoint fd ) { LatLonRect llbb = fd . getBoundingBox ( ) ; if ( llbb != null ) { return new ThreddsMetadata . GeospatialCoverage ( llbb , null , 0.0 , 0.0 ) ; } return null ; }


Input: ////////////////// [CODESPLIT] public CalendarDateRange extractCalendarDateRange ( GridDataset gridDataset ) { CalendarDateRange maxDateRange = null ; for ( GridDataset . Gridset gridset : gridDataset . getGridsets ( ) ) { GridCoordSystem gsys = gridset . getGeoCoordSystem ( ) ; CalendarDateRange dateRange ; CoordinateAxis1DTime time1D = gsys . getTimeAxis1D ( ) ; if ( time1D != null ) { dateRange = time1D . getCalendarDateRange ( ) ; } else { CoordinateAxis time = gsys . getTimeAxis ( ) ; if ( time == null ) continue ; try { CalendarDateUnit du = CalendarDateUnit . of ( null , time . getUnitsString ( ) ) ; // LOOK no calendar CalendarDate minDate = du . makeCalendarDate ( time . getMinValue ( ) ) ; CalendarDate maxDate = du . makeCalendarDate ( time . getMaxValue ( ) ) ; dateRange = CalendarDateRange . of ( minDate , maxDate ) ; } catch ( Exception e ) { logger . warn ( "Illegal Date Unit " + time . getUnitsString ( ) ) ; continue ; } } if ( maxDateRange == null ) maxDateRange = dateRange ; else maxDateRange = maxDateRange . extend ( dateRange ) ; } return maxDateRange ; }


Input:
Look for possible matches of old ( 4 . 2 ) grib names in new ( 4 . 3 ) dataset . [CODESPLIT] List < String > matchNcepNames ( GridDataset gds , String oldName ) { List < String > result = new ArrayList <> ( ) ; // look for exact match
 if ( contains ( gds , oldName ) ) { result . add ( oldName ) ; return result ; } Attribute att = gds . findGlobalAttributeIgnoreCase ( CDM . FILE_FORMAT ) ; boolean isGrib1 = ( att != null ) && att . getStringValue ( ) . startsWith ( "GRIB-1" ) ; boolean isGrib2 = ( att != null ) && att . getStringValue ( ) . startsWith ( "GRIB-2" ) ; HashMap < String , Renamer > map ; if ( isGrib1 ) { if ( map1 == null ) initMap1 ( ) ; map = map1 ; } else if ( isGrib2 ) { if ( map2 == null ) initMap2 ( ) ; map = map2 ; } else { return result ; // empty list
 } // look in our renamer map
 Renamer mbean = map . get ( oldName ) ; if ( mbean != null && mbean . newName != null && contains ( gds , mbean . newName ) ) { result . add ( mbean . newName ) ; // if its unique, then we are done
 return result ; } // not unique - match against NCEP dataset
 if ( mbean != null ) { String dataset = extractDatasetFromLocation ( gds . getLocation ( ) ) ; for ( VariableRenamerBean r : mbean . newVars ) { if ( r . getDatasetType ( ) . equals ( dataset ) && contains ( gds , r . newName ) ) result . add ( r . newName ) ; } if ( result . size ( ) == 1 ) return result ; // return if unique
 } // not unique, no unique match against dataset - check existence in the dataset
 result . clear ( ) ; if ( mbean != null ) { for ( VariableRenamerBean r : mbean . newVarsMap . values ( ) ) { if ( contains ( gds , r . newName ) ) result . add ( r . newName ) ; } if ( result . size ( ) > 0 ) return result ; } // try to map oldName -> new prefix
 result . clear ( ) ; String oldMunged = munge ( oldName ) ; for ( GridDatatype grid : gds . getGrids ( ) ) { String newMunged = munge ( grid . getShortName ( ) ) ; if ( newMunged . startsWith ( oldMunged ) ) result . add ( grid . getShortName ( ) ) ; } if ( result . size ( ) > 0 ) return result ; // return empty list
 return result ; }


Input:
//////////////////////////////////////////////// [CODESPLIT] private HashMap < String , Renamer > makeMapBeans ( List < VariableRenamerBean > vbeans ) { HashMap < String , Renamer > map = new HashMap <> ( 3000 ) ; for ( VariableRenamerBean vbean : vbeans ) { // construct the old -> new mapping
 Renamer mbean = map . get ( vbean . getOldName ( ) ) ; if ( mbean == null ) { mbean = new Renamer ( vbean . getOldName ( ) ) ; map . put ( vbean . getOldName ( ) , mbean ) ; } mbean . add ( vbean ) ; } for ( Renamer rmap : map . values ( ) ) { rmap . finish ( ) ; } return map ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : result / wml2 : MeasurementTimeseries [CODESPLIT] public static MeasurementTimeseriesType initMeasurementTimeseries ( MeasurementTimeseriesType measurementTimeseries , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( MeasurementTimeseriesType . class ) ; measurementTimeseries . setId ( id ) ; // wml2:defaultPointMetadata NcTVPDefaultMetadataPropertyType . initDefaultPointMetadata ( measurementTimeseries . addNewDefaultPointMetadata ( ) , dataVar ) ; // wml2:point[0..*] for ( PointFeature pf : stationFeat ) { // wml2:point Point . initPoint ( measurementTimeseries . addNewPoint ( ) , pf , dataVar ) ; } return measurementTimeseries ; }


Input: Multiply this unit by another unit . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { return that instanceof OffsetUnit ? getUnit ( ) . multiplyBy ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . multiplyBy ( that ) ; }


Input: Divide this unit by another unit . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { return that instanceof OffsetUnit ? getUnit ( ) . divideBy ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . divideBy ( that ) ; }


Input: Divide this unit into another unit . [CODESPLIT] @ Override protected Unit myDivideInto ( final Unit that ) throws OperationException { return that instanceof OffsetUnit ? getUnit ( ) . divideInto ( ( ( OffsetUnit ) that ) . getUnit ( ) ) : getUnit ( ) . divideInto ( that ) ; }


Input: Converts a value in this unit to the equivalent value in the convertible derived unit . [CODESPLIT] public double toDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( this , getDerivedUnit ( ) ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . toDerivedUnit ( amount + getOffset ( ) ) ; }


Input: Converts a value in the convertible derived unit to the equivalent value in this unit . [CODESPLIT] public double fromDerivedUnit ( final double amount ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } return ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( amount ) - getOffset ( ) ; }


Input: Converts values in the convertible derived unit to the equivalent values in this unit . [CODESPLIT] public double [ ] fromDerivedUnit ( final double [ ] input , final double [ ] output ) throws ConversionException { if ( ! ( _unit instanceof DerivableUnit ) ) { throw new ConversionException ( getDerivedUnit ( ) , this ) ; } ( ( DerivableUnit ) getUnit ( ) ) . fromDerivedUnit ( input , output ) ; final double origin = getOffset ( ) ; for ( int i = input . length ; -- i >= 0 ; ) { output [ i ] -= origin ; } return output ; }


Input:
Convert a DataDDS into an Array for a Structure member variable . [CODESPLIT] public Array convertNestedVariable ( ucar . nc2 . Variable v , List < Range > section , DodsV dataV , boolean flatten ) throws IOException , DAP2Exception { Array data = convertTopVariable ( v , section , dataV ) ; if ( flatten ) { ArrayStructure as = ( ArrayStructure ) data ; // make list of names
 List < String > names = new ArrayList <> ( ) ; Variable nested = v ; while ( nested . isMemberOfStructure ( ) ) { names . add ( 0 , nested . getShortName ( ) ) ; nested = nested . getParentStructure ( ) ; } StructureMembers . Member m = findNested ( as , names , v . getShortName ( ) ) ; Array mdata = m . getDataArray ( ) ; if ( mdata instanceof ArraySequenceNested ) { // gotta unroll
 ArraySequenceNested arraySeq = ( ArraySequenceNested ) mdata ; return arraySeq . flatten ( ) ; } return mdata ; } return data ; }


Input:
Convert a DataDDS into an Array for a top level variable ie not a Structure member variable . [CODESPLIT] public Array convertTopVariable ( ucar . nc2 . Variable v , List < Range > section , DodsV dataV ) throws IOException , DAP2Exception { Array data = convert ( dataV ) ; // arrays
 if ( ( dataV . darray != null ) && ( dataV . bt instanceof DString ) ) { if ( v . getDataType ( ) == DataType . STRING ) return convertStringArray ( data , v ) ; else if ( v . getDataType ( ) == DataType . CHAR ) return convertStringArrayToChar ( dataV . darray , v , section ) ; else { String mess = "DODSVariable convertArray String invalid dataType= " + v . getDataType ( ) ; logger . error ( mess ) ; throw new IllegalArgumentException ( mess ) ; } } if ( ( dataV . bt instanceof DString ) && ( v . getDataType ( ) == DataType . CHAR ) ) { // special case: convert String back to CHAR
 return convertStringToChar ( data , v ) ; } return data ; /* else { // the DGrid case comes here also
         // create the array, using  DODS internal array so there's no copying
        dods.dap.PrimitiveVector pv = dataV.darray.getPrimitiveVector();
        Object storage = pv.getInternalStorage();
        //storage = widenArray( pv, storage); // LOOK data conversion if needed
        int[] shape = (section == null) ? v.getShape() : Range.getShape(section);
        return Array.factory( v.getDataType().getPrimitiveClassType(), shape, storage);
      }   */ }


Input:
Convert a DataDDS into an Array [CODESPLIT] public Array convert ( DodsV dataV ) throws IOException , DAP2Exception { // scalars
 if ( dataV . darray == null ) { if ( dataV . bt instanceof DStructure ) { ArrayStructure structArray = makeArrayStructure ( dataV ) ; iconvertDataStructure ( ( DStructure ) dataV . bt , structArray . getStructureMembers ( ) ) ; return structArray ; } else if ( dataV . bt instanceof DGrid ) { throw new IllegalStateException ( "DGrid without a darray" ) ; } else if ( dataV . bt instanceof DSequence ) { ArrayStructure structArray = makeArrayStructure ( dataV ) ; iconvertDataSequenceArray ( ( DSequence ) dataV . bt , structArray . getStructureMembers ( ) ) ; return structArray ; } else { // scalar
 DataType dtype = dataV . getDataType ( ) ; Array scalarData = Array . factory ( dtype , new int [ 0 ] ) ; IndexIterator scalarIndex = scalarData . getIndexIterator ( ) ; iconvertDataPrimitiveScalar ( dataV . bt , scalarIndex ) ; return scalarData ; } } // arrays
 if ( dataV . darray != null ) { if ( dataV . bt instanceof DStructure ) { ArrayStructure structArray = makeArrayStructure ( dataV ) ; iconvertDataStructureArray ( dataV . darray , structArray . getStructureMembers ( ) ) ; return structArray ; } else if ( dataV . bt instanceof DString ) { return convertStringArray ( dataV . darray ) ; } else { // the DGrid case comes here also
 // create the array, using  DODS internal array so there's no copying
 opendap . dap . PrimitiveVector pv = dataV . darray . getPrimitiveVector ( ) ; Object storage = pv . getInternalStorage ( ) ; DataType dtype = dataV . getDataType ( ) ; return Array . factory ( dtype , makeShape ( dataV . darray ) , storage ) ; } } String mess = "Unknown baseType " + dataV . bt . getClass ( ) . getName ( ) + " name=" + dataV . getEncodedName ( ) ; logger . error ( mess ) ; throw new IllegalStateException ( mess ) ; }


Input:
dataV is an array of DStructure : DArray with BaseTypePrimitiveVector whose values are DStructure [CODESPLIT] private void iconvertDataStructureArray ( DVector darray , StructureMembers members ) throws DAP2Exception { List < StructureMembers . Member > mlist = members . getMembers ( ) ; for ( StructureMembers . Member member : mlist ) { // get the Array for this member
 String name = member . getName ( ) ; IndexIterator ii = ( IndexIterator ) member . getDataObject ( ) ; // loop over each row, fill up the data
 BaseTypePrimitiveVector pv = ( BaseTypePrimitiveVector ) darray . getPrimitiveVector ( ) ; for ( int row = 0 ; row < pv . getLength ( ) ; row ++ ) { DStructure ds_data = ( DStructure ) pv . getValue ( row ) ; BaseType member_data = ds_data . getVariable ( name ) ; iconvertData ( member_data , ii ) ; } } }


Input:
convert a DODS scalar value [CODESPLIT] private void iconvertDataPrimitiveScalar ( BaseType dodsScalar , IndexIterator ii ) { if ( dodsScalar instanceof DString ) { String sval = ( ( DString ) dodsScalar ) . getValue ( ) ; ii . setObjectNext ( sval ) ; } else if ( dodsScalar instanceof DUInt32 ) { int ival = ( ( DUInt32 ) dodsScalar ) . getValue ( ) ; long lval = DataType . unsignedIntToLong ( ival ) ; // LOOK unsigned
 ii . setLongNext ( lval ) ; } else if ( dodsScalar instanceof DUInt16 ) { short sval = ( ( DUInt16 ) dodsScalar ) . getValue ( ) ; // LOOK unsigned
 int ival = DataType . unsignedShortToInt ( sval ) ; ii . setIntNext ( ival ) ; } else if ( dodsScalar instanceof DFloat32 ) ii . setFloatNext ( ( ( DFloat32 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DFloat64 ) ii . setDoubleNext ( ( ( DFloat64 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DInt32 ) ii . setIntNext ( ( ( DInt32 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DInt16 ) ii . setShortNext ( ( ( DInt16 ) dodsScalar ) . getValue ( ) ) ; else if ( dodsScalar instanceof DByte ) ii . setByteNext ( ( ( DByte ) dodsScalar ) . getValue ( ) ) ; else throw new IllegalArgumentException ( "DODSVariable extractScalar invalid dataType= " + dodsScalar . getClass ( ) . getName ( ) ) ; }


Input:
convert a DODS scalar value [CODESPLIT] private void iconvertDataPrimitiveArray ( PrimitiveVector pv , IndexIterator ii ) { BaseType bt = pv . getTemplate ( ) ; // set the data value, using scalarIndex from Variable
 if ( bt instanceof DString ) { BaseTypePrimitiveVector bpv = ( BaseTypePrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) { DString ds = ( DString ) bpv . getValue ( row ) ; ii . setObjectNext ( ds . getValue ( ) ) ; // LOOK CHAR ?
 } } else if ( bt instanceof DUInt32 ) { UInt32PrimitiveVector bpv = ( UInt32PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) { int ival = bpv . getValue ( row ) ; long lval = DataType . unsignedIntToLong ( ival ) ; // LOOK unsigned
 ii . setLongNext ( lval ) ; } } else if ( bt instanceof DUInt16 ) { UInt16PrimitiveVector bpv = ( UInt16PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) { short sval = bpv . getValue ( row ) ; // LOOK unsigned
 int ival = DataType . unsignedShortToInt ( sval ) ; ii . setIntNext ( ival ) ; } } else if ( bt instanceof DFloat32 ) { Float32PrimitiveVector bpv = ( Float32PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setFloatNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DFloat64 ) { Float64PrimitiveVector bpv = ( Float64PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setDoubleNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DInt32 ) { Int32PrimitiveVector bpv = ( Int32PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setIntNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DInt16 ) { Int16PrimitiveVector bpv = ( Int16PrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setShortNext ( bpv . getValue ( row ) ) ; } else if ( bt instanceof DByte ) { BytePrimitiveVector bpv = ( BytePrimitiveVector ) pv ; for ( int row = 0 ; row < bpv . getLength ( ) ; row ++ ) ii . setByteNext ( bpv . getValue ( row ) ) ; } else throw new IllegalArgumentException ( "DODSVariable extractScalar invalid dataType= " + bt . getClass ( ) . getName ( ) ) ; }


Input:
older opendap servers send netcdf char data as Strings of length 1 ( !! ) [CODESPLIT] private Array convertStringArray ( Array data , Variable ncVar ) { String [ ] storage = ( String [ ] ) data . getStorage ( ) ; int max_len = 0 ; for ( String s : storage ) { max_len = Math . max ( max_len , s . length ( ) ) ; } if ( max_len > 1 ) return data ; // below is the length=1 barfalloney
 int count = 0 ; int n = ( int ) data . getSize ( ) ; char [ ] charStorage = new char [ n ] ; for ( String s : storage ) { if ( s . length ( ) > 0 ) charStorage [ count ++ ] = s . charAt ( 0 ) ; } // change it to a char (!!). Since its no longer a String, this code wont get called again for this variable.
 ncVar . setDataType ( DataType . CHAR ) ; // return data thats been changed to chars
 return Array . factory ( DataType . CHAR , data . getShape ( ) , charStorage ) ; /* if (section == null)
      section = ncVar.getRanges();

    // add the strLen dimension back to the array
    int[] varShape = ncVar.getShape();
    int strLen = varShape[ ncVar.getRank()-1];
    int total = (int) Range.computeSize(section);
    int newSize = total/strLen;
    String[] newStorage = new String[newSize];

    // merge last dimension
    StringBuffer sbuff = new StringBuffer();
    int newCount = 0;
    while (newCount < newSize) {
      int mergeCount = 0;
      sbuff.setLength(0);
      while (mergeCount < strLen) {
        String s = storage[strLen * newCount + mergeCount];
        if (s.length() == 0) break;
        sbuff.append( s);
        mergeCount++;
      }
      newStorage[ newCount++] = sbuff.toString();
    }

    /* List dims = ncVar.getDimensions();
    ncVar.setDimensions( dims.subList(0, ncVar.getRank()-1)); // LOOK is this dangerous or what ???
    int[] newShape = ncVar.getShape();
    return Array.factory( DataType.STRING.getPrimitiveClassType(), newShape, newStorage); */ }


Input: this is called on TDS shutdown and reinit [CODESPLIT] static synchronized public void closeAll ( ) { List < MetadataManager > closeDatabases = new ArrayList <> ( openDatabases ) ; for ( MetadataManager mm : closeDatabases ) { if ( debug ) System . out . println ( "  close database " + mm . collectionName ) ; mm . close ( ) ; } openDatabases = new ArrayList <> ( ) ; // empty if ( myEnv != null ) { try { // Finally, close the store and environment. myEnv . close ( ) ; myEnv = null ; logger . info ( "closed bdb caching" ) ; } catch ( DatabaseException dbe ) { logger . error ( "Error closing bdb: " , dbe ) ; } } }


Input: assumes only one open at a time ; could have MetadataManagers share open databases [CODESPLIT] private synchronized void openDatabase ( ) { if ( database != null ) return ; DatabaseConfig dbConfig = new DatabaseConfig ( ) ; dbConfig . setReadOnly ( readOnly ) ; dbConfig . setAllowCreate ( ! readOnly ) ; if ( ! readOnly ) dbConfig . setDeferredWrite ( true ) ; database = myEnv . openDatabase ( null , collectionName , dbConfig ) ; openDatabases . add ( this ) ; }


Input: See if edit value is valid put error message in buff . [CODESPLIT] @ Override protected boolean _validate ( StringBuffer buff ) { try { new DateType ( tf . getText ( ) , null , null ) ; return true ; } catch ( java . text . ParseException e ) { if ( null != buff ) buff . append ( name ) . append ( ": " ) . append ( e . getMessage ( ) ) ; return false ; } }


Input: get current value from editComponent [CODESPLIT] @ Override protected Object getEditValue ( ) { try { return new DateType ( tf . getText ( ) , null , null ) ; } catch ( java . text . ParseException e ) { return null ; } }


Input: Convert a time udunit string [CODESPLIT] static org . joda . time . Period convertToPeriod ( int value , String udunit ) { if ( udunit . endsWith ( "s" ) ) udunit = udunit . substring ( 0 , udunit . length ( ) - 1 ) ; switch ( udunit ) { case "msec" : return Period . millis ( value ) ; case "sec" : return Period . seconds ( value ) ; case "minute" : return Period . minutes ( value ) ; case "hour" : case "hr" : return Period . hours ( value ) ; case "day" : return Period . days ( value ) ; case "week" : return Period . weeks ( value ) ; case "month" : return Period . months ( value ) ; case "year" : return Period . years ( value ) ; } throw new IllegalArgumentException ( "cant convert " + udunit + " to Joda Period" ) ; }


Input: / * # Code table 4 . 2 - Parameter number by product discipline and parameter category 0 0 Estimated precipitation ( kg m - 2 ) 1 1 Instantaneous rain rate ( kg m - 2 s - 1 ) 2 2 Cloud top height ( m ) 3 3 Cloud top height quality indicator ( Code table 4 . 219 ) 4 4 Estimated u - component of wind ( m / s ) 5 5 Estimated v - component of wind ( m / s ) 6 6 Number of pixel used ( Numeric ) 7 7 Solar zenith angle ( deg ) 8 8 Relative azimuth angle ( deg ) 9 9 Reflectance in 0 . 6 micron channel ( % ) 10 10 Reflectance in 0 . 8 micron channel ( % ) 11 11 Reflectance in 1 . 6 micron channel ( % ) 12 12 Reflectance in 3 . 9 micron channel ( % ) 13 13 Atmospheric divergence ( / s ) 14 14 Cloudy brightness temperature ( K ) 15 15 Clear - sky brightness temperature ( K ) 16 16 Cloudy radiance ( with respect to wave number ) ( W m - 1 sr - 1 ) 17 17 Clear - sky radiance ( with respect to wave number ) ( W m - 1 sr - 1 ) 18 18 Reserved 19 19 Wind speed ( m / s ) 20 20 Aerosol optical thickness at 0 . 635 um 21 21 Aerosol optical thickness at 0 . 810 um 22 22 Aerosol optical thickness at 1 . 640 um 23 23 Angstrom coefficient # 24 - 26 Reserved 27 27 Bidirectional reflectance factor ( numeric ) 28 28 Brightness temperature ( K ) 29 29 Scaled radiance ( numeric ) # 30 - 191 Reserved # 192 - 254 Reserved for local use 255 255 Missing [CODESPLIT] private ImmutableMap < Integer , Entry > readTable ( String path ) throws IOException { ImmutableMap . Builder < Integer , Entry > builder = ImmutableMap . builder ( ) ; if ( debugOpen ) { System . out . printf ( "readEcmwfTable path= %s%n" , path ) ; } ClassLoader cl = Grib2TableConfig . class . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( path ) ) { if ( is == null ) { throw new IllegalStateException ( "Cant find " + path ) ; } try ( BufferedReader dataIS = new BufferedReader ( new InputStreamReader ( is , Charset . forName ( "UTF8" ) ) ) ) { int count = 0 ; while ( true ) { String line = dataIS . readLine ( ) ; if ( line == null ) { break ; } if ( line . startsWith ( "#" ) || line . trim ( ) . length ( ) == 0 ) { continue ; } count ++ ; int posBlank1 = line . indexOf ( ' ' ) ; int posBlank2 = line . indexOf ( ' ' , posBlank1 + 1 ) ; int lastParen = line . lastIndexOf ( ' ' ) ; String num1 = line . substring ( 0 , posBlank1 ) . trim ( ) ; String num2 = line . substring ( posBlank1 + 1 , posBlank2 ) ; String desc = ( lastParen > 0 ) ? line . substring ( posBlank2 + 1 , lastParen ) . trim ( ) : line . substring ( posBlank2 + 1 ) . trim ( ) ; if ( ! num1 . equals ( num2 ) ) { if ( debug ) { System . out . printf ( "*****num1 != num2 for %s%n" , line ) ; } continue ; } int code = Integer . parseInt ( num1 ) ; EcmwfEntry entry = new EcmwfEntry ( code , desc ) ; builder . put ( entry . getCode ( ) , entry ) ; if ( debug ) { System . out . printf ( " %s%n" , entry ) ; } } } } return builder . build ( ) ; }


Input:
brute force [CODESPLIT] public boolean findCoordElementForce ( double wantLat , double wantLon , int [ ] rectIndex ) { findBounds ( ) ; if ( wantLat < latMinMax . min ) return false ; if ( wantLat > latMinMax . max ) return false ; if ( wantLon < lonMinMax . min ) return false ; if ( wantLon > lonMinMax . max ) return false ; boolean saveDebug = debug ; debug = false ; for ( int row = 0 ; row < nrows ; row ++ ) { for ( int col = 0 ; col < ncols ; col ++ ) { rectIndex [ 0 ] = row ; rectIndex [ 1 ] = col ; if ( contains ( wantLat , wantLon , rectIndex ) ) { debug = saveDebug ; return true ; } } } //debug = saveDebug;
 return false ; }


Input:
Find the best index for the given lat lon point . @param wantLat lat of point @param wantLon lon of point @param rectIndex return ( row col ) index or best guess here . may not be null [CODESPLIT] public boolean findCoordElementNoForce ( double wantLat , double wantLon , int [ ] rectIndex ) { findBounds ( ) ; if ( wantLat < latMinMax . min ) return false ; if ( wantLat > latMinMax . max ) return false ; if ( wantLon < lonMinMax . min ) return false ; if ( wantLon > lonMinMax . max ) return false ; double gradientLat = ( latMinMax . max - latMinMax . min ) / nrows ; double gradientLon = ( lonMinMax . max - lonMinMax . min ) / ncols ; double diffLat = wantLat - latMinMax . min ; double diffLon = wantLon - lonMinMax . min ; // initial guess
 rectIndex [ 0 ] = ( int ) Math . round ( diffLat / gradientLat ) ; // row
 rectIndex [ 1 ] = ( int ) Math . round ( diffLon / gradientLon ) ; // col
 int count = 0 ; while ( true ) { count ++ ; if ( debug ) System . out . printf ( "%nIteration %d %n" , count ) ; if ( contains ( wantLat , wantLon , rectIndex ) ) return true ; if ( ! jump2 ( wantLat , wantLon , rectIndex ) ) return false ; // bouncing around
 if ( count > 10 ) { // last ditch attempt
 return incr ( wantLat , wantLon , rectIndex ) ; //if (!ok)
 //  log.error("findCoordElement didnt converge lat,lon = "+wantLat+" "+ wantLon);
 //return ok;
 } } }


Input: Reads the contents of { @code inputStream } into a StringArray . Each line of input will result in an element in the array . <p / > The specified stream remains open after this method returns . [CODESPLIT] public static ErddapStringArray fromInputStream ( InputStream inputStream , String charset ) throws IOException { if ( charset == null || charset . isEmpty ( ) ) { charset = CDM . UTF8 ; } InputStreamReader isr = new InputStreamReader ( inputStream , charset ) ; BufferedReader bufferedReader = new BufferedReader ( isr ) ; ErddapStringArray sa = new ErddapStringArray ( ) ; for ( String s ; ( s = bufferedReader . readLine ( ) ) != null ; ) { sa . add ( s ) ; } // Do not call BufferedReader.close() here; that would close the underlying InputStream, which is the // responsibility of the client. This ought to be safe, as neither InputStreamReader nor BufferedReader hold any // resources that a call to close() would make free and which the garbage collector would not make free anyway. return sa ; }


Input: This adds an item to the array ( increasing size by 1 ) . [CODESPLIT] public void add ( String value ) { if ( size == array . length ) //if we're at capacity ensureCapacity ( size + 1L ) ; array [ size ++ ] = value ; }


Input: This ensures that the capacity is at least minCapacity . [CODESPLIT] public void ensureCapacity ( long minCapacity ) { if ( array . length < minCapacity ) { //ensure minCapacity is < Integer.MAX_VALUE ErddapMath2 . ensureArraySizeOkay ( minCapacity , "StringArray" ) ; //caller may know exact number needed, so don't double above 2x current size int newCapacity = ( int ) Math . min ( Integer . MAX_VALUE - 1 , array . length + ( long ) array . length ) ; if ( newCapacity < minCapacity ) newCapacity = ( int ) minCapacity ; //safe since checked above String [ ] newArray = new String [ newCapacity ] ; System . arraycopy ( array , 0 , newArray , 0 , size ) ; array = newArray ; //do last to minimize concurrency problems } }


Input: This gets a specified element . [CODESPLIT] public String get ( int index ) { if ( index >= size ) throw new IllegalArgumentException ( ErddapString2 . ERROR + " in StringArray.get: index (" + index + ") >= size (" + size + ")." ) ; return array [ index ] ; }


Input:
/ * [CODESPLIT] public void augmentDataset ( NetcdfDataset ds , CancelTask cancelTask ) throws IOException { final Attribute levelAtt = ds . findAttribute ( "/HDFEOS/ADDITIONAL/FILE_ATTRIBUTES/@ProcessLevel" ) ; if ( levelAtt == null ) { return ; } final int level = levelAtt . getStringValue ( ) . startsWith ( "2" ) ? 2 : 3 ; //Attribute time = ds.findAttribute("/HDFEOS/ADDITIONAL/FILE_ATTRIBUTES/@TAI93At0zOfGranule");
 if ( level == 3 ) { augmentDataset3 ( ds ) ; } }


Input:
Transform a real longitude and latitude into the rotated longitude ( X ) and rotated latitude ( Y ) . [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl destPoint ) { double lat = latlon . getLatitude ( ) ; double lon = latlon . getLongitude ( ) ; //	Lon-lat pair to xyz coordinates on sphere with radius 1
 double [ ] p0 = new double [ ] { Math . cos ( lat * RAD_PER_DEG ) * Math . cos ( lon * RAD_PER_DEG ) , Math . cos ( lat * RAD_PER_DEG ) * Math . sin ( lon * RAD_PER_DEG ) , Math . sin ( lat * RAD_PER_DEG ) } ; //	Rotate around Z-axis
 double [ ] p1 = new double [ ] { rotZ [ 0 ] [ 0 ] * p0 [ 0 ] + rotZ [ 0 ] [ 1 ] * p0 [ 1 ] + rotZ [ 0 ] [ 2 ] * p0 [ 2 ] , rotZ [ 1 ] [ 0 ] * p0 [ 0 ] + rotZ [ 1 ] [ 1 ] * p0 [ 1 ] + rotZ [ 1 ] [ 2 ] * p0 [ 2 ] , rotZ [ 2 ] [ 0 ] * p0 [ 0 ] + rotZ [ 2 ] [ 1 ] * p0 [ 1 ] + rotZ [ 2 ] [ 2 ] * p0 [ 2 ] } ; //	Rotate around Y-axis
 double [ ] p2 = new double [ ] { rotY [ 0 ] [ 0 ] * p1 [ 0 ] + rotY [ 0 ] [ 1 ] * p1 [ 1 ] + rotY [ 0 ] [ 2 ] * p1 [ 2 ] , rotY [ 1 ] [ 0 ] * p1 [ 0 ] + rotY [ 1 ] [ 1 ] * p1 [ 1 ] + rotY [ 1 ] [ 2 ] * p1 [ 2 ] , rotY [ 2 ] [ 0 ] * p1 [ 0 ] + rotY [ 2 ] [ 1 ] * p1 [ 1 ] + rotY [ 2 ] [ 2 ] * p1 [ 2 ] } ; final double lonR = LatLonPointImpl . range180 ( Math . atan2 ( p2 [ 1 ] , p2 [ 0 ] ) * DEG_PER_RAD ) ; //final double lonR = Math.atan2(p2[1], p2[0]) * DEG_PER_RAD;
 final double latR = Math . asin ( p2 [ 2 ] ) * DEG_PER_RAD ; if ( destPoint == null ) destPoint = new ProjectionPointImpl ( lonR , latR ) ; else destPoint . setLocation ( lonR , latR ) ; if ( show ) System . out . println ( "LatLon= " + latlon + " proj= " + destPoint ) ; return destPoint ; }


Input:
Transform a rotated longitude ( X ) and rotated latitude ( Y ) into a real longitude - latitude pair . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint ppt , LatLonPointImpl destPoint ) { //	"x" and "y" input for rotated pole coords are actually a lon-lat pair
 final double lonR = LatLonPointImpl . range180 ( ppt . getX ( ) ) ; // LOOK guessing
 final double latR = ppt . getY ( ) ; //	Lon-lat pair to xyz coordinates on sphere with radius 1
 double [ ] p0 = new double [ ] { Math . cos ( latR * RAD_PER_DEG ) * Math . cos ( lonR * RAD_PER_DEG ) , Math . cos ( latR * RAD_PER_DEG ) * Math . sin ( lonR * RAD_PER_DEG ) , Math . sin ( latR * RAD_PER_DEG ) } ; //	Inverse rotate around Y-axis (using transpose of Y matrix)
 double [ ] p1 = new double [ ] { rotY [ 0 ] [ 0 ] * p0 [ 0 ] + rotY [ 1 ] [ 0 ] * p0 [ 1 ] + rotY [ 2 ] [ 0 ] * p0 [ 2 ] , rotY [ 0 ] [ 1 ] * p0 [ 0 ] + rotY [ 1 ] [ 1 ] * p0 [ 1 ] + rotY [ 2 ] [ 1 ] * p0 [ 2 ] , rotY [ 0 ] [ 2 ] * p0 [ 0 ] + rotY [ 1 ] [ 2 ] * p0 [ 1 ] + rotY [ 2 ] [ 2 ] * p0 [ 2 ] } ; //	Inverse rotate around Z-axis (using transpose of Z matrix)
 double [ ] p2 = new double [ ] { rotZ [ 0 ] [ 0 ] * p1 [ 0 ] + rotZ [ 1 ] [ 0 ] * p1 [ 1 ] + rotZ [ 2 ] [ 0 ] * p1 [ 2 ] , rotZ [ 0 ] [ 1 ] * p1 [ 0 ] + rotZ [ 1 ] [ 1 ] * p1 [ 1 ] + rotZ [ 2 ] [ 1 ] * p1 [ 2 ] , rotZ [ 0 ] [ 2 ] * p1 [ 0 ] + rotZ [ 1 ] [ 2 ] * p1 [ 1 ] + rotZ [ 2 ] [ 2 ] * p1 [ 2 ] } ; final double lon = Math . atan2 ( p2 [ 1 ] , p2 [ 0 ] ) * DEG_PER_RAD ; final double lat = Math . asin ( p2 [ 2 ] ) * DEG_PER_RAD ; if ( destPoint == null ) destPoint = new LatLonPointImpl ( lat , lon ) ; else destPoint . set ( lat , lon ) ; if ( show ) System . out . println ( "Proj= " + ppt + " latlon= " + destPoint ) ; return destPoint ; }


Input: Resets the location being scanned ( DO NOT USE THIS METHOD public by accident ) . [CODESPLIT] public void setScanLocation ( String scanLocation ) { // ToDo LOOK Instead hand InvDatasetScan (or InvCatFactory?) an algorithm for converting an aliased location. if ( ! scanLocation . equals ( this . scanLocation ) ) { this . isValid = true ; this . scanLocation = scanLocation ; this . scanLocationCrDs = createScanLocationCrDs ( ) ; if ( this . scanLocationCrDs == null ) { isValid = false ; invalidMessage = new StringBuilder ( "Invalid InvDatasetScan <path=" ) . append ( rootPath ) . append ( "; scanLocation=" ) . append ( scanLocation ) . append ( ">: could not create CrawlableDataset for scanLocation." ) ; } else if ( ! this . scanLocationCrDs . exists ( ) ) { isValid = false ; invalidMessage = new StringBuilder ( "Invalid InvDatasetScan <path=" ) . append ( rootPath ) . append ( "; scanLocation=" ) . append ( scanLocation ) . append ( ">: CrawlableDataset for scanLocation does not exist." ) ; } else if ( ! this . scanLocationCrDs . isCollection ( ) ) { isValid = false ; invalidMessage = new StringBuilder ( "Invalid InvDatasetScan <path=" ) . append ( rootPath ) . append ( "; scanLocation=" ) . append ( scanLocation ) . append ( ">: CrawlableDataset for scanLocation not a collection." ) ; } } }


Input: Return the CrawlableDataset path / location that corresponds to the given dataset path . The given dataset path must start with the datasetScan path for this InvDatasetScan if not a null is returned . [CODESPLIT] public String translatePathToLocation ( String dsPath ) { if ( dsPath == null ) return null ; if ( dsPath . length ( ) > 0 ) if ( dsPath . startsWith ( "/" ) ) dsPath = dsPath . substring ( 1 ) ; if ( ! dsPath . startsWith ( this . getPath ( ) ) ) return null ; // remove the matching part, the rest is the "data directory" String dataDir = dsPath . substring ( this . getPath ( ) . length ( ) ) ; if ( dataDir . startsWith ( "/" ) ) dataDir = dataDir . substring ( 1 ) ; CrawlableDataset curCrDs = scanLocationCrDs . getDescendant ( dataDir ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "translatePathToLocation(): url dsPath= " + dsPath + " to dataset dsPath= " + curCrDs . getPath ( ) ) ; return curCrDs . getPath ( ) ; }


Input: Return the CrawlableDataset for the given path null if this InvDatasetScan does not allow ( filters out ) the requested CrawlableDataset . [CODESPLIT] public CrawlableDataset requestCrawlableDataset ( String path ) throws IOException { String crDsPath = translatePathToLocation ( path ) ; if ( crDsPath == null ) return null ; CatalogBuilder catBuilder = buildCatalogBuilder ( ) ; if ( catBuilder == null ) return null ; return catBuilder . requestCrawlableDataset ( crDsPath ) ; }


Input: Try to build a catalog for the given path by scanning the location associated with this InvDatasetScan . The given path must start with the path of this InvDatasetScan . [CODESPLIT] public InvCatalogImpl makeCatalogForDirectory ( String orgPath , URI catURI ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "baseURI=" + catURI ) ; log . debug ( "orgPath=" + orgPath ) ; log . debug ( "rootPath=" + rootPath ) ; log . debug ( "scanLocation=" + scanLocation ) ; } // Get the dataset path. String dsDirPath = translatePathToLocation ( orgPath ) ; if ( dsDirPath == null ) { String tmpMsg = "makeCatalogForDirectory(): Requesting path <" + orgPath + "> must start with \"" + rootPath + "\"." ; log . error ( tmpMsg ) ; return null ; } // Setup and create catalog builder. CatalogBuilder catBuilder = buildCatalogBuilder ( ) ; if ( catBuilder == null ) return null ; // A very round about way to remove the filename (e.g., "catalog.xml"). // Note: Gets around "path separator at end of path" issues that are CrDs implementation dependant. // Note: Does not check that CrDs is allowed by filters. String dsPath = dsDirPath . substring ( scanLocationCrDs . getPath ( ) . length ( ) ) ; if ( dsPath . startsWith ( "/" ) ) dsPath = dsPath . substring ( 1 ) ; CrawlableDataset reqCrDs = scanLocationCrDs . getDescendant ( dsPath ) ; CrawlableDataset parent = reqCrDs . getParentDataset ( ) ; if ( parent == null ) { log . error ( "makeCatalogForDirectory(): I/O error getting parent crDs level <" + dsDirPath + ">: " ) ; return null ; } dsDirPath = parent . getPath ( ) ; // Get the CrawlableDataset for the desired catalog level (checks that allowed by filters). CrawlableDataset catalogCrDs ; try { catalogCrDs = catBuilder . requestCrawlableDataset ( dsDirPath ) ; } catch ( IOException e ) { log . error ( "makeCatalogForDirectory(): I/O error getting catalog level <" + dsDirPath + ">: " + e . getMessage ( ) , e ) ; return null ; } if ( catalogCrDs == null ) { log . warn ( "makeCatalogForDirectory(): requested catalog level <" + dsDirPath + "> not allowed (filtered out)." ) ; return null ; } if ( ! catalogCrDs . isCollection ( ) ) { log . warn ( "makeCatalogForDirectory(): requested catalog level <" + dsDirPath + "> is not a collection." ) ; return null ; } // Generate the desired catalog using the builder. InvCatalogImpl catalog ; try { catalog = catBuilder . generateCatalog ( catalogCrDs ) ; } catch ( IOException e ) { log . error ( "makeCatalogForDirectory(): catalog generation failed <" + catalogCrDs . getPath ( ) + ">: " + e . getMessage ( ) ) ; return null ; } // Set the catalog base URI. if ( catalog != null ) catalog . setBaseURI ( catURI ) ; //    InvDatasetImpl top = (InvDatasetImpl) catalog.getDataset(); //    // if we name it carefully, can get catalogRef to useProxy == true (disappear top dataset) //    if ( service.isRelativeBase()) { //      pos = dataDir.lastIndexOf("/"); //      String lastDir = (pos > 0) ? dataDir.substring(pos+1) : dataDir; //      String topName = lastDir.length() > 0 ? lastDir : getName(); //      top.setName( topName); //    } return catalog ; }


Input: Try to build a catalog for the given resolver path by scanning the location associated with this InvDatasetScan . The given path must start with the path of this InvDatasetScan and refer to a resolver ProxyDatasetHandler that is part of this InvDatasetScan . [CODESPLIT] public InvCatalogImpl makeProxyDsResolverCatalog ( String path , URI baseURI ) { if ( path == null ) return null ; if ( path . endsWith ( "/" ) ) return null ; // Get the dataset path. String dsDirPath = translatePathToLocation ( path ) ; if ( dsDirPath == null ) { log . error ( "makeProxyDsResolverCatalog(): Requesting path <" + path + "> must start with \"" + rootPath + "\"." ) ; return null ; } // Split into parent path and dataset name. int pos = dsDirPath . lastIndexOf ( ' ' ) ; if ( pos == - 1 ) { log . error ( "makeProxyDsResolverCatalog(): Requesting path <" + path + "> must contain a slash (\"/\")." ) ; return null ; } String dsName = dsDirPath . substring ( pos + 1 ) ; dsDirPath = dsDirPath . substring ( 0 , pos ) ; // Find matching ProxyDatasetHandler. ProxyDatasetHandler pdh = this . getProxyDatasetHandlers ( ) . get ( dsName ) ; if ( pdh == null ) { log . error ( "makeProxyDsResolverCatalog(): No matching proxy dataset handler found <" + dsName + ">." ) ; return null ; } // Setup and create catalog builder. CatalogBuilder catBuilder = buildCatalogBuilder ( ) ; if ( catBuilder == null ) return null ; // Get the CrawlableDataset for the desired catalog level. CrawlableDataset catalogCrDs ; try { catalogCrDs = catBuilder . requestCrawlableDataset ( dsDirPath ) ; } catch ( IOException e ) { log . error ( "makeProxyDsResolverCatalog(): failed to create CrawlableDataset for catalogLevel <" + dsDirPath + "> and class <" + crDsClassName + ">: " + e . getMessage ( ) , e ) ; return null ; } if ( catalogCrDs == null ) { log . warn ( "makeProxyDsResolverCatalog(): requested catalog level <" + dsDirPath + "> not allowed (filtered out)." ) ; return null ; } if ( ! catalogCrDs . isCollection ( ) ) { log . warn ( "makeProxyDsResolverCatalog(): requested catalog level <" + dsDirPath + "> not a collection." ) ; return null ; } // Generate the desired catalog using the builder. InvCatalogImpl catalog ; try { catalog = ( InvCatalogImpl ) catBuilder . generateProxyDsResolverCatalog ( catalogCrDs , pdh ) ; } catch ( IOException e ) { log . error ( "makeProxyDsResolverCatalog(): catalog generation failed <" + catalogCrDs . getPath ( ) + ">: " + e . getMessage ( ) ) ; return null ; } // Set the catalog base URI. if ( catalog != null ) catalog . setBaseURI ( baseURI ) ; return catalog ; }


Input: What is the data type of the aggregation coordinate ? [CODESPLIT] private DataType getCoordinateType ( ) { List < Dataset > nestedDatasets = getDatasets ( ) ; DatasetOuterDimension first = ( DatasetOuterDimension ) nestedDatasets . get ( 0 ) ; return first . isStringValued ? DataType . STRING : DataType . DOUBLE ; }


Input: Factory for Grib2Pds [CODESPLIT] @ Nullable public static Grib2Pds factory ( int template , byte [ ] input ) { switch ( template ) { case 0 : return new Grib2Pds0 ( input ) ; case 1 : return new Grib2Pds1 ( input ) ; case 2 : return new Grib2Pds2 ( input ) ; case 5 : return new Grib2Pds5 ( input ) ; case 6 : return new Grib2Pds6 ( input ) ; case 8 : return new Grib2Pds8 ( input ) ; case 9 : return new Grib2Pds9 ( input ) ; case 10 : return new Grib2Pds10 ( input ) ; case 11 : return new Grib2Pds11 ( input ) ; case 12 : return new Grib2Pds12 ( input ) ; case 15 : return new Grib2Pds15 ( input ) ; case 30 : return new Grib2Pds30 ( input ) ; case 31 : return new Grib2Pds31 ( input ) ; case 48 : return new Grib2Pds48 ( input ) ; case 61 : return new Grib2Pds61 ( input ) ; default : log . warn ( "Missing template " + template ) ; return null ; } }


Input: / * public double getProbabilityLowerLimit () { return GribNumbers . UNDEFINED ; } [CODESPLIT] public void show ( Formatter f ) { f . format ( "Grib2Pds{ id=%d-%d template=%d, forecastTime= %d timeUnit=%s vertLevel=%f}" , getParameterCategory ( ) , getParameterNumber ( ) , template , getForecastTime ( ) , getTimeUnit ( ) , getLevelValue1 ( ) ) ; }


Input:
null means use refTime [CODESPLIT] protected CalendarDate calcTime ( int startIndex ) { int year = GribNumbers . int2 ( getOctet ( startIndex ++ ) , getOctet ( startIndex ++ ) ) ; int month = getOctet ( startIndex ++ ) ; int day = getOctet ( startIndex ++ ) ; int hour = getOctet ( startIndex ++ ) ; int minute = getOctet ( startIndex ++ ) ; int second = getOctet ( startIndex ++ ) ; if ( ( year == 0 ) && ( month == 0 ) && ( day == 0 ) && ( hour == 0 ) && ( minute == 0 ) && ( second == 0 ) ) return CalendarDate . UNKNOWN ; // href.t00z.prob.f36.grib2
 if ( hour > 23 ) { day += ( hour / 24 ) ; hour = hour % 24 ; } return CalendarDate . of ( null , year , month , day , hour , minute , second ) ; }


Input: Apply scale factor to value return a double result . [CODESPLIT] double applyScaleFactor ( int scale , int value ) { return ( ( scale == 0 ) || ( scale == 255 ) || ( value == 0 ) ) ? value : value * Math . pow ( 10 , - scale ) ; }