Пример #1
0
  /**
   * using the time from the adapter to reset the time list
   *
   * @param realDateTimes _more_
   * @param times _more_
   * @return _more_
   */
  private List resetTimesList(DateTime[] realDateTimes, List<DateTime> times) {
    List results = new ArrayList();
    int len = realDateTimes.length;

    HashSet seenTimes = new HashSet();

    try {
      for (DateTime dateTime : times) {
        Date dttm = ucar.visad.Util.makeDate(dateTime);
        long minTimeDiff = -1;
        Date minDate = null;
        for (int i = 0; i < len; i++) {
          Date sourceDate = ucar.visad.Util.makeDate(realDateTimes[i]);
          long timeDiff = Math.abs(sourceDate.getTime() - dttm.getTime());
          if ((minTimeDiff < 0) || (timeDiff < minTimeDiff)) {
            minTimeDiff = timeDiff;
            minDate = sourceDate;
          }
        }
        if ((minDate != null) && !seenTimes.contains(minDate)) {
          results.add(new DateTime(minDate));
          seenTimes.add(minDate);
        }
      }
    } catch (Exception e) {
    }

    return results;
  }
Пример #2
0
  public Set subSetProfilesTimeSet(Set tset) throws Exception {

    List<DateTime> timeList = (List<DateTime>) Util.toList(tset);
    int size = timeList.size();
    List<DateTime> subList = new ArrayList<DateTime>();

    for (int i = 0; i < size - 1; i++) {
      Real r = timeList.get(i);
      DateTime dt = new DateTime(r);
      subList.add(dt);
    }

    return Util.makeTimeSet(subList);
  }
Пример #3
0
 /**
  * tokenize the pattern string as a numeric range
  *
  * @return min max range values
  * @throws Exception On badness
  */
 public Real[] getNumericRange() throws Exception {
   if (range == null) {
     range = new Real[] {null, null};
     List toks = StringUtil.split(pattern, ",");
     if (toks.size() == 0) {
       throw new IllegalStateException("Bad format for numeric range:" + pattern);
     }
     String tok1 = toks.get(0).toString();
     String tok2 = ((toks.size() == 1) ? tok1 : toks.get(1).toString());
     range[0] = ucar.visad.Util.toReal(tok1);
     range[1] = ucar.visad.Util.toReal(tok2);
   }
   return range;
 }
Пример #4
0
 /**
  * Set the curve
  *
  * @param curve the curve coordinates
  * @param curveTimes the curve times
  * @throws RemoteException On badness
  * @throws VisADException On badness
  */
 public void setCurve(float[][] curve, List curveTimes) throws VisADException, RemoteException {
   this.curve = curve;
   this.curveTimes = curveTimes;
   FieldImpl front = makeFront(curve);
   if (front != null) {
     setData(Util.makeTimeRangeField(front, curveTimes));
   }
 }
Пример #5
0
  /**
   * Sets the input dew-point. The data is not copied.
   *
   * @param dewPoint The input dew-point.
   * @throws NullPointerException if the argument is <code>null</code>.
   * @throws TypeException if the profile has the wrong type.
   * @throws VisADException if a VisAD failure occurs.
   * @throws RemoteException if a Java RMI failure occurs.
   */
  public synchronized void setDewPoint(Real dewPoint)
      throws TypeException, VisADException, RemoteException {

    Util.vetType(ucar.visad.quantities.DewPoint.getRealType(), dewPoint);

    this.dewPoint = dewPoint;
    dirty = true;
  }
Пример #6
0
  /**
   * Sets the input pressure. The data is not copied.
   *
   * @param pressure The input pressure.
   * @throws NullPointerException if the argument is <code>null</code>.
   * @throws TypeException if the pressure has the wrong type.
   * @throws VisADException if a VisAD failure occurs.
   * @throws RemoteException if a Java RMI failure occurs.
   */
  public synchronized void setPressure(Real pressure)
      throws TypeException, VisADException, RemoteException {

    Util.vetType(ucar.visad.quantities.AirPressure.getRealType(), pressure);

    this.pressure = pressure;
    dirty = true;
  }
Пример #7
0
 /**
  * Get the the display unit.
  *
  * @return Unit used for displaying values. May be <code>null</code>.
  */
 public Unit getDisplayUnit() {
   if ((displayUnit == null) && (displayUnitName != null)) {
     try {
       displayUnit = ucar.visad.Util.parseUnit(displayUnitName);
     } catch (Exception exc) {
     }
   }
   return displayUnit;
 }
Пример #8
0
 /**
  * Get the the colorTable unit.
  *
  * @return Unit used for colorTableing values. May be <code>null</code>.
  */
 public Unit getColorTableUnit() {
   if ((colorTableUnit == null) && (colorTableUnitName != null)) {
     try {
       colorTableUnit = ucar.visad.Util.parseUnit(colorTableUnitName);
     } catch (Exception exc) {
     }
   }
   return colorTableUnit;
 }
Пример #9
0
 /**
  * Get the the scale unit.
  *
  * @return Unit used for scaleing values. May be <code>null</code>.
  */
 public Unit getScaleUnit() {
   if ((scaleUnit == null) && (scaleUnitName != null)) {
     try {
       scaleUnit = ucar.visad.Util.parseUnit(scaleUnitName);
     } catch (Exception exc) {
     }
   }
   return scaleUnit;
 }
Пример #10
0
  /**
   * Create the charts
   *
   * @throws RemoteException On badness
   * @throws VisADException On badness
   */
  public void loadData() throws VisADException, RemoteException {
    createChart();
    List dataChoiceWrappers = getDataChoiceWrappers();
    try {
      for (int dataSetIdx = 0; dataSetIdx < plot.getDatasetCount(); dataSetIdx++) {
        MyHistogramDataset dataset = (MyHistogramDataset) plot.getDataset(dataSetIdx);
        dataset.removeAllSeries();
      }

      //            dataset.removeAllSeries();
      Hashtable props = new Hashtable();
      props.put(TrackDataSource.PROP_TRACKTYPE, TrackDataSource.ID_TIMETRACE);

      for (int paramIdx = 0; paramIdx < dataChoiceWrappers.size(); paramIdx++) {
        DataChoiceWrapper wrapper = (DataChoiceWrapper) dataChoiceWrappers.get(paramIdx);

        DataChoice dataChoice = wrapper.getDataChoice();
        FlatField data = getFlatField((FieldImpl) dataChoice.getData(null, props));
        Unit unit = ucar.visad.Util.getDefaultRangeUnits((FlatField) data)[0];
        double[][] samples = data.getValues(false);
        double[] actualValues = filterData(samples[0], getTimeValues(samples, data))[0];
        NumberAxis domainAxis = new NumberAxis(wrapper.getLabel(unit));

        XYItemRenderer renderer;
        if (stacked) {
          renderer = new StackedXYBarRenderer();
        } else {
          renderer = new XYBarRenderer();
        }
        plot.setRenderer(paramIdx, renderer);
        Color c = wrapper.getColor(paramIdx);
        domainAxis.setLabelPaint(c);
        renderer.setSeriesPaint(0, c);

        MyHistogramDataset dataset = new MyHistogramDataset();
        dataset.setType(HistogramType.FREQUENCY);
        dataset.addSeries(dataChoice.getName() + " [" + unit + "]", actualValues, bins);
        plot.setDomainAxis(paramIdx, domainAxis, false);
        plot.mapDatasetToDomainAxis(paramIdx, paramIdx);
        plot.setDataset(paramIdx, dataset);
      }

    } catch (Exception exc) {
      LogUtil.logException("Error creating data set", exc);
      return;
    }
  }
Пример #11
0
  /**
   * Create e field description from the field
   *
   * @param fi field to use
   */
  protected void makeFieldDescription(FieldImpl fi) {
    if (fi == null) {
      fieldsDescription = "Bad data: null";
      return;
    }
    try {
      if (ucar.unidata.data.grid.GridUtil.isTimeSequence(fi)) {
        fi = (FieldImpl) fi.getSample(0);
      }
      PointOb ob = (PointOb) fi.getSample(0);
      Tuple tuple = (Tuple) ob.getData();
      MathType[] comps = ((TupleType) tuple.getType()).getComponents();
      Trace.msg("PointDataSource #vars=" + comps.length);
      StringBuffer params = new StringBuffer(comps.length + " Fields:<ul>");
      String dataSourceName = getName();
      DataChoice.addCurrentName(new TwoFacedObject("Point Data>Time", "Time"));
      DataChoice.addCurrentName(new TwoFacedObject("Point Data>Latitude", "Latitude"));
      DataChoice.addCurrentName(new TwoFacedObject("Point Data>Altitude", "Altitude"));

      for (int i = 0; i < comps.length; i++) {
        params.append("<li>");
        String paramName = ucar.visad.Util.cleanTypeName(comps[i].toString());
        DataAlias alias = DataAlias.findAlias(paramName);
        params.append(paramName);
        if (alias != null) {
          params.append(" --  " + alias.getLabel());
          DataChoice.addCurrentName(
              new TwoFacedObject(
                  dataSourceName + ">" + alias.getLabel() + " -- " + paramName, paramName));
        } else {
          DataChoice.addCurrentName(
              new TwoFacedObject(dataSourceName + ">" + paramName, paramName));
        }
        Data data = tuple.getComponent(i);
        if (data instanceof Real) {
          Unit unit = ((Real) data).getUnit();
          if (unit != null) {
            params.append("  [" + unit.toString() + "]");
          }
        }
      }
      fieldsDescription = params.toString();
    } catch (Exception exc) {
      logException("getting description", exc);
    }
  }
Пример #12
0
  /**
   * Apply the properties
   *
   * @param compMap Optional map that holds components
   * @return Success
   * @throws RemoteException On badness
   * @throws VisADException On badness
   */
  protected boolean applyProperties(Hashtable compMap) throws VisADException, RemoteException {
    if (!super.applyProperties(compMap)) {
      return false;
    }
    setStartText(startTextFld.getText().trim());
    setEndText(endTextFld.getText().trim());
    try {
      if (maxDistanceFld != null) {
        Real oldMaxDataDistance = maxDataDistance;
        maxDataDistance = ucar.visad.Util.toReal(maxDistanceFld.getText().trim());
        tvm.setMaxDataDistance(maxDataDistance);
        updateLocation();
      }
    } catch (Exception exc) {
      LogUtil.userErrorMessage("Bad value:" + maxDistanceFld.getText().trim());
      return false;
    }

    return true;
  }
Пример #13
0
  /**
   * Set the vertical range unit from the preference
   *
   * @param nd navigated display to set the unit on
   * @throws RemoteException problem with remote display
   * @throws VisADException problem with local display
   */
  protected void setVerticalRangeUnitPreference(NavigatedDisplay nd)
      throws VisADException, RemoteException {
    Unit u = null;

    try {
      u =
          ucar.visad.Util.parseUnit(
              getIdv().getObjectStore().get(IdvConstants.PREF_VERTICALUNIT, "m"));
    } catch (Exception exc) {
      u = null;
    }

    if (u != null) {
      double[] range = nd.getVerticalRange();
      Unit defaultUnit = nd.getVerticalRangeUnit();

      if (!u.equals(defaultUnit) && Unit.canConvert(u, defaultUnit)) {
        range = u.toThis(range, defaultUnit);
        nd.setVerticalRangeUnit(u);
        nd.setVerticalRange(range[0], range[1]);
      }
    }
  }
Пример #14
0
 /**
  * Popup a unit selection gui. This will also save off persistently any new unit names typed in.
  *
  * @param unit The current unit
  * @param defaultUnit The default unit to return if the user chooses "Default"
  * @return The new unit or null on a cancel or an error
  */
 public Unit selectUnit(Unit unit, Unit defaultUnit) {
   JComboBox ufld = makeUnitBox(unit, defaultUnit);
   Component panel = GuiUtils.label(" New unit:  ", ufld);
   if (!GuiUtils.showOkCancelDialog(
       null, "Change unit", GuiUtils.inset(panel, 5), null, Misc.newList(ufld))) {
     return null;
   }
   Object selected = ufld.getSelectedItem();
   String unitName = TwoFacedObject.getIdString(selected);
   if (unitName == null) {
     return defaultUnit;
   }
   try {
     Unit newUnit = Util.parseUnit(unitName);
     if (!(selected instanceof TwoFacedObject)) {
       selected = new TwoFacedObject(selected.toString(), newUnit);
     }
     addToUnitList(selected);
     return newUnit;
   } catch (Exception exc) {
     LogUtil.userMessage("Error parsing unit:" + unitName + "\n" + exc);
   }
   return null;
 }
Пример #15
0
  /** Initialize the default vertical range */
  private void initVerticalRange() {
    String typeName = getTypeName().toLowerCase();
    String verticalRangeStr =
        getIdv().getProperty("idv.viewmanager." + typeName + ".verticalrange", (String) null);

    if (verticalRangeStr != null) {
      List toks = StringUtil.split(verticalRangeStr, ",", true, true);

      if (toks.size() >= 2) {
        tmpVerticalRange =
            new double[] {
              new Double(toks.get(0).toString()).doubleValue(),
              new Double(toks.get(1).toString()).doubleValue()
            };

        if (toks.size() == 3) {
          try {
            tmpVertRangeUnit = ucar.visad.Util.parseUnit(toks.get(2).toString());
          } catch (Exception exc) {
          }
        }
      }
    }
  }
Пример #16
0
  /**
   * Make a grid with a Linear3DSet for the volume rendering
   *
   * @param grid grid to transform
   * @param cs coordinate system to transform to XYZ
   * @return transformed grid
   * @throws RemoteException Java RMI Exception
   * @throws VisADException problem creating grid
   */
  private FieldImpl makeLinearGrid(FieldImpl grid, CoordinateSystem cs)
      throws VisADException, RemoteException {

    Trace.call1("VRC.makeLinearGrid");
    GriddedSet domainSet = (GriddedSet) GridUtil.getSpatialDomain(grid);
    SampledSet ss = null;
    boolean latLonOrder = GridUtil.isLatLonOrder(domainSet);
    // System.out.println("grid is latLonOrder " + latLonOrder);
    Trace.call1("VRC.convertDomain");
    if (latLonOrder) {
      ss = Util.convertDomain(domainSet, RealTupleType.LatitudeLongitudeAltitude, null);
    } else {
      ss = Util.convertDomain(domainSet, RealTupleType.SpatialEarth3DTuple, null);
    }
    Trace.call2("VRC.convertDomain");
    float[][] refVals = ss.getSamples(true);
    MapProjectionDisplay mpd = (MapProjectionDisplay) getNavigatedDisplay();
    MapProjection mp = mpd.getMapProjection();
    boolean mapLatLonOrder = mp.isLatLonOrder();
    // System.out.println("map is latLonOrder " + mapLatLonOrder);
    float[][] newVals =
        (latLonOrder) ? refVals : new float[][] {refVals[1], refVals[0], refVals[2]};
    Trace.call1("VRC.toRef");
    newVals = cs.toReference(newVals);
    Trace.call2("VRC.toRef");
    Trace.call1("VRC.scaleVerticalValues");
    newVals[2] = mpd.scaleVerticalValues(newVals[2]);
    Trace.call2("VRC.scaleVerticalValues");
    int[] lengths = domainSet.getLengths();
    // Misc.printArray("lengths",lengths);
    GriddedSet xyzSet =
        GriddedSet.create(
            RealTupleType.SpatialCartesian3DTuple,
            newVals,
            domainSet.getLengths(),
            (CoordinateSystem) null,
            (Unit[]) null,
            (ErrorEstimate[]) null,
            false,
            true);
    Trace.call1("VRC.setSpatialDomain");
    FieldImpl newGrid = GridUtil.setSpatialDomain(grid, xyzSet); // , true);
    Trace.call2("VRC.setSpatialDomain");
    float[] lows = xyzSet.getLow();
    float[] highs = xyzSet.getHi();
    // Misc.printArray("lows",lows);
    // Misc.printArray("highs",highs);
    Linear3DSet volumeXYZ =
        new Linear3DSet(
            RealTupleType.SpatialCartesian3DTuple,
            lows[0],
            highs[0],
            lengths[0],
            lows[1],
            highs[1],
            lengths[1],
            lows[2],
            highs[2],
            lengths[2]);
    // System.out.println(volumeXYZ);
    Trace.call1("VRC.resampleGrid");
    newGrid = GridUtil.resampleGrid(newGrid, volumeXYZ);
    Trace.call2("VRC.resampleGrid");
    Trace.call2("VRC.makeLinearGrid");
    return newGrid;
  }
Пример #17
0
  /**
   * Computes the output Level of Free Convection (LFC) from an (AirPressure -> MassicVolume)
   * buoyancy profile.
   *
   * @param datums The input data in the same order as during construction: <code>datums[0]
   *                                  </code> is the input buoyancy profile.
   * @return The pressure at the LFC of the buoyancy profile.
   * @throws ClassCastException if an input data reference has the wrong type of data object.
   * @throws TypeException if a VisAD data object has the wrong type.
   * @throws VisADException if a VisAD failure occurs.
   * @throws RemoteException if a Java RMI failure occurs.
   * @throws IllegalArgumentException if the profile is not ascending.
   */
  protected Data compute(Data[] datums) throws TypeException, VisADException, RemoteException {

    Field buoyProfile = (Field) datums[0];
    Real lfc = noData; // default return value

    if (buoyProfile != null) {
      FunctionType funcType = (FunctionType) buoyProfile.getType();
      RealTupleType domainType = funcType.getDomain();

      if (!Pressure.getRealType().equalsExceptNameButUnits(domainType)) {
        throw new TypeException(domainType.toString());
      }

      MathType rangeType = funcType.getRange();

      Util.vetType(MassicVolume.getRealType(), buoyProfile);

      Set domainSet = buoyProfile.getDomainSet();
      double[] pressures = domainSet.getDoubles()[0];
      float[] buoys = buoyProfile.getFloats()[0];

      if (pressures.length > 1) {
        int lastI = pressures.length - 1;
        boolean ascending = pressures[0] >= pressures[lastI];

        Unit presUnit = domainSet.getSetUnits()[0];
        int i;

        if (ascending) {
          /*
           * For a level of free convection to exist, the lower
           * buoyancy must be negative.
           */
          for (i = 0; (i < buoys.length) && (buoys[i] >= 0); i++) ;

          /*
           * To find the level of free convection, ascend to
           * positive buoyancy.
           */
          while ((++i < buoys.length) && (buoys[i] <= 0)) ;

          if (i < buoys.length) {
            lfc = interpolatePres(pressures[i], buoys[i], pressures[i - 1], buoys[i - 1], presUnit);
          }
        } else {
          /*
           * For a level of free convection to exist, the lower
           * buoyancy must be negative.
           */
          for (i = lastI; (i >= 0) && (buoys[i] >= 0); i--) ;

          /*
           * To find the level of free convection, ascend to
           * positive buoyancy.
           */
          while ((--i >= 0) && (buoys[i] <= 0)) ;

          if (i >= 0) {
            lfc = interpolatePres(pressures[i], buoys[i], pressures[i + 1], buoys[i + 1], presUnit);
          }
        }
      }
    }

    return lfc;
  }
Пример #18
0
  /**
   * Actually get the data identified by the given DataChoce. The default is to call the
   * getDataInner that does not take the requestProperties. This allows other, non unidata.data
   * DataSource-s (that follow the old API) to work.
   *
   * @param dataChoice The data choice that identifies the requested data.
   * @param category The data category of the request.
   * @param dataSelection Identifies any subsetting of the data.
   * @param requestProperties Hashtable that holds any detailed request properties.
   * @return The visad.Data object
   * @throws RemoteException Java RMI problem
   * @throws VisADException VisAD problem
   */
  protected Data getDataInner(
      DataChoice dataChoice,
      DataCategory category,
      DataSelection dataSelection,
      Hashtable requestProperties)
      throws VisADException, RemoteException {

    loadId = JobManager.getManager().stopAndRestart(loadId, "WMSControl");
    Object myLoadId = loadId;

    if (requestProperties == null) {
      requestProperties = new Hashtable();
    }
    WmsSelection wmsInfo = (WmsSelection) dataChoice.getId();

    // Look if there was a layer that overrides the one in the data choice
    Object tfoLayer = requestProperties.get(PROP_LAYER);
    if ((tfoLayer != null) && (tfoLayer instanceof TwoFacedObject)) {
      String layer = ((TwoFacedObject) tfoLayer).getId().toString();
      for (int i = 0; i < wmsSelections.size(); i++) {
        WmsSelection tmpSelection = (WmsSelection) wmsSelections.get(i);
        if (Misc.equals(tmpSelection.getLayer(), layer)) {
          wmsInfo = tmpSelection;
          break;
        }
      }
    }

    GeoLocationInfo boundsToUse = (GeoLocationInfo) requestProperties.get(PROP_BOUNDS);

    Image image = null;
    FieldImpl xyData = null;
    byte[] imageContent = null;

    //        System.err.println(wmsInfo.getImageFile());
    if (wmsInfo.getImageFile() != null) {
      try {
        boundsToUse = new GeoLocationInfo(90, -180, -90, 180);
        InputStream is = IOUtil.getInputStream(wmsInfo.getImageFile());
        imageContent = IOUtil.readBytes(is, myLoadId);
        image = Toolkit.getDefaultToolkit().createImage(imageContent);
        //                javax.swing.JLabel l = new javax.swing.JLabel(new
        // javax.swing.ImageIcon(image));
        //                l.setBackground(Color.red);
        //                ucar.unidata.util.GuiUtils.showOkCancelDialog(null,null, l,null);
        xyData = ucar.visad.Util.makeField(image, 0, false, true);
      } catch (Exception iexc) {
        logException("There was an error accessing the image:\n" + wmsInfo.getImageFile(), iexc);
        return null;
      }
    } else {
      String writeFile = (String) requestProperties.get(PROP_WRITEFILE);

      int imageWidth = Misc.getProperty(requestProperties, PROP_IMAGEWIDTH, 800);
      int imageHeight = Misc.getProperty(requestProperties, PROP_IMAGEHEIGHT, -1);
      double resolution = Misc.getProperty(requestProperties, PROP_RESOLUTION, (float) 1.0);

      if (wmsInfo.getLegendIcon() != null) {
        requestProperties.put(PROP_ICONPATH, wmsInfo.getLegendIcon());
      }
      if (!wmsInfo.getAllowSubsets() || (boundsToUse == null)) {
        boundsToUse = wmsInfo.getBounds();
      } else {
        boundsToUse.rectify(wmsInfo.getBounds(), 0.0);
        boundsToUse.snapToGrid();
        boundsToUse.rectify(wmsInfo.getBounds(), 0.0);
      }

      double widthDegrees = boundsToUse.getMaxLon() - boundsToUse.getMinLon();
      double heightDegrees = boundsToUse.getMaxLat() - boundsToUse.getMinLat();

      if ((widthDegrees == 0) || (heightDegrees == 0)) {
        return null;
      }

      if (wmsInfo.getFixedWidth() > -1) {
        imageWidth = wmsInfo.getFixedWidth();
      }
      if (wmsInfo.getFixedHeight() > -1) {
        imageHeight = wmsInfo.getFixedHeight();
      } else {
        if (imageHeight < 0) {
          imageHeight =
              Math.abs((int) (imageWidth * boundsToUse.getDegreesY() / boundsToUse.getDegreesX()));
        }
      }
      imageWidth = Math.min(Math.max(imageWidth, 50), 2056);
      imageHeight = Math.min(Math.max(imageHeight, 50), 2056);

      if (maintainRatio) {
        imageHeight = (int) (imageWidth * (heightDegrees / widthDegrees));
      }

      double diff = Math.abs(boundsToUse.getMinLon() - boundsToUse.getMaxLon());
      String url =
          wmsInfo.assembleRequest(
              boundsToUse, (int) (imageWidth / resolution), (int) (imageHeight / resolution));

      String cacheGroup = "WMS";
      synchronized (cachedUrls) {
        if (writeFile == null) {
          for (int i = 0; i < cachedUrls.size(); i++) {
            if (url.equals(cachedUrls.get(i))) {
              image = (Image) cachedData.get(i);
              break;
            }
          }
        }
      }

      try {
        if (image == null) {
          if (Misc.equals(url, lastUrl) && (lastImageContent != null)) {
            imageContent = lastImageContent;
          } else {
          }

          if (imageContent == null) {
            long t1 = System.currentTimeMillis();
            //                    System.err.println("getting image:" + url);
            LogUtil.message("Reading WMS image: " + wmsInfo);
            // System.err.println ("url:" + url);

            InputStream is = IOUtil.getInputStream(url);
            long t2 = System.currentTimeMillis();
            imageContent = IOUtil.readBytes(is, myLoadId);
            long t3 = System.currentTimeMillis();
            LogUtil.message("");
            //                    System.err.println("Done");
          }
          // If it is null then there is another thread that is doing
          // a subsequent read
          lastImageContent = null;
          if (imageContent == null) {
            return null;
          }
          Trace.call2("Getting image");
          Trace.call1("Making image");
          image = Toolkit.getDefaultToolkit().createImage(imageContent);
          // Wait on the image
          image = ucar.unidata.ui.ImageUtils.waitOnImage(image);
          if (image == null) {
            throw new IllegalStateException();
          }

          Trace.call2("Making image");
          lastImageContent = imageContent;
          lastUrl = url;
          updateDetailsText();
          if (!JobManager.getManager().canContinue(myLoadId)) {
            Trace.call2("WMSControl.loadImage");
            return null;
          }
          synchronized (cachedUrls) {
            if (cachedUrls.size() > 5) {
              cachedUrls.remove(cachedUrls.size() - 1);
              cachedData.remove(cachedData.size() - 1);
            }
            // For now don't cache
            //      cachedUrls.add(0, url);
            //                    cachedData.add(0, image);
          }
        }
        ImageHelper ih = new ImageHelper();
        int width = image.getWidth(ih);
        if (ih.badImage) {
          throw new IllegalStateException();
        }
        long tt1 = System.currentTimeMillis();

        xyData = ucar.visad.Util.makeField(image, 0, false, true);
        long tt2 = System.currentTimeMillis();
        //      System.err.println("time to make field:" + (tt2-tt1));
      } catch (Exception iexc) {
        if (imageContent != null) {
          String msg = new String(imageContent);
          //  System.err.println ("msg:" + msg);
          /* Check to see if this is of the form:

          <?xml version='1.0' encoding="UTF-8" standalone="no" ?>
          <!DOCTYPE ServiceExceptionReport SYSTEM "http://www.digitalearth.gov/wmt/xml/exception_1_1_0.dtd ">
          <ServiceExceptionReport version="1.1.0">
           <ServiceException>
             Service denied due to system overload. Please try again later.
           </ServiceException>
          </ServiceExceptionReport>

          */
          if (msg.indexOf("<ServiceExceptionReport") >= 0) {
            try {
              StringBuffer errors = new StringBuffer();
              errors.append("\n");
              Element root = XmlUtil.getRoot(msg);
              List children = XmlUtil.findChildren(root, "ServiceException");
              for (int i = 0; i < children.size(); i++) {

                Element node = (Element) children.get(i);
                String code = XmlUtil.getAttribute(node, "code", (String) null);
                String body = XmlUtil.getChildText(node);
                if (code != null) {
                  errors.append(code + "\n");
                }
                errors.append(body.trim() + "\n");
              }
              LogUtil.userErrorMessage(
                  "Error accessing image with the url:\n" + url + "\nError:\n" + errors);
            } catch (Exception exc) {
              LogUtil.userErrorMessage(
                  "Error accessing image with the url:\n"
                      + url
                      + "\nError:\n"
                      + StringUtil.stripTags(msg));
            }
            return null;
          }

          msg = StringUtil.replace(msg, "\n", " ").toLowerCase();
          if (StringUtil.stringMatch(msg, "service\\s*exception")) {
            if (StringUtil.stringMatch(msg, "cannot\\s*be\\s*less\\s*than")) {
              return null;
            }
          }
          if (msg.indexOf("error") >= 0) {
            LogUtil.userErrorMessage(
                "There was an error accessing the image with the url:\n"
                    + url
                    + "\nError:\n"
                    + new String(imageContent));
            return null;
          }
        }
        logException("There was an error accessing the image with the url:\n" + url, iexc);
        return null;
      }

      if (writeFile != null) {
        try {
          ImageXmlDataSource.writeToFile(writeFile, boundsToUse, imageContent, wmsInfo.getFormat());
        } catch (Exception exc) {
          throw new IllegalArgumentException(
              "Error writing image xml file:" + writeFile + " " + exc);
        }
      }
    }

    Linear2DSet domain = (Linear2DSet) xyData.getDomainSet();
    Linear2DSet imageDomain =
        new Linear2DSet(
            RealTupleType.SpatialEarth2DTuple,
            boundsToUse.getMinLon(),
            boundsToUse.getMaxLon(),
            domain.getX().getLength(),
            boundsToUse.getMaxLat(),
            boundsToUse.getMinLat(),
            domain.getY().getLength());

    // System.err.println("image domain:" + imageDomain);

    /*
    new Linear2DSet(RealTupleType.SpatialEarth2DTuple,
                        boundsToUse.getMinLon(), boundsToUse.getMaxLon(),
                        domain.getX().getLength(),
                        boundsToUse.getMinLat() +diff, boundsToUse.getMinLat(),
                        domain.getY().getLength());*/

    FieldImpl field = GridUtil.setSpatialDomain(xyData, imageDomain, true);

    return field;
  }
Пример #19
0
 /**
  * Make a column header from the RealType and Unit
  *
  * @param rt the RealType
  * @param unit the Unit
  * @return column name
  */
 private String makeColumnName(RealType rt, Unit unit) {
   return Util.cleanTypeName(rt) + " [" + unit + "]";
 }
Пример #20
0
  /** Make the <code>DataChoices</code> for this <code>DataSource</code>. */
  public void doMakeDataChoices() {

    if (sources == null) {
      return;
    }
    String stationModelName = (String) getProperty(PROP_STATIONMODELNAME);
    Hashtable properties =
        Misc.newHashtable(DataChoice.PROP_ICON, "/auxdata/ui/icons/Placemark16.gif");
    if (stationModelName != null) {
      properties.put(PROP_STATIONMODELNAME, stationModelName);
    }
    if (!getDefaultLevels().isEmpty()) {
      properties.put(DataSelection.PROP_DEFAULT_LEVELS, getDefaultLevels());
    }
    DataChoice uberChoice = null;
    /*  Might want to do this someday
    uberChoice = new DirectDataChoice(this,
                                        sources, getName(),
                                        getDataName(),
                                        getPointCategories(),
                                        properties);
    */

    if (sources.size() > 1) {
      uberChoice =
          new CompositeDataChoice(
              this, sources, getName(), getDataName(), getPointCategories(), properties);
      addDataChoice(uberChoice);
    }

    for (int i = 0; i < sources.size(); i++) {
      String dataChoiceDesc = getDescription();
      String dataChoiceName = getDataName();
      if (uberChoice != null) {
        dataChoiceDesc = IOUtil.getFileTail(sources.get(i).toString());
        dataChoiceName = IOUtil.getFileTail(sources.get(i).toString());
      }

      DataChoice choice =
          new DirectDataChoice(
              this,
              new Integer(i),
              dataChoiceDesc,
              dataChoiceName,
              getPointCategories(),
              properties);

      /*
      We'd like to create sub choices for each parameter but we don't really
      know the parameters until we read the data and that can be expensive
                  DirectDataChoice subChoice = new DirectDataChoice(this,
                            (String) sources.get(i),
                            getDescription(), getDataName(),
                            getPointCategories(), properties);
                            choice.addDataChoice(subChoice);*/

      if (uberChoice != null) {
        ((CompositeDataChoice) uberChoice).addDataChoice(choice);
      } else {
        addDataChoice(choice);
      }
      // Only add the grid data choices for the first source
      if (i > 0) {
        continue;
      }
      try {
        FieldImpl sample = (makeGridFields ? getSample(choice) : null);
        if (sample != null) {
          for (int dataChoiceType = 0; dataChoiceType < 2; dataChoiceType++) {
            Hashtable seenFields = new Hashtable();
            if (ucar.unidata.data.grid.GridUtil.isTimeSequence(sample)) {
              sample = (FieldImpl) sample.getSample(0);
            }
            PointOb ob = (PointOb) sample.getSample(0);
            Tuple tuple = (Tuple) ob.getData();
            TupleType tupleType = (TupleType) tuple.getType();
            MathType[] types = tupleType.getComponents();
            CompositeDataChoice compositeDataChoice = null;
            for (int typeIdx = 0; typeIdx < types.length; typeIdx++) {
              if (!(types[typeIdx] instanceof RealType)) {
                continue;
              }
              RealType type = (RealType) types[typeIdx];
              if (!canCreateGrid(type)) {
                continue;
              }
              //                        List gridCategories =
              //                            DataCategory.parseCategories("OA Fields;GRID-2D-TIME;");
              List gridCategories = DataCategory.parseCategories("GRID-2D-TIME;", false);
              if (compositeDataChoice == null) {
                compositeDataChoice =
                    new CompositeDataChoice(
                        this,
                        "",
                        "Grid Fields from Objective Analysis",
                        "Gridded Fields " + ((dataChoiceType == 0) ? "" : "(with first guess)"),
                        Misc.newList(DataCategory.NONE_CATEGORY),
                        null);
                addDataChoice(compositeDataChoice);
              }
              String name = ucar.visad.Util.cleanTypeName(type.toString());
              if (seenFields.get(name) != null) {
                continue;
              }
              seenFields.put(name, name);
              List idList = Misc.newList(new Integer(i), type);
              if (dataChoiceType == 1) {
                idList.add(new Boolean(true));
              }
              DataChoice gridChoice =
                  new DirectDataChoice(this, idList, name, name, gridCategories, (Hashtable) null);
              compositeDataChoice.addDataChoice(gridChoice);
            }
          }
        }
      } catch (Exception exc) {
        throw new WrapperException("Making grid parameters", exc);
      }
      //            if(true) break;
    }
  }
Пример #21
0
  /**
   * Return the list of {@link ucar.unidata.util.TwoFacedObject}s that make up the list of units.
   *
   * @return List of unit holding objects.
   */
  public List getDefaultUnitList() {
    synchronized (UNIT_MUTEX) {
      // TODO:
      if (unitList != null) {
        return unitList;
      }
      // First  check if we have one saved as a preference
      unitList = (List) getStore().get(PREF_UNITLIST);
      if (unitList == null) {
        unitList = new ArrayList();
        unitList.add(new TwoFacedObject("Default", null));
      }
      HashSet<String> seenName = new HashSet<String>();
      List tmp = new ArrayList();
      for (Object o : unitList) {
        String s = o.toString().toLowerCase();
        if (seenName.contains(s)) {
          continue;
        }
        if (tmp.contains(o)) {
          continue;
        }
        tmp.add(o);
        seenName.add(s);
      }
      unitList = tmp;

      String[] names = {
        // Temperature
        "Celsius",
        "Fahrenheit",
        "Kelvin",
        // Pressure
        "millibar",
        "hectoPascal",
        // Distance
        "m",
        "km",
        "miles",
        "feet",
        "inches",
        "cm",
        "mm",
        // speed
        "m/s",
        "mi/hr",
        "knot",
        "km/hr"
      };
      for (int i = 0; i < names.length; i++) {
        try {
          TwoFacedObject tfo = new TwoFacedObject(names[i], Util.parseUnit(names[i]));
          if (!unitList.contains(tfo) && !seenName.contains(tfo.toString().toLowerCase())) {
            unitList.add(tfo);
          }

        } catch (Exception exc) {
        }
      }

      return unitList;
    }
  }
Пример #22
0
  /**
   * Create the param infos from the given xml root
   *
   * @param root The xml root
   * @return List of param infos
   */
  private List createParamInfoList(Element root) {

    List infos = new ArrayList();

    if (!root.getTagName().equals(TAG_PARAMS)) {
      try {
        Object obj = getIdv().getEncoderForRead().toObject(root);
        if (obj instanceof List) {
          infos.addAll((List) obj);
        } else {
          System.err.println("Unknown object type: " + obj.getClass().getName());
        }
      } catch (Exception exc) {
        System.err.println("Error reading param defaults");
      }
      return infos;
    }

    List nodes = XmlUtil.findChildren(root, TAG_PARAM);

    for (int i = 0; i < nodes.size(); i++) {
      Element child = (Element) nodes.get(i);
      Range range = null;
      Unit displayUnit = null;
      ContourInfo contourInfo = null;

      String paramName = XmlUtil.getAttribute(child, ATTR_NAME);
      String colorTableName = XmlUtil.getAttribute(child, ATTR_COLORTABLE, (String) null);
      String range_min = XmlUtil.getAttribute(child, ATTR_RANGE_MIN, (String) null);
      String range_max = XmlUtil.getAttribute(child, ATTR_RANGE_MAX, (String) null);

      String unitName = XmlUtil.getAttribute(child, ATTR_UNIT, (String) null);

      String ci_interval = XmlUtil.getAttribute(child, ATTR_CI_INTERVAL, (String) null);
      String ci_base = XmlUtil.getAttribute(child, ATTR_CI_BASE, (String) null);
      String ci_min = XmlUtil.getAttribute(child, ATTR_CI_MIN, range_min);
      String ci_max = XmlUtil.getAttribute(child, ATTR_CI_MAX, range_max);
      boolean ci_dash = XmlUtil.getAttribute(child, ATTR_CI_DASH, DFLT_CI_DASH);
      boolean ci_label = XmlUtil.getAttribute(child, ATTR_CI_LABEL, DFLT_CI_LABEL);
      String ci_width = XmlUtil.getAttribute(child, ATTR_CI_WIDTH, String.valueOf(DFLT_CI_WIDTH));

      if (unitName != null) {
        try {
          displayUnit = ucar.visad.Util.parseUnit(unitName);
        } catch (Exception e) {
          LogUtil.printException(log_, "Creating unit: " + unitName, e);
        }
      }

      if ((ci_interval != null) || (ci_base != null)) {
        if (ci_interval == null) {
          ci_interval = "NaN";
        }

        if (ci_base == null) {
          ci_base = "NaN";
        }
        if (ci_min == null) {
          ci_min = "NaN";
        }
        if (ci_max == null) {
          ci_max = "NaN";
        }
        if (ci_width == null) {
          ci_width = "1";
        }
        contourInfo =
            new ContourInfo(
                ci_interval,
                Misc.parseDouble(ci_base),
                Misc.parseDouble(ci_min),
                Misc.parseDouble(ci_max),
                ci_label,
                ci_dash,
                ContourInfo.DEFAULT_FILL,
                Misc.parseDouble(ci_width));
      }

      if ((ci_dash != DFLT_CI_DASH) || (ci_label != DFLT_CI_LABEL)) {
        if (contourInfo == null) {
          contourInfo = new ContourInfo(Double.NaN, Double.NaN, Double.NaN, Double.NaN);
          contourInfo.setIsLabeled(ci_label);
          contourInfo.setDashOn(ci_dash);
        }
      }

      if ((range_min != null) && (range_max != null)) {
        range = new Range(Misc.parseDouble(range_min), Misc.parseDouble(range_max));
      }

      ParamInfo paramInfo =
          new ParamInfo(paramName, colorTableName, range, contourInfo, displayUnit);
      infos.add(paramInfo);
    }
    return infos;
  }
Пример #23
0
    /**
     * Edit row
     *
     * @param paramInfo param info
     * @param removeOnCancel Should remove param info if user presses cancel_
     * @return ok
     */
    public boolean editRow(ParamInfo paramInfo, boolean removeOnCancel) {

      List comps = new ArrayList();
      ParamField nameFld = new ParamField(null, true);
      nameFld.setText(paramInfo.getName());
      JPanel topPanel = GuiUtils.hbox(GuiUtils.lLabel("Parameter:  "), nameFld);
      topPanel = GuiUtils.inset(topPanel, 5);

      comps.add(GuiUtils.inset(new JLabel("Defined"), new Insets(5, 0, 0, 0)));
      comps.add(GuiUtils.filler());
      comps.add(GuiUtils.filler());

      final JLabel ctPreviewLbl = new JLabel("");
      final JLabel ctLbl = new JLabel("");
      if (paramInfo.hasColorTableName()) {
        ctLbl.setText(paramInfo.getColorTableName());
        ColorTable ct =
            getIdv().getColorTableManager().getColorTable(paramInfo.getColorTableName());
        if (ct != null) {
          ctPreviewLbl.setIcon(ColorTableCanvas.getIcon(ct));
        } else {
          ctPreviewLbl.setIcon(null);
        }
      }
      String cbxLabel = "";
      final ArrayList menus = new ArrayList();
      getIdv()
          .getColorTableManager()
          .makeColorTableMenu(
              new ObjectListener(null) {
                public void actionPerformed(ActionEvent ae, Object data) {
                  ctLbl.setText(data.toString());
                  ColorTable ct = getIdv().getColorTableManager().getColorTable(ctLbl.getText());
                  if (ct != null) {
                    ctPreviewLbl.setIcon(ColorTableCanvas.getIcon(ct));
                  } else {
                    ctPreviewLbl.setIcon(null);
                  }
                }
              },
              menus);

      JCheckBox ctUseCbx = new JCheckBox(cbxLabel, paramInfo.hasColorTableName());
      final JButton ctPopup = new JButton("Change");
      ctPopup.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
              GuiUtils.showPopupMenu(menus, ctPopup);
            }
          });
      addEditComponents(
          comps,
          "Color Table:",
          ctUseCbx,
          GuiUtils.hbox(ctPopup, GuiUtils.vbox(ctLbl, ctPreviewLbl), 5));

      JCheckBox rangeUseCbx = new JCheckBox(cbxLabel, paramInfo.hasRange());
      JTextField minFld = new JTextField("" + paramInfo.getMin(), 4);
      JTextField maxFld = new JTextField("" + paramInfo.getMax(), 4);
      JPanel rangePanel = GuiUtils.hbox(minFld, maxFld, 5);
      addEditComponents(comps, "Range:", rangeUseCbx, rangePanel);

      JCheckBox unitUseCbx = new JCheckBox(cbxLabel, paramInfo.hasDisplayUnit());
      String unitLabel = "";
      Unit unit = null;
      if (paramInfo.hasDisplayUnit()) {
        unit = paramInfo.getDisplayUnit();
      }

      JComboBox unitFld = getIdv().getDisplayConventions().makeUnitBox(unit, null);
      //            JTextField unitFld = new JTextField(unitLabel, 15);
      addEditComponents(comps, "Unit:", unitUseCbx, unitFld);

      ContourInfo ci = paramInfo.getContourInfo();
      JCheckBox contourUseCbx = new JCheckBox(cbxLabel, ci != null);
      if (ci == null) {
        ci = new ContourInfo();
      }
      ContourInfoDialog contDialog =
          new ContourInfoDialog("Edit Contour Defaults", false, null, false);
      contDialog.setState(ci);
      addEditComponents(comps, "Contour:", contourUseCbx, contDialog.getContents());

      GuiUtils.tmpInsets = new Insets(5, 5, 5, 5);
      JComponent contents = GuiUtils.doLayout(comps, 3, GuiUtils.WT_NNY, GuiUtils.WT_N);

      contents = GuiUtils.topCenter(topPanel, contents);
      contents = GuiUtils.inset(contents, 5);
      while (true) {
        if (!GuiUtils.showOkCancelDialog(null, "Parameter Defaults", contents, null)) {
          if (removeOnCancel) {
            myParamInfos.remove(paramInfo);
            tableChanged();
          }
          return false;
        }
        String what = "";
        try {
          if (contourUseCbx.isSelected()) {
            what = "setting contour defaults";
            contDialog.doApply();
            ci.set(contDialog.getInfo());
            paramInfo.setContourInfo(ci);
          } else {
            paramInfo.clearContourInfo();
          }
          if (unitUseCbx.isSelected()) {
            what = "setting display unit";
            Object selected = unitFld.getSelectedItem();
            String unitName = TwoFacedObject.getIdString(selected);
            if ((unitName == null) || unitName.trim().equals("")) {
              paramInfo.setDisplayUnit(null);
            } else {
              paramInfo.setDisplayUnit(ucar.visad.Util.parseUnit(unitName));
            }
          } else {
            paramInfo.setDisplayUnit(null);
          }

          if (ctUseCbx.isSelected()) {
            paramInfo.setColorTableName(ctLbl.getText());
          } else {
            paramInfo.clearColorTableName();
          }

          if (rangeUseCbx.isSelected()) {
            what = "setting range";
            paramInfo.setRange(
                new Range(Misc.parseNumber(minFld.getText()), Misc.parseNumber(maxFld.getText())));
          } else {
            paramInfo.clearRange();
          }

          paramInfo.setName(nameFld.getText().trim());
          break;
        } catch (Exception exc) {
          errorMsg("An error occurred " + what + "\n " + exc.getMessage());
          //              exc.printStackTrace();
        }
      }
      repaint();
      saveData();
      return true;
    }
  /**
   * Creates the display and control buttons from a {@link ucar.unidata.data.DataChoice}.
   *
   * @param dataChoice The data for this instance.
   * @return <code>true</code> if and only if this instance was correctly initialized.
   * @throws VisADException couldn't create a VisAD object needed
   * @throws RemoteException couldn't create a remote object needed
   */
  public boolean init(DataChoice dataChoice) throws VisADException, RemoteException {

    /*
     * Initialize the superclass.
     */
    if (!super.init()) {
      return false;
    }

    setSpatialLoci(track);
    setSpatialLoci(stationProbes);

    if (!setData(dataChoice)) {
      return false;
    }
    List<DataSource> dsList = new ArrayList();
    dataChoice.getDataSources(dsList);
    TrackDataSource ds = (TrackDataSource) dsList.get(0);
    List adapters = ds.getAdapters();

    try {
      initDataChoice(adapters);
    } catch (Exception e) {
    }
    initSounding(dataList.get(0));

    stationProbes.setData(Util.indexedField(latLons, false));
    stationProbes.addAction(
        new ActionImpl("Station Probe Action") {
          private boolean first = true;

          public void doAction() {
            if (first) {
              first = false;
            } else {
              Misc.run(
                  new Runnable() {
                    public void run() {
                      try {
                        int i = stationProbes.getCloseIndex();
                        if ((i >= 0) && (stationMenue != null)) {
                          ignoreStationMenuEvent = true;
                          selectedStation.setPoint((RealTuple) latLons[i]);
                          stationMenue.setSelectedIndex(i);
                          setStation(i);
                        }
                      } catch (Exception ex) {
                        logException(ex);
                      } finally {
                        ignoreStationMenuEvent = false;
                      }
                    }
                  });
            }
          }
        });

    setPointSize();

    addDisplayable(stationProbes, FLAG_COLOR);
    addDisplayable(selectedStation, FLAG_COLOR);

    if (getSelectedStationIndex() >= 0) {
      selectedStation.setPoint((RealTuple) latLons[getSelectedStationIndex()]);
    }
    updateHeaderLabel();
    return true;
  }