Java Code Examples for ucar.nc2.Attribute#getLength()

The following examples show how to use ucar.nc2.Attribute#getLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NcStream.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static NcStreamProto.Attribute.Builder encodeAtt(Attribute att) {
  NcStreamProto.Attribute.Builder attBuilder = NcStreamProto.Attribute.newBuilder();
  attBuilder.setName(att.getShortName());
  attBuilder.setDataType(convertDataType(att.getDataType()));
  attBuilder.setLen(att.getLength());

  // values
  if (att.getLength() > 0) {
    if (att.isString()) {
      for (int i = 0; i < att.getLength(); i++)
        attBuilder.addSdata(att.getStringValue(i));

    } else {
      Array data = att.getValues();
      ByteBuffer bb = data.getDataAsByteBuffer();
      attBuilder.setData(ByteString.copyFrom(bb.array()));
    }
  }

  return attBuilder;
}
 
Example 2
Source File: N3headerWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int sizeAtts(Iterable<Attribute> atts) {
  int size = 8; // magic, natts

  for (Attribute att : atts) {
    size += sizeString(att.getShortName());
    size += 4; // type

    int type = getType(att.getDataType());
    if (type == 2) {
      size += sizeStringValues(att);
    } else {
      size += 4; // nelems
      int nelems = att.getLength();
      int nbytes = 0;
      for (int j = 0; j < nelems; j++)
        nbytes += sizeAttributeValue(att.getNumericValue(j));
      size += nbytes;
      size += padding(nbytes);
    }
  }
  return size;
}
 
Example 3
Source File: ThreddsMetadata.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void setVocabularyId(Attribute id) {
  if (id == null)
    return;
  StringBuilder sbuff = new StringBuilder();
  for (int i = 0; i < id.getLength(); i++) {
    if (i > 0)
      sbuff.append(",");
    sbuff.append(id.getNumericValue(i));
  }
  this.id = sbuff.toString();
}
 
Example 4
Source File: N3headerWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeAtts(Iterable<Attribute> atts, Formatter fout) throws IOException {

    int n = Iterables.size(atts);
    if (n == 0) {
      raf.writeInt(0);
      raf.writeInt(0);
    } else {
      raf.writeInt(MAGIC_ATT);
      raf.writeInt(n);
    }

    int count = 0;
    for (Attribute att : atts) {
      if (fout != null)
        fout.format("***att %d pos= %d%n", count, raf.getFilePointer());

      writeString(att.getShortName());
      int type = getType(att.getDataType());
      raf.writeInt(type);

      if (type == 2) {
        writeStringValues(att);
      } else {
        int nelems = att.getLength();
        raf.writeInt(nelems);
        int nbytes = 0;
        for (int j = 0; j < nelems; j++)
          nbytes += writeAttributeValue(att.getNumericValue(j));
        pad(nbytes, (byte) 0);
        if (fout != null)
          fout.format(" end write val pos= %d%n", raf.getFilePointer());
      }
      if (fout != null)
        fout.format("  %s%n", att);
    }
  }
 
Example 5
Source File: N3headerWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void writeStringValues(Attribute att) throws IOException {
  int n = att.getLength();
  if (n == 1)
    writeString(att.getStringValue());
  else {
    StringBuilder values = new StringBuilder();
    for (int i = 0; i < n; i++)
      values.append(att.getStringValue(i));
    writeString(values.toString());
  }
}
 
Example 6
Source File: N3headerWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private int sizeStringValues(Attribute att) {
  int size = 0;
  int n = att.getLength();
  if (n == 1)
    size += sizeString(att.getStringValue());
  else {
    StringBuilder values = new StringBuilder();
    for (int i = 0; i < n; i++)
      values.append(att.getStringValue(i));
    size += sizeString(values.toString());
  }

  return size;
}
 
Example 7
Source File: VariableWrapper.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Implementation of {@link #getAttributeValue(String)} shared with {@link GroupWrapper}.
 */
static Object getAttributeValue(final Attribute attribute) {
    if (attribute != null) {
        final int length = attribute.getLength();
        switch (length) {
            case 0: break;
            case 1: {
                final Object value = attribute.getValue(0);
                if (value instanceof String) {
                    return Utils.nonEmpty((String) value);
                } else if (value instanceof Number) {
                    return Utils.fixSign((Number) value, attribute.isUnsigned());
                }
                break;
            }
            default: {
                if (attribute.isString()) {
                    boolean hasValues = false;
                    final String[] values = new String[length];
                    for (int i=0; i<length; i++) {
                        values[i] = Utils.nonEmpty(attribute.getStringValue(i));
                        hasValues |= (values[i] != null);
                    }
                    if (hasValues) {
                        return values;
                    }
                } else {
                    final Array array = attribute.getValues();
                    return createDecimalVector(array.get1DJavaArray(array.getElementType()), attribute.isUnsigned());
                }
            }
        }
    }
    return null;
}
 
Example 8
Source File: ADASConvention.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected void augmentDataset(CancelTask cancelTask) throws IOException {
  if (!rootGroup.findVariableLocal("x").isPresent()) {
    return; // check if its already been done - aggregating enhanced datasets.
  }

  // old way without attributes
  Attribute att = rootGroup.getAttributeContainer().findAttribute("MAPPROJ");
  int projType = att.getNumericValue().intValue();

  double lat1 = rootGroup.getAttributeContainer().findAttributeDouble("TRUELAT1", Double.NaN);
  double lat2 = rootGroup.getAttributeContainer().findAttributeDouble("TRUELAT2", Double.NaN);
  double lat_origin = lat1;
  double lon_origin = rootGroup.getAttributeContainer().findAttributeDouble("TRUELON", Double.NaN);
  double false_easting = 0.0;
  double false_northing = 0.0;

  // new way with attributes
  String projName = rootGroup.getAttributeContainer().findAttributeString(CF.GRID_MAPPING_NAME, null);
  if (projName != null) {
    projName = projName.trim();
    lat_origin = rootGroup.getAttributeContainer().findAttributeDouble("latitude_of_projection_origin", Double.NaN);
    lon_origin = rootGroup.getAttributeContainer().findAttributeDouble("longitude_of_central_meridian", Double.NaN);
    false_easting = rootGroup.getAttributeContainer().findAttributeDouble("false_easting", 0.0);
    false_northing = rootGroup.getAttributeContainer().findAttributeDouble("false_northing", 0.0);

    Attribute att2 = rootGroup.getAttributeContainer().findAttributeIgnoreCase("standard_parallel");
    if (att2 != null) {
      lat1 = att2.getNumericValue().doubleValue();
      lat2 = (att2.getLength() > 1) ? att2.getNumericValue(1).doubleValue() : lat1;
    }
  } else {
    if (projType == 2)
      projName = "lambert_conformal_conic";
  }

  Optional<Variable.Builder<?>> coordOpt = rootGroup.findVariableLocal("x_stag");
  if (coordOpt.isPresent()) {
    Variable.Builder<?> coord = coordOpt.get();
    if (!Double.isNaN(false_easting) || !Double.isNaN(false_northing)) {
      String units = coord.getAttributeContainer().findAttributeString(CDM.UNITS, null);
      double scalef = 1.0;
      try {
        scalef = SimpleUnit.getConversionFactor(units, "km");
      } catch (IllegalArgumentException e) {
        log.error(units + " not convertible to km");
      }
      false_easting *= scalef;
      false_northing *= scalef;
    }
  }

  ProjectionImpl proj;
  if ("lambert_conformal_conic".equalsIgnoreCase(projName)) {
    proj = new LambertConformal(lat_origin, lon_origin, lat1, lat2, false_easting, false_northing);
    projCT = new ProjectionCT("Projection", "FGDC", proj);
    if (false_easting == 0.0)
      calcCenterPoints(proj); // old way
  } else {
    parseInfo.format("ERROR: unknown projection type = %s%n", projName);
  }

  if (projCT != null) {
    VariableDS.Builder v = makeCoordinateTransformVariable(projCT);
    v.addAttribute(new Attribute(_Coordinate.AxisTypes, "GeoX GeoY"));
    rootGroup.addVariable(v);
  }

  makeCoordAxis("x");
  makeCoordAxis("y");
  makeCoordAxis("z");

  rootGroup.findVariableLocal("ZPSOIL")
      .ifPresent(vb -> vb.addAttribute(new Attribute(_Coordinate.AxisType, AxisType.GeoZ.toString())));
}
 
Example 9
Source File: Nc4ChunkingStrategy.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected Attribute getChunkAttribute(Variable v) {
  Attribute att = v.findAttribute(CDM.CHUNK_SIZES);
  if (att != null && att.getDataType().isIntegral() && att.getLength() == v.getRank())
    return att;
  return null;
}
 
Example 10
Source File: CDLWriter.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void writeCDL(Attribute att, String parentname) {
  if (strict && (att.isString() || att.getEnumType() != null)) {
    // Force type explicitly for string.
    out.format("string "); // note lower case and trailing blank
  }
  if (strict && parentname != null) {
    out.format(NetcdfFiles.makeValidCDLName(parentname));
  }
  out.format(":");
  out.format("%s", strict ? NetcdfFiles.makeValidCDLName(att.getShortName()) : att.getShortName());
  if (att.isString()) {
    out.format(" = ");
    for (int i = 0; i < att.getLength(); i++) {
      if (i != 0) {
        out.format(", ");
      }
      String val = att.getStringValue(i);
      if (val != null) {
        out.format("\"%s\"", encodeString(val));
      }
    }
  } else if (att.getEnumType() != null) {
    out.format(" = ");
    for (int i = 0; i < att.getLength(); i++) {
      if (i != 0) {
        out.format(", ");
      }
      EnumTypedef en = att.getEnumType();
      String econst = att.getStringValue(i);
      Integer ecint = en.lookupEnumInt(econst);
      if (ecint == null) {
        throw new ForbiddenConversionException("Illegal enum constant: " + econst);
      }
      out.format("\"%s\"", encodeString(econst));
    }
  } else {
    out.format(" = ");
    for (int i = 0; i < att.getLength(); i++) {
      if (i != 0)
        out.format(", ");

      DataType dataType = att.getDataType();
      Number number = att.getNumericValue(i);
      if (dataType.isUnsigned()) {
        // 'number' is unsigned, but will be treated as signed when we print it below, because Java only has signed
        // types. If it is large enough ( >= 2^(BIT_WIDTH-1) ), its most-significant bit will be interpreted as the
        // sign bit, which will result in an invalid (negative) value being printed. To prevent that, we're going
        // to widen the number before printing it.
        number = DataType.widenNumber(number);
      }
      out.format("%s", number);

      if (dataType.isUnsigned()) {
        out.format("U");
      }

      if (dataType == DataType.FLOAT)
        out.format("f");
      else if (dataType == DataType.SHORT || dataType == DataType.USHORT) {
        out.format("S");
      } else if (dataType == DataType.BYTE || dataType == DataType.UBYTE) {
        out.format("B");
      } else if (dataType == DataType.LONG || dataType == DataType.ULONG) {
        out.format("L");
      }
    }
  }
}
 
Example 11
Source File: Grib2ReportPanel.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void doCheckTables(MFile ff, Formatter fm, int[] accum) throws IOException {
  int local = 0;
  int miss = 0;
  int nonop = 0;
  int total = 0;

  try (GridDataset ncfile = GridDataset.open(ff.getPath())) {
    for (GridDatatype dt : ncfile.getGrids()) {
      String currName = dt.getName();
      total++;

      Attribute att = dt.findAttributeIgnoreCase("Grib_Parameter");
      if (att != null && att.getLength() == 3) {
        int discipline = (Integer) att.getValue(0);
        int category = (Integer) att.getValue(1);
        int number = (Integer) att.getValue(2);
        if ((category > 191) || (number > 191)) {
          fm.format("  local parameter (%d %d %d) = %s units=%s %n", discipline, category, number, currName,
              dt.getUnitsString());
          local++;
          continue;
        }

        GribTables.Parameter entry = WmoParamTable.getParameter(discipline, category, number);
        if (entry == null) {
          fm.format("  missing from WMO table (%d %d %d) = %s units=%s %n", discipline, category, number, currName,
              dt.getUnitsString());
          miss++;
          continue;
        }

        if (!entry.getOperationalStatus().equalsIgnoreCase("Operational")) {
          fm.format("  %s parameter = %s (%d %d %d) %n", entry.getOperationalStatus(), currName, discipline, category,
              number);
          nonop++;
        }
      }

    }
  }
  fm.format("total=%d not operational = %d local = %d missing = %d%n", total, nonop, local, miss);
  accum[0] += total;
  accum[1] += nonop;
  accum[2] += local;
  accum[3] += miss;
}