-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathNc4Iosp.java
executable file
·3430 lines (3023 loc) · 123 KB
/
Nc4Iosp.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
package ucar.nc2.jni.netcdf;
import static ucar.nc2.NetcdfFile.IOSP_MESSAGE_GET_NETCDF_FILE_FORMAT;
import static ucar.nc2.jni.netcdf.Nc4prototypes.*;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import ucar.ma2.*;
import ucar.nc2.*;
import ucar.nc2.constants.CDM;
import ucar.nc2.constants.DataFormatType;
import ucar.nc2.iosp.AbstractIOServiceProvider;
import ucar.nc2.iosp.IOServiceProviderWriter;
import ucar.nc2.iosp.IospHelper;
import ucar.nc2.iosp.NCheader;
import ucar.nc2.iosp.hdf4.HdfEos;
import ucar.nc2.iosp.hdf5.H5header;
import ucar.nc2.ffi.netcdf.NetcdfClibrary;
import ucar.nc2.iosp.netcdf4.Nc4;
import ucar.nc2.util.CancelTask;
import ucar.nc2.util.DebugFlags;
import ucar.nc2.util.EscapeStrings;
import ucar.nc2.write.Nc4Chunking;
import ucar.nc2.write.Nc4ChunkingDefault;
import ucar.unidata.io.RandomAccessFile;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;
/**
* IOSP for reading netcdf files through JNA interface to netcdf C library
*
* @author caron
* @see <a href="https://www.unidata.ucar.edu/software/netcdf/docs/netcdf-c.html" />
* @see <a href="http://earthdata.nasa.gov/sites/default/files/field/document/ESDS-RFC-022v1.pdf" />
* @see <a href=
* "https://www.unidata.ucar.edu/software/netcdf/docs/faq.html#How-can-I-convert-HDF5-files-into-netCDF-4-files" />
*
* @deprecated do not use, will be removed in ver 6.
*/
@Deprecated
public class Nc4Iosp extends AbstractIOServiceProvider implements IOServiceProviderWriter {
private static org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(Nc4Iosp.class);
private static org.slf4j.Logger startupLog = org.slf4j.LoggerFactory.getLogger("serverStartup");
public static final boolean DEBUG = false;
public static int NC_TURN_OFF_LOGGING = -1;
public static final String TRANSLATECONTROL = "ucar.translate";
public static final String TRANSLATE_NONE = "none";
public static final String TRANSLATE_NC4 = "nc4";
private static Nc4prototypes nc4 = NetcdfClibrary.getForeignFunctionInterface();
// TODO: These flags currently control debug messages that are printed to STDOUT. They ought to be logged to SLF4J.
// We could use SLF4J markers to filter which debug-level messages are printed.
// See http://stackoverflow.com/questions/12201112/can-i-add-custom-levels-to-slf4j
private static final boolean debugCompound = false;
private static final boolean debugCompoundAtt = false;
private static final boolean debugDim = false;
private static final boolean debugUserTypes = false;
private static final boolean debugWrite = false;
// if the default charset being used by java isn't UTF-8, then we will
// need to transcode any string read into netCDf-Java via netCDF-C
private static final boolean transcodeStrings = Charset.defaultCharset() != StandardCharsets.UTF_8;
/**
* set the path and name of the netcdf c library.
* must be called before load() is called.
*
* @param jnaPath path to shared libraries
* @param libName library name
* @deprecated use NetcdfClibrary.setLibraryNameAndPath
*/
@Deprecated
public static void setLibraryAndPath(String jnaPath, String libName) {
NetcdfClibrary.setLibraryNameAndPath(jnaPath, libName);
}
/**
* Test if the netcdf C library is present and loaded.
*
* @return true if present
* @deprecated use NetcdfClibrary.isLibraryPresent
*/
@Deprecated
public static synchronized boolean isClibraryPresent() {
return NetcdfClibrary.isLibraryPresent();
}
/** @deprecated use NetcdfClibrary.getNativeInterface */
@Deprecated
public static synchronized Nc4prototypes getCLibrary() {
return nc4;
}
/**
* Set the log level for loaded library.
* Do nothing if set_log_level is not available.
*
* @deprecated use NetcdfClibrary.setLogLevel
*/
@Deprecated
public static synchronized int setLogLevel(int level) {
return NetcdfClibrary.setLogLevel(level);
}
private static boolean useHdfEos = true;
public static void useHdfEos(boolean val) {
useHdfEos = val;
}
public static void setDebugFlags(DebugFlags flags) {}
//////////////////////////////////////////////////
// Instance Variables
private NetcdfFileWriter.Version version; // can use c library to create these different version files
private boolean fill = true;
private int ncid = -1; // file id
private int format; // from nc_inq_format
private boolean isClosed;
private Map<Integer, UserType> userTypes = new HashMap<>(); // hash by typeid
private Map<Group, Integer> groupHash = new HashMap<>(); // group -> nc4 grpid
private Nc4Chunking chunker = new Nc4ChunkingDefault();
private boolean isEos;
private boolean markreserved;
//////////////////////////////////////////////////
// Constructor(s)
public Nc4Iosp() {
this(NetcdfFileWriter.Version.netcdf4); // ensure the version always has a value
}
public Nc4Iosp(NetcdfFileWriter.Version version) {
this.version = version;
}
// called by reflection from NetcdfFileWriter
public void setChunker(Nc4Chunking chunker) {
if (chunker != null)
this.chunker = chunker;
}
/**
* Checks whether {@code raf} is a valid file NetCDF-4 file. Actually, it checks whether it is a valid HDF-5 file of
* any type. Furthermore, it checks whether the NetCDF C library is available on the system. If both conditions are
* satisfied, this method returns {@code true}; otherwise it returns {@code false}.
*
* @param raf a file on disk.
* @return {@code true} if {@code raf} is a valid HDF-5 file and the NetCDF C library is available.
* @throws IOException if an I/O error occurs.
*/
@Override
public boolean isValidFile(RandomAccessFile raf) throws IOException {
int format = NCheader.checkFileType(raf);
boolean valid = false;
switch (format) {
case NCheader.NC_FORMAT_NETCDF4:
case NCheader.NC_FORMAT_64BIT_DATA:
valid = true;
break;
default:
break;// everything else is invalid
}
if (valid) {
if (isClibraryPresent()) {
return true;
} else {
log.debug("File is valid but the NetCDF-4 native library isn't installed: {}", raf.getLocation());
}
}
return false;
}
// 2016-06-06 note: Once netcdf-c v4.4.1 is released, we should be able to return much better information from
// getFileTypeDescription(), getFileTypeId(), and getFileTypeVersion() (inherited from superclass).
// See https://goo.gl/pSP1Bq
@Override
public String getFileTypeDescription() {
return "Netcdf/JNI: " + version;
}
@Override
public String getFileTypeId() {
if (isEos)
return "HDF5-EOS";
return version.isNetdf4format() ? DataFormatType.NETCDF4.getDescription() : DataFormatType.HDF5.getDescription();
}
@Override
public String getFileTypeVersion() {
// TODO this only works for files writtten by netcdf4 c library. what about plain hdf5?
return ncfile.getRootGroup().findAttributeString(CDM.NCPROPERTIES, "N/A");
}
@Override
public void close() throws IOException {
if (isClosed)
return;
if (ncid < 0)
return;
int ret = nc4.nc_close(ncid);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
isClosed = true;
}
@Override
public void open(RandomAccessFile raf, NetcdfFile ncfile, CancelTask cancelTask) throws IOException {
super.open(raf, ncfile, cancelTask);
_open(raf, ncfile, true);
}
@Override
public void openForWriting(ucar.unidata.io.RandomAccessFile raf, ucar.nc2.NetcdfFile ncfile,
ucar.nc2.util.CancelTask cancelTask) throws IOException {
this.ncfile = ncfile;
_open(raf, ncfile, false);
}
private void _open(RandomAccessFile raf, NetcdfFile ncfile, boolean readOnly) throws IOException {
if (!isClibraryPresent()) {
throw new UnsupportedOperationException("Couldn't load NetCDF C library (see log for details).");
}
if (raf != null)
raf.close(); // not used
// open
// netcdf-c can't handle "file:" prefix. Must remove it.
String location = NetcdfFiles.canonicalizeUriString(ncfile.getLocation());
log.debug("open {}", location);
IntByReference ncidp = new IntByReference();
int ret = nc4.nc_open(location, readOnly ? NC_NOWRITE : NC_WRITE, ncidp);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
isClosed = false;
ncid = ncidp.getValue();
// format
IntByReference formatp = new IntByReference();
ret = nc4.nc_inq_format(ncid, formatp);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
format = formatp.getValue();
log.debug("open {} id={} format={}", ncfile.getLocation(), ncid, format);
// read root group
makeGroup(new Group4(ncid, ncfile.getRootGroup(), null));
// check if its an HDF5-EOS file
Group eosInfo = ncfile.getRootGroup().findGroupLocal(HdfEos.HDF5_GROUP);
if (eosInfo != null && useHdfEos) {
isEos = HdfEos.amendFromODL(ncfile, eosInfo);
}
ncfile.finish();
}
private void makeGroup(Group4 g4) throws IOException {
groupHash.put(g4.g, g4.grpid);
makeDimensions(g4);
makeUserTypes(g4.grpid, g4.g);
// group attributes
IntByReference ngattsp = new IntByReference();
int ret = nc4.nc_inq_natts(g4.grpid, ngattsp);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
List<Attribute> gatts = makeAttributes(g4.grpid, Nc4prototypes.NC_GLOBAL, ngattsp.getValue(), null);
for (Attribute att : gatts) {
ncfile.addAttribute(g4.g, att);
log.debug(" add Global Attribute {}", att);
}
makeVariables(g4);
if (format == Nc4prototypes.NC_FORMAT_NETCDF4) {
// read subordinate groups
IntByReference numgrps = new IntByReference();
ret = nc4.nc_inq_grps(g4.grpid, numgrps, null);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
int[] group_ids = new int[numgrps.getValue()];
ret = nc4.nc_inq_grps(g4.grpid, numgrps, group_ids);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
for (int group_id : group_ids) {
byte[] name = new byte[Nc4prototypes.NC_MAX_NAME + 1];
ret = nc4.nc_inq_grpname(group_id, name);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
Group child = new Group(ncfile, g4.g, makeString(name));
g4.g.addGroup(child);
makeGroup(new Group4(group_id, child, g4));
}
}
}
private void makeDimensions(Group4 g4) throws IOException {
// We need this in order to allocate the correct length for dimIdsInGroup.
IntByReference numDimsInGoup_p = new IntByReference();
int ret = nc4.nc_inq_ndims(g4.grpid, numDimsInGoup_p);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
IntByReference numDimidsInGroup_p = new IntByReference();
int[] dimIdsInGroup = new int[numDimsInGoup_p.getValue()];
ret = nc4.nc_inq_dimids(g4.grpid, numDimidsInGroup_p, dimIdsInGroup, 0);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
assert numDimsInGoup_p.getValue() == numDimidsInGroup_p.getValue() : String.format(
"Number of dimensions in group (%s) differed from number of dimension IDs in group (%s).",
numDimsInGoup_p.getValue(), numDimidsInGroup_p.getValue());
// We need this in order to allocate the correct length for unlimitedDimIdsInGroup.
IntByReference numUnlimitedDimsInGroup_p = new IntByReference();
ret = nc4.nc_inq_unlimdims(g4.grpid, numUnlimitedDimsInGroup_p, null);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
int[] unlimitedDimIdsInGroup = new int[numUnlimitedDimsInGroup_p.getValue()];
ret = nc4.nc_inq_unlimdims(g4.grpid, numUnlimitedDimsInGroup_p, unlimitedDimIdsInGroup);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
// Ensure array is sorted so that we can use binarySearch on it.
Arrays.sort(unlimitedDimIdsInGroup);
for (int dimId : dimIdsInGroup) {
byte[] dimNameBytes = new byte[Nc4prototypes.NC_MAX_NAME + 1];
SizeTByReference dimLength_p = new SizeTByReference();
ret = nc4.nc_inq_dim(g4.grpid, dimId, dimNameBytes, dimLength_p);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
String dimName = makeString(dimNameBytes);
boolean isUnlimited = Arrays.binarySearch(unlimitedDimIdsInGroup, dimId) >= 0;
Dimension dimension = new Dimension(dimName, dimLength_p.getValue().intValue(), true, isUnlimited, false);
ncfile.addDimension(g4.g, dimension);
log.debug("add Dimension {} ({})", dimension, dimId);
}
}
private void updateDimensions(Group g) throws IOException {
int grpid = groupHash.get(g);
IntByReference nunlimdimsp = new IntByReference();
int[] unlimdimids = new int[Nc4prototypes.NC_MAX_DIMS];
int ret = nc4.nc_inq_unlimdims(grpid, nunlimdimsp, unlimdimids);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
int ndims = nunlimdimsp.getValue();
for (int i = 0; i < ndims; i++) {
byte[] name = new byte[Nc4prototypes.NC_MAX_NAME + 1];
SizeTByReference lenp = new SizeTByReference();
ret = nc4.nc_inq_dim(grpid, unlimdimids[i], name, lenp);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
String dname = makeString(name);
Dimension d = g.findDimension(dname);
if (d == null)
throw new IllegalStateException("Cant find dimension " + dname);
if (!d.isUnlimited())
throw new IllegalStateException("dimension " + dname + " should be unlimited");
// TODO udim.setLength : need UnlimitedDimension extends Dimension?
int len = lenp.getValue().intValue();
if (len != d.getLength()) {
d.setLength(len);
// must update all variables that use this dimension
for (Variable var : g.getVariables()) {
if (contains(var.getDimensions(), d)) {
var.resetShape();
var.invalidateCache();
}
}
}
}
// recurse
for (Group child : g.getGroups())
updateDimensions(child);
}
// must check by name, not object equality
private boolean contains(List<Dimension> dims, Dimension want) {
for (Dimension have : dims) {
if (have.getShortName().equals(want.getShortName()))
return true;
}
return false;
}
/**
* By default, JNA assumes strings coming into java from the C side are using
* the system encoding. However, netCDF-C encodes using UTF-8. Because of this,
* if we are on a platform where java is not using UTF-8 as the default encoding,
* we will need to transcode the incoming strings fix the incorrect assumption
* made by JNA.
*
* Note, we could set the system property jna.encode=UTF-8, but would impact the
* behavior of other libraries that use JNA, and would not be very nice of us to
* set globally (and often times isn't the right thing to set anyways, since the
* default in C to use the system encoding).
*
* @param systemStrings String array encoded using the default charset
* @return String array encoded using the UTF-8 charset
*/
private String[] transcodeString(String[] systemStrings) {
return Arrays.stream(systemStrings).map(systemString -> {
byte[] byteArray = systemString.getBytes(Charset.defaultCharset());
return new String(byteArray, StandardCharsets.UTF_8);
}).toArray(String[]::new);
}
private String makeString(byte[] b) {
// null terminates
int count = 0;
while (count < b.length) {
if (b[count] == 0)
break;
count++; // dont include the terminating 0
}
// copy if its small
if (count < b.length / 2) {
byte[] bb = new byte[count];
System.arraycopy(b, 0, bb, 0, count);
b = bb;
}
return new String(b, 0, count, StandardCharsets.UTF_8); // all strings are considered to be UTF-8 unicode.
}
// follow what happens in the Java side
private String makeAttString(byte[] b) {
// null terminates
int count = 0;
while (count < b.length) {
if (b[count] == 0)
break;
count++; // dont include the terminating 0
}
return new String(b, 0, count, StandardCharsets.UTF_8); // all strings are considered to be UTF-8 unicode.
}
private List<Attribute> makeAttributes(int grpid, int varid, int natts, Variable v) throws IOException {
List<Attribute> result = new ArrayList<>(natts);
for (int attnum = 0; attnum < natts; attnum++) {
byte[] name = new byte[Nc4prototypes.NC_MAX_NAME + 1];
int ret = nc4.nc_inq_attname(grpid, varid, attnum, name);
if (ret != 0)
throw new IOException(nc4.nc_strerror(ret) + " varid=" + varid + " attnum=" + attnum);
String attname = makeString(name);
IntByReference xtypep = new IntByReference();
ret = nc4.nc_inq_atttype(grpid, varid, attname, xtypep);
if (ret != 0)
throw new IOException(nc4.nc_strerror(ret) + " varid=" + varid + "attnum=" + attnum);
/*
* xtypep : Pointer to location for returned attribute type,
* one of the set of predefined netCDF external data types.
* The type of this parameter, nc_type, is defined in the netCDF
* header file. The valid netCDF external data types are
* NC_BYTE, NC_CHAR, NC_SHORT, NC_INT, NC_FLOAT, and NC_DOUBLE.
* If this parameter is given as '0' (a null pointer), no type
* will be returned so no variable to hold the type needs to be declared.
*/
int type = xtypep.getValue();
SizeTByReference lenp = new SizeTByReference();
ret = nc4.nc_inq_attlen(grpid, varid, attname, lenp);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
int len = lenp.getValue().intValue();
// deal with empty attributes
if (len == 0) {
Attribute att;
switch (type) {
case Nc4prototypes.NC_BYTE:
att = new Attribute(attname, DataType.BYTE);
break;
case Nc4prototypes.NC_UBYTE:
att = new Attribute(attname, DataType.UBYTE);
break;
case Nc4prototypes.NC_CHAR:
// From what I can tell, the way we should treat char attrs depends on
// the netCDF format used (3 vs. 4)
if ((format == NC_FORMAT_NETCDF4_CLASSIC) || (format == NC_FORMAT_NETCDF4)) {
// if netcdf4, make null char attrs null string attrs
att = new Attribute(attname, DataType.STRING);
} else {
// all others, treat null char attrs as empty string attrs
att = new Attribute(attname, "");
}
break;
case Nc4prototypes.NC_DOUBLE:
att = new Attribute(attname, DataType.DOUBLE);
break;
case Nc4prototypes.NC_FLOAT:
att = new Attribute(attname, DataType.FLOAT);
break;
case Nc4prototypes.NC_INT:
att = new Attribute(attname, DataType.INT);
break;
case Nc4prototypes.NC_UINT:
att = new Attribute(attname, DataType.UINT);
break;
case Nc4prototypes.NC_UINT64:
att = new Attribute(attname, DataType.ULONG);
break;
case Nc4prototypes.NC_INT64:
att = new Attribute(attname, DataType.LONG);
break;
case Nc4prototypes.NC_USHORT:
att = new Attribute(attname, DataType.USHORT);
break;
case Nc4prototypes.NC_SHORT:
att = new Attribute(attname, DataType.SHORT);
break;
case Nc4prototypes.NC_STRING:
att = new Attribute(attname, DataType.STRING);
break;
default:
log.warn("Unsupported attribute data type == " + type);
continue;
}
result.add(att);
continue; // avoid reading the values since there are none.
}
// read the att values
Array values = null;
switch (type) {
case Nc4prototypes.NC_UBYTE:
byte[] valbu = new byte[len];
ret = nc4.nc_get_att_uchar(grpid, varid, attname, valbu);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.UBYTE, new int[] {len}, valbu);
break;
case Nc4prototypes.NC_BYTE:
byte[] valb = new byte[len];
ret = nc4.nc_get_att_schar(grpid, varid, attname, valb);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.BYTE, new int[] {len}, valb);
break;
case Nc4prototypes.NC_CHAR:
byte[] text = new byte[len];
ret = nc4.nc_get_att_text(grpid, varid, attname, text);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
Attribute att = new Attribute(attname, makeAttString(text));
result.add(att);
break;
case Nc4prototypes.NC_DOUBLE:
double[] vald = new double[len];
ret = nc4.nc_get_att_double(grpid, varid, attname, vald);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.DOUBLE, new int[] {len}, vald);
break;
case Nc4prototypes.NC_FLOAT:
float[] valf = new float[len];
ret = nc4.nc_get_att_float(grpid, varid, attname, valf);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.FLOAT, new int[] {len}, valf);
break;
case Nc4prototypes.NC_UINT:
int[] valiu = new int[len];
ret = nc4.nc_get_att_uint(grpid, varid, attname, valiu);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.UINT, new int[] {len}, valiu);
break;
case Nc4prototypes.NC_INT:
int[] vali = new int[len];
ret = nc4.nc_get_att_int(grpid, varid, attname, vali);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.INT, new int[] {len}, vali);
break;
case Nc4prototypes.NC_UINT64:
long[] vallu = new long[len];
ret = nc4.nc_get_att_ulonglong(grpid, varid, attname, vallu);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.ULONG, new int[] {len}, vallu);
break;
case Nc4prototypes.NC_INT64:
long[] vall = new long[len];
ret = nc4.nc_get_att_longlong(grpid, varid, attname, vall);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.LONG, new int[] {len}, vall);
break;
case Nc4prototypes.NC_USHORT:
short[] valsu = new short[len];
ret = nc4.nc_get_att_ushort(grpid, varid, attname, valsu);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.USHORT, new int[] {len}, valsu);
break;
case Nc4prototypes.NC_SHORT:
short[] vals = new short[len];
ret = nc4.nc_get_att_short(grpid, varid, attname, vals);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
values = Array.factory(DataType.SHORT, new int[] {len}, vals);
break;
case Nc4prototypes.NC_STRING:
String[] valss = new String[len];
ret = nc4.nc_get_att_string(grpid, varid, attname, valss);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
if (transcodeStrings) {
valss = transcodeString(valss);
}
values = Array.factory(DataType.STRING, new int[] {len}, valss);
break;
default:
UserType userType = userTypes.get(type);
if (userType == null) {
log.warn("Unsupported attribute data type == " + type);
continue;
} else if (userType.typeClass == Nc4prototypes.NC_ENUM) {
result.add(readEnumAttValues(grpid, varid, attname, len, userType));
continue;
} else if (userType.typeClass == Nc4prototypes.NC_OPAQUE) {
result.add(readOpaqueAttValues(grpid, varid, attname, len, userType));
continue;
} else if (userType.typeClass == Nc4prototypes.NC_VLEN) {
values = readVlenAttValues(grpid, varid, attname, len, userType);
} else if (userType.typeClass == Nc4prototypes.NC_COMPOUND) {
readCompoundAttValues(grpid, varid, attname, len, userType, result, v);
continue;
} else {
log.warn("Unsupported attribute data type == " + userType);
continue;
}
}
if (values != null) {
Attribute att = new Attribute(attname, values);
result.add(att);
}
}
return result;
}
private Array readVlenAttValues(int grpid, int varid, String attname, int len, UserType userType) throws IOException {
Nc4prototypes.Vlen_t[] vlen = new Nc4prototypes.Vlen_t[len];
int ret = nc4.nc_get_att(grpid, varid, attname, vlen); // vlen
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
int count = 0;
for (int i = 0; i < len; i++)
count += vlen[i].len;
switch (userType.baseTypeid) {
case Nc4prototypes.NC_INT:
Array intArray = Array.factory(DataType.INT, new int[] {count});
IndexIterator iter = intArray.getIndexIterator();
for (int i = 0; i < len; i++) {
// Coverity[FB.UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD]
int[] ba = vlen[i].p.getIntArray(0, vlen[i].len);
for (int aBa : ba) {
iter.setIntNext(aBa);
}
}
return intArray;
case Nc4prototypes.NC_FLOAT:
Array fArray = Array.factory(DataType.FLOAT, new int[] {count});
iter = fArray.getIndexIterator();
for (int i = 0; i < len; i++) {
// Coverity[FB.NP_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD]
float[] ba = vlen[i].p.getFloatArray(0, vlen[i].len);
for (float aBa : ba)
iter.setFloatNext(aBa);
}
return fArray;
}
return null;
}
private Attribute readEnumAttValues(int grpid, int varid, String attname, int len, UserType userType)
throws IOException {
int ret;
DataType dtype = convertDataType(userType.baseTypeid).dt;
int elemSize = dtype.getSize();
byte[] bbuff = new byte[len * elemSize];
ret = nc4.nc_get_att(grpid, varid, attname, bbuff);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
ByteBuffer bb = ByteBuffer.wrap(bbuff);
Array data = null;
if (false) {
/*
* This is incorrect; CDM technically does not support
* enum valued attributes (see Attribute.java).
*/
data = convertByteBuffer(bb, userType.baseTypeid, new int[] {len});
} else {
/*
* So, instead use the EnumTypedef to convert to econsts
* and store as strings.
*/
String[] econsts = new String[len];
EnumTypedef en = userType.e;
for (int i = 0; i < len; i++) {
long lval = 0;
switch (en.getBaseType()) {
case ENUM1:
lval = bb.get(i);
break;
case ENUM2:
lval = bb.getShort(i);
break;
case ENUM4:
lval = bb.getInt(i);
break;
}
int ival = (int) lval;
String name = en.lookupEnumString(ival);
if (name == null) {
name = "Unknown enum value=" + ival;
}
econsts[i] = name;
}
data = Array.factory(DataType.STRING, new int[] {len}, econsts);
}
Attribute a = new Attribute(attname, data);
a.setEnumType(userType.e);
return a;
}
private Array convertByteBuffer(ByteBuffer bb, int baseType, int[] shape) throws IOException {
switch (baseType) {
case Nc4prototypes.NC_BYTE:
return Array.factory(DataType.BYTE, shape, bb.array());
case Nc4prototypes.NC_UBYTE:
return Array.factory(DataType.UBYTE, shape, bb.array());
case Nc4prototypes.NC_SHORT:
return Array.factory(DataType.SHORT, shape, bb.asShortBuffer().array());
case Nc4prototypes.NC_USHORT:
return Array.factory(DataType.USHORT, shape, bb.asShortBuffer().array());
case Nc4prototypes.NC_INT:
return Array.factory(DataType.INT, shape, bb.asIntBuffer().array());
case Nc4prototypes.NC_UINT:
return Array.factory(DataType.UINT, shape, bb.asIntBuffer().array());
case Nc4prototypes.NC_INT64:
return Array.factory(DataType.LONG, shape, bb.asLongBuffer().array());
case Nc4prototypes.NC_UINT64:
return Array.factory(DataType.ULONG, shape, bb.asLongBuffer().array());
}
throw new IllegalArgumentException("Illegal type=" + baseType);
}
private Attribute readOpaqueAttValues(int grpid, int varid, String attname, int len, UserType userType)
throws IOException {
int total = len * userType.size;
byte[] bb = new byte[total];
int ret = nc4.nc_get_att(grpid, varid, attname, bb);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
return new Attribute(attname, Array.factory(DataType.BYTE, new int[] {total}, bb));
}
private void readCompoundAttValues(int grpid, int varid, String attname, int len, UserType userType,
List<Attribute> result, Variable v) throws IOException {
int buffSize = len * userType.size;
byte[] bb = new byte[buffSize];
int ret = nc4.nc_get_att(grpid, varid, attname, bb);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
ByteBuffer bbuff = ByteBuffer.wrap(bb);
decodeCompoundData(len, userType, bbuff);
// if its a Structure, distribute to matching fields
if (v instanceof Structure) {
Structure s = (Structure) v;
for (Field fld : userType.flds) {
Variable mv = s.findVariable(fld.name);
if (mv != null)
mv.addAttribute(new Attribute(attname, fld.data));
else
result.add(new Attribute(attname + "." + fld.name, fld.data));
}
} else {
for (Field fld : userType.flds)
result.add(new Attribute(attname + "." + fld.name, fld.data));
}
}
// LOOK: placing results in the fld of the userType - ok for production ??
private void decodeCompoundData(int len, UserType userType, ByteBuffer bbuff) throws IOException {
bbuff.order(ByteOrder.LITTLE_ENDIAN);
for (Field fld : userType.flds) {
ConvertedType ct = convertDataType(fld.fldtypeid);
if (fld.fldtypeid == Nc4prototypes.NC_CHAR) {
fld.data = Array.factory(DataType.STRING, new int[] {len}); // LOOK ??
} else if (ct.isVlen) {
// fld.data = Array.makeObjectArray(ct.dt, ct.dt.getPrimitiveClassType(), new int[]{len}, null);
// fld.data = Array.makeVlenArray(ct.dt, ct.dt.getPrimitiveClassType(), new int[]{len}, null); LOOK BAD
} else {
fld.data = Array.factory(ct.dt, new int[] {len});
}
}
for (int i = 0; i < len; i++) {
int record_start = i * userType.size;
for (Field fld : userType.flds) {
int pos = record_start + fld.offset;
switch (fld.fldtypeid) {
case Nc4prototypes.NC_CHAR:
// copy bytes out of buffer, make into a String object
int blen = 1;
if (fld.dims != null) {
Section s = new Section(fld.dims);
blen = (int) s.computeSize();
}
byte[] dst = new byte[blen];
bbuff.get(dst, 0, blen);
String cval = makeAttString(dst);
fld.data.setObject(i, cval);
if (debugCompoundAtt)
System.out.println("result= " + cval);
continue;
case Nc4prototypes.NC_UBYTE:
case Nc4prototypes.NC_BYTE:
byte bval = bbuff.get(pos);
if (debugCompoundAtt)
System.out.println("bval= " + bval);
fld.data.setByte(i, bval);
continue;
case Nc4prototypes.NC_USHORT:
case Nc4prototypes.NC_SHORT:
short sval = bbuff.getShort(pos);
if (debugCompoundAtt)
System.out.println("sval= " + sval);
fld.data.setShort(i, sval);
continue;
case Nc4prototypes.NC_UINT:
case Nc4prototypes.NC_INT:
int ival = bbuff.getInt(pos);
if (debugCompoundAtt)
System.out.println("ival= " + ival);
fld.data.setInt(i, ival);
continue;
case Nc4prototypes.NC_UINT64:
case Nc4prototypes.NC_INT64:
long lval = bbuff.getLong(pos);
if (debugCompoundAtt)
System.out.println("lval= " + lval);
fld.data.setLong(i, lval);
continue;
case Nc4prototypes.NC_FLOAT:
float fval = bbuff.getFloat(pos);
if (debugCompoundAtt)
System.out.println("fval= " + fval);
fld.data.setFloat(i, fval);
continue;
case Nc4prototypes.NC_DOUBLE:
double dval = bbuff.getDouble(pos);
if (debugCompoundAtt)
System.out.println("dval= " + dval);
fld.data.setDouble(i, dval);
continue;
case Nc4prototypes.NC_STRING:
lval = getNativeAddr(pos, bbuff);
Pointer p = new Pointer(lval);
String strval = p.getString(0, CDM.UTF8);
fld.data.setObject(i, strval);
if (debugCompoundAtt)
System.out.println("result= " + strval);
continue;
default:
UserType subUserType = userTypes.get(fld.fldtypeid);
if (subUserType == null) {
throw new IOException("Unknown compound user type == " + fld);
} else if (subUserType.typeClass == Nc4prototypes.NC_ENUM) {
// WTF ?
} else if (subUserType.typeClass == Nc4prototypes.NC_VLEN) {
decodeVlenField(fld, subUserType, pos, i, bbuff);
break;
} else if (subUserType.typeClass == Nc4prototypes.NC_OPAQUE) {
// return readOpaque(grpid, varid, len, userType.size);
} else if (subUserType.typeClass == Nc4prototypes.NC_COMPOUND) {
// return readCompound(grpid, varid, len, userType);
}
log.warn("UNSUPPORTED compound fld.fldtypeid= " + fld.fldtypeid);
} // switch on fld type
} // loop over fields
} // loop over len
}
/////////////////////////////////////////////////////////////////////////////
private void makeVariables(Group4 g4) throws IOException {
IntByReference nvarsp = new IntByReference();
int ret = nc4.nc_inq_nvars(g4.grpid, nvarsp);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
int nvars = nvarsp.getValue();
log.debug("nvars= {}", nvars);
int[] varids = new int[nvars];
ret = nc4.nc_inq_varids(g4.grpid, nvarsp, varids);
if (ret != 0)
throw new IOException(ret + ": " + nc4.nc_strerror(ret));
for (int i = 0; i < varids.length; i++) {
int varno = varids[i];
if (varno != i)
log.error("makeVariables varno={} is not equal to {}", varno, i);
byte[] name = new byte[Nc4prototypes.NC_MAX_NAME + 1];
IntByReference xtypep = new IntByReference();
IntByReference ndimsp = new IntByReference();
int[] dimids = new int[Nc4prototypes.NC_MAX_DIMS];
IntByReference nattsp = new IntByReference();
ret = nc4.nc_inq_var(g4.grpid, varno, name, xtypep, ndimsp, dimids, nattsp);
if (ret != 0)
throw new IOException(nc4.nc_strerror(ret));
// figure out the datatype
int typeid = xtypep.getValue();
// DataType dtype = convertDataType(typeid).dt;
String vname = makeString(name);
Vinfo vinfo = new Vinfo(g4, varno, typeid);