proj_name
stringclasses
110 values
relative_path
stringlengths
40
228
class_name
stringlengths
1
68
func_name
stringlengths
1
98
masked_class
stringlengths
58
2.52M
func_body
stringlengths
0
166k
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
computeStats
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) {<FILL_FUNCTION_BODY>} /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
waitForClientsUntil
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) {<FILL_FUNCTION_BODY>} /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
measureJVM
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() {<FILL_FUNCTION_BODY>} /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
getMaxThreads
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() {<FILL_FUNCTION_BODY>} /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
return maxThreads;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
getMinThreads
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() {<FILL_FUNCTION_BODY>} /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
return minThreads;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
getMaxUsedMem
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() {<FILL_FUNCTION_BODY>} /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
return maxUsedMem;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
getMinUsedMem
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() {<FILL_FUNCTION_BODY>} /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
return minUsedMem;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
getMaxLoadAvg
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() {<FILL_FUNCTION_BODY>} /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
return maxLoadAvg;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
getMinLoadAvg
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() {<FILL_FUNCTION_BODY>} /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() { return trackJVMStats; } }
return minLoadAvg;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StatusThread.java
StatusThread
trackJVMStats
class StatusThread extends Thread { // Counts down each of the clients completing private final CountDownLatch completeLatch; // Stores the measurements for the run private final Measurements measurements; // Whether or not to track the JVM stats per run private final boolean trackJVMStats; // The clients that are running. private final List<ClientThread> clients; private final String label; private final boolean standardstatus; // The interval for reporting status. private long sleeptimeNs; // JVM max/mins private int maxThreads; private int minThreads = Integer.MAX_VALUE; private long maxUsedMem; private long minUsedMem = Long.MAX_VALUE; private double maxLoadAvg; private double minLoadAvg = Double.MAX_VALUE; private long lastGCCount = 0; private long lastGCTime = 0; /** * Creates a new StatusThread without JVM stat tracking. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds) { this(completeLatch, clients, label, standardstatus, statusIntervalSeconds, false); } /** * Creates a new StatusThread. * * @param completeLatch The latch that each client thread will {@link CountDownLatch#countDown()} * as they complete. * @param clients The clients to collect metrics from. * @param label The label for the status. * @param standardstatus If true the status is printed to stdout in addition to stderr. * @param statusIntervalSeconds The number of seconds between status updates. * @param trackJVMStats Whether or not to track JVM stats. */ public StatusThread(CountDownLatch completeLatch, List<ClientThread> clients, String label, boolean standardstatus, int statusIntervalSeconds, boolean trackJVMStats) { this.completeLatch = completeLatch; this.clients = clients; this.label = label; this.standardstatus = standardstatus; sleeptimeNs = TimeUnit.SECONDS.toNanos(statusIntervalSeconds); measurements = Measurements.getMeasurements(); this.trackJVMStats = trackJVMStats; } /** * Run and periodically report status. */ @Override public void run() { final long startTimeMs = System.currentTimeMillis(); final long startTimeNanos = System.nanoTime(); long deadline = startTimeNanos + sleeptimeNs; long startIntervalMs = startTimeMs; long lastTotalOps = 0; boolean alldone; do { long nowMs = System.currentTimeMillis(); lastTotalOps = computeStats(startTimeMs, startIntervalMs, nowMs, lastTotalOps); if (trackJVMStats) { measureJVM(); } alldone = waitForClientsUntil(deadline); startIntervalMs = nowMs; deadline += sleeptimeNs; } while (!alldone); if (trackJVMStats) { measureJVM(); } // Print the final stats. computeStats(startTimeMs, startIntervalMs, System.currentTimeMillis(), lastTotalOps); } /** * Computes and prints the stats. * * @param startTimeMs The start time of the test. * @param startIntervalMs The start time of this interval. * @param endIntervalMs The end time (now) for the interval. * @param lastTotalOps The last total operations count. * @return The current operation count. */ private long computeStats(final long startTimeMs, long startIntervalMs, long endIntervalMs, long lastTotalOps) { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); long totalops = 0; long todoops = 0; // Calculate the total number of operations completed. for (ClientThread t : clients) { totalops += t.getOpsDone(); todoops += t.getOpsTodo(); } long interval = endIntervalMs - startTimeMs; double throughput = 1000.0 * (((double) totalops) / (double) interval); double curthroughput = 1000.0 * (((double) (totalops - lastTotalOps)) / ((double) (endIntervalMs - startIntervalMs))); long estremaining = (long) Math.ceil(todoops / throughput); DecimalFormat d = new DecimalFormat("#.##"); String labelString = this.label + format.format(new Date()); StringBuilder msg = new StringBuilder(labelString).append(" ").append(interval / 1000).append(" sec: "); msg.append(totalops).append(" operations; "); if (totalops != 0) { msg.append(d.format(curthroughput)).append(" current ops/sec; "); } if (todoops != 0) { msg.append("est completion in ").append(RemainingFormatter.format(estremaining)); } msg.append(Measurements.getMeasurements().getSummary()); System.err.println(msg); if (standardstatus) { System.out.println(msg); } return totalops; } /** * Waits for all of the client to finish or the deadline to expire. * * @param deadline The current deadline. * @return True if all of the clients completed. */ private boolean waitForClientsUntil(long deadline) { boolean alldone = false; long now = System.nanoTime(); while (!alldone && now < deadline) { try { alldone = completeLatch.await(deadline - now, TimeUnit.NANOSECONDS); } catch (InterruptedException ie) { // If we are interrupted the thread is being asked to shutdown. // Return true to indicate that and reset the interrupt state // of the thread. Thread.currentThread().interrupt(); alldone = true; } now = System.nanoTime(); } return alldone; } /** * Executes the JVM measurements. */ private void measureJVM() { final int threads = Utils.getActiveThreadCount(); if (threads < minThreads) { minThreads = threads; } if (threads > maxThreads) { maxThreads = threads; } measurements.measure("THREAD_COUNT", threads); // TODO - once measurements allow for other number types, switch to using // the raw bytes. Otherwise we can track in MB to avoid negative values // when faced with huge heaps. final int usedMem = Utils.getUsedMemoryMegaBytes(); if (usedMem < minUsedMem) { minUsedMem = usedMem; } if (usedMem > maxUsedMem) { maxUsedMem = usedMem; } measurements.measure("USED_MEM_MB", usedMem); // Some JVMs may not implement this feature so if the value is less than // zero, just ommit it. final double systemLoad = Utils.getSystemLoadAverage(); if (systemLoad >= 0) { // TODO - store the double if measurements allows for them measurements.measure("SYS_LOAD_AVG", (int) systemLoad); if (systemLoad > maxLoadAvg) { maxLoadAvg = systemLoad; } if (systemLoad < minLoadAvg) { minLoadAvg = systemLoad; } } final long gcs = Utils.getGCTotalCollectionCount(); measurements.measure("GCS", (int) (gcs - lastGCCount)); final long gcTime = Utils.getGCTotalTime(); measurements.measure("GCS_TIME", (int) (gcTime - lastGCTime)); lastGCCount = gcs; lastGCTime = gcTime; } /** * @return The maximum threads running during the test. */ public int getMaxThreads() { return maxThreads; } /** * @return The minimum threads running during the test. */ public int getMinThreads() { return minThreads; } /** * @return The maximum memory used during the test. */ public long getMaxUsedMem() { return maxUsedMem; } /** * @return The minimum memory used during the test. */ public long getMinUsedMem() { return minUsedMem; } /** * @return The maximum load average during the test. */ public double getMaxLoadAvg() { return maxLoadAvg; } /** * @return The minimum load average during the test. */ public double getMinLoadAvg() { return minLoadAvg; } /** * @return Whether or not the thread is tracking JVM stats. */ public boolean trackJVMStats() {<FILL_FUNCTION_BODY>} }
return trackJVMStats;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
putAllAsByteIterators
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) {<FILL_FUNCTION_BODY>} /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
putAllAsStrings
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) {<FILL_FUNCTION_BODY>} /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
getByteIteratorMap
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) {<FILL_FUNCTION_BODY>} /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
getStringMap
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) {<FILL_FUNCTION_BODY>} public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
hasNext
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() {<FILL_FUNCTION_BODY>} @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
return off < str.length();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
nextByte
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() {<FILL_FUNCTION_BODY>} @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
byte ret = (byte) str.charAt(off); off++; return ret;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
bytesLeft
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() {<FILL_FUNCTION_BODY>} @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
return str.length() - off;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
reset
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() {<FILL_FUNCTION_BODY>} @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
off = 0;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
toArray
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() {<FILL_FUNCTION_BODY>} /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() { if (off > 0) { return super.toString(); } else { return str; } } }
byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/StringByteIterator.java
StringByteIterator
toString
class StringByteIterator extends ByteIterator { private String str; private int off; /** * Put all of the entries of one map into the other, converting * String values into ByteIterators. */ public static void putAllAsByteIterators(Map<String, ByteIterator> out, Map<String, String> in) { for (Map.Entry<String, String> entry : in.entrySet()) { out.put(entry.getKey(), new StringByteIterator(entry.getValue())); } } /** * Put all of the entries of one map into the other, converting * ByteIterator values into Strings. */ public static void putAllAsStrings(Map<String, String> out, Map<String, ByteIterator> in) { for (Map.Entry<String, ByteIterator> entry : in.entrySet()) { out.put(entry.getKey(), entry.getValue().toString()); } } /** * Create a copy of a map, converting the values from Strings to * StringByteIterators. */ public static Map<String, ByteIterator> getByteIteratorMap(Map<String, String> m) { HashMap<String, ByteIterator> ret = new HashMap<String, ByteIterator>(); for (Map.Entry<String, String> entry : m.entrySet()) { ret.put(entry.getKey(), new StringByteIterator(entry.getValue())); } return ret; } /** * Create a copy of a map, converting the values from * StringByteIterators to Strings. */ public static Map<String, String> getStringMap(Map<String, ByteIterator> m) { HashMap<String, String> ret = new HashMap<String, String>(); for (Map.Entry<String, ByteIterator> entry : m.entrySet()) { ret.put(entry.getKey(), entry.getValue().toString()); } return ret; } public StringByteIterator(String s) { this.str = s; this.off = 0; } @Override public boolean hasNext() { return off < str.length(); } @Override public byte nextByte() { byte ret = (byte) str.charAt(off); off++; return ret; } @Override public long bytesLeft() { return str.length() - off; } @Override public void reset() { off = 0; } @Override public byte[] toArray() { byte[] bytes = new byte[(int) bytesLeft()]; for (int i = 0; i < bytes.length; i++) { bytes[i] = (byte) str.charAt(off + i); } off = str.length(); return bytes; } /** * Specialization of general purpose toString() to avoid unnecessary * copies. * <p> * Creating a new StringByteIterator, then calling toString() * yields the original String object, and does not perform any copies * or String conversion operations. * </p> */ @Override public String toString() {<FILL_FUNCTION_BODY>} }
if (off > 0) { return super.toString(); } else { return str; }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TerminatorThread.java
TerminatorThread
run
class TerminatorThread extends Thread { private final Collection<? extends Thread> threads; private long maxExecutionTime; private Workload workload; private long waitTimeOutInMS; public TerminatorThread(long maxExecutionTime, Collection<? extends Thread> threads, Workload workload) { this.maxExecutionTime = maxExecutionTime; this.threads = threads; this.workload = workload; waitTimeOutInMS = 2000; System.err.println("Maximum execution time specified as: " + maxExecutionTime + " secs"); } public void run() {<FILL_FUNCTION_BODY>} }
try { Thread.sleep(maxExecutionTime * 1000); } catch (InterruptedException e) { System.err.println("Could not wait until max specified time, TerminatorThread interrupted."); return; } System.err.println("Maximum time elapsed. Requesting stop for the workload."); workload.requestStop(); System.err.println("Stop requested for workload. Now Joining!"); for (Thread t : threads) { while (t.isAlive()) { try { t.join(waitTimeOutInMS); if (t.isAlive()) { System.out.println("Still waiting for thread " + t.getName() + " to complete. " + "Workload status: " + workload.isStopRequested()); } } catch (InterruptedException e) { // Do nothing. Don't know why I was interrupted. } } }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
init
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException {<FILL_FUNCTION_BODY>} @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); } /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit); } /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes } @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) { NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); } } /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) { return Status.NOT_IMPLEMENTED; } /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) { final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames; } /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
// taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT));
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
read
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException { // taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT)); } @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) {<FILL_FUNCTION_BODY>} /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit); } /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes } @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) { NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); } } /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) { return Status.NOT_IMPLEMENTED; } /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) { final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames; } /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
scan
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException { // taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT)); } @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); } /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {<FILL_FUNCTION_BODY>} /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes } @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) { NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); } } /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) { return Status.NOT_IMPLEMENTED; } /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) { final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames; } /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
update
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException { // taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT)); } @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); } /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit); } /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>} @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) { NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); } } /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) { return Status.NOT_IMPLEMENTED; } /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) { final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames; } /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
insert
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException { // taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT)); } @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); } /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit); } /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes } @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) {<FILL_FUNCTION_BODY>} /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) { return Status.NOT_IMPLEMENTED; } /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) { final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames; } /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
delete
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException { // taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT)); } @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); } /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit); } /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes } @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) { NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); } } /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) {<FILL_FUNCTION_BODY>} /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) { final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames; } /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
return Status.NOT_IMPLEMENTED;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/TimeseriesDB.java
TimeseriesDB
getPossibleTagKeys
class TimeseriesDB extends DB { // defaults for downsampling. Basically we ignore it private static final String DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT = "NONE"; private static final String DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT = "0"; // debug property loading private static final String DEBUG_PROPERTY = "debug"; private static final String DEBUG_PROPERTY_DEFAULT = "false"; // test property loading private static final String TEST_PROPERTY = "test"; private static final String TEST_PROPERTY_DEFAULT = "false"; // Workload parameters that we need to parse this protected String timestampKey; protected String valueKey; protected String tagPairDelimiter; protected String queryTimeSpanDelimiter; protected String deleteDelimiter; protected TimeUnit timestampUnit; protected String groupByKey; protected String downsamplingKey; protected Integer downsamplingInterval; protected AggregationOperation downsamplingFunction; // YCSB-parameters protected boolean debug; protected boolean test; /** * Initialize any state for this DB. * Called once per DB instance; there is one DB instance per client thread. */ @Override public void init() throws DBException { // taken from BasicTSDB timestampKey = getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY, TimeSeriesWorkload.TIMESTAMP_KEY_PROPERTY_DEFAULT); valueKey = getProperties().getProperty( TimeSeriesWorkload.VALUE_KEY_PROPERTY, TimeSeriesWorkload.VALUE_KEY_PROPERTY_DEFAULT); tagPairDelimiter = getProperties().getProperty( TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY, TimeSeriesWorkload.PAIR_DELIMITER_PROPERTY_DEFAULT); queryTimeSpanDelimiter = getProperties().getProperty( TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY, TimeSeriesWorkload.QUERY_TIMESPAN_DELIMITER_PROPERTY_DEFAULT); deleteDelimiter = getProperties().getProperty( TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY, TimeSeriesWorkload.DELETE_DELIMITER_PROPERTY_DEFAULT); timestampUnit = TimeUnit.valueOf(getProperties().getProperty( TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY, TimeSeriesWorkload.TIMESTAMP_UNITS_PROPERTY_DEFAULT)); groupByKey = getProperties().getProperty( TimeSeriesWorkload.GROUPBY_KEY_PROPERTY, TimeSeriesWorkload.GROUPBY_KEY_PROPERTY_DEFAULT); downsamplingKey = getProperties().getProperty( TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY, TimeSeriesWorkload.DOWNSAMPLING_KEY_PROPERTY_DEFAULT); downsamplingFunction = TimeseriesDB.AggregationOperation.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_FUNCTION_PROPERTY, DOWNSAMPLING_FUNCTION_PROPERTY_DEFAULT)); downsamplingInterval = Integer.valueOf(getProperties() .getProperty(TimeSeriesWorkload.DOWNSAMPLING_INTERVAL_PROPERTY, DOWNSAMPLING_INTERVAL_PROPERTY_DEFAULT)); test = Boolean.parseBoolean(getProperties().getProperty(TEST_PROPERTY, TEST_PROPERTY_DEFAULT)); debug = Boolean.parseBoolean(getProperties().getProperty(DEBUG_PROPERTY, DEBUG_PROPERTY_DEFAULT)); } @Override public final Status read(String table, String key, Set<String> fields, Map<String, ByteIterator> result) { Map<String, List<String>> tagQueries = new HashMap<>(); Long timestamp = null; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (timestampParts[1].contains(queryTimeSpanDelimiter)) { // Since we're looking for a single datapoint, a range of timestamps makes no sense. // As we cannot throw an exception to bail out here, we return `BAD_REQUEST` instead. return Status.BAD_REQUEST; } timestamp = Long.valueOf(timestampParts[1]); } else { String[] queryParts = field.split(tagPairDelimiter); tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } if (timestamp == null) { return Status.BAD_REQUEST; } return read(table, timestamp, tagQueries); } /** * Read a record from the database. Each value from the result will be stored in a HashMap * * @param metric The name of the metric * @param timestamp The timestamp of the record to read. * @param tags actual tags that were want to receive (can be empty) * @return Zero on success, a non-zero error code on error or "not found". */ protected abstract Status read(String metric, long timestamp, Map<String, List<String>> tags); /** * @inheritDoc * @implNote this method parses the information passed to it and subsequently passes it to the modified * interface at {@link #scan(String, long, long, Map, AggregationOperation, int, TimeUnit)} */ @Override public final Status scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { Map<String, List<String>> tagQueries = new HashMap<>(); TimeseriesDB.AggregationOperation aggregationOperation = TimeseriesDB.AggregationOperation.NONE; Set<String> groupByFields = new HashSet<>(); boolean rangeSet = false; long start = 0; long end = 0; for (String field : fields) { if (field.startsWith(timestampKey)) { String[] timestampParts = field.split(tagPairDelimiter); if (!timestampParts[1].contains(queryTimeSpanDelimiter)) { // seems like this should be a more elaborate query. // for now we don't support scanning single timestamps // TODO: Support Timestamp range queries return Status.NOT_IMPLEMENTED; } String[] rangeParts = timestampParts[1].split(queryTimeSpanDelimiter); rangeSet = true; start = Long.valueOf(rangeParts[0]); end = Long.valueOf(rangeParts[1]); } else if (field.startsWith(groupByKey)) { String groupBySpecifier = field.split(tagPairDelimiter)[1]; aggregationOperation = TimeseriesDB.AggregationOperation.valueOf(groupBySpecifier); } else if (field.startsWith(downsamplingKey)) { String downsamplingSpec = field.split(tagPairDelimiter)[1]; // apparently that needs to always hold true: if (!downsamplingSpec.equals(downsamplingFunction.toString() + downsamplingInterval.toString())) { System.err.print("Downsampling specification for Scan did not match configured downsampling"); return Status.BAD_REQUEST; } } else { String[] queryParts = field.split(tagPairDelimiter); if (queryParts.length == 1) { // we should probably warn about this being ignored... System.err.println("Grouping by arbitrary series is currently not supported"); groupByFields.add(field); } else { tagQueries.computeIfAbsent(queryParts[0], k -> new ArrayList<>()).add(queryParts[1]); } } } if (!rangeSet) { return Status.BAD_REQUEST; } return scan(table, start, end, tagQueries, downsamplingFunction, downsamplingInterval, timestampUnit); } /** * Perform a range scan for a set of records in the database. Each value from the result will be stored in a * HashMap. * * @param metric The name of the metric * @param startTs The timestamp of the first record to read. * @param endTs The timestamp of the last record to read. * @param tags actual tags that were want to receive (can be empty). * @param aggreg The aggregation operation to perform. * @param timeValue value for timeUnit for aggregation * @param timeUnit timeUnit for aggregation * @return A {@link Status} detailing the outcome of the scan operation. */ protected abstract Status scan(String metric, long startTs, long endTs, Map<String, List<String>> tags, AggregationOperation aggreg, int timeValue, TimeUnit timeUnit); @Override public Status update(String table, String key, Map<String, ByteIterator> values) { return Status.NOT_IMPLEMENTED; // not supportable for general TSDBs // can be explicitly overwritten in inheriting classes } @Override public final Status insert(String table, String key, Map<String, ByteIterator> values) { NumericByteIterator tsContainer = (NumericByteIterator) values.remove(timestampKey); NumericByteIterator valueContainer = (NumericByteIterator) values.remove(valueKey); if (valueContainer.isFloatingPoint()) { return insert(table, tsContainer.getLong(), valueContainer.getDouble(), values); } else { return insert(table, tsContainer.getLong(), valueContainer.getLong(), values); } } /** * Insert a record into the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value The actual value to insert. * @param tags A Map of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, long value, Map<String, ByteIterator> tags); /** * Insert a record in the database. Any tags/tagvalue pairs in the specified tagmap and the given value will be * written into the record with the specified timestamp. * * @param metric The name of the metric * @param timestamp The timestamp of the record to insert. * @param value actual value to insert * @param tags A HashMap of tag/tagvalue pairs to insert as tags * @return A {@link Status} detailing the outcome of the insert */ protected abstract Status insert(String metric, long timestamp, double value, Map<String, ByteIterator> tags); /** * NOTE: This operation is usually <b>not</b> supported for Time-Series databases. * Deletion of data is often instead regulated through automatic cleanup and "retention policies" or similar. * * @return Status.NOT_IMPLEMENTED or a {@link Status} specifying the outcome of deletion * in case the operation is supported. */ public Status delete(String table, String key) { return Status.NOT_IMPLEMENTED; } /** * Examines the given {@link Properties} and returns an array containing the Tag Keys * (basically matching column names for traditional Relational DBs) that are detailed in the workload specification. * See {@link TimeSeriesWorkload} for how these are generated. * <p> * This method is intended to be called during the initialization phase to create a table schema * for DBMS that require such a schema before values can be inserted (or queried) * * @param properties The properties detailing the workload configuration. * @return An array of strings specifying all allowed TagKeys (or column names) * except for the "value" and the "timestamp" column name. * @implSpec WARNING this method must exactly match how tagKeys are generated by the {@link TimeSeriesWorkload}, * otherwise databases requiring this information will most likely break! */ protected static String[] getPossibleTagKeys(Properties properties) {<FILL_FUNCTION_BODY>} /** * An enum containing the possible aggregation operations. * Not all of these operations are required to be supported by implementing classes. * <p> * Aggregations are applied when using the <tt>SCAN</tt> operation on a range of timestamps. * That way the result set is reduced from multiple records into * a single one or one record for each group specified through <tt>GROUP BY</tt> clauses. */ public enum AggregationOperation { /** * No aggregation whatsoever. Return the results as a full table */ NONE, /** * Sum the values of the matching records when calculating the value. * GroupBy criteria apply where relevant for sub-summing. */ SUM, /** * Calculate the arithmetic mean over the value across matching records when calculating the value. * GroupBy criteria apply where relevant for group-targeted averages */ AVERAGE, /** * Count the number of matching records and return that as value. * GroupBy criteria apply where relevant. */ COUNT, /** * Return only the maximum of the matching record values. * GroupBy criteria apply and result in group-based maxima. */ MAX, /** * Return only the minimum of the matching record values. * GroupBy criteria apply and result in group-based minima. */ MIN; } }
final int tagCount = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_COUNT_PROPERTY, TimeSeriesWorkload.TAG_COUNT_PROPERTY_DEFAULT)); final int tagKeylength = Integer.parseInt(properties.getProperty(TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY, TimeSeriesWorkload.TAG_KEY_LENGTH_PROPERTY_DEFAULT)); Generator<String> tagKeyGenerator = new IncrementingPrintableStringGenerator(tagKeylength); String[] tagNames = new String[tagCount]; for (int i = 0; i < tagCount; i++) { tagNames[i] = tagKeyGenerator.nextValue(); } return tagNames;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/UnknownDBException.java
null
null
null
null
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
hash
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) {<FILL_FUNCTION_BODY>} public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
return fnvhash64(val);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
fnvhash64
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) {<FILL_FUNCTION_BODY>} /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
//from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
bytesToLong
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) {<FILL_FUNCTION_BODY>} /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
longToBytes
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) {<FILL_FUNCTION_BODY>} /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
bytesToDouble
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) {<FILL_FUNCTION_BODY>} /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes));
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
doubleToBytes
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) {<FILL_FUNCTION_BODY>} /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
return longToBytes(Double.doubleToRawLongBits(val));
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getActiveThreadCount
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() {<FILL_FUNCTION_BODY>} /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
return Thread.activeCount();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getUsedMemoryBytes
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() {<FILL_FUNCTION_BODY>} /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getUsedMemoryMegaBytes
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() {<FILL_FUNCTION_BODY>} /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
return (int) (getUsedMemoryBytes() / 1024 / 1024);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getSystemLoadAverage
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() {<FILL_FUNCTION_BODY>} /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getGCTotalCollectionCount
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() {<FILL_FUNCTION_BODY>} /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getGCTotalTime
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() {<FILL_FUNCTION_BODY>} /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
getGCStatst
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() {<FILL_FUNCTION_BODY>} /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) { for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array; } }
final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Utils.java
Utils
shuffleArray
class Utils { private Utils() { // not used } /** * Hash an integer value. */ public static long hash(long val) { return fnvhash64(val); } public static final long FNV_OFFSET_BASIS_64 = 0xCBF29CE484222325L; public static final long FNV_PRIME_64 = 1099511628211L; /** * 64 bit FNV hash. Produces more "random" hashes than (say) String.hashCode(). * * @param val The value to hash. * @return The hash value */ public static long fnvhash64(long val) { //from http://en.wikipedia.org/wiki/Fowler_Noll_Vo_hash long hashval = FNV_OFFSET_BASIS_64; for (int i = 0; i < 8; i++) { long octet = val & 0x00ff; val = val >> 8; hashval = hashval ^ octet; hashval = hashval * FNV_PRIME_64; //hashval = hashval ^ octet; } return Math.abs(hashval); } /** * Reads a big-endian 8-byte long from an offset in the given array. * @param bytes The array to read from. * @return A long integer. * @throws IndexOutOfBoundsException if the byte array is too small. * @throws NullPointerException if the byte array is null. */ public static long bytesToLong(final byte[] bytes) { return (bytes[0] & 0xFFL) << 56 | (bytes[1] & 0xFFL) << 48 | (bytes[2] & 0xFFL) << 40 | (bytes[3] & 0xFFL) << 32 | (bytes[4] & 0xFFL) << 24 | (bytes[5] & 0xFFL) << 16 | (bytes[6] & 0xFFL) << 8 | (bytes[7] & 0xFFL) << 0; } /** * Writes a big-endian 8-byte long at an offset in the given array. * @param val The value to encode. * @throws IndexOutOfBoundsException if the byte array is too small. */ public static byte[] longToBytes(final long val) { final byte[] bytes = new byte[8]; bytes[0] = (byte) (val >>> 56); bytes[1] = (byte) (val >>> 48); bytes[2] = (byte) (val >>> 40); bytes[3] = (byte) (val >>> 32); bytes[4] = (byte) (val >>> 24); bytes[5] = (byte) (val >>> 16); bytes[6] = (byte) (val >>> 8); bytes[7] = (byte) (val >>> 0); return bytes; } /** * Parses the byte array into a double. * The byte array must be at least 8 bytes long and have been encoded using * {@link #doubleToBytes}. If the array is longer than 8 bytes, only the * first 8 bytes are parsed. * @param bytes The byte array to parse, at least 8 bytes. * @return A double value read from the byte array. * @throws IllegalArgumentException if the byte array is not 8 bytes wide. */ public static double bytesToDouble(final byte[] bytes) { if (bytes.length < 8) { throw new IllegalArgumentException("Byte array must be 8 bytes wide."); } return Double.longBitsToDouble(bytesToLong(bytes)); } /** * Encodes the double value as an 8 byte array. * @param val The double value to encode. * @return A byte array of length 8. */ public static byte[] doubleToBytes(final double val) { return longToBytes(Double.doubleToRawLongBits(val)); } /** * Measure the estimated active thread count in the current thread group. * Since this calls {@link Thread.activeCount} it should be called from the * main thread or one started by the main thread. Threads included in the * count can be in any state. * For a more accurate count we could use {@link Thread.getAllStackTraces().size()} * but that freezes the JVM and incurs a high overhead. * @return An estimated thread count, good for showing the thread count * over time. */ public static int getActiveThreadCount() { return Thread.activeCount(); } /** @return The currently used memory in bytes */ public static long getUsedMemoryBytes() { final Runtime runtime = Runtime.getRuntime(); return runtime.totalMemory() - runtime.freeMemory(); } /** @return The currently used memory in megabytes. */ public static int getUsedMemoryMegaBytes() { return (int) (getUsedMemoryBytes() / 1024 / 1024); } /** @return The current system load average if supported by the JDK. * If it's not supported, the value will be negative. */ public static double getSystemLoadAverage() { final OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); return osBean.getSystemLoadAverage(); } /** @return The total number of garbage collections executed for all * memory pools. */ public static long getGCTotalCollectionCount() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long count = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionCount() < 0) { continue; } count += bean.getCollectionCount(); } return count; } /** @return The total time, in milliseconds, spent in GC. */ public static long getGCTotalTime() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); long time = 0; for (final GarbageCollectorMXBean bean : gcBeans) { if (bean.getCollectionTime() < 0) { continue; } time += bean.getCollectionTime(); } return time; } /** * Returns a map of garbage collectors and their stats. * The first object in the array is the total count since JVM start and the * second is the total time (ms) since JVM start. * If a garbage collectors does not support the collector MXBean, then it * will not be represented in the map. * @return A non-null map of garbage collectors and their metrics. The map * may be empty. */ public static Map<String, Long[]> getGCStatst() { final List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); final Map<String, Long[]> map = new HashMap<String, Long[]>(gcBeans.size()); for (final GarbageCollectorMXBean bean : gcBeans) { if (!bean.isValid() || bean.getCollectionCount() < 0 || bean.getCollectionTime() < 0) { continue; } final Long[] measurements = new Long[]{ bean.getCollectionCount(), bean.getCollectionTime() }; map.put(bean.getName().replace(" ", "_"), measurements); } return map; } /** * Simple Fisher-Yates array shuffle to randomize discrete sets. * @param array The array to randomly shuffle. * @return The shuffled array. */ public static <T> T [] shuffleArray(final T[] array) {<FILL_FUNCTION_BODY>} }
for (int i = array.length -1; i > 0; i--) { final int idx = ThreadLocalRandom.current().nextInt(i + 1); final T temp = array[idx]; array[idx] = array[i]; array[i] = temp; } return array;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Workload.java
Workload
init
class Workload { public static final String INSERT_START_PROPERTY = "insertstart"; public static final String INSERT_COUNT_PROPERTY = "insertcount"; public static final String INSERT_START_PROPERTY_DEFAULT = "0"; private volatile AtomicBoolean stopRequested = new AtomicBoolean(false); /** Operations available for a database. */ public enum Operation { READ, UPDATE, INSERT, SCAN, DELETE } /** * Initialize the scenario. Create any generators and other shared objects here. * Called once, in the main client thread, before any operations are started. */ public void init(Properties p) throws WorkloadException {<FILL_FUNCTION_BODY>} /** * Initialize any state for a particular client thread. Since the scenario object * will be shared among all threads, this is the place to create any state that is specific * to one thread. To be clear, this means the returned object should be created anew on each * call to initThread(); do not return the same object multiple times. * The returned object will be passed to invocations of doInsert() and doTransaction() * for this thread. There should be no side effects from this call; all state should be encapsulated * in the returned object. If you have no state to retain for this thread, return null. (But if you have * no state to retain for this thread, probably you don't need to override initThread().) * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public Object initThread(Properties p, int mythreadid, int threadcount) throws WorkloadException { return null; } /** * Cleanup the scenario. Called once, in the main client thread, after all operations have completed. */ public void cleanup() throws WorkloadException { } /** * Do one insert operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. */ public abstract boolean doInsert(DB db, Object threadstate); /** * Do one transaction operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public abstract boolean doTransaction(DB db, Object threadstate); /** * Allows scheduling a request to stop the workload. */ public void requestStop() { stopRequested.set(true); } /** * Check the status of the stop request flag. * @return true if stop was requested, false otherwise. */ public boolean isStopRequested() { return stopRequested.get(); } }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Workload.java
Workload
initThread
class Workload { public static final String INSERT_START_PROPERTY = "insertstart"; public static final String INSERT_COUNT_PROPERTY = "insertcount"; public static final String INSERT_START_PROPERTY_DEFAULT = "0"; private volatile AtomicBoolean stopRequested = new AtomicBoolean(false); /** Operations available for a database. */ public enum Operation { READ, UPDATE, INSERT, SCAN, DELETE } /** * Initialize the scenario. Create any generators and other shared objects here. * Called once, in the main client thread, before any operations are started. */ public void init(Properties p) throws WorkloadException { } /** * Initialize any state for a particular client thread. Since the scenario object * will be shared among all threads, this is the place to create any state that is specific * to one thread. To be clear, this means the returned object should be created anew on each * call to initThread(); do not return the same object multiple times. * The returned object will be passed to invocations of doInsert() and doTransaction() * for this thread. There should be no side effects from this call; all state should be encapsulated * in the returned object. If you have no state to retain for this thread, return null. (But if you have * no state to retain for this thread, probably you don't need to override initThread().) * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public Object initThread(Properties p, int mythreadid, int threadcount) throws WorkloadException {<FILL_FUNCTION_BODY>} /** * Cleanup the scenario. Called once, in the main client thread, after all operations have completed. */ public void cleanup() throws WorkloadException { } /** * Do one insert operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. */ public abstract boolean doInsert(DB db, Object threadstate); /** * Do one transaction operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public abstract boolean doTransaction(DB db, Object threadstate); /** * Allows scheduling a request to stop the workload. */ public void requestStop() { stopRequested.set(true); } /** * Check the status of the stop request flag. * @return true if stop was requested, false otherwise. */ public boolean isStopRequested() { return stopRequested.get(); } }
return null;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Workload.java
Workload
cleanup
class Workload { public static final String INSERT_START_PROPERTY = "insertstart"; public static final String INSERT_COUNT_PROPERTY = "insertcount"; public static final String INSERT_START_PROPERTY_DEFAULT = "0"; private volatile AtomicBoolean stopRequested = new AtomicBoolean(false); /** Operations available for a database. */ public enum Operation { READ, UPDATE, INSERT, SCAN, DELETE } /** * Initialize the scenario. Create any generators and other shared objects here. * Called once, in the main client thread, before any operations are started. */ public void init(Properties p) throws WorkloadException { } /** * Initialize any state for a particular client thread. Since the scenario object * will be shared among all threads, this is the place to create any state that is specific * to one thread. To be clear, this means the returned object should be created anew on each * call to initThread(); do not return the same object multiple times. * The returned object will be passed to invocations of doInsert() and doTransaction() * for this thread. There should be no side effects from this call; all state should be encapsulated * in the returned object. If you have no state to retain for this thread, return null. (But if you have * no state to retain for this thread, probably you don't need to override initThread().) * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public Object initThread(Properties p, int mythreadid, int threadcount) throws WorkloadException { return null; } /** * Cleanup the scenario. Called once, in the main client thread, after all operations have completed. */ public void cleanup() throws WorkloadException {<FILL_FUNCTION_BODY>} /** * Do one insert operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. */ public abstract boolean doInsert(DB db, Object threadstate); /** * Do one transaction operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public abstract boolean doTransaction(DB db, Object threadstate); /** * Allows scheduling a request to stop the workload. */ public void requestStop() { stopRequested.set(true); } /** * Check the status of the stop request flag. * @return true if stop was requested, false otherwise. */ public boolean isStopRequested() { return stopRequested.get(); } }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Workload.java
Workload
requestStop
class Workload { public static final String INSERT_START_PROPERTY = "insertstart"; public static final String INSERT_COUNT_PROPERTY = "insertcount"; public static final String INSERT_START_PROPERTY_DEFAULT = "0"; private volatile AtomicBoolean stopRequested = new AtomicBoolean(false); /** Operations available for a database. */ public enum Operation { READ, UPDATE, INSERT, SCAN, DELETE } /** * Initialize the scenario. Create any generators and other shared objects here. * Called once, in the main client thread, before any operations are started. */ public void init(Properties p) throws WorkloadException { } /** * Initialize any state for a particular client thread. Since the scenario object * will be shared among all threads, this is the place to create any state that is specific * to one thread. To be clear, this means the returned object should be created anew on each * call to initThread(); do not return the same object multiple times. * The returned object will be passed to invocations of doInsert() and doTransaction() * for this thread. There should be no side effects from this call; all state should be encapsulated * in the returned object. If you have no state to retain for this thread, return null. (But if you have * no state to retain for this thread, probably you don't need to override initThread().) * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public Object initThread(Properties p, int mythreadid, int threadcount) throws WorkloadException { return null; } /** * Cleanup the scenario. Called once, in the main client thread, after all operations have completed. */ public void cleanup() throws WorkloadException { } /** * Do one insert operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. */ public abstract boolean doInsert(DB db, Object threadstate); /** * Do one transaction operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public abstract boolean doTransaction(DB db, Object threadstate); /** * Allows scheduling a request to stop the workload. */ public void requestStop() {<FILL_FUNCTION_BODY>} /** * Check the status of the stop request flag. * @return true if stop was requested, false otherwise. */ public boolean isStopRequested() { return stopRequested.get(); } }
stopRequested.set(true);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/Workload.java
Workload
isStopRequested
class Workload { public static final String INSERT_START_PROPERTY = "insertstart"; public static final String INSERT_COUNT_PROPERTY = "insertcount"; public static final String INSERT_START_PROPERTY_DEFAULT = "0"; private volatile AtomicBoolean stopRequested = new AtomicBoolean(false); /** Operations available for a database. */ public enum Operation { READ, UPDATE, INSERT, SCAN, DELETE } /** * Initialize the scenario. Create any generators and other shared objects here. * Called once, in the main client thread, before any operations are started. */ public void init(Properties p) throws WorkloadException { } /** * Initialize any state for a particular client thread. Since the scenario object * will be shared among all threads, this is the place to create any state that is specific * to one thread. To be clear, this means the returned object should be created anew on each * call to initThread(); do not return the same object multiple times. * The returned object will be passed to invocations of doInsert() and doTransaction() * for this thread. There should be no side effects from this call; all state should be encapsulated * in the returned object. If you have no state to retain for this thread, return null. (But if you have * no state to retain for this thread, probably you don't need to override initThread().) * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public Object initThread(Properties p, int mythreadid, int threadcount) throws WorkloadException { return null; } /** * Cleanup the scenario. Called once, in the main client thread, after all operations have completed. */ public void cleanup() throws WorkloadException { } /** * Do one insert operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. */ public abstract boolean doInsert(DB db, Object threadstate); /** * Do one transaction operation. Because it will be called concurrently from multiple client threads, this * function must be thread safe. However, avoid synchronized, or the threads will block waiting for each * other, and it will be difficult to reach the target throughput. Ideally, this function would have no side * effects other than DB operations and mutations on threadstate. Mutations to threadstate do not need to be * synchronized, since each thread has its own threadstate instance. * * @return false if the workload knows it is done for this thread. Client will terminate the thread. * Return true otherwise. Return true for workloads that rely on operationcount. For workloads that read * traces from a file, return true when there are more to do, false when you are done. */ public abstract boolean doTransaction(DB db, Object threadstate); /** * Allows scheduling a request to stop the workload. */ public void requestStop() { stopRequested.set(true); } /** * Check the status of the stop request flag. * @return true if stop was requested, false otherwise. */ public boolean isStopRequested() {<FILL_FUNCTION_BODY>} }
return stopRequested.get();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/WorkloadException.java
null
null
null
null
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/AcknowledgedCounterGenerator.java
AcknowledgedCounterGenerator
lastValue
class AcknowledgedCounterGenerator extends CounterGenerator { /** The size of the window of pending id ack's. 2^20 = {@value} */ static final int WINDOW_SIZE = Integer.rotateLeft(1, 20); /** The mask to use to turn an id into a slot in {@link #window}. */ private static final int WINDOW_MASK = WINDOW_SIZE - 1; private final ReentrantLock lock; private final boolean[] window; private volatile long limit; /** * Create a counter that starts at countstart. */ public AcknowledgedCounterGenerator(long countstart) { super(countstart); lock = new ReentrantLock(); window = new boolean[WINDOW_SIZE]; limit = countstart - 1; } /** * In this generator, the highest acknowledged counter value * (as opposed to the highest generated counter value). */ @Override public Long lastValue() {<FILL_FUNCTION_BODY>} /** * Make a generated counter value available via lastInt(). */ public void acknowledge(long value) { final int currentSlot = (int)(value & WINDOW_MASK); if (window[currentSlot]) { throw new RuntimeException("Too many unacknowledged insertion keys."); } window[currentSlot] = true; if (lock.tryLock()) { // move a contiguous sequence from the window // over to the "limit" variable try { // Only loop through the entire window at most once. long beforeFirstSlot = (limit & WINDOW_MASK); long index; for (index = limit + 1; index != beforeFirstSlot; ++index) { int slot = (int)(index & WINDOW_MASK); if (!window[slot]) { break; } window[slot] = false; } limit = index - 1; } finally { lock.unlock(); } } } }
return limit;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/AcknowledgedCounterGenerator.java
AcknowledgedCounterGenerator
acknowledge
class AcknowledgedCounterGenerator extends CounterGenerator { /** The size of the window of pending id ack's. 2^20 = {@value} */ static final int WINDOW_SIZE = Integer.rotateLeft(1, 20); /** The mask to use to turn an id into a slot in {@link #window}. */ private static final int WINDOW_MASK = WINDOW_SIZE - 1; private final ReentrantLock lock; private final boolean[] window; private volatile long limit; /** * Create a counter that starts at countstart. */ public AcknowledgedCounterGenerator(long countstart) { super(countstart); lock = new ReentrantLock(); window = new boolean[WINDOW_SIZE]; limit = countstart - 1; } /** * In this generator, the highest acknowledged counter value * (as opposed to the highest generated counter value). */ @Override public Long lastValue() { return limit; } /** * Make a generated counter value available via lastInt(). */ public void acknowledge(long value) {<FILL_FUNCTION_BODY>} }
final int currentSlot = (int)(value & WINDOW_MASK); if (window[currentSlot]) { throw new RuntimeException("Too many unacknowledged insertion keys."); } window[currentSlot] = true; if (lock.tryLock()) { // move a contiguous sequence from the window // over to the "limit" variable try { // Only loop through the entire window at most once. long beforeFirstSlot = (limit & WINDOW_MASK); long index; for (index = limit + 1; index != beforeFirstSlot; ++index) { int slot = (int)(index & WINDOW_MASK); if (!window[slot]) { break; } window[slot] = false; } limit = index - 1; } finally { lock.unlock(); } }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ConstantIntegerGenerator.java
ConstantIntegerGenerator
nextValue
class ConstantIntegerGenerator extends NumberGenerator { private final int i; /** * @param i The integer that this generator will always return. */ public ConstantIntegerGenerator(int i) { this.i = i; } @Override public Integer nextValue() {<FILL_FUNCTION_BODY>} @Override public double mean() { return i; } }
return i;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ConstantIntegerGenerator.java
ConstantIntegerGenerator
mean
class ConstantIntegerGenerator extends NumberGenerator { private final int i; /** * @param i The integer that this generator will always return. */ public ConstantIntegerGenerator(int i) { this.i = i; } @Override public Integer nextValue() { return i; } @Override public double mean() {<FILL_FUNCTION_BODY>} }
return i;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/CounterGenerator.java
CounterGenerator
nextValue
class CounterGenerator extends NumberGenerator { private final AtomicLong counter; /** * Create a counter that starts at countstart. */ public CounterGenerator(long countstart) { counter=new AtomicLong(countstart); } @Override public Long nextValue() {<FILL_FUNCTION_BODY>} @Override public Long lastValue() { return counter.get() - 1; } @Override public double mean() { throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!"); } }
return counter.getAndIncrement();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/CounterGenerator.java
CounterGenerator
lastValue
class CounterGenerator extends NumberGenerator { private final AtomicLong counter; /** * Create a counter that starts at countstart. */ public CounterGenerator(long countstart) { counter=new AtomicLong(countstart); } @Override public Long nextValue() { return counter.getAndIncrement(); } @Override public Long lastValue() {<FILL_FUNCTION_BODY>} @Override public double mean() { throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!"); } }
return counter.get() - 1;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/CounterGenerator.java
CounterGenerator
mean
class CounterGenerator extends NumberGenerator { private final AtomicLong counter; /** * Create a counter that starts at countstart. */ public CounterGenerator(long countstart) { counter=new AtomicLong(countstart); } @Override public Long nextValue() { return counter.getAndIncrement(); } @Override public Long lastValue() { return counter.get() - 1; } @Override public double mean() {<FILL_FUNCTION_BODY>} }
throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!");
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/DiscreteGenerator.java
Pair
nextValue
class Pair { private double weight; private String value; Pair(double weight, String value) { this.weight = weight; this.value = requireNonNull(value); } } private final Collection<Pair> values = new ArrayList<>(); private String lastvalue; public DiscreteGenerator() { lastvalue = null; } /** * Generate the next string in the distribution. */ @Override public String nextValue() {<FILL_FUNCTION_BODY>
double sum = 0; for (Pair p : values) { sum += p.weight; } double val = ThreadLocalRandom.current().nextDouble(); for (Pair p : values) { double pw = p.weight / sum; if (val < pw) { return p.value; } val -= pw; } throw new AssertionError("oops. should not get here.");
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/DiscreteGenerator.java
Pair
lastValue
class Pair { private double weight; private String value; Pair(double weight, String value) { this.weight = weight; this.value = requireNonNull(value); } } private final Collection<Pair> values = new ArrayList<>(); private String lastvalue; public DiscreteGenerator() { lastvalue = null; } /** * Generate the next string in the distribution. */ @Override public String nextValue() { double sum = 0; for (Pair p : values) { sum += p.weight; } double val = ThreadLocalRandom.current().nextDouble(); for (Pair p : values) { double pw = p.weight / sum; if (val < pw) { return p.value; } val -= pw; } throw new AssertionError("oops. should not get here."); } /** * Return the previous string generated by the distribution; e.g., returned from the last nextString() call. * Calling lastString() should not advance the distribution or have any side effects. If nextString() has not yet * been called, lastString() should return something reasonable. */ @Override public String lastValue() {<FILL_FUNCTION_BODY>
if (lastvalue == null) { lastvalue = nextValue(); } return lastvalue;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/DiscreteGenerator.java
Pair
addValue
class Pair { private double weight; private String value; Pair(double weight, String value) { this.weight = weight; this.value = requireNonNull(value); } } private final Collection<Pair> values = new ArrayList<>(); private String lastvalue; public DiscreteGenerator() { lastvalue = null; } /** * Generate the next string in the distribution. */ @Override public String nextValue() { double sum = 0; for (Pair p : values) { sum += p.weight; } double val = ThreadLocalRandom.current().nextDouble(); for (Pair p : values) { double pw = p.weight / sum; if (val < pw) { return p.value; } val -= pw; } throw new AssertionError("oops. should not get here."); } /** * Return the previous string generated by the distribution; e.g., returned from the last nextString() call. * Calling lastString() should not advance the distribution or have any side effects. If nextString() has not yet * been called, lastString() should return something reasonable. */ @Override public String lastValue() { if (lastvalue == null) { lastvalue = nextValue(); } return lastvalue; } public void addValue(double weight, String value) {<FILL_FUNCTION_BODY>
values.add(new Pair(weight, value));
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ExponentialGenerator.java
ExponentialGenerator
nextValue
class ExponentialGenerator extends NumberGenerator { // What percentage of the readings should be within the most recent exponential.frac portion of the dataset? public static final String EXPONENTIAL_PERCENTILE_PROPERTY = "exponential.percentile"; public static final String EXPONENTIAL_PERCENTILE_DEFAULT = "95"; // What fraction of the dataset should be accessed exponential.percentile of the time? public static final String EXPONENTIAL_FRAC_PROPERTY = "exponential.frac"; public static final String EXPONENTIAL_FRAC_DEFAULT = "0.8571428571"; // 1/7 /** * The exponential constant to use. */ private double gamma; /******************************* Constructors **************************************/ /** * Create an exponential generator with a mean arrival rate of * gamma. (And half life of 1/gamma). */ public ExponentialGenerator(double mean) { gamma = 1.0 / mean; } public ExponentialGenerator(double percentile, double range) { gamma = -Math.log(1.0 - percentile / 100.0) / range; //1.0/mean; } /****************************************************************************************/ /** * Generate the next item as a long. This distribution will be skewed toward lower values; e.g. 0 will * be the most popular, 1 the next most popular, etc. * @return The next item in the sequence. */ @Override public Double nextValue() {<FILL_FUNCTION_BODY>} @Override public double mean() { return 1.0 / gamma; } public static void main(String[] args) { ExponentialGenerator e = new ExponentialGenerator(90, 100); int j = 0; for (int i = 0; i < 1000; i++) { if (e.nextValue() < 100) { j++; } } System.out.println("Got " + j + " hits. Expect 900"); } }
return -Math.log(ThreadLocalRandom.current().nextDouble()) / gamma;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ExponentialGenerator.java
ExponentialGenerator
mean
class ExponentialGenerator extends NumberGenerator { // What percentage of the readings should be within the most recent exponential.frac portion of the dataset? public static final String EXPONENTIAL_PERCENTILE_PROPERTY = "exponential.percentile"; public static final String EXPONENTIAL_PERCENTILE_DEFAULT = "95"; // What fraction of the dataset should be accessed exponential.percentile of the time? public static final String EXPONENTIAL_FRAC_PROPERTY = "exponential.frac"; public static final String EXPONENTIAL_FRAC_DEFAULT = "0.8571428571"; // 1/7 /** * The exponential constant to use. */ private double gamma; /******************************* Constructors **************************************/ /** * Create an exponential generator with a mean arrival rate of * gamma. (And half life of 1/gamma). */ public ExponentialGenerator(double mean) { gamma = 1.0 / mean; } public ExponentialGenerator(double percentile, double range) { gamma = -Math.log(1.0 - percentile / 100.0) / range; //1.0/mean; } /****************************************************************************************/ /** * Generate the next item as a long. This distribution will be skewed toward lower values; e.g. 0 will * be the most popular, 1 the next most popular, etc. * @return The next item in the sequence. */ @Override public Double nextValue() { return -Math.log(ThreadLocalRandom.current().nextDouble()) / gamma; } @Override public double mean() {<FILL_FUNCTION_BODY>} public static void main(String[] args) { ExponentialGenerator e = new ExponentialGenerator(90, 100); int j = 0; for (int i = 0; i < 1000; i++) { if (e.nextValue() < 100) { j++; } } System.out.println("Got " + j + " hits. Expect 900"); } }
return 1.0 / gamma;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ExponentialGenerator.java
ExponentialGenerator
main
class ExponentialGenerator extends NumberGenerator { // What percentage of the readings should be within the most recent exponential.frac portion of the dataset? public static final String EXPONENTIAL_PERCENTILE_PROPERTY = "exponential.percentile"; public static final String EXPONENTIAL_PERCENTILE_DEFAULT = "95"; // What fraction of the dataset should be accessed exponential.percentile of the time? public static final String EXPONENTIAL_FRAC_PROPERTY = "exponential.frac"; public static final String EXPONENTIAL_FRAC_DEFAULT = "0.8571428571"; // 1/7 /** * The exponential constant to use. */ private double gamma; /******************************* Constructors **************************************/ /** * Create an exponential generator with a mean arrival rate of * gamma. (And half life of 1/gamma). */ public ExponentialGenerator(double mean) { gamma = 1.0 / mean; } public ExponentialGenerator(double percentile, double range) { gamma = -Math.log(1.0 - percentile / 100.0) / range; //1.0/mean; } /****************************************************************************************/ /** * Generate the next item as a long. This distribution will be skewed toward lower values; e.g. 0 will * be the most popular, 1 the next most popular, etc. * @return The next item in the sequence. */ @Override public Double nextValue() { return -Math.log(ThreadLocalRandom.current().nextDouble()) / gamma; } @Override public double mean() { return 1.0 / gamma; } public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
ExponentialGenerator e = new ExponentialGenerator(90, 100); int j = 0; for (int i = 0; i < 1000; i++) { if (e.nextValue() < 100) { j++; } } System.out.println("Got " + j + " hits. Expect 900");
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/FileGenerator.java
FileGenerator
nextValue
class FileGenerator extends Generator<String> { private final String filename; private String current; private BufferedReader reader; /** * Create a FileGenerator with the given file. * @param filename The file to read lines from. */ public FileGenerator(String filename) { this.filename = filename; reloadFile(); } /** * Return the next string of the sequence, ie the next line of the file. */ @Override public synchronized String nextValue() {<FILL_FUNCTION_BODY>} /** * Return the previous read line. */ @Override public String lastValue() { return current; } /** * Reopen the file to reuse values. */ public synchronized void reloadFile() { try (Reader r = reader) { System.err.println("Reload " + filename); reader = new BufferedReader(new FileReader(filename)); } catch (IOException e) { throw new RuntimeException(e); } } }
try { current = reader.readLine(); return current; } catch (IOException e) { throw new RuntimeException(e); }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/FileGenerator.java
FileGenerator
lastValue
class FileGenerator extends Generator<String> { private final String filename; private String current; private BufferedReader reader; /** * Create a FileGenerator with the given file. * @param filename The file to read lines from. */ public FileGenerator(String filename) { this.filename = filename; reloadFile(); } /** * Return the next string of the sequence, ie the next line of the file. */ @Override public synchronized String nextValue() { try { current = reader.readLine(); return current; } catch (IOException e) { throw new RuntimeException(e); } } /** * Return the previous read line. */ @Override public String lastValue() {<FILL_FUNCTION_BODY>} /** * Reopen the file to reuse values. */ public synchronized void reloadFile() { try (Reader r = reader) { System.err.println("Reload " + filename); reader = new BufferedReader(new FileReader(filename)); } catch (IOException e) { throw new RuntimeException(e); } } }
return current;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/FileGenerator.java
FileGenerator
reloadFile
class FileGenerator extends Generator<String> { private final String filename; private String current; private BufferedReader reader; /** * Create a FileGenerator with the given file. * @param filename The file to read lines from. */ public FileGenerator(String filename) { this.filename = filename; reloadFile(); } /** * Return the next string of the sequence, ie the next line of the file. */ @Override public synchronized String nextValue() { try { current = reader.readLine(); return current; } catch (IOException e) { throw new RuntimeException(e); } } /** * Return the previous read line. */ @Override public String lastValue() { return current; } /** * Reopen the file to reuse values. */ public synchronized void reloadFile() {<FILL_FUNCTION_BODY>} }
try (Reader r = reader) { System.err.println("Reload " + filename); reader = new BufferedReader(new FileReader(filename)); } catch (IOException e) { throw new RuntimeException(e); }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/Generator.java
Generator
nextString
class Generator<V> { /** * Generate the next value in the distribution. */ public abstract V nextValue(); /** * Return the previous value generated by the distribution; e.g., returned from the last {@link Generator#nextValue()} * call. * Calling {@link #lastValue()} should not advance the distribution or have any side effects. If {@link #nextValue()} * has not yet been called, {@link #lastValue()} should return something reasonable. */ public abstract V lastValue(); public final String nextString() {<FILL_FUNCTION_BODY>} public final String lastString() { V ret = lastValue(); return ret == null ? null : ret.toString(); } }
V ret = nextValue(); return ret == null ? null : ret.toString();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/Generator.java
Generator
lastString
class Generator<V> { /** * Generate the next value in the distribution. */ public abstract V nextValue(); /** * Return the previous value generated by the distribution; e.g., returned from the last {@link Generator#nextValue()} * call. * Calling {@link #lastValue()} should not advance the distribution or have any side effects. If {@link #nextValue()} * has not yet been called, {@link #lastValue()} should return something reasonable. */ public abstract V lastValue(); public final String nextString() { V ret = nextValue(); return ret == null ? null : ret.toString(); } public final String lastString() {<FILL_FUNCTION_BODY>} }
V ret = lastValue(); return ret == null ? null : ret.toString();
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HistogramGenerator.java
HistogramGenerator
init
class HistogramGenerator extends NumberGenerator { private final long blockSize; private final long[] buckets; private long area; private long weightedArea = 0; private double meanSize = 0; public HistogramGenerator(String histogramfile) throws IOException { try (BufferedReader in = new BufferedReader(new FileReader(histogramfile))) { String str; String[] line; ArrayList<Integer> a = new ArrayList<>(); str = in.readLine(); if (str == null) { throw new IOException("Empty input file!\n"); } line = str.split("\t"); if (line[0].compareTo("BlockSize") != 0) { throw new IOException("First line of histogram is not the BlockSize!\n"); } blockSize = Integer.parseInt(line[1]); while ((str = in.readLine()) != null) { // [0] is the bucket, [1] is the value line = str.split("\t"); a.add(Integer.parseInt(line[0]), Integer.parseInt(line[1])); } buckets = new long[a.size()]; for (int i = 0; i < a.size(); i++) { buckets[i] = a.get(i); } } init(); } public HistogramGenerator(long[] buckets, int blockSize) { this.blockSize = blockSize; this.buckets = buckets; init(); } private void init() {<FILL_FUNCTION_BODY>} @Override public Long nextValue() { int number = ThreadLocalRandom.current().nextInt((int) area); int i; for (i = 0; i < (buckets.length - 1); i++) { number -= buckets[i]; if (number <= 0) { return (i + 1) * blockSize; } } return i * blockSize; } @Override public double mean() { return meanSize; } }
for (int i = 0; i < buckets.length; i++) { area += buckets[i]; weightedArea += i * buckets[i]; } // calculate average file size meanSize = ((double) blockSize) * ((double) weightedArea) / (area);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HistogramGenerator.java
HistogramGenerator
nextValue
class HistogramGenerator extends NumberGenerator { private final long blockSize; private final long[] buckets; private long area; private long weightedArea = 0; private double meanSize = 0; public HistogramGenerator(String histogramfile) throws IOException { try (BufferedReader in = new BufferedReader(new FileReader(histogramfile))) { String str; String[] line; ArrayList<Integer> a = new ArrayList<>(); str = in.readLine(); if (str == null) { throw new IOException("Empty input file!\n"); } line = str.split("\t"); if (line[0].compareTo("BlockSize") != 0) { throw new IOException("First line of histogram is not the BlockSize!\n"); } blockSize = Integer.parseInt(line[1]); while ((str = in.readLine()) != null) { // [0] is the bucket, [1] is the value line = str.split("\t"); a.add(Integer.parseInt(line[0]), Integer.parseInt(line[1])); } buckets = new long[a.size()]; for (int i = 0; i < a.size(); i++) { buckets[i] = a.get(i); } } init(); } public HistogramGenerator(long[] buckets, int blockSize) { this.blockSize = blockSize; this.buckets = buckets; init(); } private void init() { for (int i = 0; i < buckets.length; i++) { area += buckets[i]; weightedArea += i * buckets[i]; } // calculate average file size meanSize = ((double) blockSize) * ((double) weightedArea) / (area); } @Override public Long nextValue() {<FILL_FUNCTION_BODY>} @Override public double mean() { return meanSize; } }
int number = ThreadLocalRandom.current().nextInt((int) area); int i; for (i = 0; i < (buckets.length - 1); i++) { number -= buckets[i]; if (number <= 0) { return (i + 1) * blockSize; } } return i * blockSize;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HistogramGenerator.java
HistogramGenerator
mean
class HistogramGenerator extends NumberGenerator { private final long blockSize; private final long[] buckets; private long area; private long weightedArea = 0; private double meanSize = 0; public HistogramGenerator(String histogramfile) throws IOException { try (BufferedReader in = new BufferedReader(new FileReader(histogramfile))) { String str; String[] line; ArrayList<Integer> a = new ArrayList<>(); str = in.readLine(); if (str == null) { throw new IOException("Empty input file!\n"); } line = str.split("\t"); if (line[0].compareTo("BlockSize") != 0) { throw new IOException("First line of histogram is not the BlockSize!\n"); } blockSize = Integer.parseInt(line[1]); while ((str = in.readLine()) != null) { // [0] is the bucket, [1] is the value line = str.split("\t"); a.add(Integer.parseInt(line[0]), Integer.parseInt(line[1])); } buckets = new long[a.size()]; for (int i = 0; i < a.size(); i++) { buckets[i] = a.get(i); } } init(); } public HistogramGenerator(long[] buckets, int blockSize) { this.blockSize = blockSize; this.buckets = buckets; init(); } private void init() { for (int i = 0; i < buckets.length; i++) { area += buckets[i]; weightedArea += i * buckets[i]; } // calculate average file size meanSize = ((double) blockSize) * ((double) weightedArea) / (area); } @Override public Long nextValue() { int number = ThreadLocalRandom.current().nextInt((int) area); int i; for (i = 0; i < (buckets.length - 1); i++) { number -= buckets[i]; if (number <= 0) { return (i + 1) * blockSize; } } return i * blockSize; } @Override public double mean() {<FILL_FUNCTION_BODY>} }
return meanSize;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HotspotIntegerGenerator.java
HotspotIntegerGenerator
nextValue
class HotspotIntegerGenerator extends NumberGenerator { private final long lowerBound; private final long upperBound; private final long hotInterval; private final long coldInterval; private final double hotsetFraction; private final double hotOpnFraction; /** * Create a generator for Hotspot distributions. * * @param lowerBound lower bound of the distribution. * @param upperBound upper bound of the distribution. * @param hotsetFraction percentage of data item * @param hotOpnFraction percentage of operations accessing the hot set. */ public HotspotIntegerGenerator(long lowerBound, long upperBound, double hotsetFraction, double hotOpnFraction) { if (hotsetFraction < 0.0 || hotsetFraction > 1.0) { System.err.println("Hotset fraction out of range. Setting to 0.0"); hotsetFraction = 0.0; } if (hotOpnFraction < 0.0 || hotOpnFraction > 1.0) { System.err.println("Hot operation fraction out of range. Setting to 0.0"); hotOpnFraction = 0.0; } if (lowerBound > upperBound) { System.err.println("Upper bound of Hotspot generator smaller than the lower bound. " + "Swapping the values."); long temp = lowerBound; lowerBound = upperBound; upperBound = temp; } this.lowerBound = lowerBound; this.upperBound = upperBound; this.hotsetFraction = hotsetFraction; long interval = upperBound - lowerBound + 1; this.hotInterval = (int) (interval * hotsetFraction); this.coldInterval = interval - hotInterval; this.hotOpnFraction = hotOpnFraction; } @Override public Long nextValue() {<FILL_FUNCTION_BODY>} /** * @return the lowerBound */ public long getLowerBound() { return lowerBound; } /** * @return the upperBound */ public long getUpperBound() { return upperBound; } /** * @return the hotsetFraction */ public double getHotsetFraction() { return hotsetFraction; } /** * @return the hotOpnFraction */ public double getHotOpnFraction() { return hotOpnFraction; } @Override public double mean() { return hotOpnFraction * (lowerBound + hotInterval / 2.0) + (1 - hotOpnFraction) * (lowerBound + hotInterval + coldInterval / 2.0); } }
long value = 0; Random random = ThreadLocalRandom.current(); if (random.nextDouble() < hotOpnFraction) { // Choose a value from the hot set. value = lowerBound + Math.abs(random.nextLong()) % hotInterval; } else { // Choose a value from the cold set. value = lowerBound + hotInterval + Math.abs(random.nextLong()) % coldInterval; } setLastValue(value); return value;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HotspotIntegerGenerator.java
HotspotIntegerGenerator
getLowerBound
class HotspotIntegerGenerator extends NumberGenerator { private final long lowerBound; private final long upperBound; private final long hotInterval; private final long coldInterval; private final double hotsetFraction; private final double hotOpnFraction; /** * Create a generator for Hotspot distributions. * * @param lowerBound lower bound of the distribution. * @param upperBound upper bound of the distribution. * @param hotsetFraction percentage of data item * @param hotOpnFraction percentage of operations accessing the hot set. */ public HotspotIntegerGenerator(long lowerBound, long upperBound, double hotsetFraction, double hotOpnFraction) { if (hotsetFraction < 0.0 || hotsetFraction > 1.0) { System.err.println("Hotset fraction out of range. Setting to 0.0"); hotsetFraction = 0.0; } if (hotOpnFraction < 0.0 || hotOpnFraction > 1.0) { System.err.println("Hot operation fraction out of range. Setting to 0.0"); hotOpnFraction = 0.0; } if (lowerBound > upperBound) { System.err.println("Upper bound of Hotspot generator smaller than the lower bound. " + "Swapping the values."); long temp = lowerBound; lowerBound = upperBound; upperBound = temp; } this.lowerBound = lowerBound; this.upperBound = upperBound; this.hotsetFraction = hotsetFraction; long interval = upperBound - lowerBound + 1; this.hotInterval = (int) (interval * hotsetFraction); this.coldInterval = interval - hotInterval; this.hotOpnFraction = hotOpnFraction; } @Override public Long nextValue() { long value = 0; Random random = ThreadLocalRandom.current(); if (random.nextDouble() < hotOpnFraction) { // Choose a value from the hot set. value = lowerBound + Math.abs(random.nextLong()) % hotInterval; } else { // Choose a value from the cold set. value = lowerBound + hotInterval + Math.abs(random.nextLong()) % coldInterval; } setLastValue(value); return value; } /** * @return the lowerBound */ public long getLowerBound() {<FILL_FUNCTION_BODY>} /** * @return the upperBound */ public long getUpperBound() { return upperBound; } /** * @return the hotsetFraction */ public double getHotsetFraction() { return hotsetFraction; } /** * @return the hotOpnFraction */ public double getHotOpnFraction() { return hotOpnFraction; } @Override public double mean() { return hotOpnFraction * (lowerBound + hotInterval / 2.0) + (1 - hotOpnFraction) * (lowerBound + hotInterval + coldInterval / 2.0); } }
return lowerBound;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HotspotIntegerGenerator.java
HotspotIntegerGenerator
getUpperBound
class HotspotIntegerGenerator extends NumberGenerator { private final long lowerBound; private final long upperBound; private final long hotInterval; private final long coldInterval; private final double hotsetFraction; private final double hotOpnFraction; /** * Create a generator for Hotspot distributions. * * @param lowerBound lower bound of the distribution. * @param upperBound upper bound of the distribution. * @param hotsetFraction percentage of data item * @param hotOpnFraction percentage of operations accessing the hot set. */ public HotspotIntegerGenerator(long lowerBound, long upperBound, double hotsetFraction, double hotOpnFraction) { if (hotsetFraction < 0.0 || hotsetFraction > 1.0) { System.err.println("Hotset fraction out of range. Setting to 0.0"); hotsetFraction = 0.0; } if (hotOpnFraction < 0.0 || hotOpnFraction > 1.0) { System.err.println("Hot operation fraction out of range. Setting to 0.0"); hotOpnFraction = 0.0; } if (lowerBound > upperBound) { System.err.println("Upper bound of Hotspot generator smaller than the lower bound. " + "Swapping the values."); long temp = lowerBound; lowerBound = upperBound; upperBound = temp; } this.lowerBound = lowerBound; this.upperBound = upperBound; this.hotsetFraction = hotsetFraction; long interval = upperBound - lowerBound + 1; this.hotInterval = (int) (interval * hotsetFraction); this.coldInterval = interval - hotInterval; this.hotOpnFraction = hotOpnFraction; } @Override public Long nextValue() { long value = 0; Random random = ThreadLocalRandom.current(); if (random.nextDouble() < hotOpnFraction) { // Choose a value from the hot set. value = lowerBound + Math.abs(random.nextLong()) % hotInterval; } else { // Choose a value from the cold set. value = lowerBound + hotInterval + Math.abs(random.nextLong()) % coldInterval; } setLastValue(value); return value; } /** * @return the lowerBound */ public long getLowerBound() { return lowerBound; } /** * @return the upperBound */ public long getUpperBound() {<FILL_FUNCTION_BODY>} /** * @return the hotsetFraction */ public double getHotsetFraction() { return hotsetFraction; } /** * @return the hotOpnFraction */ public double getHotOpnFraction() { return hotOpnFraction; } @Override public double mean() { return hotOpnFraction * (lowerBound + hotInterval / 2.0) + (1 - hotOpnFraction) * (lowerBound + hotInterval + coldInterval / 2.0); } }
return upperBound;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HotspotIntegerGenerator.java
HotspotIntegerGenerator
getHotsetFraction
class HotspotIntegerGenerator extends NumberGenerator { private final long lowerBound; private final long upperBound; private final long hotInterval; private final long coldInterval; private final double hotsetFraction; private final double hotOpnFraction; /** * Create a generator for Hotspot distributions. * * @param lowerBound lower bound of the distribution. * @param upperBound upper bound of the distribution. * @param hotsetFraction percentage of data item * @param hotOpnFraction percentage of operations accessing the hot set. */ public HotspotIntegerGenerator(long lowerBound, long upperBound, double hotsetFraction, double hotOpnFraction) { if (hotsetFraction < 0.0 || hotsetFraction > 1.0) { System.err.println("Hotset fraction out of range. Setting to 0.0"); hotsetFraction = 0.0; } if (hotOpnFraction < 0.0 || hotOpnFraction > 1.0) { System.err.println("Hot operation fraction out of range. Setting to 0.0"); hotOpnFraction = 0.0; } if (lowerBound > upperBound) { System.err.println("Upper bound of Hotspot generator smaller than the lower bound. " + "Swapping the values."); long temp = lowerBound; lowerBound = upperBound; upperBound = temp; } this.lowerBound = lowerBound; this.upperBound = upperBound; this.hotsetFraction = hotsetFraction; long interval = upperBound - lowerBound + 1; this.hotInterval = (int) (interval * hotsetFraction); this.coldInterval = interval - hotInterval; this.hotOpnFraction = hotOpnFraction; } @Override public Long nextValue() { long value = 0; Random random = ThreadLocalRandom.current(); if (random.nextDouble() < hotOpnFraction) { // Choose a value from the hot set. value = lowerBound + Math.abs(random.nextLong()) % hotInterval; } else { // Choose a value from the cold set. value = lowerBound + hotInterval + Math.abs(random.nextLong()) % coldInterval; } setLastValue(value); return value; } /** * @return the lowerBound */ public long getLowerBound() { return lowerBound; } /** * @return the upperBound */ public long getUpperBound() { return upperBound; } /** * @return the hotsetFraction */ public double getHotsetFraction() {<FILL_FUNCTION_BODY>} /** * @return the hotOpnFraction */ public double getHotOpnFraction() { return hotOpnFraction; } @Override public double mean() { return hotOpnFraction * (lowerBound + hotInterval / 2.0) + (1 - hotOpnFraction) * (lowerBound + hotInterval + coldInterval / 2.0); } }
return hotsetFraction;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HotspotIntegerGenerator.java
HotspotIntegerGenerator
getHotOpnFraction
class HotspotIntegerGenerator extends NumberGenerator { private final long lowerBound; private final long upperBound; private final long hotInterval; private final long coldInterval; private final double hotsetFraction; private final double hotOpnFraction; /** * Create a generator for Hotspot distributions. * * @param lowerBound lower bound of the distribution. * @param upperBound upper bound of the distribution. * @param hotsetFraction percentage of data item * @param hotOpnFraction percentage of operations accessing the hot set. */ public HotspotIntegerGenerator(long lowerBound, long upperBound, double hotsetFraction, double hotOpnFraction) { if (hotsetFraction < 0.0 || hotsetFraction > 1.0) { System.err.println("Hotset fraction out of range. Setting to 0.0"); hotsetFraction = 0.0; } if (hotOpnFraction < 0.0 || hotOpnFraction > 1.0) { System.err.println("Hot operation fraction out of range. Setting to 0.0"); hotOpnFraction = 0.0; } if (lowerBound > upperBound) { System.err.println("Upper bound of Hotspot generator smaller than the lower bound. " + "Swapping the values."); long temp = lowerBound; lowerBound = upperBound; upperBound = temp; } this.lowerBound = lowerBound; this.upperBound = upperBound; this.hotsetFraction = hotsetFraction; long interval = upperBound - lowerBound + 1; this.hotInterval = (int) (interval * hotsetFraction); this.coldInterval = interval - hotInterval; this.hotOpnFraction = hotOpnFraction; } @Override public Long nextValue() { long value = 0; Random random = ThreadLocalRandom.current(); if (random.nextDouble() < hotOpnFraction) { // Choose a value from the hot set. value = lowerBound + Math.abs(random.nextLong()) % hotInterval; } else { // Choose a value from the cold set. value = lowerBound + hotInterval + Math.abs(random.nextLong()) % coldInterval; } setLastValue(value); return value; } /** * @return the lowerBound */ public long getLowerBound() { return lowerBound; } /** * @return the upperBound */ public long getUpperBound() { return upperBound; } /** * @return the hotsetFraction */ public double getHotsetFraction() { return hotsetFraction; } /** * @return the hotOpnFraction */ public double getHotOpnFraction() {<FILL_FUNCTION_BODY>} @Override public double mean() { return hotOpnFraction * (lowerBound + hotInterval / 2.0) + (1 - hotOpnFraction) * (lowerBound + hotInterval + coldInterval / 2.0); } }
return hotOpnFraction;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/HotspotIntegerGenerator.java
HotspotIntegerGenerator
mean
class HotspotIntegerGenerator extends NumberGenerator { private final long lowerBound; private final long upperBound; private final long hotInterval; private final long coldInterval; private final double hotsetFraction; private final double hotOpnFraction; /** * Create a generator for Hotspot distributions. * * @param lowerBound lower bound of the distribution. * @param upperBound upper bound of the distribution. * @param hotsetFraction percentage of data item * @param hotOpnFraction percentage of operations accessing the hot set. */ public HotspotIntegerGenerator(long lowerBound, long upperBound, double hotsetFraction, double hotOpnFraction) { if (hotsetFraction < 0.0 || hotsetFraction > 1.0) { System.err.println("Hotset fraction out of range. Setting to 0.0"); hotsetFraction = 0.0; } if (hotOpnFraction < 0.0 || hotOpnFraction > 1.0) { System.err.println("Hot operation fraction out of range. Setting to 0.0"); hotOpnFraction = 0.0; } if (lowerBound > upperBound) { System.err.println("Upper bound of Hotspot generator smaller than the lower bound. " + "Swapping the values."); long temp = lowerBound; lowerBound = upperBound; upperBound = temp; } this.lowerBound = lowerBound; this.upperBound = upperBound; this.hotsetFraction = hotsetFraction; long interval = upperBound - lowerBound + 1; this.hotInterval = (int) (interval * hotsetFraction); this.coldInterval = interval - hotInterval; this.hotOpnFraction = hotOpnFraction; } @Override public Long nextValue() { long value = 0; Random random = ThreadLocalRandom.current(); if (random.nextDouble() < hotOpnFraction) { // Choose a value from the hot set. value = lowerBound + Math.abs(random.nextLong()) % hotInterval; } else { // Choose a value from the cold set. value = lowerBound + hotInterval + Math.abs(random.nextLong()) % coldInterval; } setLastValue(value); return value; } /** * @return the lowerBound */ public long getLowerBound() { return lowerBound; } /** * @return the upperBound */ public long getUpperBound() { return upperBound; } /** * @return the hotsetFraction */ public double getHotsetFraction() { return hotsetFraction; } /** * @return the hotOpnFraction */ public double getHotOpnFraction() { return hotOpnFraction; } @Override public double mean() {<FILL_FUNCTION_BODY>} }
return hotOpnFraction * (lowerBound + hotInterval / 2.0) + (1 - hotOpnFraction) * (lowerBound + hotInterval + coldInterval / 2.0);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
nextValue
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() {<FILL_FUNCTION_BODY>} @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
lastValue
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() {<FILL_FUNCTION_BODY>} /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
return lastValue;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
setThrowExceptionOnRollover
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) {<FILL_FUNCTION_BODY>} /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
this.throwExceptionOnRollover = exceptionOnRollover;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
getThrowExceptionOnRollover
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() {<FILL_FUNCTION_BODY>} /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
return throwExceptionOnRollover;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
printableBasicAlphaASCIISet
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() {<FILL_FUNCTION_BODY>} /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
printableBasicAlphaNumericASCIISet
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() {<FILL_FUNCTION_BODY>} /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
fullPrintableBasicASCIISet
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() {<FILL_FUNCTION_BODY>} /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
fullPrintableBasicASCIISetWithNewlines
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() {<FILL_FUNCTION_BODY>} /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
printableAlphaNumericPlaneZeroSet
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() {<FILL_FUNCTION_BODY>} /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
fullPrintablePlaneZeroSet
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() {<FILL_FUNCTION_BODY>} /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) { // since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters; } }
final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/IncrementingPrintableStringGenerator.java
IncrementingPrintableStringGenerator
generatePrintableCharacterSet
class IncrementingPrintableStringGenerator extends Generator<String> { /** Default string length for the generator. */ public static final int DEFAULTSTRINGLENGTH = 8; /** * Set of all character types that include every symbol other than non-printable * control characters. */ public static final Set<Integer> CHAR_TYPES_ALL_BUT_CONTROL; static { CHAR_TYPES_ALL_BUT_CONTROL = new HashSet<Integer>(24); // numbers CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LETTER_NUMBER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_NUMBER); // letters CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LOWERCASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.TITLECASE_LETTER); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_LETTER); // marks CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.COMBINING_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.NON_SPACING_MARK); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.ENCLOSING_MARK); // punctuation CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CONNECTOR_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.DASH_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.START_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.END_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.INITIAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.FINAL_QUOTE_PUNCTUATION); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_PUNCTUATION); // symbols CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MATH_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.CURRENCY_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.MODIFIER_SYMBOL); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.OTHER_SYMBOL); // separators CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.SPACE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.LINE_SEPARATOR); CHAR_TYPES_ALL_BUT_CONTROL.add((int) Character.PARAGRAPH_SEPARATOR); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHA; static { CHAR_TYPES_BASIC_ALPHA = new HashSet<Integer>(2); CHAR_TYPES_BASIC_ALPHA.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHA.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, upper and lower case letters. */ public static final Set<Integer> CHAR_TYPES_BASIC_ALPHANUMERICS; static { CHAR_TYPES_BASIC_ALPHANUMERICS = new HashSet<Integer>(3); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPES_BASIC_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); } /** * Set of character types including only decimals, letter numbers, * other numbers, upper, lower, title case as well as letter modifiers * and other letters. */ public static final Set<Integer> CHAR_TYPE_EXTENDED_ALPHANUMERICS; static { CHAR_TYPE_EXTENDED_ALPHANUMERICS = new HashSet<Integer>(8); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.DECIMAL_DIGIT_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LETTER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_NUMBER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.UPPERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.LOWERCASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.TITLECASE_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.MODIFIER_LETTER); CHAR_TYPE_EXTENDED_ALPHANUMERICS.add((int) Character.OTHER_LETTER); } /** The character set to iterate over. */ private final int[] characterSet; /** An array indices matching a position in the output string. */ private int[] indices; /** The length of the output string in characters. */ private final int length; /** The last value returned by the generator. Should be null if {@link #nextValue()} * has not been called.*/ private String lastValue; /** Whether or not to throw an exception when the string rolls over. */ private boolean throwExceptionOnRollover; /** Whether or not the generator has rolled over. */ private boolean hasRolledOver; /** * Generates strings of 8 characters using only the upper and lower case alphabetical * characters from the ASCII set. */ public IncrementingPrintableStringGenerator() { this(DEFAULTSTRINGLENGTH, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using only the upper and lower * case alphabetical characters from the ASCII set. * @param length The length of string to return from the generator. * @throws IllegalArgumentException if the length is less than one. */ public IncrementingPrintableStringGenerator(final int length) { this(length, printableBasicAlphaASCIISet()); } /** * Generates strings of {@link #length} characters using the code points in * {@link #characterSet}. * @param length The length of string to return from the generator. * @param characterSet A set of code points to choose from. Code points in the * set can be in any order, not necessarily lexical. * @throws IllegalArgumentException if the length is less than one or the character * set has fewer than one code points. */ public IncrementingPrintableStringGenerator(final int length, final int[] characterSet) { if (length < 1) { throw new IllegalArgumentException("Length must be greater than or equal to 1"); } if (characterSet == null || characterSet.length < 1) { throw new IllegalArgumentException("Character set must have at least one character"); } this.length = length; this.characterSet = characterSet; indices = new int[length]; } @Override public String nextValue() { if (hasRolledOver && throwExceptionOnRollover) { throw new NoSuchElementException("The generator has rolled over to the beginning"); } final StringBuilder buffer = new StringBuilder(length); for (int i = 0; i < length; i++) { buffer.append(Character.toChars(characterSet[indices[i]])); } // increment the indices; for (int i = length - 1; i >= 0; --i) { if (indices[i] >= characterSet.length - 1) { indices[i] = 0; if (i == 0 || characterSet.length == 1 && lastValue != null) { hasRolledOver = true; } } else { ++indices[i]; break; } } lastValue = buffer.toString(); return lastValue; } @Override public String lastValue() { return lastValue; } /** @param exceptionOnRollover Whether or not to throw an exception on rollover. */ public void setThrowExceptionOnRollover(final boolean exceptionOnRollover) { this.throwExceptionOnRollover = exceptionOnRollover; } /** @return Whether or not to throw an exception on rollover. */ public boolean getThrowExceptionOnRollover() { return throwExceptionOnRollover; } /** * Returns an array of printable code points with only the upper and lower * case alphabetical characters from the basic ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHA); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the upper and lower case * alphabetical characters as well as the numeric values from the basic * ASCII set. * @return An array of code points */ public static int[] printableBasicAlphaNumericASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 127, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces. Excludes new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISet() { final List<Integer> validCharacters = generatePrintableCharacterSet(32, 127, null, false, null); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points with the entire basic ASCII table, * including spaces and new lines. * @return An array of code points */ public static int[] fullPrintableBasicASCIISetWithNewlines() { final List<Integer> validCharacters = new ArrayList<Integer>(); validCharacters.add(10); // newline validCharacters.addAll(generatePrintableCharacterSet(32, 127, null, false, null)); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including only the alpha-numeric values. * @return An array of code points */ public static int[] printableAlphaNumericPlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_BASIC_ALPHANUMERICS); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Returns an array of printable code points the first plane of Unicode characters * including all printable characters. * @return An array of code points */ public static int[] fullPrintablePlaneZeroSet() { final List<Integer> validCharacters = generatePrintableCharacterSet(0, 65535, null, false, CHAR_TYPES_ALL_BUT_CONTROL); final int[] characterSet = new int[validCharacters.size()]; for (int i = 0; i < validCharacters.size(); i++) { characterSet[i] = validCharacters.get(i); } return characterSet; } /** * Generates a list of code points based on a range and filters. * These can be used for generating strings with various ASCII and/or * Unicode printable character sets for use with DBs that may have * character limitations. * <p> * Note that control, surrogate, format, private use and unassigned * code points are skipped. * @param startCodePoint The starting code point, inclusive. * @param lastCodePoint The final code point, inclusive. * @param characterTypesFilter An optional set of allowable character * types. See {@link Character} for types. * @param isFilterAllowableList Determines whether the {@code allowableTypes} * set is inclusive or exclusive. When true, only those code points that * appear in the list will be included in the resulting set. Otherwise * matching code points are excluded. * @param allowableTypes An optional list of code points for inclusion or * exclusion. * @return A list of code points matching the given range and filters. The * list may be empty but is guaranteed not to be null. */ public static List<Integer> generatePrintableCharacterSet( final int startCodePoint, final int lastCodePoint, final Set<Integer> characterTypesFilter, final boolean isFilterAllowableList, final Set<Integer> allowableTypes) {<FILL_FUNCTION_BODY>} }
// since we don't know the final size of the allowable character list we // start with a list then we'll flatten it to an array. final List<Integer> validCharacters = new ArrayList<Integer>(lastCodePoint); for (int codePoint = startCodePoint; codePoint <= lastCodePoint; ++codePoint) { if (allowableTypes != null && !allowableTypes.contains(Character.getType(codePoint))) { continue; } else { // skip control points, formats, surrogates, etc final int type = Character.getType(codePoint); if (type == Character.CONTROL || type == Character.SURROGATE || type == Character.FORMAT || type == Character.PRIVATE_USE || type == Character.UNASSIGNED) { continue; } } if (characterTypesFilter != null) { // if the filter is enabled then we need to make sure the code point // is in the allowable list if it's a whitelist or that the code point // is NOT in the list if it's a blacklist. if ((isFilterAllowableList && !characterTypesFilter.contains(codePoint)) || (characterTypesFilter.contains(codePoint))) { continue; } } validCharacters.add(codePoint); } return validCharacters;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/NumberGenerator.java
NumberGenerator
setLastValue
class NumberGenerator extends Generator<Number> { private Number lastVal; /** * Set the last value generated. NumberGenerator subclasses must use this call * to properly set the last value, or the {@link #lastValue()} calls won't work. */ protected void setLastValue(Number last) {<FILL_FUNCTION_BODY>} @Override public Number lastValue() { return lastVal; } /** * Return the expected value (mean) of the values this generator will return. */ public abstract double mean(); }
lastVal = last;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/NumberGenerator.java
NumberGenerator
lastValue
class NumberGenerator extends Generator<Number> { private Number lastVal; /** * Set the last value generated. NumberGenerator subclasses must use this call * to properly set the last value, or the {@link #lastValue()} calls won't work. */ protected void setLastValue(Number last) { lastVal = last; } @Override public Number lastValue() {<FILL_FUNCTION_BODY>} /** * Return the expected value (mean) of the values this generator will return. */ public abstract double mean(); }
return lastVal;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/RandomDiscreteTimestampGenerator.java
RandomDiscreteTimestampGenerator
setup
class RandomDiscreteTimestampGenerator extends UnixEpochTimestampGenerator { /** A hard limit on the size of the offsets array to a void using too much heap. */ public static final int MAX_INTERVALS = 16777216; /** The total number of intervals for this generator. */ private final int intervals; // can't be primitives due to the generic params on the sort function :( /** The array of generated offsets from the base time. */ private final Integer[] offsets; /** The current index into the offsets array. */ private int offsetIndex; /** * Ctor that uses the current system time as current. * @param interval The interval between timestamps. * @param timeUnits The time units of the returned Unix Epoch timestamp (as well * as the units for the interval). * @param intervals The total number of intervals for the generator. * @throws IllegalArgumentException if the intervals is larger than {@link #MAX_INTERVALS} */ public RandomDiscreteTimestampGenerator(final long interval, final TimeUnit timeUnits, final int intervals) { super(interval, timeUnits); this.intervals = intervals; offsets = new Integer[intervals]; setup(); } /** * Ctor for supplying a starting timestamp. * The interval between timestamps. * @param timeUnits The time units of the returned Unix Epoch timestamp (as well * as the units for the interval). * @param startTimestamp The start timestamp to use. * NOTE that this must match the time units used for the interval. * If the units are in nanoseconds, provide a nanosecond timestamp {@code System.nanoTime()} * or in microseconds, {@code System.nanoTime() / 1000} * or in millis, {@code System.currentTimeMillis()} * @param intervals The total number of intervals for the generator. * @throws IllegalArgumentException if the intervals is larger than {@link #MAX_INTERVALS} */ public RandomDiscreteTimestampGenerator(final long interval, final TimeUnit timeUnits, final long startTimestamp, final int intervals) { super(interval, timeUnits, startTimestamp); this.intervals = intervals; offsets = new Integer[intervals]; setup(); } /** * Generates the offsets and shuffles the array. */ private void setup() {<FILL_FUNCTION_BODY>} @Override public Long nextValue() { if (offsetIndex >= offsets.length) { throw new IllegalStateException("Reached the end of the random timestamp " + "intervals: " + offsetIndex); } lastTimestamp = currentTimestamp; currentTimestamp = startTimestamp + (offsets[offsetIndex++] * getOffset(1)); return currentTimestamp; } }
if (intervals > MAX_INTERVALS) { throw new IllegalArgumentException("Too many intervals for the in-memory " + "array. The limit is " + MAX_INTERVALS + "."); } offsetIndex = 0; for (int i = 0; i < intervals; i++) { offsets[i] = i; } Utils.shuffleArray(offsets);
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/RandomDiscreteTimestampGenerator.java
RandomDiscreteTimestampGenerator
nextValue
class RandomDiscreteTimestampGenerator extends UnixEpochTimestampGenerator { /** A hard limit on the size of the offsets array to a void using too much heap. */ public static final int MAX_INTERVALS = 16777216; /** The total number of intervals for this generator. */ private final int intervals; // can't be primitives due to the generic params on the sort function :( /** The array of generated offsets from the base time. */ private final Integer[] offsets; /** The current index into the offsets array. */ private int offsetIndex; /** * Ctor that uses the current system time as current. * @param interval The interval between timestamps. * @param timeUnits The time units of the returned Unix Epoch timestamp (as well * as the units for the interval). * @param intervals The total number of intervals for the generator. * @throws IllegalArgumentException if the intervals is larger than {@link #MAX_INTERVALS} */ public RandomDiscreteTimestampGenerator(final long interval, final TimeUnit timeUnits, final int intervals) { super(interval, timeUnits); this.intervals = intervals; offsets = new Integer[intervals]; setup(); } /** * Ctor for supplying a starting timestamp. * The interval between timestamps. * @param timeUnits The time units of the returned Unix Epoch timestamp (as well * as the units for the interval). * @param startTimestamp The start timestamp to use. * NOTE that this must match the time units used for the interval. * If the units are in nanoseconds, provide a nanosecond timestamp {@code System.nanoTime()} * or in microseconds, {@code System.nanoTime() / 1000} * or in millis, {@code System.currentTimeMillis()} * @param intervals The total number of intervals for the generator. * @throws IllegalArgumentException if the intervals is larger than {@link #MAX_INTERVALS} */ public RandomDiscreteTimestampGenerator(final long interval, final TimeUnit timeUnits, final long startTimestamp, final int intervals) { super(interval, timeUnits, startTimestamp); this.intervals = intervals; offsets = new Integer[intervals]; setup(); } /** * Generates the offsets and shuffles the array. */ private void setup() { if (intervals > MAX_INTERVALS) { throw new IllegalArgumentException("Too many intervals for the in-memory " + "array. The limit is " + MAX_INTERVALS + "."); } offsetIndex = 0; for (int i = 0; i < intervals; i++) { offsets[i] = i; } Utils.shuffleArray(offsets); } @Override public Long nextValue() {<FILL_FUNCTION_BODY>} }
if (offsetIndex >= offsets.length) { throw new IllegalStateException("Reached the end of the random timestamp " + "intervals: " + offsetIndex); } lastTimestamp = currentTimestamp; currentTimestamp = startTimestamp + (offsets[offsetIndex++] * getOffset(1)); return currentTimestamp;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ScrambledZipfianGenerator.java
ScrambledZipfianGenerator
nextValue
class ScrambledZipfianGenerator extends NumberGenerator { public static final double ZETAN = 26.46902820178302; public static final double USED_ZIPFIAN_CONSTANT = 0.99; public static final long ITEM_COUNT = 10000000000L; private ZipfianGenerator gen; private final long min, max, itemcount; /******************************* Constructors **************************************/ /** * Create a zipfian generator for the specified number of items. * * @param items The number of items in the distribution. */ public ScrambledZipfianGenerator(long items) { this(0, items - 1); } /** * Create a zipfian generator for items between min and max. * * @param min The smallest integer to generate in the sequence. * @param max The largest integer to generate in the sequence. */ public ScrambledZipfianGenerator(long min, long max) { this(min, max, ZipfianGenerator.ZIPFIAN_CONSTANT); } /** * Create a zipfian generator for the specified number of items using the specified zipfian constant. * * @param _items The number of items in the distribution. * @param _zipfianconstant The zipfian constant to use. */ /* // not supported, as the value of zeta depends on the zipfian constant, and we have only precomputed zeta for one zipfian constant public ScrambledZipfianGenerator(long _items, double _zipfianconstant) { this(0,_items-1,_zipfianconstant); } */ /** * Create a zipfian generator for items between min and max (inclusive) for the specified zipfian constant. If you * use a zipfian constant other than 0.99, this will take a long time to complete because we need to recompute zeta. * * @param min The smallest integer to generate in the sequence. * @param max The largest integer to generate in the sequence. * @param zipfianconstant The zipfian constant to use. */ public ScrambledZipfianGenerator(long min, long max, double zipfianconstant) { this.min = min; this.max = max; itemcount = this.max - this.min + 1; if (zipfianconstant == USED_ZIPFIAN_CONSTANT) { gen = new ZipfianGenerator(0, ITEM_COUNT, zipfianconstant, ZETAN); } else { gen = new ZipfianGenerator(0, ITEM_COUNT, zipfianconstant); } } /**************************************************************************************************/ /** * Return the next long in the sequence. */ @Override public Long nextValue() {<FILL_FUNCTION_BODY>} public static void main(String[] args) { double newzetan = ZipfianGenerator.zetastatic(ITEM_COUNT, ZipfianGenerator.ZIPFIAN_CONSTANT); System.out.println("zetan: " + newzetan); System.exit(0); ScrambledZipfianGenerator gen = new ScrambledZipfianGenerator(10000); for (int i = 0; i < 1000000; i++) { System.out.println("" + gen.nextValue()); } } /** * since the values are scrambled (hopefully uniformly), the mean is simply the middle of the range. */ @Override public double mean() { return ((min) + max) / 2.0; } }
long ret = gen.nextValue(); ret = min + Utils.fnvhash64(ret) % itemcount; setLastValue(ret); return ret;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ScrambledZipfianGenerator.java
ScrambledZipfianGenerator
main
class ScrambledZipfianGenerator extends NumberGenerator { public static final double ZETAN = 26.46902820178302; public static final double USED_ZIPFIAN_CONSTANT = 0.99; public static final long ITEM_COUNT = 10000000000L; private ZipfianGenerator gen; private final long min, max, itemcount; /******************************* Constructors **************************************/ /** * Create a zipfian generator for the specified number of items. * * @param items The number of items in the distribution. */ public ScrambledZipfianGenerator(long items) { this(0, items - 1); } /** * Create a zipfian generator for items between min and max. * * @param min The smallest integer to generate in the sequence. * @param max The largest integer to generate in the sequence. */ public ScrambledZipfianGenerator(long min, long max) { this(min, max, ZipfianGenerator.ZIPFIAN_CONSTANT); } /** * Create a zipfian generator for the specified number of items using the specified zipfian constant. * * @param _items The number of items in the distribution. * @param _zipfianconstant The zipfian constant to use. */ /* // not supported, as the value of zeta depends on the zipfian constant, and we have only precomputed zeta for one zipfian constant public ScrambledZipfianGenerator(long _items, double _zipfianconstant) { this(0,_items-1,_zipfianconstant); } */ /** * Create a zipfian generator for items between min and max (inclusive) for the specified zipfian constant. If you * use a zipfian constant other than 0.99, this will take a long time to complete because we need to recompute zeta. * * @param min The smallest integer to generate in the sequence. * @param max The largest integer to generate in the sequence. * @param zipfianconstant The zipfian constant to use. */ public ScrambledZipfianGenerator(long min, long max, double zipfianconstant) { this.min = min; this.max = max; itemcount = this.max - this.min + 1; if (zipfianconstant == USED_ZIPFIAN_CONSTANT) { gen = new ZipfianGenerator(0, ITEM_COUNT, zipfianconstant, ZETAN); } else { gen = new ZipfianGenerator(0, ITEM_COUNT, zipfianconstant); } } /**************************************************************************************************/ /** * Return the next long in the sequence. */ @Override public Long nextValue() { long ret = gen.nextValue(); ret = min + Utils.fnvhash64(ret) % itemcount; setLastValue(ret); return ret; } public static void main(String[] args) {<FILL_FUNCTION_BODY>} /** * since the values are scrambled (hopefully uniformly), the mean is simply the middle of the range. */ @Override public double mean() { return ((min) + max) / 2.0; } }
double newzetan = ZipfianGenerator.zetastatic(ITEM_COUNT, ZipfianGenerator.ZIPFIAN_CONSTANT); System.out.println("zetan: " + newzetan); System.exit(0); ScrambledZipfianGenerator gen = new ScrambledZipfianGenerator(10000); for (int i = 0; i < 1000000; i++) { System.out.println("" + gen.nextValue()); }
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/ScrambledZipfianGenerator.java
ScrambledZipfianGenerator
mean
class ScrambledZipfianGenerator extends NumberGenerator { public static final double ZETAN = 26.46902820178302; public static final double USED_ZIPFIAN_CONSTANT = 0.99; public static final long ITEM_COUNT = 10000000000L; private ZipfianGenerator gen; private final long min, max, itemcount; /******************************* Constructors **************************************/ /** * Create a zipfian generator for the specified number of items. * * @param items The number of items in the distribution. */ public ScrambledZipfianGenerator(long items) { this(0, items - 1); } /** * Create a zipfian generator for items between min and max. * * @param min The smallest integer to generate in the sequence. * @param max The largest integer to generate in the sequence. */ public ScrambledZipfianGenerator(long min, long max) { this(min, max, ZipfianGenerator.ZIPFIAN_CONSTANT); } /** * Create a zipfian generator for the specified number of items using the specified zipfian constant. * * @param _items The number of items in the distribution. * @param _zipfianconstant The zipfian constant to use. */ /* // not supported, as the value of zeta depends on the zipfian constant, and we have only precomputed zeta for one zipfian constant public ScrambledZipfianGenerator(long _items, double _zipfianconstant) { this(0,_items-1,_zipfianconstant); } */ /** * Create a zipfian generator for items between min and max (inclusive) for the specified zipfian constant. If you * use a zipfian constant other than 0.99, this will take a long time to complete because we need to recompute zeta. * * @param min The smallest integer to generate in the sequence. * @param max The largest integer to generate in the sequence. * @param zipfianconstant The zipfian constant to use. */ public ScrambledZipfianGenerator(long min, long max, double zipfianconstant) { this.min = min; this.max = max; itemcount = this.max - this.min + 1; if (zipfianconstant == USED_ZIPFIAN_CONSTANT) { gen = new ZipfianGenerator(0, ITEM_COUNT, zipfianconstant, ZETAN); } else { gen = new ZipfianGenerator(0, ITEM_COUNT, zipfianconstant); } } /**************************************************************************************************/ /** * Return the next long in the sequence. */ @Override public Long nextValue() { long ret = gen.nextValue(); ret = min + Utils.fnvhash64(ret) % itemcount; setLastValue(ret); return ret; } public static void main(String[] args) { double newzetan = ZipfianGenerator.zetastatic(ITEM_COUNT, ZipfianGenerator.ZIPFIAN_CONSTANT); System.out.println("zetan: " + newzetan); System.exit(0); ScrambledZipfianGenerator gen = new ScrambledZipfianGenerator(10000); for (int i = 0; i < 1000000; i++) { System.out.println("" + gen.nextValue()); } } /** * since the values are scrambled (hopefully uniformly), the mean is simply the middle of the range. */ @Override public double mean() {<FILL_FUNCTION_BODY>} }
return ((min) + max) / 2.0;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/SequentialGenerator.java
SequentialGenerator
nextLong
class SequentialGenerator extends NumberGenerator { private final AtomicLong counter; private long interval; private long countstart; /** * Create a counter that starts at countstart. */ public SequentialGenerator(long countstart, long countend) { counter = new AtomicLong(); setLastValue(counter.get()); this.countstart = countstart; interval = countend - countstart + 1; } /** * If the generator returns numeric (long) values, return the next value as an long. * Default is to return -1, which is appropriate for generators that do not return numeric values. */ public long nextLong() {<FILL_FUNCTION_BODY>} @Override public Number nextValue() { long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret; } @Override public Number lastValue() { return counter.get() + 1; } @Override public double mean() { throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!"); } }
long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/SequentialGenerator.java
SequentialGenerator
nextValue
class SequentialGenerator extends NumberGenerator { private final AtomicLong counter; private long interval; private long countstart; /** * Create a counter that starts at countstart. */ public SequentialGenerator(long countstart, long countend) { counter = new AtomicLong(); setLastValue(counter.get()); this.countstart = countstart; interval = countend - countstart + 1; } /** * If the generator returns numeric (long) values, return the next value as an long. * Default is to return -1, which is appropriate for generators that do not return numeric values. */ public long nextLong() { long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret; } @Override public Number nextValue() {<FILL_FUNCTION_BODY>} @Override public Number lastValue() { return counter.get() + 1; } @Override public double mean() { throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!"); } }
long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/SequentialGenerator.java
SequentialGenerator
lastValue
class SequentialGenerator extends NumberGenerator { private final AtomicLong counter; private long interval; private long countstart; /** * Create a counter that starts at countstart. */ public SequentialGenerator(long countstart, long countend) { counter = new AtomicLong(); setLastValue(counter.get()); this.countstart = countstart; interval = countend - countstart + 1; } /** * If the generator returns numeric (long) values, return the next value as an long. * Default is to return -1, which is appropriate for generators that do not return numeric values. */ public long nextLong() { long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret; } @Override public Number nextValue() { long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret; } @Override public Number lastValue() {<FILL_FUNCTION_BODY>} @Override public double mean() { throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!"); } }
return counter.get() + 1;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/SequentialGenerator.java
SequentialGenerator
mean
class SequentialGenerator extends NumberGenerator { private final AtomicLong counter; private long interval; private long countstart; /** * Create a counter that starts at countstart. */ public SequentialGenerator(long countstart, long countend) { counter = new AtomicLong(); setLastValue(counter.get()); this.countstart = countstart; interval = countend - countstart + 1; } /** * If the generator returns numeric (long) values, return the next value as an long. * Default is to return -1, which is appropriate for generators that do not return numeric values. */ public long nextLong() { long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret; } @Override public Number nextValue() { long ret = countstart + counter.getAndIncrement() % interval; setLastValue(ret); return ret; } @Override public Number lastValue() { return counter.get() + 1; } @Override public double mean() {<FILL_FUNCTION_BODY>} }
throw new UnsupportedOperationException("Can't compute mean of non-stationary distribution!");
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/UniformGenerator.java
UniformGenerator
nextValue
class UniformGenerator extends Generator<String> { private final List<String> values; private String laststring; private final UniformLongGenerator gen; /** * Creates a generator that will return strings from the specified set uniformly randomly. */ public UniformGenerator(Collection<String> values) { this.values = new ArrayList<>(values); laststring = null; gen = new UniformLongGenerator(0, values.size() - 1); } /** * Generate the next string in the distribution. */ @Override public String nextValue() {<FILL_FUNCTION_BODY>} /** * Return the previous string generated by the distribution; e.g., returned from the last nextString() call. * Calling lastString() should not advance the distribution or have any side effects. If nextString() has not yet * been called, lastString() should return something reasonable. */ @Override public String lastValue() { if (laststring == null) { nextValue(); } return laststring; } }
laststring = values.get(gen.nextValue().intValue()); return laststring;
brianfrankcooper_YCSB
YCSB/core/src/main/java/site/ycsb/generator/UniformGenerator.java
UniformGenerator
lastValue
class UniformGenerator extends Generator<String> { private final List<String> values; private String laststring; private final UniformLongGenerator gen; /** * Creates a generator that will return strings from the specified set uniformly randomly. */ public UniformGenerator(Collection<String> values) { this.values = new ArrayList<>(values); laststring = null; gen = new UniformLongGenerator(0, values.size() - 1); } /** * Generate the next string in the distribution. */ @Override public String nextValue() { laststring = values.get(gen.nextValue().intValue()); return laststring; } /** * Return the previous string generated by the distribution; e.g., returned from the last nextString() call. * Calling lastString() should not advance the distribution or have any side effects. If nextString() has not yet * been called, lastString() should return something reasonable. */ @Override public String lastValue() {<FILL_FUNCTION_BODY>} }
if (laststring == null) { nextValue(); } return laststring;