Exemplo n.º 1
0
  void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException {
    Unit super_degree = CommonUnit.degree.scale(2.5);
    RealType lon = RealType.getRealType("lon", super_degree);

    DataReference ref = loadFile();
    if (ref == null) {
      System.err.println("must specify netCDF file name");
      System.exit(1);
      return;
    }

    FieldImpl netcdf_data = (FieldImpl) ref.getData();

    // compute ScalarMaps from type components
    FunctionType ftype = (FunctionType) netcdf_data.getType();
    RealTupleType dtype = ftype.getDomain();
    MathType rntype = ftype.getRange();
    int n = dtype.getDimension();
    dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(0), Display.XAxis));
    if (n > 1) {
      dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(1), Display.YAxis));
    }
    if (n > 2) {
      dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(2), Display.ZAxis));
    }
    if (rntype instanceof RealType) {
      dpys[0].addMap(new ScalarMap((RealType) rntype, Display.Green));
      if (n <= 2) {
        dpys[0].addMap(new ScalarMap((RealType) rntype, Display.ZAxis));
      }
    } else if (rntype instanceof RealTupleType) {
      int m = ((RealTupleType) rntype).getDimension();
      RealType rr = (RealType) ((RealTupleType) rntype).getComponent(0);
      dpys[0].addMap(new ScalarMap(rr, Display.Green));
      if (n <= 2) {
        if (m > 1) {
          rr = (RealType) ((RealTupleType) rntype).getComponent(1);
        }
        dpys[0].addMap(new ScalarMap(rr, Display.ZAxis));
      }
    }
    dpys[0].addMap(new ConstantMap(0.5, Display.Red));
    dpys[0].addMap(new ConstantMap(0.0, Display.Blue));

    dpys[0].addReference(ref, null);

    System.out.println("now saving data as 'save.nc' and re-reading");

    Plain plain = new Plain();
    try {
      plain.save("save.nc", netcdf_data, true);
      netcdf_data = (FieldImpl) plain.open("save.nc");
    } catch (IOException e) {
      System.err.println("Couldn't open \"save.nc\": " + e.getMessage());
      System.exit(1);
      return;
    }
  }
Exemplo n.º 2
0
 /**
  * _more_
  *
  * @param range _more_
  * @param var _more_
  * @return _more_
  * @throws Exception _more_
  */
 protected float[] getFloatData(Range range, String var) throws Exception {
   long t1 = System.currentTimeMillis();
   float[] f =
       SqlUtil.readFloat(
           SqlUtil.getIterator(select("(" + var + ")", TABLE_DATA, "order by " + varTime)),
           1,
           (float) getMissingValue(var));
   long t2 = System.currentTimeMillis();
   //            System.err.println("length:" + f.length + " time:" + (t2-t1));
   if (f.length == 0) {
     throw new BadDataException("No observations found in data base");
   }
   return f;
 }
Exemplo n.º 3
0
  /**
   * Robustly make a curve to a front
   *
   * @param curve the curve
   * @param flip true to flip the pips
   * @return the resulting front as a FieldImpl
   * @throws RemoteException On badness
   */
  public FieldImpl robustCurveToFront(float[][] curve, boolean flip) throws RemoteException {

    // resample curve uniformly along length
    float increment = rsegment_length / (rprofile_length * zoom);
    float[][] oldCurve = null;
    try {
      oldCurve = resample_curve(curve, increment);
    } catch (VisADError ve) { // bad curve
      return null;
    }

    int fw = filter_window;
    fw = 1;
    FieldImpl front = null;

    float[][] originalCurve = curve;

    debug = true;
    for (int tries = 0; tries < 12; tries++) {
      // lowpass filter curve
      curve = smooth_curve(oldCurve, fw);
      // resample smoothed curve
      curve = resample_curve(curve, increment);
      try {
        front = curveToFront(curve, flip);
        break;
      } catch (VisADException e) {
        oldCurve = curve;
        if (tries > 4) {
          int n = oldCurve[0].length;
          if (n > 2) {
            float[][] no = new float[2][n - 2];
            System.arraycopy(oldCurve[0], 1, no[0], 0, n - 2);
            System.arraycopy(oldCurve[1], 1, no[1], 0, n - 2);
            oldCurve = no;
          }
        }
        if (tries > 8) {
          fw = 2 * fw;
        }
        // if (debug) System.out.println("retry filter window = " + fw + " " + e);
        if (tries == 9) {
          //                    System.out.println("cannot smooth curve");
          front = null;
        }
      }
    }
    return front;
  }
Exemplo n.º 4
0
 public void actionPerformed(ActionEvent e) {
   String cmd = e.getActionCommand();
   if (cmd.equals("del")) {
     try {
       UnionSet set = (UnionSet) ref.getData();
       SampledSet[] sets = set.getSets();
       SampledSet[] new_sets = new SampledSet[sets.length - 1];
       System.arraycopy(sets, 0, new_sets, 0, sets.length - 1);
       ref.setData(new UnionSet(set.getType(), new_sets));
     } catch (VisADException ex) {
     } catch (RemoteException ex) {
     }
   } else if (cmd.equals("fill")) {
     UnionSet set = null;
     try {
       set = (UnionSet) ref.getData();
       System.out.println("area = " + DelaunayCustom.computeArea(set));
     } catch (VisADException ex) {
       System.out.println(ex.getMessage());
     }
     try {
       // Irregular2DSet new_set = DelaunayCustom.fill(set);
       Irregular2DSet new_set = DelaunayCustom.fillCheck(set, false);
       if (new_ref == null) {
         new_ref = new DataReferenceImpl("fill");
         ConstantMap[] cmaps =
             new ConstantMap[] {
               new ConstantMap(1.0, Display.Blue),
               new ConstantMap(1.0, Display.Red),
               new ConstantMap(0.0, Display.Green)
             };
         DataRenderer renderer =
             (display instanceof DisplayImplJ3D)
                 ? (DataRenderer) new DefaultRendererJ3D()
                 : (DataRenderer) new DefaultRendererJ2D();
         renderer.suppressExceptions(true);
         display.addReferences(renderer, new_ref, cmaps);
       }
       new_ref.setData(new_set);
     } catch (VisADException ex) {
       System.out.println(ex.getMessage());
     } catch (RemoteException ex) {
       System.out.println(ex.getMessage());
     }
   } else if (cmd.equals("lines")) {
     try {
       lines = !lines;
       GraphicsModeControl mode = display.getGraphicsModeControl();
       if (lines) {
         mode.setPolygonMode(DisplayImplJ3D.POLYGON_LINE);
       } else {
         mode.setPolygonMode(DisplayImplJ3D.POLYGON_FILL);
       }
     } catch (VisADException ex) {
       System.out.println(ex.getMessage());
     } catch (RemoteException ex) {
       System.out.println(ex.getMessage());
     }
   }
 }
Exemplo n.º 5
0
  static {
    Unit min;
    Unit h;
    Unit d;
    Unit a;

    try {
      min = SECOND.scale(60).clone("min");
      h = min.scale(60).clone("h");
      d = h.scale(24).clone("d");
      a = SECOND.scale(3.15569259747e7).clone("a");
      instance = new TimeInterval();
    } catch (Exception e) {
      min = null; // to fool compiler
      h = null; // to fool compiler
      d = null; // to fool compiler
      a = null; // to fool compiler

      System.err.println("TimeInterval.<clinit>(): Couldn't initialize class: " + e);
      System.exit(1);
    }

    MINUTE = min;
    HOUR = h;
    DAY = d;
    YEAR = a;
  }
Exemplo n.º 6
0
 static {
   try {
     instance = new YSpeed();
   } catch (Exception e) {
     System.err.println("YSpeed.<clinit>(): Couldn't initialize class: " + e);
     System.exit(1);
   }
 }
Exemplo n.º 7
0
 /**
  * attempt to invoke a Method with the given Object arguments, performing static method
  * auto-detection and automatic array compression
  */
 public static Object invokeMethod(Method m, Object[] o)
     throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
   Object obj;
   Object[] args;
   Class[] c = m.getParameterTypes();
   int num = (o == null) ? 0 : o.length;
   int len = -1;
   int a = -1;
   if (c != null) {
     len = c.length;
     for (int i = 0; i < len; i++) {
       if (c[i].isArray()) a = i;
     }
   }
   if (Modifier.isStatic(m.getModifiers())) {
     // static method
     obj = null;
     if (num > 0) {
       if (a < 0) {
         args = new Object[num];
         System.arraycopy(o, 0, args, 0, num);
       } else {
         // compress some of the arguments into array form
         args = new Object[len];
         if (a > 0) System.arraycopy(o, 0, args, 0, a);
         Object array = Array.newInstance(c[a].getComponentType(), num - len + 1);
         System.arraycopy(o, a, array, 0, num - len + 1);
         args[a] = array;
         if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1);
       }
     } else args = null;
   } else {
     // object method
     if (num > 0) obj = o[0];
     else {
       // invalid object method
       return null;
     }
     if (num > 1) {
       if (a < 0) {
         args = new Object[num - 1];
         System.arraycopy(o, 1, args, 0, num - 1);
       } else {
         // compress some of the arguments into array form
         args = new Object[len];
         if (a > 0) System.arraycopy(o, 1, args, 0, a);
         Object array = Array.newInstance(c[a].getComponentType(), num - len);
         System.arraycopy(o, a + 1, array, 0, num - len);
         args[a + 1] = array;
         if (a < len - 1) System.arraycopy(o, num - len + a + 1, args, a + 1, len - a - 1);
       }
     } else args = null;
   }
   return m.invoke(obj, args);
 }
Exemplo n.º 8
0
 /**
  * Test this out
  *
  * @param args filename
  * @throws Exception problem
  */
 public static void main(String[] args) throws Exception {
   if (args.length == 0) {
     System.err.println("need to supply a filename");
     System.exit(1);
   }
   ShapefileAdapter sfa = new ShapefileAdapter(args[0]);
   UnionSet data = sfa.getData();
   // System.out.println(data);
   visad.python.JPythonMethods.dumpTypes(data);
 }
Exemplo n.º 9
0
 /**
  * Utility to make a set
  *
  * @param sets List of sets
  * @return The set of sets
  * @throws VisADException On badness
  */
 public static UnionSet makeSet(List sets) throws VisADException {
   if (sets == null) {
     return null;
   }
   SampledSet[] ss = new SampledSet[sets.size()];
   System.arraycopy(sets.toArray(), 0, ss, 0, sets.size());
   if (ss.length > 0) {
     return new UnionSet(ss[0].getType(), ss, null, null, null, false);
   } else {
     return null;
   }
 }
Exemplo n.º 10
0
  private DataReferenceImpl loadFile() throws RemoteException, VisADException {
    FieldImpl data;
    try {
      data = (FieldImpl) new Plain().open(fileName);
    } catch (IOException e) {
      System.err.println("Couldn't open \"" + fileName + "\": " + e.getMessage());
      System.exit(1);
      return null;
    }
    // System.out.println("data type = " + data.getType());

    DataReferenceImpl ref = new DataReferenceImpl("netcdf");
    ref.setData(data);

    return ref;
  }
Exemplo n.º 11
0
 static {
   // initialize cache of FlatFields
   if (adaptedFlatFieldOwner != null
       && adaptedFlatFields != null
       && adaptedFlatFieldSizes != null
       && adaptedFlatFieldTimes != null
       && adaptedFlatFieldDirty != null) {
     for (int i = 0; i < MAX_FILE_FLAT_FIELDS; i++) {
       // mark Owners for all cache entries to indicate not
       // belonging to any FileFlatField
       adaptedFlatFieldOwner[i] = null;
       adaptedFlatFields[i] = null;
       adaptedFlatFieldSizes[i] = 0;
       adaptedFlatFieldTimes[i] = System.currentTimeMillis();
       adaptedFlatFieldDirty[i] = false;
     }
   }
 }
Exemplo n.º 12
0
  static {
    Real mdp = null;
    Real mp = null;
    Real mws = null;

    try {
      mdp = (Real) DewPoint.getRealType().missingData();
      mp = (Real) AirPressure.getRealType().missingData();
      mws = (Real) WaterVaporMixingRatio.getRealType().missingData();
    } catch (Exception e) {
      System.err.print("Couldn't initialize class: ");
      e.printStackTrace();
      System.exit(1);
    }

    missingDewPoint = mdp;
    missingPres = mp;
    missingWsat = mws;
  }
Exemplo n.º 13
0
  static {
    CoordinateSystem coordSys;

    try {
      coordSys =
          new PolarCoordinateSystem(
              CartesianVelocity2D.instance().getRealTupleType(),
              Speed.DEFAULT_UNIT,
              PlaneAngle.DEFAULT_UNIT);
      instance =
          new PolarVelocity(
              "Polar_Velocity",
              (Speed) Speed.instance(),
              (PlaneAngle) PlaneAngle.instance(),
              coordSys);
    } catch (Exception e) {
      System.err.println("PolarVelocity.<clinit>(): Couldn't initialize class: " + e);
      System.exit(1);
    }
  }
Exemplo n.º 14
0
  /**
   * @param grid The grid.
   * @param gridWinds The grid-relative winds.
   * @param cs The coordinate system transformation of the grid.
   * @param index The index of the grid-relative wind component.
   * @param latI The index of latitude in the reference coordinate system.
   * @param lonI The index of longitude in the reference coordinate system.
   * @param us The array in which to add the computed U-component of the wind.
   * @param us The array in which to add the computed V-component of the wind.
   * @param vs
   * @throws IndexOutOfBoundsException if <code>gridWinds</code>, <code>us
   *                                   </code>, or <code>vs</code> is too small.
   * @throws VisADException if a VisAD failure occurs.
   */
  private static void addComponent(
      SampledSet grid,
      float[][] gridWinds,
      CoordinateSystem cs,
      int index,
      int latI,
      int lonI,
      float[] us,
      float[] vs)
      throws VisADException {

    int[][] neighbors = grid.getNeighbors(index);
    LatLonPointImpl refPt = new LatLonPointImpl();
    LatLonPointImpl neiPt = new LatLonPointImpl();
    Bearing bearing = new Bearing();
    float[] uv1 = new float[2];
    float[] uv2 = new float[2];
    boolean hasCS = cs != null;
    float[][] domainSamples = grid.getSamples(false);
    float[][] crefCoords = (hasCS) ? cs.toReference(Set.copyFloats(domainSamples)) : domainSamples;
    // If the grid is lat/lon or has an IdentityCoordinateSystem
    // don't do the rotation
    // TODO:  handle rotated lat/lon grids
    if (!hasCS
        || (crefCoords == domainSamples)
        || (Arrays.equals(crefCoords[latI], domainSamples[latI])
            && Arrays.equals(crefCoords[lonI], domainSamples[lonI]))) {
      // us = gridWinds[0];
      // vs = gridWinds[1];
      System.arraycopy(gridWinds[0], 0, us, 0, us.length);
      System.arraycopy(gridWinds[1], 0, vs, 0, vs.length);
    } else {

      for (int i = 0; i < neighbors.length; i++) {

        float[][] refCoords = grid.indexToValue(new int[] {i});
        if (hasCS) {
          refCoords = cs.toReference(refCoords);
        }

        float[][] neiCoords = grid.indexToValue(neighbors[i]);
        if (hasCS) {
          neiCoords = cs.toReference(neiCoords);
        }

        refPt.set(refCoords[latI][0], refCoords[lonI][0]);

        compute(
            refPt,
            neiPt,
            neiCoords[latI][0],
            neiCoords[lonI][0],
            -180,
            gridWinds[index][i],
            bearing,
            uv1);

        float d1 = (float) bearing.getDistance();

        compute(
            refPt,
            neiPt,
            neiCoords[latI][1],
            neiCoords[lonI][1],
            0,
            gridWinds[index][i],
            bearing,
            uv2);

        float d2 = (float) bearing.getDistance();
        boolean bad1 = Double.isNaN(d1);
        boolean bad2 = Double.isNaN(d2);

        if (bad1 && bad2) {
          us[i] = Float.NaN;
          vs[i] = Float.NaN;
        } else {
          if (bad1) {
            us[i] += uv2[0];
            vs[i] += uv2[1];
          } else if (bad2) {
            us[i] += uv1[0];
            vs[i] += uv1[1];
          } else {
            float tot = d1 + d2;
            float c1 = d2 / tot;
            float c2 = d1 / tot;

            us[i] += c1 * uv1[0] + c2 * uv2[0];
            vs[i] += c1 * uv1[1] + c2 * uv2[1];
          }
        }
      }
    }
  }
Exemplo n.º 15
0
  void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException {
    DefaultFamily df = new DefaultFamily("loader");

    DataReference ref1 = loadFile(df, file1, "img1");
    if (ref1 == null) {
      System.err.println("\"" + file1 + "\" is not a valid file");
      System.exit(1);
      return;
    }

    DataReference ref2 = loadFile(df, file2, "img2");
    if (ref2 == null) {
      System.err.println("\"" + file2 + "\" is not a valid file");
      System.exit(1);
      return;
    }

    FlatField img1 = (FlatField) ref1.getData();
    FlatField img2 = (FlatField) ref2.getData();

    /*
        if (!img1.getType().equals(img2.getType())) {
          System.err.println("Incompatible file types:");
          System.err.println("  " + file1 + ": " + img1.getType());
          System.err.println("  " + file2 + ": " + img2.getType());
          System.exit(1);
          return;
        }
    */

    // compute ScalarMaps from type components
    FunctionType ftype = (FunctionType) img1.getType();
    RealTupleType dtype = ftype.getDomain();
    RealTupleType rtype = (RealTupleType) ftype.getRange();

    /* map domain elements to spatial axes */
    final int dLen = dtype.getDimension();
    for (int i = 0; i < dLen; i++) {
      ScalarType scalT;
      DisplayRealType dpyRT;

      switch (i) {
        case 0:
          dpyRT = Display.XAxis;
          break;
        case 1:
          dpyRT = Display.YAxis;
          break;
        case 2:
          dpyRT = Display.ZAxis;
          break;
        default:
          dpyRT = null;
          break;
      }

      if (dpyRT != null) {
        dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(i), dpyRT));
      }
    }

    /* map range elements to colors */
    final int rLen = rtype.getDimension();
    for (int i = 0; i < rLen; i++) {
      ScalarType scalT;
      DisplayRealType dpyRT;

      switch (i) {
        case 0:
          dpyRT = Display.Red;
          break;
        case 1:
          dpyRT = Display.Green;
          break;
        case 2:
          dpyRT = Display.Blue;
          break;
        default:
          dpyRT = null;
          break;
      }

      if (dpyRT != null) {
        dpys[0].addMap(new ScalarMap((RealType) rtype.getComponent(i), dpyRT));
      }
    }

    dpys[0].addReference(ref1, null);
    dpys[0].addReference(ref2, null);

    dpys[0].addActivityHandler(new SwitchGIFs(dpys[0]));
  }
Exemplo n.º 16
0
  /**
   * Set the front state
   *
   * @param fsegment length of first segment in graphics coord
   * @param rsegment length of repeating segment in graphics coord
   * @param fshapes shapes of the front
   * @param fred first reds
   * @param fgreen first greens
   * @param fblue first blues
   * @param rshapes repeating shapes
   * @param rred repeating reds
   * @param rgreen repeating greens
   * @param rblue repeating blues
   * @throws RemoteException On badness
   * @throws VisADException On badness
   */
  private void setFrontState(
      float fsegment,
      float rsegment,
      float[][][] fshapes,
      float[] fred,
      float[] fgreen,
      float[] fblue,
      float[][][] rshapes,
      float[] rred,
      float[] rgreen,
      float[] rblue)
      throws VisADException, RemoteException {
    fsegment_length = fsegment;
    rsegment_length = rsegment;
    nrshapes = rshapes.length;
    for (int i = 0; i < nrshapes; i++) {
      if ((rshapes[i] == null)
          || (rshapes[i].length != 2)
          || (rshapes[i][0] == null)
          || (rshapes[i][1] == null)
          || (rshapes[i][0].length != rshapes[i][1].length)) {
        throw new VisADException("bad rshapes[" + i + "]");
      }
    }
    if ((rred == null)
        || (rred.length != nrshapes)
        || (rgreen == null)
        || (rgreen.length != nrshapes)
        || (rblue == null)
        || (rblue.length != nrshapes)) {
      throw new VisADException("bad rcolors");
    }
    repeat_tris = new int[nrshapes][][];
    for (int i = 0; i < nrshapes; i++) {
      repeat_tris[i] = DelaunayCustom.fill(rshapes[i]);
    }
    repeat_shapes = new float[nrshapes][2][];
    int rlen = 0;
    for (int i = 0; i < nrshapes; i++) {
      int n = rshapes[i][0].length;
      rlen += n;
      repeat_shapes[i][0] = new float[n];
      repeat_shapes[i][1] = new float[n];
      System.arraycopy(rshapes[i][0], 0, repeat_shapes[i][0], 0, n);
      System.arraycopy(rshapes[i][1], 0, repeat_shapes[i][1], 0, n);
    }
    rprofile_length = rlen;
    repeat_red = new float[nrshapes];
    repeat_green = new float[nrshapes];
    repeat_blue = new float[nrshapes];
    System.arraycopy(rred, 0, repeat_red, 0, nrshapes);
    System.arraycopy(rgreen, 0, repeat_green, 0, nrshapes);
    System.arraycopy(rblue, 0, repeat_blue, 0, nrshapes);

    if (fshapes == null) {
      // if no different first shapes, just use repeat shapes
      nfshapes = nrshapes;
      first_tris = repeat_tris;
      first_shapes = repeat_shapes;
      first_red = repeat_red;
      first_green = repeat_green;
      first_blue = repeat_blue;
    } else {
      nfshapes = fshapes.length;
      for (int i = 0; i < nfshapes; i++) {
        if ((fshapes[i] == null)
            || (fshapes[i].length != 2)
            || (fshapes[i][0] == null)
            || (fshapes[i][1] == null)
            || (fshapes[i][0].length != fshapes[i][1].length)) {
          throw new VisADException("bad fshapes[" + i + "]");
        }
      }
      if ((fred == null)
          || (fred.length != nfshapes)
          || (fgreen == null)
          || (fgreen.length != nfshapes)
          || (fblue == null)
          || (fblue.length != nfshapes)) {
        throw new VisADException("bad fcolors");
      }
      first_tris = new int[nfshapes][][];
      for (int i = 0; i < nfshapes; i++) {
        first_tris[i] = DelaunayCustom.fill(fshapes[i]);
      }
      first_shapes = new float[nfshapes][2][];
      int flen = 0;
      for (int i = 0; i < nfshapes; i++) {
        int n = fshapes[i][0].length;
        flen += n;
        first_shapes[i][0] = new float[n];
        first_shapes[i][1] = new float[n];
        System.arraycopy(fshapes[i][0], 0, first_shapes[i][0], 0, n);
        System.arraycopy(fshapes[i][1], 0, first_shapes[i][1], 0, n);
      }
      fprofile_length = flen;
      first_red = new float[nfshapes];
      first_green = new float[nfshapes];
      first_blue = new float[nfshapes];
      System.arraycopy(fred, 0, first_red, 0, nfshapes);
      System.arraycopy(fgreen, 0, first_green, 0, nfshapes);
      System.arraycopy(fblue, 0, first_blue, 0, nfshapes);
    }
    if (rprofile_length < 5) {
      rprofile_length = 5;
    }
    if (fprofile_length < 5) {
      fprofile_length = 5;
    }
  }
Exemplo n.º 17
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;
  }
Exemplo n.º 18
0
  private FlatField getAdaptedFlatField() {
    // if owner array is null,
    //  assume this object got serialized & unserialized
    if (adaptedFlatFieldOwner == null) {
      return null;
    }

    synchronized (adaptedFlatFields) {
      for (int ii = 0; ii < MAX_FILE_FLAT_FIELDS; ii++) {
        if (this == adaptedFlatFieldOwner[ii]) {

          // mark time of most recent access

          adaptedFlatFieldTimes[ii] = System.currentTimeMillis();

          return adaptedFlatFields[ii];
        }
      }

      // this FileFlatField does not own a cache entry, so invoke
      // CahceStrategy.allocate to allocate one, possibly by taking
      // one, possibly by taking one from another FileFlatField;
      // this will be an area for lots of thought and experimentation;

      adaptedFlatFieldIndex =
          cacheStrategy.allocate(
              adaptedFlatFields, adaptedFlatFieldDirty,
              adaptedFlatFieldSizes, adaptedFlatFieldTimes);

      // flush cache entry, if dirty

      if (adaptedFlatFieldDirty[adaptedFlatFieldIndex]) {
        try {
          adaptedFlatFieldOwner[adaptedFlatFieldIndex].flushCache();
        } catch (VisADException e) {
          System.out.println(e.getMessage());
        }
      }

      // create a new entry in adaptedFlatFields at adaptedFlatFieldIndex
      // and read data values from fileAccessor at fileLocation
      try {
        adaptedFlatFields[adaptedFlatFieldIndex] = fileAccessor.getFlatField();
      } catch (VisADException e1) {
        System.out.println(e1.getMessage());
      } catch (RemoteException e2) {
        System.out.println(e2.getMessage());
      }

      // mark cache entry as belonging to this FileFlatField

      adaptedFlatFieldOwner[adaptedFlatFieldIndex] = this;

      // get size of adapted FlatField
      // (by calling a method that currently does not exist)

      /*adaptedFlatFields[adaptedFlatFieldIndex].getSize(); */

      adaptedFlatFieldTimes[adaptedFlatFieldIndex] = System.currentTimeMillis();

      return adaptedFlatFields[adaptedFlatFieldIndex];
    }
  }