Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add check size to builder to fail faster #1213

Merged
merged 2 commits into from
Jul 13, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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