@Override public void handle(final DatagramChannel datagramChannel, final long deadline) throws IOException { try (ByteArrayBuilder bos = new ByteArrayBuilder(); OutputStreamWriter os = new OutputStreamWriter(bos, Charsets.UTF_8)) { int msgStart = 0, msgEnd = 0, prevEnd = 0; for (int i = 0; i < measurements.length; i++) { writeMetric( measurementInfo, measurementInfo.getMeasurementName(i), measurements[i], timeStampMillis, os); os.flush(); msgEnd = bos.size(); int length = msgEnd - msgStart; if (length > MAX_UDP_MSG_SIZE) { ByteBuffer byteBuffer = ByteBuffer.wrap(bos.getBuffer(), msgStart, prevEnd - msgStart); datagramChannel.write(byteBuffer); msgStart = prevEnd; } prevEnd = msgEnd; } if (msgEnd > msgStart) { ByteBuffer byteBuffer = ByteBuffer.wrap(bos.getBuffer(), msgStart, msgEnd - msgStart); datagramChannel.write(byteBuffer); } } }
/** * Write with the plaintext protocol: * https://graphite.readthedocs.io/en/0.9.10/feeding-carbon.html * * @param measurementInfo measuremrnt info * @param measurementName measurement name * @param measurement measurement value * @param timeStampMillis timestamp millis since epoch. * @param os the output writer to write to. * @throws IOException */ public static void writeMetric( final MeasurementsInfo measurementInfo, final String measurementName, final long measurement, final long timeStampMillis, final Writer os) throws IOException { Strings.writeReplaceWhitespaces(measurementInfo.getMeasuredEntity().toString(), '-', os); os.append('/'); Strings.writeReplaceWhitespaces(measurementName, '-', os); os.append(' '); os.append(Long.toString(measurement)); os.append(' '); os.append(Long.toString(timeStampMillis)); os.append('\n'); }