Input: Checks for internal consistency . For <code > DSequence< / code > verify that the variables have unique names . [CODESPLIT] public void checkSemantics ( boolean all ) throws BadSemanticsException { super . checkSemantics ( all ) ; Util . uniqueNames ( varTemplate , getEncodedName ( ) , getTypeName ( ) ) ; if ( all ) { for ( Enumeration e = varTemplate . elements ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . checkSemantics ( true ) ; } } }


Input:
Prints the value of the variable with its declaration . This function is primarily intended for debugging OPeNDAP applications and text - based clients such as geturl . [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( print_decl_p ) { printDecl ( os , space , false ) ; os . print ( " = " ) ; } os . print ( "{ " ) ; for ( Enumeration e1 = allValues . elements ( ) ; e1 . hasMoreElements ( ) ; ) { // get next instance vector
 os . print ( "{ " ) ; Vector v = ( Vector ) e1 . nextElement ( ) ; for ( Enumeration e2 = v . elements ( ) ; e2 . hasMoreElements ( ) ; ) { // get next instance variable
 BaseType bt = ( BaseType ) e2 . nextElement ( ) ; bt . printVal ( os , "" , false ) ; if ( e2 . hasMoreElements ( ) ) os . print ( ", " ) ; } os . print ( " }" ) ; if ( e1 . hasMoreElements ( ) ) os . print ( ", " ) ; } os . print ( " }" ) ; if ( print_decl_p ) os . println ( ";" ) ; }


Input:
Reads data from a <code > DataInputStream< / code > . This method is only used on the client side of the OPeNDAP client / server connection . [CODESPLIT] public synchronized void deserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , DataReadException { //LogStream.out.println("ServerVersion.getMajor() "+sv.getMajor()+"  ServerVersion.getMinor(): "+sv.getMinor());
 // check for old servers
 if ( sv != null && ( sv . getMajor ( ) < 2 || ( sv . getMajor ( ) == 2 && sv . getMinor ( ) < 15 ) ) ) { //LogStream.out.println("Using oldDeserialize() mechanism.");
 oldDeserialize ( source , sv , statusUI ) ; } else { //LogStream.out.println("Using new deserialize() mechanism.");
 // ************* Pulled out the getLevel() check in order to support the "new"
 // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp
 //            // top level of sequence handles start and end markers
 //            if (getLevel() == 0) {
 // loop until end of sequence
 for ( ; ; ) { byte marker = readMarker ( source ) ; if ( statusUI != null ) statusUI . incrementByteCount ( 4 ) ; if ( marker == START_OF_INSTANCE ) deserializeSingle ( source , sv , statusUI ) ; else if ( marker == END_OF_SEQUENCE ) break ; else throw new DataReadException ( "Sequence start marker not found" ) ; } // ************* Pulled out the getLevel() check in order to support the "new"
 // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp
 //            }
 //	    else {
 //                // lower levels only deserialize a single instance at a time
 //                deserializeSingle(source, sv, statusUI);
 //            }
 } }


Input: The old deserialize protocol has a number of limitations stemming from its inability to tell when the sequence is finished . It s really only good for a Dataset containing a single sequence or where the sequence is the last thing in the dataset . To handle this we just read single instances until we get an IOException then stop . [CODESPLIT] private void oldDeserialize ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , DataReadException { try { for ( ; ; ) { deserializeSingle ( source , sv , statusUI ) ; } } catch ( EOFException e ) { } }


Input:
Deserialize a single row of the <code > DSequence< / code > . [CODESPLIT] private void deserializeSingle ( DataInputStream source , ServerVersion sv , StatusUI statusUI ) throws IOException , EOFException , DataReadException { // create a new instance from the variable template Vector
 Vector newInstance = new Vector ( ) ; for ( int i = 0 ; i < varTemplate . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) varTemplate . elementAt ( i ) ; newInstance . addElement ( bt . clone ( ) ) ; } // deserialize the new instance
 for ( Enumeration e = newInstance . elements ( ) ; e . hasMoreElements ( ) ; ) { if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( "User cancelled" ) ; ClientIO bt = ( ClientIO ) e . nextElement ( ) ; bt . deserialize ( source , sv , statusUI ) ; } // add the new instance to the allValues vector
 allValues . addElement ( newInstance ) ; }


Input:
Reads a marker byte from the input stream . [CODESPLIT] private byte readMarker ( DataInputStream source ) throws IOException { byte marker = source . readByte ( ) ; // pad out to a multiple of four bytes
 byte unused ; for ( int i = 0 ; i < 3 ; i ++ ) unused = source . readByte ( ) ; return marker ; }


Input:
Writes a marker byte to the output stream . [CODESPLIT] protected void writeMarker ( DataOutputStream sink , byte marker ) throws IOException { //for(int i=0; i<4; i++)
 sink . writeByte ( marker ) ; sink . writeByte ( ( byte ) 0 ) ; sink . writeByte ( ( byte ) 0 ) ; sink . writeByte ( ( byte ) 0 ) ; }


Input:
Writes data to a <code > DataOutputStream< / code > . This method is used primarily by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void externalize ( DataOutputStream sink ) throws IOException { // loop until end of sequence
 for ( int i = 0 ; i < allValues . size ( ) ; i ++ ) { // ************* Pulled out the getLevel() check in order to support the "new"
 // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp
 //            if (getLevel() == 0)
 writeMarker ( sink , START_OF_INSTANCE ) ; Vector rowVec = ( Vector ) allValues . elementAt ( i ) ; for ( int j = 0 ; j < rowVec . size ( ) ; j ++ ) { ClientIO bt = ( ClientIO ) rowVec . elementAt ( j ) ; bt . externalize ( sink ) ; } } // ************* Pulled out the getLevel() check in order to support the "new"
 // and "improved" serialization of OPeNDAP sequences. 8/31/01 ndp
 //        if (getLevel() == 0)
 writeMarker ( sink , END_OF_SEQUENCE ) ; }


Input: Returns a clone of this <code > Sequence< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DSequence s = ( DSequence ) super . cloneDAG ( map ) ; s . varTemplate = new Vector ( ) ; for ( int i = 0 ; i < varTemplate . size ( ) ; i ++ ) { BaseType bt = ( BaseType ) varTemplate . elementAt ( i ) ; BaseType btclone = ( BaseType ) cloneDAG ( map , bt ) ; s . varTemplate . addElement ( btclone ) ; } s . allValues = new Vector ( ) ; for ( int i = 0 ; i < allValues . size ( ) ; i ++ ) { Vector rowVec = ( Vector ) allValues . elementAt ( i ) ; Vector newVec = new Vector ( ) ; for ( int j = 0 ; j < rowVec . size ( ) ; j ++ ) { BaseType bt = ( BaseType ) rowVec . elementAt ( j ) ; newVec . addElement ( ( BaseType ) cloneDAG ( map , bt ) ) ; } s . allValues . addElement ( newVec ) ; } return s ; }


Input: Public API [CODESPLIT] public boolean parse ( String document ) throws SAXException { // Trim and strip any leading <?xml...?> StringBuilder doc = new StringBuilder ( document . trim ( ) ) ; int index = doc . indexOf ( "<?xml" ) ; if ( index == 0 ) { index = doc . indexOf ( "?>" ) ; if ( index < 0 ) throw new SAXException ( "Document has malformed <?xml...?> prefix" ) ; doc . delete ( 0 , index + 2 ) ; // remove any leading crlf while ( doc . length ( ) > 0 && "\r\n" . indexOf ( doc . charAt ( 0 ) ) >= 0 ) doc . deleteCharAt ( 0 ) ; document = doc . toString ( ) ; } this . document = document ; // Create the sax parser that will drive us with events try { spf = SAXParserFactory . newInstance ( ) ; spf . setValidating ( false ) ; spf . setNamespaceAware ( true ) ; spf . setFeature ( LOAD_EXTERNAL_DTD , false ) ; saxparser = spf . newSAXParser ( ) ; // Set up for the parse input = new ByteArrayInputStream ( document . getBytes ( UTF8 ) ) ; saxparser . parse ( input , this ) ; //'this' is link to subclass parser return true ; } catch ( Exception e ) { throw new SAXException ( e ) ; } }


Input: Entity resolution ( Ignored ) [CODESPLIT] @ Override public InputSource resolveEntity ( String publicId , String systemId ) { if ( TRACE ) trace ( "eventtype.RESOLVEENTITY: %s.%s%n" , publicId , systemId ) ; return null ; }


Input: Error handling Events [CODESPLIT] @ Override public void fatalError ( SAXParseException e ) throws SAXException { throw new SAXParseException ( String . format ( "Sax fatal error: %s; %s%n" , e , report ( this . locator ) ) , this . locator ) ; }


Input: Location printing [CODESPLIT] protected void locatedEvent ( SaxEvent token ) throws SAXException { try { yyevent ( token ) ; } catch ( SAXException se ) { throw new SAXException ( locatedError ( se . getMessage ( ) ) ) ; } }


Input: Creates the demo chart . [CODESPLIT] private static TimeSeries createDataset ( String name , double base , RegularTimePeriod start , int count ) { TimeSeries series = new TimeSeries ( name , start . getClass ( ) ) ; RegularTimePeriod period = start ; double value = base ; for ( int i = 0 ; i < count ; i ++ ) { series . add ( period , value ) ; period = period . next ( ) ; value = value * ( 1 + ( Math . random ( ) - 0.495 ) / 10.0 ) ; } return series ; }


Input:
Starting point for the demonstration application . [CODESPLIT] public static void main ( String [ ] args ) { TimeSeries dataset1 = createDataset ( "Series 1" , 100.0 , new Minute ( ) , 200 ) ; MultipleAxisChart demo = new MultipleAxisChart ( "Multiple Axis Demo 1" , "Time of Day" , "Primary Range Axis" , dataset1 ) ; /* AXIS 2
    NumberAxis axis2 = new NumberAxis("Range Axis 2");
    axis2.setFixedDimension(10.0);
    axis2.setAutoRangeIncludesZero(false);
    plot.setRangeAxis(1, axis2);
    plot.setRangeAxisLocation(1, AxisLocation.BOTTOM_OR_LEFT); /

    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    XYItemRenderer renderer2 = new StandardXYItemRenderer();
    plot.setRenderer(1, renderer2); */ TimeSeries dataset2 = createDataset ( "Series 2" , 1000.0 , new Minute ( ) , 170 ) ; demo . addSeries ( "Range Axis 2" , dataset2 ) ; /*     // AXIS 3
    NumberAxis axis3 = new NumberAxis("Range Axis 3");
    plot.setRangeAxis(2, axis3);

    XYDataset dataset3 = createDataset("Series 3", 10000.0, new Minute(), 170);
    plot.setDataset(2, dataset3);
    plot.mapDatasetToRangeAxis(2, 2);
    XYItemRenderer renderer3 = new StandardXYItemRenderer();
    plot.setRenderer(2, renderer3);
    */ TimeSeries dataset3 = createDataset ( "Series 3" , 10000.0 , new Minute ( ) , 170 ) ; demo . addSeries ( "Range Axis 3" , dataset3 ) ; /* AXIS 4
    NumberAxis axis4 = new NumberAxis("Range Axis 4");
    plot.setRangeAxis(3, axis4);

    XYDataset dataset4 = createDataset("Series 4", 25.0, new Minute(), 200);
    plot.setDataset(3, dataset4);
    plot.mapDatasetToRangeAxis(3, 3);

    XYItemRenderer renderer4 = new StandardXYItemRenderer();
    plot.setRenderer(3, renderer4); */ TimeSeries dataset4 = createDataset ( "Series 4" , 25.0 , new Minute ( ) , 200 ) ; demo . addSeries ( "Range Axis 4" , dataset4 ) ; demo . finish ( new java . awt . Dimension ( 600 , 270 ) ) ; JFrame frame = new JFrame ( "Demovabulous " ) ; frame . getContentPane ( ) . add ( demo , BorderLayout . CENTER ) ; frame . setSize ( 640 , 480 ) ; frame . setVisible ( true ) ; frame . setDefaultCloseOperation ( JFrame . EXIT_ON_CLOSE ) ; }


Input: LOOK can we optimize ?? [CODESPLIT] public String [ ] getJavaArrayString ( StructureMembers . Member m ) { if ( m . getDataType ( ) == DataType . STRING ) { Array data = getArray ( m ) ; int n = m . getSize ( ) ; String [ ] result = new String [ n ] ; for ( int i = 0 ; i < result . length ; i ++ ) result [ i ] = ( String ) data . getObject ( i ) ; return result ; } else if ( m . getDataType ( ) == DataType . CHAR ) { ArrayChar data = ( ArrayChar ) getArray ( m ) ; ArrayChar . StringIterator iter = data . getStringIterator ( ) ; String [ ] result = new String [ iter . getNumElems ( ) ] ; int count = 0 ; while ( iter . hasNext ( ) ) result [ count ++ ] = iter . next ( ) ; return result ; } throw new IllegalArgumentException ( "getJavaArrayString: not String DataType :" + m . getDataType ( ) ) ; }


Input: Get the array of available parameter names for this volume . [CODESPLIT] public DoradePARM [ ] getParamList ( ) { int paramCount = 0 ; for ( int i = 0 ; i < nSensors ; i ++ ) paramCount += myRADDs [ i ] . getNParams ( ) ; DoradePARM [ ] list = new DoradePARM [ paramCount ] ; int next = 0 ; for ( int i = 0 ; i < nSensors ; i ++ ) { int nParams = myRADDs [ i ] . getNParams ( ) ; System . arraycopy ( myRADDs [ i ] . getParamList ( ) , 0 , list , next , nParams ) ; next += nParams ; } return list ; }


Input: override superclass [CODESPLIT] private void makeMyUI ( ) { AbstractAction incrFontAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { stnRender . incrFontSize ( ) ; redraw ( ) ; } } ; BAMutil . setActionProperties ( incrFontAction , "FontIncr" , "increase font size" , false , ' ' , - 1 ) ; AbstractAction decrFontAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { stnRender . decrFontSize ( ) ; redraw ( ) ; } } ; BAMutil . setActionProperties ( decrFontAction , "FontDecr" , "decrease font size" , false , ' ' , - 1 ) ; JCheckBox declutCB = new JCheckBox ( "Declutter" , true ) ; declutCB . addActionListener ( e -> { setDeclutter ( ( ( JCheckBox ) e . getSource ( ) ) . isSelected ( ) ) ; } ) ; AbstractAction bbAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { geoSelectionMode = ! geoSelectionMode ; np . setGeoSelectionMode ( geoSelectionMode ) ; redraw ( ) ; } } ; BAMutil . setActionProperties ( bbAction , "geoselect" , "select geo region" , true , ' ' , - 1 ) ; bbAction . putValue ( BAMutil . STATE , geoSelectionMode ? Boolean . TRUE : Boolean . FALSE ) ; // the fields use a PrefPanel if ( regionSelect ) { minmaxPP = new PrefPanel ( null , null ) ; minLonField = minmaxPP . addDoubleField ( "minLon" , "minLon" , geoSelection . getMinX ( ) , nfracDig , 0 , 0 , null ) ; maxLonField = minmaxPP . addDoubleField ( "maxLon" , "maxLon" , geoSelection . getMaxX ( ) , nfracDig , 2 , 0 , null ) ; minLatField = minmaxPP . addDoubleField ( "minLat" , "minLat" , geoSelection . getMinY ( ) , nfracDig , 4 , 0 , null ) ; maxLatField = minmaxPP . addDoubleField ( "maxLat" , "maxLat" , geoSelection . getMaxY ( ) , nfracDig , 6 , 0 , null ) ; minmaxPP . finish ( true , BorderLayout . EAST ) ; minmaxPP . addActionListener ( e -> { // "Apply" was called double minLon = minLonField . getDouble ( ) ; double minLat = minLatField . getDouble ( ) ; double maxLon = maxLonField . getDouble ( ) ; double maxLat = maxLatField . getDouble ( ) ; LatLonRect llbb = new LatLonRect ( new LatLonPointImpl ( minLat , minLon ) , new LatLonPointImpl ( maxLat , maxLon ) ) ; setGeoSelection ( llbb ) ; redraw ( ) ; } ) ; } // assemble setLayout ( new BorderLayout ( ) ) ; if ( stationSelect ) { BAMutil . addActionToContainer ( toolPanel , incrFontAction ) ; BAMutil . addActionToContainer ( toolPanel , decrFontAction ) ; toolPanel . add ( declutCB ) ; } if ( regionSelect ) BAMutil . addActionToContainer ( toolPanel , bbAction ) ; if ( dateSelect ) BAMutil . addActionToContainer ( toolPanel , dateAction ) ; JPanel upperPanel = new JPanel ( new BorderLayout ( ) ) ; if ( regionSelect ) upperPanel . add ( minmaxPP , BorderLayout . NORTH ) ; upperPanel . add ( toolPanel , BorderLayout . SOUTH ) ; JPanel statusPanel = new JPanel ( new BorderLayout ( ) ) ; statusPanel . setBorder ( new EtchedBorder ( ) ) ; JLabel positionLabel = new JLabel ( "position" ) ; statusPanel . add ( positionLabel , BorderLayout . CENTER ) ; np . setPositionLabel ( positionLabel ) ; add ( upperPanel , BorderLayout . NORTH ) ; add ( np , BorderLayout . CENTER ) ; add ( statusPanel , BorderLayout . SOUTH ) ; }


Input: Set the list of Stations . [CODESPLIT] public void setStations ( java . util . List stns ) { stnRender . setStations ( stns ) ; redraw ( true ) ; }


Input: Looks for the station with given id . If found makes it current . Redraws . [CODESPLIT] public void setSelectedStation ( String id ) { stnRender . setSelectedStation ( id ) ; selectedStation = stnRender . getSelectedStation ( ) ; assert selectedStation != null ; np . setLatLonCenterMapArea ( selectedStation . getLatitude ( ) , selectedStation . getLongitude ( ) ) ; redraw ( ) ; }


Input: Redraw the graphics on the screen . [CODESPLIT] protected void redraw ( ) { long tstart = System . currentTimeMillis ( ) ; java . awt . Graphics2D gNP = np . getBufferedImageGraphics ( ) ; if ( gNP == null ) // panel not drawn on screen yet return ; // clear it gNP . setBackground ( np . getBackgroundColor ( ) ) ; java . awt . Rectangle r = gNP . getClipBounds ( ) ; gNP . clearRect ( r . x , r . y , r . width , r . height ) ; if ( regionSelect && geoSelectionMode ) { if ( geoSelection != null ) drawBB ( gNP , geoSelection , Color . cyan ) ; if ( geoBounds != null ) drawBB ( gNP , geoBounds , null ) ; // System.out.println("GeoRegionChooser.redraw geoBounds= "+geoBounds); if ( geoSelection != null ) { // gNP.setColor( Color.orange); Navigation navigate = np . getNavigation ( ) ; double handleSize = RubberbandRectangleHandles . handleSizePixels / navigate . getPixPerWorld ( ) ; Rectangle2D rect = new Rectangle2D . Double ( geoSelection . getX ( ) , geoSelection . getY ( ) , geoSelection . getWidth ( ) , geoSelection . getHeight ( ) ) ; RubberbandRectangleHandles . drawHandledRect ( gNP , rect , handleSize ) ; if ( debug ) System . out . println ( "GeoRegionChooser.drawHandledRect=" + handleSize + " = " + geoSelection ) ; } } for ( int i = 0 ; i < renderers . size ( ) ; i ++ ) { ucar . nc2 . ui . util . Renderer rend = ( Renderer ) renderers . get ( i ) ; rend . draw ( gNP , atI ) ; } gNP . dispose ( ) ; if ( debug ) { long tend = System . currentTimeMillis ( ) ; System . out . println ( "StationRegionDateChooser draw time = " + ( tend - tstart ) / 1000.0 + " secs" ) ; } // copy buffer to the screen np . repaint ( ) ; }


Input: Setup needed for all SingleTrajectoryObsDatatypes . Can only be called once . [CODESPLIT] public void setTrajectoryInfo ( Config trajConfig ) throws IOException { if ( timeDim != null ) throw new IllegalStateException ( "The setTrajectoryInfo() method can only be called once." ) ; this . trajectoryId = trajConfig . getTrajectoryId ( ) ; this . timeDim = trajConfig . getTimeDim ( ) ; this . timeVar = trajConfig . getTimeVar ( ) ; this . latVar = trajConfig . getLatVar ( ) ; this . lonVar = trajConfig . getLonVar ( ) ; this . elevVar = trajConfig . getElevVar ( ) ; trajectoryNumPoint = this . timeDim . getLength ( ) ; timeVarUnitsString = this . timeVar . findAttribute ( "units" ) . getStringValue ( ) ; // Check that time, lat, lon, elev units are acceptable. if ( DateUnit . getStandardDate ( timeVarUnitsString ) == null ) { throw new IllegalArgumentException ( "Units of time variable <" + timeVarUnitsString + "> not a date unit." ) ; } String latVarUnitsString = this . latVar . findAttribute ( "units" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( latVarUnitsString , "degrees_north" ) ) { throw new IllegalArgumentException ( "Units of lat var <" + latVarUnitsString + "> not compatible with \"degrees_north\"." ) ; } String lonVarUnitsString = this . lonVar . findAttribute ( "units" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( lonVarUnitsString , "degrees_east" ) ) { throw new IllegalArgumentException ( "Units of lon var <" + lonVarUnitsString + "> not compatible with \"degrees_east\"." ) ; } String elevVarUnitsString = this . elevVar . findAttribute ( "units" ) . getStringValue ( ) ; if ( ! SimpleUnit . isCompatible ( elevVarUnitsString , "meters" ) ) { throw new IllegalArgumentException ( "Units of elev var <" + elevVarUnitsString + "> not compatible with \"meters\"." ) ; } try { elevVarUnitsConversionFactor = getMetersConversionFactor ( elevVarUnitsString ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( "Exception on getMetersConversionFactor() for the units of elev var <" + elevVarUnitsString + ">." ) ; } if ( this . netcdfDataset . hasUnlimitedDimension ( ) && this . netcdfDataset . getUnlimitedDimension ( ) . equals ( timeDim ) ) { Object result = this . netcdfDataset . sendIospMessage ( NetcdfFile . IOSP_MESSAGE_ADD_RECORD_STRUCTURE ) ; if ( ( result != null ) && ( Boolean ) result ) this . recordVar = ( Structure ) this . netcdfDataset . getRootGroup ( ) . findVariable ( "record" ) ; else this . recordVar = new StructurePseudo ( this . netcdfDataset , null , "record" , timeDim ) ; } else { this . recordVar = new StructurePseudo ( this . netcdfDataset , null , "record" , timeDim ) ; } // @todo HACK, HACK, HACK - remove once addRecordStructure() deals with ncd attribute changes. Variable elevVarInRecVar = this . recordVar . findVariable ( this . elevVar . getFullNameEscaped ( ) ) ; if ( ! elevVarUnitsString . equals ( elevVarInRecVar . findAttribute ( "units" ) . getStringValue ( ) ) ) { elevVarInRecVar . addAttribute ( new Attribute ( "units" , elevVarUnitsString ) ) ; } trajectoryVarsMap = new HashMap ( ) ; //for ( Iterator it = this.recordVar.getVariables().iterator(); it.hasNext(); ) for ( Iterator it = this . netcdfDataset . getRootGroup ( ) . getVariables ( ) . iterator ( ) ; it . hasNext ( ) ; ) { Variable curVar = ( Variable ) it . next ( ) ; if ( curVar . getRank ( ) > 0 && ! curVar . equals ( this . timeVar ) && ! curVar . equals ( this . latVar ) && ! curVar . equals ( this . lonVar ) && ! curVar . equals ( this . elevVar ) && ( this . recordVar == null ? true : ! curVar . equals ( this . recordVar ) ) ) { MyTypedDataVariable typedVar = new MyTypedDataVariable ( new VariableDS ( null , curVar , true ) ) ; dataVariables . add ( typedVar ) ; trajectoryVarsMap . put ( typedVar . getShortName ( ) , typedVar ) ; } } trajectory = new SingleTrajectory ( this . trajectoryId , trajectoryNumPoint , this . timeVar , timeVarUnitsString , this . latVar , this . lonVar , this . elevVar , dataVariables , trajectoryVarsMap ) ; startDate = trajectory . getTime ( 0 ) ; endDate = trajectory . getTime ( trajectoryNumPoint - 1 ) ; ( ( SingleTrajectory ) trajectory ) . setStartDate ( startDate ) ; ( ( SingleTrajectory ) trajectory ) . setEndDate ( endDate ) ; }


Input: Static methods [CODESPLIT] static public DapType lookup ( TypeSort atomic ) { if ( atomic == TypeSort . Enum ) return null ; // we need more info return typemap . get ( atomic ) ; }


Input:
Convert a LatLonPoint to projection coordinates [CODESPLIT] @ Override public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; double fromLat_r = Math . toRadians ( fromLat ) ; // infinite projection
 if ( ( Math . abs ( 90.0 - Math . abs ( fromLat ) ) ) < TOLERANCE ) { toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = A * Math . toRadians ( LatLonPointImpl . range180 ( fromLon - this . lon0 ) ) ; toY = A * SpecialMathFunction . atanh ( Math . sin ( fromLat_r ) ) ; // p 41 Snyder
 } result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }


Input:
Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] @ Override public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double toLon = Math . toDegrees ( fromX / A ) + lon0 ; double e = Math . exp ( - fromY / A ) ; double toLat = Math . toDegrees ( Math . PI / 2 - 2 * Math . atan ( e ) ) ; // Snyder p 44
 result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }


Input: Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( Catalog catalog , OutputStream os , boolean raw ) throws IOException { this . raw = raw ; writeXML ( catalog , os ) ; this . raw = false ; }


Input: Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( Catalog catalog , OutputStream os ) throws IOException { // Output the document, use standard formatter //XMLOutputter fmt = new XMLOutputter(); //fmt.setNewlines(true); //fmt.setIndent("  "); //fmt.setTrimAllWhite( true); XMLOutputter fmt = new XMLOutputter ( org . jdom2 . output . Format . getPrettyFormat ( ) ) ; // LOOK maybe compact ?? fmt . output ( writeCatalog ( catalog ) , os ) ; }


Input: / * protected void writeCat6InheritedMetadata ( Element elem ThreddsMetadata tmi ) { if (( tmi . getDataType () == null ) && ( tmi . getServiceName () == null ) && ( tmi . getAuthority () == null ) && ( tmi . getProperties () . size () == 0 )) return ; [CODESPLIT] protected void writeInheritedMetadata ( Element elem , Dataset ds ) { Element mdataElem = new Element ( "metadata" , Catalog . defNS ) ; mdataElem . setAttribute ( "inherited" , "true" ) ; ThreddsMetadata tmi = ( ThreddsMetadata ) ds . getLocalField ( Dataset . ThreddsMetadataInheritable ) ; if ( tmi == null ) return ; writeThreddsMetadata ( mdataElem , tmi ) ; if ( mdataElem . getChildren ( ) . size ( ) > 0 ) elem . addContent ( mdataElem ) ; }


Input: Adds a <code > Rectangle2D< / code > object to this <code > Rectangle2D< / code > . The resulting <code > Rectangle2D< / code > is the union of the two <code > Rectangle2D< / code > objects . [CODESPLIT] public void add ( ProjectionRect r ) { double x1 = Math . min ( getMinX ( ) , r . getMinX ( ) ) ; double x2 = Math . max ( getMaxX ( ) , r . getMaxX ( ) ) ; double y1 = Math . min ( getMinY ( ) , r . getMinY ( ) ) ; double y2 = Math . max ( getMaxY ( ) , r . getMaxY ( ) ) ; setRect ( x1 , y1 , x2 - x1 , y2 - y1 ) ; }


Input: Adds a point specified by the double precision arguments <code > newx< / code > and <code > newy< / code > to this <code > Rectangle2D< / code > . The resulting <code > Rectangle2D< / code > is the smallest <code > Rectangle2D< / code > that contains both the original <code > Rectangle2D< / code > and the specified point . <p > After adding a point a call to <code > contains< / code > with the added point as an argument does not necessarily return <code > true< / code > . The <code > contains< / code > method does not return <code > true< / code > for points on the right or bottom edges of a rectangle . Therefore if the added point falls on the left or bottom edge of the enlarged rectangle <code > contains< / code > returns <code > false< / code > for that point . [CODESPLIT] public void add ( double newx , double newy ) { double x1 = Math . min ( getMinX ( ) , newx ) ; double x2 = Math . max ( getMaxX ( ) , newx ) ; double y1 = Math . min ( getMinY ( ) , newy ) ; double y2 = Math . max ( getMaxY ( ) , newy ) ; setRect ( x1 , y1 , x2 - x1 , y2 - y1 ) ; }


Input: Intersects the pair of specified source <code > Rectangle2D< / code > objects and puts the result into the specified destination <code > Rectangle2D< / code > object . One of the source rectangles can also be the destination to avoid creating a third Rectangle2D object but in this case the original points of this source rectangle will be overwritten by this method . [CODESPLIT] public static void intersect ( ProjectionRect src1 , ProjectionRect src2 , ProjectionRect dest ) { double x1 = Math . max ( src1 . getMinX ( ) , src2 . getMinX ( ) ) ; double y1 = Math . max ( src1 . getMinY ( ) , src2 . getMinY ( ) ) ; double x2 = Math . min ( src1 . getMaxX ( ) , src2 . getMaxX ( ) ) ; double y2 = Math . min ( src1 . getMaxY ( ) , src2 . getMaxY ( ) ) ; dest . setRect ( x1 , y1 , x2 - x1 , y2 - y1 ) ; }


Input: Returns { @code true } if this bounding box contains { @code point } . [CODESPLIT] public boolean contains ( ProjectionPoint point ) { return DoubleMath . fuzzyCompare ( point . getX ( ) , getMinX ( ) , 1e-6 ) >= 0 && DoubleMath . fuzzyCompare ( point . getX ( ) , getMaxX ( ) , 1e-6 ) <= 0 && DoubleMath . fuzzyCompare ( point . getY ( ) , getMinY ( ) , 1e-6 ) >= 0 && DoubleMath . fuzzyCompare ( point . getY ( ) , getMaxY ( ) , 1e-6 ) <= 0 ; }


Input: Read the object from the input stream of the serialized object [CODESPLIT] private void readObject ( ObjectInputStream s ) throws IOException , ClassNotFoundException { double x = s . readDouble ( ) ; double y = s . readDouble ( ) ; double w = s . readDouble ( ) ; double h = s . readDouble ( ) ; setRect ( x , y , w , h ) ; }


Input: Wrtie the object to the output stream [CODESPLIT] private void writeObject ( ObjectOutputStream s ) throws IOException { s . writeDouble ( getX ( ) ) ; s . writeDouble ( getY ( ) ) ; s . writeDouble ( getWidth ( ) ) ; s . writeDouble ( getHeight ( ) ) ; }


Input: Returns { @code true } if this rectangle is nearly equal to { @code other } . The near equality of corners is determined using { @link ProjectionPoint#nearlyEquals ( ProjectionPoint double ) } with the specified maxRelDiff . [CODESPLIT] public boolean nearlyEquals ( ProjectionRect other , double maxRelDiff ) { return this . getLowerLeftPoint ( ) . nearlyEquals ( other . getLowerLeftPoint ( ) , maxRelDiff ) && this . getUpperRightPoint ( ) . nearlyEquals ( other . getUpperRightPoint ( ) , maxRelDiff ) ; }


Input: Adds all the entries in another UnitDBImpl to this database . [CODESPLIT] public void add ( final UnitDBImpl that ) throws UnitExistsException { unitSet . addAll ( that . unitSet ) ; nameMap . putAll ( that . nameMap ) ; symbolMap . putAll ( that . symbolMap ) ; }


Input: Adds a unit to the database . [CODESPLIT] public void addUnit ( final Unit unit ) throws UnitExistsException , NameException { if ( unit . getName ( ) == null ) { throw new NameException ( "Unit name can't be null" ) ; } addByName ( unit . getName ( ) , unit ) ; addByName ( unit . getPlural ( ) , unit ) ; addBySymbol ( unit . getSymbol ( ) , unit ) ; unitSet . add ( unit ) ; }


Input: Adds an alias for a unit already in the database . [CODESPLIT] public final void addAlias ( final String alias , final String name ) throws NoSuchUnitException , UnitExistsException { addAlias ( alias , name , null ) ; }


Input: Adds a symbol for a unit already in the database . [CODESPLIT] public final void addSymbol ( final String symbol , final String name ) throws NoSuchUnitException , UnitExistsException { addAlias ( null , name , symbol , null ) ; }


Input: Adds an alias for a unit already in the database . [CODESPLIT] public final void addAlias ( final String alias , final String name , final String symbol , final String plural ) throws NoSuchUnitException , UnitExistsException { addAlias ( UnitID . newUnitID ( alias , plural , symbol ) , name ) ; }


Input: Adds an alias for a unit already in the database . [CODESPLIT] public final void addAlias ( final UnitID alias , final String name ) throws NoSuchUnitException , UnitExistsException { final Unit unit = getByName ( name ) ; if ( unit == null ) { throw new NoSuchUnitException ( name ) ; } addByName ( alias . getName ( ) , unit ) ; addByName ( alias . getPlural ( ) , unit ) ; addBySymbol ( alias . getSymbol ( ) , unit ) ; }


Input: Gets a unit by either name plural or symbol . Retrieving the unit by symbol is attempted before retrieving the unit by name because symbol comparisons are case sensitive and hence should be more robust . [CODESPLIT] public Unit get ( final String id ) { Unit unit = getBySymbol ( id ) ; if ( unit == null ) { unit = getByName ( id ) ; } return unit ; }


Input: Adds a unit to the database by name . [CODESPLIT] private final void addByName ( final String name , final Unit newUnit ) throws UnitExistsException { if ( name != null ) { addUnique ( nameMap , canonicalize ( name ) , newUnit ) ; } }


Input: Adds a unit to the database by symbol . [CODESPLIT] private final void addBySymbol ( final String symbol , final Unit newUnit ) throws UnitExistsException { if ( symbol != null ) { addUnique ( symbolMap , symbol , newUnit ) ; } }


Input: Adds a unique unit to a map .. [CODESPLIT] private static final void addUnique ( final Map < String , Unit > map , final String key , final Unit newUnit ) throws UnitExistsException { final Unit oldUnit = map . put ( key , newUnit ) ; if ( oldUnit != null && ! oldUnit . equals ( newUnit ) ) { throw new UnitExistsException ( oldUnit , newUnit ) ; } }


Input: //////////////////////////////////////////////// [CODESPLIT] protected void buildFileList ( Root rootinfo ) throws DapException { File root = new File ( rootinfo . getFullPath ( ) ) ; if ( ! root . isDirectory ( ) ) throw new DapException ( "FrontPage: specified root directory is not a directory: " + rootinfo . getFullPath ( ) ) ; if ( ! root . canRead ( ) ) throw new DapException ( "FrontPage: specified root directory is not readable: " + rootinfo . getFullPath ( ) ) ; // take files from set of files immediately under root File [ ] candidates = root . listFiles ( ) ; List < FileSource > activesources = new ArrayList < FileSource > ( ) ; // Capture lists of files for each FileSource for ( FileSource src : SOURCES ) { List < File > matches = new ArrayList < File > ( ) ; for ( File candidate : candidates ) { String name = candidate . getName ( ) ; boolean excluded = false ; for ( String exclude : expatterns ) { if ( name . indexOf ( exclude ) >= 0 ) { excluded = true ; break ; } } if ( excluded ) continue ; if ( ! name . endsWith ( src . ext ) ) continue ; if ( ! candidate . canRead ( ) ) { DapLog . info ( "FrontPage: file not readable: " + candidate ) ; continue ; } matches . add ( candidate ) ; } if ( matches . size ( ) > 0 ) { // Sort the set of files matches . sort ( new Comparator < File > ( ) { public int compare ( File f1 , File f2 ) { return f1 . getName ( ) . compareTo ( f2 . getName ( ) ) ; } } ) ; if ( DUMPFILELIST ) { for ( File x : matches ) { System . err . printf ( "file: %s/%s%n" , rootinfo . prefix , x . getName ( ) ) ; } } FileSource clone = new FileSource ( src . ext , src . tag ) ; clone . files = matches ; activesources . add ( clone ) ; } } rootinfo . setFiles ( activesources ) ; }


Input: Add a set of MenuItems to the given JMenu one for each possible L&F . if this platform doesnt support the L&F disable the MenuItem . [CODESPLIT] public void addToMenu ( final JMenu menu ) { final UIManager . LookAndFeelInfo [ ] plafInfo = UIManager . getInstalledLookAndFeels ( ) ; for ( UIManager . LookAndFeelInfo aPlafInfo : plafInfo ) { addToMenu ( aPlafInfo . getName ( ) , aPlafInfo . getClassName ( ) , menu ) ; } final LookAndFeel current = UIManager . getLookAndFeel ( ) ; System . out . printf ( "current L&F=%s%n" , current . getName ( ) ) ; }


Input:
/ * C ++ implementation static bool name_is_global ( string &name ) { static Regex global ( \\ ( . * global . * \\ ) \\ | \\ ( . * opendap . * \\ ) 1 ) ; downcase ( name ) ; return global . match ( name . c_str () name . length () ) ! = - 1 ; } [CODESPLIT] public static boolean nameIsGlobal ( String name ) { String lcName = name . toLowerCase ( ) ; boolean global = false ; if ( lcName . indexOf ( "global" ) >= 0 ) global = true ; if ( lcName . indexOf ( "dods" ) >= 0 ) global = true ; //System.out.println("nameIsGlobal(): "+global);
 return ( global ) ; }


Input: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - [CODESPLIT] public static String fancyTypeName ( BaseType bt ) { if ( bt instanceof DByte ) return ( "8 bit Byte" ) ; if ( bt instanceof DUInt16 ) return ( "16 bit Unsigned Integer" ) ; if ( bt instanceof DInt16 ) return ( "16 bit Integer" ) ; if ( bt instanceof DUInt32 ) return ( "32 bit Unsigned Integer" ) ; if ( bt instanceof DInt32 ) return ( "32 bit Integer" ) ; if ( bt instanceof DFloat32 ) return ( "32 bit Real" ) ; if ( bt instanceof DFloat64 ) return ( "64 bit Real" ) ; if ( bt instanceof DURL ) return ( "URL" ) ; if ( bt instanceof DString ) return ( "String" ) ; if ( bt instanceof DArray ) { DArray a = ( DArray ) bt ; StringBuilder type = new StringBuilder ( ) ; type . append ( "Array of " ) ; type . append ( fancyTypeName ( a . getPrimitiveVector ( ) . getTemplate ( ) ) ) ; type . append ( "s " ) ; Enumeration e = a . getDimensions ( ) ; while ( e . hasMoreElements ( ) ) { DArrayDimension dad = ( DArrayDimension ) e . nextElement ( ) ; type . append ( "[" ) ; type . append ( dad . getEncodedName ( ) ) ; type . append ( " = 0.." ) ; type . append ( dad . getSize ( ) - 1 ) ; type . append ( "]" ) ; } type . append ( "\n" ) ; return ( type . toString ( ) ) ; } if ( bt instanceof DStructure ) return ( "Structure" ) ; if ( bt instanceof DSequence ) return ( "Sequence" ) ; if ( bt instanceof DGrid ) return ( "Grid" ) ; return ( "UNKNOWN" ) ; }


Input:
tricky bit of business . recapture the entire record based on drs position . for validation . [CODESPLIT] @ Nullable public static Grib2Record findRecordByDrspos ( RandomAccessFile raf , long drsPos ) throws IOException { long pos = Math . max ( 0 , drsPos - ( 20 * 1000 ) ) ; // go back 20K
 Grib2RecordScanner scan = new Grib2RecordScanner ( raf , pos ) ; while ( scan . hasNext ( ) ) { ucar . nc2 . grib . grib2 . Grib2Record gr = scan . next ( ) ; Grib2SectionDataRepresentation drs = gr . getDataRepresentationSection ( ) ; if ( drsPos == drs . getStartingPosition ( ) ) return gr ; if ( raf . getFilePointer ( ) > drsPos ) break ; // missed it.
 } return null ; }


Input:
side effect is that the new record is in repeatRecord [CODESPLIT] private boolean nextRepeating ( ) throws IOException { raf . seek ( repeatPos ) ; GribNumbers . int4 ( raf ) ; // skip octets 1-4
 int section = raf . read ( ) ; // find out what section this is
 raf . seek ( repeatPos ) ; // back to beginning of section
 if ( section == 2 ) { repeatRecord . setLus ( new Grib2SectionLocalUse ( raf ) ) ; repeatRecord . setGdss ( new Grib2SectionGridDefinition ( raf ) ) ; repeatRecord . setPdss ( new Grib2SectionProductDefinition ( raf ) ) ; repeatRecord . setDrs ( new Grib2SectionDataRepresentation ( raf ) ) ; repeatRecord . setBms ( new Grib2SectionBitMap ( raf ) , false ) ; repeatRecord . setDataSection ( new Grib2SectionData ( raf ) ) ; repeatRecord . repeat = section ; } else if ( section == 3 ) { repeatRecord . setGdss ( new Grib2SectionGridDefinition ( raf ) ) ; repeatRecord . setPdss ( new Grib2SectionProductDefinition ( raf ) ) ; repeatRecord . setDrs ( new Grib2SectionDataRepresentation ( raf ) ) ; repeatRecord . setBms ( new Grib2SectionBitMap ( raf ) , false ) ; repeatRecord . setDataSection ( new Grib2SectionData ( raf ) ) ; repeatRecord . repeat = section ; } else if ( section == 4 ) { repeatRecord . setPdss ( new Grib2SectionProductDefinition ( raf ) ) ; repeatRecord . setDrs ( new Grib2SectionDataRepresentation ( raf ) ) ; repeatRecord . setBms ( new Grib2SectionBitMap ( raf ) , false ) ; repeatRecord . setDataSection ( new Grib2SectionData ( raf ) ) ; repeatRecord . repeat = section ; } else { if ( debugRepeat ) logger . debug ( " REPEAT Terminate %d%n" , section ) ; lastPos = repeatPos ; // start next scan from here
 repeatPos = - 1 ; repeatRecord = null ; repeatBms = null ; return false ; } // look for repeating bms
 Grib2SectionBitMap bms = repeatRecord . getBitmapSection ( ) ; if ( bms . getBitMapIndicator ( ) == 254 ) { // replace BMS with last good one
 if ( repeatBms == null ) throw new IllegalStateException ( "No bms in repeating section" ) ; repeatRecord . setBms ( repeatBms , true ) ; //debug
 if ( debugRepeat ) logger . debug ( "replaced bms %d%n" , section ) ; repeatRecord . repeat += 1000 ; } else if ( bms . getBitMapIndicator ( ) == 0 ) { // track last good bms
 repeatBms = repeatRecord . getBitmapSection ( ) ; } // keep only unique gds
 if ( ( section == 2 ) || ( section == 3 ) ) { // look for duplicate gds
 Grib2SectionGridDefinition gds = repeatRecord . getGDSsection ( ) ; long crc = gds . calcCRC ( ) ; Grib2SectionGridDefinition gdsCached = gdsMap . get ( crc ) ; if ( gdsCached != null ) repeatRecord . setGdss ( gdsCached ) ; else gdsMap . put ( crc , gds ) ; } // check to see if we are at the end
 long pos = raf . getFilePointer ( ) ; long ending = repeatRecord . getIs ( ) . getEndPos ( ) ; if ( pos + 34 < ending ) { // give it 30 bytes of slop
 if ( debugRepeat ) logger . debug ( " REPEAT AGAIN %d != %d%n" , pos + 4 , ending ) ; repeatPos = pos ; return true ; } if ( debug ) logger . debug ( " REPEAT read until %d grib ending at %d header ='%s'%n" , raf . getFilePointer ( ) , ending , StringUtil2 . cleanup ( header ) ) ; // check that end section is correct
 raf . seek ( ending - 4 ) ; for ( int i = 0 ; i < 4 ; i ++ ) { if ( raf . read ( ) != 55 ) { String clean = StringUtil2 . cleanup ( header ) ; if ( clean . length ( ) > 40 ) clean = clean . substring ( 0 , 40 ) + "..." ; logger . warn ( "  REPEAT Missing End of GRIB message at pos=" + ending + " header= " + clean + " for=" + raf . getLocation ( ) ) ; break ; } } lastPos = raf . getFilePointer ( ) ; if ( debugRepeat ) logger . debug ( " REPEAT DONE%n" ) ; repeatPos = - 1 ; // no more repeats in this record
 return true ; }


Input: called if its scalar [CODESPLIT] public boolean read ( String datasetName , Object specialO ) throws NoSuchVariableException , IOException { // read the scalar structure into memory StructureData sdata = ncVar . readStructure ( ) ; setData ( sdata ) ; return ( false ) ; }


Input: LOOK - should modify to use hasNetcdf . setData ( StructureData ) for efficiency [CODESPLIT] public void setData ( StructureData sdata ) { int count = 0 ; StructureMembers sm = sdata . getStructureMembers ( ) ; java . util . Enumeration vars = getVariables ( ) ; while ( vars . hasMoreElements ( ) ) { // loop through both structures HasNetcdfVariable hasNetcdf = ( HasNetcdfVariable ) vars . nextElement ( ) ; StructureMembers . Member m = sm . getMember ( count ++ ) ; // extract the data and set it into the dods object Array data = sdata . getArray ( m ) ; hasNetcdf . setData ( data ) ; } setRead ( true ) ; }


Input: overrride for array of Structures [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { if ( org == null ) { super . serialize ( dataset , sink , ce , specialO ) ; return ; } // use the projection info in the original java . util . Enumeration vars = org . getVariables ( ) ; // run through each structure member StructureMembers sm = sdata . getStructureMembers ( ) ; int count = 0 ; while ( vars . hasMoreElements ( ) ) { HasNetcdfVariable sm_org = ( HasNetcdfVariable ) vars . nextElement ( ) ; boolean isProjected = ( ( ServerMethods ) sm_org ) . isProject ( ) ; if ( isProjected ) { StructureMembers . Member m = sm . getMember ( count ) ; sm_org . serialize ( sink , sdata , m ) ; } count ++ ; } }


Input: Get the unpacked data values for a selected parameter . [CODESPLIT] public float [ ] getParamValues ( DoradeRDAT rdat , float [ ] workingArray ) throws DescriptorException { if ( ! paramName . equals ( rdat . getParamName ( ) ) ) throw new DescriptorException ( "parameter name mismatch" ) ; byte [ ] paramData = rdat . getRawData ( ) ; int nCells = myRADD . getNCells ( ) ; float [ ] values ; if ( workingArray != null && workingArray . length == nCells ) { values = workingArray ; } else { values = new float [ nCells ] ; } short [ ] svalues = null ; if ( myRADD . getCompressionScheme ( ) == DoradeRADD . COMPRESSION_HRD ) { if ( binaryFormat != DoradePARM . FORMAT_16BIT_INT ) { throw new DescriptorException ( "Cannot unpack " + "compressed data with binary format " + binaryFormat ) ; } svalues = uncompressHRD ( paramData , nCells ) ; } for ( int cell = 0 ; cell < nCells ; cell ++ ) { switch ( binaryFormat ) { case DoradePARM . FORMAT_8BIT_INT : byte bval = paramData [ cell ] ; values [ cell ] = ( bval == badDataFlag ) ? BAD_VALUE : ( bval - bias ) / scale ; break ; case DoradePARM . FORMAT_16BIT_INT : short sval = ( svalues != null ) ? svalues [ cell ] : grabShort ( paramData , 2 * cell ) ; values [ cell ] = ( sval == badDataFlag ) ? BAD_VALUE : ( sval - bias ) / scale ; break ; case DoradePARM . FORMAT_32BIT_INT : int ival = grabInt ( paramData , 4 * cell ) ; values [ cell ] = ( ival == badDataFlag ) ? BAD_VALUE : ( ival - bias ) / scale ; break ; case DoradePARM . FORMAT_32BIT_FLOAT : float fval = grabFloat ( paramData , 4 * cell ) ; values [ cell ] = ( fval == badDataFlag ) ? BAD_VALUE : ( fval - bias ) / scale ; break ; case DoradePARM . FORMAT_16BIT_FLOAT : throw new DescriptorException ( "can't unpack 16-bit " + "float data yet" ) ; default : throw new DescriptorException ( "bad binary format (" + binaryFormat + ")" ) ; } } return values ; }


Input: Unpack MIT / HRD - compressed data into an array of exactly nCells shorts . [CODESPLIT] private short [ ] uncompressHRD ( byte [ ] compressedData , int nCells ) throws DescriptorException { short [ ] svalues = new short [ nCells ] ; int cPos = 0 ; // position in the compressed data, in bytes int nextCell = 0 ; int runLength ; for ( ; ; nextCell += runLength ) { // // Each run begins with a 16-bin run descriptor.  The // high order bit is set if the run consists of bad flags. // The remaining 15 bits tell the length of the run. // A run length of 1 indicates the end of compressed data. // short runDescriptor = grabShort ( compressedData , cPos ) ; cPos += 2 ; boolean runHasGoodValues = ( ( runDescriptor & 0x8000 ) != 0 ) ; runLength = runDescriptor & 0x7fff ; if ( runLength == 1 ) break ; // // Sanity check on run length // if ( ( nextCell + runLength ) > nCells ) throw new DescriptorException ( "attempt to unpack " + "too many cells" ) ; // // If the run contains good values, then the next runLength // values in the compressed data stream are real values.  Otherwise // we need to fill with runLength bad value flags. // for ( int cell = nextCell ; cell < nextCell + runLength ; cell ++ ) { if ( runHasGoodValues ) { svalues [ cell ] = grabShort ( compressedData , cPos ) ; cPos += 2 ; } else { svalues [ cell ] = ( short ) badDataFlag ; } } } // // Fill the remainder of the array (if any) with bad value flags // for ( int cell = nextCell ; cell < nCells ; cell ++ ) svalues [ cell ] = ( short ) badDataFlag ; return svalues ; }


Input: map limit circle of this radius from the origin p 173 [CODESPLIT] @ Override public ProjectionImpl constructCopy ( ) { ProjectionImpl result = new VerticalPerspectiveView ( getOriginLat ( ) , getOriginLon ( ) , R , getHeight ( ) , false_east , false_north ) ; result . setDefaultMapArea ( defaultMapArea ) ; result . setName ( name ) ; return result ; }


Input:
Precalculate some stuff [CODESPLIT] private void precalculate ( ) { sinLat0 = Math . sin ( lat0 ) ; cosLat0 = Math . cos ( lat0 ) ; lon0Degrees = Math . toDegrees ( lon0 ) ; P = 1.0 + H / R ; // "map limit" circle of this radius from the origin, p 173
 maxR = .99 * R * Math . sqrt ( ( P - 1 ) / ( P + 1 ) ) ; }


Input: Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double toX , toY ; double fromLat = latLon . getLatitude ( ) ; double fromLon = latLon . getLongitude ( ) ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double cosc = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double ksp = ( P - 1.0 ) / ( P - cosc ) ; if ( cosc < 1.0 / P ) { toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = false_east + R * ksp * Math . cos ( fromLat ) * Math . sin ( lonDiff ) ; toY = false_north + R * ksp * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) ; } result . setLocation ( toX , toY ) ; return result ; }


Input:
Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double toLat , toLon ; double fromX = world . getX ( ) ; double fromY = world . getY ( ) ; fromX = fromX - false_east ; fromY = fromY - false_north ; double rho = Math . sqrt ( fromX * fromX + fromY * fromY ) ; double r = rho / R ; double con = P - 1.0 ; double com = P + 1.0 ; double c = Math . asin ( ( P - Math . sqrt ( 1.0 - ( r * r * com ) / con ) ) / ( con / r + r / con ) ) ; toLon = lon0 ; double temp = 0 ; if ( Math . abs ( rho ) > TOLERANCE ) { toLat = Math . asin ( Math . cos ( c ) * sinLat0 + ( fromY * Math . sin ( c ) * cosLat0 / rho ) ) ; if ( Math . abs ( lat0 - PI_OVER_4 ) > TOLERANCE ) { // not 90 or -90
 temp = rho * cosLat0 * Math . cos ( c ) - fromY * sinLat0 * Math . sin ( c ) ; toLon = lon0 + Math . atan ( fromX * Math . sin ( c ) / temp ) ; } else if ( Double . compare ( lat0 , PI_OVER_4 ) == 0 ) { toLon = lon0 + Math . atan ( fromX / - fromY ) ; temp = - fromY ; } else { toLon = lon0 + Math . atan ( fromX / fromY ) ; temp = fromY ; } } else { toLat = lat0 ; } toLat = Math . toDegrees ( toLat ) ; toLon = Math . toDegrees ( toLon ) ; if ( temp < 0 ) { toLon += 180 ; } toLon = LatLonPointImpl . lonNormal ( toLon ) ; result . setLatitude ( toLat ) ; result . setLongitude ( toLon ) ; return result ; }


Input: Convert lat / lon coordinates to projection coordinates . [CODESPLIT] public float [ ] [ ] latLonToProj ( float [ ] [ ] from , float [ ] [ ] to , int latIndex , int lonIndex ) { int cnt = from [ 0 ] . length ; float [ ] fromLatA = from [ latIndex ] ; float [ ] fromLonA = from [ lonIndex ] ; float [ ] resultXA = to [ INDEX_X ] ; float [ ] resultYA = to [ INDEX_Y ] ; double toX , toY ; for ( int i = 0 ; i < cnt ; i ++ ) { double fromLat = fromLatA [ i ] ; double fromLon = fromLonA [ i ] ; fromLat = Math . toRadians ( fromLat ) ; double lonDiff = Math . toRadians ( LatLonPointImpl . lonNormal ( fromLon - lon0Degrees ) ) ; double cosc = sinLat0 * Math . sin ( fromLat ) + cosLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ; double ksp = ( P - 1.0 ) / ( P - cosc ) ; if ( cosc < 1.0 / P ) { toX = Double . POSITIVE_INFINITY ; toY = Double . POSITIVE_INFINITY ; } else { toX = false_east + R * ksp * Math . cos ( fromLat ) * Math . sin ( lonDiff ) ; toY = false_north + R * ksp * ( cosLat0 * Math . sin ( fromLat ) - sinLat0 * Math . cos ( fromLat ) * Math . cos ( lonDiff ) ) ; } resultXA [ i ] = ( float ) toX ; resultYA [ i ] = ( float ) toY ; } return to ; }


Input:
/ * <GRIB2_22_0_0_Template_en > <No > 1451< / No > <Title_en > Product definition template 4 . 55 - spatio - temporal changing tiles at a horizontal level or horizontal layer at a point in time< / Title_en > <OctetNo > 35< / OctetNo > <Contents_en > Type of second fixed surface< / Contents_en > <Note_en > ( see Code table 4 . 5 ) < / Note_en > <Status > Operational< / Status > < / GRIB2_22_0_0_Template_en > [CODESPLIT] private void readXml ( Version version ) throws IOException { try ( InputStream ios = WmoTemplateTables . class . getResourceAsStream ( version . getResourceName ( ) ) ) { if ( ios == null ) { throw new IOException ( "cant open TemplateTable %s " + version . getResourceName ( ) ) ; } org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( ios ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } Map < String , TemplateTable > map = new HashMap <> ( ) ; String [ ] elems = version . getElemNames ( ) ; assert elems != null ; assert elems . length > 3 ; Element root = doc . getRootElement ( ) ; List < Element > featList = root . getChildren ( elems [ 0 ] ) ; // 0 = main element
 for ( Element elem : featList ) { String desc = elem . getChildTextNormalize ( elems [ 1 ] ) ; // 1 = title
 String octet = elem . getChildTextNormalize ( "OctetNo" ) ; String content = elem . getChildTextNormalize ( elems [ 3 ] ) ; // 3 = content
 String status = elem . getChildTextNormalize ( "Status" ) ; String note = elem . getChildTextNormalize ( elems [ 2 ] ) ; // 2 == note
 TemplateTable template = map . computeIfAbsent ( desc , name -> new TemplateTable ( name ) ) ; template . add ( octet , content , status , note ) ; } ios . close ( ) ; List < TemplateTable > tlist = new ArrayList <> ( map . values ( ) ) ; for ( TemplateTable t : tlist ) { if ( t . m1 == 3 ) { t . add ( 1 , 4 , "GDS length" ) ; t . add ( 5 , 1 , "Section" ) ; t . add ( 6 , 1 , "Source of Grid Definition (see code table 3.0)" ) ; t . add ( 7 , 4 , "Number of data points" ) ; t . add ( 11 , 1 , "Number of octects for optional list of numbers" ) ; t . add ( 12 , 1 , "Interpretation of list of numbers" ) ; t . add ( 13 , 2 , "Grid Definition Template Number" ) ; } else if ( t . m1 == 4 ) { t . add ( 1 , 4 , "PDS length" ) ; t . add ( 5 , 1 , "Section" ) ; t . add ( 6 , 2 , "Number of coordinates values after Template" ) ; t . add ( 8 , 2 , "Product Definition Template Number" ) ; } Collections . sort ( t . flds ) ; } this . templateTables = map . values ( ) . stream ( ) . sorted ( ) . collect ( ImmutableList . toImmutableList ( ) ) ; ImmutableMap . Builder < String , TemplateTable > builder = ImmutableMap . builder ( ) ; map . values ( ) . forEach ( t -> builder . put ( t . getId ( ) , t ) ) ; this . templateMap = builder . build ( ) ; } }


Input:
/ * Find station that contains this point . If it exists make it the selected station . @param pickPt : world coordinates @return station that contains this point or null if none . [CODESPLIT] public void draw ( java . awt . Graphics2D g , java . awt . geom . AffineTransform normal2Device ) { if ( ( project == null ) || ! posWasCalc ) return ; // use world coordinates for position, but draw in screen coordinates
 // so that the symbols stay the same size
 AffineTransform world2Device = g . getTransform ( ) ; g . setTransform ( normal2Device ) ; //  identity transform for screen coords
 // transform World to Normal coords:
 //    world2Normal = pixelAT-1 * world2Device
 // cache for pick closest
 AffineTransform world2Normal ; try { world2Normal = normal2Device . createInverse ( ) ; world2Normal . concatenate ( world2Device ) ; } catch ( java . awt . geom . NoninvertibleTransformException e ) { System . out . println ( " RendSurfObs: NoninvertibleTransformException on " + normal2Device ) ; return ; } // we want aliasing; but save previous state to restore at end
 Object saveHint = g . getRenderingHint ( RenderingHints . KEY_ANTIALIASING ) ; //g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
 //    RenderingHints.VALUE_ANTIALIAS_ON);
 g . setStroke ( new java . awt . BasicStroke ( 1.0f ) ) ; /* set up the grid
    Rectangle2D bbox = (Rectangle2D) g.getClip(); // clipping area in normal coords
    // clear the grid = "no stations are drawn"
    stationGrid.clear();
    // set the grid size based on typical bounding box
    stationGrid.setGrid(bbox, typicalBB.getWidth(), typicalBB.getHeight());

    // always draw selected
    if (selected != null) {
      selected.calcPos( world2Normal);
      stationGrid.markIfClear( selected.getBB(), selected);
      selected.draw(g);
    } */ g . setFont ( textFont . getFont ( ) ) ; g . setColor ( color ) ; int count = 0 ; int npts = obsUIlist . size ( ) ; GeneralPath path = new GeneralPath ( GeneralPath . WIND_EVEN_ODD , npts ) ; for ( int i = 0 ; i < npts ; i ++ ) { ObservationUI s = ( ObservationUI ) obsUIlist . get ( i ) ; s . calcPos ( world2Normal ) ; s . draw ( g ) ; if ( Double . isNaN ( s . screenPos . getX ( ) ) ) { System . out . println ( "screenPos=" + s . screenPos + " world = " + s . worldPos ) ; continue ; } if ( count == 0 ) path . moveTo ( ( float ) s . screenPos . getX ( ) , ( float ) s . screenPos . getY ( ) ) ; else path . lineTo ( ( float ) s . screenPos . getX ( ) , ( float ) s . screenPos . getY ( ) ) ; count ++ ; } g . setColor ( color ) ; if ( drawConnectingLine ) g . draw ( path ) ; // draw selected
 if ( selected != null ) selected . draw ( g ) ; // restore
 g . setTransform ( world2Device ) ; g . setRenderingHint ( RenderingHints . KEY_ANTIALIASING , saveHint ) ; }


Input: Open a FeatureDataset from a URL location string . Example URLS : <ul > <li > http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : http : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : // localhost : 8080 / test / addeStationDataset . xml#surfaceHourly <li > thredds : file : c : / test / data / catalog / addeStationDataset . xml#AddeSurfaceData ( absolute file ) <li > thredds : resolve : resolveURL < / ul > [CODESPLIT] public ThreddsDataFactory . Result openFeatureDataset ( String urlString , ucar . nc2 . util . CancelTask task ) throws IOException { ThreddsDataFactory . Result result = new ThreddsDataFactory . Result ( ) ; InvDataset invDataset = processLocation ( urlString , task , result ) ; if ( result . fatalError ) return result ; return openFeatureDataset ( null , invDataset , task , result ) ; }


Input: Open a FeatureDataset from an InvDataset object deciding on which InvAccess to use . [CODESPLIT] public ThreddsDataFactory . Result openFeatureDataset ( InvDataset invDataset , ucar . nc2 . util . CancelTask task ) throws IOException { return openFeatureDataset ( null , invDataset , task , new Result ( ) ) ; }


Input: Open a FeatureDataset from an InvAccess object . [CODESPLIT] public ThreddsDataFactory . Result openFeatureDataset ( InvAccess access , ucar . nc2 . util . CancelTask task ) throws IOException { InvDataset invDataset = access . getDataset ( ) ; ThreddsDataFactory . Result result = new Result ( ) ; if ( invDataset . getDataType ( ) == null ) { result . errLog . format ( "InvDatasert must specify a FeatureType%n" ) ; result . fatalError = true ; return result ; } return openFeatureDataset ( invDataset . getDataType ( ) , access , task , result ) ; }


Input: Try to open as a NetcdfDataset . [CODESPLIT] public NetcdfDataset openDataset ( InvDataset invDataset , boolean acquire , ucar . nc2 . util . CancelTask task , Formatter log ) throws IOException { Result result = new Result ( ) ; NetcdfDataset ncd = openDataset ( invDataset , acquire , task , result ) ; if ( log != null ) log . format ( "%s" , result . errLog ) ; return ( result . fatalError ) ? null : ncd ; }


Input: Find the best access in case theres more than one based on what the CDM knows how to open and use . [CODESPLIT] public InvAccess chooseDatasetAccess ( List < InvAccess > accessList ) { if ( accessList . size ( ) == 0 ) return null ; InvAccess access = null ; if ( preferAccess != null ) { for ( ServiceType type : preferAccess ) { access = findAccessByServiceType ( accessList , type ) ; if ( access != null ) break ; } } // the order indicates preference if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . CdmRemote ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DODS ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . OPENDAP ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . DAP4 ) ; if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . FILE ) ; // should mean that it can be opened through netcdf API if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . NETCDF ) ; //  ServiceType.NETCDF is deprecated, use FILE // look for HTTP with format we can read if ( access == null ) { InvAccess tryAccess = findAccessByServiceType ( accessList , ServiceType . HTTPServer ) ; if ( tryAccess == null ) tryAccess = findAccessByServiceType ( accessList , ServiceType . HTTP ) ; //  ServiceType.HTTP should be HTTPServer if ( tryAccess != null ) { DataFormatType format = tryAccess . getDataFormatType ( ) ; // these are the file types we can read if ( ( DataFormatType . BUFR == format ) || ( DataFormatType . GINI == format ) || ( DataFormatType . GRIB1 == format ) || ( DataFormatType . GRIB2 == format ) || ( DataFormatType . HDF5 == format ) || ( DataFormatType . NCML == format ) || ( DataFormatType . NETCDF == format ) || ( DataFormatType . NEXRAD2 == format ) || ( DataFormatType . NIDS == format ) ) { access = tryAccess ; } } } // ADDE if ( access == null ) access = findAccessByServiceType ( accessList , ServiceType . ADDE ) ; // RESOLVER if ( access == null ) { access = findAccessByServiceType ( accessList , ServiceType . RESOLVER ) ; } return access ; }


Input:
Add information from the InvDataset to the NetcdfDataset . [CODESPLIT] public static void annotate ( InvDataset ds , NetcdfDataset ncDataset ) { ncDataset . setTitle ( ds . getName ( ) ) ; ncDataset . setId ( ds . getID ( ) ) ; // add properties as global attributes for ( InvProperty p : ds . getProperties ( ) ) { String name = p . getName ( ) ; if ( null == ncDataset . findGlobalAttribute ( name ) ) { ncDataset . addAttribute ( null , new Attribute ( name , p . getValue ( ) ) ) ; } } /* ThreddsMetadata.GeospatialCoverage geoCoverage = ds.getGeospatialCoverage();
   if (geoCoverage != null) {
     if ( null != geoCoverage.getNorthSouthRange()) {
       ncDataset.addAttribute(null, new Attribute("geospatial_lat_min", new Double(geoCoverage.getLatSouth())));
       ncDataset.addAttribute(null, new Attribute("geospatial_lat_max", new Double(geoCoverage.getLatNorth())));
     }
     if ( null != geoCoverage.getEastWestRange()) {
       ncDataset.addAttribute(null, new Attribute("geospatial_lon_min", new Double(geoCoverage.getLonWest())));
       ncDataset.addAttribute(null, new Attribute("geospatial_lon_max", new Double(geoCoverage.getLonEast())));
     }
     if ( null != geoCoverage.getUpDownRange()) {
       ncDataset.addAttribute(null, new Attribute("geospatial_vertical_min", new Double(geoCoverage.getHeightStart())));
       ncDataset.addAttribute(null, new Attribute("geospatial_vertical_max", new Double(geoCoverage.getHeightStart() + geoCoverage.getHeightExtent())));
     }
   }

   DateRange timeCoverage = ds.getTimeCoverage();
   if (timeCoverage != null) {
     ncDataset.addAttribute(null, new Attribute("time_coverage_start", timeCoverage.getStart().toDateTimeStringISO()));
     ncDataset.addAttribute(null, new Attribute("time_coverage_end", timeCoverage.getEnd().toDateTimeStringISO()));
   } */ ncDataset . finish ( ) ; }


Input: look for an access method for an image datatype [CODESPLIT] private InvAccess getImageAccess ( InvDataset invDataset , ucar . nc2 . util . CancelTask task , Result result ) { List < InvAccess > accessList = new ArrayList <> ( invDataset . getAccess ( ) ) ; // a list of all the accesses while ( accessList . size ( ) > 0 ) { InvAccess access = chooseImageAccess ( accessList ) ; if ( access != null ) return access ; // next choice is resolver type. access = invDataset . getAccess ( ServiceType . RESOLVER ) ; // no valid access if ( access == null ) { result . errLog . format ( "No access that could be used for Image Type %s %n" , invDataset ) ; return null ; } // deal with RESOLVER type String datasetLocation = access . getStandardUrlName ( ) ; InvDatasetImpl rds = openResolver ( datasetLocation , task , result ) ; if ( rds == null ) return null ; // use the access list from the resolved dataset accessList = new ArrayList <> ( invDataset . getAccess ( ) ) ; } // loop over accesses return null ; }


Input: works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private InvAccess findAccessByServiceType ( List < InvAccess > accessList , ServiceType type ) { for ( InvAccess a : accessList ) { if ( type . toString ( ) . equalsIgnoreCase ( a . getService ( ) . getServiceType ( ) . toString ( ) ) ) return a ; } return null ; }


Input: works against the accessList instead of the dataset list so we can remove and try again [CODESPLIT] private InvAccess findAccessByDataFormatType ( List < InvAccess > accessList , DataFormatType type ) { for ( InvAccess a : accessList ) { if ( type . toString ( ) . equalsIgnoreCase ( a . getDataFormatType ( ) . toString ( ) ) ) return a ; } return null ; }


Input: first one override [CODESPLIT] public static List < Property > removeDups ( List < Property > org ) { List < Property > result = new ArrayList <> ( org . size ( ) ) ; for ( Property p : org ) if ( ! result . contains ( p ) ) // O(n**2) result . add ( p ) ; return result ; }


Input: only used by PartitionBuilder not PartitionBuilderFromIndex [CODESPLIT] void addPartition ( int partno , int groupno , int varno , int ndups , int nrecords , int nmissing , GribCollectionMutable . VariableIndex vi ) { if ( partList == null ) partList = new ArrayList <> ( nparts ) ; partList . add ( new PartitionForVariable2D ( partno , groupno , varno ) ) ; this . ndups += ndups ; this . nrecords += nrecords ; this . nmissing += nmissing ; }


Input: acquire or construct GribCollection - caller must call gc . close () when done [CODESPLIT] public GribCollectionImmutable getGribCollection ( ) throws IOException { String path = getIndexFilenameInCache ( ) ; if ( path == null ) { if ( Grib . debugIndexOnly ) { // we are running in debug mode where we only have the indices, not the data files // tricky: substitute the current root File orgParentDir = new File ( directory ) ; File currentFile = new File ( PartitionCollectionMutable . this . indexFilename ) ; File currentParent = currentFile . getParentFile ( ) ; File currentParentWithDir = new File ( currentParent , orgParentDir . getName ( ) ) ; File nestedIndex = isPartitionOfPartitions ? new File ( currentParentWithDir , filename ) : new File ( currentParent , filename ) ; // JMJ path = nestedIndex . getPath ( ) ; } else { throw new FileNotFoundException ( "No index filename for partition= " + this . toString ( ) ) ; } } // LOOK not cached return ( GribCollectionImmutable ) PartitionCollectionImmutable . partitionCollectionFactory . open ( new DatasetUrl ( null , path ) , - 1 , null , this ) ; }


Input: the children must already exist [CODESPLIT] @ Nullable public GribCollectionMutable makeGribCollection ( ) { GribCollectionMutable result = GribCdmIndex . openMutableGCFromIndex ( dcm . getIndexFilename ( GribCdmIndex . NCX_SUFFIX ) , config , false , true , logger ) ; if ( result == null ) { logger . error ( "Failed on openMutableGCFromIndex {}" , dcm . getIndexFilename ( GribCdmIndex . NCX_SUFFIX ) ) ; return null ; } lastModified = result . lastModified ; fileSize = result . fileSize ; if ( result . masterRuntime != null ) partitionDate = result . masterRuntime . getFirstDate ( ) ; return result ; }


Input: Factory method that returns a RegExpAndDurationTimeCoverageEnhancer instance that will apply the match pattern to the dataset name . [CODESPLIT] public static RegExpAndDurationTimeCoverageEnhancer getInstanceToMatchOnDatasetName ( String matchPattern , String substitutionPattern , String duration ) { return new RegExpAndDurationTimeCoverageEnhancer ( matchPattern , substitutionPattern , duration , MatchTarget . DATASET_NAME ) ; }


Input: Factory method that returns a RegExpAndDurationTimeCoverageEnhancer instance that will apply the match pattern to the dataset path . [CODESPLIT] public static RegExpAndDurationTimeCoverageEnhancer getInstanceToMatchOnDatasetPath ( String matchPattern , String substitutionPattern , String duration ) { return new RegExpAndDurationTimeCoverageEnhancer ( matchPattern , substitutionPattern , duration , MatchTarget . DATASET_PATH ) ; }


Input: Create an QueryCapability from an XML document at a named URL . check dqc . isValid dqc . getErrorMessages () to see if ok . If Disk caching is set cache the dqc and check IfModifiedSince . [CODESPLIT] public QueryCapability readXML ( String uriString ) throws IOException { // get URI URI uri ; try { uri = new URI ( uriString ) ; } catch ( URISyntaxException e ) { throw new MalformedURLException ( e . getMessage ( ) ) ; } // check if its cached if ( diskCache != null ) { File file = diskCache . getCacheFile ( uriString ) ; if ( file != null ) { HttpURLConnection conn = null ; try { URL url = uri . toURL ( ) ; conn = ( HttpURLConnection ) url . openConnection ( ) ; conn . setRequestMethod ( "GET" ) ; conn . setIfModifiedSince ( file . lastModified ( ) ) ; int code = conn . getResponseCode ( ) ; if ( code == HttpURLConnection . HTTP_OK ) { java . io . InputStream is = conn . getInputStream ( ) ; if ( is != null ) { try ( FileOutputStream fout = new FileOutputStream ( file ) ) { IO . copyB ( is , fout , buffer_size ) ; // cache it } try ( InputStream fin = new BufferedInputStream ( new FileInputStream ( file ) , 50000 ) ) { return readXML ( fin , uri ) ; } } } else { // use file try ( FileInputStream fin = new FileInputStream ( file ) ) { return readXML ( fin , uri ) ; } } } finally { if ( conn != null ) conn . disconnect ( ) ; } } // has file // no file - read and cache IO . readURLtoFileWithExceptions ( uriString , file , buffer_size ) ; try ( InputStream fin = new BufferedInputStream ( new FileInputStream ( file ) , 50000 ) ) { return readXML ( fin , uri ) ; } } // has diskCache // otherwise just open the URL warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; Document doc = null ; try { doc = builder . build ( uriString ) ; } catch ( JDOMException e ) { fatalMessages . append ( e . getMessage ( ) ) ; // makes it invalid } return readXML ( doc , uri ) ; }


Input: Create an QueryCapability from an InputStream . check dqc . isValid dqc . getErrorMessages () to see if ok . [CODESPLIT] public QueryCapability readXML ( InputStream docIs , URI uri ) throws IOException { // get ready for XML parsing warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; Document doc = null ; try { doc = builder . build ( docIs ) ; } catch ( JDOMException e ) { fatalMessages . append ( e . getMessage ( ) ) ; // makes it invalid } return readXML ( doc , uri ) ; }


Input: Create an InvCatalog from an a JDOM document . check dqc . isValid dqc . getErrorMessages () to see if ok . [CODESPLIT] private QueryCapability readXML ( org . jdom2 . Document doc , URI uri ) throws IOException { if ( doc == null ) { // parse failed QueryCapability dqc = new QueryCapability ( ) ; if ( fatalMessages . length ( ) > 0 ) dqc . appendErrorMessage ( fatalMessages . toString ( ) , true ) ; // makes it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( errMessages . toString ( ) , false ) ; // doesnt make it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( warnMessages . toString ( ) , false ) ; // doesnt make it invalid return dqc ; } // decide on converter based on namespace Element root = doc . getRootElement ( ) ; String namespace = root . getNamespaceURI ( ) ; DqcConvertIF fac = namespaceToDqcConverterHash . get ( namespace ) ; if ( fac == null ) { fac = defaultConverter ; // LOOK if ( debugVersion ) System . out . println ( "use default converter " + fac . getClass ( ) . getName ( ) + "; no namespace " + namespace ) ; } else if ( debugVersion ) System . out . println ( "use converter " + fac . getClass ( ) . getName ( ) + " based on namespace " + namespace ) ; // convert to object model QueryCapability dqc = fac . parseXML ( this , doc , uri ) ; if ( fatalMessages . length ( ) > 0 ) dqc . appendErrorMessage ( fatalMessages . toString ( ) , true ) ; // makes it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( errMessages . toString ( ) , false ) ; // doesnt make it invalid if ( errMessages . length ( ) > 0 ) dqc . appendErrorMessage ( warnMessages . toString ( ) , false ) ; // doesnt make it invalid return dqc ; }


Input: Write the catalog as an XML document to a String . [CODESPLIT] public String writeXML ( QueryCapability dqc ) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream ( 10000 ) ; writeXML ( dqc , os ) ; return os . toString ( CDM . utf8Charset . name ( ) ) ; }


Input: Write the catalog as an XML document to the specified stream . [CODESPLIT] public void writeXML ( QueryCapability dqc , OutputStream os ) throws IOException { String ns = versionToNamespaceHash . get ( dqc . getVersion ( ) ) ; DqcConvertIF fac = namespaceToDqcConverterHash . get ( ns ) ; if ( fac == null ) fac = defaultConverter ; fac . writeXML ( dqc , os ) ; }


Input: Write the catalog as an XML document to the specified filename . [CODESPLIT] public boolean writeXML ( QueryCapability dqc , String filename ) { try { BufferedOutputStream os = new BufferedOutputStream ( new FileOutputStream ( filename ) ) ; writeXML ( dqc , os ) ; os . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; return false ; } return true ; }


Input: testing [CODESPLIT] private static void doOne ( DqcFactory fac , String url ) { System . out . println ( "***read " + url ) ; try { QueryCapability dqc = fac . readXML ( url ) ; System . out . println ( " dqc hasFatalError= " + dqc . hasFatalError ( ) ) ; System . out . println ( " dqc messages= \n" + dqc . getErrorMessages ( ) ) ; fac . writeXML ( dqc , System . out ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } }


Input:
Set the projection information for this dimension . The parameters <code > start< / code > <code > stride< / code > and <code > stop< / code > are checked to verify that they make sense relative to each other and to the size of this dimension . If not an Invalid ParameterException is thrown . The general rule is : 0&lt ; = start&lt ; size 0&lt ; stride 0&lt ; = stop&lt ; size start&lt ; = stop . [CODESPLIT] public void setProjection ( int start , int stride , int stop ) throws InvalidDimensionException { if ( projection != null ) { // See if we are changing start/stride/stop
 if ( getSize ( ) != start || getStride ( ) != stride || getStop ( ) != stop ) { Formatter f = new Formatter ( ) ; f . format ( " [%d:%d:%d (%d)] != [%d:%d:%d (%d)]" , start , stride , stop , projection . size , projection . start , projection . stride , projection . stop , projection . size ) ; throw new ConstraintException ( "Implementation limitation: muliple references to same variable in single constraint: " + container . getLongName ( ) + f . toString ( ) ) ; } } String msg = "DArrayDimension.setProjection: Bad Projection Request: " ; // validate the arguments
 if ( start < 0 ) throw new InvalidDimensionException ( msg + "start < 0" ) ; if ( stride <= 0 ) throw new InvalidDimensionException ( msg + "stride <= 0" ) ; if ( stop < 0 ) throw new InvalidDimensionException ( msg + "stop < 0" ) ; if ( start < decl . start ) throw new InvalidDimensionException ( msg + "start (" + start + ") < size (" + decl . size + ") for " + _nameClear ) ; if ( stop >= decl . size ) throw new InvalidDimensionException ( msg + "stop >= size: " + stop + ":" + decl . size ) ; if ( stop < start ) throw new InvalidDimensionException ( msg + "stop < start" ) ; projection = new Slice ( start , stride , stop ) ; }


Input: Returns a clone of this <code > Array< / code > . See DAPNode . cloneDag () [CODESPLIT] public DAPNode cloneDAG ( CloneMap map ) throws CloneNotSupportedException { DArrayDimension d = ( DArrayDimension ) super . cloneDAG ( map ) ; if ( container != null ) d . container = ( DArray ) cloneDAG ( map , container ) ; return d ; }


Input:
Structures must be fixed sized [CODESPLIT] private ucar . ma2 . ArrayStructure readStructureData ( ucar . nc2 . Structure s , Section section ) throws java . io . IOException , InvalidRangeException { H4header . Vinfo vinfo = ( H4header . Vinfo ) s . getSPobject ( ) ; vinfo . setLayoutInfo ( ) ; // make sure needed info is present
 int recsize = vinfo . elemSize ; // create the ArrayStructure
 StructureMembers members = s . makeStructureMembers ( ) ; for ( StructureMembers . Member m : members . getMembers ( ) ) { Variable v2 = s . findVariable ( m . getName ( ) ) ; H4header . Minfo minfo = ( H4header . Minfo ) v2 . getSPobject ( ) ; m . setDataParam ( minfo . offset ) ; } members . setStructureSize ( recsize ) ; ArrayStructureBB structureArray = new ArrayStructureBB ( members , section . getShape ( ) ) ; // LOOK subset
 // loop over records
 byte [ ] result = structureArray . getByteBuffer ( ) . array ( ) ; /*if (vinfo.isChunked) {
      InputStream is = getChunkedInputStream(vinfo);
      PositioningDataInputStream dataSource = new PositioningDataInputStream(is);
      Layout layout = new LayoutRegular(vinfo.start, recsize, s.getShape(), section);
      IospHelper.readData(dataSource, layout, DataType.STRUCTURE, result);  */ if ( ! vinfo . isLinked && ! vinfo . isCompressed ) { Layout layout = new LayoutRegular ( vinfo . start , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( raf , layout , DataType . STRUCTURE , result , - 1 , true ) ; /* option 1
    } else if (vinfo.isLinked && !vinfo.isCompressed) {
      Layout layout = new LayoutSegmented(vinfo.segPos, vinfo.segSize, recsize, s.getShape(), section);
      IospHelper.readData(raf, layout, DataType.STRUCTURE, result, -1);  */ // option 2
 } else if ( vinfo . isLinked && ! vinfo . isCompressed ) { InputStream is = new LinkedInputStream ( vinfo ) ; PositioningDataInputStream dataSource = new PositioningDataInputStream ( is ) ; Layout layout = new LayoutRegular ( 0 , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( dataSource , layout , DataType . STRUCTURE , result ) ; } else if ( ! vinfo . isLinked && vinfo . isCompressed ) { InputStream is = getCompressedInputStream ( vinfo ) ; PositioningDataInputStream dataSource = new PositioningDataInputStream ( is ) ; Layout layout = new LayoutRegular ( 0 , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( dataSource , layout , DataType . STRUCTURE , result ) ; } else if ( vinfo . isLinked && vinfo . isCompressed ) { InputStream is = getLinkedCompressedInputStream ( vinfo ) ; PositioningDataInputStream dataSource = new PositioningDataInputStream ( is ) ; Layout layout = new LayoutRegular ( 0 , recsize , s . getShape ( ) , section ) ; IospHelper . readData ( dataSource , layout , DataType . STRUCTURE , result ) ; } else { throw new IllegalStateException ( ) ; } return structureArray ; }


Input: brings up the indicated picture on the display . [CODESPLIT] public void setPicture ( URL filenameURL , String legendParam , double rotation ) { legend = legendParam ; centerWhenScaled = true ; sclPic . setScaleSize ( getSize ( ) ) ; sclPic . stopLoadingExcept ( filenameURL ) ; sclPic . loadAndScalePictureInThread ( filenameURL , Thread . MAX_PRIORITY , rotation ) ; }


Input: sets the buffered image directly . [CODESPLIT] public void setBufferedImage ( BufferedImage img , String statusMessage ) { legend = statusMessage ; centerWhenScaled = true ; Dimension dim = getSize ( ) ; sclPic . setScaleSize ( dim ) ; SourcePicture source = new SourcePicture ( ) ; source . setSourceBufferedImage ( img , statusMessage ) ; sclPic . setSourcePicture ( source ) ; if ( ! scaleToFit ) sclPic . setScaleFactor ( 1.0 ) ; sclPic . scalePicture ( ) ; repaint ( ) ; }


Input: Multifilies the scale factor so that paint () method scales the image larger . This method calls { [CODESPLIT] public void zoomIn ( ) { double OldScaleFactor = sclPic . getScaleFactor ( ) ; double NewScaleFactor = OldScaleFactor * 1.5 ; // If scaling goes from scale down to scale up, set ScaleFactor to exactly 1 if ( ( OldScaleFactor < 1 ) && ( NewScaleFactor > 1 ) ) NewScaleFactor = 1 ; // Check if the picture would get to large and cause the system to "hang"		 if ( ( sclPic . getOriginalWidth ( ) * sclPic . getScaleFactor ( ) < maximumPictureSize ) && ( sclPic . getOriginalHeight ( ) * sclPic . getScaleFactor ( ) < maximumPictureSize ) ) { sclPic . setScaleFactor ( NewScaleFactor ) ; sclPic . createScaledPictureInThread ( Thread . MAX_PRIORITY ) ; } }


Input: this method sets the desired scaled size of the ScalablePicture to the size of the JPanel and fires off a createScaledPictureInThread request if the ScalablePicture has been loaded or is ready . [CODESPLIT] public void zoomToFit ( ) { //Tools.log("zoomToFit invoked"); sclPic . setScaleSize ( getSize ( ) ) ; // prevent useless rescale events when the picture is not ready if ( sclPic . getStatusCode ( ) == sclPic . LOADED || sclPic . getStatusCode ( ) == sclPic . READY ) { sclPic . createScaledPictureInThread ( Thread . MAX_PRIORITY ) ; } }


Input: Set image to center of panel by putting the coordinates of the middle of the original image into the Center to X and Center to Y varaibles by invoking the setCenterLoaction method . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . [CODESPLIT] public void centerImage ( ) { if ( sclPic . getOriginalImage ( ) != null ) { setCenterLocation ( ( int ) sclPic . getOriginalWidth ( ) / 2 , ( int ) sclPic . getOriginalHeight ( ) / 2 ) ; repaint ( ) ; } }


Input: method that moves the image up by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . <p > <img src = .. / scrollUp . png border = 0 > <p > @see #scrollUp () @see #scrollDown () @see #scrollLeft () @see #scrollRight () [CODESPLIT] public void scrollUp ( ) { // if the bottom edge of the picture is visible, do not scroll if ( ( ( sclPic . getOriginalHeight ( ) - focusPoint . y ) * sclPic . getScaleFactor ( ) ) + getSize ( ) . height / 2 > getSize ( ) . height ) { focusPoint . y = focusPoint . y + ( int ) ( getSize ( ) . height * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( "Scrollup rejected because bottom of picture is already showing." ) ; } }


Input: method that moves the image down by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . <p > <img src = .. / scrollDown . png border = 0 > <p > [CODESPLIT] public void scrollDown ( ) { if ( getSize ( ) . height / 2 - focusPoint . y * sclPic . getScaleFactor ( ) < 0 ) { focusPoint . y = focusPoint . y - ( int ) ( getSize ( ) . height * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( "Scroll down rejected because top edge is aready visible" ) ; } }


Input: method that moves the image left by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . works just liks { [CODESPLIT] public void scrollLeft ( ) { // if the bottom edge of the picture is visible, do not scroll if ( ( ( sclPic . getOriginalWidth ( ) - focusPoint . x ) * sclPic . getScaleFactor ( ) ) + getSize ( ) . width / 2 > getSize ( ) . width ) { focusPoint . x = focusPoint . x + ( int ) ( getSize ( ) . width * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( "Scrollup rejected because right edge of picture is already showing." ) ; } }


Input: method that moves the image right by 10% of the pixels shown on the screen . This method calls <code > repaint () < / code > directly since no time consuming image operations need to take place . works just liks { [CODESPLIT] public void scrollRight ( ) { if ( getSize ( ) . width / 2 - focusPoint . x * sclPic . getScaleFactor ( ) < 0 ) { focusPoint . x = focusPoint . x - ( int ) ( getSize ( ) . width * 0.1 / sclPic . getScaleFactor ( ) ) ; repaint ( ) ; } else { Tools . log ( "Scroll left rejected because left edge is aready visible" ) ; } }


Input: method to set the center of the image to the true coordinates in the picture but doesn t call <code > repaint () < / code > [CODESPLIT] public void setCenterLocation ( int Xparameter , int Yparameter ) { Tools . log ( "setCenterLocation invoked with " + Xparameter + " x " + Yparameter ) ; focusPoint . setLocation ( Xparameter , Yparameter ) ; }


Input:
we are overriding the default paintComponent method grabbing the Graphics handle and doing our own drawing here . Esentially this method draws a large black rectangle . A drawRenderedImage is then painted doing an affine transformation on the scaled image to position it so the the desired point is in the middle of the Graphics object . The picture is not scaled here because this is a slow operation and only needs to be done once while moving the image is something the user is likely to do more often . [CODESPLIT] public void paintComponent ( Graphics g ) { int WindowWidth = getSize ( ) . width ; int WindowHeight = getSize ( ) . height ; Tools . log ( "paintComponent called" ) ; if ( Dragging == false ) { //otherwise it's already a move Cursor setCursor ( new Cursor ( Cursor . WAIT_CURSOR ) ) ; } if ( sclPic . getScaledPicture ( ) != null ) { Graphics2D g2d = ( Graphics2D ) g ; int X_Offset = ( int ) ( ( double ) ( WindowWidth / 2 ) - ( focusPoint . x * sclPic . getScaleFactor ( ) ) ) ; int Y_Offset = ( int ) ( ( double ) ( WindowHeight / 2 ) - ( focusPoint . y * sclPic . getScaleFactor ( ) ) ) ; // clear damaged component area Rectangle clipBounds = g2d . getClipBounds ( ) ; g2d . setColor ( Color . black ) ; // getBackground()); g2d . fillRect ( clipBounds . x , clipBounds . y , clipBounds . width , clipBounds . height ) ; g2d . drawRenderedImage ( sclPic . getScaledPicture ( ) , AffineTransform . getTranslateInstance ( X_Offset , Y_Offset ) ) ; //g2d.drawImage(sclPic.getScaledPicture(), null, 0, 0); if ( showInfo ) { g2d . setColor ( Color . white ) ; g2d . drawString ( legend , infoPoint . x , infoPoint . y ) ; g2d . drawString ( "Size: " + Integer . toString ( sclPic . getOriginalWidth ( ) ) + " x " + Integer . toString ( sclPic . getOriginalHeight ( ) ) + " Offset: " + X_Offset + " x " + Y_Offset + " Mid: " + Integer . toString ( focusPoint . x ) + " x " + Integer . toString ( focusPoint . y ) + " Scale: " + twoDecimalFormatter . format ( sclPic . getScaleFactor ( ) ) , infoPoint . x , infoPoint . y + lineSpacing ) ; /* g2d.drawString("File: " + sclPic.getFilename()
						, infoPoint.x
						, infoPoint.y + (2 * lineSpacing) );
				g2d.drawString("Loaded in: "
						+ twoDecimalFormatter.format( sclPic.getSourcePicture().loadTime / 1000F )
						+ " Seconds"
						, infoPoint.x
						, infoPoint.y + (3 * lineSpacing) );
				g2d.drawString("Free memory: "
						+ Long.toString( Runtime.getRuntime().freeMemory( )/1024/1024, 0 )
						+ " MB"
						, infoPoint.x
						, infoPoint.y + (4 * lineSpacing) ); */ } } else { // paint a black square g . setClip ( 0 , 0 , WindowWidth , WindowHeight ) ; g . setColor ( Color . black ) ; g . fillRect ( 0 , 0 , WindowWidth , WindowHeight ) ; } if ( Dragging == false ) { //otherwise a move Cursor and should remain setCursor ( new Cursor ( Cursor . DEFAULT_CURSOR ) ) ; } }


Input: method that gets invoked from the ScalablePicture object to notify of status changes . The ScalablePicture goes through several statusses : UNINITIALISED GARBAGE_COLLECTION LOADING SCALING READY ERROR . <p > Each status is passed to the listener upon receipt . <p > When the ScalablePicture signals that it is READY the legend of the picture is sent to the listener . The method { [CODESPLIT] public void scalableStatusChange ( int pictureStatusCode , String pictureStatusMessage ) { Tools . log ( "PicturePane.scalableStatusChange: got a status change: " + pictureStatusMessage ) ; if ( pictureStatusCode == ScalablePicture . READY ) { Tools . log ( "PicturePane.scalableStatusChange: a READY status" ) ; pictureStatusMessage = legend ; if ( centerWhenScaled ) { Tools . log ( "PicturePane.scalableStatusChange: centering image" ) ; centerImage ( ) ; } Tools . log ( "PicturePane.scalableStatusChange: forcing Panel repaint" ) ; repaint ( ) ; } Enumeration e = picturePaneListeners . elements ( ) ; while ( e . hasMoreElements ( ) ) { ( ( ScalablePictureListener ) e . nextElement ( ) ) . scalableStatusChange ( pictureStatusCode , pictureStatusMessage ) ; } }


Input:
This subroutine converts the two integers stored in a grid file into three integers containing the date time and forecast time . [CODESPLIT] public static int [ ] TG_FTOI ( int [ ] iftime , int start ) { int [ ] intdtf = new int [ 3 ] ; // If there is no forecast information, the string is stored as
 // date and time.
 if ( iftime [ start ] < 100000000 ) { intdtf [ 0 ] = iftime [ start ] ; intdtf [ 1 ] = iftime [ start + 1 ] ; intdtf [ 2 ] = 0 ; //  Otherwise, decode date/time and forecast info from the
 //  two integers.
 } else { //  The first word contains MMDDYYHHMM.  This must be turned
 //  into YYMMDD and HHMM.
 intdtf [ 0 ] = iftime [ start ] / 10000 ; intdtf [ 1 ] = iftime [ start ] - intdtf [ 0 ] * 10000 ; int mmdd = intdtf [ 0 ] / 100 ; int iyyy = intdtf [ 0 ] - mmdd * 100 ; intdtf [ 0 ] = iyyy * 10000 + mmdd ; //  The forecast time remains the same.
 intdtf [ 2 ] = iftime [ start + 1 ] ; } return intdtf ; }


Input:
This subroutine converts an integer time array containing the date time and forecast time into a GEMPAK grid time . [CODESPLIT] public static String TG_ITOC ( int [ ] intdtf ) { String gdattim = "" ; //Check for the blank time which may be found.
 if ( ( intdtf [ 0 ] == 0 ) && ( intdtf [ 1 ] == 0 ) && ( intdtf [ 2 ] == 0 ) ) { return gdattim ; } //  Put the date and time into the character time.
 gdattim = TI_CDTM ( intdtf [ 0 ] , intdtf [ 1 ] ) ; //  Decode the forecast information if there is any.
 if ( intdtf [ 2 ] != 0 ) { String [ ] timeType = TG_CFTM ( intdtf [ 2 ] ) ; String ftype = timeType [ 0 ] ; String ftime = timeType [ 1 ] ; //      Combine two parts into string.
 gdattim = gdattim . substring ( 0 , 11 ) + ftype + ftime ; } return gdattim ; }


Input:
This subroutine converts an integer grid forecast time into the character forecast type and time . The forecast type is A ( analysis ) F ( forecast ) G ( guess ) or I ( initialize ) . If the forecast time is less than 100 and the minutes are 00 only hh is returned . [CODESPLIT] public static String [ ] TG_CFTM ( int ifcast ) { String ftype = "" ; String ftime = "" ; //Check for negative times.
 if ( ifcast < 0 ) { return new String [ ] { ftype , ftime } ; } // Get the number representing forecast type and convert to a
 // character.
 int iftype = ifcast / 100000 ; if ( iftype == 0 ) { ftype = "A" ; } else if ( iftype == 1 ) { ftype = "F" ; } else if ( iftype == 2 ) { ftype = "G" ; } else if ( iftype == 3 ) { ftype = "I" ; } // Convert the time to a character.  Add 100000 so that leading
 // zeros will be encoded.
 int iftime = ifcast - iftype * 100000 ; int ietime = iftime + 100000 ; String fff = ST_INCH ( ietime ) ; // If the forecast time has minutes, set the character output
 // to all five digits. Otherwise, use only the first three digits,
 // which represent hours.
 if ( ietime % 100 == 0 ) { ftime = fff . substring ( 1 , 4 ) ; } else { ftime = fff . substring ( 1 ) ; } return new String [ ] { ftype , ftime } ; }


Input: This subroutine converts an integer date ( YYMMDD ) and time ( HHMM ) [CODESPLIT] public static String TI_CDTM ( int idate , int itime ) { String dattim ; int [ ] idtarr = new int [ 5 ] ; idtarr [ 0 ] = idate / 10000 ; idtarr [ 1 ] = ( idate - idtarr [ 0 ] * 10000 ) / 100 ; idtarr [ 2 ] = idate % 100 ; idtarr [ 3 ] = itime / 100 ; idtarr [ 4 ] = itime % 100 ; dattim = TI_ITOC ( idtarr ) ; return dattim ; }


Input:
This subroutine converts an integer time array into a standard GEMPAK time . The integers are checked for validity . [CODESPLIT] public static String TI_ITOC ( int [ ] idtarr ) { String dattim ; String date , time ; //   Put array values into variables.
 int iyear = idtarr [ 0 ] ; int imonth = idtarr [ 1 ] ; int iday = idtarr [ 2 ] ; int ihour = idtarr [ 3 ] ; int iminut = idtarr [ 4 ] ; //  Check for leap year.
 //int ndays = TI_DAYM(iyear, imonth);
 iyear = iyear % 100 ; //  Check that each of these values is valid.
 /*  TODO: Check these
            IF  ( iyear .lt. 0 )  iret = -7
            IF  ( ( imonth .lt. 1 ) .or. ( imonth .gt. 12 ) ) iret = -8
            IF  ( ( iday   .lt. 1 ) .or. ( iday   .gt. ndays ) )
         +                                                    iret = -9
            IF  ( ( ihour  .lt. 0 ) .or. ( ihour  .gt. 24 ) ) iret = -10
            IF  ( ( iminut .lt. 0 ) .or. ( iminut .gt. 60 ) ) iret = -11
            IF  ( iret .ne. 0 )  RETURN
        */ //  Get the date and time.
 int idate = iyear * 10000 + imonth * 100 + iday ; int itime = ihour * 100 + iminut ; //  Convert date and time to character strings.
 //  Fill in blanks with zeroes.
 date = StringUtil2 . padZero ( idate , 6 ) ; time = StringUtil2 . padZero ( itime , 4 ) ; dattim = date + "/" + time ; return dattim ; }


Input:
This subroutine returns the number of days in the given month . The year must be a full four - digit year . [CODESPLIT] public static int TI_DAYM ( int iyear , int imon ) { int iday = 0 ; if ( ( imon > 0 ) && ( imon < 13 ) ) { //  Pick the number of days for the given month.
 iday = month [ imon - 1 ] ; if ( ( imon == 2 ) && LEAP ( iyear ) ) { iday = iday + 1 ; } } return iday ; }


Input: Convert the int bits to a string [CODESPLIT] public static String ST_ITOC ( int value ) { byte [ ] bval = new byte [ 4 ] ; bval [ 0 ] = ( byte ) ( ( value & 0xff000000 ) >>> 24 ) ; bval [ 1 ] = ( byte ) ( ( value & 0x00ff0000 ) >>> 16 ) ; bval [ 2 ] = ( byte ) ( ( value & 0x0000ff00 ) >>> 8 ) ; bval [ 3 ] = ( byte ) ( ( value & 0x000000ff ) ) ; return new String ( bval , CDM . utf8Charset ) ; }


Input: Convert the int bits to a string [CODESPLIT] public static String ST_ITOC ( int [ ] values ) { StringBuilder sb = new StringBuilder ( ) ; for ( int value : values ) { sb . append ( ST_ITOC ( value ) ) ; } return sb . toString ( ) ; }


Input:
This subroutine translates a numeric value for IVCORD into its character value in VCOORD . [CODESPLIT] public static String LV_CCRD ( int ivcord ) { //Translate known vertical coordinates or look for parameter name.
 String vcoord = "" ; //Check for numeric vertical coordinates.
 if ( ( ivcord >= 0 ) && ( ivcord < vertCoords . length ) ) { vcoord = vertCoords [ ivcord ] ; } else if ( ivcord > 100 ) { //     Check for character name as vertical coordinate.  Check that
 //     each character is an alphanumeric character.
 vcoord = ST_ITOC ( ivcord ) ; /*
              Check for bad values

                DO  i = 1, 4
                    v = vcoord (i:i)
                    IF  ( ( ( v .lt. 'A' ) .or. ( v .gt. 'Z' ) ) .and.
     +                    ( ( v .lt. '0' ) .or. ( v .gt. '9' ) ) )  THEN
                        ier = -1
                    END IF
                END DO
            END IF
            */ } return vcoord ; }


Input: Swap the order of the integers in place . [CODESPLIT] public static int [ ] swp4 ( int [ ] values , int startIndex , int number ) { for ( int i = startIndex ; i < startIndex + number ; i ++ ) { values [ i ] = Integer . reverseBytes ( values [ i ] ) ; } return values ; }


Input: Get a name for the grid packing type [CODESPLIT] public static String getGridPackingName ( int pktyp ) { String packingType = "UNKNOWN" ; switch ( pktyp ) { case GempakConstants . MDGNON : packingType = "MDGNON" ; break ; case GempakConstants . MDGGRB : packingType = "MDGGRB" ; break ; case GempakConstants . MDGNMC : packingType = "MDGNMC" ; break ; case GempakConstants . MDGDIF : packingType = "MDGDIF" ; break ; case GempakConstants . MDGDEC : packingType = "MDGDEC" ; break ; case GempakConstants . MDGRB2 : packingType = "MDGRB2" ; break ; default : break ; } return packingType ; }


Input: Get a name for the data packing type [CODESPLIT] public static String getDataType ( int typrt ) { String dataType = "" + typrt ; switch ( typrt ) { case GempakConstants . MDREAL : dataType = "MDREAL" ; break ; case GempakConstants . MDINTG : dataType = "MDINTG" ; break ; case GempakConstants . MDCHAR : dataType = "MDCHAR" ; break ; case GempakConstants . MDRPCK : dataType = "MDRPCK" ; break ; case GempakConstants . MDGRID : dataType = "MDGRID" ; break ; default : break ; } return dataType ; }


Input:
Read the data stream from the given InputStream . In the C ++ version this code was in Connect . [CODESPLIT] public void readData ( InputStream is , StatusUI statusUI ) throws IOException , EOFException , DAP2Exception { /* ByteArrayOutputStream bout = new ByteArrayOutputStream(50 * 1000);
      copy(is, bout);
      LogStream.dbg.printf(" readData size=%d %n",bout.size());
      LogStream.dbg.logflush();
      ByteArrayInputStream bufferedIS = new ByteArrayInputStream( bout.toByteArray());  */ //statusUI = new Counter();
 // Buffer the input stream for better performance
 BufferedInputStream bufferedIS = new BufferedInputStream ( is ) ; // Use a DataInputStream for deserialize
 DataInputStream dataIS = new DataInputStream ( bufferedIS ) ; for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { if ( statusUI != null && statusUI . userCancelled ( ) ) throw new DataReadException ( "User cancelled" ) ; ClientIO bt = ( ClientIO ) e . nextElement ( ) ; /* if (true) {
            BaseType btt = (BaseType) bt;
            System.out.printf("Deserializing: %s (%s) %n", btt.getEncodedName(), ((BaseType) bt).getTypeName());
          } */ bt . deserialize ( dataIS , ver , statusUI ) ; } //LogStream.out.printf("Deserializing: total size = %s %n", counter);
 // notify GUI of finished download
 if ( statusUI != null ) statusUI . finished ( ) ; }


Input: debug [CODESPLIT] private long copy ( InputStream in , OutputStream out ) throws IOException { long totalBytesRead = 0 ; byte [ ] buffer = new byte [ 8000 ] ; while ( true ) { int bytesRead = in . read ( buffer ) ; if ( bytesRead == - 1 ) break ; out . write ( buffer , 0 , bytesRead ) ; totalBytesRead += bytesRead ; } return totalBytesRead ; }


Input: Print the dataset just read . In the C ++ version this code was in <code > geturl< / code > . [CODESPLIT] public void printVal ( PrintWriter pw ) { for ( Enumeration e = getVariables ( ) ; e . hasMoreElements ( ) ; ) { BaseType bt = ( BaseType ) e . nextElement ( ) ; bt . printVal ( pw , "" , true ) ; pw . flush ( ) ; } pw . println ( ) ; }