1   /**
2    * Copyright 2010, CSIRO Australia.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  /**
18   * 
19   */
20  package au.csiro.netcdf;
21  
22  import java.io.BufferedWriter;
23  import java.io.ByteArrayInputStream;
24  import java.io.ByteArrayOutputStream;
25  import java.io.DataOutputStream;
26  import java.io.File;
27  import java.io.FileWriter;
28  import java.io.IOException;
29  import java.io.InputStream;
30  import java.io.PrintStream;
31  import java.io.UnsupportedEncodingException;
32  import java.util.List;
33  
34  import junit.framework.TestCase;
35  
36  import org.apache.commons.cli.Options;
37  import org.apache.log4j.Logger;
38  
39  import ucar.ma2.DataType;
40  import ucar.ma2.Range;
41  import ucar.nc2.Dimension;
42  import ucar.nc2.NCdumpW;
43  import ucar.nc2.NetcdfFile;
44  import ucar.nc2.NetcdfFileWriteable;
45  import ucar.nc2.Variable;
46  import ucar.nc2.iosp.netcdf3.N3iosp;
47  
48  /**
49   * This class is a unit test suite to verify that the NcDefineDimension command operates correctly.
50   * <p>
51   * Copyright 2010, CSIRO Australia All rights reserved.
52   * 
53   * @author Rita Chen on 23/03/2010
54   * @version $Revision: 83 $ $Date: 2010-08-18 15:16:33 +1000 (Wed, 18 Aug 2010) $
55   */
56  public class TestNcWriteVariable extends TestCase
57  {
58      /**
59       * Constant that defines the logger to be used.
60       */
61      private static final Logger LOG = Logger.getLogger(TestNcWriteVariable.class.getName());
62  
63      /**
64       * The name of the command line option used for specifying the output netCDF file name.
65       */
66      private static final String OUTPUT_FILE = "outputFileName";
67  
68      /**
69       * The name of the command line option used for specifying the name of the variable.
70       */
71      private static final String VARIABLE_NAME = "variableName";
72  
73      /**
74       * The name of the command line option used for specifying the input text file name.
75       */
76      private static final String INPUT_FILE = "inputFileName";
77  
78      /**
79       * The name of the command line option used for specifying the range to be filled.
80       */
81      private static final String FILL_RANGE = "fillRange";
82  
83      /**
84       * The testing value for the dimension option.
85       */
86      private static final String DIM_NAME = "myDimension";
87  
88      /**
89       * The testing value for the dimension option.
90       */
91      private static final String VAR_NAME = "myVariable";
92  
93      /**
94       * The testing value for the dimension size.
95       */
96      private static final int DIM_SIZE = 10;
97  
98      /**
99       * The testing String value for the dimension size.
100      */
101     private static final String DIM_SIZE_STR = "10";
102 
103     /**
104      * The testing value for the netCDF file to write to.
105      */
106     private static final String NC_FILE_NAME = System.getProperty("user.dir") + "\\ABC.nc";
107 
108     /**
109      * The file name for the test data.
110      */
111     private static final String TST_FILE_NAME = System.getProperty("user.dir") + "\\TestData.txt";
112 
113     /**
114      * The file name for testing the lookup range function.
115      */
116     private static final String LOOKUP_RANGE_TEST_FILE_NAME = System.getProperty("user.dir") + "\\LookupRangeTest.nc";
117 
118     /**
119      * The testing value for a coordinate variable.
120      */
121     private static final String LATITUDES = "latitude";
122 
123     /**
124      * the testing value for an independent variable.
125      */
126     private static final String TEMPERATURE = "temperature";
127 
128     /**
129      * Used to capture standard output
130      */
131     private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
132 
133     /*
134      * (non-Javadoc)
135      * 
136      * @see junit.framework.TestCase#setUp()
137      */
138     @Override
139     protected void setUp() throws Exception
140     {
141         super.setUp();
142 
143         // create dummy netCDF file with content.
144         createDummyNCFile(NC_FILE_NAME, DataType.CHAR);
145 
146         // write standard output to a stream we can examine.
147         System.setOut(new PrintStream(outContent));
148     }
149 
150     /*
151      * (non-Javadoc)
152      * 
153      * @see junit.framework.TestCase#tearDown()
154      */
155     @Override
156     protected void tearDown() throws Exception
157     {
158         super.tearDown();
159 
160         System.setOut(null);
161 
162         // delete dummy netCDF file
163         File ncFile = new File(NC_FILE_NAME);
164         if (ncFile.exists())
165         {
166             NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
167             netcdfFile.close();
168             ncFile.delete();
169         }
170 
171         // delete test data file
172         File tstFile = new File(TST_FILE_NAME);
173         if (tstFile.exists())
174         {
175             tstFile.delete();
176         }
177 
178     }
179 
180     /**
181      * Check that the convertStringsToRanges copes with ranges and single values.
182      * @throws Exception If there is an unexpected issue
183      */
184     public void testConvertStringsToRanges() throws Exception
185     {
186         NcWriteVariable nwVar = new NcWriteVariable();
187 
188         String[] rangeStrings = new String[] { "0-20", "5", "3" };
189         Range[] ranges = nwVar.convertStringsToRanges(rangeStrings, null, null);
190 
191         assertEquals("Incorrect start value range 0", 0, ranges[0].first());
192         assertEquals("Incorrect end value range 0", 20, ranges[0].last());
193         assertEquals("Incorrect start value range 1", 5, ranges[1].first());
194         assertEquals("Incorrect end value range 1", 5, ranges[1].last());
195         assertEquals("Incorrect start value range 2", 3, ranges[2].first());
196         assertEquals("Incorrect end value range 2", 3, ranges[2].last());
197 
198         assertEquals("Mismatch on number of ranges", rangeStrings.length, ranges.length);
199         for (int i = 0; i < ranges.length; i++)
200         {
201             Range range = ranges[i];
202             assertEquals("Incorrect stride for range " + i, 1, range.stride());
203         }
204 
205     }
206 
207     /**
208      * Check that the convertStringsToRanges copes with strings with spaces.
209      * @throws Exception If there is an unexpected issue
210      */
211     public void testConvertStringsWithSpacesToRanges() throws Exception
212     {
213         NcWriteVariable nwVar = new NcWriteVariable();
214 
215         String[] rangeStrings = new String[] { " 0 - 20 ", " 5", "3 " };
216         Range[] ranges = nwVar.convertStringsToRanges(rangeStrings, null, null);
217 
218         assertEquals("Incorrect start value range 0", 0, ranges[0].first());
219         assertEquals("Incorrect end value range 0", 20, ranges[0].last());
220         assertEquals("Incorrect start value range 1", 5, ranges[1].first());
221         assertEquals("Incorrect end value range 1", 5, ranges[1].last());
222         assertEquals("Incorrect start value range 2", 3, ranges[2].first());
223         assertEquals("Incorrect end value range 2", 3, ranges[2].last());
224 
225         assertEquals("Mismatch on number of ranges", rangeStrings.length, ranges.length);
226         for (int i = 0; i < ranges.length; i++)
227         {
228             Range range = ranges[i];
229             assertEquals("Incorrect stride for range " + i, 1, range.stride());
230         }
231 
232     }
233 
234     /**
235      * Test the splitRange function can cope with negative lookups
236      */
237     public void testSplitRange()
238     {
239         NcWriteVariable nwVar = new NcWriteVariable();
240 
241         String rangeStrings[] = nwVar.splitRange("lookup(-52)-lookup(-40)");
242         assertEquals("Start of range was incorrect", "lookup(-52)", rangeStrings[0]);
243         assertEquals("End of range was incorrect", "lookup(-40)", rangeStrings[1]);
244     }
245 
246     /**
247      * Test the creation of an origin list for a single range
248      * 
249      * @throws Exception
250      *             if the range is invalid
251      */
252     public void testCreateOriginListSingle() throws Exception
253     {
254         NcWriteVariable nwVar = new NcWriteVariable();
255 
256         Range[] fillRanges = new Range[1];
257         fillRanges[0] = new Range(1, 10, 1);
258         List<int[]> originList = nwVar.createOriginList(fillRanges);
259         assertEquals("Should have returned start of range", 1, originList.get(0)[0]);
260         assertEquals("Should have one origin only", 1, originList.get(0).length);
261         assertEquals("Should have one origin only", 1, originList.size());
262     }
263 
264     /**
265      * Test the creation of an origin list for a two dimension range
266      * 
267      * @throws Exception
268      *             if the range is invalid
269      */
270     public void testCreateOriginListTwoRange() throws Exception
271     {
272         NcWriteVariable nwVar = new NcWriteVariable();
273 
274         Range[] fillRanges = new Range[2];
275         fillRanges[0] = new Range(1, 3, 1);
276         fillRanges[1] = new Range(10, 20, 1);
277         List<int[]> originList = nwVar.createOriginList(fillRanges);
278         int[][] expected = new int[][] { { 1, 10 }, { 2, 10 }, { 3, 10 } };
279         validateOriginList(fillRanges, originList, expected);
280 
281         assertEquals("Should have 3 origins", 3, originList.size());
282     }
283 
284     /**
285      * Test the creation of an origin list for a three dimension range
286      * 
287      * @throws Exception
288      *             if the range is invalid
289      */
290     public void testCreateOriginListThreeRange() throws Exception
291     {
292         NcWriteVariable nwVar = new NcWriteVariable();
293 
294         Range[] fillRanges = new Range[3];
295         fillRanges[0] = new Range(1, 3, 1);
296         fillRanges[1] = new Range(5, 7, 1);
297         fillRanges[2] = new Range(10, 20, 1);
298         List<int[]> originList = nwVar.createOriginList(fillRanges);
299         int[][] expected = new int[][] { { 1, 5, 10 }, { 1, 6, 10 }, { 1, 7, 10 }, { 2, 5, 10 }, { 2, 6, 10 },
300                 { 2, 7, 10 }, { 3, 5, 10 }, { 3, 6, 10 }, { 3, 7, 10 } };
301         validateOriginList(fillRanges, originList, expected);
302 
303         assertEquals("Incorrect number of origins", 9, originList.size());
304     }
305 
306     /**
307      * Check the resulting origin list against the expected values
308      * 
309      * @param fillRanges
310      *            The original ranges
311      * @param actual
312      *            The result of the createOriginList call
313      * @param expected
314      *            The expected result
315      */
316     private void validateOriginList(Range[] fillRanges, List<int[]> actual, int[][] expected)
317     {
318         for (int i = 0; i < expected.length; i++)
319         {
320             int[] cells = expected[i];
321             for (int j = 0; j < cells.length; j++)
322             {
323                 assertEquals("Mismatch of generated origin value for row " + i + " and column " + j, cells[j], actual
324                         .get(i)[j]);
325             }
326         }
327         for (int i = 0; i < actual.size(); i++)
328         {
329             assertEquals("Should have the same number of values as fill ranges", fillRanges.length,
330                     actual.get(i).length);
331         }
332     }
333 
334     public void testExecute()
335     {
336 
337     }
338 
339     // public void testCreateArray()
340     // {
341     // fail("Not yet implemented");
342     // }
343     //
344     // public void testReadData()
345     // {
346     // fail("Not yet implemented");
347     // }
348 
349     /**
350      * Test that the commands options are used.
351      */
352     public final void testCreateOptions()
353     {
354         NcWriteVariable command = new NcWriteVariable();
355         Options options = command.createOptions();
356 
357         assertTrue("The following option is not recognised by the command: " + VARIABLE_NAME, options
358                 .hasOption(VARIABLE_NAME));
359         assertTrue("The following option is not recognised by the command: " + INPUT_FILE, options
360                 .hasOption(INPUT_FILE));
361         assertTrue("The following option is not recognised by the command: " + OUTPUT_FILE, options
362                 .hasOption(OUTPUT_FILE));
363         assertTrue("The following option is not recognised by the command: " + FILL_RANGE, options
364                 .hasOption(FILL_RANGE));
365     }
366 
367     /**
368      * Test required option
369      */
370     public final void testMissingRequiredOption()
371     {
372         NcWriteVariable command = new NcWriteVariable();
373         String[] args = new String[] { command.getCommandName(), "-" + OUTPUT_FILE, NC_FILE_NAME };
374 
375         String errors = command.validCommand(args);
376         assertTrue("Command without required options should return an error", !errors.isEmpty());
377 
378     }
379 
380     /**
381      * Test validate command with valid and invalid file names
382      */
383     public final void testValidIuputFileName()
384     {
385         NcWriteVariable command = new NcWriteVariable();
386         // test invalid filename
387         String[] args = new String[] { command.getCommandName(), "-" + OUTPUT_FILE, NC_FILE_NAME, "-" + FILL_RANGE,
388                 "0-" + String.valueOf(DIM_SIZE - 1), "-" + VARIABLE_NAME, VAR_NAME, "-" + INPUT_FILE, "testing.txt" };
389 
390         String errors = command.validCommand(args);
391         assertTrue("Command with invalid input file should return an error", !errors.isEmpty());
392 
393         // test valid filename
394         createTestDataFile();
395         args = new String[] { command.getCommandName(), "-" + OUTPUT_FILE, NC_FILE_NAME, "-" + FILL_RANGE,
396                 "0-" + String.valueOf(DIM_SIZE - 1), "-" + VARIABLE_NAME, VAR_NAME, "-" + INPUT_FILE, TST_FILE_NAME };
397         errors = command.validCommand(args);
398         assertTrue("Command with invalid input file should return an error", errors.isEmpty());
399 
400         File tstFile = new File(TST_FILE_NAME);
401         tstFile.delete();
402     }
403 
404     /**
405      * Test command execution with a valid input file
406      */
407     public final void testExecuteWithValidIuputFile() throws Exception
408     {
409         createTestDataFile();
410         NcWriteVariable command = new NcWriteVariable();
411         String[] args = new String[] { command.getCommandName(), "-" + OUTPUT_FILE, NC_FILE_NAME, "-" + FILL_RANGE,
412                 "0-" + String.valueOf(DIM_SIZE - 1), "-" + VARIABLE_NAME, VAR_NAME, "-" + INPUT_FILE, TST_FILE_NAME };
413 
414         String errors = command.validCommand(args);
415         assertTrue("Command with valid input file should not return an error", errors.isEmpty());
416 
417         command.execute(args);
418         NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
419 
420         // test variable created/kept
421         Variable var = netcdfFile.findVariable(VAR_NAME);
422         assertNotNull("The variable was not kept:", var);
423         assertEquals("The Variable name was not correct:", VAR_NAME, var.getName());
424 
425         // test shapes are correct
426         assertEquals("The Variable shape was not correct: ", DIM_SIZE, var.getShape(0));
427 
428         // test data
429         // myVariable = "0123456789"\n
430         String savedData = NCdumpW.printVariableData(var, null);
431 
432         int starting = savedData.indexOf("\"") + 1;
433         int ending = savedData.lastIndexOf("\"");
434         savedData = savedData.substring(starting, ending);
435         assertEquals("The Variable data was not saved correctly: ", getTestDataLine(), savedData);
436 
437         netcdfFile.close();
438 
439         File tstFile = new File(TST_FILE_NAME);
440         tstFile.delete();
441     }
442 
443     /**
444      * Test invalid fillRange option
445      */
446     public final void testInvalidOptionType()
447     {
448         NcWriteVariable command = new NcWriteVariable();
449         String[] args = new String[] { command.getCommandName(), "-" + OUTPUT_FILE, NC_FILE_NAME, "-" + VARIABLE_NAME,
450                 VAR_NAME, "-" + FILL_RANGE, "a-z" };
451 
452         String errors = command.validCommand(args);
453         assertTrue("Command with character type fillRange option should return an error", !errors.isEmpty());
454 
455     }
456 
457     /**
458      * Test running command given an invalid Variable name.
459      */
460     public final void testWriteToInvalidVariable() throws Exception
461     {
462         try
463         {
464             // String[] args = new String[] {
465             // NcWriteVariable.NC_WRITE_VAR_COMMAND_NAME,
466             // "-" + NcDefineDimension.OUTPUT_FILE, NC_FILE_NAME,
467             // "-variableName", VAR_NAME + "123",
468             // "-fillRange", "0-" + String.valueOf(DIM_SIZE - 1)};
469             InputStream is = new ByteArrayInputStream(createTestData().getBytes("UTF-8"));
470 
471             NcWriteVariable command = new NcWriteVariable();
472             // String error = command.validCommand(args);
473 
474             command.execute(new File(NC_FILE_NAME), VAR_NAME + "123", "0-" + String.valueOf(DIM_SIZE - 1), is, false);
475 
476             // expecting command execution failed due to invalid range
477             fail("testWriteToInvalidVariable should have failed");
478 
479         }
480         catch (IllegalArgumentException expected)
481         {
482             // this is exactly what we were expecting so
483             // let's just ignore it and let the test pass
484         }
485         catch (Exception e)
486         {
487             throw e;
488         }
489     }
490 
491     /**
492      * Test validate command with a valid fillRange
493      */
494     public final void testFillValidRange()
495     {
496         NcWriteVariable command = new NcWriteVariable();
497         String[] args = new String[] { command.getCommandName(), "-" + OUTPUT_FILE, NC_FILE_NAME, "-" + VARIABLE_NAME,
498                 VAR_NAME, "-" + FILL_RANGE, "0-" + String.valueOf(DIM_SIZE - 1) };
499 
500         String errors = command.validCommand(args);
501         assertTrue("Command with valid fillRange option should not return an error", errors.isEmpty());
502     }
503 
504     /**
505      * Test execute command by providing incorrect fillRange
506      */
507     public final void testFillInvalidRange() throws Exception
508     {
509         InputStream is = new ByteArrayInputStream(createTestData().getBytes("UTF-8"));
510 
511         NcWriteVariable command = new NcWriteVariable();
512         try
513         {
514             command.execute(new File(NC_FILE_NAME), VAR_NAME, "0-" + String.valueOf(DIM_SIZE + 10), is, false);
515             fail("Expected an illegal argument exception");
516         }
517         catch (IllegalArgumentException e)
518         {
519             // Ignore this expected exception
520         }
521 
522         NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
523 
524         // test variable created/kept
525         Variable var = netcdfFile.findVariable(VAR_NAME);
526 
527         String savedData = NCdumpW.printVariableData(var, null);
528 
529         int starting = savedData.indexOf("\"") + 1;
530         int ending = savedData.lastIndexOf("\"");
531         savedData = savedData.substring(starting, ending);
532         assertEquals("The Variable data was saved incorrectly: ", "", savedData);
533         netcdfFile.close();
534     }
535 
536     /**
537      * Test execute with a number of entries in fillrange that does not match the variables dimensions
538      */
539     public final void testMismatchedFillRange() throws Exception
540     {
541         try
542         {
543             InputStream is = new ByteArrayInputStream(createTestData().getBytes("UTF-8"));
544 
545             NcWriteVariable command = new NcWriteVariable();
546             // execute(File outputFile, String variableName, String fillRange, InputStream dataStream)
547             command.execute(new File(NC_FILE_NAME), VAR_NAME, "0-" + String.valueOf(DIM_SIZE - 1) + "," + "0-1", is, false);
548             // expecting command execution failed due to invalid range
549             fail("testMismatchedFillRange should have failed");
550         }
551         catch (java.lang.IllegalArgumentException expected)
552         {
553             //
554         }
555         catch (Exception e)
556         {
557             throw e;
558         }
559     }
560 
561     /**
562      * Test execute a valid NcWriteVariable command
563      */
564     public final void testExecuteValidCommand() throws Exception
565     {
566         InputStream is = new ByteArrayInputStream(createTestData().getBytes("UTF-8"));
567 
568         NcWriteVariable command = new NcWriteVariable();
569         // execute(File outputFile, String variableName, String fillRange, InputStream dataStream)
570         command.execute(new File(NC_FILE_NAME), VAR_NAME, "0-" + String.valueOf(DIM_SIZE - 1), is, false);
571 
572         NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
573 
574         // test variable created/kept
575         Variable var = netcdfFile.findVariable(VAR_NAME);
576         assertNotNull("The variable was not kept:", var);
577         assertEquals("The Variable name was not correct:", VAR_NAME, var.getName());
578 
579         // test shapes are correct
580         assertEquals("The Variable shape was not correct: ", DIM_SIZE, var.getShape(0));
581 
582         // test data
583         // myVariable = "0123456789"\n
584         String savedData = NCdumpW.printVariableData(var, null);
585 
586         int starting = savedData.indexOf("\"") + 1;
587         int ending = savedData.lastIndexOf("\"");
588         savedData = savedData.substring(starting, ending);
589         assertEquals("The Variable data was not saved correctly: ", getTestDataLine(), savedData);
590 
591         netcdfFile.close();
592     }
593 
594     /**
595      * Test execute a valid NcWriteVariable command using Double datatype
596      */
597     public final void testExecuteValidCommandwithDoubleVar() throws Exception
598     {
599         InputStream is = new ByteArrayInputStream(createDoubleTestData().getBytes());
600 
601         NcWriteVariable command = new NcWriteVariable();
602 
603         createDummyNCFile(NC_FILE_NAME, DataType.DOUBLE);
604         command.execute(new File(NC_FILE_NAME), VAR_NAME, "0-" + String.valueOf(DIM_SIZE - 1), is, false);
605 
606         NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
607 
608         // test variable created/kept
609         Variable var = netcdfFile.findVariable(VAR_NAME);
610         assertNotNull("The variable was not kept:", var);
611         assertEquals("The Variable name was not correct:", VAR_NAME, var.getName());
612 
613         // test shapes are correct
614         assertEquals("The Variable shape was not correct: ", DIM_SIZE, var.getShape(0));
615 
616         // test data
617         // myVariable = {9.8, 10.8, 11.8, 12.8, 13.8, 14.8, 15.8, 16.8, 17.8, 18.8}
618         String savedData = NCdumpW.printVariableData(var, null);
619 
620         int starting = savedData.indexOf("{") + 1;
621         int ending = savedData.lastIndexOf("}");
622         savedData = savedData.substring(starting, ending) + ", ";
623         assertEquals("The Variable data was not saved correctly: ", createDoubleTestData().replaceAll(
624                 System.getProperty("line.separator"), ", "), savedData);
625 
626         netcdfFile.close();
627     }
628 
629     /**
630      * Test execute a valid NcWriteVariable command using Long datatype
631      */
632     public final void testExecuteValidCommandwithIntVar() throws Exception
633     {
634         InputStream is = new ByteArrayInputStream(createTestData().getBytes());
635 
636         NcWriteVariable command = new NcWriteVariable();
637 
638         createDummyNCFile(NC_FILE_NAME, DataType.INT);
639         command.execute(new File(NC_FILE_NAME), VAR_NAME, "0-" + String.valueOf(DIM_SIZE - 1), is, false);
640 
641         NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
642 
643         // test variable created/kept
644         Variable var = netcdfFile.findVariable(VAR_NAME);
645         assertNotNull("The variable was not kept:", var);
646         assertEquals("The Variable name was not correct:", VAR_NAME, var.getName());
647 
648         // test shapes are correct
649         assertEquals("The Variable shape was not correct: ", DIM_SIZE, var.getShape(0));
650 
651         // test data
652         // myVariable = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
653         String savedData = NCdumpW.printVariableData(var, null);
654 
655         int starting = savedData.indexOf("{") + 1;
656         int ending = savedData.lastIndexOf("}");
657         savedData = savedData.substring(starting, ending) + ", ";
658         assertEquals("The Variable data was not saved correctly: ", createTestData().replaceAll(
659                 System.getProperty("line.separator"), ", "), savedData);
660 
661         netcdfFile.close();
662     }
663 
664     /**
665      * Test create a Variable with three Dimensions
666      * 
667      */
668     public final void testThreeDimNCVariable() throws Exception
669     {
670         String[] args1 = new String[] { NcDefineDimension.NC_DEFINE_DIM_COMMAND_NAME,
671                 "-" + NcDefineDimension.OUTPUT_FILE, NC_FILE_NAME, "-" + NcDefineDimension.DIMENSION_SIZE,
672                 DIM_SIZE_STR, "-" + NcDefineDimension.DIMENSION_NAME, DIM_NAME };
673 
674         String[] args2 = new String[] { NcDefineDimension.NC_DEFINE_DIM_COMMAND_NAME,
675                 "-" + NcDefineDimension.OUTPUT_FILE, NC_FILE_NAME, "-" + NcDefineDimension.DIMENSION_SIZE,
676                 DIM_SIZE_STR, "-" + NcDefineDimension.DIMENSION_NAME, DIM_NAME + "2" };
677 
678         String[] args3 = new String[] { NcDefineDimension.NC_DEFINE_DIM_COMMAND_NAME,
679                 "-" + NcDefineDimension.OUTPUT_FILE, NC_FILE_NAME, "-" + NcDefineDimension.DIMENSION_SIZE,
680                 DIM_SIZE_STR, "-" + NcDefineDimension.DIMENSION_NAME, DIM_NAME + "3" };
681 
682         String[] argsVar = new String[] { NcDefineVariable.NC_DEFINE_VAR_COMMAND_NAME,
683                 "-" + NcDefineVariable.OUTPUT_FILE, NC_FILE_NAME, "-" + NcDefineVariable.VARIABLE_DATA_TYPE, "Char",
684                 "-" + NcDefineVariable.DIMENSION_NAMES, DIM_NAME + " " + DIM_NAME + "2" + " " + DIM_NAME + "3",
685                 "-" + NcDefineVariable.VARIABLE_NAME, VAR_NAME };
686 
687         File ncFile = new File(NC_FILE_NAME);
688         if (ncFile.exists())
689         {
690             ncFile.delete();
691         }
692 
693         NcDefineDimension dimCmd = new NcDefineDimension();
694         dimCmd.execute(args1);
695         dimCmd.execute(args2);
696         dimCmd.execute(args3);
697 
698         NcDefineVariable varCmd = new NcDefineVariable();
699         varCmd.execute(argsVar);
700 
701         NetcdfFile netcdfFile = NetcdfFile.open(NC_FILE_NAME);
702 
703         // test variable created/kept
704         Variable var = netcdfFile.findVariable(VAR_NAME);
705         assertNotNull("The variable was not kept:", var);
706 
707         int nbrOfDim = var.getDimensions().size();
708         assertEquals("The variable should have 3 dimensions:", nbrOfDim, 3);
709 
710         netcdfFile.close();
711         
712         // Now test writing to the variable doesn;t crash
713         NcWriteVariable writeCmd = new NcWriteVariable();
714         String values = "D\nF\nH\n";
715         InputStream inStream = new ByteArrayInputStream(values.getBytes());
716         writeCmd.execute(ncFile, VAR_NAME, "0-2,0,0", inStream, false);
717      
718         // Check the result
719         netcdfFile = NetcdfFile.open(NC_FILE_NAME);
720         var = netcdfFile.findVariable(VAR_NAME);
721 
722         String savedData = NCdumpW.printVariableData(var, null);
723         int starting = savedData.indexOf("{") + 1;
724         int ending = savedData.lastIndexOf("}");
725         savedData = savedData.substring(starting, ending) + ", ";
726         
727         String valArray[] = values.split("\n");
728         StringBuilder expected = new StringBuilder();
729         for (int i = 0; i < valArray.length; i++)
730         {
731             expected.append("\"");
732             expected.append(valArray[i]);
733             expected.append("\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",");
734         }
735         assertEquals("The Variable data was not saved correctly: ", expected.toString(), savedData.substring(0, expected.toString().length()));
736 
737         netcdfFile.close();
738         
739     }
740 
741     /**
742      * Test execute a valid integral range lookup
743      */
744     public final void testLookupRangeIntegral()
745     {
746         try
747         {
748             /////////////////////////////////
749             // create netCDF file parameters
750             ////////////////////////////////
751             String rangeStartStr = "160";
752             String rangeEndStr = "180";
753             int rangeStartInt = 2;
754             int rangeEndInt = 6;
755 
756             // create a latitude (dependent variable) values
757             String[] latitudes = new String[] { "150", "155", "160", "165", "170", "175", "180", "190", "195", "200" };
758             
759             // create a temperature (independent variable) values
760             String[] temperatures = new String[] { "10", "15", "13", "19", "21", "12", "23", "30", "24", "27" };
761 
762             // create String of latitudes to populate the variable
763             StringBuffer latitudeValues = new StringBuffer();
764             for(int i = 0; i < latitudes.length; i++)
765             {
766                 latitudeValues.append(latitudes[i]).append(System.getProperty("line.separator"));
767             }
768             
769             // create String of temperature values within "range" to populate the variable
770             StringBuffer temperatureValues = new StringBuffer();
771             for(int i = rangeStartInt; i <= rangeEndInt; i++)
772             {
773                 temperatureValues.append(temperatures[i]).append(System.getProperty("line.separator"));
774             }
775 
776             // ////////////////////////////
777             // create netCDF testing file
778             // ////////////////////////////
779             this.createRangeLookupNCFile(latitudes.length, DataType.INT);
780 
781             // //////////////////////////////////////////
782             // populate netCDF testing file with values
783             // //////////////////////////////////////////
784             this.populateVariableUsingRangeLookups(latitudeValues.toString(), latitudes.length,
785                     temperatureValues.toString(), rangeStartStr, rangeEndStr);
786             
787             /////////////////////////////////////////////////////
788             // test netCDF testing file is populated as expected
789             /////////////////////////////////////////////////////
790             NetcdfFile netcdfFile = NetcdfFile.open(LOOKUP_RANGE_TEST_FILE_NAME);
791             
792             // sanity check that latitudes variable exists
793             Variable var = netcdfFile.findVariable(LATITUDES);
794             assertEquals("The Variable name was not correct:", LATITUDES, var.getName());
795             assertEquals("The Variable shape was not correct: ", var.getShape(0), latitudes.length);
796             
797             // sanity check that temperature variable exists
798             var = netcdfFile.findVariable(TEMPERATURE);
799             assertEquals("The Variable name was not correct:", TEMPERATURE, var.getName());
800             assertEquals("The Variable shape was not correct: ", var.getShape(0), temperatures.length);
801 
802             // temperatures = "fillValue,fillValue,X,X,X,X,X,fillValue,fillValue,fillValue,fillValue", where X is an actual temperature value.
803             String savedData = NCdumpW.printVariableData(var, null);
804             int starting = savedData.indexOf("{") + 1;
805             int ending = savedData.lastIndexOf("}");
806             savedData = savedData.substring(starting, ending);
807             String[] values = savedData.split(",");
808 
809             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[0].trim()).intValue(), N3iosp.NC_FILL_INT);
810             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[1].trim()).intValue(), N3iosp.NC_FILL_INT);
811             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[2].trim()), Integer.valueOf(temperatures[2]));
812             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[3].trim()), Integer.valueOf(temperatures[3]));
813             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[4].trim()), Integer.valueOf(temperatures[4]));
814             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[5].trim()), Integer.valueOf(temperatures[5]));
815             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[6].trim()), Integer.valueOf(temperatures[6]));
816             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[7].trim()).intValue(), N3iosp.NC_FILL_INT);
817             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[8].trim()).intValue(), N3iosp.NC_FILL_INT);
818             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[9].trim()).intValue(), N3iosp.NC_FILL_INT);
819 
820             netcdfFile.close();
821         }
822         catch (Exception e)
823         {
824             LOG.error(e);
825             e.printStackTrace();
826         }
827         finally
828         {
829             //////////////////////////////
830             // delete netCDF testing file
831             /////////////////////////////
832             File file = new File(LOOKUP_RANGE_TEST_FILE_NAME);
833             if (file.exists())
834             {
835                 file.delete();
836             }
837         }
838     }
839     
840     /**
841      * Test execute a valid numeric range lookup
842      */
843     public final void testLookupRangeNumeric()
844     {
845         try
846         {
847             /////////////////////////////////
848             // create netCDF file parameters
849             ////////////////////////////////
850             String rangeStartStr = "1.3";
851             String rangeEndStr = "1.7";
852             int rangeStartInt = 2;
853             int rangeEndInt = 6;
854 
855             // create a latitude (dependent variable) values
856             String[] latitudes = new String[] { "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8", "1.9", "2.0" };
857 
858             // create a temperature (independent variable) values
859             String[] temperatures = new String[] { "10", "15", "13", "19", "21", "12", "23", "30", "24", "27" };
860 
861             // create String of latitudes to populate the variable
862             StringBuffer latitudeValues = new StringBuffer();
863             for(int i = 0; i < latitudes.length; i++)
864             {
865                 latitudeValues.append(latitudes[i]).append(System.getProperty("line.separator"));
866             }
867             
868             // create String of temperature values within "range" to populate the variable
869             StringBuffer temperatureValues = new StringBuffer();
870             for(int i = rangeStartInt; i <= rangeEndInt; i++)
871             {
872                 temperatureValues.append(temperatures[i]).append(System.getProperty("line.separator"));
873             }
874 
875             // ////////////////////////////
876             // create netCDF testing file
877             // ////////////////////////////
878             this.createRangeLookupNCFile(latitudes.length, DataType.DOUBLE);
879 
880             // //////////////////////////////////////////
881             // populate netCDF testing file with values
882             // //////////////////////////////////////////
883             this.populateVariableUsingRangeLookups(latitudeValues.toString(), latitudes.length,
884                     temperatureValues.toString(), rangeStartStr, rangeEndStr);
885             
886             /////////////////////////////////////////////////////
887             // test netCDF testing file is populated as expected
888             /////////////////////////////////////////////////////
889             NetcdfFile netcdfFile = NetcdfFile.open(LOOKUP_RANGE_TEST_FILE_NAME);
890             
891             // sanity check that latitudes variable exists
892             Variable var = netcdfFile.findVariable(LATITUDES);
893             assertEquals("The Variable name was not correct:", LATITUDES, var.getName());
894             assertEquals("The Variable shape was not correct: ", var.getShape(0), latitudes.length);
895             
896             // sanity check that temperature variable exists
897             var = netcdfFile.findVariable(TEMPERATURE);
898             assertEquals("The Variable name was not correct:", TEMPERATURE, var.getName());
899             assertEquals("The Variable shape was not correct: ", var.getShape(0), temperatures.length);
900 
901             // temperatures = "fillValue,fillValue,X,X,X,X,X,fillValue,fillValue,fillValue,fillValue", where X is an actual temperature value.
902             String savedData = NCdumpW.printVariableData(var, null);
903             int starting = savedData.indexOf("{") + 1;
904             int ending = savedData.lastIndexOf("}");
905             savedData = savedData.substring(starting, ending);
906             String[] values = savedData.split(",");
907 
908             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[0].trim()).intValue(), N3iosp.NC_FILL_INT);
909             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[1].trim()).intValue(), N3iosp.NC_FILL_INT);
910             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[2].trim()), Integer.valueOf(temperatures[2]));
911             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[3].trim()), Integer.valueOf(temperatures[3]));
912             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[4].trim()), Integer.valueOf(temperatures[4]));
913             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[5].trim()), Integer.valueOf(temperatures[5]));
914             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[6].trim()), Integer.valueOf(temperatures[6]));
915             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[7].trim()).intValue(), N3iosp.NC_FILL_INT);
916             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[8].trim()).intValue(), N3iosp.NC_FILL_INT);
917             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[9].trim()).intValue(), N3iosp.NC_FILL_INT);
918 
919             netcdfFile.close();
920         }
921         catch (Exception e)
922         {
923             LOG.error(e);
924             e.printStackTrace();
925         }
926         finally
927         {
928             //////////////////////////////
929             // delete netCDF testing file
930             /////////////////////////////
931             File file = new File(LOOKUP_RANGE_TEST_FILE_NAME);
932             if (file.exists())
933             {
934                 file.delete();
935             }
936         }
937     }
938     
939     /**
940      * Test execute a valid character range lookup
941      */
942     public final void testLookupRangeChar()
943     {
944         try
945         {
946             /////////////////////////////////
947             // create netCDF file parameters
948             ////////////////////////////////
949             String rangeStartStr = "c";
950             String rangeEndStr = "g";
951             int rangeStartInt = 2;
952             int rangeEndInt = 6;
953 
954             // create a latitude (dependent variable) values
955             String[] latitudes = new String[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j" };
956 
957             // create a temperature (independent variable) values
958             String[] temperatures = new String[] { "10", "15", "13", "19", "21", "12", "23", "30", "24", "27" };
959 
960             // create String of latitudes to populate the variable
961             StringBuffer latitudeValues = new StringBuffer();
962             for(int i = 0; i < latitudes.length; i++)
963             {
964                 latitudeValues.append(latitudes[i]).append(System.getProperty("line.separator"));
965             }
966             
967             // create String of temperature values within "range" to populate the variable
968             StringBuffer temperatureValues = new StringBuffer();
969             for(int i = rangeStartInt; i <= rangeEndInt; i++)
970             {
971                 temperatureValues.append(temperatures[i]).append(System.getProperty("line.separator"));
972             }
973 
974             // ////////////////////////////
975             // create netCDF testing file
976             // ////////////////////////////
977             this.createRangeLookupNCFile(latitudes.length, DataType.CHAR);
978 
979             // //////////////////////////////////////////
980             // populate netCDF testing file with values
981             // //////////////////////////////////////////
982             this.populateVariableUsingRangeLookups(latitudeValues.toString(), latitudes.length,
983                     temperatureValues.toString(), rangeStartStr, rangeEndStr);
984             
985             /////////////////////////////////////////////////////
986             // test netCDF testing file is populated as expected
987             /////////////////////////////////////////////////////
988             NetcdfFile netcdfFile = NetcdfFile.open(LOOKUP_RANGE_TEST_FILE_NAME);
989             
990             // sanity check that latitudes variable exists
991             Variable var = netcdfFile.findVariable(LATITUDES);
992             assertEquals("The Variable name was not correct:", LATITUDES, var.getName());
993             assertEquals("The Variable shape was not correct: ", var.getShape(0), latitudes.length);
994             
995             // sanity check that temperature variable exists
996             var = netcdfFile.findVariable(TEMPERATURE);
997             assertEquals("The Variable name was not correct:", TEMPERATURE, var.getName());
998             assertEquals("The Variable shape was not correct: ", var.getShape(0), temperatures.length);
999 
1000             // temperatures = "fillValue,fillValue,X,X,X,X,X,fillValue,fillValue,fillValue,fillValue", where X is an actual temperature value.
1001             String savedData = NCdumpW.printVariableData(var, null);
1002             int starting = savedData.indexOf("{") + 1;
1003             int ending = savedData.lastIndexOf("}");
1004             savedData = savedData.substring(starting, ending);
1005             String[] values = savedData.split(",");
1006 
1007             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[0].trim()).intValue(), N3iosp.NC_FILL_INT);
1008             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[1].trim()).intValue(), N3iosp.NC_FILL_INT);
1009             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[2].trim()), Integer.valueOf(temperatures[2]));
1010             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[3].trim()), Integer.valueOf(temperatures[3]));
1011             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[4].trim()), Integer.valueOf(temperatures[4]));
1012             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[5].trim()), Integer.valueOf(temperatures[5]));
1013             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[6].trim()), Integer.valueOf(temperatures[6]));
1014             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[7].trim()).intValue(), N3iosp.NC_FILL_INT);
1015             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[8].trim()).intValue(), N3iosp.NC_FILL_INT);
1016             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[9].trim()).intValue(), N3iosp.NC_FILL_INT);
1017 
1018             netcdfFile.close();
1019         }
1020         catch (Exception e)
1021         {
1022             LOG.error(e);
1023             e.printStackTrace();
1024         }
1025         finally
1026         {
1027             //////////////////////////////
1028             // delete netCDF testing file
1029             /////////////////////////////
1030             File file = new File(LOOKUP_RANGE_TEST_FILE_NAME);
1031             if (file.exists())
1032             {
1033                 file.delete();
1034             }
1035         }
1036     }
1037     
1038 
1039     /**
1040      * Test execute a valid integral range lookup
1041      */
1042     public final void testWriteDataBinary()
1043     {
1044         try
1045         {
1046             /////////////////////////////////
1047             // create netCDF file parameters
1048             ////////////////////////////////
1049             int rangeStartInt = 2;
1050             int rangeEndInt = 6;
1051 
1052             // create a latitude (dependent variable) values
1053             float[] latitudes = new float[] { 150.0f, 155.0f, 160.0f, 165.0f, 170.0f, 175.0f, 180.0f, 190.0f, 195.0f, 200.0f };
1054             
1055             // create a temperature (independent variable) values
1056             int[] temperatures = new int[] { 10, 15, 13, 19, 21, 12, 23, 30, 24, 27 };
1057 
1058             // create String of latitudes to populate the variable
1059             ByteArrayOutputStream baos = new ByteArrayOutputStream();
1060             DataOutputStream out = new DataOutputStream(baos);
1061             for(int i = 0; i < latitudes.length; i++)
1062             {
1063                 out.writeFloat(latitudes[i]);
1064             }
1065             out.flush();
1066             byte[] lats = baos.toByteArray();
1067             
1068             // create String of temperature values within "range" to populate the variable
1069             baos = new ByteArrayOutputStream();
1070             out = new DataOutputStream(baos);
1071             for(int i = rangeStartInt; i <= rangeEndInt; i++)
1072             {
1073                 out.writeInt(temperatures[i]);
1074             }
1075             out.flush();
1076             byte[] temps = baos.toByteArray();
1077 
1078             // ////////////////////////////
1079             // create netCDF testing file
1080             // ////////////////////////////
1081             this.createRangeLookupNCFile(latitudes.length, DataType.FLOAT);
1082 
1083             // //////////////////////////////////////////
1084             // populate netCDF testing file with values
1085             // //////////////////////////////////////////
1086             NcWriteVariable command = new NcWriteVariable();
1087             command.execute(new File(LOOKUP_RANGE_TEST_FILE_NAME), LATITUDES, "0-"
1088                     + String.valueOf(latitudes.length - 1), new ByteArrayInputStream(lats), true);
1089 
1090             command.execute(new File(LOOKUP_RANGE_TEST_FILE_NAME), TEMPERATURE, rangeStartInt + "-"
1091                     + rangeEndInt, new ByteArrayInputStream(temps), true);
1092             
1093             /////////////////////////////////////////////////////
1094             // test netCDF testing file is populated as expected
1095             /////////////////////////////////////////////////////
1096             NetcdfFile netcdfFile = NetcdfFile.open(LOOKUP_RANGE_TEST_FILE_NAME);
1097             
1098             // sanity check that latitudes variable exists
1099             Variable var = netcdfFile.findVariable(LATITUDES);
1100             assertEquals("The Variable name was not correct:", LATITUDES, var.getName());
1101             assertEquals("The Variable shape was not correct: ", var.getShape(0), latitudes.length);
1102 
1103             String savedData = NCdumpW.printVariableData(var, null);
1104             int starting = savedData.indexOf("{") + 1;
1105             int ending = savedData.lastIndexOf("}");
1106             savedData = savedData.substring(starting, ending);
1107             String[] values = savedData.split(",");
1108             for (int i = 0; i < values.length; i++)
1109             {
1110                 assertEquals("The latitude variable data was not saved correctly: ", latitudes[i], Float.valueOf(
1111                         values[i].trim()).floatValue(), 0.001);
1112             }
1113             
1114             // sanity check that temperature variable exists
1115             var = netcdfFile.findVariable(TEMPERATURE);
1116             assertEquals("The Variable name was not correct:", TEMPERATURE, var.getName());
1117             assertEquals("The Variable shape was not correct: ", var.getShape(0), temperatures.length);
1118 
1119             // temperatures = "fillValue,fillValue,X,X,X,X,X,fillValue,fillValue,fillValue,fillValue", where X is an actual temperature value.
1120             savedData = NCdumpW.printVariableData(var, null);
1121             starting = savedData.indexOf("{") + 1;
1122             ending = savedData.lastIndexOf("}");
1123             savedData = savedData.substring(starting, ending);
1124             values = savedData.split(",");
1125 
1126             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[0].trim()).intValue(), N3iosp.NC_FILL_INT);
1127             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[1].trim()).intValue(), N3iosp.NC_FILL_INT);
1128             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[2].trim()).intValue(), temperatures[2]);
1129             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[3].trim()).intValue(), temperatures[3]);
1130             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[4].trim()).intValue(), temperatures[4]);
1131             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[5].trim()).intValue(), temperatures[5]);
1132             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[6].trim()).intValue(), temperatures[6]);
1133             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[7].trim()).intValue(), N3iosp.NC_FILL_INT);
1134             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[8].trim()).intValue(), N3iosp.NC_FILL_INT);
1135             assertEquals("The Variable data was not saved correctly: ", Integer.valueOf(values[9].trim()).intValue(), N3iosp.NC_FILL_INT);
1136 
1137             netcdfFile.close();
1138         }
1139         catch (Exception e)
1140         {
1141             LOG.error(e);
1142             e.printStackTrace();
1143         }
1144         finally
1145         {
1146             //////////////////////////////
1147             // delete netCDF testing file
1148             /////////////////////////////
1149             File file = new File(LOOKUP_RANGE_TEST_FILE_NAME);
1150             if (file.exists())
1151             {
1152                 file.delete();
1153             }
1154         }
1155     }
1156     
1157     /**
1158      * Create a test netCDF file to test range lookups.
1159      * 
1160      * @param coordinateVariableValues
1161      *            the values of the coordinate variable.
1162      * @param coordinateVariableSize
1163      *            the number of coordinate values.
1164      * @param independentVariableValues
1165      *            the values of the independent variable.
1166      * @param rangeStartStr
1167      *            the start range value to lookup.
1168      * @param rangeEndStr
1169      *            the end range value to lookup.
1170      * @return
1171      * @throws IOException
1172      *             thrown if a variable can not be written.
1173      * @throws UnsupportedEncodingException
1174      *             thrown if a variable can not be written.
1175      */
1176     private void populateVariableUsingRangeLookups(String coordinateVariableValues, int coordinateVariableSize,
1177             String independentVariableValues, String rangeStartStr, String rangeEndStr)
1178             throws UnsupportedEncodingException, IOException
1179     {
1180         NcWriteVariable command = new NcWriteVariable();
1181         command.execute(new File(LOOKUP_RANGE_TEST_FILE_NAME), LATITUDES, "0-"
1182                 + String.valueOf(coordinateVariableSize - 1), new ByteArrayInputStream(coordinateVariableValues
1183                 .getBytes("UTF-8")), false);
1184 
1185         command.execute(new File(LOOKUP_RANGE_TEST_FILE_NAME), TEMPERATURE, "lookup(" + rangeStartStr + ")-lookup("
1186                 + rangeEndStr + ")", new ByteArrayInputStream(independentVariableValues.getBytes("UTF-8")), false);
1187 
1188         try
1189         {
1190             command.execute(new File(LOOKUP_RANGE_TEST_FILE_NAME), TEMPERATURE, "lookup(null)-lookup(" + rangeEndStr + ")", new ByteArrayInputStream(independentVariableValues.toString()
1191                     .getBytes("UTF-8")), false);
1192             fail("lookup invalid range should have failed");
1193 
1194         }
1195         catch (IllegalArgumentException iae)
1196         {
1197             // expected exception
1198             iae.printStackTrace();
1199         }
1200     }
1201 
1202     /**
1203      * Populate a test netCDF file to test range lookups.
1204      * 
1205      * @param coordinateVariableSize
1206      *            the size of the coordinate variable.
1207      * @param coordinateVariableDataType
1208      *            the data type of the coordinate variable.
1209      * @throws IOException
1210      *             thrown if the netCDF file can not be created.
1211      */
1212     private void createRangeLookupNCFile(int coordinateVariableSize, DataType coordinateVariableDataType)
1213             throws IOException
1214     {
1215         NetcdfFileWriteable ncFile = null;
1216         ncFile = NetcdfFileWriteable.createNew(LOOKUP_RANGE_TEST_FILE_NAME, true);
1217         try
1218         {
1219             // define coordinate variable
1220             Dimension dimension = new Dimension(LATITUDES, coordinateVariableSize, true /* isShared */,
1221                     false /* isUnlimited */, false /* isVariableLength */);
1222             ncFile.addDimension(null, dimension);
1223             ncFile.addVariable(LATITUDES, coordinateVariableDataType, LATITUDES); // note: the variable name is the
1224             // same as the dimension name,
1225             // making it a coordinate variable
1226 
1227             // define independent variable, temperature, which is measured every dayOfTheWeek.
1228             ncFile.addVariable(TEMPERATURE, DataType.INT, LATITUDES);
1229 
1230             ncFile.create();
1231         }
1232         finally
1233         {
1234             ncFile.close();
1235         }
1236     }
1237 
1238     /**
1239      * Create test data
1240      * 
1241      * @return test data
1242      */
1243     private String createTestData()
1244     {
1245         StringBuffer data = new StringBuffer();
1246         // create test data
1247         for (int i = 0; i < DIM_SIZE; i++)
1248         {
1249             data.append(i).append(System.getProperty("line.separator"));
1250         }
1251         return data.toString();
1252     }
1253 
1254     private String createDoubleTestData()
1255     {
1256         StringBuffer data = new StringBuffer();
1257         Double seed = new Double("9.8");
1258         // create test data
1259         for (int i = 0; i < DIM_SIZE; i++)
1260         {
1261             data.append(Double.valueOf(seed + i)).append(System.getProperty("line.separator"));
1262         }
1263         return data.toString();
1264     }
1265 
1266     /**
1267      * Get the test data for testing purpose
1268      * 
1269      * @return test data
1270      */
1271     private String getTestDataLine()
1272     {
1273         StringBuffer data = new StringBuffer();
1274         // create test data
1275         for (int i = 0; i < DIM_SIZE; i++)
1276         {
1277             data.append(i);
1278         }
1279         return data.toString();
1280     }
1281 
1282     /**
1283      * Makes a test data file with test data.
1284      */
1285     private void createTestDataFile()
1286     {
1287         try
1288         {
1289             // Create file
1290             BufferedWriter out = new BufferedWriter(new FileWriter(TST_FILE_NAME));
1291             out.write(createTestData());
1292             out.close();
1293         }
1294         catch (Exception e)
1295         {
1296             // Catch exception if any
1297             e.printStackTrace();
1298             fail("Failed trying to create a test data file for testing the NcWriteVariable command.");
1299         }
1300     }
1301 
1302     /**
1303      * Makes a dummy netCDF file with known contents.
1304      */
1305     private void createDummyNCFile(String outputFilename, DataType dType) throws IOException
1306     {
1307         NetcdfFileWriteable ncFile = null;
1308 
1309         ncFile = NetcdfFileWriteable.createNew(outputFilename, true);
1310         try
1311         {
1312             Dimension dimension = new Dimension(DIM_NAME, DIM_SIZE, true /* isShared */, false /* isUnlimited */, false /* isVariableLength */);
1313             ncFile.addDimension(null, dimension);
1314             ncFile.addVariable(VAR_NAME, dType, DIM_NAME);
1315             ncFile.create();
1316         }
1317         finally
1318         {
1319             ncFile.close();
1320         }
1321     }
1322 
1323 }