Example #1
0
  /** 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);
        }
      }
    }
  }
Example #2
0
 /**
  * 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;
 }
Example #3
0
  /**
   * 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();
  }
Example #4
0
 /**
  * Save the list of ParamInfo-s into the given file
  *
  * @param infoList List of infos
  * @param filename The filename to write to
  */
 public void doSave(List infoList, String filename) {
   try {
     Element root = createDom(XmlUtil.makeDocument(), infoList);
     IOUtil.writeFile(filename, XmlUtil.toString(root));
   } catch (Exception exc) {
     LogUtil.printException(log_, "Error writing file", exc);
   }
 }
Example #5
0
 /**
  * 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);
     }
   }
 }
Example #6
0
  /**
   * Load the xml defined by the given xmlPath. Try to create a display from it.
   *
   * @param xmlPath The url pointing to the xml to display.
   * @param myTimestamp Keeps track of which request this is.
   * @return Was this successful
   */
  public boolean makeUiFromPath(String xmlPath, int myTimestamp) {
    boolean ok = true;
    try {
      if (xmlPath.length() > 0) {
        showWaitCursor();
        xmlContents = IOUtil.readContents(xmlPath, NULL_STRING);
        showNormalCursor();
        if (myTimestamp != timestamp) {
          return false;
        }
        if (xmlContents == null) {
          // Clear out the tree
          xmlContents =
              XmlUtil.tag(TAG_ERROR, XmlUtil.attr("label", "Could not load url: " + xmlPath));
          ok = false;
        }
        // Check if its xml
        if (xmlContents.indexOf("<") >= 0) {
          document = XmlUtil.getDocument(xmlContents);
        }

        // If we failed to make an xml document then try to tack on the wms
        // capabilities request in case this is a wms url without one
        if ((document == null) || (document.getDocumentElement() == null)) {
          if (xmlPath.indexOf("?") < 0) {
            xmlPath = xmlPath + "?request=GetCapabilities&service=WMS";
          } else {
            xmlPath = xmlPath + "&request=GetCapabilities&service=WMS";
          }
          xmlContents = IOUtil.readContents(xmlPath, NULL_STRING);
          document = XmlUtil.getDocument(xmlContents);
        }

        if ((document == null) || (document.getDocumentElement() == null)) {
          throw new IllegalArgumentException("Could not process XML from:" + xmlPath);
        }
        makeUi(document, document.getDocumentElement(), xmlPath);
      } else {
        makeUi(null, null, xmlPath);
      }
    } catch (Exception exc) {
      if (myTimestamp != timestamp) {
        return false;
      }
      logException("Creating ui:" + xmlPath, exc);
      return false;
    }
    return ok;
  }
Example #7
0
 public void setTmp(byte[] value) {
   if (value == null) {
     password = null;
   } else {
     password = new String(XmlUtil.decodeBase64(new String(value)));
   }
 }
 private Node makeNewFolder() {
   if (imageDefaults == null) {
     imageDefaults = getImageDefaults();
   }
   if (newFolder.length() == 0) {
     return null;
   }
   List newChild = new ArrayList();
   Node newEle = imageDefaultsDocument.createElement(TAG_FOLDER);
   lastCat = newEle;
   String[] newAttrs = {ATTR_NAME, newFolder};
   XmlUtil.setAttributes((Element) newEle, newAttrs);
   newChild.add(newEle);
   XmlUtil.addChildren(imageDefaultsRoot, newChild);
   try {
     imageDefaults.writeWritable();
   } catch (Exception e) {
     logger.error("write error!", e);
   }
   imageDefaults.setWritableDocument(imageDefaultsDocument, imageDefaultsRoot);
   return newEle;
 }
Example #9
0
 /** Write out the user's editable param infos */
 private void saveData() {
   Document usersDoc = XmlUtil.makeDocument();
   Element usersRoot = createDom(usersDoc, getFirstTable().getParamInfoList());
   try {
     resources.setWritableDocument(usersDoc, usersRoot);
     resources.writeWritable();
     // Reinitialize the static state
     paramInfos = new ArrayList();
     paramToInfo = new Hashtable();
     init(resources);
   } catch (Exception exc) {
     LogUtil.printException(log_, "writing aliases xml", exc);
   }
 }
Example #10
0
 /** Import an xml param defaults file */
 public void doImport() {
   try {
     String filename = FileManager.getReadFile(FileManager.FILTER_XML);
     if (filename == null) {
       return;
     }
     Element root = XmlUtil.getRoot(IOUtil.readContents(filename));
     if (root == null) {
       return;
     }
     List infos = createParamInfoList(root);
     ParamDefaultsTable table = getCurrentTable();
     table.getParamInfoList().addAll(infos);
     table.tableChanged();
     saveData();
   } catch (Exception exc) {
     LogUtil.printException(log_, "Error importing file", exc);
   }
 }
 private void doRename(Element node) {
   if (imageDefaults == null) {
     imageDefaults = getImageDefaults();
   }
   if (!node.hasAttribute(ATTR_NAME)) return;
   JLabel label = new JLabel("New name: ");
   JTextField nameFld = new JTextField("", 20);
   JComponent contents =
       GuiUtils.doLayout(
           new Component[] {
             GuiUtils.rLabel("New name: "), nameFld,
           },
           2,
           GuiUtils.WT_N,
           GuiUtils.WT_N);
   contents = GuiUtils.center(contents);
   contents = GuiUtils.inset(contents, 10);
   if (!GuiUtils.showOkCancelDialog(
       null, "Rename \"" + node.getAttribute("name") + "\"", contents, null)) return;
   String newName = nameFld.getText().trim();
   String tagName = node.getTagName();
   Element root = imageDefaultsRoot;
   if (tagName.equals("default")) {
     root = (Element) node.getParentNode();
   }
   Element exists = XmlUtil.findElement(root, tagName, ATTR_NAME, newName);
   if (!(exists == null)) {
     if (!GuiUtils.askYesNo(
         "Name Already Exists",
         "Do you want to replace " + node.getAttribute("name") + " with" + "\"" + newName + "\"?"))
       return;
   }
   node.removeAttribute(ATTR_NAME);
   node.setAttribute(ATTR_NAME, newName);
   makeXmlTree();
   try {
     imageDefaults.writeWritable();
   } catch (Exception e) {
     logger.error("write error!", e);
   }
   imageDefaults.setWritableDocument(imageDefaultsDocument, imageDefaultsRoot);
 }
 private void doDeleteRequest(Node node) {
   if (node == null) {
     return;
   }
   Element ele = (Element) node;
   String tagName = ele.getTagName();
   if (tagName.equals("folder")) {
     if (!GuiUtils.askYesNo(
         "Verify Delete Folder",
         "Do you want to delete the folder "
             + "\""
             + ele.getAttribute("name")
             + "\"?"
             + "\nNOTE: All parameter sets it contains will be deleted.")) return;
     XmlUtil.removeChildren(ele);
   } else if (tagName.equals("default")) {
     if (!GuiUtils.askYesNo(
         "Verify Delete", "Do you want to delete " + "\"" + ele.getAttribute(ATTR_NAME) + "\"?"))
       return;
   } else {
     return;
   }
   removeNode(ele);
 }
Example #13
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;
  }
Example #14
0
 /**
  * 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, "") : "");
 }
Example #15
0
 /**
  * Method for encoding to xml the password. This simply obfuscates what is saved to disk
  *
  * @return The Password
  */
 public byte[] getTmp() {
   if (password == null) {
     return null;
   }
   return XmlUtil.encodeBase64(password.getBytes()).getBytes();
 }
Example #16
0
  /**
   * 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;
  }
 private List getFolders() {
   return XmlUtil.findChildren(imageDefaultsRoot, TAG_FOLDER);
 }
Example #18
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;
  }
  public Element saveParameterSet() {
    if (imageDefaults == null) {
      imageDefaults = getImageDefaults();
    }
    if (newCompName.length() == 0) {
      newComponentError("parameter set");
      return null;
    }
    Element newChild = imageDefaultsDocument.createElement(TAG_DEFAULT);
    newChild.setAttribute(ATTR_NAME, newCompName);

    if (datachoice == null) {
      datachoice = getDataChoice();
    }
    dataSource = getDataSource();
    if (!(dataSource.getClass().isInstance(new AddeImageParameterDataSource()))) {
      return newChild;
    }
    AddeImageParameterDataSource testDataSource = (AddeImageParameterDataSource) dataSource;
    List imageList = testDataSource.getDescriptors(datachoice, this.dataSelection);
    int numImages = imageList.size();
    List dateTimes = new ArrayList();
    DateTime thisDT = null;
    if (!(imageList == null)) {
      AddeImageDescriptor aid = null;
      for (int imageNo = 0; imageNo < numImages; imageNo++) {
        aid = (AddeImageDescriptor) (imageList.get(imageNo));
        thisDT = aid.getImageTime();
        if (!(dateTimes.contains(thisDT))) {
          if (thisDT != null) {
            dateTimes.add(thisDT);
          }
        }
      }
      String dateS = "";
      String timeS = "";
      if (!(dateTimes.isEmpty())) {
        thisDT = (DateTime) dateTimes.get(0);
        dateS = thisDT.dateString();
        timeS = thisDT.timeString();
        if (dateTimes.size() > 1) {
          for (int img = 1; img < dateTimes.size(); img++) {
            thisDT = (DateTime) dateTimes.get(img);
            String str = ',' + thisDT.dateString();
            String newString = new String(dateS + str);
            dateS = newString;
            str = ',' + thisDT.timeString();
            newString = new String(timeS + str);
            timeS = newString;
          }
        }
      }
      if (aid != null) {
        String displayUrl = testDataSource.getDisplaySource();
        ImageParameters ip = new ImageParameters(displayUrl);
        List props = ip.getProperties();
        List vals = ip.getValues();
        String server = ip.getServer();
        newChild.setAttribute(ATTR_SERVER, server);
        int num = props.size();
        if (num > 0) {
          String attr = "";
          String val = "";
          for (int i = 0; i < num; i++) {
            attr = (String) (props.get(i));
            if (attr.equals(ATTR_POS)) {
              val = new Integer(numImages - 1).toString();
            } else if (attr.equals(ATTR_DAY)) {
              val = dateS;
            } else if (attr.equals(ATTR_TIME)) {
              val = timeS;
            } else {
              val = (String) (vals.get(i));
            }
            newChild.setAttribute(attr, val);
          }
        }
      }
    }
    Element parent = xmlTree.getSelectedElement();
    if (parent == null) {
      parent = (Element) lastCat;
    }
    if (parent != null) {
      Element exists = XmlUtil.findElement(parent, "default", ATTR_NAME, newCompName);
      if (!(exists == null)) {
        JLabel label = new JLabel("Replace \"" + newCompName + "\"?");
        JPanel contents = GuiUtils.top(GuiUtils.inset(label, newCompName.length() + 12));
        if (!GuiUtils.showOkCancelDialog(null, "Parameter Set Exists", contents, null)) {
          return newChild;
        }
        parent.removeChild(exists);
      }
      parent.appendChild(newChild);
      makeXmlTree();
    }
    try {
      imageDefaults.writeWritable();
    } catch (Exception e) {
      logger.error("write error!", e);
    }
    imageDefaults.setWritableDocument(imageDefaultsDocument, imageDefaultsRoot);
    return newChild;
  }