public boolean checkEvents(BundleEvent[] expevents) {
   boolean res = true;
   for (int i = 0; i < 20; i++) {
     try {
       Thread.sleep(100);
     } catch (InterruptedException ignore) {
     }
     if (events.size() == expevents.length) {
       break;
     }
   }
   if (events.size() == expevents.length) {
     for (int i = 0; i < events.size(); i++) {
       BundleEvent be = (BundleEvent) events.elementAt(i);
       if (!(be.getBundle().equals(expevents[i].getBundle())
           && be.getType() == expevents[i].getType())) {
         res = false;
       }
     }
   } else {
     res = false;
   }
   if (!res) {
     out.println("Real events");
     for (int i = 0; i < events.size(); i++) {
       BundleEvent be = (BundleEvent) events.elementAt(i);
       out.println("Event " + be.getBundle() + ", Type " + be.getType());
     }
     out.println("Expected events");
     for (int i = 0; i < expevents.length; i++) {
       out.println("Event " + expevents[i].getBundle() + ", Type " + expevents[i].getType());
     }
   }
   return res;
 }
Пример #2
0
 /**
  * Remove the first null element found in the specified vector. Return true if a null element was
  * found and removed. Return false if a null element was not found.
  */
 private boolean removeNullElement(Vector v) {
   for (int i = 0; i < v.size(); i++) {
     if (v.elementAt(i) == null) {
       v.removeElementAt(i);
       return true;
     }
   }
   return false;
 }
  protected void fireHPubReqCompleteEvent(RequestCompleteEvent evt) {
    Vector currentListenerList = null;

    synchronized (this) {
      currentListenerList = (Vector) listenerList.clone();
    }
    for (int i = 0; i < currentListenerList.size(); i++) {
      HPubReqCompleteListener listener = (HPubReqCompleteListener) currentListenerList.elementAt(i);
      listener.hPubReqComplete(evt);
    }
  }
Пример #4
0
 /**
  * Assert that the elements in two vectors are equal. If they are not, throw an
  * AssertionFailedError. Order of the elements is significant.
  *
  * @param message the error message
  * @param expected the expected value of an vector
  * @param actual the actual value of an vector
  */
 protected void assertElementsEqual(String message, Vector expected, Vector actual) {
   if (expected == actual) {
     return;
   }
   if (expected.size() != actual.size()) {
     this.assertTrue(this.notEqualsMessage(message, expected, actual), false);
   }
   for (int i = 0; i < expected.size(); i++) {
     Object e1 = expected.elementAt(i);
     Object e2 = actual.elementAt(i);
     if (e1 == null) { // avoid null pointer exception
       if (e2 != null) {
         this.assertTrue(this.notEqualsMessage(message, expected, actual), false);
       }
     } else {
       if (!e1.equals(e2)) {
         this.assertTrue(this.notEqualsMessage(message, expected, actual), false);
       }
     }
   }
 }
Пример #5
0
  public Class[] getClassesFromClass(Class c) {
    Vector cList = new Vector();
    Class cTemp;
    Class[] aList;

    cTemp = c;
    while ((cTemp = cTemp.getSuperclass()) != null) {
      cList.addElement(cTemp);
    }

    aList = new Class[cList.size()];
    for (int i = 0; i < cList.size(); i++) {
      aList[i] = (Class) cList.elementAt(i);
    }
    return aList;
  }
Пример #6
0
  public CompositeData getNextEntry(Object[] indexObjects) {

    // User code starts here
    if (!agentName.initAlert()) return null;

    String previousKeys[] = {indexObjects[0].toString(), indexObjects[1].toString()};
    String keys[] = getNextAlert(previousKeys);

    if (keys == null) return null;

    String source = keys[0];

    // String ownerName = keys[1];

    String entity = keys[1];

    Alert alert1 = new Alert();

    alert1.setSource(source);

    //	alert1.setOwnerName(ownerName);

    alert1.setEntity(entity);

    Alert alert2 = new Alert();

    alert2.setModTime(System.currentTimeMillis());

    Vector alerts = null;

    try {
      alerts = agentName.alertAPI.getAlerts(alert1, alert2);

      if (alerts != null) return makeComData((Alert) alerts.elementAt(0));
    } catch (Exception e) {
      return null;
    }

    // User code ends here
    return null;
  }
Пример #7
0
 /**
  * Assert that the elements in two vectors are equal. If they are not, throw an
  * AssertionFailedError. The order of the elements is ignored.
  *
  * @param message the error message
  * @param expected the expected value of an vector
  * @param actual the actual value of an vector
  */
 protected void assertUnorderedElementsEqual(String message, Vector expected, Vector actual) {
   if (expected == actual) {
     return;
   }
   if (expected.size() != actual.size()) {
     this.assertTrue(this.notEqualsMessage(message, expected, actual), false);
   }
   Vector temp = (Vector) actual.clone();
   for (int i = 0; i < expected.size(); i++) {
     Object e1 = expected.elementAt(i);
     if (e1 == null) { // avoid null pointer exception
       if (!this.removeNullElement(temp)) {
         this.assertTrue(this.notEqualsMessage(message, expected, actual), false);
       }
     } else {
       if (!temp.removeElement(e1)) {
         this.assertTrue(this.notEqualsMessage(message, expected, actual), false);
       }
     }
   }
 }
Пример #8
0
  /**
   * ************************************************************************* * * Method:
   * performGet * Input: CMIRequest theRequest - tokenized LMSGetValue() request * DMErrorManager
   * dmErrorMgr - Error manager * * Output: String - the value portion of the element for the
   * LMSGetValue() * * Description: This method takes the necessary steps to process * an
   * LMSGetValue() request *
   * *************************************************************************
   */
  public String performGet(CMIRequest theRequest, DMErrorManager dmErrorMgr) {
    if (true) {
      System.out.println("CMIObjectives::performGet()");
    }

    // Resultant value to return
    String result = new String("");

    // Check to make sure this is a valid LMSGetValue() request
    if (isValidObjRequest(theRequest) == true) {
      // Get the next token off of the request
      String token = theRequest.getNextToken();

      if (true) {
        System.out.println("Token being processed: " + token);
      }

      // Check to see if the Request has more tokens to process
      if (theRequest.hasMoreTokensToProcess()) {
        // Token has to be an array index
        try {
          // Convert the string integer to a number
          Integer tmpInt = new Integer(token);
          int indexOfArr = tmpInt.intValue();

          try {
            // Get the Objective Data that is positioned at the input index
            CMIObjectiveData objData = (CMIObjectiveData) objectives.elementAt(indexOfArr);

            // Invoke the performGet on the Objective Data returned.
            result = objData.performGet(theRequest, dmErrorMgr);
          } catch (ArrayIndexOutOfBoundsException e) {
            if (true) {
              System.out.println("Element does not exist at the given index");
              System.out.println("Index: " + indexOfArr);
            }

            // if element has not been initialized, return Invalid
            // Argument Error
            dmErrorMgr.SetCurrentErrorCode("201");
          }
        } catch (NumberFormatException nfe) {
          if (true) {
            // Invalid parameter passed to LMSGetValue()
            System.out.println("Error - Data Model Element not implemented");
            System.out.println(
                "Invalid data model element: "
                    + theRequest.getRequest()
                    + " passed to LMSGetValue()");
            System.out.println("Array index required");
          }

          // Notify error manager
          dmErrorMgr.SetCurrentErrorCode("401");
        }
      } else {
        // No more tokens to process

        // Check to see if the request is for the children of Core Data
        if (theRequest.isAChildrenRequest()) {
          // Set result to the string of children
          result = getChildren();
        } else if (theRequest.isACountRequest()) {
          int count = 0;

          count = objectives.size();

          System.out.println("Count: " + count);

          Integer tmpInt = new Integer(count);
          result = tmpInt.toString();
        } else {
          if (true) {
            System.out.println("Error - Data Model Element not implemented");
            System.out.println("Invalid request: " + theRequest.getRequest());
          }

          dmErrorMgr.recNotImplementedError(theRequest);
        }
      }
    } else {
      if (true) {
        // Error - Data Model Element not implemented
        System.out.println("Error - Data Model Element not implemented");
        System.out.println("Invalid request: " + theRequest.getRequest());
      }

      dmErrorMgr.SetCurrentErrorCode("401");
    }

    // Done processing.  Let CMIRequest object know the processing
    // of the LMSGetValue() is done.
    theRequest.done();

    if (true) {
      System.out.println("Returning from CMIObjectives::performGet()");
      System.out.println("Value returned: " + result);
    }

    return result;
  } // end of performGet()
Пример #9
0
  /**
   * ************************************************************************ * * Method: performSet
   * * Input: CMIRequest theRequest - tokenized LMSSetValue() request * DMErrorManager dmErroMgr -
   * Error Manager * Output: none * * Description: This method takes the necessary steps to process
   * * an LMSSetValue() request *
   * *************************************************************************
   */
  public void performSet(CMIRequest theRequest, DMErrorManager dmErrorMgr) {
    if (true) {
      System.out.println("CMIObjectives::performSet()");
    }

    // The next token must be an array.  If not throw
    // an exception for this request.
    int index = -1;

    // Get the next token off of the request
    String token = theRequest.getNextToken();

    if (true) {
      System.out.println("Token being processed: " + token);
    }

    // Check to see if next token is an array index.  For
    // a LMSSetValue() this is true
    try {
      // Try to convert the token to the index
      Integer tmpInt = new Integer(token);
      index = tmpInt.intValue();

      // Get the Objective Data at position of the index
      CMIObjectiveData tmpObj = (CMIObjectiveData) objectives.elementAt(index);

      // An objective existed at the given index.
      // Invoke the performSet() on the Objective Data
      tmpObj.performSet(theRequest, dmErrorMgr);

      // replace the old ObjectiveData with the newly set Objective
      // Data.
      objectives.set(index, tmpObj);
    } catch (NumberFormatException nfe) {
      if (theRequest.isAKeywordRequest() == true) {
        dmErrorMgr.recKeyWordError(token);
      } else {
        if (true) {
          // Invalid parameter passed to LMSSetValue()
          System.out.println("Error - Data Model Element not implemented");
          System.out.println(
              "Invalid data model element: "
                  + theRequest.getRequest()
                  + " passed to LMSSetValue()");
        }

        // Notify error manager
        dmErrorMgr.recNotImplementedError(theRequest);
      }
    } catch (ArrayIndexOutOfBoundsException e) {
      if (true) {
        System.out.println("First time setting the Objective Data");
      }

      if (index <= objectives.size()) {
        // A new Objective Data.
        CMIObjectiveData objData = new CMIObjectiveData();

        // Invoke performSet() on the new Objective Data
        objData.performSet(theRequest, dmErrorMgr);

        // Place the Objective data into the vector at the
        // index position
        objectives.add(index, objData);
      } else {
        dmErrorMgr.SetCurrentErrorCode("201");
      }
    }

    // Done processing.  Let CMIRequest object know the processing
    // of the LMSGetValue() is done.
    theRequest.done();

    return;
  } // end of performSet
Пример #10
0
  /**
   * Parse the section file and fill in the Dbase.
   *
   * @return Success code
   */
  public void parse() throws Exception {
    JOAParameter tempProperties[] = new JOAParameter[100];
    FileInputStream in = null;
    DataInputStream inData = null;
    short inShort = 0;
    long bytesRead = 0;
    long bytesInFile = mFile.length();
    short[] sarray = new short[1];
    int mTotalStns = 0;

    EPSProgressDialog mProgress = new EPSProgressDialog(new Frame(), mProgressStr, Color.blue);
    mProgress.setVisible(true);

    // Get an epic key database specific to JOA
    EPIC_Key_DB mEpicKeyDB = new EPIC_Key_DB("joa_epic.key");

    // Get an epic key database specific to JOA
    EPIC_Key_DB mOrigEpicKeyDB = new EPIC_Key_DB("epic.key");

    // create a vector for temporary storage of the dbases
    Vector dBases = new Vector(100);

    try {
      in = new FileInputStream(mFile);
      BufferedInputStream bis = new BufferedInputStream(in, 1000000);
      inData = new DataInputStream(bis);

      // read version
      short vers = inData.readShort();
      bytesRead += 2;

      if (vers < 2) {
        FileImportException fiex = new FileImportException();
        String errStr = "Invalid version for a JOA binary file";
        fiex.setErrorType(errStr);
        throw fiex;
      }

      // read number of bytes in file description string
      inShort = inData.readShort();
      bytesRead += 2;

      // read the file description String
      byte buf[] = new byte[inShort];
      inData.read(buf, 0, inShort);
      String fileDescrip = new String(buf);
      bytesRead += inShort;

      // create a new open file object
      JOADataFile of = new JOADataFile(fileDescrip);

      // read the number of sections
      int numSections = inData.readShort();
      bytesRead += 2;

      // read each section
      JOASection sech;
      int ord = 0;
      for (int s = 0; s < numSections; s++) {
        mProgress.setPercentComplete(100.0 * ((double) bytesRead / (double) bytesInFile));

        // read the section header
        inShort = inData.readShort();
        bytesRead += 2;
        byte buf1[] = new byte[inShort];
        inData.read(buf1, 0, inShort);
        String sectionDescrip = new String(buf1);
        bytesRead += inShort;

        // read the ship code
        byte bufsc[] = new byte[2];
        bufsc[0] = inData.readByte();
        bufsc[1] = inData.readByte();
        String shipCode = new String(bufsc);
        bytesRead += 2;

        // read num casts
        int numCasts = inData.readShort();
        bytesRead += 2;

        // read num parameters
        int numVars = inData.readShort();
        bytesRead += 2;

        // quality code
        int qcStd = 1;
        if (vers == 4) {
          qcStd = inData.readShort();
          bytesRead += 2;
        }

        // create a new section
        of.mNumSections++;
        sech = new JOASection(of.mNumSections, sectionDescrip, shipCode, numCasts, numVars);

        if (vers == 2) {
          // read the properties
          byte bufv[] = new byte[4];
          for (int p = 0; p < numVars; p++) {
            // parameter name
            inData.read(bufv, 0, 4);
            String tempVar = new String(bufv);
            bytesRead += 4;

            // units
            inShort = inData.readShort();
            bytesRead += 2;

            String units = null;
            if (inShort > 0) {
              byte buf11[] = new byte[inShort];
              inData.read(buf11, 0, inShort);
              units = new String(buf11);
              bytesRead += inShort;
            }

            // convert varnames to UC
            tempVar.toUpperCase();

            // create new property
            tempProperties[p] = new JOAParameter(tempVar, units);

            // add this property to the section property list
            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits =
                  EPS_Util.paramNameToJOAUnits(false, tempProperties[0].mVarLabel);
            }

            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits = new String("na");
            }
            tempProperties[p].mCastOrObs = EPSConstants.ALL_OBS;

            // read the actual scale
            int actScale = inData.readShort();
            bytesRead += 2;

            if (actScale != 0) tempProperties[p].mActScale = 1.0 / (double) actScale;
            else tempProperties[p].mActScale = 1.0;

            // read the actual origin
            int actOrigin = inData.readShort();
            tempProperties[p].mActOrigin = (double) actOrigin * tempProperties[p].mActScale;

            // read reverse y
            int reverseY = inData.readShort();
            bytesRead += 2;

            if (reverseY == 0) tempProperties[p].mReverseY = false;
            else tempProperties[p].mReverseY = true;

            tempProperties[p].mWasCalculated = false;
          }
        } else {
          // read the properties
          String tempVar = null;
          for (int p = 0; p < numVars; p++) {
            // length of parameter name
            inShort = inData.readShort();
            bytesRead += 2;

            // parameter name
            if (inShort > 0) {
              byte buf13[] = new byte[inShort];
              inData.read(buf13, 0, inShort);
              tempVar = new String(buf13);
              bytesRead += inShort;
            }

            // units
            inShort = inData.readShort();
            bytesRead += 2;

            String units = null;
            if (inShort > 0) {
              byte buf11[] = new byte[inShort];
              inData.read(buf11, 0, inShort);
              units = new String(buf11);
              bytesRead += inShort;
            }

            // convert varnames to UC
            tempVar = tempVar.toUpperCase();

            // create new property
            tempProperties[p] = new JOAParameter(tempVar, units);

            // add this property to the section property list
            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits =
                  EPS_Util.paramNameToJOAUnits(false, tempProperties[0].mVarLabel);
            }

            if (tempProperties[p].mUnits == null) {
              tempProperties[p].mUnits = new String("na");
            }
            tempProperties[p].mCastOrObs = EPSConstants.ALL_OBS;

            // read the actual scale
            int actScale = inData.readShort();
            bytesRead += 2;
            if (actScale != 0) tempProperties[p].mActScale = 1.0 / (double) actScale;
            else tempProperties[p].mActScale = 1.0;

            // read the actual origin
            int actOrigin = inData.readShort();
            tempProperties[p].mActOrigin = (double) actOrigin * tempProperties[p].mActScale;

            // read reverse y
            int reverseY = inData.readShort();
            bytesRead += 2;
            if (reverseY == 0) tempProperties[p].mReverseY = false;
            else tempProperties[p].mReverseY = true;

            tempProperties[p].mWasCalculated = false;
          }
        }

        // read the cast headers
        for (int c = 0; c < numCasts; c++) {
          // read station number
          inShort = inData.readShort();
          bytesRead += 2;
          byte bufx[] = new byte[inShort];
          inData.read(bufx, 0, inShort);
          String stnNum = new String(bufx);
          bytesRead += inShort;

          // read cast number
          int castNum = inData.readShort();
          bytesRead += 2;

          double myLat = 0.0;
          double myLon = 0.0;
          if (vers == 2) {
            // read latitude/lon
            int lat = inData.readInt();
            bytesRead += 4;

            int lon = inData.readInt();
            bytesRead += 4;

            myLat = lat * 0.001;
            myLon = lon * 0.001;
          } else if (vers > 2) {
            // read latitude/lon
            myLat = inData.readDouble();
            bytesRead += 8;

            myLon = inData.readDouble();
            bytesRead += 4;
          }

          // read number of bottles
          int numBottles = inData.readShort();
          bytesRead += 2;

          // read the date
          int year = inData.readInt();
          bytesRead += 4;
          int month = inData.readInt();
          bytesRead += 4;
          int day = inData.readInt();
          bytesRead += 4;
          int hour = inData.readInt();
          bytesRead += 4;
          double min = inData.readDouble();
          bytesRead += 8;

          // read bottom
          int bottomdbar = inData.readInt();

          // read station quality
          int stnQual = inData.readShort();
          bytesRead += 2;

          ord++;
          JOAStation sh =
              new JOAStation(
                  ord,
                  shipCode,
                  stnNum,
                  castNum,
                  myLat,
                  myLon,
                  numBottles,
                  year,
                  month,
                  day,
                  hour,
                  min,
                  bottomdbar,
                  stnQual);
          sech.mStations.addElement(sh);
          sh.setType("JOA BOTTLE");

          // make a DBase object
          Dbase db = new Dbase();

          // add the global attributes
          db.addEPSAttribute(
              "CRUISE", EPCHAR, sech.mSectionDescription.length(), sech.mSectionDescription);
          db.addEPSAttribute("CAST", EPCHAR, sh.mStnNum.length(), sh.mStnNum);
          sarray[0] = (short) sh.mBottomDepthInDBARS;
          db.addEPSAttribute("WATER_DEPTH", EPSHORT, 1, sarray);
          db.addEPSAttribute("DATA_ORIGIN", EPCHAR, sech.mShipCode.length(), sech.mShipCode);
          String dType = sh.getType();
          if (dType == null) dType = "UNKN";
          db.addEPSAttribute("DATA_TYPE", EPCHAR, dType.length(), dType);
          sarray[0] = (short) stnQual;
          db.addEPSAttribute("STN_QUALITY", EPSHORT, 1, sarray);
          db.setDataType("JOA BOTTLE");

          // add to temporary collection
          dBases.addElement(db);
        }

        int start = mTotalStns;
        int end = sech.mStations.size() + mTotalStns;
        for (int sc = start; sc < end; sc++) {
          mProgress.setPercentComplete(100.0 * ((double) bytesRead / (double) bytesInFile));

          // get a dBase
          Dbase db = (Dbase) dBases.elementAt(sc);

          // get a station
          JOAStation sh = (JOAStation) sech.mStations.elementAt(sc - start);

          // create an array of arrays to store the data
          double[][] va = new double[sech.mNumVars][sh.mNumBottles];
          int[][] qc = new int[sech.mNumVars][sh.mNumBottles];
          short[] bqc = new short[sh.mNumBottles];
          int presPos = 0;

          // read the bottles
          for (int b = 0; b < sh.mNumBottles; b++) {
            // read the bottle quality code
            bqc[b] = inData.readShort();
            bytesRead += 2;

            for (int v = 0; v < sech.mNumVars; v++) {
              // store the position of the PRES variable
              if (tempProperties[v].mVarLabel.equals("PRES")) presPos = v;

              // get the measured parameter
              double dVarVal = EPSConstants.MISSINGVALUE;
              try {
                dVarVal = inData.readDouble();
              } catch (IOException e) {
                FileImportException fiex = new FileImportException();
                String errStr =
                    "Error reading the parameter data. "
                        + "\n"
                        + "Bottle #"
                        + b
                        + " Parameter #"
                        + v;
                fiex.setErrorType(errStr);
                throw fiex;
              }
              bytesRead += 8;

              // store the value in the multidimensional array
              va[v][b] = dVarVal;

              // get the quality flag
              short flag = (short) EPSConstants.MISSINGVALUE;

              try {
                flag = inData.readShort();
              } catch (IOException e) {
                FileImportException fiex = new FileImportException();
                String errStr =
                    "Error reading the parameter quality code. "
                        + "\n"
                        + "Bottle #"
                        + b
                        + " Parameter #"
                        + v;
                fiex.setErrorType(errStr);
                throw fiex;
              }
              bytesRead += 2;
              qc[v][b] = flag;
            } // for v
          } // for b

          // add the bottle quality codes as an attribute
          db.addEPSAttribute("BOTTLE_QUALITY_CODES", EPSHORT, sh.mNumBottles, bqc);

          // create the axes time = 0, depth = 1, lat = 2, lon = 3
          Axis timeAxis = new Axis();
          Axis zAxis = new Axis();
          Axis latAxis = new Axis();
          Axis lonAxis = new Axis();

          // time axis
          timeAxis.setName("time");
          timeAxis.setTime(true);
          timeAxis.setUnlimited(false);
          timeAxis.setAxisType(EPTAXIS);
          timeAxis.setLen(1);

          int hour = 0;
          if (sh.mHour != EPSConstants.MISSINGVALUE) hour = sh.mHour;

          double mins = 0;
          if (sh.mMinute != EPSConstants.MISSINGVALUE) mins = sh.mMinute;

          // make the time axis units
          String date = "days since ";
          int min = (int) mins;
          double fmin = mins - min;
          int secs = (int) (fmin * 60.0);
          double fsec = (fmin * 60.0) - secs;
          int msec = (int) (fsec * 1000.0);
          String fs = String.valueOf(fsec);
          fs = fs.substring(fs.indexOf(".") + 1, fs.length()).trim();
          int f = 0;
          if (fs != null && fs.length() > 0) f = Integer.valueOf(fs).intValue();

          // sprintf(time_string,"%04d-%02d-%02d %02d:%02d:%02d.%03d",yr,mon,day,hr,min,sec,f);
          String frmt =
              new String(
                  "{0,number,####}-{1,number,00}-{2,number,00} {3,number,00}:{4,number,00}:{5,number,00}.{6,number,000}");
          MessageFormat msgf = new MessageFormat(frmt);

          Object[] objs = {
            new Integer(sh.mYear),
            new Integer(sh.mMonth),
            new Integer(sh.mDay),
            new Integer(hour),
            new Integer(min),
            new Integer(secs),
            new Integer(f)
          };
          StringBuffer out = new StringBuffer();
          msgf.format(objs, out, null);
          String time_string = new String(out);
          date = date + time_string;
          timeAxis.addAttribute(0, "units", EPCHAR, date.length(), date);
          timeAxis.setUnits(date);
          GeoDate gd = null;
          try {
            gd = new GeoDate(sh.mMonth, sh.mDay, sh.mYear, hour, min, secs, msec);
            GeoDate[] ta = {gd};
            MultiArray tma = new ArrayMultiArray(ta);

            timeAxis.setData(tma);
            db.setAxis(timeAxis);
          } catch (Exception ex) {
            GeoDate[] ta = {new GeoDate()};
            MultiArray tma = new ArrayMultiArray(ta);

            timeAxis.setData(tma);
            db.setAxis(timeAxis);
          }

          // add the time axes variable
          EPSVariable var = new EPSVariable();
          var.setOname("time");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "units", EPCHAR, date.length(), date);
          var.setUnits(date);
          double[] vta = {0.0};
          MultiArray vtma = new ArrayMultiArray(vta);
          try {
            var.setData(vtma);
          } catch (Exception ex) {
          }
          db.addEPSVariable(var);

          // z axis
          zAxis.setName("depth");
          zAxis.setTime(false);
          zAxis.setUnlimited(false);
          zAxis.setLen(sh.mNumBottles);
          zAxis.setAxisType(EPZAXIS);
          zAxis.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.1");
          zAxis.addAttribute(1, "units", EPCHAR, 4, "dbar");
          zAxis.setUnits("dbar");
          zAxis.setFrmt("f10.1");
          // zAxis.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 1;
          zAxis.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          double[] za = new double[sh.mNumBottles];
          for (int b = 0; b < sh.mNumBottles; b++) {
            za[b] = va[presPos][b];
          }
          MultiArray zma = new ArrayMultiArray(za);
          zAxis.setData(zma);
          db.setAxis(zAxis);

          // add the z axes variables
          var = new EPSVariable();
          var.setOname("depth");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.1");
          var.addAttribute(1, "units", EPCHAR, 4, "dbar");
          var.setUnits("dbar");
          var.setFrmt("f10.1");
          // var.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 1;
          var.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          MultiArray zvma = new ArrayMultiArray(za);
          try {
            var.setData(zvma);
          } catch (Exception ex) {
          }
          db.addEPSVariable(var);

          // lat axis
          latAxis.setName("latitude");
          latAxis.setTime(false);
          latAxis.setUnlimited(false);
          latAxis.setLen(1);
          latAxis.setAxisType(EPYAXIS);
          latAxis.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          latAxis.addAttribute(1, "units", EPCHAR, 7, "degrees");
          latAxis.setUnits("degrees");
          latAxis.setFrmt("f10.4");
          // latAxis.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 500;
          latAxis.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          double lat = sh.mLat;
          double[] la = {lat};
          MultiArray lma = new ArrayMultiArray(la);
          latAxis.setData(lma);
          db.setAxis(latAxis);

          // add the y axes variable
          var = new EPSVariable();
          var.setOname("latitude");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          var.addAttribute(1, "units", EPCHAR, 7, "degrees");
          var.setUnits("degrees");
          var.setFrmt("f10.4");
          // var.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 500;
          var.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          MultiArray yvma = new ArrayMultiArray(la);
          try {
            var.setData(yvma);
          } catch (Exception ex) {
          }
          db.addEPSVariable(var);

          // lon axis
          lonAxis.setName("longitude");
          lonAxis.setTime(false);
          lonAxis.setUnlimited(false);
          lonAxis.setLen(1);
          lonAxis.setAxisType(EPXAXIS);
          lonAxis.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          lonAxis.addAttribute(1, "units", EPCHAR, 7, "degrees");
          lonAxis.setUnits("degrees");
          lonAxis.setFrmt("f10.4");
          // lonAxis.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 502;
          lonAxis.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          double lon = sh.mLon;
          double[] lla = {lon};
          lma = new ArrayMultiArray(lla);
          lonAxis.setData(lma);
          db.setAxis(lonAxis);

          // add the x axes variable
          var = new EPSVariable();
          var.setOname("longitude");
          var.setDtype(EPDOUBLE);
          var.setVclass(Double.TYPE);
          var.addAttribute(0, "FORTRAN_format", EPCHAR, 5, "f10.4");
          var.addAttribute(1, "units", EPCHAR, 7, "degrees");
          var.setUnits("degrees");
          var.setFrmt("f10.4");
          // var.addAttribute(2, "type", EPCHAR, 0, "");
          sarray[0] = 502;
          var.addAttribute(2, "epic_code", EPSHORT, 1, sarray);
          MultiArray xvma = new ArrayMultiArray(lla);
          try {
            var.setData(xvma);
          } catch (Exception ex) {
          }

          db.addEPSVariable(var);

          // add the measured variables
          for (int v = 0; v < sech.mNumVars; v++) {
            // if (presPos == v)
            //	continue;

            // create an array of measured EPSVariables for this database
            EPSVariable epsVar = new EPSVariable();

            // initialize the new EPSVariables
            // look this variable up in JOA EPIC_Key. find matching entry in original EPIC Key
            String oname = tempProperties[v].mVarLabel;
            String sname = null;
            String lname = null;
            String gname = null;
            String units = null;
            String ffrmt = null;
            int keyID = -99;
            int type = -99;
            try {
              keyID = mEpicKeyDB.findKey(tempProperties[v].mVarLabel);
              Key key = mOrigEpicKeyDB.findKey(keyID);
              gname = key.getGname();
              sname = key.getSname();
              lname = key.getLname();
              units = key.getUnits();
              ffrmt = key.getFrmt();
              type = key.getType();
            } catch (Exception e) {
              lname = tempProperties[v].mVarLabel;
              gname = tempProperties[v].mVarLabel;
              sname = tempProperties[v].mVarLabel;
              units = tempProperties[v].mUnits;
            }

            // make a new variable
            epsVar = new EPSVariable();

            epsVar.setOname(oname);
            epsVar.setSname(sname);
            epsVar.setLname(lname);
            epsVar.setGname(gname);
            epsVar.setDtype(EPDOUBLE);
            epsVar.setVclass(Double.TYPE);
            int numAttributes = 0;
            if (ffrmt != null) {
              epsVar.addAttribute(numAttributes++, "FORTRAN_format", EPCHAR, ffrmt.length(), ffrmt);
              epsVar.setFrmt(ffrmt);
            }
            if (units != null && units.length() > 0) {
              epsVar.addAttribute(numAttributes++, "units", EPCHAR, units.length(), units);
              epsVar.setUnits(units);
            }
            if (keyID >= 0) {
              sarray[0] = (short) type;
              // epsVar.addAttribute(numAttributes++, "type", EPSHORT, 1, sarray);
            }
            if (keyID >= 0) {
              sarray[0] = (short) keyID;
              epsVar.addAttribute(numAttributes++, "epic_code", EPSHORT, 1, sarray);
            }

            // add the quality code attribute
            String qcVar = oname + "_QC";
            epsVar.addAttribute(numAttributes++, "OBS_QC_VARIABLE", EPCHAR, qcVar.length(), qcVar);

            // connect variable to axis
            epsVar.setDimorder(0, 0);
            epsVar.setDimorder(1, 1);
            epsVar.setDimorder(2, 2);
            epsVar.setDimorder(3, 3);
            epsVar.setT(timeAxis);
            epsVar.setZ(zAxis);
            epsVar.setY(latAxis);
            epsVar.setX(lonAxis);

            // set the data
            // create storage for the measured variables
            double[][][][] vaa = new double[1][sh.mNumBottles][1][1];
            for (int b = 0; b < sh.mNumBottles; b++) {
              vaa[0][b][0][0] = va[v][b];
            }
            MultiArray mdma = new ArrayMultiArray(vaa);
            try {
              epsVar.setData(mdma);
            } catch (Exception ex) {
              System.out.println("throwing");
            }

            // add the variable to the database
            db.addEPSVariable(epsVar);

            // create the quality code variable
            epsVar = new EPSVariable();
            epsVar.setOname(oname + "_QC");
            epsVar.setSname(sname + "_QC");
            epsVar.setLname(sname + "_QC");
            epsVar.setGname(sname + "_QC");
            epsVar.setDtype(EPSHORT);
            epsVar.setVclass(Short.TYPE);

            // connect variable to axis
            epsVar.setDimorder(0, 0);
            epsVar.setDimorder(1, 1);
            epsVar.setDimorder(2, 2);
            epsVar.setDimorder(3, 3);
            epsVar.setT(timeAxis);
            epsVar.setZ(zAxis);
            epsVar.setY(latAxis);
            epsVar.setX(lonAxis);

            // set the data
            // create storage for the qc variables
            short[][][][] qcaa = new short[1][sh.mNumBottles][1][1];
            for (int b = 0; b < sh.mNumBottles; b++) {
              qcaa[0][b][0][0] = (short) qc[v][b];
            }
            MultiArray qcma = new ArrayMultiArray(qcaa);
            try {
              epsVar.setData(qcma);
            } catch (Exception ex) {
              System.out.println("throwing");
            }

            // add the qc variable to the database
            db.addEPSVariable(epsVar);
          } // for v
        }
        mTotalStns += numCasts;
      } // for sc

      // read the file comments
      StringBuffer sb = null;
      while (true) {
        try {
          // read continuation line
          inShort = inData.readShort();
          bytesRead += 2;

          if (inShort == 1) {
            // read number of bytes in file description string
            inShort = inData.readShort();
            bytesRead += 2;

            // read the file description String
            byte buf2[] = new byte[inShort];
            inData.read(buf2, 0, inShort);
            String commentLine = new String(buf2);
            bytesRead += inShort;

            if (sb == null) sb = new StringBuffer(commentLine);
            else sb.append(commentLine);
          }
        } catch (IOException e) {
          break;
        }
      } // while true

      if (sb != null) {
        // make attributes for the comments
        mOwnerDBase.setDataComment(new String(sb));
      }

      // make a sub database in the dbase
      mOwnerDBase.createSubEntries(mTotalStns, mFile.getName());
      for (int d = 0; d < mTotalStns; d++) {
        Dbase db = (Dbase) dBases.elementAt(d);
        mOwnerDBase.addSubEntry(db);
      }
      mProgress.setPercentComplete(100.0);
      mProgress.setVisible(false);
      mProgress.dispose();
      in.close();
    } catch (IOException e) {
      mProgress.setVisible(false);
      mProgress.dispose();
      throw e;
    }
  }
Пример #11
0
  /** used by preParse */
  private static String preParseOnce(String s, FormulaManager fm) {
    // convert to lower case
    String l = s.toLowerCase();

    // scan entire string
    int len = l.length();
    boolean letter = false;
    String ns = "";
    for (int i = 0; i < len; i++) {
      if (!letter && i < len - 1 && l.substring(i, i + 2).equals("d(")) {
        // convert d(x)/d(y) notation to standard derive(x, y) notation
        i += 2;
        int s1 = i;
        for (int paren = 1; paren > 0; i++) {
          // check for correct syntax
          if (i >= len) return s;
          char c = l.charAt(i);
          if (c == '(') paren++;
          if (c == ')') paren--;
        }
        int e1 = i - 1;
        // check for correct syntax
        if (i > len - 3 || !l.substring(i, i + 3).equals("/d(")) return s;
        i += 3;
        int s2 = i;
        for (int paren = 1; paren > 0; i++) {
          // check for correct syntax
          if (i >= len) return s;
          char c = l.charAt(i);
          if (c == '(') paren++;
          if (c == ')') paren--;
        }
        int e2 = i - 1;
        ns = ns + "derive(" + s.substring(s1, e1) + "," + s.substring(s2, e2) + ")";
        i--;
      } else if (!letter && i < len - 4 && l.substring(i, i + 5).equals("link(")) {
        // evaluate link(code) notation and replace with link variable
        i += 5;
        int s1 = i;
        try {
          while (l.charAt(i) != '(') i++;
        } catch (ArrayIndexOutOfBoundsException exc) {
          // incorrect syntax
          return s;
        }
        i++;
        int e1 = i - 1;
        int s2 = i;
        for (int paren = 2; paren > 1; i++) {
          // check for correct syntax
          if (i >= len) return s;
          char c = l.charAt(i);
          if (c == '(') paren++;
          if (c == ')') paren--;
        }
        int e2 = i - 1;
        // check for correct syntax
        if (i >= len || l.charAt(i) != ')') return s;
        String prestr = s.substring(s1, e1) + "(";
        String str = prestr;

        // parse method's arguments; determine if they are Data or RealType
        String sub = s.substring(s2, e2);
        StringTokenizer st = new StringTokenizer(sub, ",", false);
        boolean first = true;
        Vector v = new Vector();
        while (st.hasMoreTokens()) {
          String token = st.nextToken();
          if (first) first = false;
          else str = str + ",";
          RealType rt = RealType.getRealTypeByName(token);
          String sv = (rt == null ? "visad.Data" : "visad.RealType");
          v.add(sv);
          str = str + sv;
        }
        str = str + ")";

        // obtain Method object
        Method[] meths = FormulaUtil.stringsToMethods(new String[] {str});

        if (meths[0] == null) {
          // attempt to identify any matching methods by compressing
          // some or all of the arguments into array form
          int vlen = v.size();
          Vector vstrs = new Vector();
          for (int iv = 0; iv < vlen; iv++) {
            String si = (String) v.elementAt(iv);
            int lv = iv;
            String sl;
            while (lv < vlen) {
              sl = (String) v.elementAt(lv++);
              if (!sl.equals(si)) {
                break;
              }
              str = prestr;
              first = true;
              for (int j = 0; j < vlen; j++) {
                if (first) first = false;
                else str = str + ",";
                String sj = (String) v.elementAt(j);
                str = str + sj;
                if (iv == j) {
                  str = str + "[]";
                  j = lv - 1;
                }
              }
              str = str + ")";
              vstrs.add(str);
            }
          }
          String[] strlist = new String[vstrs.size()];
          vstrs.toArray(strlist);
          meths = FormulaUtil.stringsToMethods(strlist);
          int found = -1;
          for (int j = 0; j < meths.length && found < 0; j++) {
            if (meths[j] != null) found = j;
          }
          if (found >= 0) meths[0] = meths[found];
          else {
            // could not find a matching method
            return s;
          }
        }

        // store method object in a link variable
        String link = "link" + (++linkNum);
        try {
          fm.setThing(link, new VMethod(meths[0]));
        }
        // catch any errors setting the link variable
        catch (FormulaException exc) {
          return s;
        } catch (VisADException exc) {
          return s;
        } catch (RemoteException exc) {
          return s;
        }
        ns = ns + "linkx(" + link + "," + s.substring(s2, e2) + ")";
      } else if (!letter) {
        int j = i;
        char c = l.charAt(j++);
        while (j < len && ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))) {
          c = l.charAt(j++);
        }
        // check for end-of-string
        if (j == len) return ns + s.substring(i, len);
        if (c == '[') {
          // convert x[y] notation to standard getSample(x, y) notation
          int k = j;
          for (int paren = 1; paren > 0; k++) {
            // check for correct syntax
            if (k >= len) return s;
            c = l.charAt(k);
            if (c == '[') paren++;
            if (c == ']') paren--;
          }
          ns = ns + "getSample(" + s.substring(i, j - 1) + "," + s.substring(j, k - 1) + ")";
          i = k - 1;
        } else ns = ns + s.charAt(i);
      } else {
        // append character to new string
        ns = ns + s.charAt(i);
      }
      char c = (i < len) ? l.charAt(i) : '\0';
      letter = (c >= 'a' && c <= 'z');
    }
    return ns;
  }
Пример #12
0
  /**
   * This method returns a <tt>Class</tt> for a helper which can handle the list of distributions
   * specified by <tt>seq1</tt>. We maintain a cache of recently-loaded helpers, so check the cache
   * before going to the trouble of searching for a helper. The cache is blown away every
   * <tt>HELPER_CACHE_REFRESH</tt> seconds.
   *
   * <p>If we can't find a helper in the cache, we must search through the list of available helpers
   * to find an appropriate one. First try to find helper using class sequence as specified by
   * <tt>seq</tt>. Whether or not that succeeds, promote any <tt>Gaussian</tt> in the sequence to
   * <tt>MixGaussians</tt>, and try again. If we get a better match on the second try, return the
   * helper thus found.
   */
  public static Class find_helper_class(Vector seq1, String helper_type)
      throws ClassNotFoundException {
    // Let's see if an appropriate helper is in the cache.
    // If the cache is too old, empty it and search for the helper anew.

    if (System.currentTimeMillis() - cache_timestamp > HELPER_CACHE_REFRESH) {
      helper_cache = new Hashtable();
      cache_timestamp = System.currentTimeMillis();
      // Go on and search for appropriate helper.
    } else {
      HelperCacheKey key = new HelperCacheKey(helper_type, seq1);
      Class helper_class = (Class) helper_cache.get(key);
      if (helper_class != null) {
        if (Global.debug > -1)
          System.err.println(
              "PiHelperLoader.find_helper_class: found helper class: "
                  + helper_class
                  + "; no need to search.");
        return helper_class;
      }
      // else no luck; we have to search for helper.
    }

    // Well, we didn't find a helper in the cache, so let's go to work.
    if (Global.debug > -1)
      System.err.println(
          "PiHelperLoader.find_helper_class: DID NOT FIND HELPER CLASS; NOW SEARCH.");

    Class c1 = null, c2 = null;
    ClassNotFoundException cnfe1 = null, cnfe2 = null;
    int[] class_score1 = new int[1], count_score1 = new int[1];
    int[] class_score2 = new int[1], count_score2 = new int[1];

    try {
      c1 = find_helper_class1(seq1, helper_type, class_score1, count_score1);
    } catch (ClassNotFoundException e) {
      cnfe1 = e;
    } // hang on, we may need to re-throw later.

    Class gaussian_class = Class.forName("riso.distributions.Gaussian");
    MixGaussians mog = new MixGaussians(1, 1);

    Vector seq2 = new Vector(seq1.size());
    for (int i = 0; i < seq1.size(); i++)
      if (gaussian_class.isAssignableFrom((Class) seq1.elementAt(i)))
        seq2.addElement(mog.getClass());
      else seq2.addElement(seq1.elementAt(i));

    try {
      c2 = find_helper_class1(seq2, helper_type, class_score2, count_score2);
    } catch (ClassNotFoundException e) {
      cnfe2 = e;
    }

    if (cnfe1 == null && cnfe2 == null) {
      // Both matched; see which one fits better.
      // Break ties in favor of the helper for non-promoted messages.

      if (class_score1[0] >= class_score2[0]
          || (class_score1[0] == class_score2[0] && count_score1[0] >= count_score2[0])) {
        if (Global.debug > 1)
          System.err.println(
              "\taccept helper " + c1 + " for non-promoted classes instead of " + c2);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
        return c1;
      } else {
        if (Global.debug > 1)
          System.err.println("\taccept helper " + c2 + " for promoted classes instead of " + c1);
        if (Global.debug > 1)
          System.err.println(
              "\t\t"
                  + class_score1[0]
                  + ", "
                  + class_score2[0]
                  + "; "
                  + count_score1[0]
                  + ", "
                  + count_score2[0]);
        helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
        return c2;
      }
    } else if (cnfe1 == null && cnfe2 != null) {
      // Only the first try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c1);
      return c1;
    } else if (cnfe1 != null && cnfe2 == null) {
      // Only the second try matched, return it.
      helper_cache.put(new HelperCacheKey(helper_type, seq1), c2);
      return c2;
    } else {
      // Neither try matched. Re-throw the exception generated by the first try.
      throw cnfe1;
    }
  }