コード例 #1
0
ファイル: StationModelCanvas.java プロジェクト: ethanrd/IDV
 /**
  * Create the list of shape descriptors form the xml
  *
  * @return List of shape descriptors
  */
 public List getShapeDescriptors() {
   if (shapeDescriptors == null) {
     shapeDescriptors = new ArrayList();
     List sds = shapeDescriptors;
     XmlResourceCollection symbolTypes = smm.symbolTypes;
     for (int i = 0; i < symbolTypes.size(); i++) {
       Element root = symbolTypes.getRoot(i);
       if (root == null) {
         continue;
       }
       XmlNodeList symbols = XmlUtil.getElements(root, TAG_SYMBOL);
       for (int j = 0; j < symbols.size(); j++) {
         final Element symbolNode = (Element) symbols.item(j);
         ShapeDescriptor sd =
             new ShapeDescriptor(
                 XmlUtil.getAttribute(symbolNode, ATTR_CLASS),
                 XmlUtil.getAttribute(symbolNode, ATTR_NAME),
                 XmlUtil.getAttribute(
                     symbolNode, ATTR_ICON, "/ucar/unidata/ui/symbol/images/default.gif"),
                 XmlUtil.getAttribute(symbolNode, ATTR_ATTRS, "")) {
               public void initializeGlyph(Glyph g) {
                 super.initializeGlyph(g);
                 initializeGlyphFromXml(g, symbolNode);
               }
             };
         sds.add(sd);
       }
     }
   }
   return shapeDescriptors;
 }
コード例 #2
0
ファイル: VariableRenamer.java プロジェクト: suvarchal/IDV
  /** Read in the resource xml files and store the URL maps */
  private void readVariableRenameResources() {

    for (int varRemapResourceIdx = 0;
        varRemapResourceIdx < varmapResourceCollection.size();
        varRemapResourceIdx++) {
      Element root = this.varmapResourceCollection.getRoot(varRemapResourceIdx, false);

      if (root == null) {
        continue;
      }

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

      for (Object node1 : nodes) {
        Element node = (Element) node1;
        String oldVar = XmlUtil.getAttribute(node, "old");
        String newVar = XmlUtil.getAttribute(node, "new");

        if (!this.varMaps.containsKey(oldVar)) {
          List<String> tmpList = new ArrayList<String>();
          tmpList.add(newVar);
          varMaps.put(oldVar, tmpList);
        } else {
          List<String> tmpList = varMaps.get(oldVar);
          tmpList.add(newVar);
          varMaps.put(oldVar, tmpList);
        }
      }
    }
  }
コード例 #3
0
ファイル: DataCategory.java プロジェクト: Unidata/IDV
 /**
  * Process the categories specified in the XML.
  *
  * @param root root element for the XML
  */
 private static void processCategories(Element root) {
   List children = XmlUtil.findChildren(root, TAG_CATEGORY);
   for (int i = 0; i < children.size(); i++) {
     Element child = (Element) children.get(i);
     String name = XmlUtil.getAttribute(child, ATTR_NAME);
     String value = XmlUtil.getAttribute(child, ATTR_DESC);
     if (allCategoriesMap.get(name) == null) {
       allCategories.add(name);
       allCategoriesMap.put(name, value);
     }
   }
 }
コード例 #4
0
ファイル: XmlChooser.java プロジェクト: nbearson/IDV
  /**
   * Generate a user interface from the given xml document (derived from the given path). The xml
   * can be a thredds query capability, any verion of a thredds catalog or an IDV menus xml file.
   *
   * @param doc the xml document
   * @param xmlRoot The root of the xml document to create a display for.
   * @param path The url path we got the xml from.
   */
  protected void makeUi(Document doc, Element xmlRoot, String path) {
    this.document = doc;
    setHaveData(false);
    if (xmlRoot == null) {
      return;
    }
    setSelected(path);
    XmlHandler handler = null;
    String tagName = XmlUtil.getLocalName(xmlRoot);

    if (tagName.equals(WmsUtil.TAG_WMS1) || tagName.equals(WmsUtil.TAG_WMS2)) {
      handler = new WmsHandler(this, xmlRoot, path);
    } else if (tagName.equals(TAG_ERROR)) {
      final String error = XmlUtil.getAttribute(xmlRoot, "label", "Error");
      LogUtil.userErrorMessage("Error: " + error);
      return;
    } else if (tagName.equals(CatalogUtil.TAG_CATALOG)) {
      handler = new ThreddsHandler(this, xmlRoot, path);
    } else if (tagName.equals("menus")) {
      handler = new MenuHandler(this, xmlRoot, path);
    } else {
      throw new IllegalArgumentException(
          "Unknown xml:"
              + ((xmlContents.length() > 100) ? xmlContents.substring(0, 100) : xmlContents)
              + " ...");
    }

    JComponent contents = handler.getContents();
    contents.setPreferredSize(new Dimension(200, 250));
    addToContents(contents);
    addToHistory(handler);
    updateStatus();
  }
コード例 #5
0
ファイル: XmlChooser.java プロジェクト: nbearson/IDV
 /**
  * Create the <code>XmlChooser</code>
  *
  * @param mgr The <code>IdvChooserManager</code>
  * @param root The xml root that defines this chooser
  */
 public XmlChooser(IdvChooserManager mgr, Element root) {
   super(mgr, root);
   initialUrlPath = ((chooserNode != null) ? XmlUtil.getAttribute(chooserNode, ATTR_URL, "") : "");
 }
コード例 #6
0
ファイル: ShapefileAdapter.java プロジェクト: Unidata/IDV
  /**
   * Read the xml format
   *
   * @param name filename or url
   * @param iStream input stream
   * @return List of point sets
   */
  private List doReadXml(String name, InputStream iStream) {
    List sets = new ArrayList();
    try {
      if (iStream == null) {
        iStream = IOUtil.getInputStream(name);
      }
      String xml = IOUtil.readContents(iStream);
      Element root = XmlUtil.getRoot(xml);
      if (root == null) {
        return sets;
      }
      NodeList elements = XmlUtil.getElements(root);
      for (int i = 0; i < elements.getLength(); i++) {
        Element child = (Element) elements.item(i);
        if (!XmlUtil.hasAttribute(child, ATTR_POINTS)) {
          continue;
        }
        double[] points = Misc.parseDoubles(XmlUtil.getAttribute(child, ATTR_POINTS));

        boolean isRect = false;
        if (!child.getTagName().equals(TAG_POLYGON)) {
          if (child.getTagName().equals(ShapeGlyph.TAG_SHAPE)) {
            if (XmlUtil.getAttribute(child, ShapeGlyph.ATTR_SHAPETYPE)
                .toLowerCase()
                .equals("rectangle")) {
              isRect = true;
            } else {
              continue;
            }
          } else {
            continue;
          }
        }

        if (XmlUtil.hasAttribute(child, "coordtype")) {
          String coord = XmlUtil.getAttribute(child, "coordtype");
          if (!coord.startsWith("LATLON")) {
            continue;
          }
          if (coord.equals("LATLONALT")) {
            double[] tmp = new double[2 * points.length / 3];
            int tmpCnt = 0;
            for (int ptIdx = 0; ptIdx < points.length; ptIdx += 3) {
              tmp[tmpCnt++] = points[ptIdx];
              tmp[tmpCnt++] = points[ptIdx + 1];
            }
            points = tmp;
          }
        }

        RealTupleType coordMathType = new RealTupleType(RealType.Longitude, RealType.Latitude);
        float[][] part = new float[2][points.length / 2];
        for (int ptIdx = 0; ptIdx < points.length / 2; ptIdx++) {
          part[1][ptIdx] = (float) points[ptIdx * 2];
          part[0][ptIdx] = (float) points[ptIdx * 2 + 1];
        }

        if (isRect) {
          part = ShapeGlyph.makeRectangle(part);
        }

        MapSet mapSet =
            new MapSet(
                coordMathType,
                part,
                part[0].length,
                (CoordinateSystem) null,
                (Unit[]) null,
                (ErrorEstimate[]) null,
                false /* no copy */);
        sets.add(mapSet);
      }
    } catch (Exception exc) {
      exc.printStackTrace();
    }

    return sets;
  }
コード例 #7
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;
  }
コード例 #8
0
ファイル: WmsDataSource.java プロジェクト: RickKohrs/IDV
  /**
   * 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;
  }