Input: Converts the raw position to a position within the wheel item bounds . [CODESPLIT] public int rawPositionToWheelPosition ( int position , int adapterPosition ) { int circularOffset = mIsRepeatable ? ( ( int ) Math . floor ( ( position / ( float ) mAdapterItemCount ) ) * ( mAdapterItemCount - mItemCount ) ) : 0 ; return Circle . clamp ( adapterPosition + circularOffset , mItemCount ) ; }


Input: Estimates the wheel s new angle and angular velocity [CODESPLIT] private void update ( float deltaTime ) { float vel = mAngularVelocity ; float velSqr = vel * vel ; if ( vel > 0f ) { //TODO the damping is not based on time mAngularVelocity -= velSqr * VELOCITY_FRICTION_COEFFICIENT + CONSTANT_FRICTION_COEFFICIENT ; if ( mAngularVelocity < 0f ) mAngularVelocity = 0f ; } else if ( vel < 0f ) { mAngularVelocity -= velSqr * - VELOCITY_FRICTION_COEFFICIENT - CONSTANT_FRICTION_COEFFICIENT ; if ( mAngularVelocity > 0f ) mAngularVelocity = 0f ; } if ( mAngularVelocity != 0f ) { addAngle ( mAngularVelocity * deltaTime ) ; } else { mRequiresUpdate = false ; } }


Input: get the materials darker contrast [CODESPLIT] private int getContrastColor ( Map . Entry < String , Integer > entry ) { String colorName = MaterialColor . getColorName ( entry ) ; return MaterialColor . getContrastColor ( colorName ) ; }


Input: Clamps the value to a number between 0 and the upperLimit [CODESPLIT] static int clamp ( int value , int upperLimit ) { if ( value < 0 ) { return value + ( - 1 * ( int ) Math . floor ( value / ( float ) upperLimit ) ) * upperLimit ; } else { return value % upperLimit ; } }


Input: Matches text against a wildcard pattern where ? is single letter and * is zero or more letters . [CODESPLIT] public static boolean matches ( final String text , final String wildcard ) { String pattern = wildcard . replace ( "?" , "\\w" ) . replace ( "*" , "\\w*" ) ; return ( text != null && text . matches ( pattern ) ) ; }


Input: @return source loader that extracts source files [CODESPLIT] protected SourceLoader createSourceLoader ( final Job job ) { return new SourceLoaderFactory ( job . getGit ( ) . getBaseDir ( ) , project , sourceEncoding ) . withSourceDirectories ( sourceDirectories ) . withScanForSources ( scanForSources ) . createSourceLoader ( ) ; }


Input: Writes coverage data to JSON file . [CODESPLIT] protected void writeCoveralls ( final JsonWriter writer , final SourceCallback sourceCallback , final List < CoverageParser > parsers ) throws ProcessingException , IOException { try { getLog ( ) . info ( "Writing Coveralls data to " + writer . getCoverallsFile ( ) . getAbsolutePath ( ) + "..." ) ; long now = System . currentTimeMillis ( ) ; sourceCallback . onBegin ( ) ; for ( CoverageParser parser : parsers ) { getLog ( ) . info ( "Processing coverage report from " + parser . getCoverageFile ( ) . getAbsolutePath ( ) ) ; parser . parse ( sourceCallback ) ; } sourceCallback . onComplete ( ) ; long duration = System . currentTimeMillis ( ) - now ; getLog ( ) . info ( "Successfully wrote Coveralls data in " + duration + "ms" ) ; } finally { writer . close ( ) ; } }


Input: / * create new ArrayChar with given indexImpl and backing store . Should be private . [CODESPLIT] static ArrayChar factory ( Index index , char [ ] storage ) { if ( index instanceof Index0D ) { return new ArrayChar . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayChar . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayChar . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayChar . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayChar . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayChar . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayChar . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayChar . D7 ( index , storage ) ; } else { return new ArrayChar ( index , storage ) ; } }


Input: copy from javaArray to storage using the iterator : used by factory ( Object ) ; [CODESPLIT] protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { char [ ] ja = ( char [ ] ) javaArray ; for ( char aJa : ja ) iter . setCharNext ( aJa ) ; }


Input: Trasfer data to a ByteBuffer . Note we cast char to byte discarding top byte if any . This is because CDM char is really a byte not a java char . [CODESPLIT] @ Override public ByteBuffer getDataAsByteBuffer ( ) { ByteBuffer bb = ByteBuffer . allocate ( ( int ) getSize ( ) ) ; resetLocalIterator ( ) ; while ( hasNext ( ) ) bb . put ( nextByte ( ) ) ; return bb ; }


Input: Create a String out of this rank one ArrayChar object . If there is a null ( 0 ) value in the ArrayChar array the String will end there . The null is not returned as part of the String . [CODESPLIT] public String getString ( ) { int rank = getRank ( ) ; if ( rank == 0 ) { return new String ( storage ) ; } if ( rank != 1 ) throw new IllegalArgumentException ( "ArayChar.getString rank must be 1" ) ; int strLen = indexCalc . getShape ( 0 ) ; int count = 0 ; for ( int k = 0 ; k < strLen ; k ++ ) { if ( 0 == storage [ k ] ) break ; count ++ ; } return new String ( storage , 0 , count ) ; }


Input: Create a String out of this rank two ArrayChar object . This treats the ArrayChar as a 1D array of Strings . If there is a null ( 0 ) value in the ArrayChar array the String will end there . The null is not returned as part of the String . [CODESPLIT] public String getString ( int index ) { Index ima = getIndex ( ) ; return getString ( ima . set ( index ) ) ; }


Input: Create a String out of this ArrayChar object . The rank must be 1 or greater . If there is a null ( 0 ) value in the ArrayChar array the String will end there . The null is not returned as part of the String . <p / > If rank = 1 then this will make a string out of the entire CharArray ignoring ima . If rank is greater than 1 then make a String out of the characters of the last dimension indexed by ima . This method treats the CharArray like an array of Strings and allows you to iterate over them eg for a 2D ArrayChar : <p > <code > ArrayChar ca ; Index ima = ca . getIndex () ; for ( int i = 0 ; i<ca . getShape () [ 0 ] ; i ++ ) String s = ca . getString ( ima . set0 ( i )) ; < / code > [CODESPLIT] public String getString ( Index ima ) { int rank = getRank ( ) ; if ( rank == 0 ) throw new IllegalArgumentException ( "ArayChar.getString rank must not be 0" ) ; if ( rank == 1 ) return getString ( ) ; int strLen = indexCalc . getShape ( rank - 1 ) ; char [ ] carray = new char [ strLen ] ; int count = 0 ; for ( int k = 0 ; k < strLen ; k ++ ) { ima . setDim ( rank - 1 , k ) ; carray [ k ] = getChar ( ima ) ; if ( 0 == carray [ k ] ) break ; count ++ ; } return new String ( carray , 0 , count ) ; }


Input: Set the ArrayChar values from the characters in the String . Rank must be 1 . If String longer than ArrayChar ignore extra chars ; if shorter fill with 0 . [CODESPLIT] public void setString ( String val ) { int rank = getRank ( ) ; if ( rank != 1 ) throw new IllegalArgumentException ( "ArayChar.setString rank must be 1" ) ; int arrayLen = indexCalc . getShape ( 0 ) ; int strLen = Math . min ( val . length ( ) , arrayLen ) ; for ( int k = 0 ; k < strLen ; k ++ ) storage [ k ] = val . charAt ( k ) ; char c = 0 ; for ( int k = strLen ; k < arrayLen ; k ++ ) storage [ k ] = ; }


Input: Set the ArrayChar values from the characters in the String . Rank must be 2 . This treats the ArrayChar as a 1D array of Strings . If String val longer than ArrayChar ignore extra chars ; if shorter fill with 0 . <p / > <p > <code > String [] val = new String [ n ] ; ArrayChar ca ; Index ima = ca . getIndex () ; for ( int i = 0 ; i<n ; i ++ ) ca . setString ( i val [ i ] ) ; < / code > [CODESPLIT] public void setString ( int index , String val ) { int rank = getRank ( ) ; if ( rank != 2 ) throw new IllegalArgumentException ( "ArrayChar.setString rank must be 2" ) ; Index ima = getIndex ( ) ; setString ( ima . set ( index ) , val ) ; }


Input: Set the ArrayChar values from the characters in the String . Rank must be 1 or greater . If String longer than ArrayChar ignore extra chars ; if shorter fill with 0 . If rank 1 set entire ArrayChar ignoring ima . If rank > 1 treat the ArrayChar like an array of Strings of rank - 1 and set the row indexed by ima . For example rank 3 : <p > <code > String [] [] val ; ArrayChar ca ; Index ima = ca . getIndex () ; int rank0 = ca . getShape () [ 0 ] ; int rank1 = ca . getShape () [ 1 ] ; <p / > for ( int i = 0 ; i<rank0 ; i ++ ) for ( int j = 0 ; j<rank1 ; j ++ ) { ima . set ( i j ) ; ca . setString ( ima val [ i ] [ j ] ) ; } < / code > [CODESPLIT] public void setString ( Index ima , String val ) { int rank = getRank ( ) ; if ( rank == 0 ) throw new IllegalArgumentException ( "ArrayChar.setString rank must not be 0" ) ; int arrayLen = indexCalc . getShape ( rank - 1 ) ; int strLen = Math . min ( val . length ( ) , arrayLen ) ; int count = 0 ; for ( int k = 0 ; k < strLen ; k ++ ) { ima . setDim ( rank - 1 , k ) ; setChar ( ima , val . charAt ( k ) ) ; count ++ ; } char c = 0 ; for ( int k = count ; k < arrayLen ; k ++ ) { ima . setDim ( rank - 1 , k ) ; setChar ( ima , c ) ; } }


Input: Make this into the equivilent 1D ArrayObject of Strings . [CODESPLIT] public ArrayObject make1DStringArray ( ) { int nelems = ( getRank ( ) == 0 ) ? 1 : ( int ) getSize ( ) / indexCalc . getShape ( getRank ( ) - 1 ) ; Array sarr = Array . factory ( DataType . STRING , new int [ ] { nelems } ) ; IndexIterator newsiter = sarr . getIndexIterator ( ) ; ArrayChar . StringIterator siter = getStringIterator ( ) ; while ( siter . hasNext ( ) ) { newsiter . setObjectNext ( siter . next ( ) ) ; } return ( ArrayObject ) sarr ; }


Input: Create an ArrayChar from a String [CODESPLIT] public static ArrayChar makeFromString ( String s , int max ) { ArrayChar result = new ArrayChar . D1 ( max ) ; for ( int i = 0 ; i < max && i < s . length ( ) ; i ++ ) result . setChar ( i , s . charAt ( i ) ) ; return result ; }


Input:
Create an ArrayChar from an ArrayObject of Strings . [CODESPLIT] public static ArrayChar makeFromStringArray ( ArrayObject values ) { // find longest string
 IndexIterator ii = values . getIndexIterator ( ) ; int strlen = 0 ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . next ( ) ; strlen = Math . max ( s . length ( ) , strlen ) ; } return makeFromStringArray ( values , strlen ) ; }


Input:
Create an ArrayChar from an ArrayObject of Strings . Inverse of make1DStringArray . Copies the data . [CODESPLIT] public static ArrayChar makeFromStringArray ( ArrayObject values , int strlen ) { // create shape for equivilent charArray
 try { Section section = new Section ( values . getShape ( ) ) ; section . appendRange ( strlen ) ; int [ ] shape = section . getShape ( ) ; long size = section . computeSize ( ) ; // populate char array
 char [ ] cdata = new char [ ( int ) size ] ; int start = 0 ; IndexIterator ii = values . getIndexIterator ( ) ; while ( ii . hasNext ( ) ) { String s = ( String ) ii . next ( ) ; for ( int k = 0 ; k < s . length ( ) && k < strlen ; k ++ ) cdata [ start + k ] = s . charAt ( k ) ; start += strlen ; } // ready to create the char Array
 Array carr = Array . factory ( DataType . CHAR , shape , cdata ) ; return ( ArrayChar ) carr ; } catch ( InvalidRangeException e ) { e . printStackTrace ( ) ; // cant happen.
 return null ; } }


Input: Dot product of matrix and vector : return M dot v [CODESPLIT] public MAVector dot ( MAVector v ) { if ( ncols != v . getNelems ( ) ) throw new IllegalArgumentException ( "MAMatrix.dot " + ncols + " != " + v . getNelems ( ) ) ; ArrayDouble . D1 result = new ArrayDouble . D1 ( nrows ) ; Index imr = result . getIndex ( ) ; for ( int i = 0 ; i < nrows ; i ++ ) { double sum = 0.0 ; for ( int k = 0 ; k < ncols ; k ++ ) sum += getDouble ( i , k ) * v . getDouble ( k ) ; result . setDouble ( imr . set ( i ) , sum ) ; } return new MAVector ( result ) ; }


Input: Matrix multiply : return m1 * m2 . [CODESPLIT] static public MAMatrix multiply ( MAMatrix m1 , MAMatrix m2 ) { if ( m1 . getNcols ( ) != m2 . getNrows ( ) ) throw new IllegalArgumentException ( "MAMatrix.multiply " + m1 . getNcols ( ) + " != " + m2 . getNrows ( ) ) ; int kdims = m1 . getNcols ( ) ; ArrayDouble . D2 result = new ArrayDouble . D2 ( m1 . getNrows ( ) , m2 . getNcols ( ) ) ; Index imr = result . getIndex ( ) ; for ( int i = 0 ; i < m1 . getNrows ( ) ; i ++ ) { for ( int j = 0 ; j < m2 . getNcols ( ) ; j ++ ) { double sum = 0.0 ; for ( int k = 0 ; k < kdims ; k ++ ) sum += m1 . getDouble ( i , k ) * m2 . getDouble ( k , j ) ; result . setDouble ( imr . set ( i , j ) , sum ) ; } } return new MAMatrix ( result ) ; }


Input: Matrix multiply by a diagonal matrix store result in this : this = this * diag [CODESPLIT] public void postMultiplyDiagonal ( MAVector diag ) { if ( ncols != diag . getNelems ( ) ) throw new IllegalArgumentException ( "MAMatrix.postMultiplyDiagonal " + ncols + " != " + diag . getNelems ( ) ) ; for ( int i = 0 ; i < nrows ; i ++ ) { for ( int j = 0 ; j < ncols ; j ++ ) { double val = a . getDouble ( ima . set ( i , j ) ) * diag . getDouble ( j ) ; a . setDouble ( ima , val ) ; } } }


Input: Reference time is the start time of the first forecast other forecasts at 6 - hour intervals . Number in Ave = number of forecast used [CODESPLIT] @ Override public int [ ] getForecastTimeIntervalOffset ( Grib2Record gr ) { Grib2Pds pds = gr . getPDS ( ) ; if ( ! pds . isTimeInterval ( ) ) { return null ; } // LOOK this is hack for CFSR monthly combobulation // see http://rda.ucar.edu/datasets/ds093.2/#docs/time_ranges.html int statType = pds . getOctet ( 47 ) ; int n = pds . getInt4StartingAtOctet ( 50 ) ; int p2 = pds . getInt4StartingAtOctet ( 55 ) ; int p2mp1 = pds . getInt4StartingAtOctet ( 62 ) ; int p1 = p2 - p2mp1 ; int start , end ; switch ( statType ) { case 193 : start = p1 ; end = p1 + n * p2 ; break ; case 194 : start = 0 ; end = n * p2 ; break ; case 195 : case 204 : case 205 : start = p1 ; end = p2 ; break ; default : throw new IllegalArgumentException ( "unknown statType " + statType ) ; } return new int [ ] { start , end } ; }


Input: see http : // www . nco . ncep . noaa . gov / pmb / docs / grib2 / grib2_doc . shtml [CODESPLIT] private void initLocalTable ( ) { String tableName = config . getPath ( ) ; ClassLoader cl = this . getClass ( ) . getClassLoader ( ) ; try ( InputStream is = cl . getResourceAsStream ( tableName ) ) { if ( is == null ) { throw new IllegalStateException ( "Cant find " + tableName ) ; } try ( BufferedReader br = new BufferedReader ( new InputStreamReader ( is , CDM . utf8Charset ) ) ) { while ( true ) { String line = br . readLine ( ) ; if ( line == null ) { break ; } if ( ( line . length ( ) == 0 ) || line . startsWith ( "#" ) ) { continue ; } String [ ] flds = StringUtil2 . splitString ( line ) ; int p1 = Integer . parseInt ( flds [ 0 ] . trim ( ) ) ; // must have a number int p2 = Integer . parseInt ( flds [ 1 ] . trim ( ) ) ; // must have a number int p3 = Integer . parseInt ( flds [ 2 ] . trim ( ) ) ; // must have a number StringBuilder b = new StringBuilder ( ) ; int count = 3 ; while ( count < flds . length && ! flds [ count ] . equals ( "." ) ) { b . append ( flds [ count ++ ] ) . append ( ' ' ) ; } String abbrev = b . toString ( ) . trim ( ) ; b . setLength ( 0 ) ; count ++ ; while ( count < flds . length && ! flds [ count ] . equals ( "." ) ) { b . append ( flds [ count ++ ] ) . append ( ' ' ) ; } String name = b . toString ( ) . trim ( ) ; b . setLength ( 0 ) ; count ++ ; while ( count < flds . length && ! flds [ count ] . equals ( "." ) ) { b . append ( flds [ count ++ ] ) . append ( ' ' ) ; } String unit = b . toString ( ) . trim ( ) ; Grib2Parameter s = new Grib2Parameter ( p1 , p2 , p3 , name , unit , abbrev , null ) ; local . put ( makeParamId ( p1 , p2 , p3 ) , s ) ; } } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } }


Input:
Overrides the GisFeatureRenderer draw () method to draw contours and with contour labels . [CODESPLIT] public void draw ( java . awt . Graphics2D g , AffineTransform deviceFromNormalAT ) { /* OLD WAY
  // make & set desired font for contour label.
  // contour label size in "points" is last arg
  Font font1 = new Font("Helvetica", Font.PLAIN, 25);
  // make a transform to un-flip the font
  AffineTransform unflip = AffineTransform.getScaleInstance(1, -1);
  Font font = font1.deriveFont(unflip);
  g.setFont(font);  */ /* from original GisFeatureRenderer method draw: */ g . setColor ( Color . black ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , RenderingHints . VALUE_ANTIALIAS_OFF ) ; g . setStroke ( new java . awt . BasicStroke ( 0.0f ) ) ; Rectangle2D clipRect = ( Rectangle2D ) g . getClip ( ) ; Iterator siter = getShapes ( g , deviceFromNormalAT ) ; // draw the contours while ( siter . hasNext ( ) ) { Shape s = ( Shape ) siter . next ( ) ; Rectangle2D shapeBounds = s . getBounds2D ( ) ; if ( shapeBounds . intersects ( clipRect ) ) g . draw ( s ) ; } // additional code beyond GisFeatureRenderer method draw(): // render contour value for this contour line. */ if ( ShowLabels ) { Font f = FontUtil . getStandardFont ( 10 ) . getFont ( ) ; Font saveFont = g . getFont ( ) ; // use world coordinates for position, but draw in "normal" coordinates // so that the symbols stay the same size AffineTransform deviceFromWorldAT = g . getTransform ( ) ; AffineTransform normalFromWorldAT ; // transform World to Normal coords: //    normalFromWorldAT = deviceFromNormalAT-1 * deviceFromWorldAT try { normalFromWorldAT = deviceFromNormalAT . createInverse ( ) ; normalFromWorldAT . concatenate ( deviceFromWorldAT ) ; } catch ( java . awt . geom . NoninvertibleTransformException e ) { System . out . println ( " ContourFeatureRenderer: NoninvertibleTransformException on " + deviceFromNormalAT ) ; return ; } g . setTransform ( deviceFromNormalAT ) ; // so g now wants "normal coords" g . setFont ( f ) ; siter = getShapes ( g , deviceFromNormalAT ) ; Iterator CViter = contourList . iterator ( ) ; Point2D worldPt = new Point2D . Double ( ) ; Point2D normalPt = new Point2D . Double ( ) ; float [ ] coords = new float [ 6 ] ; while ( siter . hasNext ( ) ) { Shape s = ( Shape ) siter . next ( ) ; double contValue = ( ( ContourFeature ) CViter . next ( ) ) . getContourValue ( ) ; // get position xpos,ypos on this contour where to put label // in current world coordinates in the current Shape s. PathIterator piter = s . getPathIterator ( null ) ; //int cs, count=-1;  original int cs , count = 12 ; while ( ! piter . isDone ( ) ) { count ++ ; if ( count % 25 == 0 ) { // for every 25th position on this path cs = piter . currentSegment ( coords ) ; if ( cs == PathIterator . SEG_MOVETO || cs == PathIterator . SEG_LINETO ) { worldPt . setLocation ( coords [ 0 ] , coords [ 1 ] ) ; normalFromWorldAT . transform ( worldPt , normalPt ) ; // convert to normal // render the contour value to the screen g . drawString ( Format . d ( contValue , 4 ) , ( int ) normalPt . getX ( ) , ( int ) normalPt . getY ( ) ) ; } } piter . next ( ) ; } // while not done } // end while shape.hasNext() // restore original transform and font g . setTransform ( deviceFromWorldAT ) ; g . setFont ( saveFont ) ; } // end if ShowLabels == true if ( Debug . isSet ( "contour/doLabels" ) ) { // get iterator to the class member ArrayList of GisFeature-s for ( Object aContourList : contourList ) { //ContourFeature cf = iter.next(); System . out . println ( " ContourFeatureRenderer: contour value = " + ( ( ContourFeature ) aContourList ) . getContourValue ( ) ) ; } } }


Input:
show the window . [CODESPLIT] public void show ( ) { setState ( Frame . NORMAL ) ; // deiconify if needed
 super . toFront ( ) ; // need to put on event thread
 SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { IndependentWindow . super . show ( ) ; } } ) ; }


Input:
show if not iconified [CODESPLIT] public void showIfNotIconified ( ) { if ( getState ( ) == Frame . ICONIFIED ) return ; // need to put on event thread
 SwingUtilities . invokeLater ( new Runnable ( ) { public void run ( ) { IndependentWindow . super . show ( ) ; } } ) ; }


Input: all the work is here so can be called recursively [CODESPLIT] private Array readData ( ucar . nc2 . Variable v2 , long dataPos , List < Range > ranges , int [ ] levels ) throws IOException , InvalidRangeException { // Get to the proper offset and read in the data raf . seek ( dataPos ) ; int data_size = ( int ) ( raf . length ( ) - dataPos ) ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; // Turn it into an array Array array = makeArray ( data , levels , v2 . getShape ( ) ) ; return array . sectionNoReduce ( ranges ) ; }


Input: for the compressed data read all out into a array and then parse into requested [CODESPLIT] private Array readCompressedData ( ucar . nc2 . Variable v2 , long dataPos , List < Range > ranges , int [ ] levels ) throws IOException , InvalidRangeException { // Get to the proper offset and read in the rest of the compressed data raf . seek ( dataPos ) ; int data_size = ( int ) ( raf . length ( ) - dataPos ) ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; // Send the compressed data to ImageIO (to handle PNG) ByteArrayInputStream ios = new ByteArrayInputStream ( data ) ; BufferedImage image = javax . imageio . ImageIO . read ( ios ) ; // LOOK why ImageIO ?? DataBuffer db = image . getData ( ) . getDataBuffer ( ) ; // If the image had byte data, turn into an array if ( db instanceof DataBufferByte ) { DataBufferByte dbb = ( DataBufferByte ) db ; Array array = makeArray ( dbb . getData ( ) , levels , v2 . getShape ( ) ) ; if ( levels == null ) v2 . setCachedData ( array , false ) ; return array . sectionNoReduce ( ranges ) ; } return null ; }


Input: Compute the size of the file without writing [CODESPLIT] static public long makeSizeEstimate ( ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , ProjectionRect projRect , int horizStride , Range zRange , CalendarDateRange dateRange , int stride_time , boolean addLatLon ) throws IOException , InvalidRangeException { CFGridWriter2 writer2 = new CFGridWriter2 ( ) ; return writer2 . writeOrTestSize ( gds , gridList , llbb , projRect , horizStride , zRange , dateRange , stride_time , addLatLon , true , null ) ; }


Input: Write a netcdf / CF file from a GridDataset [CODESPLIT] static public long writeFile ( ucar . nc2 . dt . GridDataset gds , List < String > gridList , LatLonRect llbb , ProjectionRect projRect , int horizStride , Range zRange , CalendarDateRange dateRange , int stride_time , boolean addLatLon , NetcdfFileWriter writer ) throws IOException , InvalidRangeException { CFGridWriter2 writer2 = new CFGridWriter2 ( ) ; return writer2 . writeOrTestSize ( gds , gridList , llbb , projRect , horizStride , zRange , dateRange , stride_time , addLatLon , false , writer ) ; }


Input:
Write equivilent uncompressed version of the file . [CODESPLIT] private RandomAccessFile uncompress ( RandomAccessFile inputRaf , String ufilename ) throws IOException { RandomAccessFile outputRaf = new RandomAccessFile ( ufilename , "rw" ) ; FileLock lock ; while ( true ) { // loop waiting for the lock try { lock = outputRaf . getRandomAccessFile ( ) . getChannel ( ) . lock ( 0 , 1 , false ) ; break ; } catch ( OverlappingFileLockException oe ) { // not sure why lock() doesnt block try { Thread . sleep ( 100 ) ; // msecs } catch ( InterruptedException e1 ) { } } catch ( IOException e ) { outputRaf . close ( ) ; throw e ; } } try { inputRaf . seek ( 0 ) ; byte [ ] header = new byte [ Level2Record . FILE_HEADER_SIZE ] ; int bytesRead = inputRaf . read ( header ) ; if ( bytesRead != header . length ) { throw new IOException ( "Error reading NEXRAD2 header -- got " + bytesRead + " rather than" + header . length ) ; } outputRaf . write ( header ) ; boolean eof = false ; int numCompBytes ; byte [ ] ubuff = new byte [ 40000 ] ; byte [ ] obuff = new byte [ 40000 ] ; CBZip2InputStream cbzip2 = new CBZip2InputStream ( ) ; while ( ! eof ) { try { numCompBytes = inputRaf . readInt ( ) ; if ( numCompBytes == - 1 ) { if ( log . isDebugEnabled ( ) ) log . debug ( "  done: numCompBytes=-1 " ) ; break ; } } catch ( EOFException ee ) { log . debug ( "got EOFException" ) ; break ; // assume this is ok } if ( log . isDebugEnabled ( ) ) { log . debug ( "reading compressed bytes " + numCompBytes + " input starts at " + inputRaf . getFilePointer ( ) + "; output starts at " + outputRaf . getFilePointer ( ) ) ; } /*
          * For some stupid reason, the last block seems to
          * have the number of bytes negated.  So, we just
          * assume that any negative number (other than -1)
          * is the last block and go on our merry little way.
          */ if ( numCompBytes < 0 ) { if ( log . isDebugEnabled ( ) ) log . debug ( "last block?" + numCompBytes ) ; numCompBytes = - numCompBytes ; eof = true ; } byte [ ] buf = new byte [ numCompBytes ] ; inputRaf . readFully ( buf ) ; ByteArrayInputStream bis = new ByteArrayInputStream ( buf , 2 , numCompBytes - 2 ) ; //CBZip2InputStream cbzip2 = new CBZip2InputStream(bis); cbzip2 . setStream ( bis ) ; int total = 0 ; int nread ; /*
          while ((nread = cbzip2.read(ubuff)) != -1) {
            dout2.write(ubuff, 0, nread);
            total += nread;
          }
          */ try { while ( ( nread = cbzip2 . read ( ubuff ) ) != - 1 ) { if ( total + nread > obuff . length ) { byte [ ] temp = obuff ; obuff = new byte [ temp . length * 2 ] ; System . arraycopy ( temp , 0 , obuff , 0 , temp . length ) ; } System . arraycopy ( ubuff , 0 , obuff , total , nread ) ; total += nread ; } if ( obuff . length >= 0 ) outputRaf . write ( obuff , 0 , total ) ; } catch ( BZip2ReadException ioe ) { log . warn ( "Nexrad2IOSP.uncompress " , ioe ) ; } float nrecords = ( float ) ( total / 2432.0 ) ; if ( log . isDebugEnabled ( ) ) log . debug ( "  unpacked " + total + " num bytes " + nrecords + " records; ouput ends at " + outputRaf . getFilePointer ( ) ) ; } outputRaf . flush ( ) ; } catch ( IOException e ) { if ( outputRaf != null ) outputRaf . close ( ) ; // dont leave bad files around File ufile = new File ( ufilename ) ; if ( ufile . exists ( ) ) { if ( ! ufile . delete ( ) ) log . warn ( "failed to delete uncompressed file (IOException)" + ufilename ) ; } throw e ; } finally { try { if ( lock != null ) lock . release ( ) ; } catch ( IOException e ) { if ( outputRaf != null ) outputRaf . close ( ) ; throw e ; } } return outputRaf ; }


Input: Count the number of records in a grib1 file . [CODESPLIT] public static void main ( String [ ] args ) throws IOException { int count = 0 ; String file = ( args . length > 0 ) ? args [ 0 ] : "Q:/cdmUnitTest/formats/grib1/ECMWF.hybrid.grib1" ; RandomAccessFile raf = new RandomAccessFile ( file , "r" ) ; System . out . printf ( "Read %s%n" , raf . getLocation ( ) ) ; Grib1RecordScanner scan = new Grib1RecordScanner ( raf ) ; while ( scan . hasNext ( ) ) { scan . next ( ) ; count ++ ; } raf . close ( ) ; System . out . printf ( "count=%d%n" , count ) ; }


Input: Factory method for constructing a UnitName from a name and a plural form of the name . [CODESPLIT] public static UnitName newUnitName ( final String name , final String plural ) throws NameException { return newUnitName ( name , plural , null ) ; }


Input: Factory method for constructing a UnitName from a name a plural form of the name and a symbol . [CODESPLIT] public static UnitName newUnitName ( final String name , final String plural , final String symbol ) throws NameException { return new UnitName ( name , plural , symbol ) ; }


Input: Returns the plural form of a name . Regular rules are used to generate the plural form . [CODESPLIT] protected String makePlural ( final String name ) { String plural ; final int length = name . length ( ) ; final char lastChar = name . charAt ( length - 1 ) ; if ( lastChar != ' ' ) { plural = name + ( lastChar == ' ' || lastChar == ' ' || lastChar == ' ' || name . endsWith ( "ch" ) ? "es" : "s" ) ; } else { if ( length == 1 ) { plural = name + "s" ; } else { final char penultimateChar = name . charAt ( length - 2 ) ; plural = ( penultimateChar == ' ' || penultimateChar == ' ' || penultimateChar == ' ' || penultimateChar == ' ' || penultimateChar == ' ' ) ? name + "s" : name . substring ( 0 , length - 1 ) + "ies" ; } } return plural ; }


Input: choose a resolution based on # seconds [CODESPLIT] private String chooseResolution ( double time ) { if ( time < 180 ) // 3 minutes return "secs" ; time /= 60 ; // minutes if ( time < 180 ) // 3 hours return "minutes" ; time /= 60 ; // hours if ( time < 72 ) // 3 days return "hours" ; time /= 24 ; // days if ( time < 90 ) // 3 months return "days" ; time /= 30 ; // months if ( time < 36 ) // 3 years return "months" ; return "years" ; }


Input: Determine if the given date is included in this date range . The date range includes the start and end dates . [CODESPLIT] public boolean included ( Date d ) { if ( isEmpty ) return false ; if ( getStart ( ) . after ( d ) ) return false ; if ( getEnd ( ) . before ( d ) ) return false ; return true ; }


Input: Determine if the given range intersects this date range . [CODESPLIT] public boolean intersects ( Date start_want , Date end_want ) { if ( isEmpty ) return false ; if ( getStart ( ) . after ( end_want ) ) return false ; if ( getEnd ( ) . before ( start_want ) ) return false ; return true ; }


Input: Determine if the given range intersects this date range . [CODESPLIT] public boolean intersects ( DateRange other ) { return intersects ( other . getStart ( ) . getDate ( ) , other . getEnd ( ) . getDate ( ) ) ; }


Input: Intersect with another date range [CODESPLIT] public DateRange intersect ( DateRange clip ) { if ( isEmpty ) return this ; if ( clip . isEmpty ) return clip ; DateType ss = getStart ( ) ; DateType s = ss . before ( clip . getStart ( ) ) ? clip . getStart ( ) : ss ; DateType ee = getEnd ( ) ; DateType e = ee . before ( clip . getEnd ( ) ) ? ee : clip . getEnd ( ) ; return new DateRange ( s , e , null , resolution ) ; }


Input: Extend this date range by the given one . [CODESPLIT] public void extend ( DateRange dr ) { boolean localEmpty = isEmpty ; if ( localEmpty || dr . getStart ( ) . before ( getStart ( ) ) ) setStart ( dr . getStart ( ) ) ; if ( localEmpty || getEnd ( ) . before ( dr . getEnd ( ) ) ) setEnd ( dr . getEnd ( ) ) ; }


Input: Extend this date range by the given Date . [CODESPLIT] public void extend ( Date d ) { if ( d . before ( getStart ( ) . getDate ( ) ) ) setStart ( new DateType ( false , d ) ) ; if ( getEnd ( ) . before ( d ) ) setEnd ( new DateType ( false , d ) ) ; }


Input: Set the starting Date . Makes useStart true . If useEnd recalculate the duration else recalculate end . [CODESPLIT] public void setStart ( DateType start ) { this . start = start ; useStart = true ; if ( useEnd ) { this . isMoving = this . start . isPresent ( ) || this . end . isPresent ( ) ; useDuration = false ; recalcDuration ( ) ; } else { this . isMoving = this . start . isPresent ( ) ; this . end = this . start . add ( duration ) ; } checkIfEmpty ( ) ; }


Input: Set the ending Date . Makes useEnd true . If useStart recalculate the duration else recalculate start . [CODESPLIT] public void setEnd ( DateType end ) { this . end = end ; useEnd = true ; if ( useStart ) { this . isMoving = this . start . isPresent ( ) || this . end . isPresent ( ) ; useDuration = false ; recalcDuration ( ) ; } else { this . isMoving = this . end . isPresent ( ) ; this . start = this . end . subtract ( duration ) ; } checkIfEmpty ( ) ; }


Input: Set the duration of the interval . Makes useDuration true . If useStart recalculate end else recalculate start . [CODESPLIT] public void setDuration ( TimeDuration duration ) { this . duration = duration ; useDuration = true ; if ( useStart ) { this . isMoving = this . start . isPresent ( ) ; this . end = this . start . add ( duration ) ; useEnd = false ; } else { this . isMoving = this . end . isPresent ( ) ; this . start = this . end . subtract ( duration ) ; } checkIfEmpty ( ) ; }


Input: assumes not moving [CODESPLIT] private void recalcDuration ( ) { long min = getStart ( ) . getDate ( ) . getTime ( ) ; long max = getEnd ( ) . getDate ( ) . getTime ( ) ; double secs = .001 * ( max - min ) ; if ( secs < 0 ) secs = 0 ; if ( duration == null ) { try { duration = new TimeDuration ( chooseResolution ( secs ) ) ; } catch ( ParseException e ) { // cant happen throw new RuntimeException ( e ) ; } } if ( resolution == null ) { duration . setValueInSeconds ( secs ) ; } else { // make it a multiple of resolution double resSecs = resolution . getValueInSeconds ( ) ; double closest = Math . round ( secs / resSecs ) ; secs = closest * resSecs ; duration . setValueInSeconds ( secs ) ; } hashCode = 0 ; }


Input:
save all data in the PersistentStore [CODESPLIT] public void storePersistentData ( ) { store . putInt ( "vertSplit" , splitDraw . getDividerLocation ( ) ) ; store . putBoolean ( "navToolbarAction" , ( ( Boolean ) navToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( "moveToolbarAction" , ( ( Boolean ) moveToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; if ( projManager != null ) projManager . storePersistentData ( ) ; /* if (csManager != null)
      csManager.storePersistentData();
    if (sysConfigDialog != null)
      sysConfigDialog.storePersistentData(); */ dsTable . save ( ) ; dsTable . getPrefs ( ) . putBeanObject ( "DialogBounds" , dsDialog . getBounds ( ) ) ; store . put ( GEOTIFF_FILECHOOSER_DEFAULTDIR , geotiffFileChooser . getCurrentDirectory ( ) ) ; controller . storePersistentData ( ) ; }


Input:
add a MapBean to the User Interface [CODESPLIT] public void addMapBean ( MapBean mb ) { mapBeanMenu . addAction ( mb . getActionDesc ( ) , mb . getIcon ( ) , mb . getAction ( ) ) ; // first one is the "default"
 if ( mapBeanCount == 0 ) { setMapRenderer ( mb . getRenderer ( ) ) ; } mapBeanCount ++ ; mb . addPropertyChangeListener ( new PropertyChangeListener ( ) { public void propertyChange ( java . beans . PropertyChangeEvent e ) { if ( e . getPropertyName ( ) . equals ( "Renderer" ) ) { setMapRenderer ( ( Renderer ) e . getNewValue ( ) ) ; } } } ) ; }


Input:
actions that control the dataset [CODESPLIT] private void makeActionsDataset ( ) { // choose local dataset
 AbstractAction chooseLocalDatasetAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { String filename = fileChooser . chooseFilename ( ) ; if ( filename == null ) return ; Dataset invDs ; try { invDs = Dataset . makeStandalone ( filename , FeatureType . GRID . toString ( ) , "" , ServiceType . File . toString ( ) ) ; } catch ( Exception ue ) { JOptionPane . showMessageDialog ( GridUI . this , "Invalid filename = <" + filename + ">\n" + ue . getMessage ( ) ) ; ue . printStackTrace ( ) ; return ; } setDataset ( invDs ) ; } } ; BAMutil . setActionProperties ( chooseLocalDatasetAction , "FileChooser" , "open Local dataset..." , false , ' ' , - 1 ) ; /* saveDatasetAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        String fname = controller.getDatasetName();
        if (fname != null) {
          savedDatasetList.add( fname);
          BAMutil.addActionToMenu( savedDatasetMenu, new DatasetAction( fname), 0);
        }
      }
    };
    BAMutil.setActionProperties( saveDatasetAction, null, "save dataset", false, 'S', 0);
    */ // Configure
 chooseProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) . setVisible ( ) ; } } ; BAMutil . setActionProperties ( chooseProjectionAction , null , "Projection Manager..." , false , ' ' , 0 ) ; saveCurrentProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) ; // set the bounding box
 ProjectionImpl proj = panz . getProjectionImpl ( ) . constructCopy ( ) ; proj . setDefaultMapArea ( panz . getMapArea ( ) ) ; //if (debug) System.out.println(" GV save projection "+ proj);
 // projManage.setMap(renderAll.get("Map"));   LOOK!
 //projManager.saveProjection( proj);
 } } ; BAMutil . setActionProperties ( saveCurrentProjectionAction , null , "save Current Projection" , false , ' ' , 0 ) ; /* chooseColorScaleAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        if (null == csManager) // lazy instantiation
          makeColorScaleManager();
        csManager.show();
      }
    };
    BAMutil.setActionProperties( chooseColorScaleAction, null, "ColorScale Manager...", false, 'C', 0);

    */ // redraw
 redrawAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { repaint ( ) ; controller . start ( true ) ; controller . draw ( true ) ; } } ; BAMutil . setActionProperties ( redrawAction , "alien" , "RedRaw" , false , ' ' , 0 ) ; showDatasetInfoAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( infoWindow == null ) { datasetInfoTA = new TextHistoryPane ( ) ; infoWindow = new IndependentWindow ( "Dataset Information" , BAMutil . getImage ( "GDVs" ) , datasetInfoTA ) ; infoWindow . setSize ( 700 , 700 ) ; infoWindow . setLocation ( 100 , 100 ) ; } datasetInfoTA . clear ( ) ; datasetInfoTA . appendLine ( controller . getDatasetInfo ( ) ) ; datasetInfoTA . gotoTop ( ) ; infoWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showDatasetInfoAction , "Information" , "Show info..." , false , ' ' , - 1 ) ; showNcMLAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( ncmlWindow == null ) { ncmlTA = new TextHistoryPane ( ) ; ncmlWindow = new IndependentWindow ( "Dataset NcML" , BAMutil . getImage ( "GDVs" ) , ncmlTA ) ; ncmlWindow . setSize ( 700 , 700 ) ; ncmlWindow . setLocation ( 200 , 70 ) ; } ncmlTA . clear ( ) ; //datasetInfoTA.appendLine( "GeoGrid XML for "+ controller.getDatasetName()+"\n");
 ncmlTA . appendLine ( controller . getNcML ( ) ) ; ncmlTA . gotoTop ( ) ; ncmlWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showNcMLAction , null , "Show NcML..." , false , ' ' , - 1 ) ; showGridDatasetInfoAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( ncmlWindow == null ) { ncmlTA = new TextHistoryPane ( ) ; ncmlWindow = new IndependentWindow ( "Dataset NcML" , BAMutil . getImage ( "GDVs" ) , ncmlTA ) ; ncmlWindow . setSize ( 700 , 700 ) ; ncmlWindow . setLocation ( 200 , 70 ) ; } ncmlTA . clear ( ) ; //datasetInfoTA.appendLine( "GeoGrid XML for "+ controller.getDatasetName()+"\n");
 ncmlTA . appendLine ( controller . getDatasetXML ( ) ) ; ncmlTA . gotoTop ( ) ; ncmlWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showGridDatasetInfoAction , null , "Show GridDataset Info XML..." , false , ' ' , - 1 ) ; // show gridTable
 showGridTableAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { gtWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showGridTableAction , "Table" , "grid Table..." , false , ' ' , - 1 ) ; // show netcdf dataset Table
 showNetcdfDatasetAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { NetcdfDataset netcdfDataset = controller . getNetcdfDataset ( ) ; if ( null != netcdfDataset ) { try { dsTable . setDataset ( netcdfDataset , null ) ; } catch ( IOException e1 ) { e1 . printStackTrace ( ) ; return ; } dsDialog . show ( ) ; } } } ; BAMutil . setActionProperties ( showNetcdfDatasetAction , "netcdf" , "NetcdfDataset Table Info..." , false , ' ' , - 1 ) ; /* write geotiff file
    geotiffAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        GeoGrid grid = controller.getCurrentField();
        ucar.ma2.Array data = controller.getCurrentHorizDataSlice();
        if ((grid == null) || (data == null)) return;

        String filename = geotiffFileChooser.chooseFilename();
        if (filename == null) return;

        GeoTiff geotiff = null;
        try {
          /* System.out.println("write to= "+filename);
          ucar.nc2.geotiff.Writer.write2D(grid, data, filename+".tfw");
          geotiff = new GeoTiff(filename); // read back in
          geotiff.read();
          System.out.println( geotiff.showInfo());
          //geotiff.testReadData();
          geotiff.close(); * /

          // write two
          ucar.nc2.geotiff.GeotiffWriter writer = new ucar.nc2.geotiff.GeotiffWriter(filename);
          writer.writeGrid(grid, data, false);
          geotiff = new GeoTiff(filename); // read back in
          geotiff.read();
          System.out.println( "*************************************");
          System.out.println( geotiff.showInfo());
          //geotiff.testReadData();
          geotiff.close();

        } catch (IOException ioe) {
          ioe.printStackTrace();

        } finally {
          try {
            if (geotiff != null) geotiff.close();
          } catch (IOException ioe) { }
        }

      }
    };
    BAMutil.setActionProperties( geotiffAction, "Geotiff", "Write Geotiff file", false, 'G', -1);
    */ minmaxHorizAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . horiz ) ; controller . setDataMinMaxType ( ColorScale . MinMaxType . horiz ) ; } } ; BAMutil . setActionProperties ( minmaxHorizAction , null , "Horizontal plane" , false , ' ' , 0 ) ; minmaxLogAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . log ) ; controller . setDataMinMaxType ( ColorScale . MinMaxType . log ) ; } } ; BAMutil . setActionProperties ( minmaxLogAction , null , "log horiz plane" , false , ' ' , 0 ) ; /* minmaxVolAction =  new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        csDataMinMax.setSelectedIndex(GridRenderer.VOL_MinMaxType);
        controller.setDataMinMaxType(GridRenderer.MinMaxType.vert;
      }
    };
    BAMutil.setActionProperties( minmaxVolAction, null, "Grid volume", false, 'G', 0); */ minmaxHoldAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . hold ) ; controller . setDataMinMaxType ( ColorScale . MinMaxType . hold ) ; } } ; BAMutil . setActionProperties ( minmaxHoldAction , null , "Hold scale constant" , false , ' ' , 0 ) ; fieldLoopAction = new LoopControlAction ( fieldChooser ) ; levelLoopAction = new LoopControlAction ( levelChooser ) ; timeLoopAction = new LoopControlAction ( timeChooser ) ; }


Input: Get the 3D vertical coordinate array for this time step . [CODESPLIT] public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; Array cArray = readArray ( cVar , timeIndex ) ; depth_c = depthCVar . readScalarDouble ( ) ; return makeHeight ( etaArray , sArray , depthArray , cArray , depth_c ) ; }


Input: Get the 1D vertical coordinate array for this time step and the specified X Y index for Lat - Lon point . [CODESPLIT] public ArrayDouble . D1 getCoordinateArray1D ( int timeIndex , int xIndex , int yIndex ) throws IOException , InvalidRangeException { Array etaArray = readArray ( etaVar , timeIndex ) ; Array sArray = readArray ( sVar , timeIndex ) ; Array depthArray = readArray ( depthVar , timeIndex ) ; Array cArray = readArray ( cVar , timeIndex ) ; depth_c = depthCVar . readScalarDouble ( ) ; return makeHeight1D ( etaArray , sArray , depthArray , cArray , depth_c , xIndex , yIndex ) ; }


Input: ///////////////// [CODESPLIT] private long getFilePos ( long elem ) { long segno = elem / innerNelems ; long offset = elem % innerNelems ; return startPos + segno * recSize + offset * elemSize ; }


Input:
Entry point for the scanner . Returns the token identifier corresponding to the next token and prepares to return the semantic value of the token . [CODESPLIT] public int yylex ( ) throws ParseException { int token ; int c = 0 ; token = 0 ; yytext . setLength ( 0 ) ; text . mark ( ) ; token = - 1 ; while ( token < 0 && ( c = text . read ( ) ) != EOS ) { if ( c <= ' ' || c == ' ' ) { /* whitespace: ignore */ } else if ( c == ' ' || c == ' ' ) { int delim = c ; boolean more = true ; /* We have a string token; will be reported as STRINGCONST */ while ( more && ( c = text . read ( ) ) > 0 ) { switch ( c ) { case EOS : throw new ParseException ( "Unterminated character or string constant" ) ; case ' ' : more = ( delim != c ) ; break ; case ' ' : more = ( delim != c ) ; break ; case ESCAPE : /* Suppress for now
            if(c >= '0' && c <= '9') {
			int decimal = 0;
		        do {
                            decimal = decimal * 10 + (c - '0');
                            c = text.read();
                        } while(c >= '0' && c <= '9');
                        c = decimal;
			text.backup();
                        break;
		    } else
*/ switch ( c ) { case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; case ' ' : c = ' ' ; break ; default : break ; } break ; default : break ; } if ( more ) yytext . append ( ( char ) c ) ; } token = CEParserImpl . Lexer . STRING ; } else if ( DELIMS . indexOf ( c ) >= 0 ) { // Single char delimiter yytext . append ( ( char ) c ) ; token = c ; } else { // Assume we have a word or integer yytext . append ( ( char ) c ) ; while ( ( c = text . read ( ) ) > 0 ) { if ( c <= ' ' || c == ' ' ) break ; // whitespace if ( DELIMS . indexOf ( c ) >= 0 ) break ; if ( c == ESCAPE ) { c = text . read ( ) ; if ( c == EOS ) throw new ParseException ( "Unterminated backslash escape" ) ; } yytext . append ( ( char ) c ) ; } // pushback the delimiter if ( c != EOS ) text . backup ( ) ; try { // See if this looks like an integer long num = Long . parseLong ( yytext . toString ( ) ) ; token = CEParserImpl . Lexer . LONG ; } catch ( NumberFormatException nfe ) { token = CEParserImpl . Lexer . NAME ; } } } if ( c == EOS && token < 0 ) { token = 0 ; lval = null ; } else { lval = ( yytext . length ( ) == 0 ? ( String ) null : yytext . toString ( ) ) ; } if ( parsestate . getDebugLevel ( ) > 0 ) dumptoken ( token , ( String ) lval ) ; return token ; // Return the type of the token }


Input: Entry point for error reporting . Emits an error in a user - defined way . Part of Lexer interface . [CODESPLIT] public void yyerror ( String s ) { System . err . println ( "CEParserImpl.yyerror: " + s + "; parse failed at char: " + charno + "; near: " ) ; String context = getInput ( ) ; int show = ( context . length ( ) < CONTEXTLEN ? context . length ( ) : CONTEXTLEN ) ; System . err . println ( context . substring ( context . length ( ) - show ) + "^" ) ; new Exception ( ) . printStackTrace ( System . err ) ; }


Input: Open a netcdf dataset using NetcdfDataset . defaultEnhanceMode plus CoordSystems and turn into a DtCoverageDataset . [CODESPLIT] static public DtCoverageDataset open ( String location ) throws java . io . IOException { DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; return open ( durl , NetcdfDataset . getDefaultEnhanceMode ( ) ) ; }


Input: Open a netcdf dataset using NetcdfDataset . defaultEnhanceMode plus CoordSystems and turn into a DtCoverageDataset . [CODESPLIT] static public DtCoverageDataset open ( DatasetUrl durl , Set < NetcdfDataset . Enhance > enhanceMode ) throws java . io . IOException { NetcdfDataset ds = ucar . nc2 . dataset . NetcdfDataset . acquireDataset ( null , durl , enhanceMode , - 1 , null , null ) ; return new DtCoverageDataset ( ds , null ) ; }


Input: the name of the dataset is the last part of the location [CODESPLIT] public String getName ( ) { String loc = ncd . getLocation ( ) ; int pos = loc . lastIndexOf ( ' ' ) ; if ( pos < 0 ) pos = loc . lastIndexOf ( ' ' ) ; return ( pos < 0 ) ? loc : loc . substring ( pos + 1 ) ; }


Input: find the named GeoGrid . [CODESPLIT] public DtCoverage findGridByName ( String fullName ) { for ( DtCoverage ggi : grids ) { if ( fullName . equals ( ggi . getFullName ( ) ) ) return ggi ; } return null ; }


Input: find the named GeoGrid . [CODESPLIT] public DtCoverage findGridByShortName ( String shortName ) { for ( DtCoverage ggi : grids ) { if ( shortName . equals ( ggi . getShortName ( ) ) ) return ggi ; } return null ; }


Input: Create a String of the parameters . [CODESPLIT] public String paramsToString ( ) { Formatter f = new Formatter ( ) ; f . format ( "origin lat,lon=%f,%f parellels=%f,%f earth=%s" , lat0deg , lon0deg , par1deg , par2deg , earth ) ; return f . toString ( ) ; }


Input:
This returns true when the line between pt1 and pt2 crosses the seam . When the cone is flattened the seam is lon0 + - 180 . [CODESPLIT] public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) { return true ; } return false ; /* opposite signed X values, larger then 5000 km  LOOK ????
    return (pt1.getX() * pt2.getX() < 0)
            && (Math.abs(pt1.getX() - pt2.getX()) > 5000.0); */ }


Input: / * public ProjectionPoint latLonToProj ( LatLonPoint latLon ProjectionPointImpl result ) { double toX toY ; double fromLat = latLon . getLatitude () ; double fromLon = latLon . getLongitude () ; [CODESPLIT] private double computeTheta ( double lon ) { double dlon = LatLonPointImpl . lonNormal ( lon - lon0deg ) ; return n * Math . toRadians ( dlon ) ; }


Input: also see Snyder p 101 [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double fromLat = Math . toRadians ( latLon . getLatitude ( ) ) ; double theta = computeTheta ( latLon . getLongitude ( ) ) ; double rho = 0.0 ; if ( Math . abs ( Math . abs ( fromLat ) - MapMath . HALFPI ) >= TOL ) { double term ; if ( isSpherical ) term = Math . pow ( Math . tan ( MapMath . QUARTERPI + .5 * fromLat ) , - n ) ; else term = Math . pow ( MapMath . tsfn ( fromLat , Math . sin ( fromLat ) , e ) , n ) ; rho = c * term ; } double toX = ( rho * Math . sin ( theta ) ) ; double toY = ( rho0 - rho * Math . cos ( theta ) ) ; result . setLocation ( totalScale * toX + falseEasting , totalScale * toY + falseNorthing ) ; return result ; }


Input:
/ * public LatLonPoint projToLatLon ( ProjectionPoint world LatLonPointImpl result ) { double toLat toLon ; double fromX = world . getX () - falseEasting ; double fromY = world . getY () - falseNorthing ; double rhop = rho ; [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = ( world . getX ( ) - falseEasting ) / totalScale ; // assumes cartesion coords in km
 double fromY = ( world . getY ( ) - falseNorthing ) / totalScale ; fromY = rho0 - fromY ; double rho = MapMath . distance ( fromX , fromY ) ; if ( rho != 0 ) { if ( n < 0.0 ) { rho = - rho ; fromX = - fromX ; fromY = - fromY ; } if ( isSpherical ) toLat = 2.0 * Math . atan ( Math . pow ( c / rho , 1.0 / n ) ) - MapMath . HALFPI ; else toLat = MapMath . phi2 ( Math . pow ( rho / c , 1.0 / n ) , e ) ; toLon = Math . atan2 ( fromX , fromY ) / n ; //coverity[swapped_arguments]
 } else { toLon = 0.0 ; toLat = n > 0.0 ? MapMath . HALFPI : - MapMath . HALFPI ; } result . setLatitude ( Math . toDegrees ( toLat ) ) ; result . setLongitude ( Math . toDegrees ( toLon ) + lon0deg ) ; return result ; }


Input: / * proj + inv + proj = aea + lat_0 = 23 . 0 + lat_1 = 29 . 5 + lat_2 = 45 . 5 + a = 6378137 . 0 + rf = 298 . 257222101 + b = 6356752 . 31414 + lon_0 = - 96 . 0 [CODESPLIT] private static void toProj ( ProjectionImpl p , double lat , double lon ) { System . out . printf ( "lon,lat = %f %f%n" , lon , lat ) ; ProjectionPoint pt = p . latLonToProj ( lat , lon ) ; System . out . printf ( "x,y     = %f %f%n" , pt . getX ( ) , pt . getY ( ) ) ; LatLonPoint ll = p . projToLatLon ( pt ) ; System . out . printf ( "lon,lat = %f %f%n%n" , ll . getLongitude ( ) , ll . getLatitude ( ) ) ; }


Input: A path is file if it has no base protocol or is file : [CODESPLIT] public boolean dspMatch ( String location , DapContext context ) { try { XURI xuri = new XURI ( location ) ; if ( xuri . isFile ( ) ) { String path = xuri . getPath ( ) ; for ( String ext : EXTENSIONS ) { if ( path . endsWith ( ext ) ) return true ; } } } catch ( URISyntaxException use ) { return false ; } return false ; }


Input: Extension to access a raw byte stream [CODESPLIT] public FileDSP open ( byte [ ] rawdata ) throws DapException { try { this . raw = rawdata ; ByteArrayInputStream stream = new ByteArrayInputStream ( this . raw ) ; ChunkInputStream rdr = new ChunkInputStream ( stream , RequestMode . DAP ) ; String document = rdr . readDMR ( ) ; byte [ ] serialdata = DapUtil . readbinaryfile ( rdr ) ; super . build ( document , serialdata , rdr . getRemoteByteOrder ( ) ) ; return this ; } catch ( IOException ioe ) { throw new DapException ( ioe ) . setCode ( DapCodes . SC_INTERNAL_SERVER_ERROR ) ; } }


Input: Returns a clone of this <code > Alias< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { Alias a = ( Alias ) super . cloneDAG ( map ) ; a . aliasedToAttributeNamed = this . aliasedToAttributeNamed ; a . targetAttribute = ( Attribute ) cloneDAG ( map , this . targetAttribute ) ; a . targetVariable = ( BaseType ) cloneDAG ( map , this . targetVariable ) ; return a ; }


Input:
Adapted from the package - private BasicDayOfMonthDateTimeField [CODESPLIT] @ Override public int getMaximumValue ( ReadablePartial partial ) { if ( partial . isSupported ( DateTimeFieldType . monthOfYear ( ) ) ) { int month = partial . get ( DateTimeFieldType . monthOfYear ( ) ) ; return this . daysInMonth [ month - 1 ] ; // Months are 1-based
 } return this . getMaximumValue ( ) ; }


Input: Adapted from the package - private BasicDayOfMonthDateTimeField [CODESPLIT] @ Override public int getMaximumValue ( ReadablePartial partial , int [ ] values ) { int size = partial . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { if ( partial . getFieldType ( i ) == DateTimeFieldType . monthOfYear ( ) ) { int month = values [ i ] ; return this . daysInMonth [ month - 1 ] ; } } return this . getMaximumValue ( ) ; }


Input: return y x ranges [CODESPLIT] private Optional < List < RangeIterator > > computeBounds ( LatLonRect llbb , int horizStride ) { synchronized ( this ) { if ( edges == null ) edges = new Edges ( ) ; } return edges . computeBoundsExhaustive ( llbb , horizStride ) ; }


Input: wml2 : Collection [CODESPLIT] public static CollectionType initCollection ( CollectionType collection , FeatureDatasetPoint fdPoint , List < VariableSimpleIF > dataVars ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( CollectionType . class ) ; collection . setId ( id ) ; // wml2:metadata NcDocumentMetadataPropertyType . initMetadata ( collection . addNewMetadata ( ) ) ; // wml2:observationMember[0..*] StationTimeSeriesFeatureCollection stationFeatColl = getStationFeatures ( fdPoint ) ; try { while ( stationFeatColl . hasNext ( ) ) { StationTimeSeriesFeature stationFeat = stationFeatColl . next ( ) ; for ( VariableSimpleIF dataVar : dataVars ) { if ( dataVar . getDataType ( ) . isNumeric ( ) ) { // wml2:observationMember NcOMObservationPropertyType . initObservationMember ( collection . addNewObservationMember ( ) , stationFeat , dataVar ) ; } } } } finally { stationFeatColl . finish ( ) ; } return collection ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation [CODESPLIT] public static OMObservationType initOmObservation ( OMObservationType omObservation , StationTimeSeriesFeature stationFeat , VariableSimpleIF dataVar ) throws IOException { // @gml:id String id = MarshallingUtil . createIdForType ( OMObservationType . class ) ; omObservation . setId ( id ) ; // om:phenomenonTime NcTimeObjectPropertyType . initPhenomenonTime ( omObservation . addNewPhenomenonTime ( ) , stationFeat ) ; // om:resultTime NcTimeInstantPropertyType . initResultTime ( omObservation . addNewResultTime ( ) ) ; // om:observedProperty NcReferenceType . initObservedProperty ( omObservation . addNewObservedProperty ( ) , dataVar ) ; // om:procedure NcOMProcessPropertyType . initProcedure ( omObservation . addNewProcedure ( ) ) ; // om:featureOfInterest NcFeaturePropertyType . initFeatureOfInterest ( omObservation . addNewFeatureOfInterest ( ) , stationFeat ) ; // om:result MeasurementTimeseriesDocument measurementTimeseriesDoc = MeasurementTimeseriesDocument . Factory . newInstance ( ) ; NcMeasurementTimeseriesType . initMeasurementTimeseries ( measurementTimeseriesDoc . addNewMeasurementTimeseries ( ) , stationFeat , dataVar ) ; omObservation . setResult ( measurementTimeseriesDoc ) ; return omObservation ; }


Input: ///////////////////////////////////////////// [CODESPLIT] private void doCheckHash ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { f . format ( "Check Files for hash consistency%n" ) ; int [ ] accum = new int [ 4 ] ; TrackMessageTypes all = new TrackMessageTypes ( ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; if ( path . endsWith ( ".ncx" ) ) continue ; f . format ( "%n %s%n" , path ) ; try { doCheckHash ( mfile , f , all , accum ) ; } catch ( Throwable t ) { System . out . printf ( "FAIL on %s%n" , mfile . getPath ( ) ) ; t . printStackTrace ( ) ; } } f . format ( "%n================%nTotals countMess=%d countObs = %d%n" , accum [ 0 ] , accum [ 1 ] ) ; show ( all , f ) ; }


Input: ///////////////////////////////////////////// [CODESPLIT] private void doBufrSplitter ( Formatter f , MCollection dcm , boolean useIndex ) throws IOException { long start = System . currentTimeMillis ( ) ; String dirName = dcm . getRoot ( ) + "/split" ; // LOOK temp kludge f . format ( "BufrSplitter on files in collection %s, write to %s%n" , dcm , dirName ) ; BufrSplitter2 splitter = new BufrSplitter2 ( dirName , f ) ; for ( MFile mfile : dcm . getFilesSorted ( ) ) { String path = mfile . getPath ( ) ; if ( path . endsWith ( ".ncx" ) ) continue ; f . format ( "%n %s%n" , path ) ; System . out . printf ( " BufrSplitter on %s%n" , path ) ; long start2 = System . currentTimeMillis ( ) ; try { splitter . execute ( path ) ; long took2 = System . currentTimeMillis ( ) - start2 ; System . out . printf ( "  %s took %s msecs%n" , path , took2 ) ; } catch ( Throwable t ) { System . out . printf ( "FAIL on %s%n" , mfile . getPath ( ) ) ; t . printStackTrace ( ) ; } } splitter . exit ( ) ; long took = ( System . currentTimeMillis ( ) - start ) / 1000 ; System . out . printf ( "That took %s secs%n" , took ) ; }


Input: 2006 - 10 - 23T17 : 59 : 39 18 . 415434 - 93 . 480526 - 26 . 8 1 [CODESPLIT] int readAllData ( RandomAccessFile raf ) throws IOException , NumberFormatException , ParseException { ArrayList records = new ArrayList ( ) ; java . text . SimpleDateFormat isoDateTimeFormat = new java . text . SimpleDateFormat ( "yyyy-MM-dd'T'HH:mm:ss" ) ; isoDateTimeFormat . setTimeZone ( java . util . TimeZone . getTimeZone ( "GMT" ) ) ; //java.io.RandomAccessFile jraf = raf.getRandomAccessFile(); raf . seek ( 0 ) ; int count = 0 ; while ( true ) { String line = raf . readLine ( ) ; if ( line == null ) break ; if ( line . startsWith ( MAGIC ) ) continue ; StringTokenizer stoker = new StringTokenizer ( line , ",\r\n" ) ; while ( stoker . hasMoreTokens ( ) ) { Date d = isoDateTimeFormat . parse ( stoker . nextToken ( ) ) ; double lat = Double . parseDouble ( stoker . nextToken ( ) ) ; double lon = Double . parseDouble ( stoker . nextToken ( ) ) ; double amp = Double . parseDouble ( stoker . nextToken ( ) ) ; String tok = stoker . nextToken ( ) ; int nstrikes = Integer . parseInt ( tok ) ; Strike s = new Strike ( d , lat , lon , amp , nstrikes ) ; records . add ( s ) ; if ( count < 10 ) System . out . println ( count + " " + isoDateTimeFormat . format ( d ) + " " + s ) ; } count ++ ; } System . out . println ( "processed " + count + " records" ) ; int n = records . size ( ) ; int [ ] shape = new int [ ] { n } ; dateArray = ( ArrayInt . D1 ) Array . factory ( DataType . INT , shape ) ; latArray = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , shape ) ; lonArray = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , shape ) ; ampArray = ( ArrayDouble . D1 ) Array . factory ( DataType . DOUBLE , shape ) ; nstrokesArray = ( ArrayInt . D1 ) Array . factory ( DataType . INT , shape ) ; for ( int i = 0 ; i < records . size ( ) ; i ++ ) { Strike strike = ( Strike ) records . get ( i ) ; dateArray . set ( i , strike . d ) ; latArray . set ( i , strike . lat ) ; lonArray . set ( i , strike . lon ) ; ampArray . set ( i , strike . amp ) ; nstrokesArray . set ( i , strike . n ) ; } return n ; }


Input: set values on the UI [CODESPLIT] private void synchUI ( boolean slidersOK ) { eventOK = false ; if ( slidersOK ) minSlider . setValue ( scale . world2slider ( dateRange . getStart ( ) ) ) ; minField . setValue ( dateRange . getStart ( ) ) ; if ( maxField != null ) { if ( slidersOK ) maxSlider . setValue ( scale . world2slider ( dateRange . getEnd ( ) ) ) ; maxField . setValue ( dateRange . getEnd ( ) ) ; } if ( durationField != null ) durationField . setValue ( dateRange . getDuration ( ) ) ; eventOK = true ; }


Input: make it easy to test by using dimension list [CODESPLIT] public int [ ] computeUnlimitedChunking ( List < Dimension > dims , int elemSize ) { int maxElements = defaultChunkSize / elemSize ; int [ ] result = fillRightmost ( convertUnlimitedShape ( dims ) , maxElements ) ; long resultSize = new Section ( result ) . computeSize ( ) ; if ( resultSize < minChunksize ) { maxElements = minChunksize / elemSize ; result = incrUnlimitedShape ( dims , result , maxElements ) ; } return result ; }


Input: Register the given directory with the WatchService [CODESPLIT] public void register ( Path dir ) throws IOException { if ( ! enable ) return ; WatchKey key = dir . register ( watcher , ENTRY_CREATE , ENTRY_DELETE , ENTRY_MODIFY ) ; if ( trace ) { Path prev = keys . get ( key ) ; if ( prev == null ) { System . out . format ( "CatalogWatcher register: %s%n" , dir ) ; } else { if ( ! dir . equals ( prev ) ) { System . out . format ( "update: %s -> %s%n" , prev , dir ) ; } } } keys . put ( key , dir ) ; }


Input: Process all events for keys queued to the watcher [CODESPLIT] public void processEvents ( ) { if ( ! enable ) return ; for ( ; ; ) { // wait for key to be signalled WatchKey key ; try { key = watcher . take ( ) ; } catch ( InterruptedException x ) { return ; } Path dir = keys . get ( key ) ; if ( dir == null ) { System . err . println ( "WatchKey not recognized!!" ) ; continue ; } for ( WatchEvent < ? > event : key . pollEvents ( ) ) { WatchEvent . Kind kind = event . kind ( ) ; // TBD - provide example of how OVERFLOW event is handled if ( kind == OVERFLOW ) { continue ; } // Context for directory entry event is the file name of entry WatchEvent < Path > ev = cast ( event ) ; Path name = ev . context ( ) ; Path child = dir . resolve ( name ) ; // print out event System . out . format ( "%s: %s%n" , event . kind ( ) . name ( ) , child ) ; // if directory is created, and watching recursively, then // register it and its sub-directories if ( recursive && ( kind == ENTRY_CREATE ) ) { try { if ( Files . isDirectory ( child , NOFOLLOW_LINKS ) ) { registerAll ( child ) ; } } catch ( IOException x ) { // ignore to keep sample readbale } } } // reset key and remove from set if directory no longer accessible boolean valid = key . reset ( ) ; if ( ! valid ) { keys . remove ( key ) ; // all directories are inaccessible if ( keys . isEmpty ( ) ) { break ; } } } }


Input: copy on modify [CODESPLIT] public TimeHelper setReferenceDate ( CalendarDate refDate ) { CalendarDateUnit cdUnit = CalendarDateUnit . of ( dateUnit . getCalendar ( ) , dateUnit . getCalendarField ( ) , refDate ) ; return new TimeHelper ( cdUnit ) ; }


Input:
Register a class that implements a FeatureDatasetFactory . [CODESPLIT] static public boolean registerFactory ( FeatureType datatype , String className ) { try { Class c = Class . forName ( className ) ; registerFactory ( datatype , c ) ; return true ; } catch ( ClassNotFoundException e ) { // ok - these are optional
 return false ; } }


Input: Register a class that implements a FeatureDatasetFactory . [CODESPLIT] static public void registerFactory ( String className ) throws ClassNotFoundException { Class c = Class . forName ( className ) ; registerFactory ( c ) ; }


Input:
Register a class that implements a FeatureDatasetFactory . Find out which type by calling getFeatureType () . [CODESPLIT] static public void registerFactory ( Class c ) { if ( ! ( FeatureDatasetFactory . class . isAssignableFrom ( c ) ) ) throw new IllegalArgumentException ( "Class " + c . getName ( ) + " must implement FeatureDatasetFactory" ) ; // fail fast - get Instance
 Object instance ; try { instance = c . newInstance ( ) ; } catch ( InstantiationException e ) { throw new IllegalArgumentException ( "FeatureDatasetFactoryManager Class " + c . getName ( ) + " cannot instantiate, probably need default Constructor" ) ; } catch ( IllegalAccessException e ) { throw new IllegalArgumentException ( "FeatureDatasetFactoryManager Class " + c . getName ( ) + " is not accessible" ) ; } // find out what type of Features
 try { Method m = c . getMethod ( "getFeatureTypes" , new Class [ 0 ] ) ; FeatureType [ ] result = ( FeatureType [ ] ) m . invoke ( instance , new Object [ 0 ] ) ; for ( FeatureType ft : result ) { if ( userMode ) factoryList . add ( 0 , new Factory ( ft , c , ( FeatureDatasetFactory ) instance ) ) ; else factoryList . add ( new Factory ( ft , c , ( FeatureDatasetFactory ) instance ) ) ; } } catch ( Exception ex ) { throw new IllegalArgumentException ( "FeatureDatasetFactoryManager Class " + c . getName ( ) + " failed invoking getFeatureType()" , ex ) ; } }


Input:
Open a dataset as a FeatureDataset . [CODESPLIT] static public FeatureDataset open ( FeatureType wantFeatureType , String location , ucar . nc2 . util . CancelTask task , Formatter errlog ) throws IOException { // special processing for thredds: datasets
 if ( location . startsWith ( DataFactory . SCHEME ) ) { DataFactory . Result result = new DataFactory ( ) . openFeatureDataset ( wantFeatureType , location , task ) ; errlog . format ( "%s" , result . errLog ) ; if ( ! featureTypeOk ( wantFeatureType , result . featureType ) ) { errlog . format ( "wanted %s but dataset is of type %s%n" , wantFeatureType , result . featureType ) ; result . close ( ) ; return null ; } return result . featureDataset ; // special processing for cdmrFeature: datasets
 } else if ( location . startsWith ( CdmrFeatureDataset . SCHEME ) ) { Optional < FeatureDataset > opt = CdmrFeatureDataset . factory ( wantFeatureType , location ) ; if ( opt . isPresent ( ) ) return opt . get ( ) ; errlog . format ( "%s" , opt . getErrorMessage ( ) ) ; return null ; // special processing for collection: datasets
 } else if ( location . startsWith ( ucar . nc2 . ft . point . collection . CompositeDatasetFactory . SCHEME ) ) { String spec = location . substring ( CompositeDatasetFactory . SCHEME . length ( ) ) ; MFileCollectionManager dcm = MFileCollectionManager . open ( spec , spec , null , errlog ) ; // LOOK we dont have a name
 return CompositeDatasetFactory . factory ( location , wantFeatureType , dcm , errlog ) ; } DatasetUrl durl = DatasetUrl . findDatasetUrl ( location ) ; // Cache ServiceType so we don't have to keep figuring it out
 if ( durl . serviceType == null ) { // skip GRIB check for anything not a plain ole file
 // check if its GRIB, may not have to go through NetcdfDataset
 Optional < FeatureDatasetCoverage > opt = CoverageDatasetFactory . openGrib ( location ) ; if ( opt . isPresent ( ) ) { // its a GRIB file
 return opt . get ( ) ; } else if ( ! opt . getErrorMessage ( ) . startsWith ( CoverageDatasetFactory . NOT_GRIB_FILE ) && ! opt . getErrorMessage ( ) . startsWith ( CoverageDatasetFactory . NO_GRIB_CLASS ) ) { errlog . format ( "%s%n" , opt . getErrorMessage ( ) ) ; // its a GRIB file with an error
 return null ; } } // otherwise open as NetcdfDataset and run it through the FeatureDatasetFactories
 NetcdfDataset ncd = NetcdfDataset . acquireDataset ( durl , true , task ) ; FeatureDataset fd = wrap ( wantFeatureType , ncd , task , errlog ) ; if ( fd == null ) ncd . close ( ) ; return fd ; }


Input:
Wrap a NetcdfDataset as a FeatureDataset . [CODESPLIT] static public FeatureDataset wrap ( FeatureType wantFeatureType , NetcdfDataset ncd , ucar . nc2 . util . CancelTask task , Formatter errlog ) throws IOException { if ( debug ) System . out . println ( "wrap " + ncd . getLocation ( ) + " want = " + wantFeatureType ) ; // the case where we dont know what type it is
 if ( ( wantFeatureType == null ) || ( wantFeatureType == FeatureType . ANY ) ) { return wrapUnknown ( ncd , task , errlog ) ; } // find a Factory that claims this dataset by passing back an "analysis result" object
 Object analysis = null ; FeatureDatasetFactory useFactory = null ; for ( Factory fac : factoryList ) { if ( ! featureTypeOk ( wantFeatureType , fac . featureType ) ) continue ; if ( debug ) System . out . println ( " wrap try factory " + fac . factory . getClass ( ) . getName ( ) ) ; analysis = fac . factory . isMine ( wantFeatureType , ncd , errlog ) ; if ( analysis != null ) { useFactory = fac . factory ; break ; } } if ( null == useFactory ) { errlog . format ( "**Failed to find FeatureDatasetFactory for= %s datatype=%s%n" , ncd . getLocation ( ) , wantFeatureType ) ; return null ; } // this call must be thread safe - done by implementation
 return useFactory . open ( wantFeatureType , ncd , analysis , task , errlog ) ; }


Input:
Determine if factory type matches wanted feature type . [CODESPLIT] static public boolean featureTypeOk ( FeatureType want , FeatureType facType ) { if ( want == null ) return true ; if ( want == facType ) return true ; if ( want == FeatureType . ANY_POINT ) { return facType . isPointFeatureType ( ) ; } if ( facType == FeatureType . ANY_POINT ) { return want . isPointFeatureType ( ) ; } if ( want == FeatureType . COVERAGE ) { return facType . isCoverageFeatureType ( ) ; } if ( want == FeatureType . GRID ) { // for backwards compatibility
 return facType . isCoverageFeatureType ( ) ; } if ( want == FeatureType . SIMPLE_GEOMETRY ) { return facType . isCoverageFeatureType ( ) ; } if ( want == FeatureType . UGRID ) { return facType . isUnstructuredGridFeatureType ( ) ; } return false ; }


Input:
Try to determine the feature type of the dataset by examining its metadata . [CODESPLIT] static public FeatureType findFeatureType ( NetcdfFile ncd ) { // search for explicit featureType global attribute
 String cdm_datatype = ncd . findAttValueIgnoreCase ( null , CF . FEATURE_TYPE , null ) ; if ( cdm_datatype == null ) cdm_datatype = ncd . findAttValueIgnoreCase ( null , "cdm_data_type" , null ) ; if ( cdm_datatype == null ) cdm_datatype = ncd . findAttValueIgnoreCase ( null , "cdm_datatype" , null ) ; if ( cdm_datatype == null ) cdm_datatype = ncd . findAttValueIgnoreCase ( null , "thredds_data_type" , null ) ; if ( cdm_datatype != null ) { for ( FeatureType ft : FeatureType . values ( ) ) if ( cdm_datatype . equalsIgnoreCase ( ft . name ( ) ) ) { if ( debug ) System . out . println ( " wrapUnknown found cdm_datatype " + cdm_datatype ) ; return ft ; } } CF . FeatureType cff = CF . FeatureType . getFeatureTypeFromGlobalAttribute ( ncd ) ; if ( cff != null ) return CF . FeatureType . convert ( cff ) ; return null ; }


Input: Read directly from file without going through the buffer . All reading goes through here or readToByteChannel ; [CODESPLIT] @ Override protected int read_ ( long pos , byte [ ] buff , int offset , int len ) throws IOException { long end = pos + len - 1 ; if ( end >= total_length ) end = total_length - 1 ; if ( debug ) System . out . println ( " HTTPRandomAccessFile bytes=" + pos + "-" + end + ": " ) ; try ( HTTPMethod method = HTTPFactory . Get ( session , url ) ) { method . setFollowRedirects ( true ) ; method . setRange ( pos , end ) ; doConnect ( method ) ; int code = method . getStatusCode ( ) ; if ( code != 206 ) throw new IOException ( "Server does not support Range requests, code= " + code ) ; String s = method . getResponseHeader ( "Content-Length" ) . getValue ( ) ; if ( s == null ) throw new IOException ( "Server does not send Content-Length header" ) ; int readLen = Integer . parseInt ( s ) ; readLen = Math . min ( len , readLen ) ; InputStream is = method . getResponseAsStream ( ) ; readLen = copy ( is , buff , offset , readLen ) ; return readLen ; } }


Input: Write an Catalog to the HttpServletResponse return the size in bytes of the catalog written to the response . [CODESPLIT] public int writeCatalog ( HttpServletRequest req , HttpServletResponse res , Catalog cat , boolean isLocalCatalog ) throws IOException { String catHtmlAsString = convertCatalogToHtml ( cat , isLocalCatalog ) ; // Once this header is set, we know the encoding, and thus the actual // number of *bytes*, not characters, to encode res . setContentType ( ContentType . html . getContentHeader ( ) ) ; int len = ServletUtil . setResponseContentLength ( res , catHtmlAsString ) ; if ( ! req . getMethod ( ) . equals ( "HEAD" ) ) { PrintWriter writer = res . getWriter ( ) ; writer . write ( catHtmlAsString ) ; writer . flush ( ) ; } return len ; }


Input:
Write a catalog in HTML make it look like a file directory . [CODESPLIT] String convertCatalogToHtml ( Catalog cat , boolean isLocalCatalog ) { StringBuilder sb = new StringBuilder ( 10000 ) ; String uri = cat . getUriString ( ) ; if ( uri == null ) uri = cat . getName ( ) ; if ( uri == null ) uri = "unknown" ; String catname = Escape . html ( uri ) ; // Render the page header sb . append ( getHtmlDoctypeAndOpenTag ( ) ) ; // "\n" ); sb . append ( "\r\n" ) ; sb . append ( "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>" ) ; sb . append ( "<title>" ) ; //if (cat.isStatic()) //  sb.append("TdsStaticCatalog ").append(catname); // for searching //else sb . append ( "Catalog " ) . append ( catname ) ; sb . append ( "</title>\r\n" ) ; sb . append ( getTdsCatalogCssLink ( ) ) . append ( "\n" ) ; sb . append ( this . getGoogleTrackingContent ( ) ) ; sb . append ( "\r\n" ) ; sb . append ( "" ) ; sb . append ( "
" ) ; // Logo //String logoUrl = this.htmlConfig.getInstallLogoUrl(); String logoUrl = htmlConfig . prepareUrlStringForHtml ( htmlConfig . getInstallLogoUrl ( ) ) ; if ( logoUrl != null ) { sb . append ( "\n" ) ; } sb . append ( " Catalog " ) . append ( catname ) ; sb . append ( "
" ) ; sb . append ( "
" ) ; sb . append ( "
\r\n" ) ; // Render the column headings sb . append ( "
\r\n" ) ; sb . append ( "" ) ; sb . append ( "Dataset" ) ; sb . append ( "	\r\n" ) ; sb . append ( "" ) ; sb . append ( "Size" ) ; sb . append ( "	\r\n" ) ; sb . append ( "" ) ; sb . append ( "Last Modified" ) ; sb . append ( "	\r\n" ) ; sb . append ( "
" ) ; // Recursively render the datasets doDatasets ( cat , cat . getDatasetsLocal ( ) , sb , false , 0 , isLocalCatalog ) ; // Render the page footer sb . append ( "
\r\n" ) ; sb . append ( "
" ) ; appendSimpleFooter ( sb ) ; sb . append ( "\r\n" ) ; sb . append ( "\r\n" ) ; return ( sb . toString ( ) ) ; }


Input: public static final String UNIDATA_CSS [CODESPLIT] public String getUserCSS ( ) { return new StringBuilder ( ) . append ( "<link rel='stylesheet' href='" ) . append ( this . htmlConfig . prepareUrlStringForHtml ( this . htmlConfig . getPageCssUrl ( ) ) ) . append ( "' type='text/css' >" ) . toString ( ) ; }


Input:
public static final String UNIDATA_HEAD [CODESPLIT] public String getUserHead ( ) { return new StringBuilder ( ) . append ( "

\n" ) . append ( "  \n" ) . append ( "
" ) . append ( this . tdsContext . getWebappDisplayName ( ) ) . append ( "
\n" ) . append ( "

\n" ) . toString ( ) ; }


Input: If a catalog exists and is allowed ( not filtered out ) for the given path return the catalog as an Catalog . Otherwise return null . <p > The validity of the returned catalog is not guaranteed . Use Catalog . check () to check that the catalog is valid . [CODESPLIT] public Catalog getCatalog ( String path , URI baseURI ) throws IOException { if ( path == null ) return null ; String workPath = path ; if ( workPath . startsWith ( "/" ) ) workPath = workPath . substring ( 1 ) ; // Check if its a CatalogBuilder or ConfigCatalog Object dyno = makeDynamicCatalog ( workPath , baseURI ) ; if ( dyno != null ) { CatalogBuilder catBuilder ; if ( dyno instanceof CatalogBuilder ) { catBuilder = ( CatalogBuilder ) dyno ; } else { ConfigCatalog configCatalog = ( ConfigCatalog ) dyno ; catBuilder = configCatalog . makeCatalogBuilder ( ) ; // turn it back into mutable object } addGlobalServices ( catBuilder ) ; return catBuilder . makeCatalog ( ) ; } // check cache and read if needed ConfigCatalog configCatalog = ccc . get ( workPath ) ; if ( configCatalog == null ) return null ; CatalogBuilder catBuilder = configCatalog . makeCatalogBuilder ( ) ; addGlobalServices ( catBuilder ) ; return catBuilder . makeCatalog ( ) ; }


Input: barfola on the return type [CODESPLIT] private Object makeDynamicCatalog ( String path , URI baseURI ) throws IOException { boolean isLatest = path . endsWith ( "/latest.xml" ) ; // strip off the filename int pos = path . lastIndexOf ( "/" ) ; String workPath = ( pos >= 0 ) ? path . substring ( 0 , pos ) : path ; String filename = ( pos > 0 ) ? path . substring ( pos + 1 ) : path ; // now look through the data roots for a maximal match DataRootManager . DataRootMatch match = dataRootManager . findDataRootMatch ( workPath ) ; if ( match == null ) return null ; // Feature Collection if ( match . dataRoot . getFeatureCollection ( ) != null ) { InvDatasetFeatureCollection fc = featureCollectionCache . get ( match . dataRoot . getFeatureCollection ( ) ) ; if ( isLatest ) return fc . makeLatest ( match . remaining , path , baseURI ) ; else return fc . makeCatalog ( match . remaining , path , baseURI ) ; } // DatasetScan DatasetScan dscan = match . dataRoot . getDatasetScan ( ) ; if ( dscan != null ) { if ( log . isDebugEnabled ( ) ) log . debug ( "makeDynamicCatalog(): Calling DatasetScan.makeCatalogForDirectory( " + baseURI + ", " + path + ")." ) ; CatalogBuilder cat ; if ( isLatest ) cat = dscan . makeCatalogForLatest ( workPath , baseURI ) ; else cat = dscan . makeCatalogForDirectory ( workPath , baseURI ) ; if ( null == cat ) log . error ( "makeDynamicCatalog(): DatasetScan.makeCatalogForDirectory failed = " + workPath ) ; return cat ; } // CatalogScan CatalogScan catScan = match . dataRoot . getCatalogScan ( ) ; if ( catScan != null ) { if ( ! filename . equalsIgnoreCase ( CatalogScan . CATSCAN ) ) { // its an actual catalog return catScan . getCatalog ( tdsContext . getThreddsDirectory ( ) , match . remaining , filename , ccc ) ; } if ( log . isDebugEnabled ( ) ) log . debug ( "makeDynamicCatalog(): Calling CatalogScan.makeCatalogForDirectory( " + baseURI + ", " + path + ")." ) ; CatalogBuilder cat = catScan . makeCatalogFromDirectory ( tdsContext . getThreddsDirectory ( ) , match . remaining , baseURI ) ; if ( null == cat ) log . error ( "makeDynamicCatalog(): CatalogScan.makeCatalogForDirectory failed = " + workPath ) ; return cat ; } log . warn ( "makeDynamicCatalog() failed for =" + workPath + " request path= " + path ) ; return null ; }


Input: rigamorole to modify invariant catalogs ; we may need to add global services [CODESPLIT] private void addGlobalServices ( CatalogBuilder cat ) { // look for datasets that want to use global services Set < String > allServiceNames = new HashSet <> ( ) ; findServices ( cat . getDatasets ( ) , allServiceNames ) ; // all services used if ( ! allServiceNames . isEmpty ( ) ) { List < Service > servicesMissing = new ArrayList <> ( ) ; // all services missing for ( String name : allServiceNames ) { if ( cat . hasServiceInDataset ( name ) ) continue ; Service s = globalServices . findGlobalService ( name ) ; if ( s != null ) servicesMissing . add ( s ) ; } servicesMissing . forEach ( cat :: addService ) ; } // look for datasets that want to use standard services for ( DatasetBuilder node : cat . getDatasets ( ) ) { String sname = ( String ) node . getFldOrInherited ( Dataset . ServiceName ) ; String urlPath = ( String ) node . get ( Dataset . UrlPath ) ; String ftypeS = ( String ) node . getFldOrInherited ( Dataset . FeatureType ) ; if ( sname == null && urlPath != null && ftypeS != null ) { Service s = globalServices . getStandardServices ( ftypeS ) ; if ( s != null ) { node . put ( Dataset . ServiceName , s . getName ( ) ) ; cat . addService ( s ) ; } } } }


Input: initialize the HttpClient layer . [CODESPLIT] static public void init ( CredentialsProvider provider , String userAgent ) { if ( provider != null ) try { HTTPSession . setGlobalCredentialsProvider ( provider ) ; } catch ( HTTPException e ) { throw new IllegalArgumentException ( e ) ; } if ( userAgent != null ) HTTPSession . setGlobalUserAgent ( userAgent + "/NetcdfJava/HttpClient" ) ; else HTTPSession . setGlobalUserAgent ( "NetcdfJava/HttpClient" ) ; }


Input: Get the content from a url . For large returns its better to use getResponseAsStream . [CODESPLIT] @ Urlencoded @ Deprecated public static String getContentAsString ( HTTPSession session , String urlencoded ) throws IOException { HTTPSession useSession = session ; try { if ( useSession == null ) useSession = HTTPFactory . newSession ( urlencoded ) ; try ( HTTPMethod m = HTTPFactory . Get ( useSession , urlencoded ) ) { m . execute ( ) ; return m . getResponseAsString ( ) ; } } finally { if ( ( session == null ) && ( useSession != null ) ) useSession . close ( ) ; } }


Input: Put content to a url using HTTP PUT . Handles one level of 302 redirection . [CODESPLIT] public static int putContent ( String urlencoded , String content ) throws IOException { try ( HTTPMethod m = HTTPFactory . Put ( urlencoded ) ) { m . setRequestContent ( new StringEntity ( content , "application/text" , "UTF-8" ) ) ; m . execute ( ) ; int resultCode = m . getStatusCode ( ) ; // followRedirect wont work for PUT if ( resultCode == 302 ) { String redirectLocation ; Header locationHeader = m . getResponseHeader ( "location" ) ; if ( locationHeader != null ) { redirectLocation = locationHeader . getValue ( ) ; resultCode = putContent ( redirectLocation , content ) ; } } return resultCode ; } }


Input: //////////////////// [CODESPLIT] static public String getUrlContentsAsString ( String urlencoded , int maxKbytes ) throws IOException { return getUrlContentsAsString ( null , urlencoded , maxKbytes ) ; }


Input: Performs the Relatove Operation ( RelOp ) indicated by the parameter <code > oprtr< / code > on the 2 passed BaseTypes if appropriate . <p / > Obviously some type don t compare logically such as asking if String is less than a Float . For these non sensical operations and <code > InvalidOperatorException< / code > is thrown . [CODESPLIT] public static boolean op ( int oprtr , BaseType lop , BaseType rop ) throws InvalidOperatorException , RegExpException , SBHException { if ( lop instanceof DByte ) return ( op ( oprtr , ( DByte ) lop , rop ) ) ; else if ( lop instanceof DFloat32 ) return ( op ( oprtr , ( DFloat32 ) lop , rop ) ) ; else if ( lop instanceof DFloat64 ) return ( op ( oprtr , ( DFloat64 ) lop , rop ) ) ; else if ( lop instanceof DInt16 ) return ( op ( oprtr , ( DInt16 ) lop , rop ) ) ; else if ( lop instanceof DInt32 ) return ( op ( oprtr , ( DInt32 ) lop , rop ) ) ; else if ( lop instanceof DString ) return ( op ( oprtr , ( DString ) lop , rop ) ) ; else if ( lop instanceof DUInt16 ) return ( op ( oprtr , ( DUInt16 ) lop , rop ) ) ; else if ( lop instanceof DUInt32 ) return ( op ( oprtr , ( DUInt32 ) lop , rop ) ) ; else if ( lop instanceof DURL ) return ( op ( oprtr , ( DURL ) lop , rop ) ) ; else throw new InvalidOperatorException ( "Binary operations not supported for the type:" + lop . getClass ( ) ) ; }


Input: ****************************************************************************************** [CODESPLIT] private static String opErrorMsg ( int oprtr , String lop , String rop ) { switch ( oprtr ) { case LESS : return ( "Less Than (<) Operator not valid between types" + lop + "and" + rop + "." ) ; case LESS_EQL : return ( "Less Than Equal To (<=) Operator not valid between types" + lop + "and" + rop + "." ) ; case GREATER : return ( "Greater Than (>) Operator not valid between types" + lop + "and" + rop + "." ) ; case GREATER_EQL : return ( "Greater Than Equal To (>=) Operator not valid between types" + lop + "and" + rop + "." ) ; case EQUAL : return ( "Equal To (==) Operator not valid between types" + lop + "and" + rop + "." ) ; case NOT_EQUAL : return ( "Not Equal To (!=) Operator not valid between types" + lop + "and" + rop + "." ) ; case REGEXP : return ( "Regular Expression cannot beevaluated between types" + lop + "and" + rop + "." ) ; default : return ( "Unknown Operator Requested! RTFM!" ) ; } }


Input: ------------------------------------------------------------------------------------------ [CODESPLIT] private static boolean op ( int oprtr , DFloat32 lop , DByte rop ) throws InvalidOperatorException { switch ( oprtr ) { case LESS : return ( lop . getValue ( ) < rop . getValue ( ) ) ; case LESS_EQL : return ( lop . getValue ( ) <= rop . getValue ( ) ) ; case GREATER : return ( lop . getValue ( ) > rop . getValue ( ) ) ; case GREATER_EQL : return ( lop . getValue ( ) >= rop . getValue ( ) ) ; case EQUAL : return ( lop . getValue ( ) == rop . getValue ( ) ) ; case NOT_EQUAL : return ( lop . getValue ( ) != rop . getValue ( ) ) ; case REGEXP : throw new InvalidOperatorException ( opErrorMsg ( oprtr , lop . getTypeName ( ) , rop . getTypeName ( ) ) ) ; default : throw new InvalidOperatorException ( "Unknown Operator Requested! RTFM!" ) ; } }


Input: ------------------------------------------------------------------------------------------ [CODESPLIT] private static boolean op ( int oprtr , DUInt16 lop , DByte rop ) throws InvalidOperatorException { int lval = ( ( int ) lop . getValue ( ) ) & 0xFFFF ; switch ( oprtr ) { case LESS : return ( lval < rop . getValue ( ) ) ; case LESS_EQL : return ( lval <= rop . getValue ( ) ) ; case GREATER : return ( lval > rop . getValue ( ) ) ; case GREATER_EQL : return ( lval >= rop . getValue ( ) ) ; case EQUAL : return ( lval == rop . getValue ( ) ) ; case NOT_EQUAL : return ( lval != rop . getValue ( ) ) ; case REGEXP : throw new InvalidOperatorException ( opErrorMsg ( oprtr , lop . getTypeName ( ) , rop . getTypeName ( ) ) ) ; default : throw new InvalidOperatorException ( "Unknown Operator Requested! RTFM!" ) ; } }


Input: Capabilities processors [CODESPLIT] @ Override protected void doFavicon ( String icopath , DapContext cxt ) throws IOException { DapRequest drq = ( DapRequest ) cxt . get ( DapRequest . class ) ; String favfile = getResourcePath ( drq , icopath ) ; if ( favfile != null ) { try ( FileInputStream fav = new FileInputStream ( favfile ) ; ) { byte [ ] content = DapUtil . readbinaryfile ( fav ) ; OutputStream out = drq . getOutputStream ( ) ; out . write ( content ) ; } } }


Input: Isolate front page builder so we can override if desired for testing . [CODESPLIT] protected FrontPage getFrontPage ( DapRequest drq , DapContext cxt ) throws DapException { if ( this . defaultroots == null ) { // Figure out the directory containing // the files to display. String pageroot ; pageroot = getResourcePath ( drq , "" ) ; if ( pageroot == null ) throw new DapException ( "Cannot locate resources directory" ) ; this . defaultroots = new ArrayList <> ( ) ; this . defaultroots . add ( new Root ( "testfiles" , pageroot ) ) ; } return new FrontPage ( this . defaultroots , drq ) ; }


Input: /////////////////////////////////////////////////////////////////////// [CODESPLIT] private String makeCollectionShortName ( String collectionName ) { String topCollectionName = config . collectionName ; if ( collectionName . equals ( topCollectionName ) ) return topCollectionName ; if ( collectionName . startsWith ( topCollectionName ) ) { return name + collectionName . substring ( topCollectionName . length ( ) ) ; } return collectionName ; }


Input: this catalog lists the individual files comprising the collection . [CODESPLIT] protected void addFileDatasets ( DatasetBuilder parent , String parentPath , GribCollectionImmutable fromGc ) throws IOException { DatasetBuilder filesParent = new DatasetBuilder ( parent ) ; filesParent . setName ( "Raw Files" ) ; filesParent . addServiceToCatalog ( downloadService ) ; ThreddsMetadata tmi = filesParent . getInheritableMetadata ( ) ; tmi . set ( Dataset . ServiceName , downloadService . getName ( ) ) ; parent . addDataset ( filesParent ) ; List < MFile > mfiles = new ArrayList <> ( fromGc . getFiles ( ) ) ; Collections . sort ( mfiles ) ; // if not increasing (i.e. we WANT newest file listed first), reverse sort if ( ! this . config . getSortFilesAscending ( ) ) { Collections . reverse ( mfiles ) ; } for ( MFile mfile : mfiles ) { DatasetBuilder ds = new DatasetBuilder ( parent ) ; ds . setName ( mfile . getName ( ) ) ; String lpath = parentPath + "/" + FILES + "/" + mfile . getName ( ) ; ds . put ( Dataset . UrlPath , lpath ) ; ds . put ( Dataset . Id , lpath ) ; ds . put ( Dataset . DataSize , mfile . getLength ( ) ) ; if ( mfile . getLastModified ( ) > 0 ) { CalendarDate cdate = CalendarDate . of ( mfile . getLastModified ( ) ) ; ds . put ( Dataset . Dates , new DateType ( cdate ) . setType ( "modified" ) ) ; } filesParent . addDataset ( ds ) ; } }


Input: see top javadoc for possible URLs [CODESPLIT] @ Override public CatalogBuilder makeCatalog ( String match , String reqPath , URI catURI ) throws IOException { StateGrib localState = ( StateGrib ) checkState ( ) ; if ( localState == null ) return null ; // not ready yet maybe if ( localState . gribCollection == null ) return null ; // not ready yet maybe try { // case 0 if ( ( match == null ) || ( match . length ( ) == 0 ) ) { return makeCatalogTop ( catURI , localState ) ; // top catalog : uses state.top previously made in checkState() } // case 1 if ( localState . gribCollection instanceof PartitionCollectionImmutable ) { String [ ] paths = match . split ( "/" ) ; PartitionCollectionImmutable pc = ( PartitionCollectionImmutable ) localState . gribCollection ; return makeCatalogFromPartition ( pc , paths , 0 , catURI ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; logger . error ( "Error making catalog for " + configPath , e ) ; } return null ; }


Input: /////////////////////////////////// [CODESPLIT] @ Override protected DatasetBuilder makeDatasetTop ( URI catURI , State state ) throws IOException { StateGrib localState = ( StateGrib ) state ; return makeDatasetFromCollection ( catURI , true , null , null , localState . gribCollection ) ; }


Input: LOOK how come we arent using MetadataExtractor ?? [CODESPLIT] private ThreddsMetadata . GeospatialCoverage extractGeospatial ( GribCollectionImmutable . GroupGC group ) { GdsHorizCoordSys gdsCoordSys = group . getGdsHorizCoordSys ( ) ; LatLonRect llbb = GridCoordSys . getLatLonBoundingBox ( gdsCoordSys . proj , gdsCoordSys . getStartX ( ) , gdsCoordSys . getStartY ( ) , gdsCoordSys . getEndX ( ) , gdsCoordSys . getEndY ( ) ) ; double dx = 0.0 , dy = 0.0 ; if ( gdsCoordSys . isLatLon ( ) ) { dx = Math . abs ( gdsCoordSys . dx ) ; dy = Math . abs ( gdsCoordSys . dy ) ; } return new ThreddsMetadata . GeospatialCoverage ( llbb , null , dx , dy ) ; }


Input: returns visitor . obtain () either a GridDataset or a NetcdfDataset [CODESPLIT] private Object findDataset ( String matchPath , GribCollectionImmutable topCollection , DatasetCreator visit ) throws IOException { String [ ] paths = matchPath . split ( "/" ) ; List < String > pathList = ( paths . length < 1 ) ? new ArrayList <> ( ) : Arrays . asList ( paths ) ; DatasetAndGroup dg = findDatasetAndGroup ( pathList , topCollection ) ; if ( dg != null ) return visit . obtain ( topCollection , dg . ds , dg . group ) ; if ( ! ( topCollection instanceof PartitionCollectionImmutable ) ) return null ; PartitionCollectionImmutable pc = ( PartitionCollectionImmutable ) topCollection ; return findDatasetPartition ( visit , pc , pathList ) ; }


Input: / * case 0 : path / dataset ( dataset = ) // single dataset case 1 : path / dataset ( dataset = BEST TWOD TP ) // single group case 2 : path / dataset / groupName // dataset with group case 3 : path / groupName // single dataset not sure this is actually used ?? [CODESPLIT] private DatasetAndGroup findDatasetAndGroup ( List < String > paths , GribCollectionImmutable gc ) { if ( paths . size ( ) < 1 || paths . get ( 0 ) . length ( ) == 0 ) { // case 0: use first dataset,group in the collection GribCollectionImmutable . Dataset ds = gc . getDataset ( 0 ) ; GribCollectionImmutable . GroupGC dg = ds . getGroup ( 0 ) ; return new DatasetAndGroup ( ds , dg ) ; } GribCollectionImmutable . Dataset ds = getSingleDatasetOrByTypeName ( gc , paths . get ( 0 ) ) ; if ( ds == null ) return null ; boolean isSingleGroup = ds . getGroupsSize ( ) == 1 ; if ( isSingleGroup ) { GribCollectionImmutable . GroupGC g = ds . getGroup ( 0 ) ; // case 1 return new DatasetAndGroup ( ds , g ) ; } // otherwise last component is group name String groupName = ( paths . size ( ) == 1 ) ? paths . get ( 0 ) : paths . get ( 1 ) ; // case 3 else case 2 GribCollectionImmutable . GroupGC g = ds . findGroupById ( groupName ) ; if ( g != null ) return new DatasetAndGroup ( ds , g ) ; return null ; }


Input: kinda kludgey but trying not keep URLs stable [CODESPLIT] public GribCollectionImmutable . Dataset getSingleDatasetOrByTypeName ( GribCollectionImmutable gc , String typeName ) { if ( gc . getDatasets ( ) . size ( ) == 1 ) return gc . getDataset ( 0 ) ; for ( GribCollectionImmutable . Dataset ds : gc . getDatasets ( ) ) if ( ds . getType ( ) . toString ( ) . equalsIgnoreCase ( typeName ) ) return ds ; return null ; }


Input: cannot do approx equals and be consistent with hashCode so make seperate call [CODESPLIT] public boolean nearlyEquals ( VertCoordValue other ) { return Misc . nearlyEquals ( value1 , other . value1 ) && Misc . nearlyEquals ( value2 , other . value2 ) ; }


Input: Factory method for constructing an identifier from a name plural and symbol . [CODESPLIT] public static UnitID newUnitID ( final String name , final String plural , final String symbol ) { UnitID id ; try { id = name == null ? new UnitSymbol ( symbol ) : UnitName . newUnitName ( name , plural , symbol ) ; } catch ( final NameException e ) { id = null ; // can't happen } return id ; }


Input: Parse an attribute spec [CODESPLIT] public static GradsAttribute parseAttribute ( String attrSpec ) { String [ ] toks = attrSpec . split ( "\\s+" ) ; StringBuffer buf = new StringBuffer ( ) ; for ( int i = 4 ; i < toks . length ; i ++ ) { buf . append ( toks [ i ] ) ; buf . append ( " " ) ; } // toks[0] is "@" return new GradsAttribute ( toks [ 1 ] , toks [ 2 ] , toks [ 3 ] , buf . toString ( ) . trim ( ) ) ; }


Input:
read the header of input file and parsing the NOWRAD part [CODESPLIT] int readTop ( ucar . unidata . io . RandomAccessFile raf ) throws IOException { int pos = 0 ; // long     actualSize = 0;
 raf . seek ( pos ) ; int readLen = 35 ; // Read in the contents of the NEXRAD Level III product head
 byte [ ] b = new byte [ readLen ] ; int rc = raf . read ( b ) ; if ( rc != readLen ) { return 0 ; } // check
 if ( ( convertunsignedByte2Short ( b [ 0 ] ) != 0x00 ) || ( convertunsignedByte2Short ( b [ 1 ] ) != 0xF0 ) || ( convertunsignedByte2Short ( b [ 2 ] ) != 0x09 ) ) { return 0 ; } String pidd = new String ( b , 15 , 5 , CDM . utf8Charset ) ; if ( pidd . contains ( "NOWRA" ) || pidd . contains ( "USRAD" ) || pidd . contains ( "NEX" ) ) { return 1 ; } else { return 0 ; } }