Input: Calculate an affine transform based on the display size parameters - used for printing . @param rotate should the page be rotated? @param displayX upper right corner of display area @param displayY upper right corner of display area @param displayWidth display area @param displayHeight display area [CODESPLIT] public AffineTransform calcTransform ( boolean rotate , double displayX , double displayY , double displayWidth , double displayHeight ) { getMapArea ( bb ) ; // current world bounding box // scale to limiting dimension double pxpsx , pypsy ; if ( rotate ) { pxpsx = displayHeight / bb . getWidth ( ) ; pypsy = displayWidth / bb . getHeight ( ) ; } else { pxpsx = displayWidth / bb . getWidth ( ) ; pypsy = displayHeight / bb . getHeight ( ) ; } double pps = Math . min ( pxpsx , pypsy ) ; // calc offset: based on center point staying in center double wx0 = bb . getX ( ) + bb . getWidth ( ) / 2 ; // world midpoint double wy0 = bb . getY ( ) + bb . getHeight ( ) / 2 ; double x0 = displayX + displayWidth / 2 - pps * wx0 ; double y0 = displayY + displayHeight / 2 + pps * wy0 ; AffineTransform cat = new AffineTransform ( pps , 0.0 , 0.0 , - pps , x0 , y0 ) ; // rotate if we need to if ( rotate ) cat . rotate ( Math . PI / 2 , wx0 , wy0 ) ; if ( debug ) { System . out . println ( "Navigation calcTransform = " + displayX + " " + displayY + " " + displayWidth + " " + displayHeight ) ; System . out . println ( "  world = " + bb ) ; System . out . println ( "  scale/origin = " + pps + " " + x0 + " " + y0 ) ; System . out . println ( "  transform = " + cat ) ; } return cat ; }


Input: Get current MapArea . [CODESPLIT] public ProjectionRect getMapArea ( ProjectionRect rect ) { if ( rect == null ) rect = new ProjectionRect ( ) ; double width = pwidth / pix_per_world ; double height = pheight / pix_per_world ; // center point double wx0 = ( pwidth / 2 - pix_x0 ) / pix_per_world ; double wy0 = ( pix_y0 - pheight / 2 ) / pix_per_world ; rect . setRect ( wx0 - width / 2 , wy0 - height / 2 , // minx, miny width , height ) ; // width, height return rect ; }


Input: convert a world coordinate to a display point [CODESPLIT] public Point2D worldToScreen ( ProjectionPointImpl w , Point2D p ) { p . setLocation ( pix_per_world * w . getX ( ) + pix_x0 , - pix_per_world * w . getY ( ) + pix_y0 ) ; return p ; }


Input: convert screen Rectangle to a projection ( world ) rectangle [CODESPLIT] public ProjectionRect screenToWorld ( Point2D start , Point2D end ) { ProjectionPointImpl p1 = new ProjectionPointImpl ( ) ; ProjectionPointImpl p2 = new ProjectionPointImpl ( ) ; screenToWorld ( start , p1 ) ; screenToWorld ( end , p2 ) ; return new ProjectionRect ( p1 . getX ( ) , p1 . getY ( ) , p2 . getX ( ) , p2 . getY ( ) ) ; }


Input: convert a projection ( world ) rectangle to a screen Rectangle [CODESPLIT] public java . awt . Rectangle worldToScreen ( ProjectionRect projRect ) { Point2D p1 = new Point2D . Double ( ) ; Point2D p2 = new Point2D . Double ( ) ; worldToScreen ( ( ProjectionPointImpl ) projRect . getMaxPoint ( ) , p1 ) ; worldToScreen ( ( ProjectionPointImpl ) projRect . getMinPoint ( ) , p2 ) ; return new java . awt . Rectangle ( ( int ) p1 . getX ( ) , ( int ) p1 . getY ( ) , ( int ) p2 . getX ( ) , ( int ) p2 . getY ( ) ) ; }


Input: call this to change the center of the screen s world coordinates . deltax deltay in display coordinates [CODESPLIT] public void pan ( double deltax , double deltay ) { zoom . push ( ) ; pix_x0 -= deltax ; pix_y0 -= deltay ; fireMapAreaEvent ( ) ; }


Input: call this to zoom into a subset of the screen . startx starty are the upper left corner of the box in display coords width height the size of the box in display coords [CODESPLIT] public void zoom ( double startx , double starty , double width , double height ) { if ( debugZoom ) System . out . println ( "zoom " + startx + " " + starty + " " + width + " " + height + " " ) ; if ( ( width < 5 ) || ( height < 5 ) ) return ; zoom . push ( ) ; pix_x0 -= startx + width / 2 - pwidth / 2 ; pix_y0 -= starty + height / 2 - pheight / 2 ; zoom ( pwidth / width ) ; }


Input: adjust bounding box to fit inside the screen size [CODESPLIT] private void recalcFromBoundingBox ( ) { if ( debugRecalc ) { System . out . println ( "Navigation recalcFromBoundingBox= " + bb ) ; System . out . println ( "  " + pwidth + " " + pheight ) ; } // decide which dimension is limiting double pixx_per_wx = ( bb . getWidth ( ) == 0.0 ) ? 1 : pwidth / bb . getWidth ( ) ; double pixy_per_wy = ( bb . getHeight ( ) == 0.0 ) ? 1 : pheight / bb . getHeight ( ) ; pix_per_world = Math . min ( pixx_per_wx , pixy_per_wy ) ; // calc the center point double wx0 = bb . getX ( ) + bb . getWidth ( ) / 2 ; double wy0 = bb . getY ( ) + bb . getHeight ( ) / 2 ; // calc offset based on center point pix_x0 = pwidth / 2 - pix_per_world * wx0 ; pix_y0 = pheight / 2 + pix_per_world * wy0 ; if ( debugRecalc ) { System . out . println ( "Navigation recalcFromBoundingBox done= " + pix_per_world + " " + pix_x0 + " " + pix_y0 ) ; System . out . println ( "  " + pwidth + " " + pheight + " " + bb ) ; } }


Input: Add a listener . [CODESPLIT] public synchronized void addListener ( Object l ) { if ( ! listeners . contains ( l ) ) { listeners . add ( l ) ; hasListeners = true ; } else logger . warn ( "ListenerManager.addListener already has Listener " + l ) ; }


Input: Remove a listener . [CODESPLIT] public synchronized void removeListener ( Object l ) { if ( listeners . contains ( l ) ) { listeners . remove ( l ) ; hasListeners = ( listeners . size ( ) > 0 ) ; } else logger . warn ( "ListenerManager.removeListener couldnt find Listener " + l ) ; }


Input: Send an event to all registered listeners . If an exception is thrown remove the Listener from the list [CODESPLIT] public synchronized void sendEvent ( java . util . EventObject event ) { if ( ! hasListeners || ! enabled ) return ; Object [ ] args = new Object [ 1 ] ; args [ 0 ] = event ; // send event to all listeners ListIterator iter = listeners . listIterator ( ) ; while ( iter . hasNext ( ) ) { Object client = iter . next ( ) ; try { method . invoke ( client , args ) ; } catch ( IllegalAccessException e ) { logger . error ( "ListenerManager IllegalAccessException" , e ) ; iter . remove ( ) ; } catch ( IllegalArgumentException e ) { logger . error ( "ListenerManager IllegalArgumentException" , e ) ; iter . remove ( ) ; } catch ( InvocationTargetException e ) { // logger.error("ListenerManager InvocationTargetException on " + method+ " threw exception " + e.getTargetException(), e); throw new RuntimeException ( e . getCause ( ) ) ; // pass exception to the caller of sendEvent() } } }


Input: Send an event to all registered listeners except the named one . [CODESPLIT] public synchronized void sendEventExcludeSource ( java . util . EventObject event ) { if ( ! hasListeners || ! enabled ) return ; Object source = event . getSource ( ) ; Object [ ] args = new Object [ 1 ] ; args [ 0 ] = event ; // send event to all listeners except the source ListIterator iter = listeners . listIterator ( ) ; while ( iter . hasNext ( ) ) { Object client = iter . next ( ) ; if ( client == source ) continue ; try { method . invoke ( client , args ) ; } catch ( IllegalAccessException | InvocationTargetException | IllegalArgumentException e ) { e . printStackTrace ( ) ; if ( e . getCause ( ) != null ) e . getCause ( ) . printStackTrace ( ) ; // iter.remove(); logger . error ( "ListenerManager calling " + method + " threw exception " , e ) ; } } }


Input: ncdump that parses a command string . [CODESPLIT] public static boolean print ( String command , Writer out , ucar . nc2 . util . CancelTask ct ) throws IOException { // pull out the filename from the command String filename ; StringTokenizer stoke = new StringTokenizer ( command ) ; if ( stoke . hasMoreTokens ( ) ) filename = stoke . nextToken ( ) ; else { out . write ( usage ) ; return false ; } try ( NetcdfFile nc = NetcdfDataset . openFile ( filename , ct ) ) { // the rest of the command int pos = command . indexOf ( filename ) ; command = command . substring ( pos + filename . length ( ) ) ; return print ( nc , command , out , ct ) ; } catch ( java . io . FileNotFoundException e ) { out . write ( "file not found= " ) ; out . write ( filename ) ; return false ; } finally { out . close ( ) ; } }


Input: ncdump parsing command string file already open . [CODESPLIT] public static boolean print ( NetcdfFile nc , String command , Writer out , ucar . nc2 . util . CancelTask ct ) throws IOException { WantValues showValues = WantValues . none ; boolean ncml = false ; boolean strict = false ; String varNames = null ; String trueDataset = null ; String fakeDataset = null ; if ( command != null ) { StringTokenizer stoke = new StringTokenizer ( command ) ; while ( stoke . hasMoreTokens ( ) ) { String toke = stoke . nextToken ( ) ; if ( toke . equalsIgnoreCase ( "-help" ) ) { out . write ( usage ) ; out . write ( ' ' ) ; return true ; } if ( toke . equalsIgnoreCase ( "-vall" ) ) showValues = WantValues . all ; if ( toke . equalsIgnoreCase ( "-c" ) && ( showValues == WantValues . none ) ) showValues = WantValues . coordsOnly ; if ( toke . equalsIgnoreCase ( "-ncml" ) ) ncml = true ; if ( toke . equalsIgnoreCase ( "-cdl" ) || toke . equalsIgnoreCase ( "-strict" ) ) strict = true ; if ( toke . equalsIgnoreCase ( "-v" ) && stoke . hasMoreTokens ( ) ) varNames = stoke . nextToken ( ) ; if ( toke . equalsIgnoreCase ( "-datasetname" ) && stoke . hasMoreTokens ( ) ) { fakeDataset = stoke . nextToken ( ) ; if ( fakeDataset . length ( ) == 0 ) fakeDataset = null ; if ( fakeDataset != null ) { trueDataset = nc . getLocation ( ) ; nc . setLocation ( fakeDataset ) ; } } } } boolean ok = print ( nc , out , showValues , ncml , strict , varNames , ct ) ; if ( trueDataset != null && fakeDataset != null ) nc . setLocation ( trueDataset ) ; return ok ; }


Input: ncdump - like print of netcdf file . [CODESPLIT] public static boolean print ( String filename , Writer out , boolean showAll , boolean showCoords , boolean ncml , boolean strict , String varNames , ucar . nc2 . util . CancelTask ct ) throws IOException { try ( NetcdfFile nc = NetcdfDataset . openFile ( filename , ct ) ) { return print ( nc , out , showAll , showCoords , ncml , strict , varNames , ct ) ; } catch ( java . io . FileNotFoundException e ) { out . write ( "file not found= " ) ; out . write ( filename ) ; out . flush ( ) ; return false ; } }


Input: ncdump - like print of netcdf file . [CODESPLIT] public static boolean print ( NetcdfFile nc , Writer out , boolean showAll , boolean showCoords , boolean ncml , boolean strict , String varNames , ucar . nc2 . util . CancelTask ct ) throws IOException { WantValues showValues = WantValues . none ; if ( showAll ) showValues = WantValues . all ; else if ( showCoords ) showValues = WantValues . coordsOnly ; return print ( nc , out , showValues , ncml , strict , varNames , ct ) ; }


Input: ncdump - like print of netcdf file . [CODESPLIT] public static boolean print ( NetcdfFile nc , Writer out , WantValues showValues , boolean ncml , boolean strict , String varNames , ucar . nc2 . util . CancelTask ct ) throws IOException { boolean headerOnly = ( showValues == WantValues . none ) && ( varNames == null ) ; try { if ( ncml ) writeNcML ( nc , out , showValues , null ) ; // output schema in NcML else if ( headerOnly ) nc . writeCDL ( new PrintWriter ( out ) , strict ) ; // output schema in CDL form (like ncdump) else { PrintWriter ps = new PrintWriter ( out ) ; nc . toStringStart ( ps , strict ) ; Indent indent = new Indent ( 2 ) ; indent . incr ( ) ; ps . printf ( "%n%sdata:%n" , indent ) ; indent . incr ( ) ; if ( showValues == WantValues . all ) { // dump all data for ( Variable v : nc . getVariables ( ) ) { printArray ( v . read ( ) , v . getFullName ( ) , ps , indent , ct ) ; if ( ct != null && ct . isCancel ( ) ) return false ; } } else if ( showValues == WantValues . coordsOnly ) { // dump coordVars for ( Variable v : nc . getVariables ( ) ) { if ( v . isCoordinateVariable ( ) ) printArray ( v . read ( ) , v . getFullName ( ) , ps , indent , ct ) ; if ( ct != null && ct . isCancel ( ) ) return false ; } } if ( ( showValues != WantValues . all ) && ( varNames != null ) ) { // dump the list of variables StringTokenizer stoke = new StringTokenizer ( varNames , ";" ) ; while ( stoke . hasMoreTokens ( ) ) { String varSubset = stoke . nextToken ( ) ; // variable name and optionally a subset if ( varSubset . indexOf ( ' ' ) >= 0 ) { // has a selector Array data = nc . readSection ( varSubset ) ; printArray ( data , varSubset , ps , indent , ct ) ; } else { // do entire variable Variable v = nc . findVariable ( varSubset ) ; if ( v == null ) { ps . print ( " cant find variable: " + varSubset + "\n   " + usage ) ; continue ; } // dont print coord vars if they are already printed if ( ( showValues != WantValues . coordsOnly ) || v . isCoordinateVariable ( ) ) printArray ( v . read ( ) , v . getFullName ( ) , ps , indent , ct ) ; } if ( ct != null && ct . isCancel ( ) ) return false ; } } indent . decr ( ) ; indent . decr ( ) ; nc . toStringEnd ( ps ) ; } } catch ( Exception e ) { e . printStackTrace ( ) ; out . write ( e . getMessage ( ) ) ; out . flush ( ) ; return false ; } out . flush ( ) ; return true ; }


Input:
Print all the data of the given Variable . [CODESPLIT] static public String printVariableData ( VariableIF v , ucar . nc2 . util . CancelTask ct ) throws IOException { Array data = v . read ( ) ; /* try {
      data = v.isMemberOfStructure() ? v.readAllStructures(null, true) : v.read();
    }
    catch (InvalidRangeException ex) {
      return ex.getMessage();
    } */ StringWriter writer = new StringWriter ( 10000 ) ; printArray ( data , v . getFullName ( ) , new PrintWriter ( writer ) , new Indent ( 2 ) , ct ) ; return writer . toString ( ) ; }


Input: Print a section of the data of the given Variable . [CODESPLIT] static public String printVariableDataSection ( Variable v , String sectionSpec , ucar . nc2 . util . CancelTask ct ) throws IOException , InvalidRangeException { Array data = v . read ( sectionSpec ) ; StringWriter writer = new StringWriter ( 20000 ) ; printArray ( data , v . getFullName ( ) , new PrintWriter ( writer ) , new Indent ( 2 ) , ct ) ; return writer . toString ( ) ; }


Input: Print contents of a StructureData . [CODESPLIT] static public void printStructureData ( PrintWriter out , StructureData sdata ) throws IOException { printStructureData ( out , sdata , new Indent ( 2 ) , null ) ; out . flush ( ) ; }


Input: Print array as undifferentiated sequence of values . [CODESPLIT] static public void printArrayPlain ( Array ma , PrintWriter out ) { ma . resetLocalIterator ( ) ; while ( ma . hasNext ( ) ) { out . print ( ma . next ( ) ) ; out . print ( ' ' ) ; } }


Input: Print array to PrintWriter [CODESPLIT] static public void printArray ( Array array , PrintWriter pw ) { printArray ( array , null , null , pw , new Indent ( 2 ) , null , true ) ; }


Input: Write the NcML representation for a file . Note that ucar . nc2 . dataset . NcMLWriter has a JDOM implementation for complete NcML . This method implements only the core NcML for plain ole netcdf files . [CODESPLIT] static public void writeNcML ( NetcdfFile ncfile , Writer writer , WantValues showValues , String url ) throws IOException { Preconditions . checkNotNull ( ncfile ) ; Preconditions . checkNotNull ( writer ) ; Preconditions . checkNotNull ( showValues ) ; Predicate < Variable > writeVarsPred ; switch ( showValues ) { case none : writeVarsPred = NcMLWriter . writeNoVariablesPredicate ; break ; case coordsOnly : writeVarsPred = NcMLWriter . writeCoordinateVariablesPredicate ; break ; case all : writeVarsPred = NcMLWriter . writeAllVariablesPredicate ; break ; default : String message = String . format ( "CAN'T HAPPEN: showValues (%s) != null and checked all possible enum values." , showValues ) ; throw new AssertionError ( message ) ; } NcMLWriter ncmlWriter = new NcMLWriter ( ) ; ncmlWriter . setWriteVariablesPredicate ( writeVarsPred ) ; Element netcdfElement = ncmlWriter . makeNetcdfElement ( ncfile , url ) ; ncmlWriter . writeToWriter ( netcdfElement , writer ) ; }


Input: Main program . <p > <strong > ucar . nc2 . NCdumpW filename [ - cdl | - ncml ] [ - c | - vall ] [ - v varName1 ; varName2 ; .. ] [ - v varName ( 0 : 1 : 12 ) ] < / strong > <p > where : <ul > <li > filename : path of any CDM readable file <li > cdl or ncml : output format is CDL or NcML <li > - vall : dump all variable data <li > - c : dump coordinate variable data <li > - v varName1 ; varName2 ; : dump specified variable ( s ) <li > - v varName ( 0 : 1 : 12 ) : dump specified variable section < / ul > Default is to dump the header info only . [CODESPLIT] public static void main ( String [ ] args ) { if ( args . length == 0 ) { System . out . println ( usage ) ; return ; } StringBuilder sbuff = new StringBuilder ( ) ; for ( String arg : args ) { sbuff . append ( arg ) ; sbuff . append ( " " ) ; } try { Writer writer = new BufferedWriter ( new OutputStreamWriter ( System . out , CDM . utf8Charset ) ) ; NCdumpW . print ( sbuff . toString ( ) , writer , null ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } }


Input: / * from CF : false_easting ( false_northing ) : The value added to all abscissa ( ordinate ) values in the rectangular coordinates for a map projection . This value frequently is assigned to eliminate negative numbers . Expressed in the unit of the coordinate variable identified by the standard name projection_x_coordinate ( projection_y_coordinate ) . [CODESPLIT] static public double getFalseEastingScaleFactor ( NetcdfDataset ds , AttributeContainer ctv ) { String units = getGeoCoordinateUnits ( ds , ctv ) ; return getFalseEastingScaleFactor ( units ) ; }


Input: Read a variable attribute as a double . [CODESPLIT] protected double readAttributeDouble ( AttributeContainer v , String attname , double defValue ) { Attribute att = v . findAttributeIgnoreCase ( attname ) ; if ( att == null ) return defValue ; if ( att . isString ( ) ) return Double . parseDouble ( att . getStringValue ( ) ) ; else return att . getNumericValue ( ) . doubleValue ( ) ; }


Input: Read an attribute as double [ 2 ] . If only one value make second same as first . [CODESPLIT] protected double [ ] readAttributeDouble2 ( Attribute att ) { if ( att == null ) return null ; double [ ] val = new double [ 2 ] ; if ( att . isString ( ) ) { StringTokenizer stoke = new StringTokenizer ( att . getStringValue ( ) ) ; val [ 0 ] = Double . parseDouble ( stoke . nextToken ( ) ) ; val [ 1 ] = stoke . hasMoreTokens ( ) ? Double . parseDouble ( stoke . nextToken ( ) ) : val [ 0 ] ; } else { val [ 0 ] = att . getNumericValue ( ) . doubleValue ( ) ; val [ 1 ] = ( att . getLength ( ) > 1 ) ? att . getNumericValue ( 1 ) . doubleValue ( ) : val [ 0 ] ; } return val ; }


Input: Add a Parameter to a CoordinateTransform . Make sure that the variable exists . If readData is true read the data and use it as the value of the parameter otherwise use the variable name as the value of the parameter . [CODESPLIT] protected boolean addParameter ( CoordinateTransform rs , String paramName , NetcdfFile ds , String varNameEscaped ) { if ( null == ( ds . findVariable ( varNameEscaped ) ) ) { if ( null != errBuffer ) errBuffer . format ( "CoordTransBuilder %s: no Variable named %s%n" , getTransformName ( ) , varNameEscaped ) ; return false ; } rs . addParameter ( new Parameter ( paramName , varNameEscaped ) ) ; return true ; }


Input: Get the earth radius in km from the attribute earth_radius . Normally this is in meters convert to km if its > 10 000 . Use Earth . getRadius () as default . [CODESPLIT] protected double getEarthRadiusInKm ( AttributeContainer ctv ) { double earth_radius = readAttributeDouble ( ctv , CF . EARTH_RADIUS , Earth . getRadius ( ) ) ; if ( earth_radius > 10000.0 ) earth_radius *= .001 ; return earth_radius ; }


Input: try problem logs [CODESPLIT] public static void main ( String [ ] args ) throws IOException { AccessLogParser p = new AccessLogParser ( ) ; String line = "24.18.236.132 - - [04/Feb/2011:17:49:03 -0700] \"GET /thredds/fileServer//nexrad/level3/N0R/YUX/20110205/Level3_YUX_N0R_20110205_0011.nids \" 200 10409 \"-\" \"-\" 17" ; Matcher m = regPattern . matcher ( line ) ; System . out . printf ( "%s %s%n" , m . matches ( ) , m ) ; for ( int i = 0 ; i < m . groupCount ( ) ; i ++ ) { System . out . println ( " " + i + " " + m . group ( i ) ) ; } LogReader . Log log = p . parseLog ( line ) ; System . out . printf ( "%s%n" , log ) ; }


Input: * Finish constructing after all elements have been added . [CODESPLIT] public boolean finish ( ) { if ( serviceName != null ) { this . service = dataset . findService ( serviceName ) ; if ( this . service == null ) log . append ( "**InvAccess in (" ) . append ( dataset . getFullName ( ) ) . append ( "): has unknown service named (" ) . append ( serviceName ) . append ( ")\n" ) ; } // check urlPath is ok try { new java . net . URI ( urlPath ) ; } catch ( java . net . URISyntaxException e ) { log . append ( "**InvAccess in (" ) . append ( dataset . getFullName ( ) ) . append ( "):\n" + "   urlPath= " ) . append ( urlPath ) . append ( ")\n  URISyntaxException=" ) . append ( e . getMessage ( ) ) ; } return true ; }


Input: //////////////////////////////////////////////////////////////////////////// [CODESPLIT] boolean check ( StringBuilder out , boolean show ) { boolean isValid = true ; if ( log . length ( ) > 0 ) { isValid = false ; out . append ( log ) ; } if ( getService ( ) == null ) { out . append ( "**InvAccess in (" ) . append ( dataset . getFullName ( ) ) . append ( "): with urlPath= (" ) . append ( urlPath ) . append ( ") has no valid service\n" ) ; isValid = false ; } else if ( getStandardUrlName ( ) == null ) { out . append ( "**InvAccess in (" ) . append ( dataset . getFullName ( ) ) . append ( "): with urlPath= (" ) . append ( urlPath ) . append ( ") has invalid URL\n" ) ; isValid = false ; } if ( show ) System . out . println ( "   access " + urlPath + " valid = " + isValid ) ; return isValid ; }


Input: DataCursor API ( Except as Implemented in AbstractCursor ) [CODESPLIT] @ Override public Object read ( Index index ) throws DapException { return read ( DapUtil . indexToSlices ( index ) ) ; }


Input: Support methods [CODESPLIT] protected Object readAtomic ( List < Slice > slices ) throws DapException { if ( slices == null ) throw new DapException ( "DataCursor.read: null set of slices" ) ; assert this . scheme == Scheme . ATOMIC ; DapVariable atomvar = ( DapVariable ) getTemplate ( ) ; int rank = atomvar . getRank ( ) ; assert slices != null && ( ( rank == 0 && slices . size ( ) == 1 ) || ( slices . size ( ) == rank ) ) ; DapType basetype = atomvar . getBaseType ( ) ; return readAs ( atomvar , basetype , slices ) ; }


Input: Allow specification of basetype to use ; used for enumerations [CODESPLIT] protected Object readAs ( DapVariable atomvar , DapType basetype , List < Slice > slices ) throws DapException { if ( basetype . getTypeSort ( ) == TypeSort . Enum ) { // short circuit this case basetype = ( ( DapEnumeration ) basetype ) . getBaseType ( ) ; return readAs ( atomvar , basetype , slices ) ; } long count = DapUtil . sliceProduct ( slices ) ; Object result = LibTypeFcns . newVector ( basetype , count ) ; Odometer odom = Odometer . factory ( slices ) ; if ( DapUtil . isContiguous ( slices ) && basetype . isFixedSize ( ) ) readContig ( slices , basetype , count , odom , result ) ; else readOdom ( slices , basetype , odom , result ) ; return result ; }


Input: D4Cursor Extensions [CODESPLIT] public D4Cursor setElements ( D4Cursor [ ] instances ) { if ( ! ( getScheme ( ) == Scheme . SEQARRAY || getScheme ( ) == Scheme . STRUCTARRAY ) ) throw new IllegalStateException ( "Adding element to !(structure|sequence array) object" ) ; DapVariable var = ( DapVariable ) getTemplate ( ) ; this . elements = instances ; return this ; }


Input:
actions that control the dataset [CODESPLIT] private void makeActionsDataset ( ) { /*  choose local dataset
    AbstractAction chooseLocalDatasetAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        String filename = fileChooser.chooseFilename();
        if (filename == null) return;

        Dataset invDs;
        try {     // DatasetNode parent, String name, Map<String, Object> flds, List< AccessBuilder > accessBuilders, List< DatasetBuilder > datasetBuilders
          Map<String, Object> flds = new HashMap<>();
          flds.put(Dataset.FeatureType, FeatureType.GRID.toString());
          flds.put(Dataset.ServiceName, ServiceType.File.toString());  // bogus
          invDs = new Dataset(null, filename, flds, null, null);
          setDataset(invDs);

        } catch (Exception ue) {
          JOptionPane.showMessageDialog(CoverageDisplay.this, "Invalid filename = <" + filename + ">\n" + ue.getMessage());
          ue.printStackTrace();
        }
      }
    };
    BAMutil.setActionProperties(chooseLocalDatasetAction, "FileChooser", "open Local dataset...", false, 'L', -1);

    /* saveDatasetAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        String fname = controller.getDatasetName();
        if (fname != null) {
          savedDatasetList.add( fname);
          BAMutil.addActionToMenu( savedDatasetMenu, new DatasetAction( fname), 0);
        }
      }
    };
    BAMutil.setActionProperties( saveDatasetAction, null, "save dataset", false, 'S', 0);
    */ // Configure chooseProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) . setVisible ( ) ; } } ; BAMutil . setActionProperties ( chooseProjectionAction , null , "Projection Manager..." , false , ' ' , 0 ) ; saveCurrentProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { getProjectionManager ( ) ; // set the bounding box ProjectionImpl proj = navPanel . getProjectionImpl ( ) . constructCopy ( ) ; proj . setDefaultMapArea ( navPanel . getMapArea ( ) ) ; //if (debug) System.out.println(" GV save projection "+ proj); // projManage.setMap(renderAll.get("Map"));   LOOK! //projManager.saveProjection( proj); } } ; BAMutil . setActionProperties ( saveCurrentProjectionAction , null , "save Current Projection" , false , ' ' , 0 ) ; /* chooseColorScaleAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        if (null == csManager) // lazy instantiation
          makeColorScaleManager();
        csManager.show();
      }
    };
    BAMutil.setActionProperties( chooseColorScaleAction, null, "ColorScale Manager...", false, 'C', 0);

    */ // redraw redrawAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { repaint ( ) ; start ( true ) ; draw ( true ) ; } } ; BAMutil . setActionProperties ( redrawAction , "alien" , "RedRaw" , false , ' ' , 0 ) ; showDatasetInfoAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { if ( infoWindow == null ) { datasetInfoTA = new TextHistoryPane ( ) ; infoWindow = new IndependentWindow ( "Dataset Information" , BAMutil . getImage ( "GDVs" ) , datasetInfoTA ) ; infoWindow . setSize ( 700 , 700 ) ; infoWindow . setLocation ( 100 , 100 ) ; } datasetInfoTA . clear ( ) ; if ( coverageDataset != null ) { Formatter f = new Formatter ( ) ; coverageDataset . toString ( f ) ; datasetInfoTA . appendLine ( f . toString ( ) ) ; } else { datasetInfoTA . appendLine ( "No coverageDataset loaded" ) ; } datasetInfoTA . gotoTop ( ) ; infoWindow . show ( ) ; } } ; BAMutil . setActionProperties ( showDatasetInfoAction , "Information" , "Show info..." , false , ' ' , - 1 ) ; /*showNcMLAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        if (ncmlWindow == null) {
          ncmlTA = new TextHistoryPane();
          ncmlWindow = new IndependentWindow("Dataset NcML", BAMutil.getImage( "GDVs"), ncmlTA);
          ncmlWindow.setSize(700,700);
          ncmlWindow.setLocation(200, 70);
        }

        ncmlTA.clear();
        //datasetInfoTA.appendLine( "GeoGrid XML for "+ controller.getDatasetName()+"\n");
        ncmlTA.appendLine( controller.getNcML());
        ncmlTA.gotoTop();
        ncmlWindow.show();
      }
    };
    BAMutil.setActionProperties( showNcMLAction, null, "Show NcML...", false, 'X', -1);  */ /* showGridDatasetInfoAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        if (ncmlWindow == null) {
          ncmlTA = new TextHistoryPane();
          ncmlWindow = new IndependentWindow("Dataset NcML", BAMutil.getImage( "GDVs"), ncmlTA);
          ncmlWindow.setSize(700,700);
          ncmlWindow.setLocation(200, 70);
        }

        ncmlTA.clear();
        //datasetInfoTA.appendLine( "GeoGrid XML for "+ controller.getDatasetName()+"\n");
        ncmlTA.appendLine( controller.getDatasetXML());
        ncmlTA.gotoTop();
        ncmlWindow.show();
      }
    };
    BAMutil.setActionProperties( showGridDatasetInfoAction, null, "Show GridDataset Info XML...", false, 'X', -1);

      // show netcdf dataset Table
    /* showNetcdfDatasetAction = new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        NetcdfDataset netcdfDataset = controller.getNetcdfDataset();
        if (null != netcdfDataset) {
          try {
            dsTable.setDataset(netcdfDataset, null);
          } catch (IOException e1) {
            e1.printStackTrace();
            return;
          }
          dsDialog.show();
        }
      }
    };
    BAMutil.setActionProperties( showNetcdfDatasetAction, "netcdf", "NetcdfDataset Table Info...", false, 'D', -1);  */ minmaxHorizAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . horiz ) ; setDataMinMaxType ( ColorScale . MinMaxType . horiz ) ; } } ; BAMutil . setActionProperties ( minmaxHorizAction , null , "Horizontal plane" , false , ' ' , 0 ) ; minmaxLogAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . log ) ; setDataMinMaxType ( ColorScale . MinMaxType . log ) ; } } ; BAMutil . setActionProperties ( minmaxLogAction , null , "log horiz plane" , false , ' ' , 0 ) ; /* minmaxVolAction =  new AbstractAction() {
      public void actionPerformed(ActionEvent e) {
        csDataMinMax.setSelectedIndex(GridRenderer.VOL_MinMaxType);
        controller.setDataMinMaxType(GridRenderer.MinMaxType.vert;
      }
    };
    BAMutil.setActionProperties( minmaxVolAction, null, "Grid volume", false, 'G', 0); */ minmaxHoldAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { csDataMinMax . setSelectedItem ( ColorScale . MinMaxType . hold ) ; setDataMinMaxType ( ColorScale . MinMaxType . hold ) ; } } ; BAMutil . setActionProperties ( minmaxHoldAction , null , "Hold scale constant" , false , ' ' , 0 ) ; fieldLoopAction = new LoopControlAction ( fieldChooser ) ; levelLoopAction = new LoopControlAction ( levelChooser ) ; timeLoopAction = new LoopControlAction ( timeChooser ) ; runtimeLoopAction = new LoopControlAction ( runtimeChooser ) ; }


Input: the actions can then be attached to buttcons menus etc [CODESPLIT] private void makeActions ( ) { boolean state ; dataProjectionAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; if ( state ) { ProjectionImpl dataProjection = coverageRenderer . getDataProjection ( ) ; if ( null != dataProjection ) setProjection ( dataProjection ) ; } else { setProjection ( new LatLonProjection ( ) ) ; } } } ; BAMutil . setActionProperties ( dataProjectionAction , "DataProjection" , "use Data Projection" , true , ' ' , 0 ) ; dataProjectionAction . putValue ( BAMutil . STATE , true ) ; // contouring drawBBAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawBB ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( drawBBAction , "Contours" , "draw bounding box" , true , ' ' , 0 ) ; drawBBAction . putValue ( BAMutil . STATE , false ) ; // draw horiz drawHorizAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; drawHorizOn = state . booleanValue ( ) ; setDrawHorizAndVert ( drawHorizOn , drawVertOn ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( drawHorizAction , "DrawHoriz" , "draw horizontal" , true , ' ' , 0 ) ; state = store . getBoolean ( "drawHorizAction" , true ) ; drawHorizAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; drawHorizOn = state ; // draw Vert drawVertAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; drawVertOn = state . booleanValue ( ) ; setDrawHorizAndVert ( drawHorizOn , drawVertOn ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( drawVertAction , "DrawVert" , "draw vertical" , true , ' ' , 0 ) ; state = store . getBoolean ( "drawVertAction" , false ) ; drawVertAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; drawVertOn = state ; // show grid showGridAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawGridLines ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( showGridAction , "Grid" , "show grid lines" , true , ' ' , 0 ) ; state = store . getBoolean ( "showGridAction" , false ) ; showGridAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; coverageRenderer . setDrawGridLines ( state ) ; // contouring showContoursAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawContours ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( showContoursAction , "Contours" , "show contours" , true , ' ' , 0 ) ; state = store . getBoolean ( "showContoursAction" , false ) ; showContoursAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; coverageRenderer . setDrawContours ( state ) ; // contouring labels showContourLabelsAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { Boolean state = ( Boolean ) getValue ( BAMutil . STATE ) ; coverageRenderer . setDrawContourLabels ( state . booleanValue ( ) ) ; draw ( false ) ; } } ; BAMutil . setActionProperties ( showContourLabelsAction , "ContourLabels" , "show contour labels" , true , ' ' , 0 ) ; state = store . getBoolean ( "showContourLabelsAction" , false ) ; showContourLabelsAction . putValue ( BAMutil . STATE , new Boolean ( state ) ) ; coverageRenderer . setDrawContourLabels ( state ) ; }


Input:
save all data in the PersistentStore [CODESPLIT] public void save ( ) { //store.putInt( "vertSplit", splitDraw.getDividerLocation()); store . putBoolean ( "navToolbarAction" , ( ( Boolean ) navToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( "moveToolbarAction" , ( ( Boolean ) moveToolbarAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; if ( projManager != null ) projManager . storePersistentData ( ) ; /* if (csManager != null)
      csManager.storePersistentData();
    if (sysConfigDialog != null)
      sysConfigDialog.storePersistentData(); */ //dsTable.save(); //dsTable.getPrefs().putBeanObject("DialogBounds", dsDialog.getBounds()); store . put ( GEOTIFF_FILECHOOSER_DEFAULTDIR , geotiffFileChooser . getCurrentDirectory ( ) ) ; store . putBeanObject ( LastMapAreaName , navPanel . getMapArea ( ) ) ; store . putBeanObject ( LastProjectionName , navPanel . getProjectionImpl ( ) ) ; //if (gridDataset != null) //  store.put(LastDatasetName, gridDataset.getTitle()); store . putBeanObject ( ColorScaleName , colorScale ) ; store . putBoolean ( "showGridAction" , ( ( Boolean ) showGridAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( "showContoursAction" , ( ( Boolean ) showContoursAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; store . putBoolean ( "showContourLabelsAction" , ( ( Boolean ) showContourLabelsAction . getValue ( BAMutil . STATE ) ) . booleanValue ( ) ) ; }


Input: / * private boolean chooseDataset ( String url ) { InvDataset invDs = new InvDatasetImpl ( fname ServerType . NETCDF ) ; return chooseDataset ( invDs ) ; } [CODESPLIT] private void setSelected ( boolean b ) { selected = b ; //showGridTableAction.setEnabled(b); //showNcMLAction.setEnabled(b); //showNcMLAction.setEnabled(b); //showNetcdfDatasetAction.setEnabled(b); //showGridDatasetInfoAction.setEnabled(b); //showNetcdfXMLAction.setEnabled( b); navToolbarAction . setEnabled ( b ) ; moveToolbarAction . setEnabled ( b ) ; //controller.showGridAction.setEnabled( b); //controller.showContoursAction.setEnabled( b); //controller.showContourLabelsAction.setEnabled( b); redrawAction . setEnabled ( b ) ; minmaxHorizAction . setEnabled ( b ) ; minmaxLogAction . setEnabled ( b ) ; minmaxHoldAction . setEnabled ( b ) ; fieldLoopAction . setEnabled ( b ) ; levelLoopAction . setEnabled ( b ) ; timeLoopAction . setEnabled ( b ) ; runtimeLoopAction . setEnabled ( b ) ; navPanel . setEnabledActions ( b ) ; }


Input: assume that its done in the event thread [CODESPLIT] boolean showDataset ( ) { // temp kludge for initialization Iterable < Coverage > grids = coverageDataset . getCoverages ( ) ; currentField = grids . iterator ( ) . next ( ) ; // first currentSlice = 0 ; currentLevel = 0 ; currentTime = 0 ; currentEnsemble = 0 ; currentRunTime = 0 ; eventsOK = false ; // dont let this trigger redraw this . dataState = coverageRenderer . setCoverage ( coverageDataset , currentField ) ; coverageRenderer . setDataProjection ( currentField . getCoordSys ( ) . getProjection ( ) ) ; // setFields(grids); setField ( currentField ) ; // LOOK if possible, change the projection and the map area to one that fits this dataset ProjectionImpl dataProjection = currentField . getCoordSys ( ) . getProjection ( ) ; if ( dataProjection != null ) setProjection ( dataProjection ) ; // ready to draw //draw(true); // events now ok eventsOK = true ; return true ; }


Input: / * private void drawV ( boolean immediate ) { if ( !startOK ) return ; ScaledPanel drawArea = vertPanel . getDrawArea () ; Graphics2D gV = drawArea . getBufferedImageGraphics () ; if ( gV == null ) return ; [CODESPLIT] private synchronized void redrawLater ( ) { //redrawComplete |= complete; boolean already = redrawTimer . isRunning ( ) ; if ( debugThread ) System . out . println ( "redrawLater isRunning= " + already ) ; if ( already ) redrawTimer . restart ( ) ; else redrawTimer . start ( ) ; }


Input: gets parameter table then grib1 parameter based on number . [CODESPLIT] public final GridParameter getParameter ( GridRecord gr ) { String name = gr . getParameterName ( ) ; GridParameter gp = GempakGridParameterTable . getParameter ( name ) ; if ( gp != null ) { return gp ; } return new GridParameter ( 0 , name , name , "" ) ; }


Input: is this a PositiveUp VerticalCoordinate . [CODESPLIT] public final boolean isPositiveUp ( GridRecord gr ) { int type = gr . getLevelType1 ( ) ; if ( ( type == 1 ) || ( type == 5 ) ) { return false ; } return true ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : observedProperty [CODESPLIT] public static ReferenceType initObservedProperty ( ReferenceType observedProperty , VariableSimpleIF dataVar ) { // @xlink:title observedProperty . setTitle ( dataVar . getShortName ( ) ) ; return observedProperty ; }


Input: Construct the Action that is called when this bean s menu item / buttcon is selected . Typically this routine is only called once when the bean is added . The Action itself is called whenever the menu / buttcon is selected . [CODESPLIT] public javax . swing . Action getAction ( ) { AbstractAction useMap = new AbstractAction ( getActionName ( ) , getIcon ( ) ) { public void actionPerformed ( java . awt . event . ActionEvent e ) { firePropertyChangeEvent ( this , "Renderer" , null , getRenderer ( ) ) ; } } ; useMap . putValue ( Action . SHORT_DESCRIPTION , getActionDesc ( ) ) ; return useMap ; }


Input:
Convenience routine to make a button with a popup menu attached . to use : <pre > thredds . ui . PopupMenu mapBeanMenu = MapBean . makeMapSelectButton () ; AbstractButton butt = ( AbstractButton ) mapBeanMenu . getParentComponent () ; addToMenu ( butt ) ; [CODESPLIT] static public PopupMenu makeMapSelectButton ( ) { AbstractAction mapSelectAction = new AbstractAction ( ) { public void actionPerformed ( ActionEvent e ) { //System.out.println("mapSelectAction");
 //mapPopup.show();
 } } ; BAMutil . setActionProperties ( mapSelectAction , "WorldMap" , "select map" , false , ' ' , - 1 ) ; AbstractButton mapSelectButton = BAMutil . makeButtconFromAction ( mapSelectAction ) ; PopupMenu mapPopup = new PopupMenu ( mapSelectButton , "Select Map" , true ) ; return mapPopup ; }


Input: Converts numeric values from this unit to another unit . [CODESPLIT] public double [ ] convertTo ( final double [ ] amounts , final Unit outputUnit ) throws ConversionException { return convertTo ( amounts , outputUnit , new double [ amounts . length ] ) ; }


Input: Converts numeric values from this unit to another unit . [CODESPLIT] public float [ ] convertTo ( final float [ ] input , final Unit outputUnit , final float [ ] output ) throws ConversionException { return getConverterTo ( outputUnit ) . convert ( input , output ) ; }


Input: Indicates if numeric values in this unit are convertible with another unit . [CODESPLIT] public boolean isCompatible ( final Unit that ) { // jeffm: for some reason just calling getDerivedUnit().equals(...) // with jikes 1.1.7 as the compiler causes the jvm to crash. // The Unit u1=... does not crash. final Unit u1 = getDerivedUnit ( ) ; return u1 . equals ( that . getDerivedUnit ( ) ) ; // return getDerivedUnit().equals(that.getDerivedUnit()); }


Input: Returns a label for a quantity in this unit . [CODESPLIT] public String makeLabel ( final String quantityID ) { final StringBuilder buf = new StringBuilder ( quantityID ) ; if ( quantityID . contains ( " " ) ) { buf . insert ( 0 , ' ' ) . append ( ' ' ) ; } buf . append ( ' ' ) ; final int start = buf . length ( ) ; buf . append ( toString ( ) ) ; if ( buf . substring ( start ) . indexOf ( ' ' ) != - 1 ) { buf . insert ( start , ' ' ) . append ( ' ' ) ; } return buf . toString ( ) ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : featureOfInterest / wml2 : MonitoringPoint [CODESPLIT] public static MonitoringPointType initMonitoringPointType ( MonitoringPointType monitoringPoint , StationTimeSeriesFeature stationFeat ) { // @gml:id String id = MarshallingUtil . createIdForType ( MonitoringPointType . class ) ; monitoringPoint . setId ( id ) ; // gml:identifier NcCodeWithAuthorityType . initIdentifier ( monitoringPoint . addNewIdentifier ( ) , stationFeat ) ; // gml:description NcStringOrRefType . initDescription ( monitoringPoint . addNewDescription ( ) , stationFeat ) ; if ( monitoringPoint . getDescription ( ) . getStringValue ( ) == null || monitoringPoint . getDescription ( ) . getStringValue ( ) . isEmpty ( ) ) { monitoringPoint . unsetDescription ( ) ; } // sam:sampledFeature monitoringPoint . addNewSampledFeature ( ) ; monitoringPoint . setNilSampledFeatureArray ( 0 ) ; // Set the "sam:sampledFeature" we just added to nil. // sams:shape NcShapeType . initShape ( monitoringPoint . addNewShape ( ) , stationFeat ) ; return monitoringPoint ; }


Input: Given a Variable name and a beginning index and end index returns a list of polygon ( inclusive on both sides ) [CODESPLIT] public List < Polygon > getPolygons ( String name , int indexBegin , int indexEnd ) { return builder . getPolygons ( name , indexBegin , indexEnd ) ; }


Input: Given a Variable name and a beginning index and end index returns a list of lines ( inclusive on both sides ) [CODESPLIT] public List < Line > getLines ( String name , int indexBegin , int indexEnd ) { return builder . getLines ( name , indexBegin , indexEnd ) ; }


Input: Given a Variable name and a beginning index and end index returns a list of points ( inclusive on both sides ) [CODESPLIT] public List < Point > getPoints ( String name , int indexBegin , int indexEnd ) { return builder . getPoints ( name , indexBegin , indexEnd ) ; }


Input:
Position file at bitOffset from startPos [CODESPLIT] public void setBitOffset ( int bitOffset ) throws IOException { if ( bitOffset % 8 == 0 ) { raf . seek ( startPos + bitOffset / 8 ) ; bitPos = 0 ; bitBuf = 0 ; } else { raf . seek ( startPos + bitOffset / 8 ) ; bitPos = 8 - ( bitOffset % 8 ) ; bitBuf = ( byte ) raf . read ( ) ; bitBuf &= 0xff >> ( 8 - bitPos ) ; // mask off consumed bits
 } }


Input:
Read the next nb bits and return an Unsigned Long . [CODESPLIT] public long bits2UInt ( int nb ) throws IOException { assert nb <= 64 ; assert nb >= 0 ; long result = 0 ; int bitsLeft = nb ; while ( bitsLeft > 0 ) { // we ran out of bits - fetch the next byte...
 if ( bitPos == 0 ) { bitBuf = nextByte ( ) ; bitPos = BIT_LENGTH ; } // -- retrieve bit from current byte ----------
 // how many bits to read from the current byte
 int size = Math . min ( bitsLeft , bitPos ) ; // move my part to start
 int myBits = bitBuf >> ( bitPos - size ) ; // mask-off sign-extending
 myBits &= BYTE_BITMASK ; // mask-off bits of next value
 myBits &= ~ ( BYTE_BITMASK << size ) ; // -- put bit to result ----------------------
 // where to place myBits inside of result
 int shift = bitsLeft - size ; assert shift >= 0 ; // put it there
 result |= myBits << shift ; // -- put bit to result ----------------------
 // update information on what we consumed
 bitsLeft -= size ; bitPos -= size ; } return result ; }


Input:
Read the next nb bits and return an Signed Long . [CODESPLIT] public long bits2SInt ( int nb ) throws IOException { long result = bits2UInt ( nb ) ; // check if we're negative
 if ( getBit ( result , nb ) ) { // it's negative! reset leading bit
 result = setBit ( result , nb , false ) ; // build 2's-complement
 result = ~ result & LONG_BITMASK ; result = result + 1 ; } return result ; }


Input: Open a connection to the DODS server . [CODESPLIT] private void openConnection ( String urlString , Command command ) throws IOException , DAP2Exception { InputStream is = null ; try { try ( HTTPMethod method = HTTPFactory . Get ( _session , urlString ) ) { if ( acceptCompress ) method . setCompression ( "deflate,gzip" ) ; // enable sessions if ( allowSessions ) method . setUseSessions ( true ) ; int statusCode ; for ( ; ; ) { statusCode = method . execute ( ) ; if ( statusCode != HttpStatus . SC_SERVICE_UNAVAILABLE ) break ; Thread . sleep ( 5000 ) ; System . err . println ( "Service Unavailable" ) ; } // debug // if (debugHeaders) ucar.httpservices.HttpClientManager.showHttpRequestInfo(f, method); if ( statusCode == HttpStatus . SC_NOT_FOUND ) { throw new DAP2Exception ( DAP2Exception . NO_SUCH_FILE , method . getStatusText ( ) + ": " + urlString ) ; } if ( statusCode == HttpStatus . SC_UNAUTHORIZED || statusCode == HttpStatus . SC_FORBIDDEN ) { throw new InvalidCredentialsException ( method . getStatusText ( ) ) ; } if ( statusCode != HttpStatus . SC_OK ) { throw new DAP2Exception ( "Method failed:" + method . getStatusText ( ) + " on URL= " + urlString ) ; } // Get the response body. is = method . getResponseAsStream ( ) ; // check if its an error Header header = method . getResponseHeader ( "Content-Description" ) ; if ( header != null && ( header . getValue ( ) . equals ( "dods-error" ) || header . getValue ( ) . equals ( "dods_error" ) ) ) { // create server exception object DAP2Exception ds = new DAP2Exception ( ) ; // parse the Error object from stream and throw it ds . parse ( is ) ; throw ds ; } ver = new ServerVersion ( method ) ; checkHeaders ( method ) ; // check for deflator Header h = method . getResponseHeader ( "content-encoding" ) ; String encoding = ( h == null ) ? null : h . getValue ( ) ; //if (encoding != null) LogStream.out.println("encoding= " + encoding); if ( encoding != null && encoding . equals ( "deflate" ) ) { is = new BufferedInputStream ( new InflaterInputStream ( is ) , 1000 ) ; if ( showCompress ) System . out . printf ( "deflate %s%n" , urlString ) ; } else if ( encoding != null && encoding . equals ( "gzip" ) ) { is = new BufferedInputStream ( new GZIPInputStream ( is ) , 1000 ) ; if ( showCompress ) System . out . printf ( "gzip %s%n" , urlString ) ; } else { if ( showCompress ) System . out . printf ( "none %s%n" , urlString ) ; } command . process ( is ) ; } } catch ( IOException | DAP2Exception e ) { throw e ; } catch ( Exception e ) { Util . check ( e ) ; //e.printStackTrace(); throw new DAP2Exception ( e ) ; } }


Input: Returns the DAS object from the dataset referenced by this object s URL . The DAS object is referred to by appending . das to the end of a DODS URL . [CODESPLIT] public DAS getDAS ( ) throws IOException , DAP2Exception { DASCommand command = new DASCommand ( ) ; if ( filePath != null ) { // url was file: File daspath = new File ( filePath + ".das" ) ; // See if the das file exists if ( daspath . canRead ( ) ) { try ( FileInputStream is = new FileInputStream ( daspath ) ) { command . process ( is ) ; } } } else if ( stream != null ) { command . process ( stream ) ; } else { // assume url is remote try { openConnection ( urlString + ".das" + getCompleteCE ( projString , selString ) , command ) ; } catch ( DAP2Exception de ) { //if(de.getErrorCode() != DAP2Exception.NO_SUCH_FILE) //throw de;  // rethrow } } return command . das ; }


Input: Returns the DDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . dds to the end of a OPeNDAP URL . [CODESPLIT] public DDS getDDS ( String CE ) throws IOException , ParseException , DAP2Exception { DDSCommand command = new DDSCommand ( ) ; command . setURL ( CE == null || CE . length ( ) == 0 ? urlString : urlString + "?" + CE ) ; if ( filePath != null ) { try ( FileInputStream is = new FileInputStream ( filePath + ".dds" ) ) { command . process ( is ) ; } } else if ( stream != null ) { command . process ( stream ) ; } else { // must be a remote url openConnection ( urlString + ".dds" + ( getCompleteCE ( CE ) ) , command ) ; } return command . dds ; }


Input: Use some sense when assembling the CE . Since this DConnect object may have constructed using a CE any new CE will have to be integrated into it for subsequent requests . Try to do this in a sensible manner! [CODESPLIT] private String getCompleteCE ( String CE ) { String localProjString = null ; String localSelString = null ; if ( CE == null ) return "" ; //remove any leading '?' if ( CE . startsWith ( "?" ) ) CE = CE . substring ( 1 ) ; int selIndex = CE . indexOf ( ' ' ) ; if ( selIndex == 0 ) { localProjString = "" ; localSelString = CE ; } else if ( selIndex > 0 ) { localSelString = CE . substring ( selIndex ) ; localProjString = CE . substring ( 0 , selIndex ) ; } else { // selIndex < 0 localProjString = CE ; localSelString = "" ; } String ce = projString ; if ( ! localProjString . equals ( "" ) ) { if ( ! ce . equals ( "" ) && localProjString . indexOf ( ' ' ) != 0 ) ce += "," ; ce += localProjString ; } if ( ! selString . equals ( "" ) ) { if ( selString . indexOf ( ' ' ) != 0 ) ce += "&" ; ce += selString ; } if ( ! localSelString . equals ( "" ) ) { if ( localSelString . indexOf ( ' ' ) != 0 ) ce += "&" ; ce += localSelString ; } if ( ce . length ( ) > 0 ) ce = "?" + ce ; if ( false ) { DAPNode . log . debug ( "projString: '" + projString + "'" ) ; DAPNode . log . debug ( "localProjString: '" + localProjString + "'" ) ; DAPNode . log . debug ( "selString: '" + selString + "'" ) ; DAPNode . log . debug ( "localSelString: '" + localSelString + "'" ) ; DAPNode . log . debug ( "Complete CE: " + ce ) ; } return ce ; // escaping will happen elsewhere }


Input: ALternate interface to getCompleteCE ( String ce ) [CODESPLIT] private String getCompleteCE ( String proj , String sel ) { if ( proj != null && proj . length ( ) == 0 ) proj = "" ; // canonical if ( sel != null && sel . length ( ) == 0 ) sel = null ; // canonical StringBuilder buf = new StringBuilder ( ) ; if ( proj . startsWith ( "?" ) ) buf . append ( proj . substring ( 1 ) ) ; else buf . append ( proj ) ; if ( sel != null ) { if ( sel . startsWith ( "&" ) ) buf . append ( sel ) ; else { buf . append ( "&" ) ; buf . append ( sel ) ; } } return getCompleteCE ( buf . toString ( ) ) ; }


Input: Returns the DDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . ddx to the end of a OPeNDAP URL . The server should send back a DDX ( A DDS in XML format ) which will get parsed here ( locally ) and a new DDS instantiated using the DDSXMLParser . [CODESPLIT] public DDS getDDX ( String CE ) throws IOException , ParseException , DDSException , DAP2Exception { DDXCommand command = new DDXCommand ( ) ; openConnection ( urlString + ".ddx" + ( getCompleteCE ( CE ) ) , command ) ; return command . dds ; }


Input: Returns the DataDDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . ddx to the end of a OPeNDAP URL . The server should send back a DDX ( A DDS in XML format ) which will get parsed here ( locally ) and a new DDS instantiated using the DDSXMLParser . [CODESPLIT] public DataDDS getDataDDX ( String CE ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { return getDataDDX ( CE , new DefaultFactory ( ) ) ; }


Input: Returns the DataDDS object from the dataset referenced by this object s URL . The DDS object is referred to by appending . ddx to the end of a OPeNDAP URL . The server should send back a DDX ( A DDS in XML format ) which will get parsed here ( locally ) and a new DDS instantiated using the DDSXMLParser . [CODESPLIT] public DataDDS getDataDDX ( String CE , BaseTypeFactory btf ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { DataDDXCommand command = new DataDDXCommand ( btf , this . ver ) ; openConnection ( urlString + ".ddx" + ( getCompleteCE ( CE ) ) , command ) ; return command . dds ; }


Input: Returns the Data object from the dataset referenced by this object s URL given the constraint expression CE . Note that the Data object is really just a DDS object with data bound to the variables . The DDS will probably contain fewer variables ( and those might have different types ) than in the DDS returned by getDDS () because that method returns the entire DDS ( but without any data ) while this method returns only those variables listed in the projection part of the constraint expression . <p > Note that if CE is an empty String then the entire dataset will be returned unless a sticky CE has been specified in the constructor . [CODESPLIT] public DataDDS getData ( String CE , StatusUI statusUI , BaseTypeFactory btf ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { if ( CE != null && CE . trim ( ) . length ( ) == 0 ) CE = null ; DataDDS dds = new DataDDS ( ver , btf ) ; DataDDSCommand command = new DataDDSCommand ( dds , statusUI ) ; command . setURL ( urlString + ( CE == null ? "" : "?" + CE ) ) ; if ( filePath != null ) { // url is file: File dodspath = new File ( filePath + ".dods" ) ; // See if the dods file exists if ( dodspath . canRead ( ) ) { /* WARNING: any constraints are ignored in reading the file */ try ( FileInputStream is = new FileInputStream ( dodspath ) ) { command . process ( is ) ; } } } else if ( stream != null ) { command . process ( stream ) ; } else { String urls = urlString + ".dods" + ( CE == null ? "" : getCompleteCE ( CE ) ) ; openConnection ( urls , command ) ; } return command . dds ; }


Input: Returns the Data object from the dataset referenced by this object s URL given the constraint expression CE . Note that the Data object is really just a DDS object with data bound to the variables . The DDS will probably contain fewer variables ( and those might have different types ) than in the DDS returned by getDDS () because that method returns the entire DDS ( but without any data ) while this method returns only those variables listed in the projection part of the constraint expression . <p > Note that if CE is an empty String then the entire dataset will be returned unless a sticky CE has been specified in the constructor . [CODESPLIT] public DataDDS getData ( String CE , StatusUI statusUI ) throws MalformedURLException , IOException , ParseException , DDSException , DAP2Exception { return getData ( CE , statusUI , new DefaultFactory ( ) ) ; }


Input:
Does the line between these two points cross the projection seam . [CODESPLIT] @ Override public boolean crossSeam ( ProjectionPoint pt1 , ProjectionPoint pt2 ) { // either point is infinite
 if ( ProjectionPointImpl . isInfinite ( pt1 ) || ProjectionPointImpl . isInfinite ( pt2 ) ) { return true ; } // opposite signed long lines
 double x1 = pt1 . getX ( ) - falseEasting ; double x2 = pt2 . getX ( ) - falseEasting ; return ( x1 * x2 < 0 ) && ( Math . abs ( x1 - x2 ) > earthRadius ) ; }


Input:
Convert a LatLonPoint to projection coordinates [CODESPLIT] @ Override public ProjectionPoint latLonToProj ( LatLonPoint latLon , ProjectionPointImpl result ) { double deltaLon_d = LatLonPointImpl . range180 ( latLon . getLongitude ( ) - centMeridian ) ; double fromLat_r = Math . toRadians ( latLon . getLatitude ( ) ) ; double toX = earthRadius * Math . toRadians ( deltaLon_d ) * Math . cos ( fromLat_r ) ; double toY = earthRadius * fromLat_r ; // p 247 Snyder
 result . setLocation ( toX + falseEasting , toY + falseNorthing ) ; return result ; }


Input:
Convert projection coordinates to a LatLonPoint [CODESPLIT] @ Override public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { double fromX = world . getX ( ) - falseEasting ; double fromY = world . getY ( ) - falseNorthing ; double toLat_r = fromY / earthRadius ; double toLon_r ; if ( Misc . nearlyEquals ( Math . abs ( toLat_r ) , PI_OVER_2 , 1e-10 ) ) { toLat_r = toLat_r < 0 ? - PI_OVER_2 : + PI_OVER_2 ; toLon_r = Math . toRadians ( centMeridian ) ; // if lat == +- pi/2, set lon = centMeridian (Snyder 248)
 } else if ( Math . abs ( toLat_r ) < PI_OVER_2 ) { toLon_r = Math . toRadians ( centMeridian ) + fromX / ( earthRadius * Math . cos ( toLat_r ) ) ; } else { return INVALID ; // Projection point is off the map.
 } if ( Misc . nearlyEquals ( Math . abs ( toLon_r ) , PI , 1e-10 ) ) { toLon_r = toLon_r < 0 ? - PI : + PI ; } else if ( Math . abs ( toLon_r ) > PI ) { return INVALID ; // Projection point is off the map.
 } result . setLatitude ( Math . toDegrees ( toLat_r ) ) ; result . setLongitude ( Math . toDegrees ( toLon_r ) ) ; return result ; }


Input: Returns the points at which { @code projBB } intersects the map edge . [CODESPLIT] public List < ProjectionPoint > getMapEdgeIntercepts ( ProjectionRect projBB ) { List < ProjectionPoint > intercepts = new LinkedList <> ( ) ; for ( ProjectionPoint topIntercept : getMapEdgeInterceptsAtY ( projBB . getUpperRightPoint ( ) . getY ( ) ) ) { if ( pointIsBetween ( topIntercept , projBB . getUpperLeftPoint ( ) , projBB . getUpperRightPoint ( ) ) ) { intercepts . add ( topIntercept ) ; } } for ( ProjectionPoint rightIntercept : getMapEdgeInterceptsAtX ( projBB . getUpperRightPoint ( ) . getX ( ) ) ) { if ( pointIsBetween ( rightIntercept , projBB . getUpperRightPoint ( ) , projBB . getLowerRightPoint ( ) ) ) { intercepts . add ( rightIntercept ) ; } } for ( ProjectionPoint bottomIntercept : getMapEdgeInterceptsAtY ( projBB . getLowerLeftPoint ( ) . getY ( ) ) ) { if ( pointIsBetween ( bottomIntercept , projBB . getLowerLeftPoint ( ) , projBB . getLowerRightPoint ( ) ) ) { intercepts . add ( bottomIntercept ) ; } } for ( ProjectionPoint leftIntercept : getMapEdgeInterceptsAtX ( projBB . getLowerLeftPoint ( ) . getX ( ) ) ) { if ( pointIsBetween ( leftIntercept , projBB . getLowerLeftPoint ( ) , projBB . getUpperLeftPoint ( ) ) ) { intercepts . add ( leftIntercept ) ; } } return intercepts ; }


Input:
Returns the points at which the line { @code x = x0 } intersects the map edge . [CODESPLIT] public List < ProjectionPoint > getMapEdgeInterceptsAtX ( double x0 ) { List < ProjectionPoint > mapEdgeIntercepts = new LinkedList <> ( ) ; if ( projToLatLon ( x0 , falseNorthing ) == INVALID ) { // The line {@code x = x0} does not intersect the map.
 return mapEdgeIntercepts ; // Empty list.
 } double x0natural = x0 - falseEasting ; double limitLon_r = ( x0natural < 0 ) ? - PI : + PI ; double deltaLon_r = limitLon_r - Math . toRadians ( centMeridian ) ; // This formula comes from solving 30-1 for phi, and then plugging it into 30-2. See Snyder, p 247.
 double minY = - earthRadius * Math . acos ( x0natural / ( earthRadius * deltaLon_r ) ) ; double maxY = + earthRadius * Math . acos ( x0natural / ( earthRadius * deltaLon_r ) ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( x0 , minY + falseNorthing ) ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( x0 , maxY + falseNorthing ) ) ; return mapEdgeIntercepts ; }


Input:
Returns the points at which the line { @code y = y0 } intersects the map edge . [CODESPLIT] public List < ProjectionPoint > getMapEdgeInterceptsAtY ( double y0 ) { List < ProjectionPoint > mapEdgeIntercepts = new LinkedList <> ( ) ; if ( projToLatLon ( falseEasting , y0 ) == INVALID ) { // The line {@code y = y0} does not intersect the map.
 return mapEdgeIntercepts ; // Empty list.
 } double minX = getXAt ( y0 , - PI ) ; double maxX = getXAt ( y0 , + PI ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( minX , y0 ) ) ; mapEdgeIntercepts . add ( new ProjectionPointImpl ( maxX , y0 ) ) ; return mapEdgeIntercepts ; }


Input: Reference Date ( octet 13 - 17 ) . Reference time of data – date and time of start of averaging or accumulation period . [CODESPLIT] public final CalendarDate getReferenceDate ( ) { int century = getReferenceCentury ( ) - 1 ; if ( century == - 1 ) century = 20 ; int year = getOctet ( 13 ) ; int month = getOctet ( 14 ) ; int day = getOctet ( 15 ) ; int hour = getOctet ( 16 ) ; int minute = getOctet ( 17 ) ; return CalendarDate . of ( null , century * 100 + year , month , day , hour , minute , 0 ) ; }


Input: / * NCEP Appendix C Manual 388 http : // www . nco . ncep . noaa . gov / pmb / docs / on388 / appendixc . html states that if the PDS is > 28 bytes and octet 41 == 1 then it s an ensemble an product . [CODESPLIT] public boolean isEnsemble ( ) { switch ( getCenter ( ) ) { case 7 : return ( ( rawData . length >= 43 ) && ( getOctet ( 41 ) == 1 ) ) ; case 98 : return ( ( rawData . length >= 51 ) && ( getOctet ( 41 ) == 1 || getOctet ( 41 ) == 30 ) && ( getOctet ( 43 ) == 10 || getOctet ( 43 ) == 11 ) ) ; } return false ; }


Input: : title = WPDN data : selected by ob time : time range from 1207951200 to 1207954800 ; [CODESPLIT] public boolean isMine ( FeatureType wantFeatureType , NetcdfDataset ds ) { String title = ds . findAttValueIgnoreCase ( null , "title" , null ) ; if ( title == null ) { title = ds . findAttValueIgnoreCase ( null , "DD_reference" , null ) ; if ( title != null ) { title = ds . findVariable ( "staLat" ) != null ? title : null ; } } return title != null && ( title . startsWith ( "WPDN data" ) || title . startsWith ( "RASS data" ) || title . contains ( "88-21-R2" ) ) ; }


Input: This code tweaks our catalog output to match . [CODESPLIT] private String idvDatasetCatalog ( String xml ) { String ret = xml . replace ( "variables" , "Variables" ) ; ret = ret . replace ( "timeCoverage" , "TimeSpan" ) ; StringBuilder sub = new StringBuilder ( ret . substring ( 0 , ret . indexOf ( "<geospatialCoverage>" ) ) ) ; sub . append ( "<LatLonBox>\n\t<north>90.0</north>\n\t<south>-90.0</south>" ) ; sub . append ( "\n\t<east>180.0</east>\n\t<west>-180.0</west></LatLonBox>" ) ; String endCoverage = "</geospatialCoverage>" ; sub . append ( ret . substring ( ret . indexOf ( endCoverage ) + endCoverage . length ( ) ) ) ; return sub . toString ( ) ; }


Input: present and 14 days . [CODESPLIT] private DateRange idvCompatibleRange ( DateRange range ) { CalendarDate start = range . getStart ( ) . getCalendarDate ( ) ; CalendarDate end = range . getEnd ( ) . getCalendarDate ( ) ; return new DateRange ( start . toDate ( ) , end . toDate ( ) ) ; }


Input: wml2 : Collection / wml2 : observationMember / om : OM_Observation / om : phenomenonTime [CODESPLIT] public static TimeObjectPropertyType initPhenomenonTime ( TimeObjectPropertyType phenomenonTime , StationTimeSeriesFeature stationFeat ) throws IOException { // gml:TimePeriod TimePeriodDocument timePeriodDoc = TimePeriodDocument . Factory . newInstance ( ) ; NcTimePeriodType . initTimePeriod ( timePeriodDoc . addNewTimePeriod ( ) , stationFeat ) ; phenomenonTime . set ( timePeriodDoc ) ; return phenomenonTime ; }


Input: Check basic DMSP file validity of given random access file . [CODESPLIT] boolean isValidFile ( ucar . unidata . io . RandomAccessFile raFile ) { // @todo This method should not be called if read() has or will be called on this instance. this . raFile = raFile ; try { this . actualSize = raFile . length ( ) ; } catch ( IOException e ) { return ( false ) ; } try { this . readHeaderFromFile ( raFile ) ; this . handleFileInformation ( ) ; this . handleProcessingInformation ( ) ; this . handleSatelliteInformation ( ) ; this . handleSensorInformation ( ) ; } catch ( IOException e ) { return ( false ) ; } return ( true ) ; }


Input: Read the header information from the file into name / value pairs . [CODESPLIT] private void readHeaderFromFile ( ucar . unidata . io . RandomAccessFile raFile ) throws IOException { long pos = 0 ; raFile . seek ( pos ) ; // Read in first record. this . headerSizeInBytes = raFile . length ( ) > this . headerSizeInBytesGuess ? this . headerSizeInBytesGuess : ( int ) raFile . length ( ) ; byte [ ] b = new byte [ this . headerSizeInBytes ] ; if ( raFile . read ( b ) != this . headerSizeInBytes ) throw new IOException ( "Invalid DMSP file: could not read first " + this . headerSizeInBytes + " bytes." ) ; String fullHeader = new String ( b , CDM . utf8Charset ) ; // Make sure header starts with the proper item. if ( ! fullHeader . startsWith ( HeaderInfoTitle . FILE_ID . toString ( ) ) ) { throw new IOException ( "Invalid DMSP file: header does not start with \"" + HeaderInfoTitle . FILE_ID . toString ( ) + "\"." ) ; } // Make sure header contains end-of-header marker. int endOfHeaderIndex = fullHeader . indexOf ( HeaderInfoTitle . END_HEADER . toString ( ) ) ; if ( endOfHeaderIndex == - 1 ) { throw new IOException ( "Invalid DMSP file: header does not end with \"" + HeaderInfoTitle . END_HEADER . toString ( ) + "\"." ) ; } // Drop the end-of-header marker and the line feed ('\n') proceeding it. header = fullHeader . substring ( 0 , endOfHeaderIndex - 1 ) . split ( "\n" ) ; int lineSeperatorIndex = 0 ; String curHeaderLine = null ; String curHeaderTitle = null ; String curHeaderValue = null ; for ( String aHeader : this . header ) { curHeaderLine = aHeader . trim ( ) ; lineSeperatorIndex = curHeaderLine . indexOf ( ' ' ) ; if ( lineSeperatorIndex == - 1 ) throw new IOException ( "Invalid DMSP file: header line <" + curHeaderLine + "> contains no seperator <:>." ) ; if ( lineSeperatorIndex == 0 ) throw new IOException ( "Invalid DMSP file: header line <" + curHeaderLine + "> contains no title." ) ; if ( lineSeperatorIndex == curHeaderLine . length ( ) - 1 ) throw new IOException ( "Invalid DMSP file: header line <" + curHeaderLine + "> contains no value." ) ; curHeaderTitle = curHeaderLine . substring ( 0 , lineSeperatorIndex ) . trim ( ) ; curHeaderValue = curHeaderLine . substring ( lineSeperatorIndex + 1 ) . trim ( ) ; if ( curHeaderValue . equals ( "" ) ) throw new IOException ( "Invalid DMSP file: header line <" + curHeaderLine + "> contains no value." ) ; headerInfo . put ( curHeaderTitle , curHeaderValue ) ; } }


Input: Parse the file header information about the file ( e . g . file ID dataset ID record size number of records ) and create netCDF attributes and dimensions where appropriate . [CODESPLIT] private void handleFileInformation ( ) throws IOException { fileIdAtt = new Attribute ( this . fileIdAttName , headerInfo . get ( HeaderInfoTitle . FILE_ID . toString ( ) ) ) ; datasetIdAtt = new Attribute ( this . datasetIdAttName , headerInfo . get ( HeaderInfoTitle . DATA_SET_ID . toString ( ) ) ) ; recordSizeInBytes = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . RECORD_BYTES . toString ( ) ) ) ; numRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_RECORDS . toString ( ) ) ) ; numHeaderRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_HEADER_RECORDS . toString ( ) ) ) ; numDataRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_DATA_RECORDS . toString ( ) ) ) ; numDataRecordsDim = new Dimension ( this . numDataRecordsDimName , numDataRecords , true , true , false ) ; numArtificialDataRecords = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . NUM_ARTIFICIAL_DATA_RECORDS . toString ( ) ) ) ; this . headerSizeInBytes = this . numHeaderRecords * this . recordSizeInBytes ; if ( numRecords * ( ( long ) this . recordSizeInBytes ) != this . actualSize ) { throw new IOException ( "Invalid DMSP file: the number of records <" + this . numRecords + "> times the record size <" + this . recordSizeInBytes + "> does not equal the size of the file <" + this . actualSize + ">." ) ; } }


Input: Parse the processing / history information from the header . [CODESPLIT] private void handleProcessingInformation ( ) throws IOException { suborbitHistoryAtt = new Attribute ( this . suborbitHistoryAttName , headerInfo . get ( HeaderInfoTitle . SUBORBIT_HISTORY . toString ( ) ) ) ; processingSystemAtt = new Attribute ( this . processingSystemAttName , headerInfo . get ( HeaderInfoTitle . PROCESSING_SYSTEM . toString ( ) ) ) ; String processingDateString = headerInfo . get ( HeaderInfoTitle . PROCESSING_DATE . toString ( ) ) ; try { processingDate = DateFormatHandler . ALT_DATE_TIME . getDateFromDateTimeString ( processingDateString ) ; } catch ( ParseException e ) { throw new IOException ( "Invalid DMSP file: processing date string <" + processingDateString + "> not parseable: " + e . getMessage ( ) ) ; } processingDateAtt = new Attribute ( this . processingDateAttName , DateFormatHandler . ISO_DATE_TIME . getDateTimeStringFromDate ( processingDate ) ) ; }


Input: Parse the satellite information from the header . [CODESPLIT] private void handleSatelliteInformation ( ) { spacecraftIdAtt = new Attribute ( this . spacecraftIdAttName , headerInfo . get ( HeaderInfoTitle . SPACECRAFT_ID . toString ( ) ) ) ; noradIdAtt = new Attribute ( this . noradIdAttName , headerInfo . get ( HeaderInfoTitle . NORAD_ID . toString ( ) ) ) ; }


Input: Parse the sensor information from the header . [CODESPLIT] private void handleSensorInformation ( ) { numSamplesPerBand = Integer . parseInt ( headerInfo . get ( HeaderInfoTitle . SAMPLES_PER_BAND . toString ( ) ) ) ; numSamplesPerBandDim = new Dimension ( this . numSamplesPerBandDimName , numSamplesPerBand ) ; // Read nominal resolution information nominalResolutionAtt = new Attribute ( nominalResolutionAttName , headerInfo . get ( HeaderInfoTitle . NOMINAL_RESOLUTION . toString ( ) ) ) ; // Read bands per scanlin information. bandsPerScanlineAtt = new Attribute ( bandsPerScanlineAttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BANDS_PER_SCANLINE . toString ( ) ) ) ) ; // Read bytes per smaple information bytesPerSampleAtt = new Attribute ( bytesPerSampleAttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BYTES_PER_SAMPLE . toString ( ) ) ) ) ; // Read byte offset for band 1 information. byteOffsetBand1Att = new Attribute ( byteOffsetBand1AttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BYTE_OFFSET_BAND_1 . toString ( ) ) ) ) ; // Read byte offset for band 2 information. byteOffsetBand2Att = new Attribute ( byteOffsetBand2AttName , Integer . valueOf ( headerInfo . get ( HeaderInfoTitle . BYTE_OFFSET_BAND_2 . toString ( ) ) ) ) ; // Band 1 description band1Att = new Attribute ( band1AttName , headerInfo . get ( HeaderInfoTitle . BAND_1 . toString ( ) ) ) ; // Band 2 description band2Att = new Attribute ( band2AttName , headerInfo . get ( HeaderInfoTitle . BAND_2 . toString ( ) ) ) ; // Band organization bandOrganizationAtt = new Attribute ( bandOrganizationAttName , headerInfo . get ( HeaderInfoTitle . ORGANIZATION . toString ( ) ) ) ; // thermal offset thermalOffsetAtt = new Attribute ( thermalOffsetAttName , headerInfo . get ( HeaderInfoTitle . THERMAL_OFFSET . toString ( ) ) ) ; // thermal scale thermalScaleAtt = new Attribute ( thermalScaleAttName , headerInfo . get ( HeaderInfoTitle . THERMAL_SCALE . toString ( ) ) ) ; // percent daylight percentDaylightAtt = new Attribute ( percentDaylightAttName , Double . valueOf ( headerInfo . get ( HeaderInfoTitle . PERCENT_DAYLIGHT . toString ( ) ) ) ) ; // percent full moon percentFullMoonAtt = new Attribute ( percentFullMoonAttName , Double . valueOf ( headerInfo . get ( HeaderInfoTitle . PERCENT_FULL_MOON . toString ( ) ) ) ) ; // percent terminator evident percentTerminatorEvidentAtt = new Attribute ( percentTerminatorEvidentAttName , Double . valueOf ( headerInfo . get ( HeaderInfoTitle . PERCENT_TERMINATOR_EVIDENT . toString ( ) ) ) ) ; }


Input: Return a string containing the header name / value pairs . [CODESPLIT] protected String headerInfoDump ( ) { StringBuilder retVal = new StringBuilder ( ) ; for ( String curHeaderTitle : this . headerInfo . keySet ( ) ) { String curHeaderValue = this . headerInfo . get ( curHeaderTitle ) ; retVal . append ( curHeaderTitle ) ; retVal . append ( ":::::" ) ; retVal . append ( curHeaderValue ) ; retVal . append ( ":::::\n" ) ; } return ( retVal . toString ( ) ) ; }


Input: Read an XML Document from a URL and return the root element . [CODESPLIT] static public Element readRootElement ( String location ) throws IOException { org . jdom2 . Document doc ; try { SAXBuilder builder = new SAXBuilder ( ) ; doc = builder . build ( location ) ; } catch ( JDOMException e ) { throw new IOException ( e . getMessage ( ) ) ; } return doc . getRootElement ( ) ; }


Input: Make sure that text is XML safe [CODESPLIT] static public String cleanCharacterData ( String text ) { if ( text == null ) return null ; boolean bad = false ; for ( int i = 0 , len = text . length ( ) ; i < len ; i ++ ) { int ch = text . charAt ( i ) ; if ( ! org . jdom2 . Verifier . isXMLCharacter ( ch ) ) { bad = true ; break ; } } if ( ! bad ) return text ; StringBuilder sbuff = new StringBuilder ( text . length ( ) ) ; for ( int i = 0 , len = text . length ( ) ; i < len ; i ++ ) { int ch = text . charAt ( i ) ; if ( org . jdom2 . Verifier . isXMLCharacter ( ch ) ) sbuff . append ( ( char ) ch ) ; } return sbuff . toString ( ) ; }


Input: Check if this is a valid file for this IOServiceProvider . [CODESPLIT] public boolean isValidFile ( RandomAccessFile raf ) throws IOException { raf . seek ( 0 ) ; int n = MAGIC . length ( ) ; if ( raf . length ( ) < n ) { return false ; } String got = raf . readString ( n ) ; return ( pMAGIC . matcher ( got ) . find ( ) || pMAGIC_OLD . matcher ( got ) . find ( ) ) ; }


Input: Open existing file and populate ncfile with it . This method is only called by the NetcdfFile constructor on itself . The provided NetcdfFile object will be empty except for the location String and the IOServiceProvider associated with this NetcdfFile object . [CODESPLIT] public void open ( RandomAccessFile raf , NetcdfFile ncfile , CancelTask cancelTask ) throws IOException { super . open ( raf , ncfile , cancelTask ) ; isExtended = checkFormat ( ) ; isoDateFormat = new SimpleDateFormat ( ) ; isoDateFormat . setTimeZone ( java . util . TimeZone . getTimeZone ( "GMT" ) ) ; isoDateFormat . applyPattern ( isExtended ? TIME_FORMAT_EX : TIME_FORMAT ) ; Sequence seq = makeSequence ( ncfile ) ; ncfile . addVariable ( null , seq ) ; addLightningGlobalAttributes ( ncfile ) ; ncfile . finish ( ) ; sm = seq . makeStructureMembers ( ) ; ArrayStructureBB . setOffsets ( sm ) ; }


Input:
Add the global attributes . [CODESPLIT] protected void addLightningGlobalAttributes ( NetcdfFile ncfile ) { super . addLightningGlobalAttributes ( ncfile ) ; ncfile . addAttribute ( null , new Attribute ( "title" , "USPLN Lightning Data" ) ) ; ncfile . addAttribute ( null , new Attribute ( "file_format" , "USPLN1 " + ( isExtended ? "(extended)" : "(original)" ) ) ) ; /*
    ncfile.addAttribute(null,
                        new Attribute("time_coverage_start",
                                      time_min + " " + secondsSince1970));
    ncfile.addAttribute(null,
                        new Attribute("time_coverage_end",
                                      time_max + " " + secondsSince1970));

    ncfile.addAttribute(null,
                        new Attribute("geospatial_lat_min",
                                      new Double(lat_min)));
    ncfile.addAttribute(null,
                        new Attribute("geospatial_lat_max",
                                      new Double(lat_max)));

    ncfile.addAttribute(null,
                        new Attribute("geospatial_lon_min",
                                      new Double(lon_min)));
    ncfile.addAttribute(null,
                        new Attribute("geospatial_lon_max",
                                      new Double(lon_max)));
    */ }


Input: Read all the data and return the number of strokes [CODESPLIT] private boolean checkFormat ( ) throws IOException { raf . seek ( 0 ) ; boolean extended = false ; while ( true ) { long offset = raf . getFilePointer ( ) ; String line = raf . readLine ( ) ; if ( line == null ) { break ; } if ( pMAGIC . matcher ( line ) . find ( ) || pMAGIC_OLD . matcher ( line ) . find ( ) ) { extended = pMAGIC_EX . matcher ( line ) . find ( ) ; break ; } } return extended ; }


Input:
Read all the data and return the number of strokes [CODESPLIT] int readAllData ( RandomAccessFile raf ) throws IOException , NumberFormatException , ParseException { ArrayList offsetList = new ArrayList ( ) ; java . text . SimpleDateFormat isoDateTimeFormat = new java . text . SimpleDateFormat ( TIME_FORMAT ) ; isoDateTimeFormat . setTimeZone ( java . util . TimeZone . getTimeZone ( "GMT" ) ) ; lat_min = 1000.0 ; lat_max = - 1000.0 ; lon_min = 1000.0 ; lon_max = - 1000.0 ; time_min = Double . POSITIVE_INFINITY ; time_max = Double . NEGATIVE_INFINITY ; raf . seek ( 0 ) ; int count = 0 ; boolean knowExtended = false ; while ( true ) { long offset = raf . getFilePointer ( ) ; String line = raf . readLine ( ) ; if ( line == null ) { break ; } if ( pMAGIC . matcher ( line ) . find ( ) || pMAGIC_OLD . matcher ( line ) . find ( ) ) { if ( ! knowExtended ) { isExtended = pMAGIC_EX . matcher ( line ) . find ( ) ; if ( isExtended ) { isoDateTimeFormat . applyPattern ( TIME_FORMAT_EX ) ; } knowExtended = true ; } continue ; } // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,1             (original)
 // 2006-10-23T17:59:39,18.415434,-93.480526,-26.8,0.25,0.5,80   (extended)
 StringTokenizer stoker = new StringTokenizer ( line , ",\r\n" ) ; while ( stoker . hasMoreTokens ( ) ) { Date date = isoDateTimeFormat . parse ( stoker . nextToken ( ) ) ; double lat = Double . parseDouble ( stoker . nextToken ( ) ) ; double lon = Double . parseDouble ( stoker . nextToken ( ) ) ; double amp = Double . parseDouble ( stoker . nextToken ( ) ) ; int nstrokes = 1 ; double axisMaj = Double . NaN ; double axisMin = Double . NaN ; int orient = 0 ; if ( isExtended ) { axisMaj = Double . parseDouble ( stoker . nextToken ( ) ) ; axisMin = Double . parseDouble ( stoker . nextToken ( ) ) ; orient = Integer . parseInt ( stoker . nextToken ( ) ) ; } else { nstrokes = Integer . parseInt ( stoker . nextToken ( ) ) ; } Stroke s = isExtended ? new Stroke ( date , lat , lon , amp , axisMaj , axisMin , orient ) : new Stroke ( date , lat , lon , amp , nstrokes ) ; lat_min = Math . min ( lat_min , s . lat ) ; lat_max = Math . max ( lat_max , s . lat ) ; lon_min = Math . min ( lon_min , s . lon ) ; lon_max = Math . max ( lon_max , s . lon ) ; time_min = Math . min ( time_min , s . secs ) ; time_max = Math . max ( time_max , s . secs ) ; } offsetList . add ( new Long ( offset ) ) ; count ++ ; } offsets = new long [ count ] ; for ( int i = 0 ; i < offsetList . size ( ) ; i ++ ) { Long off = ( Long ) offsetList . get ( i ) ; offsets [ i ] = off . longValue ( ) ; } //System.out.println("processed " + count + " records");
 return count ; }


Input: Read data from a top level Variable and return a memory resident Array . This Array has the same element type as the Variable and the requested shape . [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { return new ArraySequence ( sm , getStructureIterator ( null , 0 ) , nelems ) ; }


Input: Given a string that contains WWW escape sequences translate those escape sequences back into ASCII characters . Return the modified string . [CODESPLIT] private static String xunescapeString ( String in , char escape , boolean spaceplus ) { try { if ( in == null ) return null ; byte [ ] utf8 = in . getBytes ( utf8Charset ) ; byte escape8 = ( byte ) escape ; byte [ ] out = new byte [ utf8 . length ] ; // Should be max we need int index8 = 0 ; for ( int i = 0 ; i < utf8 . length ; ) { byte b = utf8 [ i ++ ] ; if ( b == plus && spaceplus ) { out [ index8 ++ ] = blank ; } else if ( b == escape8 ) { // check to see if there are enough characters left if ( i + 2 <= utf8 . length ) { b = ( byte ) ( fromHex ( utf8 [ i ] ) << 4 | fromHex ( utf8 [ i + 1 ] ) ) ; i += 2 ; } } out [ index8 ++ ] = b ; } return new String ( out , 0 , index8 , utf8Charset ) ; } catch ( Exception e ) { return in ; } }


Input: Define the DEFINITIVE URL constraint expression escape function . [CODESPLIT] public static String escapeURLQuery ( String ce ) { try { ce = escapeString ( ce , _allowableInUrlQuery ) ; } catch ( Exception e ) { ce = null ; } return ce ; }


Input: Define the DEFINITIVE URL constraint expression unescape function . [CODESPLIT] public static String unescapeURLQuery ( String ce ) { try { ce = unescapeString ( ce ) ; } catch ( Exception e ) { ce = null ; } return ce ; }


Input: Define the DEFINITIVE URL BACKSLASH unescape function . [CODESPLIT] public static String backslashDecode ( String s ) { StringBuilder buf = new StringBuilder ( s ) ; int i = 0 ; while ( i < buf . length ( ) ) { if ( buf . charAt ( i ) == ' ' ) { buf . deleteCharAt ( i ) ; } i ++ ; } return buf . toString ( ) ; }


Input: Define the DEFINITIVE URL BACKSLASH escape function . [CODESPLIT] public static String backslashEncode ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = buf . charAt ( i ) ; if ( _MustBackslashEscape . indexOf ( c ) >= 0 ) buf . append ( _BACKSLASHEscape ) ; buf . append ( ( char ) c ) ; } return buf . toString ( ) ; }


Input: Make lightning variables @param ncfile the netCDF file @param group the group ( may be null ) @param seq the sequence to add to @param name variable name @param dataType the data type @param dims dimenstion names @param longName the long_name attribute value ( a description ) @param cfName the CF standard_name attribute value ( may be null ) @param units the units attribute value ( if null not added ) @param type coordinate axis type units ( if null not added ) [CODESPLIT] protected Variable makeLightningVariable ( NetcdfFile ncfile , Group group , Structure seq , String name , DataType dataType , String dims , String longName , String cfName , String units , AxisType type ) { Variable v = new Variable ( ncfile , group , seq , name ) ; v . setDataType ( dataType ) ; v . setDimensions ( dims ) ; v . addAttribute ( new Attribute ( CDM . LONG_NAME , longName ) ) ; if ( cfName != null ) { v . addAttribute ( new Attribute ( CF . STANDARD_NAME , cfName ) ) ; } if ( units != null ) { v . addAttribute ( new Attribute ( CDM . UNITS , units ) ) ; } if ( type != null ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , type . toString ( ) ) ) ; } return v ; }


Input: Add the global attributes . Specific implementations should call super and then add their own . [CODESPLIT] protected void addLightningGlobalAttributes ( NetcdfFile ncfile ) { ncfile . addAttribute ( null , new Attribute ( CF . FEATURE_TYPE , CF . FeatureType . point . toString ( ) ) ) ; ncfile . addAttribute ( null , new Attribute ( CDM . HISTORY , "Read directly by Netcdf Java IOSP" ) ) ; }


Input: res . setHeader ( Content - Disposition attachment ; filename = + path + . nc ) ; [CODESPLIT] public static String setContentDispositionValue ( String filename , String suffix ) { int pos = filename . lastIndexOf ( ' ' ) ; String outname = ( pos > 0 ) ? filename . substring ( pos + 1 ) : filename ; int pos2 = outname . lastIndexOf ( ' ' ) ; outname = ( pos > 0 ) ? outname . substring ( 0 , pos2 ) : outname ; outname = outname + suffix ; return setContentDispositionValue ( outname ) ; }


Input:
Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printDecl ( PrintWriter os , String space , boolean print_semi , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType // and all of the different signatures of printDecl() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. boolean isSingle = false ; boolean isStructure = false ; boolean isGrid = false ; boolean psemi = true ; //os.println("The grid contains "+projectedComponents(true)+" projected components"); if ( constrained && projectedComponents ( true ) == 0 ) return ; // If we are printing the declaration of a constrained Grid then check for // the case where the projection removes all but one component; the // resulting object is a simple array. // 2013-2-26: Heimbigner : this is incorrect, even single // projected components should be in a structure. /* Wrong
            if (constrained && projectedComponents(true) == 1) {
            //os.println("It's a single Array.");
            isSingle = true;
            psemi = print_semi;
        } */ // If there are M (< N) components (Array and Maps combined) in a N // component Grid, send the M components as elements of a Structure. // This will preserve the grouping without violating the rules for a // Grid. else if ( constrained && ! projectionYieldsGrid ( true ) ) { //os.println("It's a Structure."); isStructure = true ; } else { // The number of elements in the (projected) Grid must be such that // we have a valid Grid object; send it as such. //os.println("It's a Grid."); isGrid = true ; } if ( isGrid ) os . println ( space + getTypeName ( ) + " {" ) ; if ( isGrid ) os . println ( space + " ARRAY:" ) ; if ( isStructure ) os . println ( space + "Structure {" ) ; ( ( SDArray ) arrayVar ) . printDecl ( os , space + "    " , psemi , constrained ) ; if ( isGrid ) os . println ( space + " MAPS:" ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { SDArray sda = ( SDArray ) e . nextElement ( ) ; sda . printDecl ( os , space + "    " , psemi , constrained ) ; } if ( isStructure || isGrid ) { os . print ( space + "} " + getEncodedName ( ) ) ; if ( print_semi ) os . println ( ";" ) ; } return ; }


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 .

 Important Note
 This method overrides the BaseType method of the same name and type signature and it significantly changes the behavior for all versions of  printVal ()  for this type :   All the various versions of printVal () will only print a value or a value with declaration if the variable is in the projection .

 In other words if a call to  isProject ()  for a particular variable returns  true then  printVal ()  will print a value ( or a declaration and a value ) .

 If  isProject ()  for a particular variable returns  false then  printVal ()  is basically a No - Op .

 [CODESPLIT] public void printVal ( PrintWriter os , String space , boolean print_decl_p ) { if ( ! isProject ( ) ) return ; //System.out.println("\nSome Part of this object is projected..."); if ( print_decl_p ) { printDecl ( os , space , false , true ) ; os . print ( " = " ) ; } boolean isStillGrid = projectionYieldsGrid ( true ) ; os . print ( "{ " ) ; if ( isStillGrid ) os . print ( "ARRAY: " ) ; if ( ( ( SDArray ) arrayVar ) . isProject ( ) ) arrayVar . printVal ( os , "" , false ) ; if ( isStillGrid ) os . print ( " MAPS: " ) ; boolean firstPass = true ; Enumeration e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { SDArray sda = ( SDArray ) e . nextElement ( ) ; if ( ( ( SDArray ) sda ) . isProject ( ) ) { if ( ! firstPass ) os . print ( ", " ) ; sda . printVal ( os , "" , false ) ; firstPass = false ; } } os . print ( " }" ) ; if ( print_decl_p ) os . println ( ";" ) ; }


Input: Set the state of this variable s projection . <code > true< / code > means that this variable is part of the current projection as defined by the current constraint expression otherwise the current projection for this variable should be <code > false< / code > . [CODESPLIT] @ Override public void setProject ( boolean state , boolean all ) { setProjected ( state ) ; if ( all ) { // System.out.println("SDGrid:setProject: Blindly setting Project"); ( ( SDArray ) arrayVar ) . setProject ( state ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; sm . setProject ( state ) ; } } }


Input: Server - side serialization for OPeNDAP variables ( sub - classes of <code > BaseType< / code > ) . This does not send the entire class as the Java <code > Serializable< / code > interface does rather it sends only the binary data values . Other software is responsible for sending variable type information ( see <code > DDS< / code > ) . <p / > Writes data to a <code > DataOutputStream< / code > . This method is used on the server side of the OPeNDAP client / server connection and possibly by GUI clients which need to download OPeNDAP data manipulate it and then re - save it as a binary file . [CODESPLIT] public void serialize ( String dataset , DataOutputStream sink , CEEvaluator ce , Object specialO ) throws NoSuchVariableException , DAP2ServerSideException , IOException { if ( ! isRead ( ) ) read ( dataset , specialO ) ; if ( ce . evalClauses ( specialO ) ) { if ( ( ( ServerMethods ) arrayVar ) . isProject ( ) ) ( ( ServerMethods ) arrayVar ) . serialize ( dataset , sink , ce , specialO ) ; for ( Enumeration e = mapVars . elements ( ) ; e . hasMoreElements ( ) ; ) { ServerMethods sm = ( ServerMethods ) e . nextElement ( ) ; if ( sm . isProject ( ) ) sm . serialize ( dataset , sink , ce , specialO ) ; } } }


Input: Set the projection information for this dimension . The internal <code > DArray< / code > is retrieved and then the <code > DArrayDimension< / code > associated with the <code > dimension< / code > specified is retrieved and the <code > start< / code > <code > stride< / code > and <code > stop< / code > parameters are passed to its <code > setProjection () < / code > method . [CODESPLIT] public void setProjection ( int dimension , int start , int stride , int stop ) throws InvalidDimensionException , SBHException { try { DArray a = ( DArray ) getVar ( 0 ) ; DArrayDimension d = a . getDimension ( dimension ) ; d . setProjection ( start , stride , stop ) ; DArray map = ( DArray ) getVar ( dimension + 1 ) ; DArrayDimension mapD = map . getDimension ( 0 ) ; mapD . setProjection ( start , stride , stop ) ; } catch ( NoSuchVariableException e ) { throw new InvalidDimensionException ( "SDGrid.setProjection(): Bad Value for dimension!: " + e . getMessage ( ) ) ; } }


Input: Gets the <b > start< / b > value for the projection of the <code > dimension< / code > indicated . The parameter <code > dimension< / code > is checked against the instance of the <code > SDArray< / code > for bounds violation . [CODESPLIT] public int getStart ( int dimension ) throws InvalidDimensionException { try { DArray a = ( DArray ) getVar ( 0 ) ; DArrayDimension d = a . getDimension ( dimension ) ; return ( d . getStart ( ) ) ; } catch ( NoSuchVariableException e ) { throw new InvalidDimensionException ( "SDGrid.getStart(): Bad Value for dimension!: " + e . getMessage ( ) ) ; } }


Input: Write the variable s declaration in a C - style syntax . This function is used to create textual representation of the Data Descriptor Structure ( DDS ) . See <em > The OPeNDAP User Manual< / em > for information about this structure . [CODESPLIT] public void printXML ( PrintWriter pw , String pad , boolean constrained ) { // BEWARE! Since printDecl()is (multiple) overloaded in BaseType // and all of the different signatures of printDecl() in BaseType // lead to one signature, we must be careful to override that // SAME signature here. That way all calls to printDecl() for // this object lead to this implementation. boolean isSingle = false ; boolean isStructure = false ; boolean isGrid = false ; boolean psemi = true ; //os.println("The gird contains "+projectedComponents(true)+" projected components"); if ( constrained && projectedComponents ( true ) == 0 ) return ; // If we are printing the declaration of a constrained Grid then check for // the case where the projection removes all but one component; the // resulting object is a simple array. if ( constrained && projectedComponents ( true ) == 1 ) { //os.println("It's a single Array."); isSingle = true ; } // If there are M (< N) componets (Array and Maps combined) in a N // component Grid, send the M components as elements of a Struture. // This will preserve the grouping without violating the rules for a // Grid. else if ( constrained && ! projectionYieldsGrid ( true ) ) { //os.println("It's a Structure."); isStructure = true ; } else { // The number of elements in the (projected) Grid must be such that // we have a valid Grid object; send it as such. //os.println("It's a Grid."); isGrid = true ; } if ( isGrid ) { pw . print ( pad + "<Grid " ) ; if ( getEncodedName ( ) != null ) { pw . print ( " name=\"" + DDSXMLParser . normalizeToXML ( getEncodedName ( ) ) + "\"" ) ; } pw . println ( ">" ) ; } if ( isStructure ) { pw . print ( pad + "<Structure" ) ; if ( getEncodedName ( ) != null ) { pw . print ( " name=\"" + DDSXMLParser . normalizeToXML ( getEncodedName ( ) ) + "\"" ) ; } pw . println ( ">" ) ; } Enumeration e = getAttributeNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; Attribute a = getAttribute ( aName ) ; if ( a != null ) a . printXML ( pw , pad + "\t" , constrained ) ; } ( ( SDArray ) arrayVar ) . printXML ( pw , pad + ( isSingle ? "" : "\t" ) , constrained ) ; if ( isGrid ) { e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { SDArray map = ( SDArray ) e . nextElement ( ) ; //Coverity[DEADCODE] map . printAsMapXML ( pw , pad + ( isSingle ? "" : "\t" ) , constrained ) ; } } else { e = mapVars . elements ( ) ; while ( e . hasMoreElements ( ) ) { SDArray sda = ( SDArray ) e . nextElement ( ) ; sda . printXML ( pw , pad + ( isSingle ? "" : "\t" ) , constrained ) ; } } if ( isStructure ) { pw . println ( pad + "</Structure>" ) ; } else if ( isGrid ) { pw . println ( pad + "</Grid>" ) ; } return ; }


Input:
Returns the short resulting from swapping 2 bytes at a specified offset in a byte array . [CODESPLIT] static public short swapShort ( byte [ ] b , int offset ) { // 2 bytes
 int low = b [ offset ] & 0xff ; int high = b [ offset + 1 ] & 0xff ; return ( short ) ( high << 8 | low ) ; }


Input:
Returns the int resulting from reversing 4 bytes at a specified offset in a byte array . [CODESPLIT] static public int swapInt ( byte [ ] b , int offset ) { // 4 bytes
 int accum = 0 ; for ( int shiftBy = 0 , i = offset ; shiftBy < 32 ; shiftBy += 8 , i ++ ) { accum |= ( b [ i ] & 0xff ) << shiftBy ; } return accum ; }


Input: Returns the double resulting from reversing 8 bytes at a specified offset in a byte array . [CODESPLIT] static public double swapDouble ( byte [ ] b , int offset ) { long accum = 0 ; long shiftedval ; for ( int shiftBy = 0 , i = offset ; shiftBy < 64 ; shiftBy += 8 , i ++ ) { shiftedval = ( ( long ) ( b [ i ] & 0xff ) ) << shiftBy ; accum |= shiftedval ; } return Double . longBitsToDouble ( accum ) ; }


Input: Returns the float resulting from reversing 4 bytes of a specified float . [CODESPLIT] static public float swapFloat ( float v ) { int l = swapInt ( Float . floatToIntBits ( v ) ) ; return ( Float . intBitsToFloat ( l ) ) ; }


Input: Returns the double resulting from reversing 8 bytes of a specified double . [CODESPLIT] static public double swapDouble ( double v ) { long l = swapLong ( Double . doubleToLongBits ( v ) ) ; return ( Double . longBitsToDouble ( l ) ) ; }


Input: Convert a short to an array of 2 bytes . [CODESPLIT] static public byte [ ] shortToBytes ( short v ) { byte [ ] b = new byte [ 2 ] ; int allbits = 255 ; for ( int i = 0 ; i < 2 ; i ++ ) { b [ 1 - i ] = ( byte ) ( ( v & ( allbits << i * 8 ) ) >> i * 8 ) ; } return b ; }


Input: Convert an int to an array of 4 bytes . [CODESPLIT] static public byte [ ] intToBytes ( int v ) { byte [ ] b = new byte [ 4 ] ; int allbits = 255 ; for ( int i = 0 ; i < 4 ; i ++ ) { b [ 3 - i ] = ( byte ) ( ( v & ( allbits << i * 8 ) ) >> i * 8 ) ; } return b ; }


Input: Convert a long to an array of 8 bytes . [CODESPLIT] static public byte [ ] longToBytes ( long v ) { byte [ ] b = new byte [ 8 ] ; long allbits = 255 ; for ( int i = 0 ; i < 8 ; i ++ ) { b [ 7 - i ] = ( byte ) ( ( v & ( allbits << i * 8 ) ) >> i * 8 ) ; } return b ; }


Input: Read the data { @link ucar . ma2 . Array } from the variable at the specified time index if applicable . If the variable does not have a time dimension the data array will have the same rank as the Variable . If the variable has a time dimension the data array will have rank - 1 . [CODESPLIT] protected Array readArray ( Variable v , int timeIndex ) throws IOException , InvalidRangeException { int [ ] shape = v . getShape ( ) ; int [ ] origin = new int [ v . getRank ( ) ] ; if ( getTimeDimension ( ) != null ) { int dimIndex = v . findDimensionIndex ( getTimeDimension ( ) . getShortName ( ) ) ; if ( dimIndex >= 0 ) { shape [ dimIndex ] = 1 ; origin [ dimIndex ] = timeIndex ; return v . read ( origin , shape ) . reduce ( dimIndex ) ; } } return v . read ( origin , shape ) ; }