Skip to content

Commit

Permalink
Merge pull request #1213 from haileyajohnson/max-size
Browse files Browse the repository at this point in the history
add check size to builder to fail faster
  • Loading branch information
haileyajohnson committed Jul 13, 2023
2 parents 57c8c7a + 9507546 commit a821e25
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -155,14 +155,14 @@ private Result writeFile(CoverageCollection gdsOrg, List<String> gridNames, Subs
}
addCFAnnotations(subsetDataset, rootGroup, shouldAddLatLon2D);

// test if its too large
long totalSizeOfVars = writer.calcSize();
if (maxBytes > 0 && totalSizeOfVars > maxBytes) {
return Result.create(totalSizeOfVars, false, TOO_LARGE_MESSAGE);
}

// Actually create file and write variable data to it.
try (NetcdfFormatWriter ncwriter = writer.build()) {
// test if its too large
long totalSizeOfVars = ncwriter.calcSize();
if (maxBytes > 0 && totalSizeOfVars > maxBytes) {
return Result.create(totalSizeOfVars, false, TOO_LARGE_MESSAGE);
}

writeCoordinateData(subsetDataset, ncwriter);
writeCoverageData(gdsOrg, subsetParams, subsetDataset, ncwriter);

Expand Down
16 changes: 16 additions & 0 deletions cdm/core/src/main/java/ucar/nc2/write/NetcdfFormatWriter.java
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,22 @@ public Structure.Builder addStructure(String shortName, String dimString) {
return vb;
}

public long calcSize() {
return calcSize(this.rootGroup);
}

// Note that we have enough info to try to estimate effects of compression, if its a Netcdf4 file.
private long calcSize(Group.Builder group) {
long totalSizeOfVars = 0;
for (Variable.Builder var : this.rootGroup.vbuilders) {
totalSizeOfVars += Dimensions.getSize(var.getDimensions()) * var.getElementSize();
}
for (Group.Builder nested : group.gbuilders) {
totalSizeOfVars += calcSize(nested);
}
return totalSizeOfVars;
}

/** Once this is called, do not use the Builder again. */
public NetcdfFormatWriter build() throws IOException {
return new NetcdfFormatWriter(this);
Expand Down

0 comments on commit a821e25

Please sign in to comment.