Input: only one message per CoordinatePartitionUnionizer instance [CODESPLIT] public void addCoords ( List < Coordinate > coords , PartitionCollectionMutable . Partition part ) { Coordinate runtime = null ; for ( Coordinate coord : coords ) { switch ( coord . getType ( ) ) { case runtime : CoordinateRuntime rtime = ( CoordinateRuntime ) coord ; if ( runtimeBuilder == null ) runtimeBuilder = new CoordinateRuntime . Builder2 ( rtime . getTimeUnits ( ) ) ; runtimeBuilder . addAll ( coord ) ; runtime = coord ; if ( debugPartitionErrors && ! duplicateRuntimeMessage && part != null ) testDuplicateRuntime ( rtime , part ) ; break ; case time : CoordinateTime time = ( CoordinateTime ) coord ; if ( timeBuilder == null ) timeBuilder = new CoordinateTime . Builder2 ( coord . getCode ( ) , time . getTimeUnit ( ) , time . getRefDate ( ) ) ; timeBuilder . addAll ( coord ) ; break ; case timeIntv : CoordinateTimeIntv timeIntv = ( CoordinateTimeIntv ) coord ; if ( timeIntvBuilder == null ) timeIntvBuilder = new CoordinateTimeIntv . Builder2 ( null , coord . getCode ( ) , timeIntv . getTimeUnit ( ) , timeIntv . getRefDate ( ) ) ; timeIntvBuilder . addAll ( intervalFilter ( ( CoordinateTimeIntv ) coord ) ) ; break ; case time2D : CoordinateTime2D time2D = ( CoordinateTime2D ) coord ; if ( time2DBuilder == null ) time2DBuilder = new CoordinateTime2DUnionizer ( time2D . isTimeInterval ( ) , time2D . getTimeUnit ( ) , coord . getCode ( ) , false , logger ) ; time2DBuilder . addAll ( time2D ) ; // debug CoordinateRuntime runtimeFrom2D = time2D . getRuntimeCoordinate ( ) ; if ( ! runtimeFrom2D . equals ( runtime ) ) logger . warn ( "HEY CoordinateUnionizer runtimes not equal" ) ; break ; case ens : if ( ensBuilder == null ) ensBuilder = new CoordinateEns . Builder2 ( coord . getCode ( ) ) ; ensBuilder . addAll ( coord ) ; break ; case vert : CoordinateVert vertCoord = ( CoordinateVert ) coord ; if ( vertBuilder == null ) vertBuilder = new CoordinateVert . Builder2 ( coord . getCode ( ) , vertCoord . getVertUnit ( ) ) ; vertBuilder . addAll ( coord ) ; break ; } } }


Input: Split a <Value > ... < / Value > into its component strings . Generally type checking is not performed . String quotes are obeyed and backslash escapes are removed . [CODESPLIT] static public List < String > collectValues ( String text ) throws ParseException { List < String > values = new ArrayList < String > ( ) ; StringBuffer buf = new StringBuffer ( ) ; text = text . trim ( ) + ' ' ; int i = 0 ; for ( ; ; ) { char c = text . charAt ( i ++ ) ; if ( c == ' ' ) break ; // eos if ( c <= ' ' || c == 127 ) // whitespace continue ; if ( c == ' ' ) { // collect char constant c = text . charAt ( i ++ ) ; if ( c == ' ' ) throw new ParseException ( "Malformed char constant: no final '''" ) ; else if ( i >= 128 ) throw new ParseException ( "Illegal char constant: " + ( int ) c ) ; buf . append ( c ) ; values . add ( buf . toString ( ) ) ; buf . setLength ( 0 ) ; } else if ( c == ' ' ) { // collect quoted string for ( ; ; ) { c = text . charAt ( i ++ ) ; if ( c == ' ' ) { i -- ; break ; } if ( c == ' ' ) { c = text . charAt ( i ++ ) ; } else if ( c == ' ' ) break ; buf . append ( c ) ; } if ( c == ' ' ) throw new ParseException ( "Malformed string: no final '\"'" ) ; values . add ( buf . toString ( ) ) ; buf . setLength ( 0 ) ; } else { // collect upto next whitespace or eos do { if ( c == ' ' ) { c = text . charAt ( i ++ ) ; } buf . append ( c ) ; c = text . charAt ( i ++ ) ; } while ( c > ' ' && c != 127 ) ; values . add ( buf . toString ( ) ) ; buf . setLength ( 0 ) ; if ( c == 0 ) i -- ; // So we never move past the trailing eol } } return values ; }


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


Input: all the work is here so can be called recursively [CODESPLIT] private Array readData ( ucar . nc2 . Variable v2 , long dataPos , int [ ] origin , int [ ] shape , int [ ] stride ) throws IOException , InvalidRangeException { // long length = myRaf.length(); raf . seek ( dataPos ) ; Vinfo vi = ( Vinfo ) v2 . getSPobject ( ) ; int data_size = vi . vsize ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; Array array ; if ( vi . classType == DataType . BYTE . getPrimitiveClassType ( ) ) { array = Array . factory ( DataType . BYTE , v2 . getShape ( ) , data ) ; } else if ( vi . classType == DataType . SHORT . getPrimitiveClassType ( ) ) { EndianByteBuffer byteBuff = new EndianByteBuffer ( data , vi . byteOrder ) ; short [ ] sdata = byteBuff . getShortArray ( ) ; //for(int i=0; i<sdata.length; i++){ //	System.out.println(sdata[i]); //} array = Array . factory ( DataType . SHORT , v2 . getShape ( ) , sdata ) ; } else if ( vi . classType == DataType . INT . getPrimitiveClassType ( ) ) { EndianByteBuffer byteBuff = new EndianByteBuffer ( data , vi . byteOrder ) ; short [ ] idata = byteBuff . getShortArray ( ) ; array = Array . factory ( DataType . INT , v2 . getShape ( ) , idata ) ; } else { throw new UnsupportedEncodingException ( ) ; } return array . sectionNoReduce ( origin , shape , stride ) ; }


Input: for the compressed data read all out into a array and then parse into requested [CODESPLIT] public Array readCompressedData ( ucar . nc2 . Variable v2 , long dataPos , int [ ] origin , int [ ] shape , int [ ] stride ) throws IOException , InvalidRangeException { long length = raf . length ( ) ; raf . seek ( dataPos ) ; int data_size = ( int ) ( length - dataPos ) ; byte [ ] data = new byte [ data_size ] ; raf . readFully ( data ) ; ByteArrayInputStream ios = new ByteArrayInputStream ( data ) ; BufferedImage image = javax . imageio . ImageIO . read ( ios ) ; Raster raster = image . getData ( ) ; DataBuffer db = raster . getDataBuffer ( ) ; if ( db instanceof DataBufferByte ) { DataBufferByte dbb = ( DataBufferByte ) db ; byte [ ] udata = dbb . getData ( ) ; Array array = Array . factory ( DataType . BYTE , v2 . getShape ( ) , udata ) ; v2 . setCachedData ( array , false ) ; return array . sectionNoReduce ( origin , shape , stride ) ; } return null ; }


Input:
/ * * Name : GetGiniLine * * Purpose : Extract a line of data from a GINI image * * Parameters : * buf - buffer containing image data * * Returns : * SUCCESS == 1 * FAILURE == 0 * * [CODESPLIT] private byte [ ] getGiniLine ( int nx , int ny , long doff , int lineNumber , int len , int stride ) throws IOException { byte [ ] data = new byte [ len ] ; /*
    ** checking image file and set location of first line in file
    */ raf . seek ( doff ) ; if ( lineNumber >= ny ) throw new IOException ( "Try to access the file at line number= " + lineNumber + " larger then last line number = " + ny ) ; /*
    ** Read in the requested line
    */ int offset = lineNumber * nx + ( int ) doff ; //myRaf.seek ( offset ); for ( int i = 0 ; i < len ; i ++ ) { raf . seek ( offset ) ; data [ i ] = raf . readByte ( ) ; offset = offset + stride ; //myRaf.seek(offset); } //myRaf.read( data, 0, len); return data ; }


Input:
some weird adjustment for la1 and la2 . [CODESPLIT] public void setGaussianLats ( int nparallels , float la1 , float la2 ) { log . debug ( "la1 {}, la2 {}" , la1 , la2 ) ; if ( this . gaussLats != null ) throw new RuntimeException ( "Cant modify GdsHorizCoordSys" ) ; int nlats = ( 2 * nparallels ) ; GaussianLatitudes gaussLats = GaussianLatitudes . factory ( nlats ) ; int bestStartIndex = 0 , bestEndIndex = 0 ; double bestStartDiff = Double . MAX_VALUE ; double bestEndDiff = Double . MAX_VALUE ; for ( int i = 0 ; i < nlats ; i ++ ) { double diff = Math . abs ( gaussLats . latd [ i ] - la1 ) ; if ( diff < bestStartDiff ) { bestStartDiff = diff ; bestStartIndex = i ; } diff = Math . abs ( gaussLats . latd [ i ] - la2 ) ; if ( diff < bestEndDiff ) { bestEndDiff = diff ; bestEndIndex = i ; } } log . debug ( "first pass: bestStartIndex {}, bestEndIndex {}" , bestStartIndex , bestEndIndex ) ; if ( Math . abs ( bestEndIndex - bestStartIndex ) + 1 != nyRaw ) { log . warn ( "GRIB gaussian lats: NP != NY, use NY" ) ; // see email from Toussaint@dkrz.de datafil:
 nlats = nyRaw ; gaussLats = GaussianLatitudes . factory ( nlats ) ; bestStartIndex = 0 ; bestEndIndex = nyRaw - 1 ; } boolean goesUp = bestEndIndex > bestStartIndex ; log . debug ( "bestStartIndex {}, bestEndIndex {}, goesUp {}" , bestStartIndex , bestEndIndex , goesUp ) ; // create the data
 int useIndex = bestStartIndex ; float [ ] data = new float [ nyRaw ] ; float [ ] gaussw = new float [ nyRaw ] ; for ( int i = 0 ; i < nyRaw ; i ++ ) { data [ i ] = ( float ) gaussLats . latd [ useIndex ] ; gaussw [ i ] = ( float ) gaussLats . gaussw [ useIndex ] ; log . trace ( "i {}, useIndex {}, data {}, gaussw {}" , i , useIndex , data [ i ] , gaussw [ i ] ) ; if ( goesUp ) { useIndex ++ ; } else { useIndex -- ; } } this . gaussLats = Array . factory ( DataType . FLOAT , new int [ ] { nyRaw } , data ) ; this . gaussw = Array . factory ( DataType . FLOAT , new int [ ] { nyRaw } , gaussw ) ; }


Input:
_more_ [CODESPLIT] protected void init ( double a , double f , int zone , boolean isNorth ) { A = a ; F = 1.0 / f ; // F is flattening
 this . axlon0_deg = ( zone * 6 - 183 ) ; this . axlon0 = axlon0_deg * RADIANS_PER_DEGREE ; double polx2b , polx3b , polx4b , polx5b ; //  Create the ERM constants.
 Eps2 = ( F ) * ( 2.0 - F ) ; Eps25 = .25 * ( Eps2 ) ; Epps2 = ( Eps2 ) / ( 1.0 - Eps2 ) ; polx2b = Eps2 + 1.0 / 4.0 * Math . pow ( Eps2 , 2 ) + 15.0 / 128.0 * Math . pow ( Eps2 , 3 ) - 455.0 / 4096.0 * Math . pow ( Eps2 , 4 ) ; polx2b = 3.0 / 8.0 * polx2b ; polx3b = Math . pow ( Eps2 , 2 ) + 3.0 / 4.0 * Math . pow ( Eps2 , 3 ) - 77.0 / 128.0 * Math . pow ( Eps2 , 4 ) ; polx3b = 15.0 / 256.0 * polx3b ; polx4b = Math . pow ( Eps2 , 3 ) - 41.0 / 32.0 * Math . pow ( Eps2 , 4 ) ; polx4b = polx4b * 35.0 / 3072.0 ; polx5b = - 315.0 / 131072.0 * Math . pow ( Eps2 , 4 ) ; poly1b = 1.0 - ( 1.0 / 4.0 * Eps2 ) - ( 3.0 / 64.0 * Math . pow ( Eps2 , 2 ) ) - ( 5.0 / 256.0 * Math . pow ( Eps2 , 3 ) ) - ( 175.0 / 16384.0 * Math . pow ( Eps2 , 4 ) ) ; poly2b = polx2b * - 2.0 + polx3b * 4.0 - polx4b * 6.0 + polx5b * 8.0 ; poly3b = polx3b * - 8.0 + polx4b * 32.0 - polx5b * 80.0 ; poly4b = polx4b * - 32.0 + polx5b * 192.0 ; poly5b = polx5b * - 128.0 ; }


Input: Parse a section specification String . These have the form : <pre > section specification : = selector | selector . selector selector : = varName [ ( dims ) ] varName : = ESCAPED_STRING <p / > dims : = dim | dim dims dim : = : | slice | start : end | start : end : stride slice : = INTEGER start : = INTEGER stride : = INTEGER end : = INTEGER ESCAPED_STRING : must escape characters = . ( < / pre > <p / > Nonterminals are in lower case terminals are in upper case literals are in single quotes . Optional components are enclosed between square braces [ and ] . [CODESPLIT] public static ParsedSectionSpec parseVariableSection ( NetcdfFile ncfile , String variableSection ) throws InvalidRangeException { List < String > tokes = EscapeStrings . tokenizeEscapedName ( variableSection ) ; if ( tokes . size ( ) == 0 ) throw new IllegalArgumentException ( "empty sectionSpec = " + variableSection ) ; String selector = tokes . get ( 0 ) ; ParsedSectionSpec outerV = parseVariableSelector ( ncfile , selector ) ; // parse each selector, find the inner variable ParsedSectionSpec current = outerV ; for ( int i = 1 ; i < tokes . size ( ) ; i ++ ) { selector = tokes . get ( i ) ; current . child = parseVariableSelector ( current . v , selector ) ; current = current . child ; } return outerV ; }


Input: parse variable name and index selector out of the selector String . variable name must be escaped [CODESPLIT] private static ParsedSectionSpec parseVariableSelector ( Object parent , String selector ) throws InvalidRangeException { String varNameEsc , indexSelect = null ; int pos1 = EscapeStrings . indexOf ( selector , ' ' ) ; if ( pos1 < 0 ) { // no index varNameEsc = selector ; } else { varNameEsc = selector . substring ( 0 , pos1 ) ; int pos2 = selector . indexOf ( ' ' , pos1 + 1 ) ; indexSelect = selector . substring ( pos1 , pos2 ) ; } if ( debugSelector ) System . out . println ( " parseVariableSection <" + selector + "> = <" + varNameEsc + ">, <" + indexSelect + ">" ) ; Variable v = null ; if ( parent instanceof NetcdfFile ) { // then varNameEsc = varFullNameEsc (i.e. includes groups) NetcdfFile ncfile = ( NetcdfFile ) parent ; v = ncfile . findVariable ( varNameEsc ) ; } else if ( parent instanceof Structure ) { // then varNameEsc = memberNameEsc (i.e. includes groups) Structure s = ( Structure ) parent ; v = s . findVariable ( NetcdfFile . makeNameUnescaped ( varNameEsc ) ) ; // s.findVariable wants unescaped version } if ( v == null ) throw new IllegalArgumentException ( " cant find variable: " + varNameEsc + " in selector=" + selector ) ; if ( v . getDataType ( ) == DataType . SEQUENCE ) indexSelect = null ; // ignore whatever was sent // get the selected Ranges, or all, and add to the list Section section ; if ( indexSelect != null ) { section = new Section ( indexSelect ) ; section = Section . fill ( section , v . getShape ( ) ) ; // Check section has no nulls, set from shape array. } else { section = v . getShapeAsSection ( ) ; // all } return new ParsedSectionSpec ( v , section ) ; }


Input: Make section specification String from a range list for a Variable . [CODESPLIT] public static String makeSectionSpecString ( Variable v , List < Range > ranges ) throws InvalidRangeException { StringBuilder sb = new StringBuilder ( ) ; makeSpec ( sb , v , ranges ) ; return sb . toString ( ) ; }


Input: Is the point ( lat lon ) contained in the ( row col ) rectangle ? [CODESPLIT] private boolean containsOld ( double wantLat , double wantLon , int [ ] rectIndex ) { rectIndex [ 0 ] = Math . max ( Math . min ( rectIndex [ 0 ] , nrows - 1 ) , 0 ) ; rectIndex [ 1 ] = Math . max ( Math . min ( rectIndex [ 1 ] , ncols - 1 ) , 0 ) ; int row = rectIndex [ 0 ] ; int col = rectIndex [ 1 ] ; if ( debug ) System . out . printf ( " (%d,%d) contains (%f,%f) in (lat=%f %f) (lon=%f %f) ?%n" , rectIndex [ 0 ] , rectIndex [ 1 ] , wantLat , wantLon , latEdge . get ( row , col ) , latEdge . get ( row + 1 , col ) , lonEdge . get ( row , col ) , lonEdge . get ( row , col + 1 ) ) ; if ( wantLat < latEdge . get ( row , col ) ) return false ; if ( wantLat > latEdge . get ( row + 1 , col ) ) return false ; if ( wantLon < lonEdge . get ( row , col ) ) return false ; if ( wantLon > lonEdge . get ( row , col + 1 ) ) return false ; return true ; }


Input: / * http : // mathforum . org / library / drmath / view / 54386 . html [CODESPLIT] private boolean contains ( double wantLat , double wantLon , int [ ] rectIndex ) { rectIndex [ 0 ] = Math . max ( Math . min ( rectIndex [ 0 ] , nrows - 1 ) , 0 ) ; rectIndex [ 1 ] = Math . max ( Math . min ( rectIndex [ 1 ] , ncols - 1 ) , 0 ) ; int row = rectIndex [ 0 ] ; int col = rectIndex [ 1 ] ; double x1 = lonEdge . get ( row , col ) ; double y1 = latEdge . get ( row , col ) ; double x2 = lonEdge . get ( row , col + 1 ) ; double y2 = latEdge . get ( row , col + 1 ) ; double x3 = lonEdge . get ( row + 1 , col + 1 ) ; double y3 = latEdge . get ( row + 1 , col + 1 ) ; double x4 = lonEdge . get ( row + 1 , col ) ; double y4 = latEdge . get ( row + 1 , col ) ; // must all have same determinate sign boolean sign = detIsPositive ( x1 , y1 , x2 , y2 , wantLon , wantLat ) ; if ( sign != detIsPositive ( x2 , y2 , x3 , y3 , wantLon , wantLat ) ) return false ; if ( sign != detIsPositive ( x3 , y3 , x4 , y4 , wantLon , wantLat ) ) return false ; if ( sign != detIsPositive ( x4 , y4 , x1 , y1 , wantLon , wantLat ) ) return false ; return true ; }


Input: / * choose x y such that ( matrix multiply ) : [CODESPLIT] private boolean jump2 ( double wantLat , double wantLon , int [ ] rectIndex ) { int row = Math . max ( Math . min ( rectIndex [ 0 ] , nrows - 1 ) , 0 ) ; int col = Math . max ( Math . min ( rectIndex [ 1 ] , ncols - 1 ) , 0 ) ; double lat = latEdge . get ( row , col ) ; double lon = lonEdge . get ( row , col ) ; double diffLat = wantLat - lat ; double diffLon = wantLon - lon ; double dlatdy = latEdge . get ( row + 1 , col ) - lat ; double dlatdx = latEdge . get ( row , col + 1 ) - lat ; double dlondx = lonEdge . get ( row , col + 1 ) - lon ; double dlondy = lonEdge . get ( row + 1 , col ) - lon ; // solve for dlon double dx = ( diffLon - dlondy * diffLat / dlatdy ) / ( dlondx - dlatdx * dlondy / dlatdy ) ; // double dy =  (diffLat - dlatdx * diffLon / dlondx) / (dlatdy - dlatdx * dlondy / dlondx); double dy = ( diffLat - dlatdx * dx ) / dlatdy ; if ( debug ) System . out . printf ( "   jump from %d %d (dlondx=%f dlondy=%f dlatdx=%f dlatdy=%f) (diffLat,Lon=%f %f) (deltalat,Lon=%f %f)" , row , col , dlondx , dlondy , dlatdx , dlatdy , diffLat , diffLon , dy , dx ) ; int drow = ( int ) Math . round ( dy ) ; int dcol = ( int ) Math . round ( dx ) ; if ( ( drow == 0 ) && ( dcol == 0 ) ) { if ( debug ) System . out . printf ( "%n   incr:" ) ; return incr ( wantLat , wantLon , rectIndex ) ; } else { rectIndex [ 0 ] = Math . max ( Math . min ( row + drow , nrows - 1 ) , 0 ) ; rectIndex [ 1 ] = Math . max ( Math . min ( col + dcol , ncols - 1 ) , 0 ) ; if ( debug ) System . out . printf ( " to (%d %d)%n" , rectIndex [ 0 ] , rectIndex [ 1 ] ) ; if ( ( row == rectIndex [ 0 ] ) && ( col == rectIndex [ 1 ] ) ) return false ; // nothing has changed } return true ; }


Input: we think its got to be in one of the 9 boxes around rectIndex [CODESPLIT] private boolean box9 ( double wantLat , double wantLon , int [ ] rectIndex ) { int row = rectIndex [ 0 ] ; int minrow = Math . max ( row - 1 , 0 ) ; int maxrow = Math . min ( row + 1 , nrows ) ; int col = rectIndex [ 1 ] ; int mincol = Math . max ( col - 1 , 0 ) ; int maxcol = Math . min ( col + 1 , ncols ) ; if ( debug ) System . out . printf ( "%n   box9:" ) ; for ( int i = minrow ; i <= maxrow ; i ++ ) for ( int j = mincol ; j <= maxcol ; j ++ ) { rectIndex [ 0 ] = i ; rectIndex [ 1 ] = j ; if ( contains ( wantLat , wantLon , rectIndex ) ) return true ; } return false ; }


Input: Make the <code > CoordinateTransform< / code > from the dataset [CODESPLIT] public VerticalCT makeCoordinateTransform ( NetcdfDataset ds , AttributeContainer ctv ) { String formula_terms = getFormula ( ctv ) ; if ( null == formula_terms ) return null ; // parse the formula string String [ ] values = parseFormula ( formula_terms , "a b orog" ) ; if ( values == null ) return null ; a = values [ 0 ] ; b = values [ 1 ] ; orog = values [ 2 ] ; VerticalCT rs = new VerticalCT ( "AtmHybridHeight_Transform_" + ctv . getName ( ) , getTransformName ( ) , VerticalCT . Type . HybridHeight , this ) ; rs . addParameter ( new Parameter ( "standard_name" , getTransformName ( ) ) ) ; rs . addParameter ( new Parameter ( "formula_terms" , formula_terms ) ) ; rs . addParameter ( new Parameter ( "formula" , "height(x,y,z) = a(z) + b(z)*orog(x,y)" ) ) ; if ( ! addParameter ( rs , HybridHeight . A , ds , a ) ) { return null ; } if ( ! addParameter ( rs , HybridHeight . B , ds , b ) ) { return null ; } if ( ! addParameter ( rs , HybridHeight . OROG , ds , orog ) ) { return null ; } return rs ; }


Input: Calling close will force the method to close and will force any open stream to terminate . If the session is local Then that too will be closed . [CODESPLIT] public synchronized void close ( ) { if ( closed ) return ; // recursive calls ok closed = true ; // mark as closed to prevent recursive calls if ( methodstream != null ) { try { this . methodstream . close ( ) ; // May recursr } catch ( IOException ioe ) { /*failure is ok*/ } this . methodstream = null ; } // Force release underlying connection back to the connection manager if ( this . lastresponse != null ) { if ( false ) { try { try { // Attempt to keep connection alive by consuming its remaining content EntityUtils . consume ( this . lastresponse . getEntity ( ) ) ; } finally { HttpClientUtils . closeQuietly ( this . lastresponse ) ; // Paranoia } } catch ( IOException ignore ) { /*ignore*/ } } else HttpClientUtils . closeQuietly ( this . lastresponse ) ; this . lastresponse = null ; } if ( session != null ) { session . removeMethod ( this ) ; if ( localsession ) { session . close ( ) ; session = null ; } } this . lastrequest = null ; }


Input: Create a request add headers and content then send to HTTPSession to do the bulk of the work . [CODESPLIT] public int execute ( ) throws HTTPException { HttpResponse res = executeRaw ( ) ; if ( res != null ) return res . getStatusLine ( ) . getStatusCode ( ) ; else throw new HTTPException ( "HTTPMethod.execute: null response" ) ; }


Input: debug only [CODESPLIT] public HttpResponse executeRaw ( ) throws HTTPException { if ( this . closed ) throw new IllegalStateException ( "HTTPMethod: attempt to execute closed method" ) ; if ( this . executed ) throw new IllegalStateException ( "HTTPMethod: attempt to re-execute method" ) ; this . executed = true ; if ( this . methodurl == null ) throw new HTTPException ( "HTTPMethod: no url specified" ) ; if ( ! localsession && ! sessionCompatible ( this . methodurl ) ) throw new HTTPException ( "HTTPMethod: session incompatible url: " + this . methodurl ) ; // Capture the current state of the parent HTTPSession; never to be modified in this class this . settings = session . mergedSettings ( ) ; try { // add range header if ( this . range != null ) { this . headers . put ( "Range" , "bytes=" + range [ 0 ] + "-" + range [ 1 ] ) ; range = null ; } RequestBuilder rb = getRequestBuilder ( ) ; setcontent ( rb ) ; setheaders ( rb , this . headers ) ; this . lastrequest = buildRequest ( rb , this . settings ) ; AuthScope methodscope = HTTPAuthUtil . uriToAuthScope ( this . methodurl ) ; AuthScope target = HTTPAuthUtil . authscopeUpgrade ( session . getSessionScope ( ) , methodscope ) ; // AFAIK, targethost, httpclient, rb, and session // contain non-overlapping info => we cannot derive one // from any of the others. HttpHost targethost = HTTPAuthUtil . authscopeToHost ( target ) ; HttpClientBuilder cb = HttpClients . custom ( ) ; configClient ( cb , this . settings ) ; session . setAuthenticationAndProxy ( cb ) ; HttpClient httpclient = cb . build ( ) ; if ( MOCKEXECUTOR != null ) { URI uri = this . lastrequest . getURI ( ) ; this . lastresponse = MOCKEXECUTOR . execute ( this . lastrequest ) ; } else { this . lastresponse = httpclient . execute ( targethost , this . lastrequest , session . getContext ( ) ) ; } if ( this . lastresponse == null ) throw new HTTPException ( "HTTPMethod.execute: Response was null" ) ; return this . lastresponse ; } catch ( IOException ioe ) { throw new HTTPException ( ioe ) ; } }


Input: /////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected TableConfig getPointConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( info . time . getRank ( ) != 1 ) { errlog . format ( "CFpointObs type=point: coord time must have rank 1, coord var= %s %n" , info . time . getNameAndDimensions ( ) ) ; return null ; } Dimension obsDim = info . time . getDimension ( 0 ) ; TableConfig obsTable = makeSingle ( ds , obsDim , errlog ) ; obsTable . featureType = FeatureType . POINT ; return obsTable ; }


Input:
//////////////////////////////////////////////////////////////////////////////// [CODESPLIT] protected TableConfig getStationConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingStation ( ds , info , CF . FeatureType . timeSeries , errlog ) ) return null ; // make station table
 TableConfig stnTable = makeStationTable ( ds , FeatureType . STATION , info , errlog ) ; if ( stnTable == null ) return null ; Dimension obsDim = info . childDim ; TableConfig obsTable = null ; switch ( info . encoding ) { case single : obsTable = makeSingle ( ds , obsDim , errlog ) ; break ; case multidim : obsTable = makeMultidimInner ( ds , stnTable , info . childDim , info , errlog ) ; if ( info . time . getRank ( ) == 1 ) { // join time(time)
 obsTable . addJoin ( new JoinArray ( info . time , JoinArray . Type . raw , 0 ) ) ; obsTable . time = info . time . getFullName ( ) ; } break ; case raggedContiguous : stnTable . numRecords = info . ragged_rowSize . getFullName ( ) ; obsTable = makeRaggedContiguousChildTable ( ds , info . parentDim , info . childDim , info . childStruct , errlog ) ; break ; case raggedIndex : obsTable = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; break ; case flat : info . set ( Encoding . flat , obsDim ) ; obsTable = makeStructTable ( ds , FeatureType . STATION , info , errlog ) ; obsTable . parentIndex = ( info . instanceId == null ) ? null : info . instanceId . getFullName ( ) ; Variable stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . CF_ROLE , CF . STATION_ID , obsDim , errlog ) ; if ( stnIdVar == null ) stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . STANDARD_NAME , CF . STATION_ID , obsDim , errlog ) ; obsTable . stnId = ( stnIdVar == null ) ? null : stnIdVar . getFullName ( ) ; obsTable . stnDesc = Evaluator . findNameOfVariableWithAttributeValue ( ds , CF . STANDARD_NAME , CF . PLATFORM_NAME ) ; if ( obsTable . stnDesc == null ) obsTable . stnDesc = Evaluator . findNameOfVariableWithAttributeValue ( ds , CF . STANDARD_NAME , CF . STATION_DESC ) ; obsTable . stnWmoId = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_WMOID , obsDim , errlog ) ; obsTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . SURFACE_ALTITUDE , obsDim , errlog ) ; if ( obsTable . stnAlt == null ) obsTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_ALTITUDE , obsDim , errlog ) ; break ; } if ( obsTable == null ) return null ; stnTable . addChild ( obsTable ) ; return stnTable ; }


Input:
// [CODESPLIT] protected TableConfig getProfileConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingProfile ( ds , info , errlog ) ) return null ; TableConfig profileTable = makeStructTable ( ds , FeatureType . PROFILE , info , errlog ) ; if ( profileTable == null ) return null ; profileTable . feature_id = identifyIdVariableName ( ds , CF . FeatureType . profile ) ; if ( profileTable . feature_id == null ) { errlog . format ( "CFpointObs getProfileConfig cant find a profile id %n" ) ; } // obs table
 VariableDS z = CoordSysEvaluator . findCoordByType ( ds , AxisType . Height ) ; if ( z == null ) z = CoordSysEvaluator . findCoordByType ( ds , AxisType . Pressure ) ; if ( z == null ) z = CoordSysEvaluator . findCoordByType ( ds , AxisType . GeoZ ) ; if ( z == null ) { errlog . format ( "CFpointObs getProfileConfig cant find a Height coordinate %n" ) ; return null ; } if ( info . childStruct == null ) info . childStruct = z . getParentStructure ( ) ; TableConfig obsTable = null ; switch ( info . encoding ) { case single : obsTable = makeSingle ( ds , info . childDim , errlog ) ; break ; case multidim : obsTable = makeMultidimInner ( ds , profileTable , info . childDim , info , errlog ) ; if ( z . getRank ( ) == 1 ) { // z(z)
 obsTable . addJoin ( new JoinArray ( z , JoinArray . Type . raw , 0 ) ) ; obsTable . elev = z . getFullName ( ) ; } break ; case raggedContiguous : profileTable . numRecords = info . ragged_rowSize . getFullName ( ) ; obsTable = makeRaggedContiguousChildTable ( ds , info . parentDim , info . childDim , info . childStruct , errlog ) ; break ; case raggedIndex : obsTable = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; break ; case flat : throw new UnsupportedOperationException ( "CFpointObs: profile flat encoding" ) ; } if ( obsTable == null ) return null ; profileTable . addChild ( obsTable ) ; return profileTable ; }


Input:
// [CODESPLIT] protected TableConfig getTrajectoryConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingTraj ( ds , info , errlog ) ) return null ; TableConfig trajTable = makeStructTable ( ds , FeatureType . TRAJECTORY , info , errlog ) ; if ( trajTable == null ) return null ; trajTable . feature_id = identifyIdVariableName ( ds , CF . FeatureType . trajectory ) ; if ( trajTable . feature_id == null ) { errlog . format ( "CFpointObs getTrajectoryConfig cant find a trajectoy id %n" ) ; } // obs table
 //Dimension obsDim = time.getDimension(time.getRank() - 1); // may be time(time) or time(traj, obs)
 TableConfig obsConfig = null ; switch ( info . encoding ) { case single : obsConfig = makeSingle ( ds , info . childDim , errlog ) ; break ; case multidim : obsConfig = makeMultidimInner ( ds , trajTable , info . childDim , info , errlog ) ; if ( info . time . getRank ( ) == 1 ) { // join time(obs) or time(time)
 obsConfig . addJoin ( new JoinArray ( info . time , JoinArray . Type . raw , 0 ) ) ; obsConfig . time = info . time . getFullName ( ) ; } break ; case raggedContiguous : trajTable . numRecords = info . ragged_rowSize . getFullName ( ) ; obsConfig = makeRaggedContiguousChildTable ( ds , info . parentDim , info . childDim , info . childStruct , errlog ) ; break ; case raggedIndex : obsConfig = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; break ; case flat : throw new UnsupportedOperationException ( "CFpointObs: trajectory flat encoding" ) ; } if ( obsConfig == null ) return null ; trajTable . addChild ( obsConfig ) ; return trajTable ; }


Input:
// [CODESPLIT] protected TableConfig getTimeSeriesProfileConfig ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) throws IOException { if ( ! identifyEncodingTimeSeriesProfile ( ds , info , CF . FeatureType . timeSeriesProfile , errlog ) ) return null ; VariableDS time = CoordSysEvaluator . findCoordByType ( ds , AxisType . Time ) ; if ( time == null ) return null ; if ( time . getRank ( ) == 0 && time . getParentStructure ( ) == null ) { errlog . format ( "CFpointObs timeSeriesProfile cannot have a scalar time coordinate%n" ) ; // why ?
 return null ; } /* distinguish multidim from flat
    if ((info.encoding == Encoding.multidim) && (time.getRank() < 3) && (z.getRank() < 3)) {
      Variable parentId = identifyParent(ds, CF.FeatureType.timeSeriesProfile);
      if ((parentId != null) && (parentId.getRank() == 1) && (parentId.getDimension(0).equals(time.getDimension(0)))) {
        if (time.getRank() == 1) // multidim time must be 2 or 3 dim
          info = new EncodingInfo(Encoding.flat, parentId);
        else if (time.getRank() == 2) {
          Dimension zDim = z.getDimension(z.getRank() - 1); // may be z(z) or z(profile, z)
          if (zDim.equals(time.getDimension(1))) // flat 2D time will have time as inner dim
            info = new EncodingInfo(Encoding.flat, parentId);
        }
      }
    } */ TableConfig stationTable = makeStationTable ( ds , FeatureType . STATION_PROFILE , info , errlog ) ; if ( stationTable == null ) return null ; //Dimension stationDim = ds.findDimension(stationTable.dimName);
 //Dimension profileDim = null;
 //Dimension zDim = null;
 VariableDS z = info . alt ; switch ( info . encoding ) { case single : { assert ( ( time . getRank ( ) >= 1 ) && ( time . getRank ( ) <= 2 ) ) : "time must be rank 1 or 2" ; assert ( ( z . getRank ( ) >= 1 ) && ( z . getRank ( ) <= 2 ) ) : "z must be rank 1 or 2" ; if ( time . getRank ( ) == 2 ) { if ( z . getRank ( ) == 2 ) // 2d time, 2d z
 assert time . getDimensions ( ) . equals ( z . getDimensions ( ) ) : "rank-2 time and z dimensions must be the same" ; else // 2d time, 1d z
 assert time . getDimension ( 1 ) . equals ( z . getDimension ( 0 ) ) : "rank-2 time must have z inner dimension" ; //profileDim = time.getDimension(0);
 //zDim = time.getDimension(1);
 } else { // 1d time
 if ( z . getRank ( ) == 2 ) { // 1d time, 2d z
 assert z . getDimension ( 0 ) . equals ( time . getDimension ( 0 ) ) : "rank-2 z must have time outer dimension" ; //profileDim = z.getDimension(0);
 //zDim = z.getDimension(1);
 } else { // 1d time, 1d z
 assert ! time . getDimension ( 0 ) . equals ( z . getDimension ( 0 ) ) : "time and z dimensions must be different" ; //profileDim = time.getDimension(0);
 //zDim = z.getDimension(0);
 } } // make profile table
 TableConfig profileTable = makeStructTable ( ds , FeatureType . PROFILE , new EncodingInfo ( ) . set ( Encoding . multidim , info . childDim ) , errlog ) ; if ( profileTable == null ) return null ; if ( time . getRank ( ) == 1 ) { // join time(time)
 //profileTable.addJoin(new JoinArray(time, JoinArray.Type.raw, 0));
 profileTable . addJoin ( new JoinArray ( time , JoinArray . Type . level , 1 ) ) ; profileTable . time = time . getFullName ( ) ; } stationTable . addChild ( profileTable ) ; // make the inner (z) table
 TableConfig zTable = makeMultidimInner ( ds , profileTable , info . grandChildDim , info , errlog ) ; if ( z . getRank ( ) == 1 ) { // join z(z)
 zTable . addJoin ( new JoinArray ( z , JoinArray . Type . raw , 0 ) ) ; zTable . elev = z . getFullName ( ) ; } profileTable . addChild ( zTable ) ; break ; } case multidim : { assert ( ( time . getRank ( ) >= 1 ) && ( time . getRank ( ) <= 3 ) ) : "time must be rank 2 or 3" ; assert ( ( z . getRank ( ) == 1 ) || ( z . getRank ( ) == 3 ) ) : "z must be rank 1 or 3" ; if ( time . getRank ( ) == 3 ) { if ( z . getRank ( ) == 3 ) // 3d time, 3d z
 assert time . getDimensions ( ) . equals ( z . getDimensions ( ) ) : "rank-3 time and z dimensions must be the same" ; else // 3d time, 1d z
 assert time . getDimension ( 2 ) . equals ( z . getDimension ( 0 ) ) : "rank-3 time must have z inner dimension" ; //profileDim = time.getDimension(1);
 //zDim = time.getDimension(2);
 } else if ( time . getRank ( ) == 2 ) { // 2d time
 if ( z . getRank ( ) == 3 ) { // 2d time, 3d z
 assert z . getDimension ( 1 ) . equals ( time . getDimension ( 1 ) ) : "rank-2 time must have time inner dimension" ; //profileDim = z.getDimension(1);
 //zDim = z.getDimension(2);
 } else { // 2d time, 1d z
 assert ! time . getDimension ( 0 ) . equals ( z . getDimension ( 0 ) ) : "time and z dimensions must be different" ; assert ! time . getDimension ( 1 ) . equals ( z . getDimension ( 0 ) ) : "time and z dimensions must be different" ; //profileDim = time.getDimension(1);
 //zDim = z.getDimension(0);
 } } else { // 1d time
 if ( z . getRank ( ) == 1 ) { assert ! time . getDimension ( 0 ) . equals ( z . getDimension ( 0 ) ) : "time and z dimensions must be different" ; } } TableConfig profileTable = makeMultidimInner ( ds , stationTable , info . childDim , info , errlog ) ; if ( profileTable == null ) return null ; if ( time . getRank ( ) == 1 ) { // join time(time)
 profileTable . addJoin ( new JoinArray ( time , JoinArray . Type . level , 1 ) ) ; profileTable . time = time . getFullName ( ) ; } stationTable . addChild ( profileTable ) ; // make the inner (z) table
 TableConfig zTable = makeMultidimInner3D ( ds , stationTable , profileTable , info . grandChildDim , errlog ) ; if ( z . getRank ( ) == 1 ) { // join z(z)
 zTable . addJoin ( new JoinArray ( z , JoinArray . Type . raw , 0 ) ) ; zTable . elev = z . getFullName ( ) ; } profileTable . addChild ( zTable ) ; break ; } case raggedIndex : { TableConfig profileTable = makeRaggedIndexChildTable ( ds , info . parentDim , info . childDim , info . ragged_parentIndex , errlog ) ; stationTable . addChild ( profileTable ) ; profileTable . numRecords = info . ragged_rowSize . getFullName ( ) ; TableConfig obsTable = makeRaggedContiguousChildTable ( ds , info . childDim , info . grandChildDim , info . grandChildStruct , errlog ) ; profileTable . addChild ( obsTable ) ; break ; } case raggedContiguous : // NOT USED
 throw new UnsupportedOperationException ( "CFpointObs: timeSeriesProfile raggedContiguous encoding not allowed" ) ; /*
      case flat:
        //profileDim = time.getDimension(0); // may be time(profile) or time(profile, z)
        Variable parentId = identifyParent(ds, CF.FeatureType.timeSeriesProfile);

        TableConfig profileTable = makeStructTable(ds, FeatureType.PROFILE, info, errlog);
        profileTable.parentIndex = parentId.getName();
        profileTable.stnId = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_ID, info.childDim, errlog);
        profileTable.stnDesc = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_DESC, info.childDim, errlog);
        profileTable.stnWmoId = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_WMOID, info.childDim, errlog);
        profileTable.stnAlt = findNameVariableWithStandardNameAndDimension(ds, CF.STATION_ALTITUDE, info.childDim, errlog);
        stationTable.addChild(profileTable);

        //zDim = z.getDimension(z.getRank() - 1); // may be z(z) or z(profile, z)
        TableConfig zTable = makeMultidimInner(ds, profileTable, info.grandChildDim, errlog);
        if (z.getRank() == 1) // z(z)
          zTable.addJoin(new JoinArray(z, JoinArray.Type.raw, 0));
        profileTable.addChild(zTable);

        break; */ } return stationTable ; }


Input:
for stations figure out the encoding [CODESPLIT] protected boolean identifyEncodingStation ( NetcdfDataset ds , EncodingInfo info , CF . FeatureType ftype , Formatter errlog ) { // find the obs dimension
 Dimension obsDim = null ; if ( info . time . getRank ( ) > 0 ) obsDim = info . time . getDimension ( info . time . getRank ( ) - 1 ) ; // may be time(time) or time(stn, obs)
 else if ( info . time . getParentStructure ( ) != null ) { Structure parent = info . time . getParentStructure ( ) ; // if time axis is a structure member, try pulling dimension out of parent structure
 obsDim = parent . getDimension ( parent . getRank ( ) - 1 ) ; } if ( obsDim == null ) { errlog . format ( "CFpointObs: must have a non-scalar Time coordinate%n" ) ; return false ; } // find the station dimension
 if ( info . lat . getRank ( ) == 0 ) { // scalar means single
 info . set ( Encoding . single , null , obsDim ) ; return true ; } Dimension stnDim = info . lat . getDimension ( 0 ) ; if ( obsDim == stnDim ) { info . set ( Encoding . flat , null , obsDim ) ; // not used ?
 return true ; } // the raggeds
 if ( identifyRaggeds ( ds , info , stnDim , obsDim , errlog ) ) return true ; // heres whats left
 if ( info . lat . getRank ( ) == 1 ) { //Encoding e = (info.time.getParentStructure() != null) ? Encoding.multiStructure : Encoding.multidim;
 info . set ( Encoding . multidim , stnDim , obsDim ) ; return true ; } errlog . format ( "CFpointObs: %s Must have Lat/Lon coordinates of rank 0 or 1%n" , ftype ) ; return false ; }


Input:
Identify ragged array representations for single nests ( station profile trajectory ) [CODESPLIT] protected boolean identifyRaggeds ( NetcdfDataset ds , EncodingInfo info , Dimension instanceDim , Dimension sampleDim , Formatter errlog ) { // check for contiguous
 Evaluator . VarAtt varatt = Evaluator . findVariableWithAttribute ( ds , CF . SAMPLE_DIMENSION ) ; // CF 1.6
 if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_ROWSIZE ) ; // backwards compatibility
 if ( varatt != null ) { Variable ragged_rowSize = varatt . var ; String sampleDimName = varatt . att . getStringValue ( ) ; if ( sampleDim != null && ! sampleDimName . equals ( sampleDim . getShortName ( ) ) ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable has sample dimension %s must be %s%n" , sampleDimName , sampleDim . getShortName ( ) ) ; return false ; } if ( sampleDim == null ) { sampleDim = ds . findDimension ( sampleDimName ) ; if ( sampleDim == null ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable has invalid sample dimension %s%n" , sampleDimName ) ; return false ; } } Dimension rrDim ; if ( ragged_rowSize . getRank ( ) > 0 ) rrDim = ragged_rowSize . getDimension ( 0 ) ; // nobs(station)
 else if ( ragged_rowSize . getParentStructure ( ) != null ) { Structure parent = ragged_rowSize . getParentStructure ( ) ; // if ragged_rowSize is a structure member, use dimension of parent structure
 rrDim = parent . getDimension ( 0 ) ; } else { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable (%s) must have rank 1%n" , ragged_rowSize ) ; return false ; } if ( instanceDim != null && instanceDim != rrDim ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable has invalid instance dimension %s must be %s%n" , rrDim , instanceDim ) ; return false ; } instanceDim = rrDim ; if ( ragged_rowSize . getDataType ( ) != DataType . INT ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable must be of type integer%n" ) ; return false ; } info . set ( Encoding . raggedContiguous , instanceDim , sampleDim ) ; info . ragged_rowSize = ragged_rowSize ; info . parentStruct = ragged_rowSize . getParentStructure ( ) ; return true ; } // rowsize was found
 varatt = Evaluator . findVariableWithAttribute ( ds , CF . INSTANCE_DIMENSION ) ; // CF 1.6
 if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_PARENTINDEX ) ; // backwards compatibility
 if ( varatt != null ) { Variable ragged_parentIndex = varatt . var ; String instanceDimName = varatt . att . getStringValue ( ) ; if ( instanceDim != null && ! instanceDimName . equals ( instanceDim . getShortName ( ) ) ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable has instance dimension %s must be %s%n" , instanceDimName , instanceDim . getShortName ( ) ) ; return false ; } if ( instanceDim == null ) { instanceDim = ds . findDimension ( instanceDimName ) ; if ( instanceDim == null ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable has invalid instance dimension %s%n" , instanceDimName ) ; return false ; } } if ( ragged_parentIndex . getDataType ( ) != DataType . INT ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable must be of type integer%n" ) ; return false ; } // allow netcdf-4 structures, eg kunicki
 if ( ragged_parentIndex . isMemberOfStructure ( ) ) { Structure s = ragged_parentIndex . getParentStructure ( ) ; if ( s . getRank ( ) == 0 || ! s . getDimension ( 0 ) . equals ( sampleDim ) ) { errlog . format ( "CFpointObs: Indexed ragged array representation (structure): parent_index variable must be of form Struct { %s }(%s) %n" , ragged_parentIndex . getFullName ( ) , sampleDim . getShortName ( ) ) ; return false ; } } else { if ( ragged_parentIndex . getRank ( ) != 1 || ! ragged_parentIndex . getDimension ( 0 ) . equals ( sampleDim ) ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable must be of form %s(%s) %n" , ragged_parentIndex . getFullName ( ) , sampleDim . getShortName ( ) ) ; return false ; } } info . set ( Encoding . raggedIndex , instanceDim , sampleDim ) ; info . ragged_parentIndex = ragged_parentIndex ; info . childStruct = ragged_parentIndex . getParentStructure ( ) ; return true ; } // parent index was found
 /* kunicki 10/21/2011
    Variable ragged_parentIndex = Evaluator.getVariableWithAttributeValue(ds, CF.RAGGED_PARENTINDEX, parentDim.getShortName());
    if ((ragged_parentIndex == null) ||
            (!ragged_parentIndex.isMemberOfStructure() && (ragged_parentIndex.getRank() == 0 || ragged_parentIndex.getDimension(0).getShortName() != childDim.getShortName()) ||
                    (ragged_parentIndex.isMemberOfStructure() && (ragged_parentIndex.getParentStructure().getRank() == 0 || ragged_parentIndex.getParentStructure().getDimension(0).getShortName() != childDim.getShortName())))
            ) {
      // if ((null == ragged_parentIndex) || (ragged_parentIndex.getRank() == 0) || (ragged_parentIndex.getDimension(0).getShortName() != childDim.getShortName())) {
      errlog.format("there must be a ragged_parent_index variable with outer dimension that matches obs dimension %s%n", childDim.getShortName());
      return null;
    }  */ return false ; }


Input:
Identify ragged array representations for double nests ( timeSeries profile timeSeries trajectory ) <p / > This uses the contiguous ragged array representation for each profile ( 9 . 5 . 43 . 3 ) and the indexed ragged array representation to organise the profiles into time series ( 9 . 3 . 54 ) . The canonical use case is when writing real - time data streams that contain profiles from many stations arriving randomly with the data for each entire profile written all at once . [CODESPLIT] protected boolean identifyDoubleRaggeds ( NetcdfDataset ds , EncodingInfo info , Formatter errlog ) { // the timeseries are stored as ragged index
 Evaluator . VarAtt varatt = Evaluator . findVariableWithAttribute ( ds , CF . INSTANCE_DIMENSION ) ; if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_PARENTINDEX ) ; if ( varatt == null ) return false ; Variable ragged_parentIndex = varatt . var ; String instanceDimName = varatt . att . getStringValue ( ) ; Dimension stationDim = ds . findDimension ( instanceDimName ) ; if ( stationDim == null ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable has illegal value for %s = %s%n" , CF . INSTANCE_DIMENSION , instanceDimName ) ; return false ; } if ( ragged_parentIndex . getDataType ( ) != DataType . INT ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable must be of type integer%n" ) ; return false ; } if ( ragged_parentIndex . getRank ( ) != 1 && info . childStruct == null ) { errlog . format ( "CFpointObs: Indexed ragged array representation: parent_index variable %s must be 1D %n" , ragged_parentIndex ) ; return false ; } Dimension profileDim = ( info . childDim != null ) ? info . childDim : ragged_parentIndex . getDimension ( 0 ) ; // onto the profiles, stored contiguously
 varatt = Evaluator . findVariableWithAttribute ( ds , CF . SAMPLE_DIMENSION ) ; if ( varatt == null ) varatt = Evaluator . findVariableWithAttribute ( ds , CF . RAGGED_ROWSIZE ) ; if ( varatt == null ) return false ; Variable ragged_rowSize = varatt . var ; String obsDimName = varatt . att . getStringValue ( ) ; Dimension obsDim = ds . findDimension ( obsDimName ) ; if ( obsDimName == null ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: parent_index variable has illegal value for %s = %s%n" , CF . SAMPLE_DIMENSION , obsDimName ) ; return false ; } if ( ! obsDimName . equals ( info . grandChildDim . getShortName ( ) ) ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable has obs dimension %s must be %s%n" , obsDimName , info . childDim ) ; return false ; } if ( ragged_rowSize . getDataType ( ) != DataType . INT ) { errlog . format ( "CFpointObs: Contiguous ragged array representation: row_size variable must be of type integer%n" ) ; return false ; } if ( info . childDim == null ) { // nc4 ext
 Dimension profileDim2 = ragged_rowSize . getDimension ( 0 ) ; if ( profileDim2 != profileDim ) { errlog . format ( "CFpointObs: Double ragged array representation dimensions do not agree: %s != %s%n" , profileDim2 . getShortName ( ) , profileDim . getShortName ( ) ) ; return false ; } } info . set ( Encoding . raggedIndex , stationDim , profileDim , obsDim ) ; info . ragged_parentIndex = ragged_parentIndex ; info . ragged_rowSize = ragged_rowSize ; return true ; }


Input:
for station and stationProfile not flat [CODESPLIT] private TableConfig makeStationTable ( NetcdfDataset ds , FeatureType ftype , EncodingInfo info , Formatter errlog ) throws IOException { Variable lat = CoordSysEvaluator . findCoordByType ( ds , AxisType . Lat ) ; Variable lon = CoordSysEvaluator . findCoordByType ( ds , AxisType . Lon ) ; if ( lat == null || lon == null ) { errlog . format ( "CFpointObs: must have lat and lon coordinates%n" ) ; return null ; } //Dimension stationDim = (info.encoding == Encoding.single) ? null : lat.getDimension(0); // assumes outer dim of lat is parent dimension, single = scalar
 Table . Type stationTableType = Table . Type . Structure ; if ( info . encoding == Encoding . single ) stationTableType = Table . Type . Top ; if ( info . encoding == Encoding . flat ) stationTableType = Table . Type . Construct ; Dimension stationDim = ( info . encoding == Encoding . flat ) ? info . childDim : info . parentDim ; String name = ( stationDim == null ) ? " single" : stationDim . getShortName ( ) ; TableConfig stnTable = new TableConfig ( stationTableType , name ) ; stnTable . featureType = ftype ; // stnId
 Variable stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . CF_ROLE , CF . TIMESERIES_ID , stationDim , errlog ) ; if ( stnIdVar == null ) stnIdVar = Evaluator . findVariableWithAttributeAndDimension ( ds , CF . STANDARD_NAME , CF . STATION_ID , stationDim , errlog ) ; if ( stnIdVar == null ) { errlog . format ( "CFpointObs: must have a Station id variable with %s = %s%n" , CF . CF_ROLE , CF . TIMESERIES_ID ) ; return null ; } stnTable . stnId = stnIdVar . getFullName ( ) ; info . instanceId = stnIdVar ; stnTable . stnDesc = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . PLATFORM_NAME , stationDim , errlog ) ; if ( stnTable . stnDesc == null ) stnTable . stnDesc = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_DESC , stationDim , errlog ) ; stnTable . stnWmoId = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . PLATFORM_ID , stationDim , errlog ) ; if ( stnTable . stnWmoId == null ) stnTable . stnWmoId = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_WMOID , stationDim , errlog ) ; stnTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . SURFACE_ALTITUDE , stationDim , errlog ) ; if ( stnTable . stnAlt == null ) stnTable . stnAlt = Evaluator . findNameVariableWithStandardNameAndDimension ( ds , CF . STATION_ALTITUDE , stationDim , errlog ) ; stnTable . lat = lat . getFullName ( ) ; stnTable . lon = lon . getFullName ( ) ; if ( info . encoding != Encoding . single && stationDim != null ) { stnTable . dimName = stationDim . getShortName ( ) ; makeStructureInfo ( stnTable , ds , stnIdVar . getParentStructure ( ) , stationDim ) ; } // LOOK probably need a standard name here
 // optional alt coord - detect if its a station height or actually associated with the obs, eg for a profile
 if ( stnTable . stnAlt == null ) { Variable alt = CoordSysEvaluator . findCoordByType ( ds , AxisType . Height ) ; if ( alt != null ) { if ( ( info . encoding == Encoding . single ) && alt . getRank ( ) == 0 ) stnTable . stnAlt = alt . getFullName ( ) ; if ( ( info . encoding != Encoding . single ) && ( lat . getRank ( ) == alt . getRank ( ) ) && alt . getRank ( ) > 0 && alt . getDimension ( 0 ) . equals ( stationDim ) ) stnTable . stnAlt = alt . getFullName ( ) ; } } return stnTable ; }


Input: /////////////////////////////////////////////////////////////////////////////// [CODESPLIT] private TableConfig makeRaggedContiguousChildTable ( NetcdfDataset ds , Dimension parentDim , Dimension childDim , Structure childStruct , Formatter errlog ) throws IOException { TableConfig childTable = new TableConfig ( Table . Type . Contiguous , childDim . getShortName ( ) ) ; childTable . dimName = childDim . getShortName ( ) ; childTable . lat = matchAxisTypeAndDimension ( ds , AxisType . Lat , childDim ) ; childTable . lon = matchAxisTypeAndDimension ( ds , AxisType . Lon , childDim ) ; childTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Height , childDim ) ; if ( childTable . elev == null ) childTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Pressure , childDim ) ; if ( childTable . elev == null ) childTable . elev = matchAxisTypeAndDimension ( ds , AxisType . GeoZ , childDim ) ; childTable . time = matchAxisTypeAndDimension ( ds , AxisType . Time , childDim ) ; makeStructureInfo ( childTable , ds , childStruct , childDim ) ; return childTable ; }


Input:
the inner table of Structure ( outer inner ) and middle table of Structure ( outer middle inner ) [CODESPLIT] private TableConfig makeMultidimInner ( NetcdfDataset ds , TableConfig parentTable , Dimension obsDim , EncodingInfo info , Formatter errlog ) throws IOException { Dimension parentDim = ds . findDimension ( parentTable . dimName ) ; Table . Type obsTableType = ( parentTable . structureType == TableConfig . StructureType . PsuedoStructure ) ? Table . Type . MultidimInnerPsuedo : Table . Type . MultidimInner ; // if (info.time.isMemberOfStructure()) obsTableType = Table.Type.Structure;
 TableConfig obsTable = new TableConfig ( obsTableType , obsDim . getShortName ( ) ) ; obsTable . lat = matchAxisTypeAndDimension ( ds , AxisType . Lat , parentDim , obsDim ) ; obsTable . lon = matchAxisTypeAndDimension ( ds , AxisType . Lon , parentDim , obsDim ) ; obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Height , parentDim , obsDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Pressure , parentDim , obsDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . GeoZ , parentDim , obsDim ) ; obsTable . time = matchAxisTypeAndDimension ( ds , AxisType . Time , parentDim , obsDim ) ; // divide up the variables between the parent and the obs
 List < String > obsVars ; List < Variable > vars = ds . getVariables ( ) ; List < String > parentVars = new ArrayList <> ( vars . size ( ) ) ; obsVars = new ArrayList <> ( vars . size ( ) ) ; for ( Variable orgV : vars ) { if ( orgV instanceof Structure ) continue ; Dimension dim0 = orgV . getDimension ( 0 ) ; if ( ( dim0 != null ) && dim0 . equals ( parentDim ) ) { if ( ( orgV . getRank ( ) == 1 ) || ( ( orgV . getRank ( ) == 2 ) && orgV . getDataType ( ) == DataType . CHAR ) ) { parentVars . add ( orgV . getShortName ( ) ) ; } else { Dimension dim1 = orgV . getDimension ( 1 ) ; if ( ( dim1 != null ) && dim1 . equals ( obsDim ) ) obsVars . add ( orgV . getShortName ( ) ) ; } } } parentTable . vars = parentVars ; // parentTable.vars = parentTable.isPsuedoStructure ? parentVars : null; // restrict to these if psuedoStruct
 obsTable . structureType = parentTable . structureType ; obsTable . outerName = parentDim . getShortName ( ) ; obsTable . innerName = obsDim . getShortName ( ) ; obsTable . dimName = ( parentTable . structureType == TableConfig . StructureType . PsuedoStructure ) ? obsTable . outerName : obsTable . innerName ; obsTable . structName = obsDim . getShortName ( ) ; obsTable . vars = obsVars ; return obsTable ; }


Input:
the inner table of Structure ( outer middle inner ) [CODESPLIT] private TableConfig makeMultidimInner3D ( NetcdfDataset ds , TableConfig outerTable , TableConfig middleTable , Dimension innerDim , Formatter errlog ) throws IOException { Dimension outerDim = ds . findDimension ( outerTable . dimName ) ; Dimension middleDim = ds . findDimension ( middleTable . innerName ) ; Table . Type obsTableType = ( outerTable . structureType == TableConfig . StructureType . PsuedoStructure ) ? Table . Type . MultidimInnerPsuedo3D : Table . Type . MultidimInner3D ; TableConfig obsTable = new TableConfig ( obsTableType , innerDim . getShortName ( ) ) ; obsTable . structureType = TableConfig . StructureType . PsuedoStructure2D ; obsTable . dimName = outerTable . dimName ; obsTable . outerName = middleTable . innerName ; obsTable . innerName = innerDim . getShortName ( ) ; obsTable . structName = innerDim . getShortName ( ) ; obsTable . lat = matchAxisTypeAndDimension ( ds , AxisType . Lat , outerDim , middleDim , innerDim ) ; obsTable . lon = matchAxisTypeAndDimension ( ds , AxisType . Lon , outerDim , middleDim , innerDim ) ; obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Height , outerDim , middleDim , innerDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . Pressure , middleDim , innerDim ) ; if ( obsTable . elev == null ) obsTable . elev = matchAxisTypeAndDimension ( ds , AxisType . GeoZ , middleDim , innerDim ) ; obsTable . time = matchAxisTypeAndDimension ( ds , AxisType . Time , outerDim , middleDim , innerDim ) ; // divide up the variables between the 3 tables
 List < Variable > vars = ds . getVariables ( ) ; List < String > outerVars = new ArrayList <> ( vars . size ( ) ) ; List < String > middleVars = new ArrayList <> ( vars . size ( ) ) ; List < String > innerVars = new ArrayList <> ( vars . size ( ) ) ; for ( Variable orgV : vars ) { if ( orgV instanceof Structure ) continue ; if ( ( orgV . getRank ( ) == 1 ) || ( ( orgV . getRank ( ) == 2 ) && orgV . getDataType ( ) == DataType . CHAR ) ) { if ( outerDim . equals ( orgV . getDimension ( 0 ) ) ) outerVars . add ( orgV . getShortName ( ) ) ; } else if ( orgV . getRank ( ) == 2 ) { if ( outerDim . equals ( orgV . getDimension ( 0 ) ) && middleDim . equals ( orgV . getDimension ( 1 ) ) ) middleVars . add ( orgV . getShortName ( ) ) ; } else if ( orgV . getRank ( ) == 3 ) { if ( outerDim . equals ( orgV . getDimension ( 0 ) ) && middleDim . equals ( orgV . getDimension ( 1 ) ) && innerDim . equals ( orgV . getDimension ( 2 ) ) ) innerVars . add ( orgV . getShortName ( ) ) ; } } outerTable . vars = outerVars ; middleTable . vars = middleVars ; obsTable . vars = innerVars ; return obsTable ; }


Input:
class I don t understand enough of the code base to anticipate implementation artifacts . [CODESPLIT] protected String matchAxisTypeAndDimension ( NetcdfDataset ds , AxisType type , final Dimension outer ) { Variable var = CoordSysEvaluator . findCoordByType ( ds , type , new CoordSysEvaluator . Predicate ( ) { public boolean match ( CoordinateAxis axis ) { if ( ( outer == null ) && ( axis . getRank ( ) == 0 ) ) return true ; if ( ( outer != null ) && ( axis . getRank ( ) == 1 ) && ( outer . equals ( axis . getDimension ( 0 ) ) ) ) return true ; // if axis is structure member, try pulling dimension out of parent structure
 if ( axis . getParentStructure ( ) != null ) { Structure parent = axis . getParentStructure ( ) ; if ( ( outer != null ) && ( parent . getRank ( ) == 1 ) && ( outer . equals ( parent . getDimension ( 0 ) ) ) ) return true ; } return false ; } } ) ; if ( var == null ) return null ; return var . getFullName ( ) ; }


Input: Added 5 - 30 - 2006 to allow for resetting of the input used by this object . This saves in memory allocation costs [CODESPLIT] public void setStream ( InputStream zStream ) { last = 0 ; origPtr = 0 ; blockSize100k = 0 ; blockRandomised = false ; bsBuff = 0 ; bsLive = 0 ; mCrc = new CRC ( ) ; nInUse = 0 ; bsStream = null ; streamEnd = false ; currentChar = - 1 ; currentState = START_BLOCK_STATE ; storedBlockCRC = storedCombinedCRC = 0 ; computedBlockCRC = computedCombinedCRC = 0 ; i2 = count = chPrev = ch2 = 0 ; i = tPos = 0 ; rNToGo = 0 ; rTPos = 0 ; j2 = 0 ; z = 0 ; bsSetStream ( zStream ) ; initialize ( ) ; if ( ! streamEnd ) { // Handle if initialize does not detect valid bz2 stream initBlock ( ) ; setupBlock ( ) ; } }


Input: Reads the stream . [CODESPLIT] public int read ( ) { if ( streamEnd ) { return - 1 ; } else { int retChar = currentChar ; switch ( currentState ) { case START_BLOCK_STATE : break ; case RAND_PART_A_STATE : break ; case RAND_PART_B_STATE : setupRandPartB ( ) ; break ; case RAND_PART_C_STATE : setupRandPartC ( ) ; break ; case NO_RAND_PART_A_STATE : break ; case NO_RAND_PART_B_STATE : setupNoRandPartB ( ) ; break ; case NO_RAND_PART_C_STATE : setupNoRandPartC ( ) ; break ; default : break ; } return retChar ; } }


Input: Call this from awt event thread . The task is run in a background thread . [CODESPLIT] public void start ( java . awt . Component top , String taskName , int progressMaxCount ) { // create ProgressMonitor pm = new javax . swing . ProgressMonitor ( top , taskName , "" , 0 , progressMaxCount ) ; pm . setMillisToDecideToPopup ( millisToDecideToPopup ) ; pm . setMillisToPopup ( millisToPopup ) ; // do task in a seperate, non-event, thread taskThread = new Thread ( task ) ; taskThread . start ( ) ; // create timer, whose events happen on the awt event Thread ActionListener watcher = new ActionListener ( ) { public void actionPerformed ( ActionEvent evt ) { secs ++ ; if ( pm . isCanceled ( ) ) { task . cancel ( ) ; } else { // indicate progress String note = task . getNote ( ) ; pm . setNote ( note == null ? secs + " secs" : note ) ; int progress = task . getProgress ( ) ; pm . setProgress ( progress <= 0 ? secs : progress ) ; } // need to make sure task acknowledges the cancel; so dont shut down // until the task is done if ( task . isDone ( ) ) { timer . stop ( ) ; pm . close ( ) ; // Toolkit.getDefaultToolkit().beep(); if ( task . isError ( ) ) { javax . swing . JOptionPane . showMessageDialog ( null , task . getErrorMessage ( ) ) ; } if ( task . isSuccess ( ) ) fireEvent ( new ActionEvent ( this , 0 , "success" ) ) ; else if ( task . isError ( ) ) fireEvent ( new ActionEvent ( this , 0 , "error" ) ) ; else if ( task . isCancel ( ) ) fireEvent ( new ActionEvent ( this , 0 , "cancel" ) ) ; else fireEvent ( new ActionEvent ( this , 0 , "done" ) ) ; } } } ; timer = new javax . swing . Timer ( 1000 , watcher ) ; // every second timer . start ( ) ; }


Input: Misc . [CODESPLIT] static public byte [ ] readbinaryfile ( File f ) throws IOException { try ( FileInputStream fis = new FileInputStream ( f ) ) { return readbinaryfile ( fis ) ; } }


Input: Convert a uri string to an instance of java . net . URI . The critical thing is that this procedure can handle backslash escaped uris as well as %xx escaped uris . [CODESPLIT] static public URI parseToURI ( final String u ) throws URISyntaxException { StringBuilder buf = new StringBuilder ( ) ; int i = 0 ; while ( i < u . length ( ) ) { char c = u . charAt ( i ) ; if ( c == ' ' ) { if ( i + 1 == u . length ( ) ) throw new URISyntaxException ( u , "Trailing '\' at end of url" ) ; buf . append ( "%5c" ) ; i ++ ; c = u . charAt ( i ) ; buf . append ( String . format ( "%%%02x" , ( int ) c ) ) ; } else buf . append ( c ) ; i ++ ; } return new URI ( buf . toString ( ) ) ; }


Input: Remove selected fields from a URI producing a new URI [CODESPLIT] static URI uriExclude ( final URI uri , URIPart ... excludes ) { URIBuilder urib = new URIBuilder ( ) ; EnumSet < URIPart > set = EnumSet . of ( excludes [ 0 ] , excludes ) ; for ( URIPart part : URIPart . values ( ) ) { if ( set . contains ( part ) ) continue ; switch ( part ) { case SCHEME : urib . setScheme ( uri . getScheme ( ) ) ; break ; case USERINFO : urib . setUserInfo ( uri . getUserInfo ( ) ) ; break ; case HOST : urib . setHost ( uri . getHost ( ) ) ; break ; case PORT : urib . setPort ( uri . getPort ( ) ) ; break ; case PATH : urib . setPath ( uri . getPath ( ) ) ; break ; case QUERY : urib . setCustomQuery ( uri . getQuery ( ) ) ; break ; case FRAGMENT : urib . setFragment ( uri . getFragment ( ) ) ; break ; } } try { return urib . build ( ) ; } catch ( URISyntaxException e ) { throw new IllegalArgumentException ( e . getMessage ( ) ) ; } }


Input: Convert a zero - length string to null [CODESPLIT] static public String nullify ( String s ) { if ( s != null && s . length ( ) == 0 ) s = null ; return s ; }


Input: Join two string together to form proper path WITHOUT trailing slash [CODESPLIT] static public String canonjoin ( String prefix , String suffix ) { if ( prefix == null ) prefix = "" ; if ( suffix == null ) suffix = "" ; prefix = HTTPUtil . canonicalpath ( prefix ) ; suffix = HTTPUtil . canonicalpath ( suffix ) ; StringBuilder result = new StringBuilder ( ) ; result . append ( prefix ) ; int prelen = prefix . length ( ) ; if ( prelen > 0 && result . charAt ( prelen - 1 ) != ' ' ) { result . append ( ' ' ) ; prelen ++ ; } if ( suffix . length ( ) > 0 && suffix . charAt ( 0 ) == ' ' ) result . append ( suffix . substring ( 1 ) ) ; else result . append ( suffix ) ; int len = result . length ( ) ; if ( len > 0 && result . charAt ( len - 1 ) == ' ' ) { result . deleteCharAt ( len - 1 ) ; len -- ; } return result . toString ( ) ; }


Input: Convert path to use / consistently and to remove any trailing / [CODESPLIT] static public String canonicalpath ( String path ) { if ( path == null ) return null ; StringBuilder b = new StringBuilder ( path ) ; canonicalpath ( b ) ; return b . toString ( ) ; }


Input: Convert path to remove any leading / or drive letter assumes canonical . [CODESPLIT] static public String relpath ( String path ) { if ( path == null ) return null ; StringBuilder b = new StringBuilder ( path ) ; canonicalpath ( b ) ; if ( b . length ( ) > 0 ) { if ( b . charAt ( 0 ) == ' ' ) b . deleteCharAt ( 0 ) ; if ( hasDriveLetter ( b ) ) b . delete ( 0 , 2 ) ; } return b . toString ( ) ; }


Input: Support function [CODESPLIT] static protected boolean hasDriveLetter ( StringBuilder path ) { return ( path . length ( ) >= 2 && path . charAt ( 1 ) == ' ' && DRIVELETTERS . indexOf ( path . charAt ( 0 ) ) >= 0 ) ; }


Input: Convert path to add a leading / ; assumes canonical . [CODESPLIT] static public String abspath ( String path ) { if ( path == null ) return "/" ; StringBuilder b = new StringBuilder ( path ) ; canonicalpath ( b ) ; if ( b . charAt ( 0 ) == ' ' ) b . deleteCharAt ( 0 ) ; if ( b . charAt ( 0 ) != ' ' || ! hasDriveLetter ( b ) ) b . insert ( 0 , ' ' ) ; return b . toString ( ) ; }


Input: Accept datasets whose last modified date is at least the last modified limit of milliseconds in the past . [CODESPLIT] public boolean accept ( CrawlableDataset dataset ) { Date lastModDate = dataset . lastModified ( ) ; if ( lastModDate != null ) { long now = System . currentTimeMillis ( ) ; if ( now - lastModDate . getTime ( ) > lastModifiedLimitInMillis ) return true ; } return false ; }


Input: //////////////////////////////////////////////////////// [CODESPLIT] static MFile makeIndexMFile ( String collectionName , File directory ) { String nameNoBlanks = StringUtil2 . replace ( collectionName , ' ' , "_" ) ; return new GcMFile ( directory , nameNoBlanks + GribCdmIndex . NCX_SUFFIX , - 1 , - 1 , - 1 ) ; // LOOK dont know lastMod, size. can it be added later? }


Input: for making partition collection [CODESPLIT] void copyInfo ( GribCollectionMutable from ) { this . center = from . center ; this . subcenter = from . subcenter ; this . master = from . master ; this . local = from . local ; this . genProcessType = from . genProcessType ; this . genProcessId = from . genProcessId ; this . backProcessId = from . backProcessId ; }


Input: The files that comprise the collection . Actual paths including the grib cache if used . [CODESPLIT] public List < String > getFilenames ( ) { List < String > result = new ArrayList <> ( ) ; for ( MFile file : fileMap . values ( ) ) result . ( file . getPath ( ) ) ; Collections . sort ( result ) ; return result ; }


Input: public by accident do not use [CODESPLIT] void setIndexRaf ( RandomAccessFile indexRaf ) { this . indexRaf = indexRaf ; if ( indexRaf != null ) { this . indexFilename = indexRaf . getLocation ( ) ; } }


Input: get index filename [CODESPLIT] private String getIndexFilepathInCache ( ) { File indexFile = GribCdmIndex . makeIndexFile ( name , directory ) ; return GribIndexCache . getFileOrCache ( indexFile . getPath ( ) ) . getPath ( ) ; }


Input: set from GribCollectionBuilderFromIndex . readFromIndex () [CODESPLIT] File setOrgDirectory ( String orgDirectory ) { this . orgDirectory = orgDirectory ; directory = new File ( orgDirectory ) ; if ( ! directory . exists ( ) ) { File indexFile = new File ( indexFilename ) ; File parent = indexFile . getParentFile ( ) ; if ( parent . exists ( ) ) directory = parent ; } return directory ; }


Input: stuff for FileCacheable [CODESPLIT] public void close ( ) throws java . io . IOException { if ( indexRaf != null ) { indexRaf . close ( ) ; indexRaf = null ; } }


Input: Coverity [ CALL_SUPER ] [CODESPLIT] public void printXML ( PrintWriter pw , String pad , boolean constrained ) { Enumeration e = getAttributeNames ( ) ; Enumeration ve = getVariables ( ) ; boolean hasAttributes = e . hasMoreElements ( ) ; boolean hasVariables = ve . hasMoreElements ( ) ; pw . print ( pad + "<" + getTypeName ( ) ) ; if ( getEncodedName ( ) != null ) { pw . print ( " name=\"" + DDSXMLParser . normalizeToXML ( getClearName ( ) ) + "\"" ) ; } if ( hasAttributes || hasVariables ) { pw . println ( ">" ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( aName ) ; if ( a != null ) a . printXML ( pw , pad + "\t" , constrained ) ; } while ( ve . hasMoreElements ( ) ) { BaseType bt = ( BaseType ) ve . nextElement ( ) ; bt . printXML ( pw , pad + "\t" , constrained ) ; } pw . println ( pad + "</" + getTypeName ( ) + ">" ) ; } else { pw . println ( "/>" ) ; } }


Input: Number of nested fields [CODESPLIT] public int ncounters ( ) { if ( nested == null ) return 1 ; else { int ncounters = 0 ; for ( BitCounterCompressed [ ] counters : nested ) { if ( counters == null ) continue ; for ( BitCounterCompressed counter : counters ) if ( counter != null ) ncounters += counter . ncounters ( ) ; } return ncounters ; } }


Input: Open an existing Netcdf file for writing data . Cannot add new objects you can only read / write data to existing Variables . Setting fill = false is more efficient use when you know you will write all data . [CODESPLIT] static public NetcdfFileWriteable openExisting ( String location , boolean fill ) throws IOException { return new NetcdfFileWriteable ( location , fill , true ) ; }


Input: Create a new Netcdf file put it into define mode . Make calls to addXXX () then when all objects are added call create () . You cannot read or write data until create () is called . Setting fill = false is more efficient use when you know you will write all data . [CODESPLIT] static public NetcdfFileWriteable createNew ( String location , boolean fill ) throws IOException { return new NetcdfFileWriteable ( location , fill , false ) ; }


Input: Add a Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( String dimName , int length ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( length <= 0 ) throw new IllegalArgumentException ( "dimension length must be > 0 :" + length ) ; if ( ! N3iosp . isValidNetcdfObjectName ( dimName ) ) throw new IllegalArgumentException ( "illegal netCDF-3 dimension name: " + dimName ) ; Dimension dim = new Dimension ( dimName , length , true , false , false ) ; super . addDimension ( null , dim ) ; return dim ; }


Input: Add a Dimension to the file . Must be in define mode . [CODESPLIT] public Dimension addDimension ( String dimName , int length , boolean isShared , boolean isUnlimited , boolean isVariableLength ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( dimName ) ) throw new IllegalArgumentException ( "illegal netCDF-3 dimension name " + dimName ) ; Dimension dim = new Dimension ( dimName , length , isShared , isUnlimited , isVariableLength ) ; super . addDimension ( null , dim ) ; return dim ; }


Input: Rename a Dimension . Must be in define mode . [CODESPLIT] public Dimension renameDimension ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Dimension dim = findDimension ( oldName ) ; if ( null != dim ) dim . setName ( newName ) ; return dim ; }


Input: Add a Global attribute to the file . Must be in define mode . [CODESPLIT] public Attribute addGlobalAttribute ( Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( att . getShortName ( ) ) ) { String attName = N3iosp . makeValidNetcdfObjectName ( att . getShortName ( ) ) ; log . warn ( "illegal netCDF-3 attribute name= " + att . getShortName ( ) + " change to " + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } return super . addAttribute ( null , att ) ; }


Input: Add a Global attribute of type String to the file . Must be in define mode . [CODESPLIT] public Attribute addGlobalAttribute ( String name , String value ) { return addGlobalAttribute ( new Attribute ( name , value ) ) ; }


Input: Add a Global attribute of type Array to the file . Must be in define mode . [CODESPLIT] public Attribute addGlobalAttribute ( String name , Array values ) { return addGlobalAttribute ( new Attribute ( name , values ) ) ; }


Input: Delete a global Attribute . Must be in define mode . [CODESPLIT] public Attribute deleteGlobalAttribute ( String attName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Attribute att = findGlobalAttribute ( attName ) ; if ( null == att ) return null ; rootGroup . remove ( att ) ; return att ; }


Input: Rename a global Attribute . Must be in define mode . [CODESPLIT] public Attribute renameGlobalAttribute ( String oldName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Attribute att = findGlobalAttribute ( oldName ) ; if ( null == att ) return null ; rootGroup . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; rootGroup . addAttribute ( att ) ; return att ; }


Input: Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String varName , DataType dataType , Dimension [ ] dims ) { ArrayList < Dimension > list = new ArrayList < Dimension > ( ) ; list . addAll ( Arrays . asList ( dims ) ) ; return addVariable ( varName , dataType , list ) ; }


Input: Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String varName , DataType dataType , String dims ) { // parse the list ArrayList < Dimension > list = new ArrayList < Dimension > ( ) ; StringTokenizer stoker = new StringTokenizer ( dims ) ; while ( stoker . hasMoreTokens ( ) ) { String tok = stoker . nextToken ( ) ; Dimension d = rootGroup . findDimension ( tok ) ; if ( null == d ) throw new IllegalArgumentException ( "Cant find dimension " + tok ) ; list . add ( d ) ; } return addVariable ( varName , dataType , list ) ; }


Input: Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String shortName , DataType dataType , List < Dimension > dims ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( shortName ) ) throw new IllegalArgumentException ( "illegal netCDF-3 variable name: " + shortName ) ; if ( ! valid . contains ( dataType ) ) throw new IllegalArgumentException ( "illegal dataType for netcdf-3 format: " + dataType ) ; // check unlimited int count = 0 ; for ( Dimension d : dims ) { if ( d . isUnlimited ( ) ) if ( count != 0 ) throw new IllegalArgumentException ( "Unlimited dimension " + d + " must be first instead its  =" + count ) ; count ++ ; } Variable v = new Variable ( this , rootGroup , null , shortName ) ; v . setDataType ( dataType ) ; v . setDimensions ( dims ) ; long size = v . getSize ( ) * v . getElementSize ( ) ; if ( size > N3iosp . MAX_VARSIZE ) throw new IllegalArgumentException ( "Variable size in bytes " + size + " may not exceed " + N3iosp . MAX_VARSIZE ) ; super . addVariable ( null , v ) ; return v ; }


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


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


Input: Add an attribute to the named Variable . Must be in define mode . [CODESPLIT] public void addVariableAttribute ( String varName , Attribute att ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( ! N3iosp . isValidNetcdfObjectName ( att . getShortName ( ) ) ) { String attName = N3iosp . makeValidNetcdfObjectName ( att . getShortName ( ) ) ; log . warn ( "illegal netCDF-3 attribute name= " + att . getShortName ( ) + " change to " + attName ) ; att = new Attribute ( attName , att . getValues ( ) ) ; } Variable v = rootGroup . findVariable ( varName ) ; if ( null == v ) throw new IllegalArgumentException ( "addVariableAttribute variable name not found = <" + varName + ">" ) ; v . addAttribute ( att ) ; }


Input: Add an attribute of type String to the named Variable . Must be in define mode . [CODESPLIT] public void addVariableAttribute ( String varName , String attName , String value ) { addVariableAttribute ( varName , new Attribute ( attName , value ) ) ; }


Input: Add an attribute of type Array to the named Variable . Must be in define mode . [CODESPLIT] public void addVariableAttribute ( String varName , String attName , Array value ) { Attribute att = new Attribute ( attName , value ) ; addVariableAttribute ( varName , att ) ; }


Input: Delete a variable Attribute . Must be in define mode . [CODESPLIT] public Attribute deleteVariableAttribute ( String varName , String attName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Variable v = findVariable ( varName ) ; if ( v == null ) return null ; Attribute att = v . findAttribute ( attName ) ; if ( null == att ) return null ; v . remove ( att ) ; return att ; }


Input: Rename a variable Attribute . Must be in define mode . [CODESPLIT] public Attribute renameVariableAttribute ( String varName , String attName , String newName ) { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; Variable v = findVariable ( varName ) ; if ( v == null ) return null ; Attribute att = v . findAttribute ( attName ) ; if ( null == att ) return null ; v . remove ( att ) ; att = new Attribute ( newName , att . getValues ( ) ) ; v . addAttribute ( att ) ; return att ; }


Input: Update the value of an existing attribute . Attribute is found by name which must match exactly . You cannot make an attribute longer or change the number of values . For strings : truncate if longer zero fill if shorter . Strings are padded to 4 byte boundaries ok to use padding if it exists . For numerics : must have same number of values . [CODESPLIT] public void updateAttribute ( ucar . nc2 . Variable v2 , Attribute att ) throws IOException { if ( defineMode ) throw new UnsupportedOperationException ( "in define mode" ) ; spiw . updateAttribute ( v2 , att ) ; }


Input: After you have added all of the Dimensions Variables and Attributes call create () to actually create the file . You must be in define mode . After this call you are no longer in define mode . [CODESPLIT] public void create ( ) throws java . io . IOException { if ( ! defineMode ) throw new UnsupportedOperationException ( "not in define mode" ) ; if ( cached_spiw == null ) { spi = SPFactory . getServiceProvider ( ) ; spiw = ( IOServiceProviderWriter ) spi ; } else { spiw = cached_spiw ; spi = spiw ; } spiw . setFill ( fill ) ; spiw . create ( location , this , extraHeader , preallocateSize , isLargeFile ) ; defineMode = false ; }


Input:
rewrite entire file [CODESPLIT] private void rewrite ( ) throws IOException { // close existing file, rename and open as read-only spiw . flush ( ) ; spiw . close ( ) ; File prevFile = new File ( location ) ; File tmpFile = new File ( location + ".tmp" ) ; if ( tmpFile . exists ( ) ) tmpFile . delete ( ) ; if ( ! prevFile . renameTo ( tmpFile ) ) { System . out . printf ( "%50s prevFile.exists=%s canRead=%s canWrite=%s%n" , prevFile . getPath ( ) , prevFile . exists ( ) , prevFile . canRead ( ) , prevFile . canWrite ( ) ) ; System . out . printf ( "%50s  tmpFile.exists=%s canRead=%s canWrite=%s%n" , tmpFile . getPath ( ) , tmpFile . exists ( ) , tmpFile . canRead ( ) , tmpFile . canWrite ( ) ) ; throw new RuntimeException ( "Cant rename " + prevFile . getAbsolutePath ( ) + " to " + tmpFile . getAbsolutePath ( ) ) ; } NetcdfFile oldFile = NetcdfFile . open ( tmpFile . getPath ( ) ) ; // use record dimension if it has one Structure recordVar = null ; if ( oldFile . hasUnlimitedDimension ( ) ) { oldFile . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; recordVar = ( Structure ) oldFile . findVariable ( "record" ) ; /* if (recordVar != null) {
        Boolean result = (Boolean) spiw.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);
        if (!result)
          recordVar = null;
      } */ } // create new file with current set of objects spiw . create ( location , this , extraHeader , preallocateSize , isLargeFile ) ; spiw . setFill ( fill ) ; //isClosed = false; // wait till header is written before adding the record variable to the file if ( recordVar != null ) { Boolean result = ( Boolean ) spiw . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ! result ) recordVar = null ; } // copy old file to new List < Variable > oldList = new ArrayList < Variable > ( getVariables ( ) . size ( ) ) ; for ( Variable v : getVariables ( ) ) { Variable oldVar = oldFile . findVariable ( v . getFullNameEscaped ( ) ) ; if ( oldVar != null ) oldList . add ( oldVar ) ; } FileWriter . copyVarData ( this , oldList , recordVar , null ) ; flush ( ) ; // delete old oldFile . close ( ) ; if ( ! tmpFile . delete ( ) ) throw new RuntimeException ( "Cant delete " + location ) ; }


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


Input: Write data to the named variable . Must not be in define mode . [CODESPLIT] public void write ( String fullNameEsc , int [ ] origin , Array values ) throws java . io . IOException , InvalidRangeException { if ( defineMode ) throw new UnsupportedOperationException ( "in define mode" ) ; ucar . nc2 . Variable v2 = findVariable ( fullNameEsc ) ; if ( v2 == null ) throw new IllegalArgumentException ( "NetcdfFileWriteable.write illegal variable name = " + fullNameEsc ) ; spiw . writeData ( v2 , new Section ( origin , values . getShape ( ) ) , values ) ; v2 . invalidateCache ( ) ; }


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


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


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


Input: Add a variable to the file . Must be in define mode . [CODESPLIT] public Variable addVariable ( String varName , Class componentType , Dimension [ ] dims ) { List < Dimension > list = new ArrayList < Dimension > ( ) ; list . addAll ( Arrays . asList ( dims ) ) ; return addVariable ( varName , DataType . getType ( componentType , false ) , list ) ; // LOOK unsigned }


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


Input:
Initialize this reader . Get the Grid specific info [CODESPLIT] protected boolean init ( boolean fullCheck ) throws IOException { if ( ! super . init ( fullCheck ) ) { return false ; } // Modeled after SF_OFIL
 if ( dmLabel . kftype != MFSF ) { logError ( "not a surface data file " ) ; return false ; } int numParams = 0 ; String partType = ( ( dmLabel . kfsrce == 100 ) && ( dmLabel . kprt == 1 ) ) ? SFTX : SFDT ; DMPart part = getPart ( partType ) ; if ( part == null ) { logError ( "No part named " + partType + " found" ) ; return false ; } else { numParams = part . kparms ; } if ( ! readStationsAndTimes ( true ) ) { logError ( "Unable to read stations and times" ) ; return false ; } // since the reads are ob by ob, set buffer size small
 if ( subType . equals ( STANDARD ) ) rf . setBufferSize ( 256 ) ; return true ; }


Input:
Set the file subType . [CODESPLIT] protected void makeFileSubType ( ) { // determine file type
 Key key = findKey ( GempakStation . SLAT ) ; if ( key == null ) throw new IllegalStateException ( "File does not have key=" + GempakStation . SLAT ) ; String latType = key . type ; Key dateKey = findKey ( DATE ) ; if ( dateKey != null && ! dateKey . type . equals ( latType ) ) { if ( latType . equals ( ROW ) ) { subType = CLIMATE ; } else { subType = STANDARD ; } } else { subType = SHIP ; } }


Input: Print the list of dates in the file [CODESPLIT] public void printOb ( int row , int col ) { int stnIndex = ( getFileSubType ( ) . equals ( CLIMATE ) ) ? row : col ; List < GempakStation > stations = getStations ( ) ; if ( stations . isEmpty ( ) || stnIndex > stations . size ( ) ) { System . out . println ( "\nNo data available" ) ; return ; } GempakStation station = getStations ( ) . get ( stnIndex - 1 ) ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "\nStation:\n" ) ; builder . append ( station . toString ( ) ) ; builder . append ( "\nObs\n\t" ) ; List < GempakParameter > params = getParameters ( SFDT ) ; for ( GempakParameter parm : params ) { builder . append ( StringUtil2 . padLeft ( parm . getName ( ) , 7 ) ) ; builder . append ( "\t" ) ; } builder . append ( "\n" ) ; RData rd ; try { rd = DM_RDTR ( row , col , SFDT ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; rd = null ; } if ( rd == null ) { builder . append ( "No Data Available" ) ; } else { builder . append ( "\t" ) ; float [ ] data = rd . data ; for ( int i = 0 ; i < data . length ; i ++ ) { builder . append ( StringUtil2 . padLeft ( Format . formatDouble ( data [ i ] , 7 , 1 ) , 7 ) ) ; builder . append ( "\t" ) ; } int [ ] header = rd . header ; if ( header . length > 0 ) { builder . append ( "\nOb Time = " ) ; builder . append ( header [ 0 ] ) ; } } System . out . println ( builder . toString ( ) ) ; }


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


Input:
Writes headers and bounding box [CODESPLIT] private void writeHeadersAndBB ( ) { fileOutput += "<wfs:FeatureCollection xsi:schemaLocation=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/wfs/2.0 http://schemas.opengis.net/wfs/2.0/wfs.xsd " + namespace + " " + server + "?request=DescribeFeatureType" + WFSXMLHelper . AMPERSAND + "service=wfs" + WFSXMLHelper . AMPERSAND + "version=2.0.0" + WFSXMLHelper . AMPERSAND + "typename=" + WFSController . TDSNAMESPACE + "%3A" + ftName ) + " xmlns:xsi=" + WFSXMLHelper . encQuotes ( "http://www.w3.org/2001/XMLSchema-instance" ) + " xmlns:xlink=" + WFSXMLHelper . encQuotes ( "http://www.w3.org/1999/xlink" ) + " xmlns:gml=" + WFSXMLHelper . encQuotes ( "http://opengis.net/gml/3.2" ) + " xmlns:fes=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/fes/2.0" ) + " xmlns:ogc=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/ogc" ) + " xmlns:wfs=" + WFSXMLHelper . encQuotes ( "http://opengis.net/wfs/2.0" ) + " xmlns:" + WFSController . TDSNAMESPACE + "=" + WFSXMLHelper . encQuotes ( namespace ) + " xmlns=" + WFSXMLHelper . encQuotes ( "http://www.opengis.net/wfs/2.0" ) + " version=\"2.0.0\" numberMatched=" + WFSXMLHelper . encQuotes ( String . valueOf ( geometries . size ( ) ) ) + " numberReturned=" + WFSXMLHelper . encQuotes ( String . valueOf ( geometries . size ( ) ) ) + ">" ; double [ ] boundLower ; double [ ] boundUpper ; if ( geometries . isEmpty ( ) ) { boundLower = new double [ 2 ] ; boundUpper = new double [ 2 ] ; boundLower [ 0 ] = - 180 ; boundLower [ 1 ] = - 90 ; boundUpper [ 0 ] = 180 ; boundUpper [ 1 ] = 90 ; } else { boundLower = geometries . get ( 0 ) . getBBLower ( ) ; boundUpper = geometries . get ( 0 ) . getBBUpper ( ) ; } // WFS Bounding Box
 for ( SimpleGeometry item : geometries ) { // Find the overall BB
 // Test Lower
 double [ ] low = item . getBBLower ( ) ; if ( boundLower [ 0 ] > low [ 0 ] ) boundLower [ 0 ] = low [ 0 ] ; if ( boundLower [ 1 ] > low [ 1 ] ) boundLower [ 1 ] = low [ 1 ] ; // Test Upper
 double [ ] upper = item . getBBUpper ( ) ; if ( boundUpper [ 0 ] < upper [ 0 ] ) boundUpper [ 0 ] = upper [ 0 ] ; if ( boundUpper [ 1 ] < upper [ 1 ] ) boundUpper [ 1 ] = upper [ 1 ] ; // Add some padding
 boundLower [ 0 ] -= 10 ; boundLower [ 1 ] -= 10 ; boundUpper [ 0 ] += 10 ; boundUpper [ 1 ] += 10 ; } fileOutput += "<wfs:boundedBy>" + "<wfs:Envelope srsName=" + "\"urn:ogc:def:crs:EPSG::4326\"" + ">" + "<wfs:lowerCorner>" + boundLower [ 0 ] + " " + boundLower [ 1 ] + "</wfs:lowerCorner>" + "<wfs:upperCorner>" + boundUpper [ 0 ] + " " + boundUpper [ 1 ] + "</wfs:upperCorner>" + "</wfs:Envelope>" + "</wfs:boundedBy>" ; }


Input:
In the WFS specification for GetFeature each feature type is its own member and so writeMembers add each member to the fileOutput [CODESPLIT] public void writeMembers ( ) { int index = 1 ; GMLFeatureWriter writer = new GMLFeatureWriter ( ) ; for ( SimpleGeometry geometryItem : geometries ) { // Find bounding box information
 double [ ] lowerCorner = geometryItem . getBBLower ( ) ; double [ ] upperCorner = geometryItem . getBBUpper ( ) ; fileOutput += "<wfs:member>" // Write Geometry Information
 + "<" + WFSController . TDSNAMESPACE + ":" + ftName + " gml:id=\"" + ftName + "." + index + "\">" // GML Bounding Box
 + "<gml:boundedBy>" + "<gml:Envelope srsName=" + "\"urn:ogc:def:crs:EPSG::4326\"" + ">" + "<gml:lowerCorner>" + lowerCorner [ 0 ] + " " + lowerCorner [ 1 ] + "</gml:lowerCorner>" + "<gml:upperCorner>" + upperCorner [ 0 ] + " " + upperCorner [ 1 ] + "</gml:upperCorner>" + "</gml:Envelope>" + "</gml:boundedBy>" + "<" + WFSController . TDSNAMESPACE + ":geometryInformation>" ; //write GML features
 fileOutput += writer . writeFeature ( geometryItem ) ; // Cap off headers
 fileOutput += "</" + WFSController . TDSNAMESPACE + ":geometryInformation>" + "</" + WFSController . TDSNAMESPACE + ":" + ftName + ">" + "</wfs:member>" ; index ++ ; } }


Input: Write stationObsDataset XML document [CODESPLIT] public String writeStationObsDatasetXML ( ) { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( makeStationObsDatasetDocument ( ) ) ; }


Input: Write stationCollection XML document [CODESPLIT] public String writeStationCollectionXML ( ) throws IOException { XMLOutputter fmt = new XMLOutputter ( Format . getPrettyFormat ( ) ) ; return fmt . outputString ( makeStationCollectionDocument ( ) ) ; }


Input: Create an XML document from this info [CODESPLIT] public Document makeStationCollectionDocument ( ) throws IOException { Element rootElem = new Element ( "stationCollection" ) ; Document doc = new Document ( rootElem ) ; List stns = sobs . getStations ( ) ; System . out . println ( "nstns = " + stns . size ( ) ) ; for ( int i = 0 ; i < stns . size ( ) ; i ++ ) { ucar . unidata . geoloc . Station s = ( ucar . unidata . geoloc . Station ) stns . get ( i ) ; Element sElem = new Element ( "station" ) ; sElem . setAttribute ( "name" , s . getName ( ) ) ; if ( s . getWmoId ( ) != null ) sElem . setAttribute ( "wmo_id" , s . getWmoId ( ) ) ; if ( s . getDescription ( ) != null ) sElem . addContent ( new Element ( "description" ) . addContent ( s . getDescription ( ) ) ) ; sElem . addContent ( new Element ( "longitude" ) . addContent ( ucar . unidata . util . Format . d ( s . getLongitude ( ) , 6 ) ) ) ; sElem . addContent ( new Element ( "latitide" ) . addContent ( ucar . unidata . util . Format . d ( s . getLatitude ( ) , 6 ) ) ) ; if ( ! Double . isNaN ( s . getAltitude ( ) ) ) sElem . addContent ( new Element ( "altitude" ) . addContent ( ucar . unidata . util . Format . d ( s . getAltitude ( ) , 6 ) ) ) ; rootElem . addContent ( sElem ) ; } return doc ; }


Input:
Create an XML document from this info [CODESPLIT] public Document makeStationObsDatasetDocument ( ) { Element rootElem = new Element ( "stationObsDataset" ) ; Document doc = new Document ( rootElem ) ; rootElem . setAttribute ( "location" , sobs . getLocationURI ( ) ) ; if ( null != path ) rootElem . setAttribute ( "path" , path ) ; /* dimensions
    List dims = getDimensions(sobs);
    for (int j = 0; j < dims.size(); j++) {
      Dimension dim = (Dimension) dims.get(j);
      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeDimension(dim, null));
    } */ /* coordinate axes
    List coordAxes = getCoordAxes(sobs);
    for (int i = 0; i < coordAxes.size(); i++) {
      CoordinateAxis axis = (CoordinateAxis) coordAxes.get(i);
      rootElem.addContent(writeAxis(axis));
    } */ // grids List vars = sobs . getDataVariables ( ) ; Collections . sort ( vars ) ; for ( int i = 0 ; i < vars . size ( ) ; i ++ ) { VariableSimpleIF v = ( VariableSimpleIF ) vars . get ( i ) ; rootElem . addContent ( writeVariable ( v ) ) ; } /* global attributes
    Iterator atts = sobs.getGlobalAttributes().iterator();
    while (atts.hasNext()) {
      ucar.nc2.Attribute att = (ucar.nc2.Attribute) atts.next();
      rootElem.addContent(ucar.nc2.ncml.NcMLWriter.writeAttribute(att, "attribute", null));
    } */ // add lat/lon bounding box LatLonRect bb = sobs . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range Date start = sobs . getStartDate ( ) ; Date end = sobs . getEndDate ( ) ; if ( ( start != null ) && ( end != null ) ) { DateFormatter format = new DateFormatter ( ) ; Element dateRange = new Element ( "TimeSpan" ) ; dateRange . addContent ( new Element ( "begin" ) . addContent ( format . toDateTimeStringISO ( start ) ) ) ; dateRange . addContent ( new Element ( "end" ) . addContent ( format . toDateTimeStringISO ( end ) ) ) ; rootElem . addContent ( dateRange ) ; } // add accept list Element elem = new Element ( "AcceptList" ) ; elem . addContent ( new Element ( "accept" ) . addContent ( "raw" ) ) ; elem . addContent ( new Element ( "accept" ) . addContent ( "xml" ) ) ; elem . addContent ( new Element ( "accept" ) . addContent ( "csv" ) ) ; elem . addContent ( new Element ( "accept" ) . addContent ( "netcdf" ) ) ; elem . addContent ( new Element ( "accept" ) . addContent ( "netcdfStream" ) ) ; rootElem . addContent ( elem ) ; return doc ; }


Input: debug [CODESPLIT] public static void main ( String args [ ] ) throws IOException { String url = "C:/data/metars/Surface_METAR_20060326_0000.nc" ; StationObsDataset ncd = ( StationObsDataset ) TypedDatasetFactory . open ( FeatureType . STATION , url , null , new StringBuilder ( ) ) ; StationObsDatasetInfo info = new StationObsDatasetInfo ( ncd , null ) ; FileOutputStream fos2 = new FileOutputStream ( "C:/TEMP/stationCollection.xml" ) ; GZIPOutputStream zout = new GZIPOutputStream ( fos2 ) ; info . writeStationObsDatasetXML ( System . out ) ; info . writeStationCollectionXML ( zout ) ; zout . close ( ) ; File f = new File ( "C:/TEMP/stationCollection.xml" ) ; System . out . println ( " size=" + f . length ( ) ) ; }


Input: Write the DSR ; do not bother to cache . [CODESPLIT] public void writeDSR ( String dsr ) throws IOException { if ( state != State . INITIAL ) throw new DapException ( "Attempt to write DSR twice" ) ; if ( dsr == null ) throw new DapException ( "Attempt to write empty DSR" ) ; // Strip off any trailing sequence of CR or LF. int len = dsr . length ( ) ; while ( len > 0 ) { char c = dsr . charAt ( len - 1 ) ; if ( c != ' ' && c != ' ' ) break ; len -- ; } if ( dsr . length ( ) == 0 ) throw new DapException ( "Attempt to write empty DSR" ) ; dsr = dsr . substring ( 0 , len ) + DapUtil . CRLF ; // Add <?xml...?> prefix dsr = XMLDOCUMENTHEADER + "\n" + dsr ; // Convert the dsr to UTF-8 and then to byte[] byte [ ] dsr8 = DapUtil . extract ( DapUtil . UTF8 . encode ( dsr ) ) ; sendDXR ( dsr8 ) ; state = State . END ; }