Java Code Examples for java.util.Formatter#toString()

The following examples show how to use java.util.Formatter#toString() . 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: StandardXYZItemLabelGenerator.java    From orson-charts with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a label for the specified data item.
 * 
 * @param dataset  the dataset ({@code null} not permitted).
 * @param seriesKey  the series key ({@code null} not permitted).
 * 
 * @return The series label (possibly {@code null}). 
 */
@Override @SuppressWarnings("unchecked")
public String generateItemLabel(XYZDataset dataset, 
        Comparable<?> seriesKey, int itemIndex) {
    Args.nullNotPermitted(dataset, "dataset");
    Args.nullNotPermitted(seriesKey, "seriesKey");
    if (this.itemSelection != null) {
        XYZItemKey key = new XYZItemKey(seriesKey, itemIndex);
        if (!this.itemSelection.isSelected(key)) {
            return null;
        }
    }
    int seriesIndex = dataset.getSeriesIndex(seriesKey);
    Formatter formatter = new Formatter(new StringBuilder());
    double x = dataset.getX(seriesIndex, itemIndex);
    double y = dataset.getY(seriesIndex, itemIndex);
    double z = dataset.getZ(seriesIndex, itemIndex);
    formatter.format(this.template, seriesKey, x, y, z);
    String result = formatter.toString();
    formatter.close();
    return result;
}
 
Example 2
Source File: AbstractVector.java    From matrix-toolkits-java with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String toString() {
    // Output into coordinate format. Indices start from 1 instead of 0
    Formatter out = new Formatter();

    out.format("%10d %19d\n", size, Matrices.cardinality(this));

    int i = 0;
    for (VectorEntry e : this) {
        if (e.get() != 0)
            out.format("%10d % .12e\n", e.index() + 1, e.get());
        if (++i == 100) {
            out.format("...\n");
            break;
        }
    }

    return out.toString();
}
 
Example 3
Source File: WriterCFPointCollection.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void writeHeader(PointFeature pf) throws IOException {
  List<VariableSimpleIF> coords = new ArrayList<>();
  coords.add(VariableSimpleBuilder.makeScalar(timeName, "time of measurement", timeUnit.getUdUnit(), DataType.DOUBLE)
      .addAttribute(CF.CALENDAR, timeUnit.getCalendar().toString()).build());

  coords.add(
      VariableSimpleBuilder.makeScalar(latName, "latitude of measurement", CDM.LAT_UNITS, DataType.DOUBLE).build());
  coords.add(
      VariableSimpleBuilder.makeScalar(lonName, "longitude of measurement", CDM.LON_UNITS, DataType.DOUBLE).build());
  Formatter coordNames = new Formatter().format("%s %s %s", timeName, latName, lonName);
  if (altUnits != null) {
    coords.add(VariableSimpleBuilder.makeScalar(altName, "altitude of measurement", altUnits, DataType.DOUBLE)
        .addAttribute(CF.POSITIVE, CF1Convention.getZisPositive(altName, altUnits)).build());
    coordNames.format(" %s", altName);
  }

  super.writeHeader(coords, null, null, pf.getDataAll(), coordNames.toString());
}
 
Example 4
Source File: CatOLog.java    From c5-replicator with Apache License 2.0 6 votes vote down vote up
private static String formatEntry(OLogEntryDescription entry) {
  StringBuilder sb = new StringBuilder();
  Formatter formatter = new Formatter(sb, Locale.US);

  formatter.format(" [term: %" + LONG_DIGITS + "d]", entry.getElectionTerm());
  formatter.format(" [seq: %" + LONG_DIGITS + "d]", entry.getSeqNum());

  formatContent(formatter, entry);

  if (!entry.isHeaderCrcValid()) {
    formatter.format(" <invalid header CRC>");
  }

  if (!entry.isContentCrcValid()) {
    formatter.format(" <invalid content CRC>");
  }

  return formatter.toString();
}
 
Example 5
Source File: FileUtils.java    From YTPlayer with GNU General Public License v3.0 6 votes vote down vote up
public static String SHA1(InputStream is) {
    try {
        MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        for (int read; (read = is.read(buffer)) != -1; ) {
            messageDigest.update(buffer, 0, read);
        }

        Formatter formatter = new Formatter();
        // Convert the byte to hex format
        for (final byte b : messageDigest.digest()) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    } catch (NoSuchAlgorithmException | IOException e) {
        android.util.Log.e(TAG,e.getMessage());
    } finally {
        YTutils.close(is);
    }
    return null;
}
 
Example 6
Source File: Ncdump.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Print StructureData to returned String. */
public static String printStructureData(StructureData sdata) {
  Formatter out = new Formatter();
  for (StructureMembers.Member m : sdata.getMembers()) {
    Array memData = sdata.getArray(m);
    if (memData instanceof ArrayChar) {
      out.format("%s", ((ArrayChar) memData).getString());
    } else {
      printArray(out, memData, null, null, new Indent(2), null, true);
    }
    out.format(",");
  }
  return out.toString();
}
 
Example 7
Source File: TestCollectionSpecParser.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void doit(String spec, String filterExpect) {
  Formatter errlog = new Formatter();
  CollectionSpecParser specp = new CollectionSpecParser(spec, errlog);
  System.out.printf("spec= %s%n%s%n", spec, specp);
  String err = errlog.toString();
  System.out.printf("-----------------------------------%n");
  String filterHave = (specp.getFilter() != null) ? specp.getFilter().toString() : "null";
  assertThat(filterHave).isEqualTo(filterExpect);
}
 
Example 8
Source File: Detector.java    From language-detection with Apache License 2.0 5 votes vote down vote up
private String wordProbToString(double[] prob) {
    Formatter formatter = new Formatter();
    for(int j=0;j<prob.length;++j) {
        double p = prob[j];
        if (p>=0.00001) {
            formatter.format(" %s:%.5f", langlist.get(j), p);
        }
    }
    formatter.close();
    return formatter.toString();
}
 
Example 9
Source File: GridTable.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
Row(GridDatatype gg) {
  this.gg = gg;
  Formatter f = new Formatter();
  for (Dimension dim : gg.getDimensions())
    f.format("%s ", dim.getShortName());
  dims = f.toString();
}
 
Example 10
Source File: ThimblerigService.java    From Test-Driven-Java-Development-Second-Edition with MIT License 5 votes vote down vote up
private void checkBetAmount(BigDecimal betAmount) {
  if (BigDecimal.ZERO.compareTo(betAmount) >= 0) {
    Formatter formatter = new Formatter(Locale.US).format(
        "Invalid bet amount <%.2f>. Please place a bet of more than 0",
        betAmount
    );
    throw new IllegalArgumentException(formatter.toString());
  }
}
 
Example 11
Source File: StringUtil.java    From netty-cookbook with Apache License 2.0 5 votes vote down vote up
private static String byteArray2Hex(final byte[] hash) {
	Formatter formatter = new Formatter();
	for (byte b : hash) {
		formatter.format("%02x", b);
	}
	return formatter.toString();
}
 
Example 12
Source File: ChannelState.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Publishes a value on MQTT. A command topic needs to be set in the configuration.
 *
 * @param command The command to send
 * @return A future that completes with true if the publishing worked and false and/or exceptionally otherwise.
 */
public CompletableFuture<@Nullable Void> publishValue(Command command) {
    cachedValue.update(command);

    String mqttCommandValue = cachedValue.getMQTTpublishValue();

    final MqttBrokerConnection connection = this.connection;

    if (!readOnly && connection != null) {
        // Formatter: Applied before the channel state value is published to the MQTT broker.
        if (config.formatBeforePublish.length() > 0) {
            try (Formatter formatter = new Formatter()) {
                Formatter format = formatter.format(config.formatBeforePublish, mqttCommandValue);
                mqttCommandValue = format.toString();
            } catch (IllegalFormatException e) {
                logger.debug("Format pattern incorrect for {}", channelUID, e);
            }
        }
        // Outgoing transformations
        for (ChannelStateTransformation t : transformationsOut) {
            mqttCommandValue = t.processValue(mqttCommandValue);
        }
        // Send retained messages if this is a stateful channel
        return connection.publish(config.commandTopic, mqttCommandValue.getBytes(), 1, config.retained)
                .thenRun(() -> {
                });
    } else {
        CompletableFuture<@Nullable Void> f = new CompletableFuture<>();
        f.completeExceptionally(new IllegalStateException("No connection or readOnly channel!"));
        return f;
    }
}
 
Example 13
Source File: FeatureScan.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public String runClassifier() {
  Formatter ff = new Formatter();
  String type = null;
  try (NetcdfDataset ds = NetcdfDatasets.openDataset(f.getPath())) {
    type = DtCoverageCSBuilder.describe(ds, ff);

  } catch (IOException e) {
    StringWriter sw = new StringWriter(10000);
    e.printStackTrace(new PrintWriter(sw));
    ff.format("%n%s", sw.toString());
  }
  ff.format("CoverageCS.Type = %s", type);
  return ff.toString();
}
 
Example 14
Source File: SimpleGeomController.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
String getDatasetInfo() {
  if (null == gridDataset)
    return "";
  Formatter info = new Formatter();
  gridDataset.getDetailInfo(info);
  return info.toString();
}
 
Example 15
Source File: JarListSanitizer.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
private static String byteArray2Hex(final byte[] hash) {
    Formatter formatter = new Formatter();
    try {
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        return formatter.toString();
    } finally {
        formatter.close();
    }
}
 
Example 16
Source File: DominoUtils.java    From org.openntf.domino with Apache License 2.0 5 votes vote down vote up
public static String toHex(final byte[] bytes) {
	Formatter formatter = new Formatter();
	for (byte b : bytes) {
		formatter.format("%02x", b);
	}
	String result = formatter.toString();
	formatter.close();
	return result;
}
 
Example 17
Source File: NumberRenderer.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public String toString(Object o, String formatString, Locale locale) {
    // o will be instanceof Number
    if ( formatString==null ) return o.toString();
    Formatter f = new Formatter(locale);
    f.format(formatString, o);
    return f.toString();
}
 
Example 18
Source File: SimpleGeomPanel.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 *
 */
public void setDataset(NetcdfDataset newds) {
  if (newds == null) {
    return;
  }
  try {
    if (ds != null) {
      ds.close();
    }
  } catch (IOException ioe) {
    logger.warn("close failed");
  }

  Formatter parseInfo = new Formatter();
  this.ds = newds;
  try {
    sgTable.setDataset(newds, parseInfo);
  } catch (IOException e) {
    String info = parseInfo.toString();
    if (!info.isEmpty()) {
      detailTA.setText(info);
      detailWindow.show();
    }
    e.printStackTrace();
    return;
  }
  setSelectedItem(newds.getLocation());
}
 
Example 19
Source File: NetcdfDatasetInfo.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private String getDecl(Variable ve) {
  Formatter sb = new Formatter();
  sb.format("%s ", ve.getDataType().toString());
  ve.getNameAndDimensions(sb, true, true);
  return sb.toString();
}
 
Example 20
Source File: Ncdump.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 3 votes vote down vote up
/**
 * Print a section of the data of the given Variable.
 *
 * @param v variable to print
 * @param sectionSpec string specification
 * @param ct allow task to be cancelled; may be null.
 * @return String result formatted data ouptut
 * @throws IOException on write error
 * @throws InvalidRangeException is specified section doesnt match variable shape
 */
private static String printVariableDataSection(Variable v, String sectionSpec, CancelTask ct)
    throws IOException, InvalidRangeException {
  Array data = v.read(sectionSpec);

  Formatter out = new Formatter();
  printArray(out, data, v.getFullName(), new Indent(2), ct);
  return out.toString();
}