Esempio n. 1
0
  /**
   * Get the {@link JComponent} that displays the given message.
   *
   * @param msg Message to display.
   * @param breakLines Whether or not {@literal "long"} lines should be broken up.
   * @return {@code JComponent} that displays {@code msg}.
   */
  private static JComponent getMessageComponent(String msg, boolean breakLines) {
    if (msg.startsWith("<html>")) {
      Component[] comps = GuiUtils.getHtmlComponent(msg, null, 500, 400);
      return (JScrollPane) comps[1];
    }

    int msgLength = msg.length();
    if (msgLength < 50) {
      return new JLabel(msg);
    }

    StringBuilder sb = new StringBuilder(msgLength * 2);
    if (breakLines) {
      for (String line : StringUtil.split(msg, "\n")) {
        line = StringUtil.breakText(line, "\n", 50);
        sb.append(line).append('\n');
      }
    } else {
      sb.append(msg).append('\n');
    }

    JTextArea textArea = new JTextArea(sb.toString());
    textArea.setFont(textArea.getFont().deriveFont(Font.BOLD));
    textArea.setBackground(new JPanel().getBackground());
    textArea.setEditable(false);
    JScrollPane textSp = GuiUtils.makeScrollPane(textArea, 400, 200);
    textSp.setPreferredSize(new Dimension(400, 200));
    return textSp;
  }
  /**
   * _more_
   *
   * @param visitInfo _more_
   * @param headerLines _more_
   * @return _more_
   * @throws IOException _more_
   */
  private VisitInfo preparePosFile(VisitInfo visitInfo, List<String> headerLines)
      throws IOException {

    /*
      PBO Station Position Time Series. Reference Frame : IGS05 (061102)
      Format Version: 1.1.0
      4-character ID: AB01
      Station name  : AtkaIslandAK2007
      First Epoch   : 20070518 120000
    */
    String referenceFrame = StringUtil.split(headerLines.get(0), ":", true, true).get(1);
    String formatVersion = StringUtil.split(headerLines.get(1), ":", true, true).get(1);
    String fourCharId = StringUtil.split(headerLines.get(2), ":", true, true).get(1);
    String processingCenter =
        StringUtil.split(getOriginalFilename(getFilename()), ".", true, true).get(1);
    List<String> toks = StringUtil.split(headerLines.get(3), ":", true, true);
    String stationName = (toks.size() > 1) ? toks.get(1) : fourCharId;
    setFileMetadata(
        new Object[] {
          fourCharId, stationName,
          referenceFrame, formatVersion,
          processingCenter
        });

    putProperty(PROP_FIELDS, getFieldsFileContents());

    return visitInfo;
  }
Esempio n. 3
0
  /**
   * _more_
   *
   * @return _more_
   */
  public Connection getConnection() {
    if (connection != null) {
      return connection;
    }
    String url = getFilename();
    if ((dataSource.getUserName() == null) || (dataSource.getUserName().trim().length() == 0)) {
      if (url.indexOf("?") >= 0) {
        int idx = url.indexOf("?");
        List<String> args =
            (List<String>) StringUtil.split(url.substring(idx + 1), "&", true, true);
        url = url.substring(0, idx);
        for (String tok : args) {
          List<String> subtoks = (List<String>) StringUtil.split(tok, "=", true, true);
          if (subtoks.size() != 2) {
            continue;
          }
          String name = subtoks.get(0);
          String value = subtoks.get(1);
          if (name.equals("user")) {
            dataSource.setUserName(value);
          } else if (name.equals("password")) {
            dataSource.setPassword(value);
          }
        }
      }
    }

    int cnt = 0;
    while (true) {
      String userName = dataSource.getUserName();
      String password = dataSource.getPassword();
      if (userName == null) {
        userName = "";
      }
      if (password == null) {
        password = "";
      }
      try {
        connection = DriverManager.getConnection(url, userName, password);
        return connection;
      } catch (SQLException sqe) {
        if ((sqe.toString().indexOf("role \"" + userName + "\" does not exist") >= 0)
            || (sqe.toString().indexOf("user name specified") >= 0)) {
          String label;
          if (cnt == 0) {
            label =
                "<html>The database requires a login.<br>Please enter a user name and password:</html>";
          } else {
            label = "<html>Incorrect username/password. Please try again.</html>";
          }
          if (!dataSource.showPasswordDialog("Database Login", label)) {
            return null;
          }
          cnt++;
          continue;
        }
        throw new BadDataException("Unable to connect to database", sqe);
      }
    }
  }
Esempio n. 4
0
  /**
   * Find the {@link ucar.unidata.idv.ui.ParamInfo} for the given name
   *
   * @param paramName The name to look for
   * @return The {@link ucar.unidata.idv.ui.ParamInfo} associated with the name
   */
  private ParamInfo getParamInfo(String paramName) {
    if (paramName == null) {
      return null;
    }
    ParamInfo info = (ParamInfo) StringUtil.findMatch(paramName, paramInfos, null);
    if (info == null) {
      info = (ParamInfo) StringUtil.findMatch(paramName.toLowerCase(), paramInfos, null);
    }

    if (info == null) {
      String canonicalName = DataAlias.aliasToCanonical(paramName);
      if (canonicalName != null) {
        info = (ParamInfo) StringUtil.findMatch(canonicalName.toLowerCase(), paramInfos, null);
      }
    }
    return info;
  }
Esempio n. 5
0
  /**
   * _more_
   *
   * @param symbols _more_
   * @param listener _more_
   * @param smm _more_
   * @return _more_
   */
  public static List makeStationModelMenuItems(
      List symbols, final ObjectListener listener, StationModelManager smm) {
    List items = new ArrayList();
    List subMenus = new ArrayList();
    Hashtable categories = new Hashtable();
    for (int i = 0; i < symbols.size(); i++) {
      StationModel sm = (StationModel) symbols.get(i);
      boolean isUsers = smm.isUsers(sm);
      String name = sm.getName();
      if (name.equals("")) continue;
      List toks = StringUtil.split(name, ">", true, true);
      if (toks.size() > 0) {
        name = (String) toks.get(toks.size() - 1);
      }
      JMenuItem item = new JMenuItem(GuiUtils.getLocalName(name, isUsers));
      item.addActionListener(
          new ObjectListener(sm) {
            public void actionPerformed(ActionEvent ae) {
              listener.setObject(this.theObject);
              listener.actionPerformed(ae);
            }
          });

      toks.remove(toks.size() - 1);
      if (toks.size() == 0) {
        items.add(item);
        continue;
      }
      JMenu categoryMenu = null;
      String catSoFar = "";
      String menuCategory = "";
      for (int catIdx = 0; catIdx < toks.size(); catIdx++) {
        String subCat = (String) toks.get(catIdx);
        catSoFar = catSoFar + "/" + subCat;
        JMenu m = (JMenu) categories.get(catSoFar);
        if (m == null) {
          m = new JMenu(subCat);
          menuCategory = catSoFar;
          categories.put(catSoFar, m);
          if (categoryMenu != null) {
            categoryMenu.add(m, 0);
          } else {
            subMenus.add(m);
          }
        }
        categoryMenu = m;
      }
      if (categoryMenu == null) {
        categoryMenu = new JMenu("");
        categories.put(toks.toString(), categoryMenu);
        subMenus.add(categoryMenu);
        menuCategory = toks.toString();
      }
      categoryMenu.add(item);
    }
    items.addAll(subMenus);
    return items;
  }
Esempio n. 6
0
 public static String[] getRoots() {
   String rootString = StringUtil.replace(roots, "\n", ",");
   String[] root2 = rootString.split(",");
   String[] result = new String[root2.length / 2];
   for (int i = 0; i < root2.length; i += 2) {
     result[i / 2] = root2[i];
   }
   return result;
 }
Esempio n. 7
0
 /**
  * Get the label to show the user what I am in the properties
  *
  * @return label
  */
 public String getLabel() {
   String className = getClass().getName();
   int idx = className.lastIndexOf(".");
   if (idx >= 0) {
     className = className.substring(idx + 1);
   }
   if (className.endsWith("Symbol")) {
     className = StringUtil.replace(className, "Symbol", " Symbol");
   }
   return className;
 }
Esempio n. 8
0
  public static PathMatcher readRoots() {
    PathMatcher pathMatcher = new PathMatcher();
    String rootString = StringUtil.replace(roots, "\n", ",");
    String[] roots = rootString.split(",");
    for (int i = 0; i < roots.length; i += 2) {
      if (showRoots) System.out.printf("  %-40s %-40s%n", roots[i], roots[i + 1]);
      pathMatcher.put(roots[i], roots[i + 1]);
    }

    return pathMatcher;
  }
Esempio n. 9
0
 /**
  * Print out the command line usage message and exit
  *
  * @param err The usage message
  */
 @Override
 public void usage(String err) {
   List<String> chunks = StringUtil.split(err, ":");
   if (chunks.size() == 2) {
     err = chunks.get(0) + ": " + chunks.get(1) + '\n';
   }
   String msg = USAGE_MESSAGE;
   msg = msg + '\n' + getUsageMessage();
   userErrorMessage(err + '\n' + msg, false);
   ((McIDASV) getIdv()).exit(1);
 }
Esempio n. 10
0
 /** Set the label text. */
 private void setLabelText() {
   if (!active) {
     return;
   }
   StringBuffer buf = new StringBuffer();
   buf.append(" ");
   buf.append(getRangeName());
   buf.append(": ");
   buf.append(StringUtil.padLeft(rangeReadout.getNumericString(), 6));
   buf.append(" ");
   buf.append(getBearingName());
   buf.append(": ");
   buf.append(StringUtil.padLeft(bearingReadout.getNumericString(), 6));
   String text = buf.toString();
   valueDisplay.setText(text);
   if (myOwnLabel) {
     FontMetrics fm = valueDisplay.getFontMetrics(valueDisplay.getFont());
     valueDisplay.setPreferredSize(new Dimension(fm.stringWidth(text), fm.getHeight()));
   }
 }
Esempio n. 11
0
  /**
   * Does the pattern match the given value
   *
   * @param value value to check
   * @return Pattern matches value
   */
  public boolean match(Data value) throws Exception {
    if (value instanceof Real && isNumericRange()) {
      Real[] range = getNumericRange();
      Real r = (Real) value;
      if (r.__ge__(range[0]) == 0) return false;
      if (r.__le__(range[1]) == 0) return false;
      return true;
    }

    String stringValue = value.toString();
    return StringUtil.stringMatch(stringValue, pattern, true, true);
  }
Esempio n. 12
0
 /**
  * See if a String is a match for a pattern
  *
  * @param source source string
  * @param pattern regular expression pattern
  * @return true if there is a match
  * @deprecated use ucar.unidata.util.StringUtil.stringMatch(String, String) instead
  */
 public static boolean matchRegexp(String source, String pattern)
       //        throws MalformedPatternException
     {
   return StringUtil.stringMatch(source, pattern);
   /*
   if (matcher == null) {
       matcher  = new Perl5Matcher();
       compiler = new Perl5Compiler();
   }
   return matcher.contains(source, compiler.compile(pattern));
   */
 }
Esempio n. 13
0
 /**
  * Return a String representation of this
  *
  * @return a String representation of this
  */
 public String toString() {
   StringBuilder builder = new StringBuilder();
   builder.append(StringUtil.padRight((stid.trim() + std2.trim()), 8));
   builder.append(" ");
   builder.append(Format.i(stnm, 6));
   builder.append(" ");
   builder.append(StringUtil.padRight(sdesc, 32));
   builder.append(" ");
   builder.append(StringUtil.padLeft(stat.trim(), 2));
   builder.append(" ");
   builder.append(StringUtil.padLeft(coun.trim(), 2));
   builder.append(" ");
   builder.append(Format.i(slat, 5));
   builder.append(" ");
   builder.append(Format.i(slon, 6));
   builder.append(" ");
   builder.append(Format.i(selv, 5));
   builder.append(" ");
   builder.append(Format.i(spri, 2));
   builder.append(" ");
   builder.append(StringUtil.padLeft(swfo.trim(), 3));
   return builder.toString();
 }
Esempio n. 14
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;
 }
Esempio n. 15
0
 /**
  * Check to see if this object is applicable to the given DataCategory argument. The definition of
  * applicability is that this data category is hierarchically a "base-class" hierachy of the given
  * argument. There is a slight twist though: A data category can have a sub-component that
  * represents a regular expression, i.e., :
  *
  * <pre>
  *  "*" represents 0 or more sub-categories,
  *  "+" represents one or more sub-categories
  *  "." represents one sub-category
  *  </pre>
  *
  * Here are some examples:
  *
  * <table>
  *  <tr><td>This</td><td>Argument</td><td> applicableTo</td></tr>
  *  <tr><td>"FOO-BAR"</td><td>"FOO-BAR"</td><td>true</td></tr>
  *  <tr><td>"FOO-BAR-ZOO"</td><td>"FOO-BAR"</td><td>false</td></tr>
  *  <tr><td>"FOO-BAR-ZOO"</td><td>"FOO-BAR"</td><td>false</td></tr>
  *  <tr><td>"FOO-BAR-*"</td><td>"FOO-BAR"</td><td>true</td></tr>
  *  <tr><td>"FOO-BAR-+"</td><td>"FOO-BAR"</td><td>false</td></tr>
  *  <tr><td>"FOO-."</td><td>"FOO-BAR"</td><td>true</td></tr>
  *  <tr><td>"FOO-.-*"</td><td>"FOO-BAR"</td><td>true</td></tr>
  *  <tr><td>"*"</td><td>"FOO-BAR"</td><td>true</td></tr>
  *  <tr><td>".-.-*"</td><td>"FOO-BAR"</td><td>true</td></tr>
  *  </table>
  *
  * @param d DataCategory to check
  * @return true if applicable to <code>d</code>
  */
 public boolean applicableTo(DataCategory d) {
   String myPattern = getPattern();
   String input = d.getFullName(DIVIDER, DIVIDER);
   if (input.equals("-*-")) {
     return true;
   }
   try {
     // boolean results = matchRegexp(input, myPattern);
     boolean results = StringUtil.stringMatch(input, myPattern);
     return results;
   } catch (Exception exc) {
     throw new IllegalArgumentException("DataCategory error:" + exc);
   }
 }
Esempio n. 16
0
  private InvDataset processLocation(
      String location, ucar.nc2.util.CancelTask task, Result result) {
    location = location.trim();
    location = ucar.unidata.util.StringUtil.replace(location, '\\', "/");

    if (location.startsWith(SCHEME)) location = location.substring(8);

    if (location.startsWith("resolve:")) {
      location = location.substring(8);
      return openResolver(location, task, result);
    }

    if (!location.startsWith("http:") && !location.startsWith("file:")) // LOOK whats this for??
    location = "http:" + location;

    InvCatalog catalog;
    InvDataset invDataset;
    String datasetId;

    int pos = location.indexOf('#');
    if (pos < 0) {
      result.fatalError = true;
      result.errLog.format("Must have the form catalog.xml#datasetId%n");
      return null;
    }

    InvCatalogFactory catFactory = new InvCatalogFactory("", false);
    String catalogLocation = location.substring(0, pos);
    catalog = catFactory.readXML(catalogLocation);
    StringBuilder buff = new StringBuilder();
    if (!catalog.check(buff)) {
      result.errLog.format(
          "Invalid catalog from Resolver <%s>%n%s%n", catalogLocation, buff.toString());
      result.fatalError = true;
      return null;
    }

    datasetId = location.substring(pos + 1);
    invDataset = catalog.findDatasetByID(datasetId);
    if (invDataset == null) {
      result.fatalError = true;
      result.errLog.format("Could not find dataset %s in %s %n", datasetId, catalogLocation);
      return null;
    }

    return invDataset;
  }
Esempio n. 17
0
  /** Handle unknown data set error */
  protected void handleUnknownDataSetError() {
    // Don't do this for now
    //        List groups =  readGroups();
    List groups = null;
    if (groups == null) {
      LogUtil.userErrorMessage("Dataset not found on server: " + getServer());

    } else {
      LogUtil.userErrorMessage(
          "Dataset not found on server: "
              + getServer()
              + "\nPossible data sets:\n"
              + "   "
              + StringUtil.join("\n   ", groups));
    }
    setState(STATE_UNCONNECTED);
  }
Esempio n. 18
0
 /**
  * Read the groups from the public.srv file on the server
  *
  * @return List of groups
  */
 protected List readGroups() {
   List groups = new ArrayList();
   try {
     String dataType = getDataType();
     String type = ((dataType.length() > 0) ? "TYPE=" + dataType : "TYPE=NOTYPE");
     StringBuffer buff = getUrl(REQ_TEXT);
     appendKeyValue(buff, PROP_FILE, FILE_PUBLICSRV);
     List lines = readTextLines(buff.toString());
     //            System.err.println ("lines:" + StringUtil.join("\n",lines));
     if (lines == null) {
       return null;
     }
     Hashtable seen = new Hashtable();
     for (int i = 0; i < lines.size(); i++) {
       String line = lines.get(i).toString();
       if (line.indexOf(type) < 0) {
         continue;
       }
       List toks = StringUtil.split(line, ",", true, true);
       if (toks.size() == 0) {
         continue;
       }
       String tok = (String) toks.get(0);
       int idx = tok.indexOf("=");
       if (idx < 0) {
         continue;
       }
       if (!tok.substring(0, idx).trim().equals("N1")) {
         continue;
       }
       String group = tok.substring(idx + 1).trim();
       if (seen.get(group) != null) {
         continue;
       }
       seen.put(group, group);
       groups.add(group);
     }
   } catch (Exception e) {
     return null;
   }
   return groups;
 }
Esempio n. 19
0
 /**
  * Read the xml format
  *
  * @param name filename or url
  * @param iStream input stream
  * @return List of point sets
  */
 private List doReadSSF(String name, InputStream iStream) {
   List sets = new ArrayList();
   try {
     if (iStream == null) {
       iStream = IOUtil.getInputStream(name);
     }
     List toks = StringUtil.split(IOUtil.readContents(iStream), " ", true, true);
     int xcnt = 0;
     int cnt = 0;
     while (cnt < toks.size()) {
       int size = Integer.parseInt((String) toks.get(cnt));
       cnt += 5;
       double[] points = new double[size];
       for (int i = 0; i < size; i++) {
         points[i] = Double.parseDouble((String) toks.get(cnt));
         cnt++;
       }
       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];
       }
       xcnt++;
       sets.add(
           new MapSet(
               coordMathType,
               part,
               points.length / 2,
               (CoordinateSystem) null,
               (Unit[]) null,
               (ErrorEstimate[]) null,
               false /* no copy */));
     }
   } catch (Exception exc) {
     exc.printStackTrace();
   }
   return sets;
 }
Esempio n. 20
0
 /** The static initialization */
 private static void doInit() {
   String csv =
       ucar.unidata.util.IOUtil.readContents(csvFileName, CoordinateAxisName.class, (String) null);
   if (csv == null) {
     System.err.println("Failed to read:" + csvFileName);
     return;
   }
   List lines = StringUtil.parseCsv(csv, true);
   for (int i = 0; i < lines.size(); i++) {
     List line = (List) lines.get(i);
     if (line.size() < 9) {
       System.err.println("csv/coordinate_axis_name.csv: line #" + i + " " + line);
       continue;
     }
     try {
       new CoordinateAxisName(line);
     } catch (Exception exc) {
       System.err.println("Error creating CoordinateAxisName " + exc);
       exc.printStackTrace();
       return;
     }
   }
 }
Esempio n. 21
0
  /**
   * Extract any command-line properties and their corresponding values.
   *
   * <p>May print out usage information if a badly formatted {@literal "property=value"} pair is
   * encountered, or when an unknown argument is found (depending on value of the {@code
   * ignoreUnknown} parameter).
   *
   * <p><b>NOTE:</b> {@code null} is not a permitted value for any parameter.
   *
   * @param ignoreUnknown Whether or not to handle unknown arguments.
   * @param fromStartupManager Whether or not this call originated from {@code startupmanager.jar}.
   * @param args Array containing command-line arguments.
   * @param defaults Default parameter values.
   * @return Command-line arguments as a collection of property identifiers and values.
   */
  public static Properties getArgs(
      final boolean ignoreUnknown,
      final boolean fromStartupManager,
      final String[] args,
      final Properties defaults) {
    Properties props = new Properties(defaults);
    for (int i = 0; i < args.length; i++) {

      // handle property definitions
      if (args[i].startsWith("-D")) {
        List<String> l = StringUtil.split(args[i].substring(2), "=");
        if (l.size() == 2) {
          props.setProperty(l.get(0), l.get(1));
        } else {
          usage("Invalid property:" + args[i]);
        }
      }

      // handle userpath changes
      else if (ARG_USERPATH.equals(args[i]) && (i + 1) < args.length) {
        props.setProperty("userpath", args[++i]);
      }

      // handle help requests
      else if (ARG_HELP.equals(args[i]) && (fromStartupManager)) {
        System.err.println(USAGE_MESSAGE);
        System.err.println(getUsageMessage());
        System.exit(1);
      }

      // bail out for unknown args, unless we don't care!
      else if (!ignoreUnknown) {
        usage("Unknown argument: " + args[i]);
      }
    }
    return props;
  }
Esempio n. 22
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) {
          }
        }
      }
    }
  }
Esempio n. 23
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;
  }
Esempio n. 24
0
 public static String getFileURL(String filename) {
   filename = filename.replace('\\', '/');
   filename = StringUtil.replace(filename, ' ', "+");
   return "file:" + filename;
 }
Esempio n. 25
0
  /**
   * Currently we're only handling the {@code -forceaqua} flag so we can mitigate some overlay
   * issues we've been seeing on OS X Leopard.
   *
   * @param arg The current argument we're examining.
   * @param args The actual array of arguments.
   * @param idx The index of {@code arg} within {@code args}.
   * @return The idx of the last value in the args array we look at. i.e., if the flag arg does not
   *     require any further values in the args array then don't increment idx. If arg requires one
   *     more value then increment idx by one. etc.
   * @throws Exception Throw bad things off to something that can handle 'em!
   */
  protected int parseArg(String arg, String[] args, int idx) throws Exception {

    if ("-forceaqua".equals(arg)) {
      // unfortunately we can't simply set the look and feel here. If I
      // were to do so, the loadLookAndFeel in the IdvUIManager would
      // eventually get loaded and then set the look and feel to whatever
      // the preferences dictate.
      // instead I use the boolean toggle to signal to McV's
      // UIManager.loadLookAndFeel that it should simply ignore the user's
      // preference is and load the Aqua L&F from there.
      McIDASV.useAquaLookAndFeel = true;
    } else if (ARG_HELP.equals(arg)) {
      String msg = USAGE_MESSAGE + "\n" + getUsageMessage();
      if (McIDASV.isWindows() && !GraphicsEnvironment.isHeadless()) {
        userMessage(msg, false);
      } else {
        helpLogger.info(System.getProperty("line.separator") + msg);
      }
      ((McIDASV) getIdv()).exit(1);
    } else if (checkArg(arg, "-script", args, idx, 1) || checkArg(arg, "-pyfile", args, idx, 1)) {
      String scriptArg = args[idx++];
      jythonScript = scriptArg;
      scriptingFiles.add(scriptArg);
      if (!getIslInteractive()) {
        setIsOffScreen(true);
      }
    } else if ("-welcomewindow".equals(arg)) {
      // do nothing

    } else if (checkArg(arg, "-autoquit", args, idx, 1)) {
      // do nothing besides skip the next parameter
      // (which should be the autoquit delay)
      idx++;
    } else if ("-console".equals(arg)) {
      System.err.println("*** WARNING: console flag is likely to go away soon!");
    } else if (ARG_JYTHONARGS.equals(arg)) {
      if (scriptingFiles.isEmpty()) {
        System.err.println(
            "*** WARNING: Jython script arguments will be ignored unless you provide a Jython script to execute!");
      } else {
        jythonArguments.addAll(extractJythonArgs(idx, args));

        // jump to end of args to halt further idv processing.
        return args.length;
      }
    } else if (checkArg(arg, ARG_LOGPATH, args, idx, 1)) {
      String argValue = args[idx++];
      persistentCommandLineArgs.add(ARG_LOGPATH);
      persistentCommandLineArgs.add(argValue);
    } else if (checkArg(arg, ARG_BUNDLE, args, idx, 1)) {
      String argValue = args[idx++];
      String[] results = FileOption.parseFormat(argValue);
      if (FileOption.booleanFromFormat(results[0])) {
        argXidvFiles.add(results[1]);
      }
      System.err.println("result[0]: " + FileOption.booleanFromFormat(results[0]));
      System.err.println("result[1]: '" + results[1] + '\'');
    } else if (checkArg(arg, ARG_DOACTION, args, idx, 1)) {
      startupAction = args[idx++];
    } else {
      if (ARG_ISLINTERACTIVE.equals(arg)
          || ARG_B64ISL.equals(arg)
          || ARG_ISLFILE.equals(arg)
          || isIslFile(arg)) {
        System.err.println("*** WARNING: ISL is being deprecated!");
      } else if (arg.startsWith("-D")) {
        List<String> l = StringUtil.split(arg.substring(2), "=");
        if (l.size() == 2) {
          System.setProperty(l.get(0), l.get(1));
        }
      }
      return super.parseArg(arg, args, idx);
    }
    return idx;
  }
Esempio n. 26
0
  /**
   * _more_
   *
   * @return _more_
   * @throws Exception _more_
   */
  private boolean initConnection() throws Exception {
    if (getConnection() == null) {
      return false;
    }
    // jdbc:postgresql://eol-rt-data.guest.ucar.edu/real-time
    //        evaluate("CREATE RULE update AS ON UPDATE TO global_attributes DO NOTIFY current;");

    Statement stmt;
    ResultSet results;
    SqlUtil.Iterator iter;
    EolDbTrackInfo trackInfo = new EolDbTrackInfo(this, "TRACK");
    Hashtable cats = new Hashtable();
    try {
      stmt = select("*", TABLE_CATEGORIES);
      iter = SqlUtil.getIterator(stmt);
      while ((results = iter.getNext()) != null) {
        cats.put(results.getString(COL_VARIABLE), results.getString(COL_CATEGORY));
      }
    } catch (Exception exc) {
      //                exc.printStackTrace();
    }

    missingMap = new Hashtable();
    stmt = select("*", TABLE_GLOBALS);
    globals = new Hashtable();
    boolean gotCoords = false;
    description = "<b>Globals</b><br>";
    iter = SqlUtil.getIterator(stmt);
    while ((results = iter.getNext()) != null) {
      String globalName = results.getString(1).trim();
      String globalValue = results.getString(2).trim();
      globals.put(globalName, globalValue);
      description =
          description
              + "<tr valign=\"top\"><td>"
              + globalName
              + "</td><td>"
              + globalValue
              + "</td></tr>";

      //            System.err.println(globalName +"=" + globalValue);

      if (globalName.equals(GLOBAL_STARTTIME)) {
        startTime = new DateTime(DateUtil.parse(globalValue));
      } else if (globalName.equals(GLOBAL_ENDTIME)) {
        endTime = new DateTime(DateUtil.parse(globalValue));
      } else if (globalName.equals(GLOBAL_COORDINATES)) {
        List toks = StringUtil.split(globalValue, " ", true, true);
        if (toks.size() != 4) {
          throw new BadDataException("Incorrect coordinates value in database:" + globalValue);
        }
        gotCoords = true;
        System.err.println("coords:" + toks);
        trackInfo.setCoordinateVars(
            (String) toks.get(0), (String) toks.get(1), (String) toks.get(2), (String) toks.get(3));

        trackInfo.setCoordinateVars("GGLON", "GGLAT", "GGALT", "datetime");
      }
    }
    description = description + "</table>";

    if (!gotCoords) {
      throw new BadDataException("No coordinates found in database");
    }

    this.name = (String) globals.get(GLOBAL_PROJECTNAME);
    String flight = (String) globals.get(GLOBAL_FLIGHTNUMBER);
    if ((this.name != null) && (flight != null) && (flight.length() != 0)) {
      this.name += " - " + flight;
    }

    stmt = select("*", TABLE_VARIABLE_LIST);
    iter = SqlUtil.getIterator(stmt);
    while ((results = iter.getNext()) != null) {
      String name = results.getString(COL_NAME).trim();
      String desc = results.getString(COL_LONG_NAME).trim();
      Unit unit = DataUtil.parseUnit(results.getString(COL_UNITS).trim());
      String cat = (String) cats.get(name);
      double missing = results.getDouble(COL_MISSING_VALUE);
      VarInfo variable = new VarInfo(name, desc, cat, unit, missing);
      trackInfo.addVariable(variable);
    }
    addTrackInfo(trackInfo);
    return true;
  }
  /**
   * Gets called when first reading the file. Parses the header
   *
   * @param visitInfo visit info
   * @return the visit info
   * @throws Exception _more_
   */
  @Override
  public VisitInfo prepareToVisit(VisitInfo visitInfo) throws Exception {
    putProperty(PROP_DELIMITER, isPos ? " " : ",");
    putProperty(PROP_SKIPLINES, isPos ? "37" : "9");

    super.prepareToVisit(visitInfo);
    List<String> headerLines = getHeaderLines();
    if (headerLines.size() != getSkipLines(visitInfo)) {
      throw new IllegalArgumentException("Bad number of header lines:" + headerLines.size());
    }

    if (isPos) {
      return preparePosFile(visitInfo, headerLines);
    }

    // PBO Station Position Time Series. Reference Frame : IGS08
    String referenceFrame = StringUtil.split(headerLines.get(0), ":", true, true).get(1);

    // Format Version,1.0.4
    String formatVersion = StringUtil.split(headerLines.get(1), ",", true, true).get(1);

    // 4-character ID,P101
    String fourCharId = StringUtil.split(headerLines.get(2), ",", true, true).get(1);

    // Station name,RandolphLLUT2005
    String processingCenter =
        StringUtil.split(getOriginalFilename(getFilename()), ".", true, true).get(1);
    List<String> toks = StringUtil.split(headerLines.get(3), ":", true, true);
    String stationName = (toks.size() > 1) ? toks.get(1) : fourCharId;

    // LOOK: this needs to be in the same order as the unavcotypes.xml defines in the point plugin
    setFileMetadata(
        new Object[] {
          fourCharId, stationName,
          referenceFrame, formatVersion,
          processingCenter
        });

    // Reference position, 41.6922736024 North Latitude, -111.2360162488 East Longitude, 2016.12225
    // meters elevation,
    String positionLine = headerLines.get(7);
    positionLine = positionLine.replaceAll(",", " ");
    List<String> positionToks = StringUtil.split(positionLine, " ", true, true);

    // TODO: Check the 'North' latitude part. I'm assuming this is always degrees north and east
    double lat = Double.parseDouble(positionToks.get(2));
    double lon = Double.parseDouble(positionToks.get(5));
    double elevation = Double.parseDouble(positionToks.get(8));
    setLocation(lat, lon, elevation);

    putFields(
        new String[] {
          makeField(FIELD_SITE_ID, attrType(TYPE_STRING), attrValue(fourCharId.trim())),
          makeField(FIELD_LATITUDE, attrValue(lat)),
          makeField(FIELD_LONGITUDE, attrValue(lon)),
          makeField(FIELD_ELEVATION, attrValue(elevation)),
          makeField(FIELD_DATE, attrFormat("yyyy-MM-dd")),
          makeField(FIELD_NORTH, attrUnit("mm"), attrChartable()),
          makeField(FIELD_EAST, attrUnit("mm"), attrChartable()),
          makeField(FIELD_VERTICAL, attrUnit("mm"), attrChartable()),
          makeField(FIELD_NORTH_STD_DEVIATION, attrUnit("mm"), attrChartable()),
          makeField(FIELD_EAST_STD_DEVIATION, attrUnit("mm"), attrChartable()),
          makeField(FIELD_VERTICAL_STD_DEVIATION, attrUnit("mm"), attrChartable()),
          makeField(FIELD_QUALITY, attrType("string"), attrChartable()),
          //            makeField("skip", "")
        });
    ;

    return visitInfo;
  }
  public static void main(String args[]) throws Exception {
    long start = System.currentTimeMillis();
    Map<String, ucar.unidata.geoloc.Station> staHash =
        new HashMap<String, ucar.unidata.geoloc.Station>();

    String location = "R:/testdata/sounding/netcdf/Upperair_20070401_0000.nc";
    NetcdfDataset ncfile = NetcdfDataset.openDataset(location);
    ncfile.sendIospMessage(NetcdfFile.IOSP_MESSAGE_ADD_RECORD_STRUCTURE);

    // look through record varibles, for those that have "manLevel" dimension
    // make a StructureData object for those
    StructureMembers sm = new StructureMembers("manLevel");
    Dimension manDim = ncfile.findDimension("manLevel");
    Structure record = (Structure) ncfile.findVariable("record");
    List<Variable> allList = record.getVariables();
    List<VariableSimpleIF> varList = new ArrayList<VariableSimpleIF>();
    for (Variable v : allList) {
      if ((v.getRank() == 1) && v.getDimension(0).equals(manDim)) {
        // public VariableDS(NetcdfDataset ds, Group group, Structure parentStructure, String
        // shortName, DataType dataType,
        // String dims, String units, String desc) {
        varList.add(
            new VariableDS(
                ncfile,
                null,
                null,
                v.getShortName(),
                v.getDataType(),
                "",
                v.getUnitsString(),
                v.getDescription()));
        // (String name, String desc, String units, DataType dtype, int []shape)
        sm.addMember(
            v.getShortName(),
            v.getDescription(),
            v.getUnitsString(),
            v.getDataType(),
            new int[0]); // scalar
      }
    }

    ArrayStructureMA manAS = new ArrayStructureMA(sm, new int[] {manDim.getLength()});

    // need the date units
    Variable time = ncfile.findVariable("synTime");
    String timeUnits = ncfile.findAttValueIgnoreCase(time, "units", null);
    timeUnits = StringUtil.remove(timeUnits, '('); // crappy fsl'ism
    timeUnits = StringUtil.remove(timeUnits, ')');
    DateUnit timeUnit = new DateUnit(timeUnits);

    // extract stations
    int nrecs = 0;
    StructureDataIterator iter = record.getStructureIterator();
    while (iter.hasNext()) {
      StructureData sdata = iter.next();
      String name = sdata.getScalarString("staName");
      ucar.unidata.geoloc.Station s = staHash.get(name);
      if (s == null) {
        float lat = sdata.convertScalarFloat("staLat");
        float lon = sdata.convertScalarFloat("staLon");
        float elev = sdata.convertScalarFloat("staElev");
        s = new StationImpl(name, "", lat, lon, elev);
        staHash.put(name, s);
      }
      nrecs++;
    }
    List<ucar.unidata.geoloc.Station> stnList =
        Arrays.asList(staHash.values().toArray(new ucar.unidata.geoloc.Station[staHash.size()]));
    Collections.sort(stnList);

    // create the writer
    WriterProfileObsDataset writer =
        new WriterProfileObsDataset(location + ".out", "rewrite " + location);
    writer.writeHeader(stnList, varList, nrecs, "prMan");

    // extract records
    iter = record.getStructureIterator();
    while (iter.hasNext()) {
      StructureData sdata = iter.next();
      String name = sdata.getScalarString("staName");
      double timeValue = sdata.convertScalarDouble("synTime");
      Date date = timeUnit.makeDate(timeValue);

      // transfer to the ArrayStructure
      List<String> names = sm.getMemberNames();
      for (String mname : names) {
        manAS.setMemberArray(mname, sdata.getArray(mname));
      }

      // each level is weritten as a seperate structure
      int numMand = sdata.getScalarInt("numMand");
      if (numMand >= manDim.getLength()) continue;

      for (int i = 0; i < numMand; i++) {
        StructureData useData = manAS.getStructureData(i);
        writer.writeRecord(name, date, useData);
      }
    }

    writer.finish();

    long took = System.currentTimeMillis() - start;
    System.out.println("That took = " + took);
  }
Esempio n. 29
0
  /**
   * _more_
   *
   * @param nx _more_
   * @param ny _more_
   * @param gv _more_
   * @param imsorc _more_
   * @param imtype _more_
   * @return _more_
   */
  float[][] im_gvtota(int nx, int ny, float[][] gv, int imsorc, int imtype)

        /**
         * im_gvtota
         *
         * <p>This subroutine converts GVAR counts to actual temperatures based on the current image
         * set in IM_SIMG.
         *
         * <p>im_gvtota ( int *nvals, unsigned int *gv, float *ta, int *iret )
         *
         * <p>Input parameters: *nvals int Number of values to convert *gv int Array of GVAR count
         * values
         *
         * <p>Output parameters: *ta float Array of actual temperatures *iret int Return value = -1
         * - could not open table = -2 - could not find match
         *
         * <p>Log: D.W.Plummer/NCEP 02/03 D.W.Plummer/NCEP 06/03 Add coeff G for 2nd order poly conv
         * T. Piper/SAIC 07/06 Added tmpdbl to eliminate warning
         */
      {
    int ii, ip, chan, found, ier;
    double Rad, Teff, tmpdbl;
    float[][] ta = new float[nx][ny];
    int iret;
    String fp = "/ucar/unidata/data/storm/ImgCoeffs.tbl";

    iret = 0;

    for (ii = 0; ii < nx; ii++) {
      for (int jj = 0; jj < ny; jj++) {
        ta[ii][jj] = Float.NaN;
      }
    }

    /*
     * Read in coefficient table if necessary.
     */
    String s = null;
    try {
      s = IOUtil.readContents(fp);
    } catch (Exception re) {
    }

    int i = 0;
    StormAODTInfo.ImgCoeffs[] ImageConvInfo = new StormAODTInfo.ImgCoeffs[50];
    for (String line : StringUtil.split(s, "\n", true, true)) {
      if (line.startsWith("!")) {
        continue;
      }
      List<String> stoks = StringUtil.split(line, " ", true, true);

      ImageConvInfo[i] = new StormAODTInfo.ImgCoeffs(stoks);
      ;
      i++;
    }
    int nImgRecs = i;
    found = 0;
    ii = 0;
    while ((ii < nImgRecs) && (found == 0)) {

      tmpdbl = (double) (ImageConvInfo[ii].chan - 1) * (ImageConvInfo[ii].chan - 1);
      chan = G_NINT(tmpdbl);

      if ((imsorc == ImageConvInfo[ii].sat_num) && (imtype == chan)) {
        found = 1;
      } else {
        ii++;
      }
    }

    if (found == 0) {
      iret = -2;
      return null;
    } else {

      ip = ii;
      for (ii = 0; ii < nx; ii++) {
        for (int jj = 0; jj < ny; jj++) {

          /*
           * Convert GVAR count (gv) to Scene Radiance
           */
          Rad =
              ((double) gv[ii][jj] - ImageConvInfo[ip].scal_b)
                  /
                  /* ------------------------------------- */
                  ImageConvInfo[ip].scal_m;

          Rad = Math.max(Rad, 0.0);

          /*
           * Convert Scene Radiance to Effective Temperature
           */
          Teff =
              (c2 * ImageConvInfo[ip].conv_n)
                  /
                  /*
                   * --------------------------------------------------
                   * -----
                   */
                  (Math.log(1.0 + (c1 * Math.pow(ImageConvInfo[ip].conv_n, 3.0)) / Rad));

          /*
           * Convert Effective Temperature to Temperature
           */
          ta[ii][jj] =
              (float)
                  (ImageConvInfo[ip].conv_a
                      + ImageConvInfo[ip].conv_b * Teff
                      + ImageConvInfo[ip].conv_g * Teff * Teff);
        }
      }
    }

    return ta;
  }