signature:
public class ServletUtil { /** * Forward this request to the CatalogServices servlet ( " / catalog . html " ) .
 * @ param req request
 * @ param res response
 * @ throws IOException on IO error
 * @ throws ServletException other error */
public static void forwardToCatalogServices ( HttpServletRequest req , HttpServletResponse res ) throws IOException , ServletException { } }

implementation:
String reqs = "catalog=" + getReletiveURL ( req ) ; String query = req . getQueryString ( ) ; if ( query != null ) reqs = reqs + "&" + query ; log . info ( "forwardToCatalogServices(): request string = \"/catalog.html?" + reqs + "\"" ) ; // dispatch to CatalogHtml servlet
RequestForwardUtils . forwardRequestRelativeToCurrentContext ( "/catalog.html?" + reqs , req , res ) ;


signature:
public class ServletUtil { /** * This is the server part , eg http : / / motherlode : 8080
 * @ param req the HttpServletRequest
 * @ return request server */
public static String getRequestServer ( HttpServletRequest req ) { } }

implementation: return req . getScheme ( ) + "://" + req . getServerName ( ) + ":" + req . getServerPort ( ) ;


signature:
public class ServletUtil { /** * The request base as a URI
 * @ param req the HttpServletRequest
 * @ return parsed request as a URI */
public static URI getRequestURI ( HttpServletRequest req ) { } }

implementation: try { return new URI ( getRequestBase ( req ) ) ; } catch ( URISyntaxException e ) { e . printStackTrace ( ) ; return null ; }


signature:
public class ServletUtil { /** * servletPath + pathInfo
 * @ param req the HttpServletRequest
 * @ return parsed request servletPath + pathInfo */
public static String getRequestPath ( HttpServletRequest req ) { } }

implementation: StringBuilder buff = new StringBuilder ( ) ; if ( req . getServletPath ( ) != null ) buff . append ( req . getServletPath ( ) ) ; if ( req . getPathInfo ( ) != null ) buff . append ( req . getPathInfo ( ) ) ; return buff . toString ( ) ;


signature:
public class ServletUtil { /** * The entire request including query string
 * @ param req the HttpServletRequest
 * @ return entire parsed request */
public static String getRequest ( HttpServletRequest req ) { } }

implementation: String query = req . getQueryString ( ) ; return getRequestBase ( req ) + ( query == null ? "" : "?" + query ) ;


signature:
public class ServletUtil { /** * Return the value of the given parameter for the given request . Should
 * only be used if the parameter is known to only have one value . If used
 * on a multi - valued parameter , the first value is returned .
 * @ param req the HttpServletRequest
 * @ param paramName the name of the parameter to find .
 * @ return the value of the given parameter for the given request . */
public static String getParameterIgnoreCase ( HttpServletRequest req , String paramName ) { } }

implementation: Enumeration e = req . getParameterNames ( ) ; while ( e . hasMoreElements ( ) ) { String s = ( String ) e . nextElement ( ) ; if ( s . equalsIgnoreCase ( paramName ) ) return req . getParameter ( s ) ; } return null ;


signature:
public class ServletUtil { /** * Show details about the request
 * @ param req the request
 * @ return string showing the details of the request . */
static public String showRequestDetail ( HttpServletRequest req ) { } }

implementation:
StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( "Request Info\n" ) ; sbuff . append ( " req.getServerName(): " ) . append ( req . getServerName ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getServerPort(): " ) . append ( req . getServerPort ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getContextPath:" ) . append ( req . getContextPath ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getServletPath:" ) . append ( req . getServletPath ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getPathInfo:" ) . append ( req . getPathInfo ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getQueryString:" ) . append ( req . getQueryString ( ) ) . append ( "\n" ) ; sbuff . append ( " getQueryStringDecoded:" ) . append ( EscapeStrings . urlDecode ( req . getQueryString ( ) ) ) . append ( "\n" ) ; /* try {
 sbuff . append ( " getQueryStringDecoded : " ) . append ( URLDecoder . decode ( req . getQueryString ( ) , " UTF - 8 " ) ) . append ( " \ n " ) ;
 } catch ( UnsupportedEncodingException e1 ) {
 e1 . printStackTrace ( ) ; */
sbuff . append ( " req.getRequestURI:" ) . append ( req . getRequestURI ( ) ) . append ( "\n" ) ; sbuff . append ( " getRequestBase:" ) . append ( getRequestBase ( req ) ) . append ( "\n" ) ; sbuff . append ( " getRequestServer:" ) . append ( getRequestServer ( req ) ) . append ( "\n" ) ; sbuff . append ( " getRequest:" ) . append ( getRequest ( req ) ) . append ( "\n" ) ; sbuff . append ( "\n" ) ; sbuff . append ( " req.getPathTranslated:" ) . append ( req . getPathTranslated ( ) ) . append ( "\n" ) ; sbuff . append ( "\n" ) ; sbuff . append ( " req.getScheme:" ) . append ( req . getScheme ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getProtocol:" ) . append ( req . getProtocol ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getMethod:" ) . append ( req . getMethod ( ) ) . append ( "\n" ) ; sbuff . append ( "\n" ) ; sbuff . append ( " req.getContentType:" ) . append ( req . getContentType ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getContentLength:" ) . append ( req . getContentLength ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getRemoteAddr():" ) . append ( req . getRemoteAddr ( ) ) ; try { sbuff . append ( " getRemoteHost():" ) . append ( java . net . InetAddress . getByName ( req . getRemoteHost ( ) ) . getHostName ( ) ) . append ( "\n" ) ; } catch ( java . net . UnknownHostException e ) { sbuff . append ( " getRemoteHost():" ) . append ( e . getMessage ( ) ) . append ( "\n" ) ; } sbuff . append ( " getRemoteUser():" ) . append ( req . getRemoteUser ( ) ) . append ( "\n" ) ; sbuff . append ( "\n" ) ; sbuff . append ( "Request Parameters:\n" ) ; Enumeration params = req . getParameterNames ( ) ; while ( params . hasMoreElements ( ) ) { String name = ( String ) params . nextElement ( ) ; String values [ ] = req . getParameterValues ( name ) ; if ( values != null ) { for ( int i = 0 ; i < values . length ; i ++ ) { sbuff . append ( "  " ) . append ( name ) . append ( "  (" ) . append ( i ) . append ( "): " ) . append ( values [ i ] ) . append ( "\n" ) ; } } } sbuff . append ( "\n" ) ; sbuff . append ( "Request Headers:\n" ) ; Enumeration names = req . getHeaderNames ( ) ; while ( names . hasMoreElements ( ) ) { String name = ( String ) names . nextElement ( ) ; Enumeration values = req . getHeaders ( name ) ; // support multiple values
if ( values != null ) { while ( values . hasMoreElements ( ) ) { String value = ( String ) values . nextElement ( ) ; sbuff . append ( "  " ) . append ( name ) . append ( ": " ) . append ( value ) . append ( "\n" ) ; } } } sbuff . append ( " ------------------\n" ) ; return sbuff . toString ( ) ;


signature:
public class ServletUtil { /** * / * static public void showSession ( HttpServletRequest req , PrintStream out ) {
 * res . setContentType ( " text / html " ) ;
 * Get the current session object , create one if necessary
 * HttpSession session = req . getSession ( ) ;
 * out . println ( " Session id : " + session . getId ( ) ) ;
 * out . println ( " session . isNew ( ) : " + session . isNew ( ) ) ;
 * out . println ( " session . getMaxInactiveInterval ( ) : " + session . getMaxInactiveInterval ( ) + " secs " ) ;
 * out . println ( " session . getCreationTime ( ) : " + session . getCreationTime ( ) + " ( " + new Date ( session . getCreationTime ( ) ) + " ) " ) ;
 * out . println ( " session . getLastAccessedTime ( ) : " + session . getLastAccessedTime ( ) + " ( " + new Date ( session . getLastAccessedTime ( ) ) + " ) " ) ;
 * out . println ( " req . isRequestedSessionIdFromCookie : " + req . isRequestedSessionIdFromCookie ( ) ) ;
 * out . println ( " req . isRequestedSessionIdFromURL : " + req . isRequestedSessionIdFromURL ( ) ) ;
 * out . println ( " req . isRequestedSessionIdValid : " + req . isRequestedSessionIdValid ( ) ) ;
 * out . println ( " Saved session Attributes : " ) ;
 * Enumeration atts = session . getAttributeNames ( ) ;
 * while ( atts . hasMoreElements ( ) ) {
 * String name = ( String ) atts . nextElement ( ) ;
 * out . println ( " " + name + " : " + session . getAttribute ( name ) + " < BR > " ) ; */
static public String showSecurity ( HttpServletRequest req , String role ) { } }

implementation: StringBuilder sbuff = new StringBuilder ( ) ; sbuff . append ( "Security Info\n" ) ; sbuff . append ( " req.getRemoteUser(): " ) . append ( req . getRemoteUser ( ) ) . append ( "\n" ) ; sbuff . append ( " req.getUserPrincipal(): " ) . append ( req . getUserPrincipal ( ) ) . append ( "\n" ) ; sbuff . append ( " req.isUserInRole(" ) . append ( role ) . append ( "):" ) . append ( req . isUserInRole ( role ) ) . append ( "\n" ) ; sbuff . append ( " ------------------\n" ) ; return sbuff . toString ( ) ;


signature:
public class ServletUtil { /** * / * static private String getServerInfoName ( String serverInfo ) {
 * int slash = serverInfo . indexOf ( ' / ' ) ;
 * if ( slash = = - 1 ) return serverInfo ;
 * else return serverInfo . substring ( 0 , slash ) ;
 * static private String getServerInfoVersion ( String serverInfo ) {
 * Version info is everything between the slash and the space
 * int slash = serverInfo . indexOf ( ' / ' ) ;
 * if ( slash = = - 1 ) return null ;
 * int space = serverInfo . indexOf ( ' ' , slash ) ;
 * if ( space = = - 1 ) space = serverInfo . length ( ) ;
 * return serverInfo . substring ( slash + 1 , space ) ; */
static public void showThreads ( PrintStream pw ) { } }

implementation: Thread current = Thread . currentThread ( ) ; ThreadGroup group = current . getThreadGroup ( ) ; while ( true ) { if ( group . getParent ( ) == null ) break ; group = group . getParent ( ) ; } showThreads ( pw , group , current ) ;


signature: public class AWIPSsatConvention { protected AxisType getAxisType ( NetcdfDataset ds , VariableEnhanced ve ) { } }

implementation: Variable v = ( Variable ) ve ; String vname = v . getShortName ( ) ; String units = v . getUnitsString ( ) ; if ( units . equalsIgnoreCase ( CDM . LON_UNITS ) ) return AxisType . Lon ; if ( units . equalsIgnoreCase ( CDM . LAT_UNITS ) ) return AxisType . Lat ; if ( vname . equalsIgnoreCase ( "x" ) ) return AxisType . GeoX ; if ( vname . equalsIgnoreCase ( "lon" ) ) return AxisType . Lon ; if ( vname . equalsIgnoreCase ( "y" ) ) return AxisType . GeoY ; if ( vname . equalsIgnoreCase ( "lat" ) ) return AxisType . Lat ; if ( vname . equalsIgnoreCase ( "record" ) ) return AxisType . Time ; Dimension dim = v . getDimension ( 0 ) ; if ( ( dim != null ) && dim . getShortName ( ) . equalsIgnoreCase ( "record" ) ) return AxisType . Time ; String unit = ve . getUnitsString ( ) ; if ( unit != null ) { if ( SimpleUnit . isCompatible ( "millibar" , unit ) ) return AxisType . Pressure ; if ( SimpleUnit . isCompatible ( "m" , unit ) ) return AxisType . Height ; } return AxisType . GeoZ ;


signature:
public class CatalogChooser { /** * Save persistent state . */
public void save ( ) { } }

implementation: if ( catListBox != null ) catListBox . save ( ) ; if ( prefs != null ) { if ( fileChooser != null ) fileChooser . save ( ) ; if ( catgenFileChooser != null ) catgenFileChooser . save ( ) ; prefs . putInt ( HDIVIDER , split . getDividerLocation ( ) ) ; }


signature:
public class CatalogChooser { /** * Wrap this in a JDialog component .
 * @ param parent JFrame ( application ) or JApplet ( applet ) or null
 * @ param title dialog window title
 * @ param modal is modal */
public JDialog makeDialog ( RootPaneContainer parent , String title , boolean modal ) { } }

implementation: this . parent = parent ; return new Dialog ( parent , title , modal ) ;


signature:
public class HtmlWriting { /** * Write a file directory .
 * @ param res the HttpServletResponse on which to write the file directory response .
 * @ param dir directory
 * @ param path the URL path reletive to the base
 * @ return the number of characters ( Unicode code units ) in the response .
 * @ throws java . io . IOException if an I / O exception occurs . */
public int writeDirectory ( HttpServletResponse res , File dir , String path ) throws IOException { } }

implementation:
// error checking
if ( dir == null ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return 0 ; } if ( ! dir . exists ( ) || ! dir . isDirectory ( ) ) { res . sendError ( HttpServletResponse . SC_NOT_FOUND ) ; return 0 ; } // Get directory as HTML
String dirHtmlString = getDirectory ( path , dir ) ; thredds . servlet . ServletUtil . setResponseContentLength ( res , dirHtmlString ) ; res . setContentType ( ContentType . html . getContentHeader ( ) ) ; PrintWriter writer = res . getWriter ( ) ; writer . write ( dirHtmlString ) ; writer . flush ( ) ; return dirHtmlString . length ( ) ;


signature:
public class ArrayFloat { /** * / * create new ArrayFloat with given indexImpl and backing store .
 * Should be private .
 * @ param index use this Index
 * @ param stor . use this storage . if null , allocate .
 * @ return . new ArrayFloat . D < rank > or ArrayFloat object . */
static ArrayFloat factory ( Index index , float [ ] storage ) { } }

implementation: if ( index instanceof Index0D ) { return new ArrayFloat . D0 ( index , storage ) ; } else if ( index instanceof Index1D ) { return new ArrayFloat . D1 ( index , storage ) ; } else if ( index instanceof Index2D ) { return new ArrayFloat . D2 ( index , storage ) ; } else if ( index instanceof Index3D ) { return new ArrayFloat . D3 ( index , storage ) ; } else if ( index instanceof Index4D ) { return new ArrayFloat . D4 ( index , storage ) ; } else if ( index instanceof Index5D ) { return new ArrayFloat . D5 ( index , storage ) ; } else if ( index instanceof Index6D ) { return new ArrayFloat . D6 ( index , storage ) ; } else if ( index instanceof Index7D ) { return new ArrayFloat . D7 ( index , storage ) ; } else { return new ArrayFloat ( index , storage ) ; }


signature:
public class ArrayFloat { /** * copy from javaArray to storage using the iterator : used by factory ( Object ) ; */
protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { } }

implementation: float [ ] ja = ( float [ ] ) javaArray ; for ( float aJa : ja ) iter . setFloatNext ( aJa ) ;


signature:
public class NcTimePositionType { /** * wml2 : MeasurementTVP / wml2 : time */
public static TimePositionType initTime ( TimePositionType time , PointFeature pointFeat ) { } }

implementation:
// TEXT
time . setStringValue ( pointFeat . getNominalTimeAsCalendarDate ( ) . toString ( ) ) ; return time ;


signature:
public class NcTimePositionType { /** * wml2 : Collection / wml2 : observationMember / om : OM _ Observation / om : phenomenonTime / gml : TimePeriod / gml : beginPosition */
public static TimePositionType initBeginPosition ( TimePositionType beginPosition , CalendarDate date ) throws IOException { } }

implementation:
// TEXT
beginPosition . setStringValue ( date . toString ( ) ) ; return beginPosition ;


signature:
public class NcTimePositionType { /** * wml2 : Collection / wml2 : observationMember / om : OM _ Observation / om : phenomenonTime / gml : TimePeriod / gml : endPosition */
public static TimePositionType initEndPosition ( TimePositionType endPosition , CalendarDate date ) throws IOException { } }

implementation:
// TEXT
endPosition . setStringValue ( date . toString ( ) ) ; return endPosition ;


signature:
public class NcTimePositionType { /** * wml2 : Collection / wml2 : observationMember / om : OM _ Observation / om : resultTime / gml : TimeInstant / gml : timePosition */
public static TimePositionType initTimePosition ( TimePositionType timePosition ) { } }

implementation:
DateTime resultTime = MarshallingUtil . fixedResultTime ; if ( resultTime == null ) { resultTime = new DateTime ( ) ; // Initialized to " now " .
} // TEXT
timePosition . setStringValue ( resultTime . toString ( ) ) ; return timePosition ;


signature: public class NsslRadialAdapter { public Object isMine ( FeatureType wantFeatureType , NetcdfDataset ncd , Formatter errlog ) throws IOException { } }

implementation: String format = ncd . findAttValueIgnoreCase ( null , "format" , null ) ; if ( format != null ) { if ( format . startsWith ( "nssl/netcdf" ) ) return this ; } Dimension az = ncd . findDimension ( "Azimuth" ) ; Dimension gt = ncd . findDimension ( "Gate" ) ; if ( ( null != az ) && ( null != gt ) ) { return this ; } return null ;


signature:
public class BitCounterUncompressed { /** * not used yet */
public void setBitOffset ( DataDescriptor dkey ) { } }

implementation: if ( bitPosition == null ) bitPosition = new HashMap < DataDescriptor , Integer > ( 2 * parent . getSubKeys ( ) . size ( ) ) ; bitPosition . put ( dkey , bitOffset ) ; bitOffset += dkey . getBitWidth ( ) ;


signature:
public class BitCounterUncompressed { /** * Track nested Tables .
 * @ param subKey subKey is a structure or a sequence - so itself has subKeys
 * @ param n numbers of rows in the nested table
 * @ param row which row in the parent Table this belongs to
 * @ param replicationCountSize number of bits taken up by the count ( non - zero for sequences )
 * @ return nested ReplicationCounter */
public BitCounterUncompressed makeNested ( DataDescriptor subKey , int n , int row , int replicationCountSize ) { } }

implementation:
if ( subCounters == null ) subCounters = new HashMap < DataDescriptor , BitCounterUncompressed [ ] > ( 5 ) ; // assumes DataDescriptor . equals is = =
BitCounterUncompressed [ ] subCounter = subCounters . get ( subKey ) ; if ( subCounter == null ) { subCounter = new BitCounterUncompressed [ nrows ] ; // one for each row in this table
subCounters . put ( subKey , subCounter ) ; } BitCounterUncompressed rc = new BitCounterUncompressed ( subKey , n , replicationCountSize ) ; subCounter [ row ] = rc ; return rc ;


signature:
public class BitCounterUncompressed { /** * total bits of this table and all subtables */
int countBits ( int startBit ) { } }

implementation:
countBits = replicationCountSize ; this . startBit = new int [ nrows ] ; for ( int i = 0 ; i < nrows ; i ++ ) { this . startBit [ i ] = startBit + countBits ; if ( debug ) System . out . println ( " BitCounterUncompressed row " + i + " startBit=" + this . startBit [ i ] ) ; for ( DataDescriptor nd : parent . subKeys ) { BitCounterUncompressed [ ] bitCounter = ( subCounters == null ) ? null : subCounters . get ( nd ) ; if ( bitCounter == null ) // a regular field
countBits += nd . getBitWidth ( ) ; else { if ( debug ) System . out . println ( " ---------> nested " + nd . getFxyName ( ) + " starts at =" + ( startBit + countBits ) ) ; countBits += bitCounter [ i ] . countBits ( startBit + countBits ) ; if ( debug ) System . out . println ( " <--------- nested " + nd . getFxyName ( ) + " ends at =" + ( startBit + countBits ) ) ; } } } return countBits ;


implementation:
Map < Integer , Grib2Parameter > result = new HashMap < > ( 100 ) ; try ( InputStream is = GribResourceReader . getInputStream ( resourcePath ) ) { if ( f != null ) f . format ( "%s, %-20s, %-20s, %-20s%n" , "id" , "name" , "units" , "gname" ) ; TableParser parser = new TableParser ( "3i,7i,11i,15i,49,69,74," ) ; parser . setComment ( "!" ) ; List < TableParser . Record > recs = parser . readAllRecords ( is , 50000 ) ; for ( TableParser . Record record : recs ) { int disc = ( Integer ) record . get ( 0 ) ; int cat = ( Integer ) record . get ( 1 ) ; int id = ( Integer ) record . get ( 2 ) ; int template = ( Integer ) record . get ( 3 ) ; // LOOK - 19 , 29 , 39 ? ? ?
String name = ( ( String ) record . get ( 4 ) ) . trim ( ) ; String units = ( ( String ) record . get ( 5 ) ) . trim ( ) ; String gname = ( ( String ) record . get ( 6 ) ) . trim ( ) ; String ids = disc + "-" + cat + "-" + id ; if ( f != null ) f . format ( "%s == %-20s, %-20s, %-20s%n" , ids , name , units , gname ) ; Grib2Parameter gp = new Grib2Parameter ( disc , cat , id , gname , units , null , name ) ; result . put ( Grib2Tables . makeParamId ( disc , cat , id ) , gp ) ; } } catch ( IOException ioe ) { throw new RuntimeException ( ioe ) ; } return result ;


signature:
public class TextHistoryPane { /** * Append this line to the bottom of the JTextArea .
 * A newline is added and JTextArea is scrolled to bottom ;
 * remove lines at top if needed .
 * @ param line append this line . Ok to have multiple lines ( ie embedded newlines )
 * but not too many . */
public void appendLine ( String line ) { } }

implementation:
if ( count >= nlines ) { try { int remove = Math . max ( removeIncr , count - nlines ) ; // nlines may have changed
int offset = ta . getLineEndOffset ( remove ) ; ta . replaceRange ( "" , 0 , offset ) ; } catch ( Exception e ) { log . error ( "Problem in TextHistoryPane" , e ) ; } count = nlines - removeIncr ; } ta . append ( line ) ; ta . append ( "\n" ) ; count ++ ; // scroll to end
ta . setCaretPosition ( ta . getText ( ) . length ( ) ) ;


signature:
public class Celex { /** * / * This is part of the Lexer interface */
public int yylex ( ) throws ParseException { } }

implementation:
int token ; int c ; token = 0 ; yytext . setLength ( 0 ) ; /* invariant : p always points to current char */
try { token = - 1 ; while ( token < 0 ) { if ( ( c = read ( ) ) <= 0 ) break ; if ( c == '\n' ) { } else if ( c <= ' ' || c == '\177' ) { /* whitespace : ignore */
} else if ( worddelims . indexOf ( c ) >= 0 ) { /* don ' t put in yytext to avoid memory leak */
token = c ; } else if ( c == '"' ) { boolean more = true ; /* We have a string token ; will be reported as SCAN _ STRINGCONST */
while ( more && ( c = read ( ) ) > 0 ) { if ( c == '"' ) more = false ; else if ( c == '\\' ) { c = read ( ) ; if ( c < 0 ) more = false ; } if ( more ) yytext . append ( ( char ) c ) ; } token = SCAN_STRINGCONST ; } else if ( false && numchars1 . indexOf ( c ) >= 0 ) { // we might have a SCAN _ NUMBERCONST
boolean isnumber = false ; yytext . append ( ( char ) c ) ; while ( ( c = read ( ) ) > 0 ) { if ( numcharsn . indexOf ( c ) < 0 ) { pushback ( c ) ; break ; } yytext . append ( ( char ) c ) ; } removetrailingblanks ( ) ; // See if this is a number
try { Double number = new Double ( yytext . toString ( ) ) ; isnumber = true ; } catch ( NumberFormatException nfe ) { isnumber = false ; } // A number followed by an id char is assumed to just be a funny id
if ( isnumber ) { c = read ( ) ; if ( wordcharsn . indexOf ( c ) >= 0 ) { // this is apparently just a funny id
token = SCAN_WORD ; } else { // its really a number
token = SCAN_NUMBERCONST ; if ( c != '\0' ) pushback ( c ) ; } } else { // ! isNumber
/* Now , if the funny word has a " . " in it ,
 we have to back up to that dot */
int dotpoint = yytext . toString ( ) . indexOf ( '.' ) ; if ( dotpoint >= 0 ) { for ( int i = 0 ; i < dotpoint ; i ++ ) { pushback ( yytext . charAt ( i ) ) ; } yytext . setLength ( dotpoint ) ; } token = SCAN_WORD ; } } else if ( wordornumberchars1 . indexOf ( c ) >= 0 ) { boolean isnumber = false ; /* we have a WORD or a number */
yytext . append ( ( char ) c ) ; while ( ( c = read ( ) ) > 0 ) { if ( wordornumbercharsn . indexOf ( c ) < 0 ) { pushback ( c ) ; break ; } yytext . append ( ( char ) c ) ; } removetrailingblanks ( ) ; /* If this looks like a number , then treat it as such . */
try { new Double ( yytext . toString ( ) ) ; isnumber = true ; } catch ( NumberFormatException nfe ) { isnumber = false ; } if ( isnumber ) token = SCAN_NUMBERCONST ; else { token = SCAN_WORD ; /* If this is a mistaken number , then we need to
 backup to the last occurrence of a dot ' . '
 because all other number characters are legitmate
 identifier characters . Special case occurs when
 we are left with a single dot . */
int dotpoint = yytext . toString ( ) . indexOf ( '.' ) ; if ( dotpoint >= 0 ) { // pushback the whole of yytext ( in reverse order )
for ( int i = yytext . length ( ) - 1 ; i >= 0 ; i -- ) pushback ( yytext . charAt ( i ) ) ; yytext . setLength ( 0 ) ; if ( dotpoint == 0 ) { // single character delimiter
token = '.' ; yytext . append ( ( char ) ( c = read ( ) ) ) ; } else { // Recollect up to but not including the first dot .
for ( int i = 0 ; i < dotpoint ; i ++ ) yytext . append ( ( char ) ( c = read ( ) ) ) ; } } } } else { /* we have a single char token */
token = c ; } } if ( token < 0 ) { token = 0 ; lval = null ; } else { // We have to apply DAP2 % xx escaping if this is a SCAN _ WORD
String text = yytext . toString ( ) ; if ( token == SCAN_WORD ) text = EscapeStrings . unescapeDAPIdentifier ( text ) ; lval = ( text . length ( ) == 0 ? ( String ) null : text ) ; } if ( parsestate . getDebugLevel ( ) > 0 ) dumptoken ( token , ( String ) lval ) ; return token ; /* Return the type of the token . */
} catch ( IOException ioe ) { throw new ParseException ( ioe ) ; }


signature:
public class Celex { /** * Entry point for error reporting . Emits an error
 * in a user - defined way .
 * @ param s The string for the error message . */
public void yyerror ( String s ) { } }

implementation:
Ceparse . log . error ( "yyerror: constraint parse error:" + s + "; char " + charno ) ; if ( yytext . length ( ) > 0 ) Ceparse . log . error ( " near |" + yytext + "|" ) ; // Add extra info
if ( parsestate . getURL ( ) != null ) Ceparse . log . error ( "\turl=" + parsestate . getURL ( ) ) ; Ceparse . log . error ( "\tconstraint=" + ( constraint == null ? "none" : constraint ) ) ;


signature:
public class MyMouseAdapter { /** * System . out . println ( " drag : " + deltax + " " + deltay ) ; } */
public static void main ( String args [ ] ) { } }

implementation: JFrame frame = new JFrame ( "Test MyMouseAdapter" ) ; frame . addWindowListener ( new WindowAdapter ( ) { public void windowClosing ( WindowEvent e ) { System . exit ( 0 ) ; } } ) ; JLabel comp = new JLabel ( "test  sdfk sdf ks;dflk ;sdlkf ldsk lk" ) ; comp . setOpaque ( true ) ; comp . setBackground ( Color . white ) ; comp . setForeground ( Color . black ) ; comp . addMouseListener ( new MyMouseAdapter ( ) ) ; JPanel main = new JPanel ( new FlowLayout ( ) ) ; frame . getContentPane ( ) . add ( main ) ; main . setPreferredSize ( new Dimension ( 200 , 200 ) ) ; main . add ( comp ) ; frame . pack ( ) ; frame . setLocation ( 300 , 300 ) ; frame . setVisible ( true ) ;


signature:
public class DapStructure { /** * Accessors */
public DapVariable findByName ( String shortname ) { } }

implementation: for ( DapVariable field : fields ) { if ( shortname . equals ( field . getShortName ( ) ) ) return field ; } return null ;


signature:
public class FeatureDatasetCapabilitiesWriter { /** * Create an XML document for the stations in this dataset , possible subsetted by bb .
 * Must be a station dataset .
 * @ param bb restrict stations to this bounding box , may be null
 * @ param names restrict stations to these names , may be null
 * @ return XML document for the stations
 * @ throws IOException on read error */
public Document makeStationCollectionDocument ( LatLonRect bb , String [ ] names ) throws IOException { } }

implementation:
List < DsgFeatureCollection > list = fdp . getPointFeatureCollectionList ( ) ; DsgFeatureCollection fc = list . get ( 0 ) ; // LOOK maybe should pass in the dsg ?
if ( ! ( fc instanceof StationTimeSeriesFeatureCollection ) ) { throw new UnsupportedOperationException ( fc . getClass ( ) . getName ( ) + " not a StationTimeSeriesFeatureCollection" ) ; } StationTimeSeriesFeatureCollection sobs = ( StationTimeSeriesFeatureCollection ) fc ; Element rootElem = new Element ( "stationCollection" ) ; Document doc = new Document ( rootElem ) ; List < StationFeature > stations ; if ( bb != null ) stations = sobs . getStationFeatures ( bb ) ; else if ( names != null ) stations = sobs . getStationFeatures ( Arrays . asList ( names ) ) ; else stations = sobs . getStationFeatures ( ) ; for ( Station s : stations ) { Element sElem = new Element ( "station" ) ; sElem . setAttribute ( "name" , s . getName ( ) ) ; if ( s . getWmoId ( ) != null ) sElem . setAttribute ( "wmo_id" , s . getWmoId ( ) ) ; if ( ( s . getDescription ( ) != null ) && ( s . getDescription ( ) . length ( ) > 0 ) ) sElem . addContent ( new Element ( "description" ) . addContent ( s . getDescription ( ) ) ) ; sElem . addContent ( new Element ( "longitude" ) . addContent ( Double . toString ( s . getLongitude ( ) ) ) ) ; sElem . addContent ( new Element ( "latitide" ) . addContent ( Double . toString ( s . getLatitude ( ) ) ) ) ; if ( ! Double . isNaN ( s . getAltitude ( ) ) ) sElem . addContent ( new Element ( "altitude" ) . addContent ( Double . toString ( s . getAltitude ( ) ) ) ) ; rootElem . addContent ( sElem ) ; } return doc ;


signature:
public class FeatureDatasetCapabilitiesWriter { /** * Create the capabilities XML document for this dataset
 * @ return capabilities XML document */
public Document getCapabilitiesDocument ( ) { } }

implementation:
Element rootElem = new Element ( "capabilities" ) ; Document doc = new Document ( rootElem ) ; if ( null != path ) { rootElem . setAttribute ( "location" , path ) ; Element elem = new Element ( "featureDataset" ) ; FeatureType ft = fdp . getFeatureType ( ) ; elem . setAttribute ( "type" , ft . toString ( ) . toLowerCase ( ) ) ; String url = path . replace ( "dataset.xml" , ft . toString ( ) . toLowerCase ( ) + ".xml" ) ; elem . setAttribute ( "url" , url ) ; rootElem . addContent ( elem ) ; } List < DsgFeatureCollection > list = fdp . getPointFeatureCollectionList ( ) ; DsgFeatureCollection fc = list . get ( 0 ) ; // LOOK maybe should pass in the dsg ?
rootElem . addContent ( writeTimeUnit ( fc . getTimeUnit ( ) ) ) ; rootElem . addContent ( new Element ( "AltitudeUnits" ) . addContent ( fc . getAltUnits ( ) ) ) ; // data variables
List < ? extends VariableSimpleIF > vars = fdp . getDataVariables ( ) ; Collections . sort ( vars ) ; for ( VariableSimpleIF v : vars ) { rootElem . addContent ( writeVariable ( v ) ) ; } /* CollectionInfo info ;
 try {
 info = new DsgCollectionHelper ( fc ) . calcBounds ( ) ;
 } catch ( IOException e ) {
 throw new RuntimeException ( e ) ; */
LatLonRect bb = fc . getBoundingBox ( ) ; if ( bb != null ) rootElem . addContent ( writeBoundingBox ( bb ) ) ; // add date range
CalendarDateRange dateRange = fc . getCalendarDateRange ( ) ; if ( dateRange != null ) { Element drElem = new Element ( "TimeSpan" ) ; // from KML
drElem . addContent ( new Element ( "begin" ) . addContent ( dateRange . getStart ( ) . toString ( ) ) ) ; drElem . addContent ( new Element ( "end" ) . addContent ( dateRange . getEnd ( ) . toString ( ) ) ) ; if ( dateRange . getResolution ( ) != null ) drElem . addContent ( new Element ( "resolution" ) . addContent ( dateRange . getResolution ( ) . toString ( ) ) ) ; rootElem . addContent ( drElem ) ; } /* add accept list
 Element elem = new Element ( " AcceptList " ) ;
 / / elem . addContent ( new Element ( " accept " ) . addContent ( " raw " ) ) ;
 elem . addContent ( new Element ( " accept " ) . addContent ( " csv " ) . setAttribute ( " displayName " , " csv " ) ) ;
 elem . addContent ( new Element ( " accept " ) . addContent ( " text / csv " ) . setAttribute ( " displayName " , " csv ( file ) " ) ) ;
 elem . addContent ( new Element ( " accept " ) . addContent ( " xml " ) . setAttribute ( " displayName " , " xml " ) ) ;
 elem . addContent ( new Element ( " accept " ) . addContent ( " text / xml " ) . setAttribute ( " displayName " , " xml ( file ) " ) ) ;
 elem . addContent ( new Element ( " accept " ) . addContent ( " waterml2 " ) . setAttribute ( " displayName " , " WaterML 2.0 " ) ) ;
 elem . addContent ( new Element ( " accept " ) . addContent ( " netcdf " ) . setAttribute ( " displayName " , " CF / NetCDF - 3 " ) ) ;
 / / elem . addContent ( new Element ( " accept " ) . addContent ( " ncstream " ) ) ;
 rootElem . addContent ( elem ) ; */
return doc ;


signature:
public class ArrayByte { /** * package private . use Array . factory ( ) */
static ArrayByte factory ( Index index , boolean isUnsigned ) { } }

implementation: return ArrayByte . factory ( index , isUnsigned , null ) ;


signature:
public class ArrayByte { /** * copy from javaArray to storage using the iterator : used by factory ( Object ) ; */
protected void copyFrom1DJavaArray ( IndexIterator iter , Object javaArray ) { } }

implementation: byte [ ] ja = ( byte [ ] ) javaArray ; for ( byte aJa : ja ) iter . setByteNext ( aJa ) ;


signature:
public class ArrayByte { /** * package private : mostly for iterators */
public double getDouble ( int index ) { } }

implementation: byte val = storage [ index ] ; return ( double ) ( isUnsigned ( ) ? DataType . unsignedByteToShort ( val ) : val ) ;


signature:
public class VariableIndex { /** * coord based record finding . note only one record at a time */
@ Nullable synchronized Record getRecordAt ( SubsetParams coords ) { } }

implementation:
int [ ] want = new int [ getRank ( ) ] ; int count = 0 ; int runIdx = - 1 ; for ( Coordinate coord : getCoordinates ( ) ) { int idx = - 1 ; switch ( coord . getType ( ) ) { case runtime : CalendarDate runtimeCooord = coords . getRunTime ( ) ; idx = coord . getIndex ( runtimeCooord ) ; runIdx = idx ; break ; case timeIntv : double [ ] timeIntv = coords . getTimeOffsetIntv ( ) ; idx = coord . getIndex ( new TimeCoordIntvValue ( ( int ) timeIntv [ 0 ] , ( int ) timeIntv [ 1 ] ) ) ; break ; case time : Double timeOffset = coords . getTimeOffset ( ) ; // Double
int coordInt = timeOffset . intValue ( ) ; idx = coord . getIndex ( coordInt ) ; break ; case time2D : timeIntv = coords . getTimeOffsetIntv ( ) ; if ( timeIntv != null ) { TimeCoordIntvValue coordTinv = new TimeCoordIntvValue ( ( int ) timeIntv [ 0 ] , ( int ) timeIntv [ 1 ] ) ; idx = ( ( CoordinateTime2D ) coord ) . findTimeIndexFromVal ( runIdx , coordTinv ) ; // LOOK can only use if orthogonal
break ; } Double timeCoord = coords . getTimeOffset ( ) ; if ( timeCoord != null ) { coordInt = timeCoord . intValue ( ) ; idx = ( ( CoordinateTime2D ) coord ) . findTimeIndexFromVal ( runIdx , coordInt ) ; break ; } // the OneTime case
CoordinateTime2D coord2D = ( CoordinateTime2D ) coord ; if ( coord2D . getNtimes ( ) == 1 ) { idx = 0 ; break ; } throw new IllegalStateException ( "time2D must have timeOffset ot timeOffsetIntv coordinare" ) ; case vert : double [ ] vertIntv = coords . getVertCoordIntv ( ) ; if ( vertIntv != null ) { VertCoordValue coordVert = new VertCoordValue ( vertIntv [ 0 ] , vertIntv [ 1 ] ) ; idx = coord . getIndex ( coordVert ) ; break ; } Double vertCoord = coords . getVertCoord ( ) ; if ( vertCoord != null ) { VertCoordValue coordVert = new VertCoordValue ( vertCoord ) ; idx = coord . getIndex ( coordVert ) ; } break ; case ens : Double ensVal = coords . getEnsCoord ( ) ; idx = ( ( CoordinateEns ) coord ) . getIndexByMember ( ensVal ) ; break ; default : logger . warn ( "GribCollectionImmutable: missing CoordVal for {}%n" , coord . getName ( ) ) ; } if ( idx < 0 ) { logger . debug ( "Cant find index for value in axis {} in variable {}" , coord . getName ( ) , name ) ; return null ; } want [ count ++ ] = idx ; } return sa . getContent ( want ) ;


signature:
public class VariableIndex { /** * get the ith coordinate */
public Coordinate getCoordinate ( int index ) { } }

implementation: int grpIndex = coordIndex . get ( index ) ; return group . coords . get ( grpIndex ) ;


signature:
public class DMRFactory { /** * DMRFactory API */
public DapAttribute newAttribute ( String name , DapType basetype ) { } }

implementation: DapAttribute node = new DapAttribute ( name , basetype ) ; return node ;


signature:
public class ComboBox { /** * Add the item to the top of the list . If it already exists , move it to the top .
 * @ param item to be added . */
public void addItem ( Object item ) { } }

implementation:
if ( item == null ) return ; for ( int i = 0 ; i < getItemCount ( ) ; i ++ ) { if ( item . equals ( getItemAt ( i ) ) ) { if ( i == 0 ) { setSelectedIndex ( 0 ) ; return ; // already there
} removeItemAt ( i ) ; } } // add as first in the list
insertItemAt ( item , 0 ) ; setSelectedIndex ( 0 ) ;


signature:
public class AtmosLnPressure { /** * Get the 3D vertical coordinate array for this time step .
 * @ param timeIndex the time index . Ignored if ! isTimeDependent ( ) .
 * @ return vertical coordinate array
 * @ throws IOException problem reading data
 * @ throws ucar . ma2 . InvalidRangeException _ more _ */
public ArrayDouble . D3 getCoordinateArray ( int timeIndex ) throws IOException , InvalidRangeException { } }

implementation: int nz = ( int ) pressure . getSize ( ) ; int [ ] shape2D = pressure . getShape ( ) ; int ny = shape2D [ 0 ] ; int nx = shape2D [ 1 ] ; ArrayDouble . D3 result = new ArrayDouble . D3 ( nz , ny , nx ) ; IndexIterator ii = pressure . getIndexIterator ( ) ; for ( int z = 0 ; z < nz ; z ++ ) { double p = ii . getDoubleNext ( ) ; for ( int y = 0 ; y < ny ; y ++ ) { for ( int x = 0 ; x < nx ; x ++ ) { result . set ( z , y , x , p ) ; } } } return result ;


signature:
public class TdsErrorHandling { /** * LOOK this could be a problem */
@ ExceptionHandler ( Throwable . class ) public ResponseEntity < String > handle ( Throwable ex ) throws Throwable { } }

implementation:
// If the exception is annotated with @ ResponseStatus rethrow it and let
// the framework handle it - like the OrderNotFoundException example
// at the start of this post .
// AnnotationUtils is a Spring Framework utility class .
// see https : / / spring . io / blog / 2013/11/01 / exception - handling - in - spring - mvc
if ( AnnotationUtils . findAnnotation ( ex . getClass ( ) , ResponseStatus . class ) != null ) throw ex ; logger . error ( "uncaught exception" , ex ) ; // ex . printStackTrace ( ) ; / / temporary - remove in production
HttpHeaders responseHeaders = new HttpHeaders ( ) ; responseHeaders . setContentType ( MediaType . TEXT_PLAIN ) ; String msg = ex . getMessage ( ) ; StringWriter sw = new StringWriter ( ) ; PrintWriter p = new PrintWriter ( sw ) ; ex . printStackTrace ( p ) ; p . close ( ) ; sw . close ( ) ; msg = sw . toString ( ) ; return new ResponseEntity < > ( "Throwable exception handled : " + htmlEscape ( msg ) , responseHeaders , HttpStatus . INTERNAL_SERVER_ERROR ) ;


signature:
public class Odometer { /** * Return ith slice */
public Slice slice ( int i ) { } }

implementation: if ( i < 0 || i >= this . rank ) throw new IllegalArgumentException ( ) ; return this . slices . get ( i ) ;


signature:
public class Odometer { /** * Compute the total number of elements . */
public long totalSize ( ) { } }

implementation: long size = 1 ; for ( int i = 0 ; i < this . rank ; i ++ ) { size *= this . slices . get ( i ) . getCount ( ) ; } return size ;


signature:
public class Odometer { /** * Iterator API */
@ Override public boolean hasNext ( ) { } }

implementation:
int stop = this . rank ; switch ( this . state ) { case INITIAL : return true ; case STARTED : int i ; for ( i = stop - 1 ; i >= 0 ; i -- ) { // walk backwards
if ( this . index . indices [ i ] <= this . endpoint [ i ] ) return true ; } this . state = STATE . DONE ; break ; case DONE : } return false ;


signature:
public class Odometer { /** * return - 1 if we have completed . */
public int step ( int firstpos , int lastpos ) { } }

implementation:
for ( int i = lastpos - 1 ; i >= firstpos ; i -- ) { // walk backwards
if ( this . index . indices [ i ] > this . endpoint [ i ] ) this . index . indices [ i ] = this . slices . get ( i ) . getFirst ( ) ; // reset this position
else { this . index . indices [ i ] += this . slices . get ( i ) . getStride ( ) ; // move to next indices
return i ; } } return - 1 ;


signature:
public class NcepTables { /** * http : / / www . nco . ncep . noaa . gov / pmb / docs / on388 / table5 . html */
@ Override public GribStatType getStatType ( int timeRangeIndicator ) { } }

implementation: switch ( timeRangeIndicator ) { case 128 : case 129 : case 130 : case 131 : case 132 : case 133 : case 137 : case 138 : case 139 : case 140 : return GribStatType . Average ; case 134 : return GribStatType . RootMeanSquare ; case 135 : case 136 : return GribStatType . StandardDeviation ; default : return super . getStatType ( timeRangeIndicator ) ; }


signature:
public class NcepTables { /** * public so can be called from Grib2 */
@ Nullable public static Map < Integer , String > getNcepGenProcess ( ) { } }

implementation:
if ( genProcessMap != null ) return genProcessMap ; String path = "resources/grib1/ncep/ncepTableA.xml" ; try ( InputStream is = GribResourceReader . getInputStream ( path ) ) { SAXBuilder builder = new SAXBuilder ( ) ; org . jdom2 . Document doc = builder . build ( is ) ; Element root = doc . getRootElement ( ) ; HashMap < Integer , String > result = new HashMap < > ( 200 ) ; List < Element > params = root . getChildren ( "parameter" ) ; for ( Element elem1 : params ) { int code = Integer . parseInt ( elem1 . getAttributeValue ( "code" ) ) ; String desc = elem1 . getChildText ( "description" ) ; result . put ( code , desc ) ; } return Collections . unmodifiableMap ( result ) ; // all at once - thread safe
} catch ( IOException | JDOMException ioe ) { logger . error ( "Cant read NCEP Table 1 = " + path , ioe ) ; return null ; }


signature:
public class NcepTables { /** * / / / / / levels */
protected VertCoordType getLevelType ( int code ) { } }

implementation:
if ( code < 129 ) return super . getLevelType ( code ) ; // LOOK dont let NCEP override standard tables ( ? ? ) looks like a conflict with level code 210 ( ! )
if ( levelTypesMap == null ) levelTypesMap = readTable3 ( "resources/grib1/ncep/ncepTable3.xml" ) ; if ( levelTypesMap == null ) return super . getLevelType ( code ) ; VertCoordType levelType = levelTypesMap . get ( code ) ; if ( levelType != null ) return levelType ; return super . getLevelType ( code ) ;


signature:
public class Grib2CollectionWriter { /** * MAGIC _ START
 * version
 * sizeRecords
 * SparseArray ' s ( sizeRecords bytes )
 * sizeIndex
 * GribCollectionIndex ( sizeIndex bytes ) */
boolean writeIndex ( String name , File idxFile , CoordinateRuntime masterRuntime , List < Group > groups , List < MFile > files , GribCollectionImmutable . Type type , CalendarDateRange dateRange ) throws IOException { } }

implementation:
Grib2Record first = null ; // take global metadata from here
boolean deleteOnClose = false ; if ( idxFile . exists ( ) ) { RandomAccessFile . eject ( idxFile . getPath ( ) ) ; if ( ! idxFile . delete ( ) ) { logger . error ( "gc2 cant delete index file {}" , idxFile . getPath ( ) ) ; } } logger . debug ( " createIndex for {}" , idxFile . getPath ( ) ) ; try ( RandomAccessFile raf = new RandomAccessFile ( idxFile . getPath ( ) , "rw" ) ) { // / / header message
raf . order ( RandomAccessFile . BIG_ENDIAN ) ; raf . write ( MAGIC_START . getBytes ( CDM . utf8Charset ) ) ; raf . writeInt ( version ) ; long lenPos = raf . getFilePointer ( ) ; raf . writeLong ( 0 ) ; // save space to write the length of the record section
long countBytes = 0 ; int countRecords = 0 ; Set < Integer > allFileSet = new HashSet < > ( ) ; for ( Group g : groups ) { g . fileSet = new HashSet < > ( ) ; for ( Grib2CollectionBuilder . VariableBag vb : g . gribVars ) { if ( first == null ) first = vb . first ; GribCollectionProto . SparseArray vr = writeSparseArray ( vb , g . fileSet ) ; byte [ ] b = vr . toByteArray ( ) ; vb . pos = raf . getFilePointer ( ) ; vb . length = b . length ; raf . write ( b ) ; countBytes += b . length ; countRecords += vb . coordND . getSparseArray ( ) . countNotMissing ( ) ; } allFileSet . addAll ( g . fileSet ) ; } if ( logger . isDebugEnabled ( ) ) { long bytesPerRecord = countBytes / ( ( countRecords == 0 ) ? 1 : countRecords ) ; logger . debug ( "  write RecordMaps: bytes = {} record = {} bytesPerRecord={}" , countBytes , countRecords , bytesPerRecord ) ; } if ( first == null ) { deleteOnClose = true ; throw new IOException ( "GribCollection " + name + " has no records" ) ; } long pos = raf . getFilePointer ( ) ; raf . seek ( lenPos ) ; raf . writeLong ( countBytes ) ; raf . seek ( pos ) ; // back to the output .
/* message GribCollection {
 string name = 1 ; / / must be unique - index filename is name . ncx
 string topDir = 2 ; / / MFile , Partition filenames are reletive to this
 repeated MFile mfiles = 3 ; / / list of grib MFiles
 repeated Dataset dataset = 4;
 repeated Gds gds = 5 ; / / unique Gds , shared amongst datasets
 Coord masterRuntime = 6 ; / / list of runtimes in this GC
 int32 center = 7 ; / / these 4 fields are to get a GribCustomizer
 int32 subcenter = 8;
 int32 master = 9;
 int32 local = 10 ; / / grib1 table Version
 int32 genProcessType = 11;
 int32 genProcessId = 12;
 int32 backProcessId = 13;
 int32 version = 14 ; / / > = 3 for proto3 ( 5.0 + )
 / / repeated Parameter params = 20 ; / / not used
 FcConfig config = 21;
 / / extensions
 repeated Partition partitions = 100;
 bool isPartitionOfPartitions = 101;
 repeated uint32 run2part = 102 [ packed = true ] ; / / masterRuntime index to partition index */
GribCollectionProto . GribCollection . Builder indexBuilder = GribCollectionProto . GribCollection . newBuilder ( ) ; indexBuilder . setName ( name ) ; indexBuilder . setTopDir ( dcm . getRoot ( ) ) ; indexBuilder . setVersion ( currentVersion ) ; // directory and mfile list
File directory = new File ( dcm . getRoot ( ) ) ; List < GcMFile > gcmfiles = GcMFile . makeFiles ( directory , files , allFileSet ) ; for ( GcMFile gcmfile : gcmfiles ) { GribCollectionProto . MFile . Builder b = GribCollectionProto . MFile . newBuilder ( ) ; b . setFilename ( gcmfile . getName ( ) ) ; b . setLastModified ( gcmfile . getLastModified ( ) ) ; b . setLength ( gcmfile . getLength ( ) ) ; b . setIndex ( gcmfile . index ) ; indexBuilder . addMfiles ( b . build ( ) ) ; } indexBuilder . setMasterRuntime ( writeCoordProto ( masterRuntime ) ) ; // gds
for ( Object go : groups ) { Group g = ( Group ) go ; indexBuilder . addGds ( writeGdsProto ( g . gdss . getRawBytes ( ) , - 1 ) ) ; } // the GC dataset
indexBuilder . addDataset ( writeDatasetProto ( type , groups ) ) ; // what about just storing first ? ?
Grib2SectionIdentification ids = first . getId ( ) ; indexBuilder . setCenter ( ids . getCenter_id ( ) ) ; indexBuilder . setSubcenter ( ids . getSubcenter_id ( ) ) ; indexBuilder . setMaster ( ids . getMaster_table_version ( ) ) ; indexBuilder . setLocal ( ids . getLocal_table_version ( ) ) ; Grib2Pds pds = first . getPDS ( ) ; indexBuilder . setGenProcessType ( pds . getGenProcessType ( ) ) ; indexBuilder . setGenProcessId ( pds . getGenProcessId ( ) ) ; indexBuilder . setBackProcessId ( pds . getBackProcessId ( ) ) ; indexBuilder . setStartTime ( dateRange . getStart ( ) . getMillis ( ) ) ; indexBuilder . setEndTime ( dateRange . getEnd ( ) . getMillis ( ) ) ; GribCollectionProto . GribCollection index = indexBuilder . build ( ) ; byte [ ] b = index . toByteArray ( ) ; NcStream . writeVInt ( raf , b . length ) ; // message size
raf . write ( b ) ; // message - all in one gulp
logger . debug ( "  write GribCollectionIndex= {} bytes" , b . length ) ; } finally { // remove it on failure
if ( deleteOnClose && ! idxFile . delete ( ) ) logger . error ( " gc2 cant deleteOnClose index file {}" , idxFile . getPath ( ) ) ; } return true ;


signature:
public class Grib2CollectionWriter { /** * message Record {
 * uint32 fileno = 1 ; / / which GRIB file ? key into GC . fileMap
 * uint64 pos = 2 ; / / offset in GRIB file of the start of entire message
 * uint64 bmsPos = 3 ; / / use alternate bms if non - zero
 * uint32 drsOffset = 4 ; / / offset of drs from pos ( grib2 only )
 * SparseArray only at the GCs ( MRC and SRC ) not at the Partitions
 * dont need SparseArray in memory until someone wants to read from the variable
 * message SparseArray {
 * repeated uint32 size = 2 [ packed = true ] ; / / multidim sizes = shape [ ]
 * repeated uint32 track = 3 [ packed = true ] ; / / 1 - based index into record list , 0 = = missing
 * repeated Record records = 4 ; / / List < Record >
 * uint32 ndups = 5 ; / / duplicates found when creating */
private GribCollectionProto . SparseArray writeSparseArray ( Grib2CollectionBuilder . VariableBag vb , Set < Integer > fileSet ) { } }

implementation: GribCollectionProto . SparseArray . Builder b = GribCollectionProto . SparseArray . newBuilder ( ) ; SparseArray < Grib2Record > sa = vb . coordND . getSparseArray ( ) ; for ( int size : sa . getShape ( ) ) b . addSize ( size ) ; for ( int track : sa . getTrack ( ) ) b . addTrack ( track ) ; for ( Grib2Record gr : sa . getContent ( ) ) { GribCollectionProto . Record . Builder br = GribCollectionProto . Record . newBuilder ( ) ; br . setFileno ( gr . getFile ( ) ) ; fileSet . add ( gr . getFile ( ) ) ; long startPos = gr . getIs ( ) . getStartPos ( ) ; br . setStartPos ( startPos ) ; if ( gr . isBmsReplaced ( ) ) { Grib2SectionBitMap bms = gr . getBitmapSection ( ) ; br . setBmsOffset ( ( int ) ( bms . getStartingPosition ( ) - startPos ) ) ; } Grib2SectionDataRepresentation drs = gr . getDataRepresentationSection ( ) ; br . setDrsOffset ( ( int ) ( drs . getStartingPosition ( ) - startPos ) ) ; b . addRecords ( br ) ; } b . setNdups ( sa . getNdups ( ) ) ; return b . build ( ) ;


signature:
public class DatasetScanConfigBuilder { /** * < xsd : element name = " datasetScan " substitutionGroup = " dataset " >
 * < xsd : complexType >
 * < xsd : complexContent >
 * < xsd : extension base = " DatasetType " >
 * < xsd : sequence >
 * < xsd : element ref = " filter " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < xsd : element ref = " namer " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < xsd : element ref = " sort " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < xsd : element ref = " addLatest " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < xsd : element ref = " addProxies " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < xsd : element name = " addDatasetSize " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < xsd : element ref = " addTimeCoverage " minOccurs = " 0 " maxOccurs = " 1 " / >
 * < / xsd : sequence >
 * < xsd : attribute name = " path " type = " xsd : string " use = " required " / >
 * < xsd : attribute name = " location " type = " xsd : string " / >
 * < xsd : attribute name = " addLatest " type = " xsd : boolean " / >
 * < xsd : attribute name = " filter " type = " xsd : string " / > < ! - - deprecated : use filter element - - >
 * < / xsd : extension >
 * < / xsd : complexContent >
 * < / xsd : complexType >
 * < / xsd : element > */
public DatasetScanConfig readDatasetScanConfig ( Element dsElem ) { } }

implementation:
DatasetScanConfig result = new DatasetScanConfig ( ) ; result . name = dsElem . getAttributeValue ( "name" ) ; result . path = StringUtil2 . trim ( dsElem . getAttributeValue ( "path" ) , '/' ) ; if ( result . path == null ) { errlog . format ( "ERROR: must specify path attribute.%n" ) ; fatalError = true ; } String scanDir = dsElem . getAttributeValue ( "location" ) ; if ( scanDir == null ) { errlog . format ( "ERROR: must specify directory root in location attribute.%n" ) ; fatalError = true ; } else { result . scanDir = AliasTranslator . translateAlias ( scanDir ) ; File scanFile = new File ( result . scanDir ) ; if ( ! scanFile . exists ( ) ) { errlog . format ( "ERROR: directory %s does not exist%n" , result . scanDir ) ; fatalError = true ; } } result . restrictAccess = dsElem . getAttributeValue ( "restrictAccess" ) ; // look for ncml
Element ncmlElem = dsElem . getChild ( "netcdf" , Catalog . defNS ) ; if ( ncmlElem != null ) { ncmlElem . detach ( ) ; result . ncmlElement = ncmlElem ; } // Read filter element
Element filterElem = dsElem . getChild ( "filter" , Catalog . defNS ) ; result . filters = readDatasetScanFilter ( filterElem ) ; // Read namer element
Element namerElem = dsElem . getChild ( "namer" , Catalog . defNS ) ; result . namers = readDatasetScanNamer ( namerElem ) ; // Read filesSort or sort element
Element filesSortElem = dsElem . getChild ( "filesSort" , Catalog . defNS ) ; if ( filesSortElem != null ) result . isSortIncreasing = readFilesSort ( filesSortElem ) ; Element sorterElem = dsElem . getChild ( "sort" , Catalog . defNS ) ; if ( ! result . isSortIncreasing . isPresent ( ) && sorterElem != null ) result . isSortIncreasing = readSort ( sorterElem ) ; // Deal with latest
String addLatestAttribute = dsElem . getAttributeValue ( "addLatest" ) ; Element addLatestElem = dsElem . getChild ( "addLatest" , Catalog . defNS ) ; // not in docs
Element addProxiesElem = dsElem . getChild ( "addProxies" , Catalog . defNS ) ; result . addLatest = readDatasetScanAddProxies ( addProxiesElem , addLatestElem , addLatestAttribute ) ; /* Read addDatasetSize element .
 Element addDsSizeElem = dsElem . getChild ( " addDatasetSize " , Catalog . defNS ) ;
 if ( addDsSizeElem ! = null ) { / / docs : default true
 if ( addDsSizeElem . getTextNormalize ( ) . equalsIgnoreCase ( " false " ) )
 result . addDatasetSize = false ; */
// Read addTimeCoverage element .
Element addTimeCovElem = dsElem . getChild ( "addTimeCoverage" , Catalog . defNS ) ; if ( addTimeCovElem != null ) { result . addTimeCoverage = readDatasetScanAddTimeCoverage ( addTimeCovElem ) ; } return result ;


signature:
public class DatasetScanConfigBuilder { /** * < xsd : element name = " filter " >
 * < xsd : complexType >
 * < xsd : choice >
 * < xsd : sequence minOccurs = " 0 " maxOccurs = " unbounded " >
 * < xsd : element name = " include " type = " FilterSelectorType " minOccurs = " 0 " / >
 * < xsd : element name = " exclude " type = " FilterSelectorType " minOccurs = " 0 " / >
 * < / xsd : sequence >
 * < / xsd : choice >
 * < / xsd : complexType >
 * < / xsd : element >
 * < xsd : complexType name = " FilterSelectorType " >
 * < xsd : attribute name = " regExp " type = " xsd : string " / >
 * < xsd : attribute name = " wildcard " type = " xsd : string " / >
 * < xsd : attribute name = " atomic " type = " xsd : boolean " / >
 * < xsd : attribute name = " collection " type = " xsd : boolean " / >
 * < / xsd : complexType > */
private List < DatasetScanConfig . Filter > readDatasetScanFilter ( Element filterElem ) { } }

implementation:
List < DatasetScanConfig . Filter > filters = new ArrayList < > ( ) ; if ( filterElem == null ) return null ; for ( Element curElem : filterElem . getChildren ( ) ) { String regExpAttVal = curElem . getAttributeValue ( "regExp" ) ; String wildcardAttVal = curElem . getAttributeValue ( "wildcard" ) ; String lastModLimitAttValS = curElem . getAttributeValue ( "lastModLimitInMillis" ) ; if ( regExpAttVal == null && wildcardAttVal == null && lastModLimitAttValS == null ) { // If no regExp or wildcard attributes , skip this selector .
errlog . format ( "WARN: readDatasetScanFilter(): no regExp, wildcard, or lastModLimitInMillis attribute in filter child <%s>%n" , curElem . getName ( ) ) ; } else { // Determine if applies to atomic datasets , default true .
String atomicAttVal = curElem . getAttributeValue ( "atomic" ) ; boolean atomic = ( atomicAttVal == null || ! atomicAttVal . equalsIgnoreCase ( "false" ) ) ; // Determine if applies to collection datasets , default false .
String collectionAttVal = curElem . getAttributeValue ( "collection" ) ; boolean notCollection = collectionAttVal == null || ! collectionAttVal . equalsIgnoreCase ( "true" ) ; // Determine if include or exclude selectors .
boolean includer = true ; if ( curElem . getName ( ) . equals ( "exclude" ) ) { includer = false ; } else if ( ! curElem . getName ( ) . equals ( "include" ) ) { errlog . format ( "WARN: readDatasetScanFilter(): unhandled filter child <%s>.%n" , curElem . getName ( ) ) ; continue ; } // check for errors
long lastModLimitAttVal = - 1 ; if ( lastModLimitAttValS != null ) { try { lastModLimitAttVal = Long . parseLong ( lastModLimitAttValS ) ; } catch ( NumberFormatException e ) { errlog . format ( "WARN: readDatasetScanFilter(): lastModLimitInMillis not valid <%s>.%n" , curElem ) ; } } filters . add ( new DatasetScanConfig . Filter ( regExpAttVal , wildcardAttVal , lastModLimitAttVal , atomic , ! notCollection , includer ) ) ; } } return filters ;


signature:
public class DatasetScanConfigBuilder { /** * < xsd : element name = " namer " >
 * < xsd : complexType >
 * < xsd : choice maxOccurs = " unbounded " >
 * < xsd : element name = " regExpOnName " type = " NamerSelectorType " / >
 * < xsd : element name = " regExpOnPath " type = " NamerSelectorType " / >
 * < / xsd : choice >
 * < / xsd : complexType >
 * < / xsd : element >
 * < xsd : complexType name = " NamerSelectorType " >
 * < xsd : attribute name = " regExp " type = " xsd : string " / >
 * < xsd : attribute name = " replaceString " type = " xsd : string " / >
 * < / xsd : complexType > */
protected List < DatasetScanConfig . Namer > readDatasetScanNamer ( Element namerElem ) { } }

implementation: List < DatasetScanConfig . Namer > result = new ArrayList < > ( ) ; if ( namerElem == null ) return result ; for ( Element curElem : namerElem . getChildren ( ) ) { String regExp = curElem . getAttributeValue ( "regExp" ) ; String replaceString = curElem . getAttributeValue ( "replaceString" ) ; boolean onName = curElem . getName ( ) . equals ( "regExpOnName" ) ; boolean onPath = curElem . getName ( ) . equals ( "regExpOnPath" ) ; if ( ! onName && ! onPath ) { errlog . format ( "WARN: readDatasetScanNamer(): namer child '%s'%n" , curElem . getName ( ) ) ; continue ; } result . add ( new DatasetScanConfig . Namer ( onName , regExp , replaceString ) ) ; } return result ;


signature:
public class DatasetScanConfigBuilder { /** * < xsd : element name = " sort " >
 * < xsd : complexType >
 * < xsd : choice >
 * < xsd : element name = " lexigraphicByName " >
 * < xsd : complexType >
 * < xsd : attribute name = " increasing " type = " xsd : boolean " / >
 * < / xsd : complexType >
 * < / xsd : element >
 * < xsd : element name = " crawlableDatasetSorterImpl " minOccurs = " 0 " type = " UserImplType " / >
 * < / xsd : choice >
 * < / xsd : complexType >
 * < / xsd : element > */
protected Optional < Boolean > readFilesSort ( Element sorterElem ) { } }

implementation: String increasingString = sorterElem . getAttributeValue ( "increasing" ) ; if ( increasingString != null ) { if ( increasingString . equalsIgnoreCase ( "true" ) ) return Optional . of ( true ) ; else if ( increasingString . equalsIgnoreCase ( "false" ) ) return Optional . of ( false ) ; } return Optional . empty ( ) ;


signature:
public class DatasetScanConfigBuilder { /** * < xsd : element name = " addTimeCoverage " >
 * < xsd : complexType >
 * < xsd : attribute name = " datasetNameMatchPattern " type = " xsd : string " / >
 * < xsd : attribute name = " datasetPathMatchPattern " type = " xsd : string " / >
 * < xsd : attribute name = " startTimeSubstitutionPattern " type = " xsd : string " / >
 * < xsd : attribute name = " duration " type = " xsd : string " / >
 * < / xsd : complexType >
 * < / xsd : element > */
protected DatasetScanConfig . AddTimeCoverage readDatasetScanAddTimeCoverage ( Element addTimeCovElem ) { } }

implementation: String matchName = addTimeCovElem . getAttributeValue ( "datasetNameMatchPattern" ) ; String matchPath = addTimeCovElem . getAttributeValue ( "datasetPathMatchPattern" ) ; String subst = addTimeCovElem . getAttributeValue ( "startTimeSubstitutionPattern" ) ; String duration = addTimeCovElem . getAttributeValue ( "duration" ) ; boolean err = false ; if ( subst == null ) { errlog . format ( "WARN: readDatasetScanAddTimeCoverage(): must have startTimeSubstitutionPattern elem=<%s>%n" , addTimeCovElem ) ; err = true ; } else if ( duration == null ) { errlog . format ( "WARN: readDatasetScanAddTimeCoverage(): must have duration elem=<%s>%n" , addTimeCovElem ) ; err = true ; } else if ( matchName == null && matchPath == null ) { errlog . format ( "WARN: readDatasetScanAddTimeCoverage(): must have either datasetNameMatchPattern or datasetPathMatchPattern elem=<%s>%n" , addTimeCovElem ) ; err = true ; } return err ? null : new DatasetScanConfig . AddTimeCoverage ( matchName , matchPath , subst , duration ) ;


signature:
public class CdmrFeatureDataset { /** * all CdmrFeatureDatasets must return their featureType - use as a fail - fast test of the endpoint */
public static FeatureType isCdmrfEndpoint ( String endpoint ) throws IOException { } }

implementation:
HTTPSession httpClient = HTTPFactory . newSession ( endpoint ) ; String url = endpoint + "?req=featureType" ; // get the header
try ( HTTPMethod method = HTTPFactory . Get ( httpClient , url ) ) { method . setFollowRedirects ( true ) ; int statusCode = method . execute ( ) ; if ( statusCode != 200 ) return null ; String content = method . getResponseAsString ( ) ; return FeatureType . getType ( content ) ; } catch ( Throwable t ) { t . printStackTrace ( ) ; return null ; }


signature:
public class OptSwitch { /** * Set the value type of the option switch to the type passed
 * @ param type type of value that switch may accept or be */
public void SetHasValue ( int type ) { } }

implementation: this . type = type ; if ( debug ) { System . out . println ( "sw = " + ( char ) sw + "; type = " + type + "; set = " + set + "; val = " + val ) ; }


signature:
public class NcTimePeriodType { /** * wml2 : Collection / wml2 : observationMember / om : OM _ Observation / om : phenomenonTime / gml : TimePeriod */
public static TimePeriodType initTimePeriod ( TimePeriodType timePeriod , StationTimeSeriesFeature stationFeat ) throws IOException { } }

implementation:
// @ gml : id
String id = MarshallingUtil . createIdForType ( TimePeriodType . class ) ; timePeriod . setId ( id ) ; CollectionInfo info ; try { info = new DsgCollectionHelper ( stationFeat ) . calcBounds ( ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } CalendarDateRange cdr = info . getCalendarDateRange ( stationFeat . getTimeUnit ( ) ) ; if ( cdr != null ) { // gml : beginPosition
NcTimePositionType . initBeginPosition ( timePeriod . addNewBeginPosition ( ) , cdr . getStart ( ) ) ; // gml : endPosition
NcTimePositionType . initEndPosition ( timePeriod . addNewEndPosition ( ) , cdr . getEnd ( ) ) ; } return timePeriod ;


signature:
public class Grib1GdsPredefined { /** * Constructs a Grib1Gds object from a pds and predefined tables .
 * @ param center center id
 * @ param gridNumber from pds ( octet 7)
 * @ return predefined GDS */
public static Grib1Gds factory ( int center , int gridNumber ) { } }

implementation: if ( center == 7 ) { return factoryNCEP ( gridNumber ) ; } else throw new IllegalArgumentException ( "Dont have predefined GDS " + gridNumber + " from " + center ) ;


signature:
public class Grib1GdsPredefined { /** * 21-26 , 61-64 : International Exchange and Family of Services ( FOS ) grids . So may be more general than NCEP */
private static Grib1Gds factoryNCEP ( int gridNumber ) { } }

implementation: switch ( gridNumber ) { case 21 : return new NcepLatLon ( gridNumber , 37 , 36 , 0.0F , 0.0F , 90.0F , 180.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 22 : return new NcepLatLon ( gridNumber , 37 , 36 , 0.0F , - 180.0F , 90.0F , 0.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 23 : return new NcepLatLon ( gridNumber , 37 , 36 , - 90.0F , 0.0F , 180.0F , 0.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 24 : return new NcepLatLon ( gridNumber , 37 , 36 , - 90.0F , - 180.0F , 0.0F , 0.0F , 5.0F , 2.5F , ( byte ) 0x88 , ( byte ) 64 ) ; case 25 : return new NcepLatLon ( gridNumber , 72 , 18 , 0.0F , 0.0F , 90.0F , 355.0F , 5.0F , 5.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 26 : return new NcepLatLon ( gridNumber , 72 , 18 , - 90.0F , 0.0F , 0.0F , 355.0F , 5.0F , 5.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 61 : return new NcepLatLon ( gridNumber , 91 , 45 , 0.0F , 0.0F , 90.0F , 180.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 62 : return new NcepLatLon ( gridNumber , 91 , 45 , - 90.0F , 0.0F , 0.0F , 180.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 63 : return new NcepLatLon ( gridNumber , 91 , 45 , - 90.0F , 0.0F , 0.0F , 180.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 64 : return new NcepLatLon ( gridNumber , 91 , 45 , - 90.0F , - 180.0F , 0.0F , 0.0F , 2.0F , 2.0F , ( byte ) 0x88 , ( byte ) 64 ) ; case 87 : return new NcepPS ( gridNumber , 81 , 62 , 22.8756F , 239.5089F , 255.0F , 68153.0F , 68153.0F , ( byte ) 0x08 , ( byte ) 64 ) ; } throw new IllegalArgumentException ( "Dont have predefined GDS " + gridNumber + " from NCEP (center 7)" ) ;


signature:
public class IO { /** * copy all bytes from in and throw them away .
 * @ param in InputStream
 * @ param buffersize size of buffer to use , if - 1 uses default value ( 9200)
 * @ return number of bytes copied
 * @ throws java . io . IOException on io error */
static public long copy2null ( InputStream in , int buffersize ) throws IOException { } }

implementation:
long totalBytesRead = 0 ; if ( buffersize <= 0 ) buffersize = default_file_buffersize ; byte [ ] buffer = new byte [ buffersize ] ; while ( true ) { int n = in . read ( buffer ) ; if ( n == - 1 ) break ; totalBytesRead += n ; } // if ( fout ! = null ) fout . format ( " done = % d % n " , totalBytesRead ) ;
return totalBytesRead ;


signature:
public class IO { /** * copy all bytes from in and throw them away .
 * @ param in FileChannel
 * @ param buffersize size of buffer to use , if - 1 uses default value ( 9200)
 * @ return number of bytes copied
 * @ throws java . io . IOException on io error */
static public long copy2null ( FileChannel in , int buffersize ) throws IOException { } }

implementation: long totalBytesRead = 0 ; if ( buffersize <= 0 ) buffersize = default_file_buffersize ; ByteBuffer buffer = ByteBuffer . allocate ( buffersize ) ; while ( true ) { int n = in . read ( buffer ) ; if ( n == - 1 ) break ; totalBytesRead += n ; buffer . flip ( ) ; } return totalBytesRead ;


signature:
public class IO { /** * copy all bytes from in to out , specify buffer size
 * @ param in InputStream
 * @ param out OutputStream
 * @ param bufferSize : internal buffer size .
 * @ return number of bytes copied
 * @ throws java . io . IOException on io error */
static public long copyB ( InputStream in , OutputStream out , int bufferSize ) throws IOException { } }

implementation: long totalBytesRead = 0 ; int done = 0 , next = 1 ; byte [ ] buffer = new byte [ bufferSize ] ; while ( true ) { int n = in . read ( buffer ) ; if ( n == - 1 ) break ; out . write ( buffer , 0 , n ) ; totalBytesRead += n ; if ( showCopy ) { done += n ; if ( done > 1000 * 1000 * next ) { System . out . println ( next + " Mb" ) ; next ++ ; } } } out . flush ( ) ; return totalBytesRead ;


signature:
public class IO { /** * Read the contents from the inputStream and place into a String ,
 * with any error messages put in the return String .
 * @ param is the inputStream to read from .
 * @ return String holding the contents , or an error message .
 * @ throws java . io . IOException on io error */
static public String readContents ( InputStream is , String charset ) throws IOException { } }

implementation: ByteArrayOutputStream bout = new ByteArrayOutputStream ( 10 * default_file_buffersize ) ; IO . copy ( is , bout ) ; return bout . toString ( charset ) ;


signature:
public class IO { /** * Read the contents from the inputStream and place into a byte array ,
 * with any error messages put in the return String .
 * @ param is the inputStream to read from .
 * @ return byte [ ] holding the contents , or an error message .
 * @ throws java . io . IOException on io error */
static public byte [ ] readContentsToByteArray ( InputStream is ) throws IOException { } }

implementation: ByteArrayOutputStream bout = new ByteArrayOutputStream ( 10 * default_file_buffersize ) ; IO . copy ( is , bout ) ; return bout . toByteArray ( ) ;


signature:
public class IO { /** * Wite the contents from the String to a Stream ,
 * @ param contents String holding the contents .
 * @ param os write to this OutputStream
 * @ throws java . io . IOException on io error */
static public void writeContents ( String contents , OutputStream os ) throws IOException { } }

implementation: ByteArrayInputStream bin = new ByteArrayInputStream ( contents . getBytes ( CDM . utf8Charset ) ) ; IO . copy ( bin , os ) ;


signature:
public class IO { /** * copy one file to another .
 * @ param fileInName copy from this file , which must exist .
 * @ param fileOutName copy to this file , which is overrwritten if already exists .
 * @ throws java . io . IOException on io error */
static public void copyFile ( String fileInName , String fileOutName ) throws IOException { } }

implementation: try ( FileInputStream fin = new FileInputStream ( fileInName ) ; FileOutputStream fout = new FileOutputStream ( fileOutName ) ) { InputStream in = new BufferedInputStream ( fin ) ; OutputStream out = new BufferedOutputStream ( fout ) ; IO . copy ( in , out ) ; }


signature:
public class IO { /** * copy one file to another .
 * @ param fileIn copy from this file , which must exist .
 * @ param fileOut copy to this file , which is overrwritten if already exists .
 * @ throws java . io . IOException on io error */
static public void copyFile ( File fileIn , File fileOut ) throws IOException { } }

implementation: try ( FileInputStream fin = new FileInputStream ( fileIn ) ; FileOutputStream fout = new FileOutputStream ( fileOut ) ) { InputStream in = new BufferedInputStream ( fin ) ; OutputStream out = new BufferedOutputStream ( fout ) ; IO . copy ( in , out ) ; }


signature:
public class IO { /** * copy file to output stream
 * @ param src source
 * @ param fileOut copy to this file
 * @ throws java . io . IOException on io error */
static public void copy2File ( byte [ ] src , String fileOut ) throws IOException { } }

implementation: try ( FileOutputStream fout = new FileOutputStream ( fileOut ) ) { InputStream in = new BufferedInputStream ( new ByteArrayInputStream ( src ) ) ; OutputStream out = new BufferedOutputStream ( fout ) ; IO . copy ( in , out ) ; }


signature:
public class IO { /** * copy file to output stream
 * @ param fileInName open this file
 * @ param out copy here
 * @ throws java . io . IOException on io error */
static public void copyFile ( String fileInName , OutputStream out ) throws IOException { } }

implementation: copyFileB ( new File ( fileInName ) , out , default_file_buffersize ) ;


signature:
public class IO { /** * copy file to output stream , specify internal buffer size
 * @ param fileIn copy this file
 * @ param out copy to this stream
 * @ param bufferSize internal buffer size .
 * @ throws java . io . IOException on io error */
static public void copyFileB ( File fileIn , OutputStream out , int bufferSize ) throws IOException { } }

implementation: try ( FileInputStream fin = new FileInputStream ( fileIn ) ) { InputStream in = new BufferedInputStream ( fin ) ; IO . copyB ( in , out , bufferSize ) ; }


signature:
public class IO { /** * Copy part of a RandomAccessFile to output stream , specify internal buffer size
 * @ param raf copy this file
 * @ param offset start here ( byte offset )
 * @ param length number of bytes to copy
 * @ param out copy to this stream
 * @ param buffer use this buffer .
 * @ return number of bytes copied
 * @ throws java . io . IOException on io error */
static public long copyRafB ( ucar . unidata . io . RandomAccessFile raf , long offset , long length , OutputStream out , byte [ ] buffer ) throws IOException { } }

implementation: int bufferSize = buffer . length ; long want = length ; raf . seek ( offset ) ; while ( want > 0 ) { int len = ( int ) Math . min ( want , bufferSize ) ; int bytesRead = raf . read ( buffer , 0 , len ) ; if ( bytesRead <= 0 ) break ; out . write ( buffer , 0 , bytesRead ) ; want -= bytesRead ; } out . flush ( ) ; return length - want ;


signature:
public class IO { /** * Copy an entire directory tree .
 * @ param fromDirName from this directory ( do nothing if not exist )
 * @ param toDirName to this directory ( will create if not exist )
 * @ throws java . io . IOException on io error */
static public void copyDirTree ( String fromDirName , String toDirName ) throws IOException { } }

implementation: File fromDir = new File ( fromDirName ) ; File toDir = new File ( toDirName ) ; if ( ! fromDir . exists ( ) ) return ; if ( ! toDir . exists ( ) ) { if ( ! toDir . mkdirs ( ) ) { throw new IOException ( "Could not create directory: " + toDir ) ; } } File [ ] files = fromDir . listFiles ( ) ; if ( files != null ) for ( File f : files ) { if ( f . isDirectory ( ) ) copyDirTree ( f . getAbsolutePath ( ) , toDir . getAbsolutePath ( ) + "/" + f . getName ( ) ) ; else copyFile ( f . getAbsolutePath ( ) , toDir . getAbsolutePath ( ) + "/" + f . getName ( ) ) ; }


signature:
public class IO { /** * Read the file and place contents into a byte array ,
 * with any error messages put in the return String .
 * @ param filename the file to read from .
 * @ return byte [ ] holding the contents , or an error message .
 * @ throws java . io . IOException on io error */
static public byte [ ] readFileToByteArray ( String filename ) throws IOException { } }

implementation: try ( FileInputStream fin = new FileInputStream ( filename ) ) { InputStream in = new BufferedInputStream ( fin ) ; return readContentsToByteArray ( in ) ; }


signature:
public class IO { /** * Read the contents from the named file and place into a String , assuming UTF - 8 encoding .
 * @ param filename the URL to read from .
 * @ return String holding the file contents
 * @ throws java . io . IOException on io error */
static public String readFile ( String filename ) throws IOException { } }

implementation: try ( FileInputStream fin = new FileInputStream ( filename ) ) { InputStreamReader reader = new InputStreamReader ( fin , CDM . utf8Charset ) ; StringWriter swriter = new StringWriter ( 50000 ) ; UnsynchronizedBufferedWriter writer = new UnsynchronizedBufferedWriter ( swriter ) ; writer . write ( reader ) ; return swriter . toString ( ) ; }


signature:
public class IO { /** * Write String contents to a file , using UTF - 8 encoding .
 * @ param contents String holding the contents
 * @ param file write to this file ( overwrite if exists )
 * @ throws java . io . IOException on io error */
static public void writeToFile ( String contents , File file ) throws IOException { } }

implementation: try ( FileOutputStream fout = new FileOutputStream ( file ) ) { OutputStreamWriter fw = new OutputStreamWriter ( fout , CDM . utf8Charset ) ; UnsynchronizedBufferedWriter writer = new UnsynchronizedBufferedWriter ( fw ) ; writer . write ( contents ) ; writer . flush ( ) ; }


signature:
public class IO { /** * Write byte [ ] contents to a file .
 * @ param contents String holding the contents
 * @ param file write to this file ( overwrite if exists )
 * @ throws java . io . IOException on io error */
static public void writeToFile ( byte [ ] contents , File file ) throws IOException { } }

implementation: try ( FileOutputStream fw = new FileOutputStream ( file ) ) { fw . write ( contents ) ; fw . flush ( ) ; }


signature:
public class IO { /** * Write contents to a file , using UTF - 8 encoding .
 * @ param contents String holding the contents
 * @ param fileOutName write to this file ( overwrite if exists )
 * @ throws java . io . IOException on io error */
static public void writeToFile ( String contents , String fileOutName ) throws IOException { } }

implementation: writeToFile ( contents , new File ( fileOutName ) ) ;


signature:
public class IO { /** * copy input stream to file . close input stream when done .
 * @ param in copy from here
 * @ param fileOutName open this file ( overwrite ) and copy to it .
 * @ return number of bytes copied
 * @ throws java . io . IOException on io error */
static public long writeToFile ( InputStream in , String fileOutName ) throws IOException { } }

implementation: try ( FileOutputStream fout = new FileOutputStream ( fileOutName ) ) { OutputStream out = new BufferedOutputStream ( fout ) ; return IO . copy ( in , out ) ; } finally { if ( null != in ) in . close ( ) ; }


signature:
public class IO { /** * copy contents of URL to output stream , specify internal buffer size . request gzip encoding
 * @ param urlString copy the contents of this URL
 * @ param out copy to this stream . If null , throw bytes away
 * @ param bufferSize internal buffer size .
 * @ return number of bytes copied
 * @ throws java . io . IOException on io error */
static public long copyUrlB ( String urlString , OutputStream out , int bufferSize ) throws IOException { } }

implementation:
long count ; URL url ; try { url = new URL ( urlString ) ; } catch ( MalformedURLException e ) { throw new IOException ( "** MalformedURLException on URL <" + urlString + ">\n" + e . getMessage ( ) + "\n" ) ; } try { java . net . URLConnection connection = url . openConnection ( ) ; java . net . HttpURLConnection httpConnection = null ; if ( connection instanceof java . net . HttpURLConnection ) { httpConnection = ( java . net . HttpURLConnection ) connection ; httpConnection . addRequestProperty ( "Accept-Encoding" , "gzip" ) ; } if ( showHeaders ) { showRequestHeaders ( urlString , connection ) ; } // get response
if ( httpConnection != null ) { int responseCode = httpConnection . getResponseCode ( ) ; if ( responseCode / 100 != 2 ) throw new IOException ( "** Cant open URL <" + urlString + ">\n Response code = " + responseCode + "\n" + httpConnection . getResponseMessage ( ) + "\n" ) ; } if ( showHeaders && ( httpConnection != null ) ) { int code = httpConnection . getResponseCode ( ) ; String response = httpConnection . getResponseMessage ( ) ; // response headers
System . out . println ( "\nRESPONSE for " + urlString + ": " ) ; System . out . println ( " HTTP/1.x " + code + " " + response ) ; System . out . println ( "Headers: " ) ; for ( int j = 1 ; ; j ++ ) { String header = connection . getHeaderField ( j ) ; String key = connection . getHeaderFieldKey ( j ) ; if ( header == null || key == null ) break ; System . out . println ( " " + key + ": " + header ) ; } } // read it
try ( InputStream is = connection . getInputStream ( ) ) { BufferedInputStream bis ; // check if its gzipped
if ( "gzip" . equalsIgnoreCase ( connection . getContentEncoding ( ) ) ) { bis = new BufferedInputStream ( new GZIPInputStream ( is ) , 8000 ) ; } else { bis = new BufferedInputStream ( is , 8000 ) ; } if ( out == null ) count = IO . copy2null ( bis , bufferSize ) ; else count = IO . copyB ( bis , out , bufferSize ) ; } } catch ( java . net . ConnectException e ) { if ( showStackTrace ) e . printStackTrace ( ) ; throw new IOException ( "** ConnectException on URL: <" + urlString + ">\n" + e . getMessage ( ) + "\nServer probably not running" ) ; } catch ( java . net . UnknownHostException e ) { if ( showStackTrace ) e . printStackTrace ( ) ; throw new IOException ( "** UnknownHostException on URL: <" + urlString + ">\n" ) ; } catch ( Exception e ) { if ( showStackTrace ) e . printStackTrace ( ) ; throw new IOException ( "** Exception on URL: <" + urlString + ">\n" + e ) ; } return count ;


signature:
public class DTSServlet { /** * Turns a ParseException into a OPeNDAP DAP2 error and sends it to the client .
 * @ param pe The < code > ParseException < / code > that caused the problem .
 * @ param response The < code > HttpServletResponse < / code > for the client . */
public void parseExceptionHandler ( ParseException pe , HttpServletResponse response ) { } }

implementation:
// log . error ( " DODSServlet . parseExceptionHandler " , pe ) ;
if ( Debug . isSet ( "showException" ) ) { log . error ( pe . toString ( ) ) ; printThrowable ( pe ) ; } try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( "Content-Description" , "dods-error" ) ; // This should probably be set to " plain " but this works , the
// C + + slients don ' t barf as they would if I sent " plain " AND
// the C + + don ' t expect compressed data if I do this . . .
response . setHeader ( "Content-Encoding" , "" ) ; // response . setContentType ( " text / plain " ) ;
// Strip any double quotes out of the parser error message .
// These get stuck in auto - magically by the javacc generated parser
// code and they break our error parser ( bummer ! )
String msg = pe . getMessage ( ) . replace ( '\"' , '\'' ) ; DAP2Exception de2 = new DAP2Exception ( opendap . dap . DAP2Exception . CANNOT_READ_FILE , msg ) ; de2 . print ( eOut ) ; } catch ( IOException ioe ) { log . error ( "Cannot respond to client! IO Error: " + ioe . getMessage ( ) ) ; }


signature:
public class DTSServlet { /** * Sends a OPeNDAP DAP2 error to the client .
 * @ param de The OPeNDAP DAP2 exception that caused the problem .
 * @ param response The < code > HttpServletResponse < / code > for the client . */
public void dap2ExceptionHandler ( DAP2Exception de , HttpServletResponse response ) { } }

implementation:
// log . info ( " DODSServlet . dodsExceptionHandler ( " + de . getErrorCode ( ) + " ) " + de . getErrorMessage ( ) ) ;
if ( Debug . isSet ( "showException" ) ) { log . error ( de . toString ( ) ) ; de . printStackTrace ( ) ; printDODSException ( de ) ; } // Convert Dap2Excaption code to an HttpCode
switch ( de . getErrorCode ( ) ) { case DAP2Exception . NO_SUCH_FILE : case DAP2Exception . CANNOT_READ_FILE : response . setStatus ( HttpStatus . SC_NOT_FOUND ) ; break ; case DAP2Exception . NO_AUTHORIZATION : response . setStatus ( HttpStatus . SC_UNAUTHORIZED ) ; break ; case DAP2Exception . NO_SUCH_VARIABLE : case DAP2Exception . MALFORMED_EXPR : case DAP2Exception . UNKNOWN_ERROR : // fall thru
default : response . setStatus ( HttpStatus . SC_BAD_REQUEST ) ; break ; } try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( "Content-Description" , "dods-error" ) ; // This should probably be set to " plain " but this works , the
// C + + slients don ' t barf as they would if I sent " plain " AND
// the C + + don ' t expect compressed data if I do this . . .
response . setHeader ( "Content-Encoding" , "" ) ; de . print ( eOut ) ; } catch ( IOException ioe ) { log . error ( "Cannot respond to client! IO Error: " + ioe . getMessage ( ) ) ; }


signature:
public class DTSServlet { /** * Sends an error to the client .
 * fix : The problem is that if the message is already committed when the IOException occurs , the headers dont get set .
 * @ param e The exception that caused the problem .
 * @ param rs The < code > ReqState < / code > for the client . */
public void IOExceptionHandler ( IOException e , ReqState rs ) { } }

implementation:
HttpServletResponse response = rs . getResponse ( ) ; try { BufferedOutputStream eOut = new BufferedOutputStream ( response . getOutputStream ( ) ) ; response . setHeader ( "Content-Description" , "dods-error" ) ; // This should probably be set to " plain " but this works , the
// C + + slients don ' t barf as they would if I sent " plain " AND
// the C + + don ' t expect compressed data if I do this . . .
response . setHeader ( "Content-Encoding" , "" ) ; // Strip any double quotes out of the parser error message .
// These get stuck in auto - magically by the javacc generated parser
// code and they break our error parser ( bummer ! )
String msg = e . getMessage ( ) ; if ( msg != null ) msg = msg . replace ( '\"' , '\'' ) ; DAP2Exception de2 = new DAP2Exception ( opendap . dap . DAP2Exception . CANNOT_READ_FILE , msg ) ; de2 . print ( eOut ) ; if ( Debug . isSet ( "showException" ) ) { // Error message
log . error ( "DODServlet ERROR (IOExceptionHandler): " + e ) ; log . error ( rs . toString ( ) ) ; if ( track ) { RequestDebug reqD = ( RequestDebug ) rs . getUserObject ( ) ; log . error ( "  request number: " + reqD . reqno + " thread: " + reqD . threadDesc ) ; } printThrowable ( e ) ; } } catch ( IOException ioe ) { log . error ( "Cannot respond to client! IO Error: " + ioe . getMessage ( ) ) ; }


signature:
public class DTSServlet { /** * Sends a OPeNDAP DAP2 error ( type UNKNOWN ERROR ) to the client and displays a
 * message on the server console .
 * @ param rs The client ' s < code > ReqState < / code > object .
 * @ param clientMsg Error message < code > String < / code > to send to the client .
 * @ param serverMsg Error message < code > String < / code > to display on the server console . */
public void sendDODSError ( ReqState rs , String clientMsg , String serverMsg ) throws Exception { } }

implementation:
rs . getResponse ( ) . setContentType ( "text/plain" ) ; rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-error" ) ; // Commented because of a bug in the OPeNDAP C + + stuff . . .
// response . setHeader ( " Content - Encoding " , " none " ) ;
ServletOutputStream Out = rs . getResponse ( ) . getOutputStream ( ) ; DAP2Exception de = new DAP2Exception ( opendap . dap . DAP2Exception . UNKNOWN_ERROR , clientMsg ) ; de . print ( Out ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; log . error ( serverMsg ) ;


signature:
public class DTSServlet { /** * Handler for the client ' s DDX request . Requires the getDDX ( ) method
 * implemented by each server localization effort .
 * < p > Once the DDX has been parsed and constrained it is sent to the
 * requesting client .
 * @ param rs The ReqState of this client request . Contains all kinds of
 * important stuff .
 * @ see ReqState */
public void doGetDDX ( ReqState rs ) throws Exception { } }

implementation:
if ( Debug . isSet ( "showResponse" ) ) { log . debug ( "doGetDDX for dataset: " + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( null == ds ) return ; rs . getResponse ( ) . setContentType ( "text/plain" ) ; rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-ddx" ) ; // Commented because of a bug in the OPeNDAP C + + stuff . . .
// rs . getResponse ( ) . setHeader ( " Content - Encoding " , " plain " ) ;
OutputStream Out = new BufferedOutputStream ( rs . getResponse ( ) . getOutputStream ( ) ) ; // Utilize the getDDS ( ) method to get a parsed and populated DDS
// for this server .
ServerDDS myDDS = ds . getDDS ( ) ; if ( rs . getConstraintExpression ( ) . equals ( "" ) ) { // No Constraint Expression ?
// Send the whole DDS
myDDS . printXML ( Out ) ; Out . flush ( ) ; } else { // Otherwise , send the constrained DDS
// Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator ( myDDS ) ; ce . parseConstraint ( rs ) ; // Send the constrained DDS back to the client
PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( Out , Util . UTF8 ) ) ; myDDS . printConstrainedXML ( pw ) ; pw . flush ( ) ; } rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; if ( Debug . isSet ( "showResponse" ) ) { if ( rs . getConstraintExpression ( ) . equals ( "" ) ) { // No Constraint Expression ?
// log . debug ( " Unconstrained DDX = \ n " ) ;
// myDDS . printXML ( System . out ) ;
} else { // log . debug ( " Constrained DDX = \ n " ) ;
// myDDS . printConstrainedXML ( System . out ) ;
} } } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException pe ) { IOExceptionHandler ( pe , rs ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed
if ( ds != null ) ds . release ( ) ; }


signature:
public class DTSServlet { /** * Handler for the client ' s data request . Requires the getDDS ( )
 * method implemented by each server localization effort .
 * < p > Once the DDS has been parsed , the data is read ( using the class in the
 * localized server factory etc . ) , compared to the constraint expression ,
 * and then sent to the client .
 * @ param rs The ReqState of this client request . Contains all kinds of
 * important stuff .
 * @ opendap . ddx . experimental
 * @ see ReqState */
public void doGetBLOB ( ReqState rs ) throws Exception { } }

implementation:
if ( Debug . isSet ( "showResponse" ) ) { log . debug ( "doGetBLOB For: " + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; rs . getResponse ( ) . setContentType ( "application/octet-stream" ) ; rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-blob" ) ; ServletOutputStream sOut = rs . getResponse ( ) . getOutputStream ( ) ; OutputStream bOut ; DeflaterOutputStream dOut = null ; if ( rs . getAcceptsCompressed ( ) && allowDeflate ) { rs . getResponse ( ) . setHeader ( "Content-Encoding" , "deflate" ) ; dOut = new DeflaterOutputStream ( sOut ) ; bOut = new BufferedOutputStream ( dOut ) ; } else { // Commented out because of a bug in the OPeNDAP C + + stuff . . .
// rs . getResponse ( ) . setHeader ( " Content - Encoding " , " plain " ) ;
bOut = new BufferedOutputStream ( sOut ) ; } // Utilize the getDDS ( ) method to get
// a parsed and populated DDS
// for this server .
ServerDDS myDDS = ds . getDDS ( ) ; cacheArrayShapes ( myDDS ) ; // Instantiate the CEEvaluator and parse the constraint expression
CEEvaluator ce = new CEEvaluator ( myDDS , new ClauseFactory ( functionLibrary ) ) ; ce . parseConstraint ( rs . getConstraintExpression ( ) , rs . getRequestURL ( ) . toString ( ) ) ; // Send the binary data back to the client
DataOutputStream sink = new DataOutputStream ( bOut ) ; int seqLength = 5 ; String sls = rs . getInitParameter ( "SequenceLength" ) ; if ( sls != null ) { seqLength = ( Integer . valueOf ( sls ) ) . intValue ( ) ; } testEngine te = new testEngine ( seqLength ) ; ce . send ( myDDS . getEncodedName ( ) , sink , te ) ; sink . flush ( ) ; // Finish up sending the compressed stuff , but don ' t
// close the stream ( who knows what the Servlet may expect ! )
if ( rs . getAcceptsCompressed ( ) ) { if ( bOut != null ) bOut . flush ( ) ; if ( dOut != null ) ( ( DeflaterOutputStream ) dOut ) . finish ( ) ; } // ? if ( null ! = dOut ) dOut . finish ( ) ;
// ? bOut . flush ( ) ;
rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException ioe ) { IOExceptionHandler ( ioe , rs ) ; } finally { // release lock if needed
if ( ds != null ) ds . release ( ) ; }


signature:
public class DTSServlet { /** * Handler for the client ' s directory request .
 * Returns an html document to the client showing ( a possibly pseudo )
 * listing of the datasets available on the server in a directory listing
 * format .
 * The bulk of this code resides in the class opendap . servlet . GetDirHandler and
 * documentation may be found there .
 * @ param rs The client ' s < code > ReqState < / code >
 * @ see opendap . servlet . GetDirHandler */
public void doGetDIR ( ReqState rs ) throws Exception { } }

implementation: rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( "text/html" ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-directory" ) ; try { GetDirHandler di = new GetDirHandler ( ) ; di . sendDIR ( rs ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; }


signature:
public class DTSServlet { /** * Sends an html document to the client explaining that they have used a
 * poorly formed URL and then the help page . . .
 * @ param request The client ' s < code > request < / code >
 * @ param response The client < code > response < / code > */
public void badURL ( HttpServletRequest request , HttpServletResponse response ) throws Exception { } }

implementation:
if ( Debug . isSet ( "showResponse" ) ) { log . debug ( "Sending Bad URL Page." ) ; } // log . info ( " DODSServlet . badURL " + rs . getRequest ( ) . getRequestURI ( ) ) ;
response . setContentType ( "text/html" ) ; response . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; response . setHeader ( "Content-Description" , "dods-error" ) ; // Commented because of a bug in the OPeNDAP C + + stuff . . .
// rs . getResponse ( ) . setHeader ( " Content - Encoding " , " plain " ) ;
PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( response . getOutputStream ( ) , Util . UTF8 ) ) ; printBadURLPage ( pw ) ; printHelpPage ( pw ) ; pw . flush ( ) ; response . setStatus ( HttpServletResponse . SC_OK ) ;


signature:
public class DTSServlet { /** * Handler for OPeNDAP info requests . Returns an HTML document
 * describing the contents of the servers datasets .
 * The bulk of this code resides in the class opendap . servlet . GetInfoHandler and
 * documentation may be found there .
 * @ param rs The client ' s < code > ReqState < / code >
 * @ see GetInfoHandler */
public void doGetINFO ( ReqState rs ) throws Exception { } }

implementation:
if ( Debug . isSet ( "showResponse" ) ) { log . debug ( "doGetINFO For: " + rs . getDataSet ( ) ) ; } GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( "text/html" ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-description" ) ; GetInfoHandler di = new GetInfoHandler ( ) ; di . sendINFO ( pw , ds , rs ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException pe ) { IOExceptionHandler ( pe , rs ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed
if ( ds != null ) ds . release ( ) ; }


signature:
public class DTSServlet { /** * Handler for OPeNDAP . html requests . Returns the OPeNDAP Web
 * Interface ( aka The Interface From Hell ) to the client .
 * The bulk of this code resides in the class
 * opendap . servlet . GetHTMLInterfaceHandler and
 * documentation may be found there .
 * @ param rs The client ' s < code > ReqState < / code >
 * @ see GetHTMLInterfaceHandler */
public void doGetHTML ( ReqState rs ) throws Exception { } }

implementation:
GuardedDataset ds = null ; try { ds = getDataset ( rs ) ; if ( ds == null ) return ; rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( "text/html" ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-form" ) ; // Utilize the getDDS ( ) method to geta parsed and populated DDS
// for this server .
ServerDDS myDDS = ds . getDDS ( ) ; DAS das = ds . getDAS ( ) ; GetHTMLInterfaceHandler di = new GetHTMLInterfaceHandler ( ) ; di . sendDataRequestForm ( rs , rs . getDataSet ( ) , myDDS , das ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ; } catch ( ParseException pe ) { parseExceptionHandler ( pe , rs . getResponse ( ) ) ; } catch ( DAP2Exception de ) { dap2ExceptionHandler ( de , rs . getResponse ( ) ) ; } catch ( IOException pe ) { IOExceptionHandler ( pe , rs ) ; } catch ( Throwable t ) { anyExceptionHandler ( t , rs ) ; } finally { // release lock if needed
if ( ds != null ) ds . release ( ) ; }


signature:
public class DTSServlet { /** * Handler for OPeNDAP catalog . xml requests .
 * @ param rs The client ' s < code > ReqState < / code >
 * @ see GetHTMLInterfaceHandler */
public void doGetCatalog ( ReqState rs ) throws Exception { } }

implementation: rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( "text/xml" ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-catalog" ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; printCatalog ( rs , pw ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ;


signature:
public class DTSServlet { /** * to be overridden by servers that implement catalogs */
protected void printCatalog ( ReqState rs , PrintWriter os ) throws IOException { } }

implementation: os . println ( "Catalog not available for this server" ) ; os . println ( "Server version = " + getServerVersion ( ) ) ;


signature:
public class DTSServlet { /** * Handler for OPeNDAP status requests ; not publically available ,
 * used only for debugging
 * @ param rs The client ' s < code > ReqState < / code >
 * @ see GetHTMLInterfaceHandler */
public void doGetSystemProps ( ReqState rs ) throws Exception { } }

implementation:
rs . getResponse ( ) . setHeader ( "XDODS-Server" , getServerVersion ( ) ) ; rs . getResponse ( ) . setContentType ( "text/html" ) ; rs . getResponse ( ) . setHeader ( "Content-Description" , "dods-status" ) ; PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; pw . println ( "" ) ; pw . println ( "<title>System Properties</title>" ) ; pw . println ( "
" ) ; pw . println ( "
System Properties
" ) ; pw . println ( "
Date: " + new Date ( ) + "
" ) ; Properties sysp = System . getProperties ( ) ; Enumeration e = sysp . propertyNames ( ) ; pw . println ( "
" ) ; while ( e . hasMoreElements ( ) ) { String name = ( String ) e . nextElement ( ) ; String value = System . getProperty ( name ) ; pw . println ( "
" + name + ": " + value + "
" ) ; } pw . println ( "
" ) ; pw . println ( "
Runtime Info:
" ) ; Runtime rt = Runtime . getRuntime ( ) ; pw . println ( "JVM Max Memory:   " + ( rt . maxMemory ( ) / 1024 ) / 1000. + " MB (JVM Maximum Allowable Heap)
" ) ; pw . println ( "JVM Total Memory: " + ( rt . totalMemory ( ) / 1024 ) / 1000. + " MB (JVM Heap size)
" ) ; pw . println ( "JVM Free Memory:  " + ( rt . freeMemory ( ) / 1024 ) / 1000. + " MB (Unused part of heap)
" ) ; pw . println ( "JVM Used Memory:  " + ( ( rt . totalMemory ( ) - rt . freeMemory ( ) ) / 1024 ) / 1000. + " MB (Currently active memory)
" ) ; pw . println ( "
" ) ; pw . println ( "" ) ; pw . println ( "" ) ; pw . flush ( ) ; rs . getResponse ( ) . setStatus ( HttpServletResponse . SC_OK ) ;