Input:
Is this a valid file? [CODESPLIT] @ Override public boolean isValidFile ( RandomAccessFile raf ) throws IOException { if ( ! super . isValidFile ( raf ) ) { return false ; } // TODO:  handle other types of surface files
 return gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . MERGED ) || gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . UNMERGED ) ; }


Input: Read the data for the variable [CODESPLIT] public Array readData ( Variable v2 , Section section ) throws IOException , InvalidRangeException { if ( gemreader == null ) { throw new IllegalStateException ( "reader not initialized" ) ; } return readSoundingData ( v2 , section , gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . MERGED ) ) ; }


Input: Read in the data for the variable . In this case it should be a Structure . The section should be rank 2 ( station time ) . [CODESPLIT] private Array readSoundingData ( Variable v2 , Section section , boolean isMerged ) throws IOException { Array array = null ; if ( v2 instanceof Structure ) { Range stationRange = section . getRange ( 0 ) ; Range timeRange = section . getRange ( 1 ) ; int size = stationRange . length ( ) * timeRange . length ( ) ; Structure pdata = ( Structure ) v2 ; StructureMembers members = pdata . makeStructureMembers ( ) ; ArrayStructureBB . setOffsets ( members ) ; ArrayStructureBB abb = new ArrayStructureBB ( members , new int [ ] { size } ) ; ByteBuffer buf = abb . getByteBuffer ( ) ; for ( int stnIdx : stationRange ) { for ( int timeIdx : timeRange ) { List < String > parts = ( isMerged ) ? ( ( GempakSoundingFileReader ) gemreader ) . getMergedParts ( ) : ( ( GempakSoundingFileReader ) gemreader ) . getUnmergedParts ( ) ; boolean allMissing = true ; for ( String part : parts ) { List < GempakParameter > params = gemreader . getParameters ( part ) ; GempakFileReader . RData vals = gemreader . DM_RDTR ( timeIdx + 1 , stnIdx + 1 , part ) ; ArraySequence aseq ; Sequence seq = ( Sequence ) pdata . findVariable ( part ) ; if ( vals == null ) { aseq = makeEmptySequence ( seq ) ; } else { allMissing = false ; aseq = makeArraySequence ( seq , params , vals . data ) ; } int index = abb . addObjectToHeap ( aseq ) ; buf . putInt ( index ) ; } buf . put ( ( byte ) ( allMissing ? 1 : 0 ) ) ; } } array = abb ; } return array ; }


Input: Create an empty ArraySequence for missing data [CODESPLIT] private ArraySequence makeEmptySequence ( Sequence seq ) { StructureMembers members = seq . makeStructureMembers ( ) ; return new ArraySequence ( members , new EmptyStructureDataIterator ( ) , - 1 ) ; }


Input: Create an ArraySequence to hold the data [CODESPLIT] private ArraySequence makeArraySequence ( Sequence seq , List < GempakParameter > params , float [ ] values ) { if ( values == null ) { return makeEmptySequence ( seq ) ; } int numLevels = values . length / params . size ( ) ; StructureMembers members = seq . makeStructureMembers ( ) ; int offset = ArrayStructureBB . setOffsets ( members ) ; int size = offset * numLevels ; byte [ ] bytes = new byte [ size ] ; ByteBuffer buf = ByteBuffer . wrap ( bytes ) ; ArrayStructureBB abb = new ArrayStructureBB ( members , new int [ ] { numLevels } , buf , 0 ) ; int var = 0 ; for ( int i = 0 ; i < numLevels ; i ++ ) { for ( GempakParameter param : params ) { if ( members . findMember ( param . getName ( ) ) != null ) { buf . putFloat ( values [ var ] ) ; } var ++ ; } } return new ArraySequence ( members , new SequenceIterator ( numLevels , abb ) , numLevels ) ; }


Input: Build the netCDF file [CODESPLIT] protected void fillNCFile ( ) throws IOException { String fileType = gemreader . getFileSubType ( ) ; buildFile ( fileType . equals ( GempakSoundingFileReader . MERGED ) ) ; }


Input:
Build a standard station structure [CODESPLIT] private void buildFile ( boolean isMerged ) { // Build station list
 List < GempakStation > stations = gemreader . getStations ( ) ; Dimension station = new Dimension ( "station" , stations . size ( ) , true ) ; ncfile . addDimension ( null , station ) ; ncfile . addDimension ( null , DIM_LEN8 ) ; ncfile . addDimension ( null , DIM_LEN4 ) ; ncfile . addDimension ( null , DIM_LEN2 ) ; List < Variable > stationVars = makeStationVars ( stations , station ) ; // loop through and add to ncfile
 for ( Variable stnVar : stationVars ) { ncfile . addVariable ( null , stnVar ) ; } // Build variable list (var(station,time))
 // time
 List < Date > timeList = gemreader . getDates ( ) ; int numTimes = timeList . size ( ) ; Dimension times = new Dimension ( TIME_VAR , numTimes , true ) ; ncfile . addDimension ( null , times ) ; Array varArray ; Variable timeVar = new Variable ( ncfile , null , null , TIME_VAR , DataType . DOUBLE , TIME_VAR ) ; timeVar . addAttribute ( new Attribute ( CDM . UNITS , "seconds since 1970-01-01 00:00:00" ) ) ; timeVar . addAttribute ( new Attribute ( "long_name" , TIME_VAR ) ) ; varArray = new ArrayDouble . D1 ( numTimes ) ; int i = 0 ; for ( Date date : timeList ) { ( ( ArrayDouble . D1 ) varArray ) . set ( i , date . getTime ( ) / 1000.d ) ; i ++ ; } timeVar . setCachedData ( varArray , false ) ; ncfile . addVariable ( null , timeVar ) ; // build the data structure
 List < Dimension > stationTime = new ArrayList <> ( ) ; stationTime . add ( station ) ; stationTime . add ( times ) ; String structName = ( isMerged ) ? GempakSoundingFileReader . MERGED : GempakSoundingFileReader . UNMERGED ; structName = structName + "Sounding" ; Structure sVar = new Structure ( ncfile , null , null , structName ) ; sVar . setDimensions ( stationTime ) ; sVar . addAttribute ( new Attribute ( CF . COORDINATES , "time SLAT SLON SELV" ) ) ; List < String > sequenceNames ; if ( isMerged ) { sequenceNames = new ArrayList <> ( ) ; sequenceNames . add ( GempakSoundingFileReader . SNDT ) ; } else { sequenceNames = ( ( GempakSoundingFileReader ) gemreader ) . getUnmergedParts ( ) ; } for ( String seqName : sequenceNames ) { Sequence paramData = makeSequence ( sVar , seqName , false ) ; if ( paramData == null ) { continue ; } sVar . addMemberVariable ( paramData ) ; } sVar . addMemberVariable ( makeMissingVariable ( ) ) ; ncfile . addAttribute ( null , new Attribute ( "CF:featureType" , CF . FeatureType . timeSeriesProfile . toString ( ) ) ) ; ncfile . addVariable ( null , sVar ) ; }


Input: Make a Sequence for the part [CODESPLIT] protected Sequence makeSequence ( Structure parent , String partName , boolean includeMissing ) { List < GempakParameter > params = gemreader . getParameters ( partName ) ; if ( params == null ) { return null ; } Sequence sVar = new Sequence ( ncfile , null , parent , partName ) ; sVar . setDimensions ( "" ) ; for ( GempakParameter param : params ) { Variable v = makeParamVariable ( param , null ) ; addVerticalCoordAttribute ( v ) ; sVar . addMemberVariable ( v ) ; } if ( includeMissing ) { sVar . addMemberVariable ( makeMissingVariable ( ) ) ; } return sVar ; }


Input: Add the vertical coordinate variables if necessary [CODESPLIT] private void addVerticalCoordAttribute ( Variable v ) { GempakSoundingFileReader gsfr = ( GempakSoundingFileReader ) gemreader ; int vertType = gsfr . getVerticalCoordinate ( ) ; String pName = v . getFullName ( ) ; if ( gemreader . getFileSubType ( ) . equals ( GempakSoundingFileReader . MERGED ) ) { if ( ( vertType == GempakSoundingFileReader . PRES_COORD ) && pName . equals ( "PRES" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Pressure . name ( ) ) ) ; } else if ( ( vertType == GempakSoundingFileReader . HGHT_COORD ) && ( pName . equals ( "HGHT" ) || pName . equals ( "MHGT" ) || pName . equals ( "DHGT" ) ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Height . name ( ) ) ) ; } } else if ( pName . equals ( "PRES" ) ) { v . addAttribute ( new Attribute ( _Coordinate . AxisType , AxisType . Pressure . name ( ) ) ) ; } }


Input: This allows the possibility of reading a catalog in another thread . The default implementation does not do that but a subclass may override and implement . If the catalog is read successfully it is passed on to the callback . [CODESPLIT] public void readXMLasynch ( String uriString , CatalogSetCallback callback ) { InvCatalogImpl cat = readXML ( uriString ) ; callback . setCatalog ( cat ) ; }


Input:
Create an InvCatalog from an XML document at a named URI . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( String uriString ) { URI uri ; try { uri = new URI ( uriString ) ; } catch ( URISyntaxException e ) { InvCatalogImpl cat = new InvCatalogImpl ( uriString , null , null ) ; cat . appendErrorMessage ( "**Fatal:  InvCatalogFactory.readXML URISyntaxException on URL (" + uriString + ") " + e . getMessage ( ) + "\n" , true ) ; return cat ; } /* if (uriString.startsWith("file:")) {
      String filename = uriString.substring(5);
      File f = new File(filename);
      if (f.exists()) {
        try {
          return readXML(new FileInputStream(f), uri);

        } catch (Exception e) {
          InvCatalogImpl cat = new InvCatalogImpl(uriString, null, null);
          cat.appendErrorMessage("**Fatal:  InvCatalogFactory.readXML error (" +
              uriString + ") " + e.getMessage() + "\n", true);
        }
      }
    }  */ return readXML ( uri ) ; }


Input: Read an InvCatalog from an a URI . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( URI uri ) { // get ready for XML parsing warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; org . jdom2 . Document jdomDoc ; InputStream is = null ; try { jdomDoc = saxBuilder . build ( uri . toURL ( ) ) ; //      HttpUriResolver httpUriResolver = HttpUriResolver.newDefaultUriResolver(); //      String s = httpUriResolver.getString( url ); //      //StringReader //      is = new BufferedInputStream( httpUriResolver.getInputStream( url ), 1000000 ); //      jdomDoc = saxBuilder.build( is ); } catch ( Exception e ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , null ) ; cat . appendErrorMessage ( "**Fatal:  InvCatalogFactory.readXML failed" + "\n Exception= " + e . getClass ( ) . getName ( ) + " " + e . getMessage ( ) + "\n fatalMessages= " + fatalMessages . toString ( ) + "\n errMessages= " + errMessages . toString ( ) + "\n warnMessages= " + warnMessages . toString ( ) + "\n" , true ) ; return cat ; } finally { if ( is != null ) try { is . close ( ) ; } catch ( IOException e ) { log . warn ( "Failed to close input stream [" + uri . toString ( ) + "]." ) ; } } if ( fatalMessages . length ( ) > 0 ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , null ) ; cat . appendErrorMessage ( "**Fatal:  InvCatalogFactory.readXML XML Fatal error(s) =\n" + fatalMessages . toString ( ) + "\n" , true ) ; return cat ; } return readXML ( jdomDoc , uri ) ; }


Input: Create an InvCatalog by reading catalog XML from a String . [CODESPLIT] public InvCatalogImpl readXML ( String catAsString , URI baseUri ) { return readXML ( new StringReader ( catAsString ) , baseUri ) ; }


Input: Create an InvCatalog by reading catalog XML from a StringReader . [CODESPLIT] public InvCatalogImpl readXML ( StringReader catAsStringReader , URI baseUri ) { XMLEntityResolver resolver = new XMLEntityResolver ( false ) ; SAXBuilder builder = resolver . getSAXBuilder ( ) ; Document inDoc ; try { inDoc = builder . build ( catAsStringReader ) ; } catch ( Exception e ) { InvCatalogImpl cat = new InvCatalogImpl ( baseUri . toString ( ) , null , null ) ; cat . appendErrorMessage ( "**Fatal:  InvCatalogFactory.readXML(String catAsString, URI url) failed:" + "\n  Exception= " + e . getClass ( ) . getName ( ) + " " + e . getMessage ( ) + "\n  fatalMessages= " + fatalMessages . toString ( ) + "\n  errMessages= " + errMessages . toString ( ) + "\n  warnMessages= " + warnMessages . toString ( ) + "\n" , true ) ; return cat ; } return readXML ( inDoc , baseUri ) ; }


Input: Create an InvCatalog from an InputStream . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( InputStream docIs , URI uri ) { // get ready for XML parsing warnMessages . setLength ( 0 ) ; errMessages . setLength ( 0 ) ; fatalMessages . setLength ( 0 ) ; org . jdom2 . Document jdomDoc ; try { jdomDoc = saxBuilder . build ( docIs ) ; } catch ( Exception e ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , uri ) ; cat . appendErrorMessage ( "**Fatal:  InvCatalogFactory.readXML failed" + "\n Exception= " + e . getClass ( ) . getName ( ) + " " + e . getMessage ( ) + "\n fatalMessages= " + fatalMessages . toString ( ) + "\n errMessages= " + errMessages . toString ( ) + "\n warnMessages= " + warnMessages . toString ( ) + "\n" , true ) ; return cat ; } if ( fatalMessages . length ( ) > 0 ) { InvCatalogImpl cat = new InvCatalogImpl ( uri . toString ( ) , null , uri ) ; cat . appendErrorMessage ( "**Fatal:  InvCatalogFactory.readXML XML Fatal error(s) =\n" + fatalMessages . toString ( ) + "\n" , true ) ; return cat ; } return readXML ( jdomDoc , uri ) ; }


Input:
Create an InvCatalog from a JDOM document . Failures and exceptions are handled by causing validate () to fail . Therefore be sure to call validate () before trying to use the InvCatalog object . [CODESPLIT] public InvCatalogImpl readXML ( org . jdom2 . Document jdomDoc , URI uri ) { // decide on converter based on namespace Element root = jdomDoc . getRootElement ( ) ; if ( ! root . getName ( ) . equalsIgnoreCase ( "catalog" ) ) { throw new IllegalArgumentException ( "not a catalog" ) ; } String namespace = root . getNamespaceURI ( ) ; InvCatalogConvertIF fac = converters . get ( namespace ) ; if ( fac == null ) { fac = defaultConverter ; // LOOK if ( debugVersion ) System . out . println ( "use default converter " + fac . getClass ( ) . getName ( ) + "; no namespace " + namespace ) ; } else if ( debugVersion ) System . out . println ( "use converter " + fac . getClass ( ) . getName ( ) + " based on namespace " + namespace ) ; InvCatalogImpl cat = fac . parseXML ( this , jdomDoc , uri ) ; cat . setCreateFrom ( uri . toString ( ) ) ; // cat.setCatalogFactory(this); //cat.setCatalogConverter(fac); cat . finish ( ) ; /* if (showCatalogXML) {
      System.out.println("*** catalog/showCatalogXML");
      try {
        writeXML(cat, System.out);
      }
      catch (IOException ex) {
        log.warn("Error writing catalog for debugging", ex);
      }
    }  */ if ( fatalMessages . length ( ) > 0 ) cat . appendErrorMessage ( fatalMessages . toString ( ) , true ) ; // makes it invalid if ( errMessages . length ( ) > 0 ) cat . appendErrorMessage ( errMessages . toString ( ) , false ) ; // doesnt make it invalid if ( warnMessages . length ( ) > 0 ) cat . appendErrorMessage ( warnMessages . toString ( ) , false ) ; // doesnt make it invalid return cat ; }


Input: Write the InvCatalogImpl to the OutputStream as a InvCatalog 1 . 0 document . [CODESPLIT] public void writeXML ( InvCatalogImpl catalog , OutputStream os , boolean raw ) throws IOException { InvCatalogConvertIF converter = this . getCatalogConverter ( XMLEntityResolver . CATALOG_NAMESPACE_10 ) ; converter . writeXML ( catalog , os , raw ) ; }


Input: / * Write the catalog as an XML document to the specified filename . [CODESPLIT] public void writeXML ( InvCatalogImpl catalog , String filename ) throws IOException { BufferedOutputStream os = new BufferedOutputStream ( new FileOutputStream ( filename ) ) ; writeXML ( catalog , os , false ) ; os . close ( ) ; }


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


Input: Find the MetadataConverterIF registered for this key [CODESPLIT] public MetadataConverterIF getMetadataConverter ( String key ) { if ( key == null ) return null ; return metadataConverters . get ( key ) ; }


Input: testing [CODESPLIT] private static InvCatalogImpl doOne ( InvCatalogFactory fac , String urlString , boolean show ) { System . out . println ( "***read " + urlString ) ; if ( show ) System . out . println ( " original catalog=\n" + IO . readURLcontents ( urlString ) ) ; try { InvCatalogImpl cat = fac . readXML ( new URI ( urlString ) ) ; StringBuilder buff = new StringBuilder ( ) ; boolean isValid = cat . check ( buff , false ) ; System . out . println ( "catalog <" + cat . getName ( ) + "> " + ( isValid ? "is" : "is not" ) + " valid" ) ; System . out . println ( " validation output=\n" + buff ) ; // if (show) System.out.println(" parsed catalog=\n" + fac.writeXML(cat)); //System.out.println(" -----\n"+cat.dump()); return cat ; } catch ( Exception e ) { e . printStackTrace ( ) ; return null ; } }


Input: Returns the identifiers associated with the dimensionless derived unit . [CODESPLIT] private static UnitName dimensionlessID ( ) { UnitName id ; try { id = UnitName . newUnitName ( "1" , "1" , "1" ) ; } catch ( final NameException e ) { id = null ; } return id ; }


Input: Multiplies this derived unit by another . [CODESPLIT] @ Override protected Unit myMultiplyBy ( final Unit that ) throws MultiplyException { Unit result ; if ( dimension . getRank ( ) == 0 ) { result = that ; } else { if ( ! ( that instanceof DerivedUnit ) ) { result = that . multiplyBy ( this ) ; } else { final UnitDimension thatDimension = ( ( DerivedUnit ) that ) . getDimension ( ) ; result = thatDimension . getRank ( ) == 0 ? this : new DerivedUnitImpl ( dimension . multiplyBy ( thatDimension ) ) ; } } return result ; }


Input: Divides this derived unit by another . [CODESPLIT] @ Override protected Unit myDivideBy ( final Unit that ) throws OperationException { Unit result ; if ( dimension . getRank ( ) == 0 ) { result = that . raiseTo ( - 1 ) ; } else { if ( ! ( that instanceof DerivedUnit ) ) { result = that . divideInto ( this ) ; } else { final UnitDimension thatDimension = ( ( DerivedUnit ) that ) . getDimension ( ) ; result = thatDimension . getRank ( ) == 0 ? this : new DerivedUnitImpl ( dimension . divideBy ( thatDimension ) ) ; } } return result ; }


Input: Converts numerical values from this unit to the derived unit . Obviously the numerical values are unchanged . [CODESPLIT] public final float [ ] toDerivedUnit ( final float [ ] input , final float [ ] output ) { if ( input != output ) { System . arraycopy ( input , 0 , output , 0 , input . length ) ; } return output ; }


Input: Indicates if values in this unit are convertible with another unit . [CODESPLIT] @ Override public final boolean isCompatible ( final Unit that ) { final DerivedUnit unit = that . getDerivedUnit ( ) ; return equals ( unit ) || isReciprocalOf ( unit ) ; }


Input: Tests this class . [CODESPLIT] public static void main ( final String [ ] args ) throws Exception { final BaseUnit second = BaseUnit . getOrCreate ( UnitName . newUnitName ( "second" , null , "s" ) , BaseQuantity . TIME ) ; System . out . println ( "second = \"" + second + ' ' ) ; final BaseUnit meter = BaseUnit . getOrCreate ( UnitName . newUnitName ( "meter" , null , "m" ) , BaseQuantity . LENGTH ) ; System . out . println ( "meter = \"" + meter + ' ' ) ; final DerivedUnitImpl meterSecond = ( DerivedUnitImpl ) meter . myMultiplyBy ( second ) ; System . out . println ( "meterSecond = \"" + meterSecond + ' ' ) ; final DerivedUnitImpl meterPerSecond = ( DerivedUnitImpl ) meter . myDivideBy ( second ) ; System . out . println ( "meterPerSecond = \"" + meterPerSecond + ' ' ) ; final DerivedUnitImpl secondPerMeter = ( DerivedUnitImpl ) second . myDivideBy ( meter ) ; System . out . println ( "secondPerMeter = \"" + secondPerMeter + ' ' ) ; System . out . println ( "meterPerSecond.isReciprocalOf(secondPerMeter)=" + meterPerSecond . isReciprocalOf ( secondPerMeter ) ) ; System . out . println ( "meter.toDerivedUnit(1.0)=" + meter . toDerivedUnit ( 1.0 ) ) ; System . out . println ( "meter.toDerivedUnit(new double[] {1,2,3}, new double[3])[1]=" + meter . toDerivedUnit ( new double [ ] { 1 , 2 , 3 } , new double [ 3 ] ) [ 1 ] ) ; System . out . println ( "meter.fromDerivedUnit(1.0)=" + meter . fromDerivedUnit ( 1.0 ) ) ; System . out . println ( "meter.fromDerivedUnit(new double[] {1,2,3}, new double[3])[2]=" + meter . fromDerivedUnit ( new double [ ] { 1 , 2 , 3 } , new double [ 3 ] ) [ 2 ] ) ; System . out . println ( "meter.isCompatible(meter)=" + meter . isCompatible ( meter ) ) ; System . out . println ( "meter.isCompatible(second)=" + meter . isCompatible ( second ) ) ; System . out . println ( "meter.equals(meter)=" + meter . equals ( meter ) ) ; System . out . println ( "meter.equals(second)=" + meter . equals ( second ) ) ; System . out . println ( "meter.isDimensionless()=" + meter . isDimensionless ( ) ) ; final Unit sPerS = second . myDivideBy ( second ) ; System . out . println ( "sPerS = \"" + sPerS + ' ' ) ; System . out . println ( "sPerS.isDimensionless()=" + sPerS . isDimensionless ( ) ) ; meterPerSecond . raiseTo ( 2 ) ; meter . myDivideBy ( meterPerSecond ) ; }


Input: Checks the type of the Simple Geom and calls the appropriate method to build the xml [CODESPLIT] public String writeFeature ( SimpleGeometry geom ) { if ( geom instanceof Point ) return writePoint ( ( Point ) geom ) ; else if ( geom instanceof Line ) return writeLine ( ( Line ) geom ) ; else if ( geom instanceof Polygon ) return writePolygon ( ( Polygon ) geom ) ; else return null ; }


Input: Takes in a point and writes its xml [CODESPLIT] private String writePoint ( Point point ) { String xml = "" ; xml += "<gml:Point srsName=\"http://www.opengis.net/gml/srs/epsg.xml@900913\" srsDimension=\"2\">" + "<gml:pos>" + point . getX ( ) + " " + point . getY ( ) + "</gml:pos>" + "</gml:Point>" ; return xml ; }


Input: Takes in a line and iterates through all its points writing the posList to xml [CODESPLIT] private String writeLine ( Line line ) { String xml = "" ; xml += "<gml:LineString><gml:posList>" ; for ( Point point : line . getPoints ( ) ) { xml += point . getX ( ) + " " + point . getY ( ) + " " ; } xml += "</gml:posList></gml:LineString>" ; return xml ; }


Input:
Takes in a polygon checks whether it is an interior or exterior ring and writes the corresponding xml . Iterates through all linked polygons [CODESPLIT] private String writePolygon ( Polygon poly ) { String xml = "" ; xml += "<gml:Polygon>" ; Polygon polygon = poly ; //    while (polygon != null) {
 if ( ! polygon . getInteriorRing ( ) ) { xml += "<gml:exterior><gml:LinearRing><gml:posList>" ; for ( Point point : polygon . getPoints ( ) ) { xml += point . getX ( ) + " " + point . getY ( ) + " " ; } xml += "</gml:posList></gml:LinearRing></gml:exterior>" ; } else { xml += "<gml:interior><gml:LinearRing><gml:posList>" ; for ( Point point : polygon . getPoints ( ) ) { xml += point . getX ( ) + " " + point . getY ( ) + " " ; } xml += "</gml:posList></gml:LinearRing></gml:interior>" ; } //      polygon = polygon.getNext();
 // }
 xml += "</gml:Polygon>" ; return xml ; }


Input: Parser API [CODESPLIT] public boolean parse ( String input ) throws SAXException { try { DocumentBuilderFactory domfactory = DocumentBuilderFactory . newInstance ( ) ; DocumentBuilder dombuilder = domfactory . newDocumentBuilder ( ) ; StringReader rdr = new StringReader ( input ) ; InputSource src = new InputSource ( rdr ) ; Document doc = dombuilder . parse ( src ) ; doc . getDocumentElement ( ) . normalize ( ) ; rdr . close ( ) ; parseresponse ( doc . getDocumentElement ( ) ) ; return true ; } catch ( ParserConfigurationException | IOException e ) { throw new SAXException ( e ) ; } }


Input: XML Attribute utilities [CODESPLIT] protected String pull ( Node n , String name ) { NamedNodeMap map = n . getAttributes ( ) ; Node attr = map . getNamedItem ( name ) ; if ( attr == null ) return null ; return attr . getNodeValue ( ) ; }


Input: Attribute construction [CODESPLIT] DapAttribute makeAttribute ( DapSort sort , String name , DapType basetype , List < String > nslist ) throws ParseException { DapAttribute attr = factory . newAttribute ( name , basetype ) ; if ( sort == DapSort . ATTRIBUTE ) { attr . setBaseType ( basetype ) ; } attr . setNamespaceList ( nslist ) ; return attr ; }


Input: Return the subnodes of a node with non - element nodes suppressed [CODESPLIT] List < Node > getSubnodes ( Node parent ) { List < Node > subs = new ArrayList <> ( ) ; NodeList nodes = parent . getChildNodes ( ) ; for ( int i = 0 ; i < nodes . getLength ( ) ; i ++ ) { Node n = nodes . item ( i ) ; if ( n . getNodeType ( ) == Node . ELEMENT_NODE ) subs . add ( n ) ; } return subs ; }


Input: Recursive descent parser [CODESPLIT] protected void parseresponse ( Node root ) throws ParseException { String elemname = root . getNodeName ( ) ; if ( elemname . equalsIgnoreCase ( "Error" ) ) { parseerror ( root ) ; } else if ( elemname . equalsIgnoreCase ( "Dataset" ) ) { parsedataset ( root ) ; } else throw new ParseException ( "Unexpected response root: " + elemname ) ; }


Input: Pass reserved xml attributes unchanged [CODESPLIT] protected void passReserved ( Node node , DapNode dap ) throws ParseException { try { NamedNodeMap attrs = node . getAttributes ( ) ; for ( int i = 0 ; i < attrs . getLength ( ) ; i ++ ) { Node n = attrs . item ( i ) ; String key = n . getNodeName ( ) ; String value = n . getNodeValue ( ) ; if ( isReserved ( key ) ) dap . addXMLAttribute ( key , value ) ; } } catch ( DapException de ) { throw new ParseException ( de ) ; } }


Input:
Gets the subset string to be used in NetCDFFile . read given a variable and some indicies . useful for subsetting timeseries [CODESPLIT] public static String getSubsetString ( Variable var , int beginInd , int endInd , int id ) { if ( var == null ) return null ; String subStr = "" ; List < Dimension > dimList = var . getDimensions ( ) ; // Enforce two dimension arrays
 if ( dimList . size ( ) > 2 || dimList . size ( ) < 1 ) { return null ; } for ( int i = 0 ; i < dimList . size ( ) ; i ++ ) { Dimension dim = dimList . get ( i ) ; if ( dim == null ) continue ; // If not CF Time then select only that ID
 if ( ! CF . TIME . equalsIgnoreCase ( dim . getShortName ( ) ) && ! CF . TIME . equalsIgnoreCase ( dim . getFullNameEscaped ( ) ) ) { subStr += id ; } // Otherwise subset based on time
 else { if ( beginInd < 0 || endInd < 0 ) subStr += ":" ; else subStr += ( beginInd + ":" + endInd ) ; } if ( i < dimList . size ( ) - 1 ) { subStr += "," ; } } return subStr ; }


Input:
Turn any ArrayStructure into a ArrayStructureMA [CODESPLIT] static public ArrayStructureMA factoryMA ( ArrayStructure from ) throws IOException { if ( from instanceof ArrayStructureMA ) return ( ArrayStructureMA ) from ; // To create an ArrayStructureMA that we can iterate over later, we need to know the shape of "from".
 if ( from . getSize ( ) > 0 ) { ArrayStructureMA to = new ArrayStructureMA ( new StructureMembers ( from . getStructureMembers ( ) ) , from . getShape ( ) ) ; for ( StructureMembers . Member m : from . getMembers ( ) ) { to . setMemberArray ( m . getName ( ) , from . extractMemberArray ( m ) ) ; } return to ; } // from.getSize() <= 0. This usually means that "from" is an ArraySequence, and that we won't know its size until
 // we iterate over it. extractMemberArray() will do that iteration for us, and then we can use the size of the
 // array it returns to determine the shape of "from".
 int numRecords = - 1 ; Map < String , Array > memberArrayMap = new LinkedHashMap <> ( ) ; for ( StructureMembers . Member m : from . getMembers ( ) ) { Array array = from . extractMemberArray ( m ) ; assert array . getSize ( ) > 0 : "array's size should have been computed in extractMemberArray()." ; int firstDimLen = array . getShape ( ) [ 0 ] ; if ( numRecords == - 1 ) { numRecords = firstDimLen ; } else { assert numRecords == firstDimLen : String . format ( "Expected all structure members to have the same first" + "dimension length, but %d != %d." , numRecords , firstDimLen ) ; } memberArrayMap . put ( m . getName ( ) , array ) ; } int [ ] shape ; if ( numRecords == - 1 ) { shape = new int [ ] { 0 } ; // "from" really was empty.
 } else { shape = new int [ ] { numRecords } ; } ArrayStructureMA to = new ArrayStructureMA ( new StructureMembers ( from . getStructureMembers ( ) ) , shape ) ; for ( Map . Entry < String , Array > entry : memberArrayMap . entrySet ( ) ) { to . setMemberArray ( entry . getKey ( ) , entry . getValue ( ) ) ; } return to ; }


Input: Set the data array for this member . [CODESPLIT] public void setMemberArray ( String memberName , Array data ) { StructureMembers . Member m = members . findMember ( memberName ) ; m . setDataArray ( data ) ; }


Input:
Create an ArrayStructure for a Structure . Allow nested Structures . Create the data arrays and an iterator . [CODESPLIT] static public ArrayStructureMA factoryMA ( Structure from , int [ ] shape ) throws IOException { StructureMembers sm = from . makeStructureMembers ( ) ; for ( Variable v : from . getVariables ( ) ) { Array data ; if ( v instanceof Sequence ) { data = Array . factory ( DataType . SEQUENCE , shape ) ; // an array sequence - one for each parent element
 //Structure s = (Structure) v;
 //StructureMembers smn = s.makeStructureMembers();
 // data = new ArraySequenceNested(smn, (int) Index.computeSize(v.getShapeAll())); // ??
 } else if ( v instanceof Structure ) data = ArrayStructureMA . factoryMA ( ( Structure ) v , combine ( shape , v . getShape ( ) ) ) ; else data = Array . factory ( v . getDataType ( ) , combine ( shape , v . getShape ( ) ) ) ; StructureMembers . Member m = sm . findMember ( v . getShortName ( ) ) ; m . setDataArray ( data ) ; } return new ArrayStructureMA ( sm , shape ) ; }


Input:
Returns a Polygon given a variable name and the geometric index . If the Polygon is not found it will return null . If the Polygon is a part of the Multi - Polygon it will return the head ( the first Polygon in the series which constitutes the Multi - Polygon ) . [CODESPLIT] public Polygon readPolygon ( String name , int index ) { Variable polyvar = ds . findVariable ( name ) ; if ( polyvar == null ) return null ; Polygon poly = null ; // CFConvention
 if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) poly = new CFPolygon ( ) ; if ( poly == null ) return null ; else return poly . setupPolygon ( ds , polyvar , index ) ; }


Input:
Returns a Line given a variable name and the geometric index . If the Line is not found it will return null . If the Line is a part of the Multi - Line it will return the head ( the first Line in the series which constitutes the Multi - Line ) . [CODESPLIT] public Line readLine ( String name , int index ) { Variable linevar = ds . findVariable ( name ) ; if ( linevar == null ) return null ; Line line = null ; // CFConvention
 if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) line = new CFLine ( ) ; if ( line == null ) return null ; else return line . setupLine ( ds , linevar , index ) ; }


Input:
Returns a Point given a variable name and the geometric index . If the Point is not found it will return null . If the Point is a part of the Multi - Point it will return the head ( the first Point in the series which constitutes the Multi - Point ) . [CODESPLIT] public Point readPoint ( String name , int index ) { Variable pointvar = ds . findVariable ( name ) ; if ( pointvar == null ) return null ; Point pt = null ; // CFConvention
 if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) pt = new CFPoint ( ) ; if ( pt == null ) return pt ; else return pt . setupPoint ( ds , pointvar , index ) ; }


Input:
Given a variable name returns the geometry type which that variable is associated with . If the variable has no simple geometry information null will be returned . [CODESPLIT] public GeometryType getGeometryType ( String name ) { Variable geometryVar = ds . findVariable ( name ) ; if ( geometryVar == null ) return null ; // CFConvention
 if ( ds . findGlobalAttribute ( CF . CONVENTIONS ) != null ) if ( ucar . nc2 . dataset . conv . CF1Convention . getVersion ( ds . findGlobalAttribute ( CF . CONVENTIONS ) . getStringValue ( ) ) >= 8 ) { Attribute geometryTypeAttr = null ; String geometry_type = null ; geometryTypeAttr = geometryVar . findAttribute ( CF . GEOMETRY_TYPE ) ; if ( geometryTypeAttr == null ) return null ; geometry_type = geometryTypeAttr . getStringValue ( ) ; switch ( geometry_type ) { case CF . POLYGON : return GeometryType . POLYGON ; case CF . LINE : return GeometryType . LINE ; case CF . POINT : return GeometryType . POINT ; default : return null ; } } return null ; }


Input: Make a Station from the station data structure . [CODESPLIT] public StationTimeSeriesFeature makeStation ( StructureData stationData , int recnum ) { StationFeature s = ft . makeStation ( stationData ) ; if ( s == null ) return null ; return new StandardStationFeatureImpl ( s , timeUnit , stationData , recnum ) ; }


Input: Recursive AST walker ; compilation of filters is done elsewhere . [CODESPLIT] protected void compileAST ( CEAST ast ) throws DapException { switch ( ast . sort ) { case CONSTRAINT : for ( CEAST clause : ast . clauses ) { compileAST ( clause ) ; } // invoke semantic checks this . ce . expand ( ) ; this . ce . finish ( ) ; break ; case PROJECTION : scopestack . clear ( ) ; compileAST ( ast . tree ) ; break ; case SEGMENT : compilesegment ( ast ) ; break ; case SELECTION : scopestack . clear ( ) ; compileselection ( ast ) ; break ; case DEFINE : dimredef ( ast ) ; break ; default : assert false : "uknown CEAST node type" ; } }


Input: Convert field references in a filter [CODESPLIT] public void compilefilter ( DapVariable var , DapSequence seq , CEAST expr ) throws DapException { if ( expr == null ) return ; if ( expr . sort == CEAST . Sort . SEGMENT ) { // This must be a simple segment and it must appear in seq if ( expr . subnodes != null ) throw new DapException ( "compilefilter: Non-simple segment:" + expr . name ) ; // Look for the name in the top-level field of seq DapVariable field = seq . findByName ( expr . name ) ; if ( field == null ) throw new DapException ( "compilefilter: Unknown filter variable:" + expr . name ) ; expr . field = field ; } else if ( expr . sort == CEAST . Sort . EXPR ) { if ( expr . lhs != null ) compilefilter ( var , seq , expr . lhs ) ; if ( expr . rhs != null ) compilefilter ( var , seq , expr . rhs ) ; // If both lhs and rhs are non-null, // canonicalize any comparison so that it is var op const if ( expr . lhs != null && expr . rhs != null ) { boolean leftvar = ( expr . lhs . sort == CEAST . Sort . SEGMENT ) ; boolean rightvar = ( expr . rhs . sort == CEAST . Sort . SEGMENT ) ; if ( rightvar && ! leftvar ) { // swap operands CEAST tmp = expr . lhs ; expr . lhs = expr . rhs ; expr . rhs = tmp ; // fix operator switch ( expr . op ) { case LT : //x<y -> y>x expr . op = CEAST . Operator . GT ; break ; case LE : //x<=y -> y>=x expr . op = CEAST . Operator . GE ; break ; case GT : //x>y -> y<x expr . op = CEAST . Operator . LT ; break ; case GE : //x>=y -> y<=x expr . op = CEAST . Operator . LE ; break ; default : break ; // leave as is } } } } else if ( expr . sort == CEAST . Sort . CONSTANT ) { return ; } else throw new DapException ( "compilefilter: Unexpected node type:" + expr . sort ) ; }


Input: Process a dim redefinition [CODESPLIT] protected void dimredef ( CEAST node ) throws DapException { DapDimension dim = ( DapDimension ) dataset . findByFQN ( node . name , DapSort . DIMENSION ) ; if ( dim == null ) throw new DapException ( "Constraint dim redef: no dimension name: " + node . name ) ; Slice slice = node . slice ; slice . finish ( ) ; ce . addRedef ( dim , slice ) ; }


Input: package private . use Array . factory () [CODESPLIT] static ArrayObject factory ( DataType dtype , Class elemType , boolean isVlen , Index index ) { return ArrayObject . factory ( dtype , elemType , isVlen , index , null ) ; }


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


Input: create new Array with given indexImpl and the same backing store [CODESPLIT] protected Array createView ( Index index ) { return ArrayObject . factory ( dataType , elementType , isVlen , index , storage ) ; }


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


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


Input:
Determine if the given lat / lon point is contined inside this rectangle . [CODESPLIT] public boolean contains ( double lat , double lon ) { // check lat first
 double eps = 1.0e-9 ; if ( ( lat + eps < lowerLeft . getLatitude ( ) ) || ( lat - eps > upperRight . getLatitude ( ) ) ) { return false ; } if ( allLongitude ) return true ; if ( crossDateline ) { // bounding box crosses the +/- 180 seam
 return ( ( lon >= lowerLeft . getLongitude ( ) ) || ( lon <= upperRight . getLongitude ( ) ) ) ; } else { // check "normal" lon case
 return ( ( lon >= lowerLeft . getLongitude ( ) ) && ( lon <= upperRight . getLongitude ( ) ) ) ; } }


Input: Determine if this bounding box is contained in another LatLonRect . [CODESPLIT] public boolean containedIn ( LatLonRect b ) { return ( b . getWidth ( ) >= width ) && b . contains ( upperRight ) && b . contains ( lowerLeft ) ; }


Input:
Extend the bounding box to contain this point [CODESPLIT] public void extend ( LatLonPoint p ) { if ( contains ( p ) ) return ; double lat = p . getLatitude ( ) ; double lon = p . getLongitude ( ) ; // lat is easy to deal with
 if ( lat > upperRight . getLatitude ( ) ) { upperRight . setLatitude ( lat ) ; } if ( lat < lowerLeft . getLatitude ( ) ) { lowerLeft . setLatitude ( lat ) ; } // lon is uglier
 if ( allLongitude ) { // do nothing
 } else if ( crossDateline ) { // bounding box crosses the +/- 180 seam
 double d1 = lon - upperRight . getLongitude ( ) ; double d2 = lowerLeft . getLongitude ( ) - lon ; if ( ( d1 > 0.0 ) && ( d2 > 0.0 ) ) { // needed ?
 if ( d1 > d2 ) { lowerLeft . setLongitude ( lon ) ; } else { upperRight . setLongitude ( lon ) ; } } } else { // normal case
 if ( lon > upperRight . getLongitude ( ) ) { if ( lon - upperRight . getLongitude ( ) > lowerLeft . getLongitude ( ) - lon + 360 ) { crossDateline = true ; lowerLeft . setLongitude ( lon ) ; } else { upperRight . setLongitude ( lon ) ; } } else if ( lon < lowerLeft . getLongitude ( ) ) { if ( lowerLeft . getLongitude ( ) - lon > lon + 360.0 - upperRight . getLongitude ( ) ) { crossDateline = true ; upperRight . setLongitude ( lon ) ; } else { lowerLeft . setLongitude ( lon ) ; } } } // recalc delta, center
 width = upperRight . getLongitude ( ) - lowerLeft . getLongitude ( ) ; lon0 = ( upperRight . getLongitude ( ) + lowerLeft . getLongitude ( ) ) / 2 ; if ( crossDateline ) { width += 360 ; lon0 -= 180 ; } this . allLongitude = this . allLongitude || ( this . width >= 360.0 ) ; }


Input:
Extend the bounding box to contain the given rectangle [CODESPLIT] public void extend ( LatLonRect r ) { Preconditions . checkNotNull ( r ) ; // lat is easy
 double latMin = r . getLatMin ( ) ; double latMax = r . getLatMax ( ) ; if ( latMax > upperRight . getLatitude ( ) ) { upperRight . setLatitude ( latMax ) ; } if ( latMin < lowerLeft . getLatitude ( ) ) { lowerLeft . setLatitude ( latMin ) ; } // lon is uglier
 if ( allLongitude ) return ; // everything is reletive to current LonMin
 double lonMin = getLonMin ( ) ; double lonMax = getLonMax ( ) ; double nlonMin = LatLonPointImpl . lonNormal ( r . getLonMin ( ) , lonMin ) ; double nlonMax = nlonMin + r . getWidth ( ) ; lonMin = Math . min ( lonMin , nlonMin ) ; lonMax = Math . max ( lonMax , nlonMax ) ; width = lonMax - lonMin ; allLongitude = width >= 360.0 ; if ( allLongitude ) { width = 360.0 ; lonMin = - 180.0 ; } else { lonMin = LatLonPointImpl . lonNormal ( lonMin ) ; } lowerLeft . setLongitude ( lonMin ) ; upperRight . setLongitude ( lonMin + width ) ; lon0 = lonMin + width / 2 ; crossDateline = lowerLeft . getLongitude ( ) > upperRight . getLongitude ( ) ; }


Input:
Create the instersection of this LatLon with the given one [CODESPLIT] public LatLonRect intersect ( LatLonRect clip ) { double latMin = Math . max ( getLatMin ( ) , clip . getLatMin ( ) ) ; double latMax = Math . min ( getLatMax ( ) , clip . getLatMax ( ) ) ; double deltaLat = latMax - latMin ; if ( deltaLat < 0 ) return null ; // lon as always is a pain : if not intersection, try +/- 360
 double lon1min = getLonMin ( ) ; double lon1max = getLonMax ( ) ; double lon2min = clip . getLonMin ( ) ; double lon2max = clip . getLonMax ( ) ; if ( ! intersect ( lon1min , lon1max , lon2min , lon2max ) ) { lon2min = clip . getLonMin ( ) + 360 ; lon2max = clip . getLonMax ( ) + 360 ; if ( ! intersect ( lon1min , lon1max , lon2min , lon2max ) ) { lon2min = clip . getLonMin ( ) - 360 ; lon2max = clip . getLonMax ( ) - 360 ; } } // we did our best to find an intersection
 double lonMin = Math . max ( lon1min , lon2min ) ; double lonMax = Math . min ( lon1max , lon2max ) ; double deltaLon = lonMax - lonMin ; if ( deltaLon < 0 ) return null ; return new LatLonRect ( new LatLonPointImpl ( latMin , lonMin ) , deltaLat , deltaLon ) ; }


Input: Return a String representation of this object . <pre > lat = [ - 90 . 00 90 . 00 ] lon = [ 0 . 00 360 . 00< / pre > [CODESPLIT] public String toString2 ( ) { return " lat= [" + Format . dfrac ( getLatMin ( ) , 2 ) + "," + Format . dfrac ( getLatMax ( ) , 2 ) + "] lon= [" + Format . dfrac ( getLonMin ( ) , 2 ) + "," + Format . dfrac ( getLonMax ( ) , 2 ) + "]" ; }


Input: Add elements of two arrays together allocating the result array . The result type and the operation type are taken from the type of a . [CODESPLIT] public static Array add ( Array a , Array b ) throws IllegalArgumentException { Array result = Array . factory ( a . getDataType ( ) , a . getShape ( ) ) ; if ( a . getElementType ( ) == double . class ) { addDouble ( result , a , b ) ; } else throw new UnsupportedOperationException ( ) ; return result ; }


Input: Add elements of two arrays together as doubles place sum in the result array . The values from the arrays a and b are converted to double ( if needed ) and the sum is converted to the type of result ( if needed ) . [CODESPLIT] public static void addDouble ( Array result , Array a , Array b ) throws IllegalArgumentException { if ( ! conformable ( result , a ) || ! conformable ( a , b ) ) throw new IllegalArgumentException ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterB = b . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setDoubleNext ( iterA . getDoubleNext ( ) + iterB . getDoubleNext ( ) ) ; }


Input: Check that two arrays are conformable . [CODESPLIT] public static boolean conformable ( Array a , Array b ) { return conformable ( a . getShape ( ) , b . getShape ( ) ) ; }


Input:
Check that two array shapes are conformable . The shapes must match exactly except that dimensions of length 1 are ignored . [CODESPLIT] public static boolean conformable ( int [ ] shapeA , int [ ] shapeB ) { if ( reducedRank ( shapeA ) != reducedRank ( shapeB ) ) return false ; int rankB = shapeB . length ; int dimB = 0 ; for ( int aShapeA : shapeA ) { //System.out.println(dimA + " "+ dimB);
 //skip length 1 dimensions
 if ( aShapeA == 1 ) continue ; while ( dimB < rankB ) if ( shapeB [ dimB ] == 1 ) dimB ++ ; else break ; // test same shape (NB dimB cant be > rankB due to first test)
 if ( aShapeA != shapeB [ dimB ] ) return false ; dimB ++ ; } return true ; }


Input: Convert original array to desired type [CODESPLIT] public static Array convert ( Array org , DataType wantType ) { if ( org == null ) return null ; Class wantClass = wantType . getPrimitiveClassType ( ) ; if ( org . getElementType ( ) . equals ( wantClass ) ) return org ; Array result = Array . factory ( wantType , org . getShape ( ) ) ; copy ( wantType , org . getIndexIterator ( ) , result . getIndexIterator ( ) ) ; return result ; }


Input: Copy using iterators . Will copy until !from . hasNext () . [CODESPLIT] public static void copy ( DataType dataType , IndexIterator from , IndexIterator to ) throws IllegalArgumentException { if ( dataType == DataType . DOUBLE ) { while ( from . hasNext ( ) ) to . setDoubleNext ( from . getDoubleNext ( ) ) ; } else if ( dataType == DataType . FLOAT ) { while ( from . hasNext ( ) ) to . setFloatNext ( from . getFloatNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == long . class ) { while ( from . hasNext ( ) ) to . setLongNext ( from . getLongNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == int . class ) { while ( from . hasNext ( ) ) to . setIntNext ( from . getIntNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == short . class ) { while ( from . hasNext ( ) ) to . setShortNext ( from . getShortNext ( ) ) ; } else if ( dataType == DataType . CHAR ) { while ( from . hasNext ( ) ) to . setCharNext ( from . getCharNext ( ) ) ; } else if ( dataType . getPrimitiveClassType ( ) == byte . class ) { while ( from . hasNext ( ) ) to . setByteNext ( from . getByteNext ( ) ) ; } else if ( dataType == DataType . BOOLEAN ) { while ( from . hasNext ( ) ) to . setBooleanNext ( from . getBooleanNext ( ) ) ; } else { while ( from . hasNext ( ) ) to . setObjectNext ( from . getObjectNext ( ) ) ; } }


Input: Copy array a to array result the result array will be in canonical order The operation type is taken from the type of a . [CODESPLIT] public static void copy ( Array result , Array a ) throws IllegalArgumentException { Class classType = a . getElementType ( ) ; if ( classType == double . class ) { copyDouble ( result , a ) ; } else if ( classType == float . class ) { copyFloat ( result , a ) ; } else if ( classType == long . class ) { copyLong ( result , a ) ; } else if ( classType == int . class ) { copyInt ( result , a ) ; } else if ( classType == short . class ) { copyShort ( result , a ) ; } else if ( classType == char . class ) { copyChar ( result , a ) ; } else if ( classType == byte . class ) { copyByte ( result , a ) ; } else if ( classType == boolean . class ) { copyBoolean ( result , a ) ; } else copyObject ( result , a ) ; }


Input: copy array a to array result as doubles The values from the arrays a are converted to double ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyDouble ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setDoubleNext ( iterA . getDoubleNext ( ) ) ; }


Input: copy array a to array result as floats The values from the arrays a are converted to float ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyFloat ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setFloatNext ( iterA . getFloatNext ( ) ) ; }


Input: copy array a to array result as longs The values from the array a are converted to long ( if needed ) and then converted to the type of result ( if needed ) . @param result copy to here @param a copy from here [CODESPLIT] public static void copyLong ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setLongNext ( iterA . getLongNext ( ) ) ; }


Input: copy array a to array result as integers The values from the arrays a are converted to integer ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyInt ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setIntNext ( iterA . getIntNext ( ) ) ; }


Input: copy array a to array result as shorts The values from the array a are converted to short ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyShort ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setShortNext ( iterA . getShortNext ( ) ) ; }


Input: copy array a to array result as char The values from the array a are converted to char ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyChar ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setCharNext ( iterA . getCharNext ( ) ) ; }


Input: copy array a to array result as bytes The values from the array a are converted to byte ( if needed ) and then converted to the type of result ( if needed ) . [CODESPLIT] public static void copyByte ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setByteNext ( iterA . getByteNext ( ) ) ; }


Input: copy array a to array result as bytes The array a and result must be type boolean [CODESPLIT] public static void copyBoolean ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) iterR . setBooleanNext ( iterA . getBooleanNext ( ) ) ; }


Input: copy array a to array result as an Object The array a and result must be type object [CODESPLIT] public static void copyObject ( Array result , Array a ) throws IllegalArgumentException { if ( ! conformable ( a , result ) ) throw new IllegalArgumentException ( "copy arrays are not conformable" ) ; IndexIterator iterA = a . getIndexIterator ( ) ; IndexIterator iterR = result . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) { iterR . setObjectNext ( iterA . getObjectNext ( ) ) ; } }


Input: Find min and max value in this array getting values as doubles . Skip Double . NaN . [CODESPLIT] public static MAMath . MinMax getMinMax ( Array a ) { IndexIterator iter = a . getIndexIterator ( ) ; double max = - Double . MAX_VALUE ; double min = Double . MAX_VALUE ; while ( iter . hasNext ( ) ) { double val = iter . getDoubleNext ( ) ; if ( Double . isNaN ( val ) ) continue ; if ( val > max ) max = val ; if ( val < min ) min = val ; } return new MinMax ( min , max ) ; }


Input: Set all the elements of this array to the given double value . The value is converted to the element type of the array if needed . [CODESPLIT] public static void setDouble ( Array result , double val ) { IndexIterator iter = result . getIndexIterator ( ) ; while ( iter . hasNext ( ) ) { iter . setDoubleNext ( val ) ; } }


Input: sum all of the elements of array a as doubles . The values from the array a are converted to double ( if needed ) . [CODESPLIT] public static double sumDouble ( Array a ) { double sum = 0 ; IndexIterator iterA = a . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) { sum += iterA . getDoubleNext ( ) ; } return sum ; }


Input: sum all of the elements of array a as doubles . The values from the array a are converted to double ( if needed ) . [CODESPLIT] public static double sumDoubleSkipMissingData ( Array a , double missingValue ) { double sum = 0 ; IndexIterator iterA = a . getIndexIterator ( ) ; while ( iterA . hasNext ( ) ) { double val = iterA . getDoubleNext ( ) ; if ( ( val == missingValue ) || Double . isNaN ( val ) ) continue ; sum += val ; } return sum ; }


Input: Calculate the scale / offset for an array of numbers . <pre > If signed : then max value unpacked = 2^ ( n - 1 ) - 1 packed min value unpacked = - ( 2^ ( n - 1 ) - 1 ) packed note that - 2^ ( n - 1 ) is unused and a good place to map missing values by solving 2 eq in 2 unknowns we get : scale = ( max - min ) / ( 2^n - 2 ) offset = ( max + min ) / 2 If unsigned then max value unpacked = 2^n - 1 packed min value unpacked = 0 packed and : scale = ( max - min ) / ( 2^n - 1 ) offset = min One could modify this to allow a holder for missing values . < / pre > [CODESPLIT] public static MAMath . ScaleOffset calcScaleOffsetSkipMissingData ( Array a , double missingValue , int nbits ) { MAMath . MinMax minmax = getMinMaxSkipMissingData ( a , missingValue ) ; if ( a . isUnsigned ( ) ) { long size = ( 1L << nbits ) - 1 ; double offset = minmax . min ; double scale = ( minmax . max - minmax . min ) / size ; return new ScaleOffset ( scale , offset ) ; } else { long size = ( 1L << nbits ) - 2 ; double offset = ( minmax . max + minmax . min ) / 2 ; double scale = ( minmax . max - minmax . min ) / size ; return new ScaleOffset ( scale , offset ) ; } }


Input:
Returns true if the specified arrays have the same size signedness and <b > approximately< / b > equal corresponding elements . { @code float } elements must be within { @link Misc#defaultMaxRelativeDiffFloat } of each other as determined by { @link Misc#nearlyEquals ( double double double ) } . Similarly { @code double } elements must be within { @link Misc#defaultMaxRelativeDiffDouble } of each other . <p > { @link #equals ( Array Array ) } is an alternative to this method that requires that corresponding elements be <b > exactly< / b > equal . It is suitable for use in { @link Object#equals } implementations whereas this method isn t . [CODESPLIT] public static boolean nearlyEquals ( Array data1 , Array data2 ) { if ( data1 == data2 ) { // Covers case when both are null.
 return true ; } else if ( data1 == null || data2 == null ) { return false ; } if ( data1 . getSize ( ) != data2 . getSize ( ) ) return false ; if ( data1 . isUnsigned ( ) != data2 . isUnsigned ( ) ) return false ; DataType dt = DataType . getType ( data1 ) ; IndexIterator iter1 = data1 . getIndexIterator ( ) ; IndexIterator iter2 = data2 . getIndexIterator ( ) ; if ( dt == DataType . DOUBLE ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { double v1 = iter1 . getDoubleNext ( ) ; double v2 = iter2 . getDoubleNext ( ) ; if ( ! Misc . nearlyEquals ( v1 , v2 , Misc . defaultMaxRelativeDiffDouble ) ) return false ; } } else if ( dt == DataType . FLOAT ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { float v1 = iter1 . getFloatNext ( ) ; float v2 = iter2 . getFloatNext ( ) ; if ( ! Misc . nearlyEquals ( v1 , v2 , Misc . defaultMaxRelativeDiffFloat ) ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == int . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { int v1 = iter1 . getIntNext ( ) ; int v2 = iter2 . getIntNext ( ) ; if ( v1 != v2 ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == byte . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { short v1 = iter1 . getShortNext ( ) ; short v2 = iter2 . getShortNext ( ) ; if ( v1 != v2 ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == short . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { byte v1 = iter1 . getByteNext ( ) ; byte v2 = iter2 . getByteNext ( ) ; if ( v1 != v2 ) return false ; } } else if ( dt . getPrimitiveClassType ( ) == long . class ) { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { long v1 = iter1 . getLongNext ( ) ; long v2 = iter2 . getLongNext ( ) ; if ( v1 != v2 ) return false ; } } else { while ( iter1 . hasNext ( ) && iter2 . hasNext ( ) ) { if ( ! Objects . equals ( iter1 . next ( ) , iter2 . next ( ) ) ) { return false ; } } } return true ; }


Input: / * @Override public List<CalendarDate > getCalendarDates () { if ( getTimeAxis () ! = null ) return getTimeAxis () . getCalendarDates () ; [CODESPLIT] @ Override public CalendarDateRange getCalendarDateRange ( ) { if ( getTimeAxis ( ) != null ) return getTimeAxis ( ) . getCalendarDateRange ( ) ; else if ( getRunTimeAxis ( ) != null ) return getRunTimeAxis ( ) . getCalendarDateRange ( ) ; else return null ; }


Input: turn ConfigCatalog into a mutable CatalogBuilder so we can mutate [CODESPLIT] public CatalogBuilder makeCatalogBuilder ( ) { CatalogBuilder builder = new CatalogBuilder ( this ) ; for ( Dataset ds : getDatasetsLocal ( ) ) { builder . addDataset ( makeDatasetBuilder ( null , ds ) ) ; } return builder ; }


Input: Returns the <code > AttributeTable< / code > with the given name . [CODESPLIT] public final AttributeTable getAttributeTable ( String name ) throws NoSuchAttributeException { AttributeTable at = null ; Attribute a = getAttribute ( name ) ; if ( a != null ) { if ( a . isContainer ( ) ) { at = a . getContainer ( ) ; } } return ( at ) ; }


Input: Returns the <code > AttributeTable< / code > with the given name . [CODESPLIT] public final AttributeTable getAttributeTableN ( String name ) { AttributeTable at = null ; Attribute a = getAttribute ( name ) ; if ( a != null ) { if ( a . isContainer ( ) ) { at = a . getContainerN ( ) ; } } return ( at ) ; }


Input:
This method searchs through the <code > DAS< / code > for Alias members . When an Alias is found the method attempts to resolve it to a specific Attribute . <p / > This method is invoked by <code > parse ( InputStream is ) < / code > and is used to search for Aliases in AttributeTables found in the DAS . <p / > If you are building a DAS from it s API it is important to call this method prior to returning said DAS to an application . If this call is not made Aliases will not work correctly . [CODESPLIT] public void resolveAliases ( ) throws MalformedAliasException , UnresolvedAliasException , NoSuchAttributeException { resolveAliases ( this ) ; // Enforce the rule that Aliases at the highest level of the DAS
 // must point to a container (AttributeTable)
 Enumeration e = getNames ( ) ; while ( e . hasMoreElements ( ) ) { String aName = ( String ) e . nextElement ( ) ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "DAS.resolveAliases() - aName: " + aName ) ; } Attribute at = getAttribute ( aName ) ; if ( at == null || ! at . isContainer ( ) ) { throw new MalformedAliasException ( "Aliases at the top-level of a DAS MUST reference a container (AttributeTable), not a simple Attribute" ) ; } } }


Input:
This method recursively searchs through the passed <code > AttributeTable< / code > parameter at for Alias members . When an Alias is found the method attempts to resolve it to a specific Attribute . <p / > This method gets called is invoked by <code > reolveAliases ( BaseType bt ) < / code > and is used to search for Aliases in AttributeTables found in a BaseTypes Attributes . <p / > This method manipulates the global variable <code > currentBT< / code > . [CODESPLIT] private void resolveAliases ( AttributeTable at ) throws MalformedAliasException , UnresolvedAliasException , NoSuchAttributeException { // Cache the current (parent) Attribute table. This value is
 // null if this method is called from parse();
 AttributeTable cacheAT = currentAT ; try { // Set the current AttributeTable to the one that we are searching.
 currentAT = at ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "DAS.resolveAliases(at=" + at + ")" ) ; } //getall of the Attributes from the table.
 Enumeration aNames = at . getNames ( ) ; while ( aNames . hasMoreElements ( ) ) { String aName = ( String ) aNames . nextElement ( ) ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "DAS.resolveAliases(at=" + at + ") - aName: " + aName ) ; } opendap . dap . Attribute thisA = currentAT . getAttribute ( aName ) ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "thisA.getClass().getName(): " + thisA . getClass ( ) . getName ( ) ) ; } if ( thisA . isAlias ( ) ) { //Is Alias? Resolve it!
 resolveAlias ( ( Alias ) thisA ) ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "Resolved Alias: '" + thisA . getEncodedName ( ) + "'\n" ) ; } } else if ( thisA . isContainer ( ) ) { //Is AttributeTable (container)? Search it!
 resolveAliases ( thisA . getContainer ( ) ) ; } } } finally { // Restore the previous currentAT state.
 currentAT = cacheAT ; } }


Input:
This method attempts to resolve the past Alias to a specific Attribute in the DDS . It does this by : <ul > <li > 1 ) Tokenizing the Alias s variable and attribute fields ( see <code > Alias< / code > ) < / li > <li > 2 ) Evaluating the tokenized fields to determine if the Alias is defined in terms of a relative or absolute path < / li > <li > 3 ) Searching the DAS or the currentAT ( depending on results of 2 ) for the target Attribute < / li > <li > 4 ) Setting the Aliases intrnal reference to it s Attribute < / ul > <p / > If an Attribute matching the definition of the Alias cannot be located an Exception is thrown [CODESPLIT] private void resolveAlias ( Alias alias ) throws MalformedAliasException , UnresolvedAliasException { //Get the crucial stuff out of the Alias
 String name = alias . getClearName ( ) ; String attribute = alias . getAliasedToAttributeFieldAsClearString ( ) ; // Get ready!
 Enumeration e = null ; currentAlias = alias ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "\n\nFound: Alias " + name + "  " + attribute ) ; } // Let's go
 // see if we can find an Attribute within that DAS that matches the attribute field
 // in the Alias declartion.
 // The Attribute field MAY NOT be empty.
 if ( attribute . equals ( "" ) ) { throw new MalformedAliasException ( "The attribute 'attribute' in the Alias " + "element must have a value other than an empty string." ) ; } if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "Attribute: `" + attribute + "'" ) ; } // Tokenize the attribute field.
 Vector aNames = opendap . dap . DDS . tokenizeAliasField ( attribute ) ; if ( Debug . isSet ( "DAS" ) ) { DAPNode . log . debug ( "Attribute name tokenized to " + aNames . size ( ) + " elements" ) ; e = aNames . elements ( ) ; while ( e . hasMoreElements ( ) ) { String aname = ( String ) e . nextElement ( ) ; DAPNode . log . debug ( "name: " + aname ) ; } } opendap . dap . Attribute targetAT = null ; // Absolute paths for attributes names must start with the dot character.
 boolean isAbsolutePath = aNames . get ( 0 ) . equals ( "." ) ; if ( isAbsolutePath ) { //Is it an absolute path?
 if ( aNames . size ( ) == 1 ) { throw new MalformedAliasException ( "Aliases must reference an Attribute. " + "An attribute field of dot (.) references the entire " + "DAS, which is not allowed." ) ; } else { // Dump the dot from the vector of tokens and go try to find
 // the Attribute in the DAS.
 aNames . remove ( 0 ) ; targetAT = getAliasAttribute ( this , aNames ) ; } } else { throw new MalformedAliasException ( "In the Alias '" + name + "'" + " the attribute 'attribute' does not begin with the character dot (.). " + "The 'attribute' field must always be an absoulute path name from the " + "top level of the dataset, and thus must always begin with the dot (.) character." ) ; } alias . setMyAttribute ( targetAT ) ; }


Input:
This method executes a ( recursive ) search of the <code > AttributeTable< / code > parameter <b > at< / b > for an <code > Attribute< / code > whose name resolves to the vector of names contained in the <code > Vector< / code > parameter <b > aNames< / b > . An Attribute is considered a match if each of it s node names in the hierarchy of AttributeTables contained in the one passed as parameter <b > at< / b > matches ( equals ) the corresponding name in the Vector <b > aNames< / b > . [CODESPLIT] private opendap . dap . Attribute getAliasAttribute ( AttributeTable att , Vector aNames ) throws MalformedAliasException , UnresolvedAliasException { // Get the first node name form the vector.
 String aName = ( String ) aNames . get ( 0 ) ; // Get the list of child nodes from the AttributeTable
 Enumeration e = att . getNames ( ) ; while ( e . hasMoreElements ( ) ) { // Get an Attribute
 String atName = ( String ) e . nextElement ( ) ; opendap . dap . Attribute a = att . getAttribute ( atName ) ; // Get the Attributes name and Normalize it.
 String normName = opendap . dap . DDS . normalize ( a . getEncodedName ( ) ) ; // Are they the same?
 if ( normName . equals ( aName ) ) { // Make sure this reference doesn't pass through an Alias.
 if ( a . isAlias ( ) ) { throw new MalformedAliasException ( "Aliases may NOT point to other aliases" ) ; } //dump the name from the list of names.
 aNames . remove ( 0 ) ; // Are there more?
 if ( aNames . size ( ) == 0 ) { //No! We found it!
 return ( a ) ; } else if ( a . isContainer ( ) ) { // Is this Attribute a container (it better be)
 try { // Recursively search for the rest of the name vector in the container.
 return ( getAliasAttribute ( a . getContainer ( ) , aNames ) ) ; } catch ( NoSuchAttributeException nsae ) { throw new MalformedAliasException ( "Attribute " + a . getEncodedName ( ) + " is not an attribute container. (AttributeTable) " + " It may not contain the attribute: " + aName ) ; } } else { // Dead-end, through an exception!
 throw new MalformedAliasException ( "Attribute " + a . getEncodedName ( ) + " is not an attribute container. (AttributeTable) " + " It may not contain the attribute: " + aName ) ; } } } // Nothing Matched, so this search failed.
 throw new UnresolvedAliasException ( "The alias `" + currentAlias . getEncodedName ( ) + "` references the attribute: `" + aName + "` which cannot be found." ) ; }


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


Input: / * Code table 6 – Data representation type Code figure Meaning 0 Latitude / longitude grid – equidistant cylindrical or Plate Carrée projection 1 Mercator projection 2 Gnomonic projection 3 Lambert conformal secant or tangent conic or bi - polar projection 4 Gaussian latitude / longitude grid 5 Polar stereographic projection 6 Universal Transverse Mercator ( UTM ) projection 7 Simple polyconic projection 8 Albers equal - area secant or tangent conic or bi - polar projection 9 Miller’s cylindrical projection 10 Rotated latitude / longitude grid 11–12 Reserved 13 Oblique Lambert conformal secant or tangent conic or bi - polar projection 14 Rotated Gaussian latitude / longitude grid 15–19 Reserved 20 Stretched latitude / longitude grid 21–23 Reserved 24 Stretched Gaussian latitude / longitude grid 25–29 Reserved 30 Stretched and rotated latitude / longitude grids 31–33 Reserved 34 Stretched and rotated Gaussian latitude / longitude grids 35–49 Reserved ^ 50 Spherical harmonic coefficients 51–59 Reserved 60 Rotated spherical harmonic coefficients 61–69 Reserved 70 Stretched spherical harmonics 71–79 Reserved 80 Stretched and rotated spherical harmonic coefficients 81–89 Reserved 90 Space view perspective or orthographic 91–191 Reserved 192–254 Reserved for local use [CODESPLIT] public static Grib1Gds factory ( int template , byte [ ] data ) { switch ( template ) { case 0 : return new LatLon ( data , 0 ) ; case 1 : return new Mercator ( data , 1 ) ; case 3 : return new LambertConformal ( data , 3 ) ; case 4 : return new GaussianLatLon ( data , 4 ) ; case 5 : return new PolarStereographic ( data , 5 ) ; case 10 : return new RotatedLatLon ( data , 10 ) ; case 50 : return new SphericalHarmonicCoefficients ( data , 50 ) ; default : return new UnknownGds ( data , template ) ; } }


Input: signed [CODESPLIT] protected int getOctet3 ( int start ) { return GribNumbers . int3 ( getOctet ( start ) , getOctet ( start + 1 ) , getOctet ( start + 2 ) ) ; }


Input:
************************************************************************ Default handler for OPeNDAP directory requests . Returns an html document with a list of all datasets on this server with links to their DDS DAS Information and HTML responses . [CODESPLIT] public void sendDIR ( ReqState rs ) throws opendap . dap . DAP2Exception , ParseException { if ( _Debug ) System . out . println ( "sendDIR request = " + rs . getRequest ( ) ) ; try { PrintWriter pw = new PrintWriter ( new OutputStreamWriter ( rs . getResponse ( ) . getOutputStream ( ) , Util . UTF8 ) ) ; // ignore String ddxCacheDir = rs.getDDXCache(rs.getRootPath()); String ddsCacheDir = rs . getDDSCache ( rs . getRootPath ( ) ) ; String thisServer = rs . getRequest ( ) . getRequestURL ( ) . toString ( ) ; pw . println ( "" ) ; pw . println ( "" ) ; pw . println ( "<title>OPeNDAP Directory</title>" ) ; pw . println ( "<meta http-equiv=\"Content-Type\" content=\"text/html\">" ) ; pw . println ( "" ) ; pw . println ( "" ) ; pw . println ( "
OPeNDAP Directory for:
" ) ; pw . println ( "
" + thisServer + "
" ) ; // ignore printDIR(pw, ddxCacheDir, "DDX", thisServer); printDIR ( pw , ddsCacheDir , "DDS" , thisServer ) ; pw . println ( "
" ) ; pw . println ( "" ) ; pw . flush ( ) ; } catch ( FileNotFoundException fnfe ) { System . out . println ( "OUCH! FileNotFoundException: " + fnfe . getMessage ( ) ) ; fnfe . printStackTrace ( System . out ) ; } catch ( IOException ioe ) { System . out . println ( "OUCH! IOException: " + ioe . getMessage ( ) ) ; ioe . printStackTrace ( System . out ) ; } }


Input: Create a ProjectionImpl from the projection [CODESPLIT] static public ProjectionImpl factory ( Projection proj ) { if ( proj instanceof ProjectionImpl ) { return ( ProjectionImpl ) proj ; } return new ProjectionAdapter ( proj ) ; }


Input: Convert a LatLonPoint to projection coordinates [CODESPLIT] public ProjectionPoint latLonToProj ( LatLonPoint latlon , ProjectionPointImpl result ) { return proj . latLonToProj ( latlon , result ) ; }


Input: Convert projection coordinates to a LatLonPoint Note : a new object is not created on each call for the return value . [CODESPLIT] public LatLonPoint projToLatLon ( ProjectionPoint world , LatLonPointImpl result ) { return proj . projToLatLon ( world , result ) ; }


Input: /////////////////////////////////////////////////////////////////////////////////// [CODESPLIT] @ Override public Iterator < StationProfileFeature > iterator ( ) { try { PointFeatureCCIterator pfIterator = getNestedPointFeatureCollectionIterator ( ) ; return new NestedCollectionIteratorAdapter <> ( pfIterator ) ; } catch ( IOException e ) { throw new RuntimeException ( e ) ; } }


Input: Define the DEFINITIVE opendap identifier unescape function . [CODESPLIT] public static String unescapeDAPIdentifier ( String id ) { String s ; try { s = unescapeString ( id ) ; } catch ( Exception e ) { s = null ; } return s ; }


Input: Define the DEFINITIVE URL unescape function . [CODESPLIT] public static String urlDecode ( String s ) { try { //s = unescapeString(s, _URIEscape, "", false); s = URLDecoder . decode ( s , "UTF-8" ) ; } catch ( Exception e ) { s = null ; } return s ; }


Input: Decode all of the parts of the url including query and fragment [CODESPLIT] public static String unescapeURL ( String url ) { String newurl ; newurl = urlDecode ( url ) ; return newurl ; }


Input: backslash escape a string [CODESPLIT] static public String backslashEscape ( String x , String reservedChars ) { if ( x == null ) { return null ; } else if ( reservedChars == null ) { return x ; } boolean ok = true ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( reservedChars . indexOf ( c ) >= 0 ) { ok = false ; break ; } } if ( ok ) return x ; // gotta do it StringBuilder sb = new StringBuilder ( x ) ; for ( int pos = 0 ; pos < sb . length ( ) ; pos ++ ) { char c = sb . charAt ( pos ) ; if ( reservedChars . indexOf ( c ) < 0 ) { continue ; } sb . setCharAt ( pos , ' ' ) ; pos ++ ; sb . insert ( pos , c ) ; pos ++ ; } return sb . toString ( ) ; }


Input: backslash unescape a string [CODESPLIT] static public String backslashUnescape ( String x ) { if ( ! x . contains ( "\\" ) ) return x ; // gotta do it StringBuilder sb = new StringBuilder ( x . length ( ) ) ; for ( int pos = 0 ; pos < x . length ( ) ; pos ++ ) { char c = x . charAt ( pos ) ; if ( c == ' ' ) { c = x . charAt ( ++ pos ) ; // skip backslash, get next cha } sb . append ( c ) ; } return sb . toString ( ) ; }


Input: Tokenize an escaped name using . as delimiter skipping \ . [CODESPLIT] public static List < String > tokenizeEscapedName ( String escapedName ) { List < String > result = new ArrayList <> ( ) ; int pos = 0 ; int start = 0 ; while ( true ) { pos = escapedName . indexOf ( sep , pos + 1 ) ; if ( pos <= 0 ) break ; if ( ( pos > 0 ) && escapedName . charAt ( pos - 1 ) != ' ' ) { result . add ( escapedName . substring ( start , pos ) ) ; start = pos + 1 ; } } result . add ( escapedName . substring ( start , escapedName . length ( ) ) ) ; // remaining return result ; }


Input: Find first occurence of char c in escapedName excluding escaped c . [CODESPLIT] public static int indexOf ( String escapedName , char c ) { int pos = 0 ; while ( true ) { pos = escapedName . indexOf ( c , pos + 1 ) ; if ( pos <= 0 ) return pos ; if ( ( pos > 0 ) && escapedName . charAt ( pos - 1 ) != ' ' ) return pos ; } }


Input: Given a backslash escaped name convert to a DAP escaped name [CODESPLIT] public static String backslashToDAP ( String bs ) { StringBuilder buf = new StringBuilder ( ) ; int len = bs . length ( ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = bs . charAt ( i ) ; if ( i < ( len - 1 ) && c == ' ' ) { c = bs . charAt ( ++ i ) ; } if ( _allowableInDAP . indexOf ( c ) < 0 ) { buf . append ( _URIEscape ) ; // convert the char to hex String ashex = Integer . toHexString ( ( int ) c ) ; if ( ashex . length ( ) < 2 ) buf . append ( ' ' ) ; buf . append ( ashex ) ; } else buf . append ( c ) ; } return buf . toString ( ) ; }


Input: Given a DAP ( attribute ) string insert backslashes before and / characters . This code also escapes control characters although the spec does not call for it ; make that code conditional . [CODESPLIT] static public String backslashEscapeDapString ( String s ) { StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; if ( true ) { if ( c < ' ' ) { switch ( c ) { case ' ' : case ' ' : case ' ' : case ' ' : buf . append ( ( char ) c ) ; break ; default : buf . append ( String . format ( "\\x%02x" , ( c & 0xff ) ) ) ; break ; } continue ; } } if ( c == ' ' ) { buf . append ( "\\\"" ) ; } else if ( c == ' ' ) { buf . append ( "\\\\" ) ; } else buf . append ( ( char ) c ) ; } return buf . toString ( ) ; }


Input: Given a CDM string insert backslashes before <toescape > characters . [CODESPLIT] static public String backslashEscapeCDMString ( String s , String toescape ) { if ( toescape == null || toescape . length ( ) == 0 ) return s ; if ( s == null || s . length ( ) == 0 ) return s ; StringBuilder buf = new StringBuilder ( ) ; for ( int i = 0 ; i < s . length ( ) ; i ++ ) { int c = s . charAt ( i ) ; if ( toescape . indexOf ( c ) >= 0 ) { buf . append ( ' ' ) ; } buf . append ( ( char ) c ) ; } return buf . toString ( ) ; }


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 ) ) ; // Get VarNotes and TypeNotes Notes n = ( ( Nc4DSP ) this . dsp ) . find ( this . template ) ; Object result = null ; long count = DapUtil . sliceProduct ( slices ) ; VarNotes vn = ( VarNotes ) n ; TypeNotes ti = vn . getBaseType ( ) ; if ( getContainer ( ) == null ) { if ( rank == 0 ) { //scalar result = readAtomicScalar ( vn , ti ) ; } else { result = readAtomicVector ( vn , ti , count , slices ) ; } } else { // field of a structure instance or record long elemsize = ( ( DapType ) ti . get ( ) ) . getSize ( ) ; assert ( this . container != null ) ; long trueoffset = computeTrueOffset ( this ) ; Nc4Pointer varmem = getMemory ( ) ; Nc4Pointer mem = varmem . share ( trueoffset , count * elemsize ) ; result = getatomicdata ( ti . getType ( ) , count , elemsize , mem ) ; } return result ; }


Input: Read a top - level scalar atomic variable [CODESPLIT] protected Object readAtomicScalar ( VarNotes vi , TypeNotes ti ) throws DapException { DapVariable atomvar = ( DapVariable ) getTemplate ( ) ; // Get into memory Nc4prototypes nc4 = ( ( Nc4DSP ) this . dsp ) . getJNI ( ) ; int ret ; DapType basetype = ti . getType ( ) ; Object result = null ; if ( basetype . isFixedSize ( ) ) { long memsize = ( ( DapType ) ti . get ( ) ) . getSize ( ) ; Nc4Pointer mem = Nc4Pointer . allocate ( memsize ) ; readcheck ( nc4 , ret = nc4 . nc_get_var ( vi . gid , vi . id , mem . p ) ) ; setMemory ( mem ) ; result = getatomicdata ( ti . getType ( ) , 1 , mem . size , mem ) ; } else if ( basetype . isStringType ( ) ) { String [ ] s = new String [ 1 ] ; readcheck ( nc4 , ret = nc4 . nc_get_var_string ( vi . gid , vi . id , s ) ) ; result = s ; } else if ( basetype . isOpaqueType ( ) ) { Nc4Pointer mem = Nc4Pointer . allocate ( ti . getSize ( ) ) ; readcheck ( nc4 , ret = nc4 . nc_get_var ( vi . gid , vi . id , mem . p ) ) ; setMemory ( mem ) ; ByteBuffer [ ] buf = new ByteBuffer [ 1 ] ; buf [ 0 ] = mem . p . getByteBuffer ( 0 , ti . getSize ( ) ) ; result = buf ; } else throw new DapException ( "Unexpected atomic type: " + basetype ) ; return result ; }


Input: Nc4Cursor Extensions [CODESPLIT] public long getOffset ( ) { DapVariable dv = ( DapVariable ) getTemplate ( ) ; Notes n = ( ( Nc4DSP ) this . dsp ) . find ( dv ) ; return n . getOffset ( ) ; }


Input: Utilities [CODESPLIT] protected long getElementSize ( TypeNotes ti ) { DapType type = ti . getType ( ) ; switch ( type . getTypeSort ( ) ) { case Structure : case Sequence : return ti . getSize ( ) ; case String : case URL : return Pointer . SIZE ; case Enum : return getElementSize ( ( TypeNotes ) ( ( Nc4DSP ) getDSP ( ) ) . find ( ti . enumbase , NoteSort . TYPE ) ) ; case Opaque : return ti . getSize ( ) ; default : return type . getSize ( ) ; } }


Input: Given a field ref compute the true offset with respect to it top - level containing structure / record [CODESPLIT] long computeTrueOffset ( Nc4Cursor f ) throws DapException { List < Nc4Cursor > path = getCursorPath ( f ) ; long totaloffset = 0 ; Nc4Cursor current ; // First element is presumed to be a structure ore record variable, // and that its memory covers only it's instance. // Walk intermediate nodes for ( int i = 1 ; i < ( path . size ( ) - 1 ) ; i ++ ) { current = path . get ( i ) ; DapVariable template = ( DapVariable ) current . getTemplate ( ) ; VarNotes vi = ( VarNotes ) ( ( Nc4DSP ) getDSP ( ) ) . find ( template ) ; long size = vi . getSize ( ) ; long offset = current . getOffset ( ) ; long pos = 0 ; switch ( current . getScheme ( ) ) { case SEQUENCE : case STRUCTURE : pos = current . getIndex ( ) . index ( ) ; break ; case RECORD : // readrecord will have set our memory to the start of the record pos = 0 ; break ; default : throw new DapException ( "Illegal cursor type: " + current . getScheme ( ) ) ; } long delta = size * pos + offset ; totaloffset += delta ; } assert path . get ( path . size ( ) - 1 ) == f ; totaloffset += f . getOffset ( ) ; return totaloffset ; }


Input: Given a cursor get a list of containing cursors with the following constraints . 1 . the first element in the path is a top - level variable . 2 . the remaining elements are the enclosing compound variables 3 . the last element is the incoming cursor . [CODESPLIT] static List < Nc4Cursor > getCursorPath ( Nc4Cursor cursor ) { List < Nc4Cursor > path = new ArrayList <> ( ) ; for ( ; ; ) { if ( ! cursor . getScheme ( ) . isCompoundArray ( ) ) // suppress path . add ( 0 , cursor ) ; if ( cursor . getScheme ( ) == Scheme . SEQUENCE ) { // Stop here because the sequence has the vlen mem as its mem break ; } Nc4Cursor next = ( Nc4Cursor ) cursor . getContainer ( ) ; if ( next == null ) { assert cursor . getTemplate ( ) . isTopLevel ( ) ; break ; } assert next . getTemplate ( ) . getSort ( ) == DapSort . VARIABLE ; cursor = next ; } return path ; }


Input: If the basetype is sequence ( = > isVlen () ) then return the type of the first field of this sequence . Otherwise return null . [CODESPLIT] public TypeNotes getVlenType ( DapVariable v ) { DapType t = v . getBaseType ( ) ; if ( t . getSort ( ) != DapSort . SEQUENCE || ( ( DapSequence ) t ) . getFields ( ) . size ( ) != 1 ) throw new IllegalArgumentException ( t . getFQN ( ) ) ; DapSequence ds = ( DapSequence ) t ; DapVariable f0 = ds . getField ( 0 ) ; DapType f0type = f0 . getBaseType ( ) ; return ( TypeNotes ) ( ( Nc4DSP ) this . dsp ) . find ( f0type ) ; }


Input: { [CODESPLIT] @ Override public File saveObjectToFile ( S3URI s3uri , File file ) throws IOException { Optional < File > cachedFile = objectFileCache . getIfPresent ( s3uri ) ; if ( cachedFile == null ) { logger . debug ( "Object cache MISS: '%s'" , s3uri ) ; // Do download below. } else { logger . debug ( "Object cache hit: '%s'" , s3uri ) ; if ( ! cachedFile . isPresent ( ) ) { return null ; } else if ( ! cachedFile . get ( ) . exists ( ) ) { logger . info ( String . format ( "Found cache entry {'%s'-->'%s'}, but local file doesn't exist. " + "Was it deleted? Re-downloading." , s3uri , cachedFile . get ( ) ) ) ; objectFileCache . invalidate ( s3uri ) ; // Evict old entry. Re-download below. } else if ( ! cachedFile . get ( ) . equals ( file ) ) { // Copy content of cachedFile to file. Evict cachedFile from the cache. Files . copy ( cachedFile . get ( ) , file ) ; objectFileCache . put ( s3uri , Optional . of ( file ) ) ; return file ; } else { return file ; // File already contains the content of the object at s3uri. } } cachedFile = Optional . fromNullable ( threddsS3Client . saveObjectToFile ( s3uri , file ) ) ; objectFileCache . put ( s3uri , cachedFile ) ; return cachedFile . orNull ( ) ; }


Input: Convenience method for searching below <code > container< / code > in the component hierarchy and return nested components that are instances of class <code > clazz< / code > it finds . Returns an empty list if no such components exist in the container . <P > Invoking this method with a class parameter of JComponent . class will return all nested components . <P > This method invokes getDescendantsOfType ( clazz container true ) [CODESPLIT] public static < T extends JComponent > List < T > getDescendantsOfType ( Class < T > clazz , Container container ) { return getDescendantsOfType ( clazz , container , true ) ; }


Input: Convenience method for searching below <code > container< / code > in the component hierarchy and return nested components that are instances of class <code > clazz< / code > it finds . Returns an empty list if no such components exist in the container . <P > Invoking this method with a class parameter of JComponent . class will return all nested components . [CODESPLIT] public static < T extends JComponent > List < T > getDescendantsOfType ( Class < T > clazz , Container container , boolean nested ) { List < T > tList = new ArrayList < T > ( ) ; for ( Component component : container . getComponents ( ) ) { if ( clazz . isAssignableFrom ( component . getClass ( ) ) ) { tList . add ( clazz . cast ( component ) ) ; } if ( nested || ! clazz . isAssignableFrom ( component . getClass ( ) ) ) { tList . addAll ( SwingUtils . < T > getDescendantsOfType ( clazz , ( Container ) component , nested ) ) ; } } return tList ; }


Input: Convenience method that searches below <code > container< / code > in the component hierarchy and returns the first found component that is an instance of class <code > clazz< / code > and has the bound property value . Returns { @code null } if such component cannot be found . [CODESPLIT] public static < T extends JComponent > T getDescendantOfType ( Class < T > clazz , Container container , String property , Object value , boolean nested ) throws IllegalArgumentException { List < T > list = getDescendantsOfType ( clazz , container , nested ) ; return getComponentFromList ( clazz , list , property , value ) ; }


Input: Convenience method that searches below <code > container< / code > in the component hierarchy in a depth first manner and returns the first found component of class <code > clazz< / code > having the bound property value . <P > Returns { @code null } if such component cannot be found . <P > This method invokes getDescendantOfClass ( clazz container property value true ) [CODESPLIT] public static < T extends JComponent > T getDescendantOfClass ( Class < T > clazz , Container container , String property , Object value ) throws IllegalArgumentException { return getDescendantOfClass ( clazz , container , property , value , true ) ; }


Input: Convenience method that searches below <code > container< / code > in the component hierarchy in a depth first manner and returns the first found component of class <code > clazz< / code > having the bound property value . <P > Returns { @code null } if such component cannot be found . [CODESPLIT] public static < T extends JComponent > T getDescendantOfClass ( Class < T > clazz , Container container , String property , Object value , boolean nested ) throws IllegalArgumentException { List < T > list = getDescendantsOfClass ( clazz , container , nested ) ; return getComponentFromList ( clazz , list , property , value ) ; }


Input: Convenience method for mapping a container in the hierarchy to its contained components . The keys are the containers and the values are lists of contained components . <P > Implementation note : The returned value is a HashMap and the values are of type ArrayList . This is subject to change so callers should code against the interfaces Map and List . [CODESPLIT] public static Map < JComponent , List < JComponent > > getComponentMap ( JComponent container , boolean nested ) { HashMap < JComponent , List < JComponent > > retVal = new HashMap < JComponent , List < JComponent > > ( ) ; for ( JComponent component : getDescendantsOfType ( JComponent . class , container , false ) ) { if ( ! retVal . containsKey ( container ) ) { retVal . put ( container , new ArrayList < JComponent > ( ) ) ; } retVal . get ( container ) . add ( component ) ; if ( nested ) { retVal . putAll ( getComponentMap ( component , nested ) ) ; } } return retVal ; }


Input: Convenience method for retrieving a subset of the UIDefaults pertaining to a particular class . [CODESPLIT] public static UIDefaults getUIDefaultsOfClass ( Class clazz ) { String name = clazz . getName ( ) ; name = name . substring ( name . lastIndexOf ( "." ) + 2 ) ; return getUIDefaultsOfClass ( name ) ; }


Input: Convenience method for retrieving a subset of the UIDefaults pertaining to a particular class . [CODESPLIT] public static UIDefaults getUIDefaultsOfClass ( String className ) { UIDefaults retVal = new UIDefaults ( ) ; UIDefaults defaults = UIManager . getLookAndFeelDefaults ( ) ; List < ? > listKeys = Collections . list ( defaults . keys ( ) ) ; for ( Object key : listKeys ) { if ( key instanceof String && ( ( String ) key ) . startsWith ( className ) ) { String stringKey = ( String ) key ; String property = stringKey ; if ( stringKey . contains ( "." ) ) { property = stringKey . substring ( stringKey . indexOf ( "." ) + 1 ) ; } retVal . put ( property , defaults . get ( key ) ) ; } } return retVal ; }


Input: Convenience method for retrieving the UIDefault for a single property of a particular class . [CODESPLIT] public static Object getUIDefaultOfClass ( Class clazz , String property ) { Object retVal = null ; UIDefaults defaults = getUIDefaultsOfClass ( clazz ) ; List < Object > listKeys = Collections . list ( defaults . keys ( ) ) ; for ( Object key : listKeys ) { if ( key . equals ( property ) ) { return defaults . get ( key ) ; } if ( key . toString ( ) . equalsIgnoreCase ( property ) ) { retVal = defaults . get ( key ) ; } } return retVal ; }


Input: Convenience method for obtaining most non - null human readable properties of a JComponent . Array properties are not included . <P > Implementation note : The returned value is a HashMap . This is subject to change so callers should code against the interface Map . [CODESPLIT] public static Map < Object , Object > getProperties ( JComponent component ) { Map < Object , Object > retVal = new HashMap < Object , Object > ( ) ; Class < ? > clazz = component . getClass ( ) ; Method [ ] methods = clazz . getMethods ( ) ; Object value = null ; for ( Method method : methods ) { if ( method . getName ( ) . matches ( "^(is|get).*" ) && method . getParameterTypes ( ) . length == 0 ) { try { Class returnType = method . getReturnType ( ) ; if ( returnType != void . class && ! returnType . getName ( ) . startsWith ( "[" ) && ! setExclude . contains ( method . getName ( ) ) ) { String key = method . getName ( ) ; value = method . invoke ( component ) ; if ( value != null && ! ( value instanceof Component ) ) { retVal . put ( key , value ) ; } } // ignore exceptions that arise if the property could not be accessed } catch ( IllegalAccessException ex ) { } catch ( IllegalArgumentException ex ) { } catch ( InvocationTargetException ex ) { } } } return retVal ; }


Input: Convenience method to obtain the Swing class from which this component was directly or indirectly derived . [CODESPLIT] public static < T extends JComponent > Class getJClass ( T component ) { Class < ? > clazz = component . getClass ( ) ; while ( ! clazz . getName ( ) . matches ( "javax.swing.J[^.]*$" ) ) { clazz = clazz . getSuperclass ( ) ; } return clazz ; }


Input: The goal here is to process the serialized databuffer and locate top - level variable positions in the serialized databuffer . Access to non - top - level variables is accomplished on the fly . [CODESPLIT] public void compile ( ) throws DapException { assert ( this . dataset != null && this . databuffer != null ) ; // iterate over the variables represented in the databuffer for ( DapVariable vv : this . dataset . getTopVariables ( ) ) { D4Cursor data = compileVar ( vv , null ) ; this . dsp . addVariableData ( vv , data ) ; } }


Input: Compile a structure array . [CODESPLIT] protected D4Cursor compileStructureArray ( DapVariable var , D4Cursor container ) throws DapException { DapStructure dapstruct = ( DapStructure ) var . getBaseType ( ) ; D4Cursor structarray = new D4Cursor ( Scheme . STRUCTARRAY , this . dsp , var , container ) . setOffset ( getPos ( this . databuffer ) ) ; List < DapDimension > dimset = var . getDimensions ( ) ; long dimproduct = DapUtil . dimProduct ( dimset ) ; D4Cursor [ ] instances = new D4Cursor [ ( int ) dimproduct ] ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) , dimset ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; D4Cursor instance = compileStructure ( var , dapstruct , structarray ) ; instance . setIndex ( index ) ; instances [ ( int ) index . index ( ) ] = instance ; } structarray . setElements ( instances ) ; return structarray ; }


Input: Compile a structure instance . [CODESPLIT] protected D4Cursor compileStructure ( DapVariable var , DapStructure dapstruct , D4Cursor container ) throws DapException { int pos = getPos ( this . databuffer ) ; D4Cursor d4ds = new D4Cursor ( Scheme . STRUCTURE , ( D4DSP ) this . dsp , var , container ) . setOffset ( pos ) ; List < DapVariable > dfields = dapstruct . getFields ( ) ; for ( int m = 0 ; m < dfields . size ( ) ; m ++ ) { DapVariable dfield = dfields . get ( m ) ; D4Cursor dvfield = compileVar ( dfield , d4ds ) ; d4ds . addField ( m , dvfield ) ; assert dfield . getParent ( ) != null ; } return d4ds ; }


Input: Compile a sequence array . [CODESPLIT] protected D4Cursor compileSequenceArray ( DapVariable var , D4Cursor container ) throws DapException { DapSequence dapseq = ( DapSequence ) var . getBaseType ( ) ; D4Cursor seqarray = new D4Cursor ( Scheme . SEQARRAY , this . dsp , var , container ) . setOffset ( getPos ( this . databuffer ) ) ; List < DapDimension > dimset = var . getDimensions ( ) ; long dimproduct = DapUtil . dimProduct ( dimset ) ; D4Cursor [ ] instances = new D4Cursor [ ( int ) dimproduct ] ; Odometer odom = Odometer . factory ( DapUtil . dimsetToSlices ( dimset ) , dimset ) ; while ( odom . hasNext ( ) ) { Index index = odom . next ( ) ; D4Cursor instance = compileSequence ( var , dapseq , seqarray ) ; instance . setIndex ( index ) ; instances [ ( int ) index . index ( ) ] = instance ; } seqarray . setElements ( instances ) ; return seqarray ; }


Input: Compile a sequence as a set of records . [CODESPLIT] public D4Cursor compileSequence ( DapVariable var , DapSequence dapseq , D4Cursor container ) throws DapException { int pos = getPos ( this . databuffer ) ; D4Cursor seq = new D4Cursor ( Scheme . SEQUENCE , this . dsp , var , container ) . setOffset ( pos ) ; List < DapVariable > dfields = dapseq . getFields ( ) ; // Get the count of the number of records long nrecs = getCount ( this . databuffer ) ; for ( int r = 0 ; r < nrecs ; r ++ ) { pos = getPos ( this . databuffer ) ; D4Cursor rec = ( D4Cursor ) new D4Cursor ( D4Cursor . Scheme . RECORD , this . dsp , var , container ) . setOffset ( pos ) . setRecordIndex ( r ) ; for ( int m = 0 ; m < dfields . size ( ) ; m ++ ) { DapVariable dfield = dfields . get ( m ) ; D4Cursor dvfield = compileVar ( dfield , rec ) ; rec . addField ( m , dvfield ) ; assert dfield . getParent ( ) != null ; } seq . addRecord ( rec ) ; } return seq ; }


Input: Utilities [CODESPLIT] protected int extractChecksum ( ByteBuffer data ) throws DapException { assert ChecksumMode . DAP . enabled ( this . checksummode ) ; if ( data . remaining ( ) < DapUtil . CHECKSUMSIZE ) throw new DapException ( "Short serialization: missing checksum" ) ; return data . getInt ( ) ; }


Input: Reads <code > n< / code > little - endian doubles from a random access file . <p / > <p > This method is provided for speed when accessing a number of consecutive values of the same type . [CODESPLIT] public final void readLEDoubles ( double [ ] d , int n ) throws IOException { int nLeft = n ; int dCount = 0 ; int nToRead = kLongs ; while ( nLeft > 0 ) { if ( nToRead > nLeft ) nToRead = nLeft ; readLELongs ( longWorkSpace , nToRead ) ; for ( int i = 0 ; i < nToRead ; i ++ ) { d [ dCount ++ ] = Double . longBitsToDouble ( longWorkSpace [ i ] ) ; } nLeft -= nToRead ; } }


Input: read a long in little endian format [CODESPLIT] public long readLELong ( ) throws IOException { readFully ( w , 0 , 8 ) ; return ( long ) ( w [ 7 ] & 0xff ) << 56 | ( long ) ( w [ 6 ] & 0xff ) << 48 | ( long ) ( w [ 5 ] & 0xff ) << 40 | ( long ) ( w [ 4 ] & 0xff ) << 32 | ( long ) ( w [ 3 ] & 0xff ) << 24 | ( long ) ( w [ 2 ] & 0xff ) << 16 | ( long ) ( w [ 1 ] & 0xff ) << 8 | ( long ) ( w [ 0 ] & 0xff ) ; }


Input: Reads <code > n< / code > little - endian longs from a random access file . <p / > <p > This method is provided for speed when accessing a number of consecutive values of the same type . [CODESPLIT] public final void readLELongs ( long lbuf [ ] , int n ) throws IOException { int nLeft = n ; int lCount = 0 ; int nToRead = kLongs ; while ( nLeft > 0 ) { if ( nToRead > nLeft ) nToRead = nLeft ; readFully ( byteWorkSpace , 0 , 8 * nToRead ) ; int j = 0 ; for ( int i = 0 ; i < nToRead ; i ++ ) { lbuf [ lCount ++ ] = ( long ) ( byteWorkSpace [ j ] & 0xff ) | ( long ) ( byteWorkSpace [ j + 1 ] & 0xff ) << 8 | ( long ) ( byteWorkSpace [ j + 2 ] & 0xff ) << 16 | ( long ) ( byteWorkSpace [ j + 3 ] & 0xff ) << 24 | ( long ) ( byteWorkSpace [ j + 4 ] & 0xff ) << 32 | ( long ) ( byteWorkSpace [ j + 5 ] & 0xff ) << 40 | ( long ) ( byteWorkSpace [ j + 6 ] & 0xff ) << 48 | ( long ) ( byteWorkSpace [ j + 7 ] & 0xff ) << 56 ; j += 8 ; } nLeft -= nToRead ; } }