PageRenderTime 51ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/cdm/src/main/java/ucar/nc2/iosp/gempak/GempakParameterTable.java

https://github.com/blazetopher/THREDDS
Java | 353 lines | 202 code | 35 blank | 116 comment | 47 complexity | 3e8b5c7374608efff92338cee1b4cd18 MD5 | raw file
  1. /*
  2. * $Id: IDV-Style.xjs,v 1.3 2007/02/16 19:18:30 dmurray Exp $
  3. *
  4. * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata
  5. *
  6. * Portions of this software were developed by the Unidata Program at the
  7. * University Corporation for Atmospheric Research.
  8. *
  9. * Access and use of this software shall impose the following obligations
  10. * and understandings on the user. The user is granted the right, without
  11. * any fee or cost, to use, copy, modify, alter, enhance and distribute
  12. * this software, and any derivative works thereof, and its supporting
  13. * documentation for any purpose whatsoever, provided that this entire
  14. * notice appears in all copies of the software, derivative works and
  15. * supporting documentation. Further, UCAR requests that the user credit
  16. * UCAR/Unidata in any publications that result from the use of this
  17. * software or in any product that includes this software. The names UCAR
  18. * and/or Unidata, however, may not be used in any advertising or publicity
  19. * to endorse or promote any products or commercial entity unless specific
  20. * written permission is obtained from UCAR/Unidata. The user also
  21. * understands that UCAR/Unidata is not obligated to provide the user with
  22. * any support, consulting, training or assistance of any kind with regard
  23. * to the use, operation and performance of this software nor to provide
  24. * the user with any updates, revisions, new versions or "bug fixes."
  25. *
  26. * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR
  27. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  28. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  29. * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL,
  30. * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
  31. * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  32. * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
  33. * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE.
  34. */
  35. package ucar.nc2.iosp.gempak;
  36. import ucar.unidata.util.StringUtil;
  37. import java.io.*;
  38. // When ucar.unidata.util is in common, revert to using this
  39. //import ucar.unidata.util.IOUtil;
  40. import java.net.URL;
  41. import java.net.URLConnection;
  42. import java.util.ArrayList;
  43. import java.util.HashMap;
  44. import java.util.Iterator;
  45. import java.util.List;
  46. import java.util.Set;
  47. import java.util.regex.Matcher;
  48. import java.util.regex.Pattern;
  49. /**
  50. * Class to hold a lookup of gempak parameters
  51. *
  52. *
  53. * @author IDV Development Team
  54. * @version $Revision: 1.3 $
  55. */
  56. public class GempakParameterTable {
  57. /** table to hold the values */
  58. private HashMap<String, GempakParameter> paramMap =
  59. new HashMap<String, GempakParameter>(256);
  60. /** table to hold the template values */
  61. private HashMap<String, GempakParameter> templateParamMap =
  62. new HashMap<String, GempakParameter>(20);
  63. /** indices of breakpoints in the table */
  64. private static int[] indices = {
  65. 0, 4, 38, 59, 72, 79, 90, 97
  66. };
  67. /** lengths */
  68. private static int[] lengths = {
  69. 4, 33, 21, 13, 7, 11, 6, 6
  70. };
  71. /**
  72. * Create a new table.
  73. */
  74. public GempakParameterTable() {}
  75. /*
  76. ID# NAME UNITS GNAM SCALE MISSING HZREMAP DIRECTION
  77. */
  78. /**
  79. * Add parameters from the table
  80. *
  81. * @param tbl table location
  82. *
  83. * @throws IOException problem reading table.
  84. */
  85. public void addParameters(String tbl) throws IOException {
  86. //String content = IOUtil.readContents(tbl, GempakParameterTable.class);
  87. InputStream is = getInputStream(tbl);
  88. if (is == null) {
  89. throw new IOException("Unable to open " + tbl);
  90. }
  91. String content = readContents(is);
  92. List lines = StringUtil.split(content, "\n", false);
  93. List<String[]> result = new ArrayList<String[]>();
  94. for (int i = 0; i < lines.size(); i++) {
  95. String line = (String) lines.get(i);
  96. String tline = line.trim();
  97. if (tline.length() == 0) {
  98. continue;
  99. }
  100. if (tline.startsWith("!")) {
  101. continue;
  102. }
  103. String[] words = new String[indices.length];
  104. for (int idx = 0; idx < indices.length; idx++) {
  105. if (indices[idx] >= tline.length()) {
  106. continue;
  107. }
  108. if (indices[idx] + lengths[idx] > tline.length()) {
  109. words[idx] = line.substring(indices[idx]);
  110. } else {
  111. words[idx] = line.substring(indices[idx],
  112. indices[idx] + lengths[idx]);
  113. }
  114. //if (trimWords) {
  115. words[idx] = words[idx].trim();
  116. //}
  117. }
  118. result.add(words);
  119. }
  120. for (int i = 0; i < result.size(); i++) {
  121. GempakParameter p = makeParameter((String[]) result.get(i));
  122. if (p != null) {
  123. if (p.getName().indexOf("(") >= 0) {
  124. templateParamMap.put(p.getName(), p);
  125. } else {
  126. paramMap.put(p.getName(), p);
  127. }
  128. }
  129. }
  130. }
  131. /**
  132. * Make a parameter from the tokens
  133. *
  134. * @param words the tokens
  135. *
  136. * @return a grid parameter (may be null)
  137. */
  138. private GempakParameter makeParameter(String[] words) {
  139. int num = 0;
  140. String description;
  141. if (words[0] != null) {
  142. num = (int) Double.parseDouble(words[0]);
  143. }
  144. if ((words[3] == null) || words[3].equals("")) { // no param name
  145. return null;
  146. }
  147. String name = words[3];
  148. if (name.indexOf("-") >= 0) {
  149. int first = name.indexOf("-");
  150. int last = name.lastIndexOf("-");
  151. StringBuffer buf = new StringBuffer(name.substring(0, first));
  152. buf.append("(");
  153. for (int i = first; i <= last; i++) {
  154. buf.append("\\d");
  155. }
  156. buf.append(")");
  157. buf.append(name.substring(last + 1));
  158. name = buf.toString();
  159. }
  160. if ((words[1] == null) || words[1].equals("")) {
  161. description = words[3];
  162. } else {
  163. description = words[1];
  164. }
  165. String unit = words[2];
  166. if (unit != null) {
  167. unit = unit.replaceAll("\\*\\*", "");
  168. if (unit.equals("-")) {
  169. unit = "";
  170. }
  171. }
  172. int decimalScale = 0;
  173. try {
  174. decimalScale = Integer.parseInt(words[4].trim());
  175. } catch (NumberFormatException ne) {
  176. decimalScale = 0;
  177. }
  178. return new GempakParameter(num, name, description, unit,
  179. decimalScale);
  180. }
  181. /**
  182. * Get the parameter for the given name
  183. *
  184. * @param name name of the parameter (eg:, TMPK);
  185. *
  186. * @return corresponding parameter or null if not found in table
  187. */
  188. public GempakParameter getParameter(String name) {
  189. GempakParameter param = (GempakParameter) paramMap.get(name);
  190. if (param == null) { // try the regex list
  191. Set<String> keys = templateParamMap.keySet();
  192. if ( !keys.isEmpty()) {
  193. for (Iterator iter = keys.iterator(); iter.hasNext(); ) {
  194. String key = (String) iter.next();
  195. Pattern p = Pattern.compile(key);
  196. Matcher m = p.matcher(name);
  197. if (m.matches()) {
  198. //System.out.println("found match " + key + " for " + name);
  199. String value = m.group(1);
  200. GempakParameter match =
  201. (GempakParameter) templateParamMap.get(key);
  202. param = new GempakParameter(match.getNumber(), name,
  203. match.getDescription() + " (" + value
  204. + " hour)", match.getUnit(),
  205. match.getDecimalScale());
  206. paramMap.put(name, param);
  207. break;
  208. }
  209. }
  210. }
  211. }
  212. return param;
  213. }
  214. /**
  215. * Test
  216. *
  217. * @param args ignored
  218. *
  219. * @throws IOException problem reading the table.
  220. */
  221. public static void main(String[] args) throws IOException {
  222. GempakParameterTable pt = new GempakParameterTable();
  223. //pt.addParameters("resources/nj22/tables/gempak/wmogrib3.tbl");
  224. pt.addParameters("resources/nj22/tables/gempak/params.tbl");
  225. if (args.length > 0) {
  226. String param = args[0];
  227. GempakParameter parm = pt.getParameter(param);
  228. if (parm != null) {
  229. System.out.println("Found " + param + ": " + parm);
  230. }
  231. }
  232. }
  233. /**
  234. * Read in the bytes from the given InputStream
  235. * and construct and return a String.
  236. * Closes the InputStream argument.
  237. *
  238. * @param is InputStream to read from
  239. * @return contents as a String
  240. *
  241. * @throws IOException problem reading contents
  242. */
  243. private String readContents(InputStream is) throws IOException {
  244. return new String(readBytes(is));
  245. }
  246. /**
  247. * Read the bytes in the given input stream.
  248. *
  249. * @param is The input stream
  250. *
  251. * @return The bytes
  252. *
  253. * @throws IOException On badness
  254. */
  255. private byte[] readBytes(InputStream is) throws IOException {
  256. int totalRead = 0;
  257. byte[] content = new byte[1000000];
  258. while (true) {
  259. int howMany = is.read(content, totalRead,
  260. content.length - totalRead);
  261. if (howMany < 0) {
  262. break;
  263. }
  264. if (howMany == 0) {
  265. continue;
  266. }
  267. totalRead += howMany;
  268. if (totalRead >= content.length) {
  269. byte[] tmp = content;
  270. int newLength = ((content.length < 25000000)
  271. ? content.length * 2
  272. : content.length + 5000000);
  273. content = new byte[newLength];
  274. System.arraycopy(tmp, 0, content, 0, totalRead);
  275. }
  276. }
  277. is.close();
  278. byte[] results = new byte[totalRead];
  279. System.arraycopy(content, 0, results, 0, totalRead);
  280. return results;
  281. }
  282. /**
  283. * Get the input stream to the given resource
  284. *
  285. * @param resourceName The resource name. May be a file, url,
  286. * java resource, etc.
  287. *
  288. * @return The input stream to the resource
  289. */
  290. private InputStream getInputStream(String resourceName) {
  291. InputStream s = null;
  292. // Try class loader to get resource
  293. ClassLoader cl = GempakParameterTable.class.getClassLoader();
  294. s = cl.getResourceAsStream(resourceName);
  295. if (s != null) {
  296. return s;
  297. }
  298. //Try the file system
  299. File f = new File(resourceName);
  300. if (f.exists()) {
  301. try {
  302. s = new FileInputStream(f);
  303. } catch (Exception e) {}
  304. }
  305. if (s != null) {
  306. return s;
  307. }
  308. //Try it as a url
  309. try {
  310. Matcher m = Pattern.compile(" ").matcher(resourceName);
  311. String encodedUrl = m.replaceAll("%20");
  312. URL dataUrl = new URL(encodedUrl);
  313. URLConnection connection = dataUrl.openConnection();
  314. s = connection.getInputStream();
  315. } catch (Exception exc) {}
  316. return s;
  317. }
  318. }